Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
test(ui): model hub playwright e2e suite for the web-interaction scenarios (#1816)
Maxe77326b08554
diff --git a/ui/.gitignore b/ui/.gitignoreindex a547bf36d..28ee874bc 100644--- a/ui/.gitignore+++ b/ui/.gitignore@@ -22,3 +22,11 @@ dist-ssr*.njsproj*.sln*.sw?++# Playwright: every artifact the e2e run writes lands under one directory, so+# there is one entry to keep rather than four scattered defaults.+e2e/.artifacts+playwright-report+test-results+blob-report+.playwrightdiff --git a/ui/e2e/README.md b/ui/e2e/README.mdnew file mode 100644index 000000000..6d6508935--- /dev/null+++ b/ui/e2e/README.md@@ -0,0 +1,292 @@+# Model Hub end-to-end suite++Playwright specs that drive the Model Hub surface of a **running Avibe+instance** through a real browser. They are not wired into CI, and they do not+start anything for you: you point them at an instance, and they exercise it.++Scenario IDs in the spec titles (A1…E3) refer to+`docs/plans/model-hub-e2e-test-plan.md` §3 — the web-interaction plan this suite+implements. They are that plan's working labels, deliberately not the+`MH-*` ids of `tests/scenarios/model_hub/catalog.yaml`: the catalog's canonical+evidence gate binds each `MH-*` row to one pytest or vitest case it can verify+collects, and a Playwright spec drives a live instance rather than collecting+under either runner, so citing it there would make an unverifiable claim. The+cross-reference lives in the plan, which maps every §3 id to its `MH-*`+counterpart; if the pytest lane lands an orchestration that runs this suite and+records its result, that runner — not the spec files — is what belongs in the+catalog.++## What it talks to++| Variable | Default | What it is |+| --- | --- | --- |+| `VIBE_E2E_BASE_URL` | *(none — required)* | The Avibe instance under test. The run refuses to start without it. |+| `VIBE_E2E_DESTRUCTIVE_TARGET` | *(none — required)* | The same URL again, stating that instance is disposable. |+| `VIBE_E2E_MOCK_UPSTREAM_URL` | *(unset)* | A controllable model upstream. Specs that need one **skip** when it is absent. |++Nothing else is read, and the suite never imports the mock's code — it types the+mock's URL into the dialog's Base URL field the way a user would, and steers it+over its own HTTP control plane.++### The mock upstream++The driver the repo's own instructions reference (`tests/e2e/drivers/+mock_llm_upstream.py`) ships with the pytest lane and is not in this PR, so a+clean checkout has no bundled copy. Any server implementing the §5a control+plane will do: `POST /__control/config` with `auth`, `protocol`,+`models_endpoint`, `stream`, and `models`; `GET /__control/requests` returning+`{"requests": [...]}`; `DELETE /__control/requests` to reset; plus the+Anthropic/OpenAI protocol endpoints under `/v1/*`. Until the pytest lane lands+its driver, run the suite with a mock you provide on that contract.++## Preconditions, and why they skip instead of fail++A live instance can legitimately be missing the thing a spec needs: the Model Hub+capability can be off, the gateway runtime can be stopped, no agent backend CLI+can be installed. Those are facts about the instance, not defects, so each one+produces a **skip whose message says what to start**. A red test here always+means the product did something wrong.++The line between the two is deliberate (test plan §5a): only an environmental+fact may skip. Once the instance has answered — the capability read succeeded,+the mock's control plane replied — a later refusal (a source it will not create,+a mode switch that does not take, a forced route PUT it rejects) is a product+failure and fails the spec. `VIBE_E2E_BASE_URL` has no default for the same+reason: the suite mutates the instance it is pointed at, and refusing to start+on an unspecified target is safer than any warning.++### Admitting a target++Being named is not the same as being disposable, and the suite is destructive on+every axis the Model Hub has — it force-deletes sources, rewrites route chains,+flips agent modes, and stops the gateway. So a target is admitted only when:++- `VIBE_E2E_DESTRUCTIVE_TARGET` names the **same** URL as `VIBE_E2E_BASE_URL`+ (trailing slashes and case are normalized away, so only the target has to+ match, not the spelling); and+- that URL is not on port `5123`, which is where the packaged service listens+ unless its operator moved it. That port is refused outright, consent or not —+ the likeliest way to reach it is pasting the URL of the vibe UI you have open.++The consent variable names the target rather than being a flag on purpose: an+answer given for one instance then expires the moment `VIBE_E2E_BASE_URL` moves,+instead of sitting in a shell profile approving whatever comes next. Nothing a+running instance reports could replace it — a hermetic instance and the one you+work on serve the same API — so consent is the only honest form the check has.++## Running it++```bash+cd ui+npm install # once+npx playwright install chromium # once++VIBE_E2E_BASE_URL=http://127.0.0.1:5199 \+VIBE_E2E_DESTRUCTIVE_TARGET=http://127.0.0.1:5199 \+VIBE_E2E_MOCK_UPSTREAM_URL=http://127.0.0.1:9931 \+npm run e2e+```++Both target variables are required and must agree — the suite refuses to start+otherwise, because it mutates the instance it points at (see below).++`npm run e2e:headed` runs the same thing in a visible browser. Artifacts (traces+for failures, screenshots, the HTML report) land in `ui/e2e/.artifacts/` and are+gitignored.++## Against a local hermetic instance++The suite mutates the instance it points at — it creates sources, edits routes,+and deletes things. **Do not point it at the Avibe you use.** Give it its own+`AVIBE_HOME` and its own port:++```bash+export E2E_HOME=/tmp/avibe-e2e-home+mkdir -p "$E2E_HOME"++# 1 · a config the instance will accept, with no IM platform enabled and the+# Model Hub on. The UI port must not be 5123 if a real vibe is running there.+mkdir -p "$E2E_HOME/config"+python3 - <<'PY'+import json, os+home = os.environ['E2E_HOME']+json.dump({+ 'version': 'v2',+ 'platform': 'avibe',+ 'platforms': {'enabled': [], 'primary': 'avibe'},+ 'mode': 'self_host',+ 'avibe': {'enabled': True, 'proxy_url': None},+ 'runtime': {'default_cwd': f'{home}/work', 'log_level': 'INFO'},+ 'agents': {'claude': {'enabled': True, 'cli_path': 'claude'}},+ 'model_hub': {'enabled': True},+ 'ui': {'setup_host': '127.0.0.1', 'setup_port': 5199, 'open_browser': False},+ 'language': 'en',+ # Without this every browser navigation is redirected to the setup wizard,+ # and the suite fails on "the Model Hub shell is not there" for every spec.+ 'setup_completed': True,+}, open(f'{home}/config/config.json', 'w'), indent=2)+PY++# 2 · the controller (owns Model Hub state) and the UI server are separate+# processes; the suite needs both. Both run from the REPOSITORY ROOT — the+# `cd ui` above is for the browser side only, so return before starting them+# (`python main.py` finds no `ui/main.py`, and `vibe` is imported from the+# root, not from `ui/`).+#+# And `AVIBE_HOME` alone does NOT make the run hermetic: switching a+# backend to Gateway mode scans the CLI homes the controller process+# sees — `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, the XDG dirs, `~/.claude`,+# `~/.codex` — and on a machine with real CLI credentials that scan can+# read production tokens and import a real native account into the test+# instance's state. The processes get test-owned copies of all of them.+#+# On macOS there is one more channel the env cannot redirect: a Claude CLI+# that stores OAuth in the SYSTEM KEYCHAIN still sees your real login even+# under a redirected HOME, because `claude auth status` (which the mode+# switch's presence probe executes) reads the keychain, not the filesystem.+# If your install is keychain-backed, point the suite at a shim instead of+# the real binary — put a directory FIRST on PATH carrying an executable+# `claude` that answers `auth status --json` from test-owned state (e.g.+# `{"oauth_account":null}` printed and exit 0) and execs nothing else. A+# container or separate OS user is the stronger form of the same boundary.+cd "$(git rev-parse --show-toplevel)"+export E2E_ISOLATED_HOME="$E2E_HOME/home"+mkdir -p "$E2E_ISOLATED_HOME/.claude" "$E2E_ISOLATED_HOME/.codex" \+ "$E2E_ISOLATED_HOME/.config" "$E2E_ISOLATED_HOME/.cache" \+ "$E2E_ISOLATED_HOME/.local/share"+export HOME="$E2E_ISOLATED_HOME"+export XDG_CONFIG_HOME="$E2E_ISOLATED_HOME/.config"+export XDG_CACHE_HOME="$E2E_ISOLATED_HOME/.cache"+export XDG_DATA_HOME="$E2E_ISOLATED_HOME/.local/share"+export CLAUDE_CONFIG_DIR="$E2E_ISOLATED_HOME/.claude"+export CODEX_HOME="$E2E_ISOLATED_HOME/.codex"+AVIBE_HOME=$E2E_HOME VIBE_MODEL_HUB_ENABLED=1 python main.py &+AVIBE_HOME=$E2E_HOME VIBE_MODEL_HUB_ENABLED=1 python -c \+ "from vibe.ui_server import run_ui_server; run_ui_server('127.0.0.1', 5199)" &+```++Then turn the gateway on once, from the UI at+`http://127.0.0.1:5199/settings/models`. Suite B, D, and G need the runtime+**running**; they skip otherwise. No spec in the suite starts a stopped gateway+for you: A2's round-trip spec skips unless the runtime is already running, and+the install-entry spec opens and cancels the install dialog without ever+completing an install.++Finally, return to `ui/` before running the suite — step 2's `cd` to the+repository root left the shell there, and `npm run e2e` needs `ui/package.json`:++```bash+cd "$(git rev-parse --show-toplevel)/ui"+# Linux: Chromium must be (re)installed HERE, after the isolated cache exists —+# `npx playwright install chromium` run before step 2 exported XDG_CACHE_HOME+# put it in the original cache, which the isolated run no longer reads. Setting+# PLAYWRIGHT_BROWSERS_PATH to a stable path instead works equally well.+npx playwright install chromium+VIBE_E2E_BASE_URL=http://127.0.0.1:5199 \+VIBE_E2E_DESTRUCTIVE_TARGET=http://127.0.0.1:5199 \+VIBE_E2E_MOCK_UPSTREAM_URL=http://127.0.0.1:9931 \+npm run e2e+```++Set `VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH` to a local manifest if the machine+should not fetch the engine archive from the network.++Tear it down by killing both processes and deleting `$E2E_HOME`. Nothing outside+it was written — the CLI config stores were redirected into it at step 2 before+either process read anything.++## Against a remote VM++Same suite, same two variables:++```bash+VIBE_E2E_BASE_URL=http://<vm-host>:5123 \+VIBE_E2E_DESTRUCTIVE_TARGET=http://<vm-host>:5123 \+npm run e2e+```++Port `5123` is refused only on loopback, where it is recognizably the local+service; on another host it is admitted with consent, because nothing here can+tell whose machine that is. Which makes the consent yours to mean: a shared+regression VM accumulates product state on purpose, and this suite deletes+sources and rewrites routes on whatever it is pointed at.++Two caveats. The suite has **no login step**, so the endpoint must be one that+serves without one — a VM's own `host:port` on a network you trust, not a+tunnel fronted by a remote-access login. Being signed in to that instance in+your own browser does not carry: Playwright opens a fresh browser context and+its API context keeps a separate cookie jar. Pointed at a tunnel that wants a+login, the run fails on a precondition read and says exactly that; supporting+one would mean a bootstrap that authenticates the page and the API context+alike, and this suite does not have it. And the mock upstream must be reachable+*from the VM* as well as from this machine, because the instance is what dials+it — a `127.0.0.1` mock URL will resolve to the VM's own loopback, not to+yours.++## What it leaves behind++Every source the suite creates is named `e2e-playwright-*`, and each suite+removes its own in teardown. If a run is killed mid-way, the next run's teardown+sweeps whatever is left by that prefix.++The route-chain and priority-order specs **cancel** rather than save: they test+the editor, and the instance's real routing is not theirs to change. The one+spec that commits is B7, and it commits to a source the suite created.++## Known flakes++**B6 · the replace-key precondition.** A source only offers to have its key+replaced once the key has actually been rejected, and the only thing that can+reject it is a real request down the route chain — a refetch reads the model+list, which an upstream that refuses completions still serves. So B6 arranges a+chain onto its own source, sets the mock to answer `401`, and drives+`POST /api/models/agents/{backend}/probe` until the source settles.++Roughly one run in three, the gateway engine answers that dry run with a 5xx of+its own and the mock upstream never receives anything. Avibe classifies it as+`models.source.cooldown.server_error`, which blocks the chain for thirty seconds;+the retry after that window fails the same way and re-arms it, so the source+never reaches a verdict about its key. Recreating the source clears it; waiting,+restarting the engine, and stopping and starting the whole gateway do not. It is+filed as [#1818](https://github.com/avibe-bot/avibe/issues/1818).++B6 retries that sticky state by rebuilding its arrangement (delete the source,+recreate it, re-chain, re-settle) up to three times. If all three attempts land+in the same cooldown, that is #1818's exact signature, and the spec retires+itself via a runtime `test.fixme` naming #1818 — the run reports one skipped+spec with the issue in its reason, because an intermittent engine defect does+not get to burn the suite red on its own schedule. Any other verdict fails+immediately, because a wrong classification is exactly what the scenario exists+to catch.++`test.fixme` rather than `test.fail`, for two reasons. `test.fail` sets the+expected status of the whole test — its own `finally`, the suite's `afterEach`,+and the gateway fixture's teardown included — so a failed restoration would+have satisfied "expected to fail" and reported green over a displaced route+chain. And a skip states the outcome: the scenario was not reached, which is+what happened, where a green tick says it passed.++Neither marker detects its own obsolescence, and an earlier version of this+note claimed otherwise. A `test.fail(cond)` whose `cond` and whose following+`expect` read the same verdict can never produce *"Expected to fail, but+passed"*: when `cond` holds the assertion necessarily fails, and when it does+not the test is not marked. What signals that #1818 is fixed is the report+itself — the skip and its reason stop appearing, and the spec runs to its+assertions.++## What this suite cannot reach++Recorded here so the gaps are visible rather than merely absent:++- **Metered usage figures.** They come from turns the gateway actually proxied.+ The E specs assert that each tab reaches a *stated* state; asserting numbers+ needs seeded gateway traffic and belongs to the pytest layer.+- **`discovered_at` preservation across a refetch** (B9). Not rendered anywhere+ a browser can read it.+- **Member-role dead-ends** (D13). Reaching them needs a second, non-operator+ auth context; every request from this browser to loopback is trusted by+ construction, which is exactly why the suite needs no login.+- **Subscription sources** (D1). No browser-reachable way to create one against+ a mock without a real OAuth provider.+- **Malformed guard echoes** (G1). The echo is built by the product; a browser+ cannot corrupt it without a product-side hook.diff --git a/ui/e2e/a-gating-runtime.spec.ts b/ui/e2e/a-gating-runtime.spec.tsnew file mode 100644index 000000000..219379043--- /dev/null+++ b/ui/e2e/a-gating-runtime.spec.ts@@ -0,0 +1,220 @@+// Suite A — the capability gate and the gateway runtime switch.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+import {+ MODEL_HUB_DISABLED_REDIRECT,+ MODEL_HUB_SETTINGS_PATH,+} from '../src/components/settings/models/modelHubRoutes';+import type { Agent } from './support/api';+import { surfaceKind } from './support/api';+import { hub as copy } from './support/copy';+import {+ expect,+ requireModelHub,+ requireRuntimeRunning,+ runtimeIsRunning,+ test,+} from './support/fixtures';+import { restoreNativeSources, withRuntimeRestored } from './support/restore';++test.describe('A · capability gate and runtime lifecycle', () => {+ test('A1 · the capability gate, not the browser, decides the route', async ({ page, hub, api }) => {+ // One test covers both halves on purpose. Which half runs is a property of+ // the instance, and the assertion that matters is that the browser obeys+ // whatever the backend declared — splitting it into an "enabled" spec and a+ // "disabled" spec would leave one of them permanently skipped and hide the+ // fact that nobody ever checked the other direction.+ const enabled = await api.modelHubEnabled();+ await hub.goto();++ if (enabled) {+ await expect(page).toHaveURL(new RegExp(`${MODEL_HUB_SETTINGS_PATH}$`));+ await expect(hub.shell).toBeVisible();+ await expect(page.getByRole('heading', { name: copy('shell.title'), level: 1 })).toBeVisible();+ return;+ }+ await expect(page).toHaveURL(new RegExp(`${MODEL_HUB_DISABLED_REDIRECT}$`));+ await expect(hub.shell).toHaveCount(0);+ });++ test('A2 · the switch offers to install when the gateway is not installed', async ({ hub, api }) => {+ await requireModelHub(api);+ const runtime = await api.runtime();+ test.skip(+ runtime?.status?.health !== 'not_installed',+ 'The install entry point exists only in the not-installed state — an installed runtime (whatever '+ + 'its health) and an in-progress installation both render different closed states with the '+ + 'switch disabled or busy, so this spec covers neither. '+ + 'Point VIBE_E2E_BASE_URL at a fresh hermetic instance to cover it (see ui/e2e/README.md).',+ );+ // `not_installed` with an `unsupported` manifest is a different closed+ // state the product renders on purpose, with the switch disabled: there is+ // no install to offer on that host, and asserting the install path there+ // would report the unsupported state as a product failure. The product's+ // own gate (`runtimeCanAttemptInstall`) decides which of the two it is.+ test.skip(+ runtime?.manifest.resolution === 'unsupported',+ 'The runtime manifest resolves to unsupported on this host, so the product offers no install — '+ + 'that is the closed state it renders, not a defect in the install path.',+ );++ await hub.goto();+ // The closed state has to say the gateway is missing before the switch is+ // touched: a user who cannot install has to learn that from the page.+ await expect(hub.closedState).toContainText(copy('shell.closed.notInstalled.title'));+ await expect(hub.runtimeToggle).toHaveAttribute('aria-label', copy('shell.toggle.turnOn'));++ await hub.runtimeToggle.click();+ await expect(hub.installDialog).toBeVisible();+ await expect(hub.installDialog).toContainText(copy('install.section.effects'));+ // Cancel rather than install: downloading and unpacking a release is the+ // operator's setup step, not something a UI test should do to a machine.+ await hub.installDialog.getByRole('button', { name: copy('install.cancel'), exact: true }).first().click();+ await expect(hub.installDialog).toHaveCount(0);+ });++ test('A2 · turning the gateway off and back on round-trips', async ({ hub, api }) => {+ // The lifecycle alone can lawfully take 150s on a slow host (60s stop ++ // 90s verified restart), and per-expect timeouts do not extend the test+ // timeout — the config's 90s cap used to be able to cancel the spec while+ // its finally was still proving the runtime back up, failing the run AND+ // closing the page over an unconfirmed shared runtime.+ test.setTimeout(240_000);+ await requireModelHub(api);+ const runtime = await api.runtime();+ test.skip(+ !runtimeIsRunning(runtime?.status?.health),+ 'The gateway is not running on this instance, so there is no running state to stop.',+ );+ const hubBackends = (await api.agents()).filter((agent) => agent.mode === 'hub');+ test.skip(+ hubBackends.length > 0,+ `Stopping is blocked while ${hubBackends.map((a) => a.backend).join(', ')} is in Gateway mode — that is scenario A3.`,+ );++ await hub.goto();+ await expect(hub.runtimeToggle).toHaveAttribute('aria-label', copy('shell.toggle.turnOff'));+ await expect(hub.runtimeToggle).toHaveAttribute('aria-checked', 'true');++ // The stopping click is INSIDE the boundary, not above it. The debt is owed+ // from the moment the stop is ASKED FOR — the request is already gone when+ // the click's own promise settles, so a page or browser that disconnects+ // mid-flight rejects it with the server still completing the stop, and a+ // boundary opened below this line is skipped on exactly that path.+ // `support/restore.ts` owns both halves: where the boundary starts, and that+ // "up" is a postcondition read from BOTH runtime facts rather than a second+ // guess at which click is owed.+ await withRuntimeRestored(api, async () => {+ await hub.runtimeToggle.click();+ await expect(hub.runtimeToggle).toHaveAttribute('aria-checked', 'false', { timeout: 60_000 });+ // The page must explain the stopped gateway, not just flip a switch.+ await expect(hub.closedState).toBeVisible();+ expect((await api.runtime())?.enabled).toBe(false);++ // The return half of the round trip is the SCENARIO, so it happens here,+ // in the body, through the switch the user would use. It used to live in+ // the teardown, which made the spec's own subject a side effect of its+ // cleanup — and left the assertions below reporting a restart nobody had+ // asserted as a step.+ await hub.runtimeToggle.click();+ await expect(hub.runtimeToggle).toHaveAttribute('aria-checked', 'true', { timeout: 90_000 });+ await expect(hub.closedState).toHaveCount(0);+ });+ });++ test('A3 · the blocked stop names the backends that block it', async ({ hub, api }) => {+ await requireModelHub(api);+ // RUNNING, not merely enabled: the UI computes `stopBlocked` from+ // `runtimeEnabled` plus a Gateway-mode backend without consulting health+ // (`SettingsModelsPage.tsx`), so an enabled-but-`down` instance would pass+ // every assertion below while never exercising the guard on a gateway that+ // could actually be stopped.+ await requireRuntimeRunning(api);++ const restore: string[] = [];+ // Same snapshot discipline as the gateway fixture: the Direct→Gateway+ // switch is not mode-only on a machine whose CLI holds a native login — it+ // imports a `native_cli` subscription source as part of the transition, and+ // that source carries no suite prefix the sweep could find.+ let sourcesBeforeSwitch: Set<string> | null = null;+ const hubBackends = (await api.agents()).filter((agent) => agent.mode === 'hub').map((a) => a.backend);+ try {+ if (hubBackends.length === 0) {+ const candidate = (await api.agents()).find((agent: Agent) => agent.cli_present);+ test.skip(!candidate, 'No agent backend is present on this instance to put into Gateway mode.');+ sourcesBeforeSwitch = new Set((await api.sources()).map((source) => source.id));+ // Recorded BEFORE the PATCH is awaited: the server commits the mode+ // before its response leaves, so a lost or timed-out response rejects+ // the await with the instance already switched — a marker assigned+ // after the await skips the Direct restore on exactly that path.+ // (`sourcesBeforeSwitch` above is snapshotted first for the same+ // reason.) Every exit from here passes through the finally, so the+ // backend cannot stay in Gateway mode on any path out of this spec.+ restore.push(candidate!.backend);+ await api.setAgentMode(candidate!.backend, 'hub');+ // An accepted switch that a later read does not show is a persistence+ // or projection regression, not a precondition: the server's+ // `set_agent_mode` commits the requested mode without requiring an+ // eligible source, so `hub` here is the contract. A skip would turn+ // that regression into a green hole.+ const now = (await api.agents()).filter((agent) => agent.mode === 'hub').map((a) => a.backend);+ expect(+ now,+ `Backend ${candidate!.backend} accepted the Gateway-mode switch but the next /agents read does not show it.`,+ ).toContain(candidate!.backend);+ }++ const names = (await api.agents()).filter((a) => a.mode === 'hub').map((a) => a.backend).join(', ');+ await hub.goto();+ // The product refuses the stop AND says who is holding it. A generic+ // "cannot stop" would satisfy the disabled state and fail the user.+ await expect(hub.runtimeToggle).toBeDisabled();+ await expect(hub.runtimeToggle).toHaveAttribute(+ 'aria-label',+ copy('shell.toggle.stopBlocked', { names }),+ );+ } finally {+ // Mode first (the switch imported the source into a Gateway context),+ // then the transition-created source — before any sweep, because it does+ // not carry the prefix. Which source that is belongs to+ // `restoreNativeSources`, shared with the gateway fixture, so the two+ // sites cannot drift into two different answers. Two nested blocks keep+ // the two restorations independent.+ try {+ for (const backend of restore) await api.setAgentMode(backend, 'direct');+ } finally {+ if (sourcesBeforeSwitch) await restoreNativeSources(api, sourcesBeforeSwitch);+ await api.removeSuiteSources();+ }+ }+ });++ test('C6-direct-home · a machine with no sources lands on the direct home', async ({ hub, api }) => {+ await requireModelHub(api);+ // The tab body only renders once the runtime is configurable; below that the+ // page owes a closed state, which is scenario A2's subject, not this one's.+ await requireRuntimeRunning(api);+ // Which surface this instance renders, asked once rather than re-derived+ // here: the direct home has TWO forms, and the one this scenario is about is+ // the one an installed backend puts a card in.+ const surface = surfaceKind(await api.agents(), await api.sources());+ test.skip(+ surface === 'gateway',+ 'This instance already has sources or a Gateway backend, so the direct home is not its surface.',+ );+ test.skip(+ surface === 'direct-no-backend',+ 'No agent backend CLI is installed, so the direct home renders its install prompt — there is no '+ + 'backend card and no way out of Direct mode to assert. Install a backend CLI (see ui/e2e/README.md).',+ );++ await hub.goto();+ await expect(hub.directHome).toBeVisible();+ await expect(hub.directHome).toContainText(copy('direct.card.current'));+ // The point of this surface is the way out of it, so the way out is what+ // gets asserted — not merely that the card rendered.+ await expect(+ hub.directHome.getByRole('button', { name: copy('direct.action.switchToGateway') }).first(),+ ).toBeVisible();+ });+});diff --git a/ui/e2e/b-add-api-key.spec.ts b/ui/e2e/b-add-api-key.spec.tsnew file mode 100644index 000000000..4ebc8eb82--- /dev/null+++ b/ui/e2e/b-add-api-key.spec.ts@@ -0,0 +1,411 @@+// Suite B — the Add API key dialog, end to end against a controllable upstream.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+//+// Every spec here needs an upstream whose answers it can choose, so every spec+// here skips without one. The mock is reached ONLY over HTTP at+// `VIBE_E2E_MOCK_UPSTREAM_URL`, and its URL enters the product the same way a+// user's would: typed into the dialog's Base URL field.+import type { HubApi, RouteHop } from './support/api';+import { hub as copy } from './support/copy';+import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';+import {+ expectVisibleWithout,+ requireMockUpstream,+ requireModelHub,+ requireRuntimeRunning,+} from './support/fixtures';+// `gateway` rather than `fixtures` for the auto `hubSurface` fixture it carries:+// the Add API key button lives on the gateway surface, and an instance with no+// sources shows the direct home instead. See support/gateway.ts.+import { expect, test } from './support/gateway';+import { fillApiKeyForm } from './support/hub';+import { anthropicInventory } from './support/mock';+import { captureAgentChain, restoreAgentChain } from './support/restore';++/**+ * Runs the routed dry run until the source has settled on a verdict about its+ * KEY, and returns that verdict's detail key.+ *+ * Both halves are load-bearing, and neither works alone:+ *+ * - drive with the probe, because a dry run is the only thing that reaches the+ * upstream with a real request; a refetch reads the model list, which an+ * upstream that rejects completions still serves.+ * - read the SOURCE, because the first probe that fails also makes the chain+ * unrunnable — every probe after it is refused `409 probe_no_candidate` and+ * carries no verdict at all. A poll on the probe's own answer goes null+ * forever, one round after the state it was waiting for arrived.+ *+ * A healthy instance answers on the first dry run. The loop exists for the one+ * state that is not an answer: a cooldown, which is what an unreachable upstream+ * settles as, and which the state itself dates in `retry_at`. Sleeping to that+ * instant is the difference between one more attempt and a busy wait; the budget+ * is what stops it from waiting forever on an upstream that is genuinely gone.+ */+const settleKeyVerdict = async (+ api: HubApi,+ sourceId: string,+ route: { backend: string; model: string },+ budgetMs = 90_000,+): Promise<string | null> => {+ const deadline = Date.now() + budgetMs;+ let last: string | null = null;+ while (Date.now() < deadline) {+ await api.probeAgent(route.backend, route.model);+ const state = (await api.sources()).find((source) => source.id === sourceId)?.state;+ last = (state?.detail_key as string | null) ?? null;+ // `needs_action` is terminal by construction: nothing but the user acts on+ // it. A cooldown is the opposite — it expires, and then the next dry run is+ // the one that learns what is actually wrong.+ if (state?.status === 'needs_action' || state?.status === 'error') return last;+ const retryAt = typeof state?.retry_at === 'string' ? Date.parse(state.retry_at) : Number.NaN;+ const resumeAt = Number.isNaN(retryAt) ? Date.now() + 1_000 : retryAt + 500;+ const pause = Math.min(Math.max(resumeAt - Date.now(), 500), deadline - Date.now());+ if (pause <= 0) break;+ await new Promise((resolve) => setTimeout(resolve, pause));+ }+ return last;+};++// Each protocol's segment button carries its own label, and the observation is+// supposed to reach the same verdict for all three without being told which.+const PROTOCOLS = [+ { id: 'anthropic', label: copy('addKey.protocol.anthropicMessages') },+ { id: 'openai_responses', label: copy('addKey.protocol.openaiResponses') },+ { id: 'openai_chat', label: copy('addKey.protocol.openaiChatCompletions') },+] as const;++test.describe('B · add an API-key source', () => {+ test.beforeEach(async ({ api, mock }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ await requireMockUpstream(mock);+ });++ // Every spec adds sources; none of them may outlive the spec that made them.+ // Teardown runs on failure too, which is the case that matters: a red test+ // that also poisons the next five is two problems reported as six.+ test.afterEach(async ({ api }) => {+ await api.removeSuiteSources();+ });++ for (const protocol of PROTOCOLS) {+ test(`B1 · Add identifies a ${protocol.id} upstream without being told`, async ({ hub, mock, api }) => {+ await mock.configure({ auth: 'ok', protocol: protocol.id, models_endpoint: 'ok' });+ const name = `${E2E_SOURCE_PREFIX}auto-${protocol.id}`;++ await hub.goto();+ await hub.addApiKeyButton.click();+ await expect(hub.addKeyDialog).toBeVisible();+ // No protocol is chosen: "Auto detect" is the default, and the response+ // shape is the only evidence the product is allowed to use.+ await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-add' });+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();++ // Success is defined by where the user lands, not by a toast: the dialog+ // closes and the new source's detail panel opens.+ await expect(hub.addKeyDialog).toHaveCount(0, { timeout: 30_000 });+ await expect(hub.sourceDetailDialog).toBeVisible();+ await expect(hub.sourceDetailDialog).toContainText(name);++ const created = (await api.sources()).find((source) => source.display_name === name);+ expect(created?.protocol).toBe(protocol.id);+ });+ }++ test('B1 · a rejected credential is named as a credential problem', async ({ hub, mock }) => {+ await mock.configure({ auth: '401', protocol: 'anthropic', models_endpoint: 'ok' });++ await hub.goto();+ await hub.addApiKeyButton.click();+ // The suite prefix is on this "doomed" create too: if the regression under+ // test commits the source before reporting the failure, teardown still has+ // to be able to sweep it. A failure path that can leave state behind is a+ // failure path that poisons whichever spec runs next.+ await fillApiKeyForm(hub.addKeyDialog, {+ name: `${E2E_SOURCE_PREFIX}auth-rejected`,+ baseUrl: mockBaseUrl(),+ apiKey: 'e2e-bad-key',+ });+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();++ // The three lines are one message: what went wrong, where to look, and that+ // Add cannot proceed until it is fixed. A test that asserted only the first+ // would pass on a dialog that has stopped explaining itself.+ await expect(hub.addKeyDialog).toContainText(copy('addKey.fail.auth'), { timeout: 30_000 });+ await expect(hub.addKeyDialog).toContainText(copy('addKey.fail.auth.detail'));+ await expect(hub.addKeyDialog).toContainText(copy('addKey.fail.subtitle'));+ await expect(hub.addKeyDialog).toBeVisible();+ });++ test('B2 · naming the wrong interface is refused, and says why', async ({ hub, mock }) => {+ // The upstream speaks OpenAI Chat Completions; the user insists on Anthropic+ // Messages. The probe path then 404s, so nothing proves the interface.+ await mock.configure({ auth: 'ok', protocol: 'openai_chat', models_endpoint: 'ok' });++ await hub.goto();+ await hub.addApiKeyButton.click();+ await fillApiKeyForm(hub.addKeyDialog, {+ // Prefixed for the same reason as B1's rejected credential: a mismatch+ // that commits anyway must still be sweepable.+ name: `${E2E_SOURCE_PREFIX}mismatch`,+ baseUrl: mockBaseUrl(),+ apiKey: 'e2e-mismatch',+ protocol: copy('addKey.protocol.anthropicMessages'),+ });+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();++ // "Connected and authenticated, but we cannot tell which interface" — the+ // distinction from a credential failure is the whole point of the copy.+ await expect(hub.addKeyDialog).toContainText(copy('addKey.undetermined.title'), { timeout: 30_000 });+ await expect(hub.addKeyDialog).toContainText(copy('addKey.undetermined.detail'));+ await expectVisibleWithout(hub.addKeyDialog, copy('addKey.fail.auth'));+ // Retry stays available because a different choice is a different probe.+ await expect(+ hub.addKeyDialog.getByRole('button', { name: copy('addKey.retry'), exact: true }),+ ).toBeEnabled();+ });++ test('B3 · Fetch models reports the count, and only ids survive the save', async ({ hub, mock, api }) => {+ // The mock returns rich rows on purpose: `display_name`, `context_length`+ // and `pricing` all come back and all are dropped. §3 marks B3+ // `assert-current` — this documents the drop, it does not bless it.+ const inventory = anthropicInventory(['e2e-alpha', 'e2e-beta', 'e2e-gamma']);+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: inventory,+ });+ const name = `${E2E_SOURCE_PREFIX}inventory`;++ await hub.goto();+ await hub.addApiKeyButton.click();+ await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-pull' });++ // "Fetch models" is the optional pre-flight: it reports, it does not save.+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.test'), exact: true }).click();+ await expect(hub.addKeyDialog).toContainText(+ copy('addKey.pull.result', { count: inventory.length }),+ { timeout: 30_000 },+ );+ expect(await api.sources()).not.toContainEqual(expect.objectContaining({ display_name: name }));++ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await expect(hub.sourceDetailDialog).toBeVisible({ timeout: 30_000 });++ const created = (await api.sources()).find((source) => source.display_name === name);+ expect(created?.models.map((model) => model.id).sort()).toEqual(+ inventory.map((model) => model.id).sort(),+ );+ for (const model of created?.models ?? []) {+ // assert-current: everything the upstream said about a model except its id+ // is discarded on the way to storage.+ expect(Object.keys(model).sort()).toEqual(+ ['discovered_at', 'display_name', 'id', 'origin', 'reasoning_efforts', 'retired'],+ );+ expect(model.display_name).toBeNull();+ expect(model.reasoning_efforts).toEqual([]);+ }+ });++ test('B4 · a proven interface with no model list can still be added, on the record', async ({ hub, mock, api }) => {+ // The interface answers; only discovery is broken. That is a different+ // situation from "we do not know what this is", and the product treats it+ // as one: it offers to add the source anyway. `models_endpoint: http_500`+ // is exactly this shape: the interface probes 200, `/v1/models` 500s.+ await mock.configure({ auth: 'ok', protocol: 'anthropic', models_endpoint: 'http_500' });+ const name = `${E2E_SOURCE_PREFIX}no-inventory`;++ await hub.goto();+ await hub.addApiKeyButton.click();+ await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-empty' });+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();++ await expect(hub.addKeyDialog).toContainText(copy('addKey.inventory.title'), { timeout: 30_000 });+ const addAnyway = hub.addKeyDialog.getByRole('button', {+ name: copy('addKey.addAnyway'),+ exact: true,+ });+ await expect(addAnyway).toBeVisible();+ await addAnyway.click();++ await expect(hub.sourceDetailDialog).toBeVisible({ timeout: 30_000 });+ const created = (await api.sources()).find((source) => source.display_name === name);+ // The source commits, and it commits carrying the failure — a source that+ // came in this way must not look identical to one that discovered cleanly.+ expect(created?.protocol).toBe('anthropic');+ expect(created?.models).toEqual([]);+ expect(created?.state.status).toBe('error');+ });++ test('B6 · replacing the key reuses the same dialog, and reports what it did', async ({ hub, mock, api, gateway }) => {+ // The only spec in the suite that may have to sit out a 30-second cooldown+ // before its precondition even exists. See `settleKeyVerdict`.+ test.setTimeout(300_000);+ // A source offers to have its key replaced only once the key has actually+ // been rejected: `repairAction` reads `needs_action.credential_revoked`, and+ // that button is the dialog's ONLY entry point in replace mode. Nothing+ // about a healthy source opens it, so the rejection has to be arranged —+ // and arranged the way a real one happens, since a refetch will not do it.+ // The upstream still serves its model list to an unauthorised caller; only a+ // request that runs down the chain learns the key is dead.+ let source = gateway.sources[0];+ const supplied = source.models[0]?.id;+ const arrange = async (): Promise<void> => {+ expect(+ supplied,+ `The precondition source ${source.display_name} came back with no models, so no route can reach it.`,+ ).toBeDefined();+ const arranged = await api.putAgentChain(gateway.backend, gateway.model, [+ { source_id: source.id, model_id: supplied! },+ ]);+ expect(arranged, 'The instance refused the arranged route, so the key cannot be rejected.').toBe(true);+ };++ // The operator's chain only. The retry below deletes and recreates the+ // precondition source, so a baseline carrying its hop would name a source id+ // that no longer exists — and that refusal is not partial.+ const original: RouteHop[] = await captureAgentChain(api, gateway);+ try {+ // The restoration boundary is entered BEFORE the arranged PUT (inside+ // `arrange` below), not after it returns: a PUT whose response is lost+ // or times out rejects that await with the chain already replaced+ // server-side, and a finally outside it would leave the user's route+ // swapped for the arrangement — then the fixture's source sweep empties+ // it.+ await arrange();++ // `cooldown.server_error` is the one answer that is not an answer: the+ // gateway engine fails the dry run itself, without the upstream ever+ // receiving it, and every retry re-arms a fresh thirty-second cooldown on+ // top of the last — roughly one run in three (#1818). Recreating the source+ // sometimes clears it; waiting, restarting the engine, and cycling the whole+ // gateway do not. So a sticky cooldown is retried by rebuilding the+ // arrangement, bounded to three attempts.+ //+ // A defect that survives all three attempts is #1818's exact signature+ // (5xx + the upstream received nothing + the cooldown re-arming), and the+ // run then retires ITSELF via `test.fixme` naming #1818, so an+ // intermittent defect never burns the suite red. Any OTHER verdict still+ // fails hard below; a wrong classification is what the scenario exists to+ // catch.+ //+ // `test.fixme`, not `test.fail`. `test.fail` sets the expected status of+ // the whole TEST — its finally, the suite's afterEach, and the gateway+ // fixture's teardown included — so a restoration that then failed would+ // satisfy "expected to fail" and the run would report green over a+ // displaced route chain. Measured, not assumed: a mid-body `test.fail`+ // with a throwing finally reports PASSED, while `test.fixme` in the same+ // shape reports the teardown failure. Fixme also states the outcome+ // honestly — one skipped spec naming the issue, rather than a green tick+ // over a scenario that was never reached.+ // The #1818 signature is TWO facts together, and both are checked before+ // the marker fires: the source in `cooldown.server_error`, AND the mock+ // having received no DRY RUN while it got there. A cooldown with the dry+ // run on the log is a different defect — the upstream answered 401 and+ // something classified it badly — and it must fail hard, not ride #1818's+ // marker to green. Two discrimination rules keep that line honest:+ //+ // - Only a POST down a protocol path counts (`/v1/messages`,+ // `/v1/responses`, `/v1/chat/completions`): the 401 the marker+ // exists to route travels only on the dry run, while a `GET+ // /v1/models` is model-list traffic an engine reads at startup — and+ // #1818's engine restarts mid-settle, so startup GETs land on a+ // post-reset log without any completion ever being attempted.+ // - The marker reads the FINAL attempt's log, not an OR across+ // attempts: an earlier attempt's dial that still ended in a sticky+ // cooldown says nothing about the attempt that produced the verdict+ // being marked, and OR-ing them let #1818 ride in green under an+ // earlier attempt's history.+ const upstreamSawDryRun = async (): Promise<boolean> => {+ const requests = await mock.requests();+ return requests.some(+ (request) => request.method === 'POST'+ && /^\/v1\/(messages|responses|chat\/completions)$/.test(request.path.split('?')[0]),+ );+ };+ await mock.resetRequests();+ await mock.configure({ auth: '401' });+ let verdict = await settleKeyVerdict(api, source.id, gateway);+ // Per-attempt, not cumulative: the marker at the end must be able to say+ // "the attempt that produced THIS verdict never reached the upstream."+ let upstreamReceived = await upstreamSawDryRun();+ for (let attempt = 0; attempt < 3 && verdict === 'models.source.cooldown.server_error'; attempt += 1) {+ // The recreation has to happen against a HEALTHY upstream — the create+ // probes the source before committing it, and the mock is still set to+ // 401 for the settle. The rejection is re-armed after the new source+ // exists, by the same dry run as before.+ await mock.configure({ auth: 'ok' });+ await api.deleteSource(source.id);+ const rebuilt = await api.createApiKeySource(source.display_name, mockBaseUrl());+ if (!rebuilt) {+ // The instance that cannot rebuild this arrangement is a product+ // failure wearing the cooldown's clothes — named, not skipped, and not+ // #1818 either.+ throw new Error('The instance refused to recreate the precondition source.');+ }+ expect(+ rebuilt.models.some((model) => model.id === supplied),+ 'The recreated source lost the model the route depends on.',+ ).toBe(true);+ source = rebuilt;+ await arrange();+ await mock.configure({ auth: '401' });+ // One cooldown window (plus slack) is enough for a retry attempt: the+ // defect this loop exists for re-arms the cooldown on EVERY probe, so a+ // second window after the first re-armed would only burn another 30 s on+ // the way to the same verdict. The FIRST settle keeps the full budget,+ // where a genuine one-off transient still gets its chance to clear.+ await mock.resetRequests();+ verdict = await settleKeyVerdict(api, source.id, gateway, 35_000);+ upstreamReceived = await upstreamSawDryRun();+ }+ test.fixme(+ verdict === 'models.source.cooldown.server_error' && !upstreamReceived,+ 'Engine 5xx on the routed dry run (#1818): the upstream never received the request and the '+ + 'cooldown re-armed on every retry, so the replace-key flow was never reachable this run.',+ );+ expect(verdict).toBe('models.source.needs_action.credential_revoked');+ // The replacement has to be a key that works, or the dialog would be+ // reporting the same failure over again under a different name.+ await mock.configure({ auth: 'ok' });++ await hub.goto();+ await hub.openSource(source.id);+ await expect(hub.sourceDetailDialog).toBeVisible();++ // What a stopped row owes the user is one tap to the fix, not an error+ // string. The attribute is the product's own statement of where that tap+ // goes, and the label is what the user reads on it.+ const repair = hub.sourceDetailDialog.locator('[data-repair-destination="replace_key_dialog"]');+ await expect(repair).toHaveText(copy('repair.replaceKey'));+ await repair.click();++ const dialog = hub.addKeyDialog;+ await expect(dialog).toBeVisible();+ await expect(dialog).toContainText(copy('repair.replaceTitle', { name: source.display_name }));++ await dialog.getByLabel(copy('repair.replaceLabel'), { exact: true }).fill('e2e-second-key');+ await dialog.getByRole('button', { name: copy('repair.replaceSubmit'), exact: true }).click();++ // The upstream still lists the same models, so the new key costs the route+ // nothing — a plain repair, and the dialog says which of the two it was.+ await expect(dialog).toContainText(copy('repair.repaired'), { timeout: 30_000 });+ // And the row it was raised from is no longer stopped. A dialog that+ // reports a repair over a source still marked blocked has reported a+ // repair that did not happen.+ await expect+ .poll(+ async () => (await api.sources()).find((s) => s.id === source.id)?.state.detail_key,+ { timeout: 15_000 },+ )+ .toBeNull();+ } finally {+ // Whatever happened above, the instance's chain for this model goes back+ // to what it was — the arrangement was the scenario's, not the user's.+ await restoreAgentChain(api, gateway, original);+ }+ });+});diff --git a/ui/e2e/b-source-detail.spec.ts b/ui/e2e/b-source-detail.spec.tsnew file mode 100644index 000000000..41e35c05f--- /dev/null+++ b/ui/e2e/b-source-detail.spec.ts@@ -0,0 +1,172 @@+// Suite B (continued) — what a source's own panel lets a user do to it.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+//+// The source these specs act on is created through the API, not through the Add+// dialog: their subject is what happens AFTER a source exists, and re-driving+// Add here would report Add's failures under a rename test's name.+import { hub as copy } from './support/copy';+import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';+import {+ expect,+ expectVisibleWithout,+ requireMockUpstream,+ requireModelHub,+ requireRuntimeRunning,+ requireSource,+ test,+} from './support/fixtures';+import { anthropicInventory } from './support/mock';++test.describe('B · the source detail panel', () => {+ test.beforeEach(async ({ api, mock }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ await requireMockUpstream(mock);+ });++ test.afterEach(async ({ api }) => {+ await api.removeSuiteSources();+ });++ test('B6 · renaming a source goes through the manage menu and sticks', async ({ hub, mock, api }) => {+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-rename-a']),+ });+ const before = `${E2E_SOURCE_PREFIX}rename-before`;+ const after = `${E2E_SOURCE_PREFIX}rename-after`;+ const source = await requireSource(api, before, mockBaseUrl());++ await hub.goto();+ await hub.openSource(source.id);+ await expect(hub.sourceDetailDialog).toBeVisible();++ await hub.manageMenuTrigger(before).click();+ await hub.manageItem('edit_source').click();++ // The edit dialog and the guard dialog share a class, so this names the one+ // it means by its title rather than by hoping only one is mounted.+ const edit = hub.dialogTitled(copy('sourceDetail.edit.title', { source: before }));+ await expect(edit).toBeVisible();+ await edit.getByLabel(copy('sourceDetail.edit.name'), { exact: true }).fill(after);+ await edit.getByRole('button', { name: copy('sourceDetail.edit.save'), exact: true }).click();++ // Nothing routes through this source, so the rename settles with no guard+ // and the panel is showing the new name by the time the dialog is gone.+ await expect(edit).toHaveCount(0, { timeout: 30_000 });+ await expect(hub.sourceDetailDialog).toContainText(after);+ await expect+ .poll(async () => (await api.sources()).find((s) => s.id === source.id)?.display_name, {+ timeout: 15_000,+ })+ .toBe(after);+ });++ test('B9 · a refetch marks what arrived and names what left', async ({ hub, mock, api }) => {+ // The upstream's inventory changes between the two fetches. That diff — not+ // the final list — is what the panel owes the user.+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-keep', 'e2e-drop']),+ });+ const name = `${E2E_SOURCE_PREFIX}refetch`;+ const source = await requireSource(api, name, mockBaseUrl());+ // The mock has been seeded and has answered; a source that comes back+ // without the inventory it was handed is the product's doing, not the+ // environment's (§5a).+ expect(+ source.models.length,+ 'The precondition source did not take the seeded inventory, so there is no diff to observe.',+ ).toBe(2);++ await mock.configure({ models: anthropicInventory(['e2e-keep', 'e2e-arrive']) });++ await hub.goto();+ await hub.openSource(source.id);+ await hub.sourceDetailDialog+ .getByRole('button', { name: copy('sourceDetail.action.refetch'), exact: true })+ .click();++ // Arrived: the row exists and is flagged as new. Left: named in a line, not+ // silently absent — a user who never saw `e2e-drop` vanish cannot act on it.+ await expect(hub.modelRow('e2e-arrive')).toBeVisible({ timeout: 30_000 });+ await expect(hub.modelRow('e2e-arrive')).toContainText(copy('sourceDetail.refetch.added'));+ await expect(hub.sourceDetailDialog).toContainText(+ copy('sourceDetail.refetch.removed', { count: 1, models: 'e2e-drop' }),+ );+ await expect(hub.modelRow('e2e-drop')).toHaveCount(0);+ // The survivor is STILL THERE and is not re-announced: "New" means new.+ // Both halves, because a refetch that dropped `e2e-keep` alongside `e2e-drop`+ // satisfies the second one all by itself.+ await expectVisibleWithout(hub.modelRow('e2e-keep'), copy('sourceDetail.refetch.added'));++ // NOTE (spec §3 B9): the other half of B9 — that a surviving model keeps its+ // original `discovered_at` — is not observable from the browser at all. It+ // belongs to the pytest lane; asserting a rendered timestamp here would only+ // test the formatter.+ });++ test('B10 · a model added by hand carries its tiers, and can be taken back out', async ({ hub, mock, api }) => {+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-discovered']),+ });+ const name = `${E2E_SOURCE_PREFIX}manual-model`;+ const source = await requireSource(api, name, mockBaseUrl());++ await hub.goto();+ await hub.openSource(source.id);+ await hub.sourceDetailDialog+ .getByRole('button', { name: copy('sourceDetail.action.addModel'), exact: true })+ .click();++ const draft = hub.manualDraftRow;+ await expect(draft).toBeVisible();+ await draft.getByPlaceholder(copy('sourceDetail.col.id'), { exact: true }).fill('e2e-by-hand');+ // Tiers are free text committed with Enter — the product says so in the+ // placeholder, and this is the path a user actually takes.+ const tierInput = draft.getByPlaceholder(copy('sourceDetail.tiers.inputHint'), { exact: true });+ await tierInput.fill('e2e-low');+ await tierInput.press('Enter');+ await tierInput.fill('e2e-high');+ await tierInput.press('Enter');+ // Typed, then thought better of: removing a tier before committing must+ // actually drop it, not just hide the chip.+ await draft.getByRole('button', { name: copy('sourceDetail.tiers.remove', { tier: 'e2e-high' }), exact: true }).click();++ await draft.getByRole('button', { name: copy('sourceDetail.action.addModel'), exact: true }).click();++ const row = hub.modelRow('e2e-by-hand');+ await expect(row).toBeVisible({ timeout: 30_000 });+ // Provenance is visible, because a hand-added model behaves differently on+ // the next refetch than a discovered one.+ await expect(row).toContainText(copy('sourceDetail.entry.manual'));+ await expect(row).toContainText('e2e-low');+ await expectVisibleWithout(row, 'e2e-high');+ await expect+ .poll(+ async () =>+ (await api.sources())+ .find((s) => s.id === source.id)+ ?.models.find((model) => model.id === 'e2e-by-hand')?.reasoning_efforts,+ { timeout: 15_000 },+ )+ .toEqual(['e2e-low']);++ // And back out again. No route runs through it, so nothing guards this.+ await row.getByRole('button', { name: `${copy('sourceDetail.row.remove')} e2e-by-hand`, exact: true }).click();+ await hub.page+ .getByRole('menuitem', { name: copy('sourceDetail.row.remove'), exact: true })+ .click();+ await expect(row).toHaveCount(0, { timeout: 30_000 });+ // The discovered model is untouched: removing one model is not a refetch.+ await expect(hub.modelRow('e2e-discovered')).toBeVisible();+ });+});diff --git a/ui/e2e/d-routing.spec.ts b/ui/e2e/d-routing.spec.tsnew file mode 100644index 000000000..c97cef945--- /dev/null+++ b/ui/e2e/d-routing.spec.ts@@ -0,0 +1,283 @@+// Suite D — the two surfaces that decide which source serves a request: a+// model's own route chain, and the backend-wide priority order.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+//+// Both surfaces here are edited and then CANCELLED. That is not timidity: this+// suite runs against a live instance whose routing may be real, and the+// behaviour under test is what the editor does while you are editing it. The+// commit path is scenario B7's subject, on a source this suite owns outright.+import type { RouteHop } from './support/api';+import { hub as copy, hubOrNull } from './support/copy';+import { requireMockUpstream, requireModelHub, requireRuntimeRunning } from './support/fixtures';+import { expect, test } from './support/gateway';+import { labelledButton } from './support/hub';+import { captureAgentChain, restoreAgentChain } from './support/restore';++/** The product falls back to the raw backend id for a backend it has no label+ * for, so this does too rather than throwing on an id the bundle never named. */+const backendLabel = (backend: string): string => hubOrNull(`backends.${backend}`) ?? backend;++test.describe('D · route chains and priority order', () => {+ test.beforeEach(async ({ api, mock }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ await requireMockUpstream(mock);+ });++ test('D · a hop can be added, removed, and reordered by keyboard alone', async ({ hub, gateway, page }) => {+ await hub.goto();+ const row = hub.firstRouteRow(gateway.backend);+ await expect(row).toBeVisible();+ await row.click();++ const dialog = hub.routeDialog;+ await expect(dialog).toBeVisible();+ const hops = dialog.locator('.model-hub-route-hop');+ const before = await hops.count();++ // --- add (keyboard) -------------------------------------------------------+ // The whole scenario is a keyboard claim, so every step below drives focus+ // and keystrokes the way the claim's reader assumes it was driven: trigger,+ // candidate, confirm, and removal are all reached without a pointer.+ const addHop = dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true });+ const addOneHop = async (): Promise<void> => {+ // The trigger itself is key-activated too. It lives in the dialog, outside+ // the popover's cmdk panel — so Enter presses it (like the remove buttons+ // below); the Enter-swallowing rule only begins once the panel is open.+ await addHop.focus();+ await addHop.press('Enter');+ // The picker autofocuses its search box; cmdk's list takes ArrowDown to+ // move the selection and Enter to fire `onSelect`, which is the product's+ // own keyboard path for choosing a candidate.+ const search = page.getByPlaceholder(copy('routeDialog.add.search'), { exact: true });+ await expect(search).toBeFocused();+ await search.press('ArrowDown');+ await search.press('Enter');+ // The footer confirm is the next tabbable after the search box, and —+ // inside a cmdk panel — it answers Space, not Enter: cmdk's root handler+ // calls preventDefault() on every Enter that reaches it (Enter belongs to+ // the list there), which suppresses the button's native Enter activation.+ // Space is the activation that genuinely works, so Space is what a+ // keyboard user actually presses here.+ await search.press('Tab');+ const confirm = page.getByRole('button', { name: copy('routeDialog.add.confirm'), exact: true });+ await expect(confirm).toBeFocused();+ await confirm.press(' ');+ };+ test.skip(+ await addHop.isDisabled(),+ 'Every available source/model pair is already in this chain, so there is nothing left to add.',+ );+ await addOneHop();+ await expect(hops).toHaveCount(before + 1);++ // The reorder below is the other half of this spec, and a one-hop chain has+ // no order to change — which is exactly what an empty chain plus one add+ // is. So take a second hop while the instance still offers one, rather than+ // skipping the keyboard path on an arrangement this spec can fix itself.+ if (before + 1 < 2 && !(await addHop.isDisabled())) {+ await addOneHop();+ await expect(hops).toHaveCount(before + 2);+ }++ // --- keyboard reorder ---------------------------------------------------+ const added = await hops.count();+ test.skip(+ added < 2,+ 'A single-hop chain has no order to change; this instance offered only one candidate.',+ );+ const announcer = dialog.locator('[aria-live="polite"]');+ const firstGrip = hops.first().getByRole('button', { name: copy('routeDialog.grip'), exact: true });+ await firstGrip.focus();+ await firstGrip.press(' ');+ // The grab is announced, and the row says it is held — a sighted user sees+ // the lift, and this is the same fact stated for everyone else.+ await expect(announcer).toHaveText(copy('routeDialog.reorder.grabbed', { position: 1 }));+ await expect(firstGrip).toHaveAttribute('aria-grabbed', 'true');++ await firstGrip.press('ArrowDown');+ await expect(announcer).toHaveText(copy('routeDialog.reorder.position', { position: 2 }));++ // Space again drops what Space picked up, and says where it landed. The+ // OTHER way out of a grab — Escape, which should put the hop back — closes+ // the whole editor instead; see the fixme below.+ //+ // The drop is addressed by the row that reports itself held, not by+ // `hops.first()`: the move just made the first row a different hop, and a+ // locator re-resolves every time it is used.+ const heldGrip = dialog.locator('[aria-grabbed="true"]');+ await heldGrip.press(' ');+ await expect(announcer).toHaveText(copy('routeDialog.reorder.dropped', { position: 2 }));+ await expect(dialog.locator('[aria-grabbed="true"]')).toHaveCount(0);++ // --- remove (keyboard) ----------------------------------------------------+ // Back down to what was there before, one row at a time — the editor has to+ // give back everything it took, not just the last thing. The remove buttons+ // are roving-tabindex siblings of the grips, so each is focused directly and+ // pressed rather than clicked.+ for (let remaining = added; remaining > before; remaining -= 1) {+ const remove = hops.last().getByRole('button', { name: copy('routeDialog.removeHop'), exact: true });+ await remove.focus();+ await remove.press('Enter');+ await expect(hops).toHaveCount(remaining - 1);+ }++ // Cancel: this spec is about the editor, and the instance's real routing is+ // not this spec's to change.+ await labelledButton(dialog, copy('routeDialog.cancel')).click();+ await expect(dialog).toHaveCount(0);+ });++ // A defect this suite found, not a scenario from §3, and reported rather than+ // patched (this lane changes no product code) — filed as #1819.+ //+ // Escape during a keyboard grab is meant to be an undo: `onGripKeyDown` puts+ // the hop back, refocuses it, and announces `reorder.cancelled`. It does all+ // three — and then the dialog closes on the same keystroke, discarding every+ // unsaved edit, so nobody ever reads that announcement. The handler calls+ // `preventDefault()` only; Radix's dismissable layer listens on the document+ // and does not consult `defaultPrevented`. `SourceOrderDrawer` gets this right+ // twice over: `stopPropagation()` in the row handler AND an `onEscapeKeyDown`+ // guard on the dialog content. The route dialog has neither.+ //+ // Unfixme once #1819 lands the same guard on the route dialog; the assertion+ // is the two lines below, which is exactly what the drawer spec already+ // asserts.+ test.fixme('D · Escape cancels a grab without discarding the chain edit', async ({ hub, gateway, page }) => {+ await hub.goto();+ await hub.firstRouteRow(gateway.backend).click();+ const dialog = hub.routeDialog;+ const grip = dialog.locator('.model-hub-route-hop').first().getByRole('button', {+ name: copy('routeDialog.grip'),+ exact: true,+ });+ await grip.press(' ');+ await page.keyboard.press('Escape');+ await expect(dialog).toBeVisible();+ await expect(dialog.locator('[aria-live="polite"]')).toHaveText(+ copy('routeDialog.reorder.cancelled', { position: 1 }),+ );+ });++ test('D · Reorder by Source order restates the chain, and says which it did', async ({ hub, gateway, api }) => {+ // Arranged, not hoped for. On a fresh hermetic instance the fixture's+ // `e2e-route-*` models do not match the backend menu, so this route begins+ // EMPTY — and an empty chain leaves the button with nothing to sort, so the+ // `unchanged` branch passes without the sorter ever running. The two hops+ // below are therefore the actual subject: deliberately opposite to Source+ // order, so the sort has a real permutation to perform.+ const supply = gateway.sources.flatMap((source) =>+ source.models.map((model) => ({ source_id: source.id, model_id: model.id })),+ );+ test.skip(+ supply.length < 2,+ 'This instance offers fewer than two source/model pairs, so no unsorted chain can be arranged.',+ );+ // The order of `gateway.sources` is the suite's own; the order the instance+ // routes by is Source order. Arranging route-b before route-a is opposite to+ // creation order only when creation order became priority order — which the+ // API call below establishes rather than assumes.+ const arrangeHops = [+ { source_id: gateway.sources[1].id, model_id: gateway.sources[1].models[0].id },+ { source_id: gateway.sources[0].id, model_id: gateway.sources[0].models[0].id },+ ];+ const original: RouteHop[] = await captureAgentChain(api, gateway);+ try {+ // Entered BEFORE the arranged PUT, not after it succeeds: a PUT whose+ // response is lost or times out rejects that await with the chain+ // already replaced server-side, and a finally outside it would leave+ // the user's route swapped for the arrangement — then the fixture's+ // source sweep empties it entirely.+ expect(+ await api.putAgentChain(gateway.backend, gateway.model, arrangeHops),+ 'The instance refused the arranged route, so there is no chain to sort.',+ ).toBe(true);++ await hub.goto();+ // The row for THIS model, not the card's first: the first row a card+ // shows is whichever model the supply ranks first — a different chain+ // than the one arranged above. And a collapsed card renders only its+ // first six models, so a selected model seventh-or-later has no row in+ // the DOM at all until the card is expanded.+ const card = hub.agentCard(gateway.backend);+ const expand = card.locator('.model-hub-model-collapse').first();+ if (await expand.count()) await expand.click();+ await hub.routeRow(gateway.backend, gateway.model).click();+ const dialog = hub.routeDialog;+ await expect(dialog).toBeVisible();++ const announcer = dialog.locator('[aria-live="polite"]');+ await dialog.getByRole('button', { name: copy('routeDialog.reorder.label'), exact: true }).click();++ // The announcement must say it sorted — the draft was arranged opposite+ // to Source order, so "already matches" would be the wrong claim.+ await expect(announcer).toHaveText(copy('routeDialog.reorder.sorted'));+ // And the hops must now BE in Source order, asserted by display name: the+ // name cell carries the id only for unjoined sources, so the display name+ // is the one observable every rendering shares. Each fixture source+ // contributes exactly one hop here, so name order IS hop order.+ const hops = dialog.locator('.model-hub-route-hop-name');+ await expect(hops).toHaveCount(2);+ await expect(hops.nth(0)).toHaveText(gateway.sources[0].display_name);+ await expect(hops.nth(1)).toHaveText(gateway.sources[1].display_name);++ await labelledButton(dialog, copy('routeDialog.cancel')).click();+ await expect(dialog).toHaveCount(0);+ } finally {+ await restoreAgentChain(api, gateway, original);+ }+ });++ test('D · the priority drawer moves a source by keyboard and can be backed out of', async ({ hub, gateway, page }) => {+ await hub.goto();+ await hub.adjustPriorityButton(gateway.backend).click();++ const drawer = hub.orderDrawer;+ await expect(drawer).toBeVisible();+ await expect(drawer).toContainText(+ copy('order.title', { backend: backendLabel(gateway.backend) }),+ );++ const ordered = drawer.locator('.model-hub-order-row--ordered');+ const count = await ordered.count();+ test.skip(count < 2, 'Fewer than two sources are in this backend\'s order, so there is nothing to reorder.');++ const announcer = drawer.locator('[aria-live="polite"]');+ // The row's own name cell, not its first line: the row leads with its+ // position ordinal, so `innerText().split('\n')[0]` is "1" and the expected+ // announcement becomes "Grabbed 1, position 1 of 3."+ const firstName = (await ordered.first().locator('.model-hub-order-name').innerText()).trim();+ const grip = ordered.first().getByRole('button', { name: copy('order.reorder'), exact: true });+ await grip.focus();+ await grip.press(' ');+ await expect(announcer).toHaveText(+ copy('order.grabbed', { source: firstName, position: 1, count }),+ );++ await grip.press('ArrowDown');+ await expect(announcer).toHaveText(+ copy('order.moved', { source: firstName, position: 2, count }),+ );++ await page.keyboard.press('Escape');+ await expect(announcer).toHaveText(copy('order.grabCancelled', { source: firstName }));+ // Cancelling restored the position, so the first row is the one it started as.+ await expect(ordered.first()).toContainText(firstName);++ // Closed without saving: nothing this drawer did reaches the instance.+ await labelledButton(drawer, copy('order.cancel')).click();+ await expect(drawer).toHaveCount(0);+ });++ // D1 — "a newly added source lands at the tail of the order rather than+ // displacing an existing one" — needs a SECOND source to arrive while a+ // non-trivial order already exists, and the plan's D1 states it for a+ // subscription source. A subscription source cannot be created from a browser+ // without a real OAuth provider, and this lane may not add a product test+ // hook, so the observable half is left to the pytest lane.+ test.fixme('D1 · a new source is appended to the priority order, not inserted', async () => {+ // Blocked on: no browser-reachable way to add a subscription source against+ // a mock. Reported to the orchestrator as a coverage gap, not a defect.+ });+});diff --git a/ui/e2e/e-usage-logs.spec.ts b/ui/e2e/e-usage-logs.spec.tsnew file mode 100644index 000000000..499fc7cbe--- /dev/null+++ b/ui/e2e/e-usage-logs.spec.ts@@ -0,0 +1,142 @@+// Suite E — the two read-only tabs: Usage and Logs.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+//+// Neither tab can be made to show a particular number from a browser: the+// figures come from turns the gateway actually proxied, and this suite does not+// run agent turns. What IS assertable, and is what these specs assert, is that+// each tab reaches a *stated* state rather than a blank panel — an empty window+// says it is empty in words, and a populated one carries the sections it+// promises. Asserting specific figures needs seeded gateway traffic and belongs+// to the pytest lane.+import { hub as copy } from './support/copy';+import { expect, requireModelHub, requireRuntimeRunning, test } from './support/fixtures';++test.describe('E · usage and logs', () => {+ test.beforeEach(async ({ api }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ });++ test('E1 · the usage tab states its window, and states when the window is empty', async ({ hub, page }) => {+ await hub.goto();+ await hub.openTab('usage');+ await expect(hub.tab('usage')).toHaveAttribute('aria-selected', 'true');++ await expect(page.getByRole('heading', { name: copy('usage.title'), level: 2 })).toBeVisible();++ // The window is the reading's frame, so it is a labelled control, not a+ // caption: a number with no stated window is not a usage report.+ const window = page.getByRole('radiogroup', { name: copy('usage.window.label') });+ await expect(window).toBeVisible();+ await expect(window.getByRole('radio', { checked: true })).toHaveCount(1);++ // Two honest shapes, and the tab has to say which it is. `count()` reads+ // instantly, and the tab renders NEITHER shape while the read is in flight+ // — so branching on it this early would classify a valid empty report as+ // populated. Waiting on one shape or the other settles the read first.+ const empty = page.getByText(copy('usage.empty'), { exact: true });+ const populated = page.getByRole('heading', { name: copy('usage.bySource.title'), level: 3 });+ await expect(empty.or(populated)).toBeVisible();+ if (await empty.count()) {+ await expect(empty).toBeVisible();+ return;+ }+ // Populated owes both breakdowns — a total with no attribution cannot be+ // acted on.+ await expect(populated).toBeVisible();+ await expect(page.getByRole('heading', { name: copy('usage.byDay.title'), level: 3 })).toBeVisible();+ });++ test('E1 · picking another window moves the selection and re-reads the range', async ({ hub, page }) => {+ await hub.goto();+ await hub.openTab('usage');++ const window = page.getByRole('radiogroup', { name: copy('usage.window.label') });+ const options = window.getByRole('radio');+ const total = await options.count();+ test.skip(total < 2, 'This build offers a single usage window, so there is nothing to switch between.');++ const note = page.locator('.model-hub-usage-note');+ // The tab's own loading/unread copy IS the detail text, so a `before`+ // captured mid-read is indistinguishable from a settled empty report — and+ // the branch below would skip the only assertion that the selection moved+ // the reading. Even a successfully loaded empty window renders a range, so+ // waiting for one is waiting for the read to settle, not for data.+ await expect(note).toContainText(/–|—|Nothing metered yet/, { timeout: 20_000 });+ const before = (await note.innerText()).trim();+ // Named, not matched on state: `getByRole('radio').and('[aria-checked=false]')`+ // re-resolves on every assertion, so the moment the click lands it stops+ // pointing at the option that was clicked and starts pointing at the next+ // still-unchecked one — which is, correctly, still false.+ const checked = (await window.getByRole('radio', { checked: true }).innerText()).trim();+ const labels = (await options.allInnerTexts()).map((label) => label.trim());+ const targetLabel = labels.find((label) => label !== checked);+ // A `find` miss here means every option carries the same label, which is a+ // broken radio group, not an environment the instance was born with.+ expect(targetLabel, 'Every usage window option carries the same label.').toBeDefined();+ const target = window.getByRole('radio', { name: targetLabel!, exact: true });+ await target.click();++ // The selection is exclusive — a segmented control that checks a second+ // option without unchecking the first has stopped being a radio group.+ await expect(target).toHaveAttribute('aria-checked', 'true');+ await expect(window.getByRole('radio', { checked: true })).toHaveCount(1);++ // And the reading follows it. The wait above has already ruled out the+ // loading text, so a `before` that still reads as the static explainer is a+ // genuinely empty window: an instance that never metered a turn, where the+ // range has nothing to restate. That is a state, not a pass by default, so+ // it is named here instead of being swept into the assertion.+ if (before !== copy('usage.detail')) {+ await expect+ .poll(async () => (await note.innerText()).trim(), { timeout: 15_000 })+ .not.toBe(before);+ }+ });++ test('E3 · the logs tab shows the switch history, or says there is none', async ({ hub, page }) => {+ await hub.goto();+ await hub.openTab('logs');+ await expect(hub.tab('logs')).toHaveAttribute('aria-selected', 'true');++ // NOTE: the Logs tab has no `settings.models.logs.*` copy of its own — it+ // renders the recent-switches card, whose strings live under+ // `settings.models.recent.*`. Asserting a `logs.*` key here would assert a+ // key that does not exist.+ await expect(page.getByRole('heading', { name: copy('recent.title'), level: 2 })).toBeVisible();++ // The tab must settle. A card left on "Loading…" is the failure this+ // catches, and it is the one an empty-state assertion alone would miss.+ await expect(page.getByText(copy('recent.loadingMore'), { exact: true })).toHaveCount(0, {+ timeout: 20_000,+ });++ const empty = page.getByText(copy('recent.empty'), { exact: true });+ const viewAll = page.getByRole('button', { name: copy('recent.viewAll'), exact: true });+ // A populated card's event rows carry no stable class, so the third honest+ // shape is named by what every row must render — the timestamped cell. The+ // `loadingMore` guard above has already settled the read by this point.+ // `.or()` demands exactly one match and a populated card shows BOTH "View+ // all" and rows, so the populated branch asserts its own element rather+ // than joining the chain.+ const populated = page+ .locator('section')+ .filter({ has: page.getByRole('heading', { name: copy('recent.title'), level: 2 }) })+ .locator('span.font-mono')+ .first();+ if (await empty.count()) {+ await expect(empty).toBeVisible();+ return;+ }+ await expect(populated).toBeVisible();+ // With history present the card offers the rest of it, unless everything+ // already fits — both are stated states, and neither is a blank panel.+ if (await viewAll.count()) {+ await viewAll.click();+ await expect(+ page.getByRole('button', { name: copy('recent.collapse'), exact: true }),+ ).toBeVisible();+ }+ });+});diff --git a/ui/e2e/g-guards-copy.spec.ts b/ui/e2e/g-guards-copy.spec.tsnew file mode 100644index 000000000..be3bafc60--- /dev/null+++ b/ui/e2e/g-guards-copy.spec.ts@@ -0,0 +1,168 @@+// Suite G — the supply guards, and the copy the failure paths owe the user.+//+// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.+//+// Baseline discipline (§5a): `fix-first` scenarios land as `test.fixme` with+// the open decision named, never as red tests. Four of them do so below; each+// says what would have to change for it to become an assertion.+import type { RouteHop } from './support/api';+import { hasCopy, hub as copy } from './support/copy';+import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';+import {+ expectVisibleWithout,+ requireMockUpstream,+ requireModelHub,+ requireRuntimeRunning,+} from './support/fixtures';+import { expect, test } from './support/gateway';+import { fillApiKeyForm, labelledButton } from './support/hub';+import { captureAgentChain, restoreAgentChain } from './support/restore';++test.describe('G · supply guards and failure copy', () => {+ test.beforeEach(async ({ api, mock }) => {+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ await requireMockUpstream(mock);+ });++ test('B7 · removing the only source of a route is refused, explained, then reported', async ({ hub, api, gateway }) => {+ const source = gateway.sources[0];+ const supplied = source.models[0]?.id;+ expect(+ supplied,+ `The precondition source ${source.display_name} came back with no models, so no route can reach it.`,+ ).toBeDefined();++ // Arrange the one state a guard exists for: this source is the ONLY hop of a+ // configured route, so removing it leaves that model with no supply. The+ // chain is captured first and put back in teardown — the instance's real+ // routing is not this spec's to keep. Real routing is also all it captures:+ // the source deleted below may already be a hop here, and restoring a hop+ // this spec is about to delete is how the whole restore gets refused.+ const original: RouteHop[] = await captureAgentChain(api, gateway);+ try {+ // Entered BEFORE the arranged PUT, not after it succeeds: a response+ // lost to a timeout or disconnect rejects that await with the chain+ // already replaced server-side, and a finally outside it would leave+ // the user's route swapped for the arrangement — then the fixture's+ // source sweep empties it entirely.+ const arranged = await api.putAgentChain(gateway.backend, gateway.model, [+ { source_id: source.id, model_id: supplied! },+ ]);+ expect(arranged, 'The instance refused the arranged route, so no guard can be raised.').toBe(true);++ await hub.goto();+ await hub.openSource(source.id);+ await expect(hub.sourceDetailDialog).toBeVisible();+ await hub.manageMenuTrigger(source.display_name).click();+ await hub.manageItem('delete_source').click();++ // 1 · the plain confirm. The menu item opens it with no evidence in it,+ // because the client has not asked the server anything yet — it only knows+ // that deleting a source is destructive.+ const guard = hub.dialogTitled(copy('guard.title.deleteSource', { source: source.display_name }));+ const confirm = guard.getByRole('button', {+ name: copy('guard.confirm.deleteSource'),+ exact: true,+ });+ await expect(guard).toBeVisible({ timeout: 30_000 });+ await expect(guard).toContainText(copy('guard.subtitle.deleteSource'));+ await expectVisibleWithout(guard, copy('guard.label'));++ // 2 · confirming ATTEMPTS the delete, and the SERVER refuses it. The same+ // dialog comes back carrying the refusal's own plan — which hops go, and+ // which models are left with nothing. That two-step shape is the scenario:+ // a source nothing routes through is deleted on the first confirm, and the+ // evidence below appears only because something is actually at stake.+ await confirm.click();+ await expect(guard).toContainText(copy('guard.label'), { timeout: 30_000 });+ await expect(guard).toContainText(copy('guard.gap.label'));+ await expect(guard).toContainText(copy('guard.hint.interrupt'));+ await expect(guard).toContainText(gateway.model);++ // 3 · confirm again, which re-sends the delete echoing that plan back.+ await confirm.click();++ // 4 · the impact report. Not a toast: the same facts restated in the past+ // tense, so a user who confirmed too fast can still read what they did.+ const report = hub.mutationReport('delete');+ await expect(report).toBeVisible({ timeout: 30_000 });+ await expect(report).toContainText(copy('sourceDetail.remove.impact.title'));+ await expect(report).toContainText(copy('guard.result.label'));+ await expect(report).toContainText(copy('guard.result.gapLabel'));+ await labelledButton(report, copy('sourceDetail.remove.impact.done')).click();+ await expect(report).toHaveCount(0);++ await expect+ .poll(async () => (await api.sources()).some((s) => s.id === source.id), { timeout: 15_000 })+ .toBe(false);+ } finally {+ // The delete that just ran means nothing downstream can put this chain+ // back, so `restoreAgentChain`'s refusal-is-a-failure contract is the+ // whole guarantee here.+ await restoreAgentChain(api, gateway, original);+ }+ });++ // G1 (fix-first) — "guard echo with a gap missing `agents` → no confirm-loop".+ // The echo is a request body field. A browser cannot send a malformed echo+ // without the product building it, and this lane may not add a product hook to+ // corrupt it, so the probe is not reachable from Playwright at all. It belongs+ // to the pytest lane; recorded here so the scenario is not silently uncovered.+ test.fixme('G1 · a guard echo missing `agents` does not re-open the guard', async () => {+ // Blocked on: open decision B7 / §5 — and on the echo being unreachable from+ // a browser. See docs/plans/model-hub-e2e-test-plan.md §3 G1.+ });++ // B11 (fix-first, baseline expected-fail per open decision D-3) — every server+ // failure must reach the user as human copy, never as a raw+ // `modelHub.errors.*` key. `AddApiKeyDialog.tsx` passes `failure.detail`+ // straight through as an i18n key when it starts with that prefix, and no+ // `modelHub.*` namespace exists in either browser bundle, so the key renders+ // as itself. The form is filled and SUBMITTED, because the defect only shows+ // in the answer to a submission that failed: an unsubmitted dialog shows+ // nothing to leak, and asserting on one would pass with the defect present.+ test.fixme('B11 · a server failure code is rendered as human copy, not as its key', async ({ hub, mock }) => {+ // Unfixme when D-3 lands the missing `modelHub.*` keys. The check itself:+ // drive a failure whose detail carries the prefix, then assert no visible+ // text looks like a bare i18n key.+ await mock.configure({ auth: '5xx', protocol: 'anthropic', models_endpoint: 'ok' });+ await hub.goto();+ await hub.addApiKeyButton.click();+ await expect(hub.addKeyDialog).toBeVisible();+ await fillApiKeyForm(hub.addKeyDialog, {+ name: `${E2E_SOURCE_PREFIX}b11-copy`,+ baseUrl: mockBaseUrl(),+ apiKey: 'e2e-copy-probe',+ });+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await expect(hub.addKeyDialog).toContainText(/modelHub\.errors\.|settings\.models\./);+ // The defect: the raw key is what reaches the user.+ await expectVisibleWithout(hub.addKeyDialog, /modelHub\.errors\./);+ });++ // D13 (assert) — the member-role dead-ends. Reaching them needs a SECOND auth+ // context: a browser session authenticated as a member rather than as the+ // trusted loopback operator. Every request from Playwright's browser to+ // 127.0.0.1 is trusted by construction, which is exactly why the suite needs+ // no login — and exactly why it cannot demote itself. Covering this needs a+ // member-session bootstrap the harness does not have; reported as a follow-up,+ // not patched into product code.+ test.fixme('D13 · a member sees visible refusals, not silently dead controls', async () => {+ // Blocked on: no second auth context. Loopback is trusted, so this browser+ // is always the operator. See ui/e2e/README.md § "What this suite cannot+ // reach".+ });++ // A copy defect found while writing this suite, not a scenario from §3:+ // `SettingsModelsPage.tsx` renders `settings.models.sourceDetail.gone` when an+ // open source disappears underneath the panel, and that key exists in neither+ // `en.json` nor `zh.json` — so the user is shown the key. Same class as B11+ // and reported with it.+ test.fixme('B11-adjacent · a source that vanishes under the open panel says so in words', async () => {+ // The assertion is on the bundle, not on the browser: the panel only reaches+ // this state when a source is removed out from under an open dialog, and the+ // key being absent is the whole defect.+ expect(hasCopy('settings.models.sourceDetail.gone')).toBe(true);+ });+});diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.tsnew file mode 100644index 000000000..bd73b19b6--- /dev/null+++ b/ui/e2e/support/api.ts@@ -0,0 +1,468 @@+// A thin state client over the frozen `/api/models/*` surface.+//+// This is deliberately NOT the thing under test. The suite asserts what a user+// can do in the browser; the API is here to read what state the live instance is+// in, to establish a scenario's PRECONDITIONS, and to put back what a spec+// changed. Two reasons it is not more UI clicking:+//+// - a teardown that clicked would fail for the same reason the test just+// failed, and leave the instance dirty for every spec after it;+// - a routing test whose setup re-drives the add-key dialog is really an+// add-key test wearing a routing test's name, and it reports the add flow's+// failures as routing failures.+//+// The line is: whatever the scenario is about goes through the browser.+import type { APIRequestContext } from '@playwright/test';++import { BASE_URL, E2E_SOURCE_PREFIX } from './env';++export type SourceState = { status: string; [key: string]: unknown };++export type Source = {+ id: string;+ display_name: string;+ kind: string;+ protocol: string;+ supply_channel: string;+ base_url?: string | null;+ credential_ref?: string | null;+ client_nonce?: string | null;+ models: { id: string; origin: string; reasoning_efforts: string[]; [key: string]: unknown }[];+ state: SourceState;+ adopted_by?: { backend: string; model: string }[];+};++export type Agent = {+ backend: string;+ mode: 'hub' | 'direct';+ cli_present: boolean;+ /**+ * The backend's model menu, each entry carrying how that model is routed.+ * This is where the agents payload names its models — there is no `models`+ * array on it, and a fixture that reads one silently skips every spec that+ * needs a route.+ *+ * Null outside Gateway mode — the server gates it on `mode == "hub"` — so it+ * answers "what does this backend route" only for a backend that already+ * routes. `routableModels` below is the question asked of any backend.+ */+ model_supply?: { model_id: string; chain_length: number; has_runnable_hop: boolean }[] | null;+ selected_model_id?: string | null;+ /** `fixed` for `claude`/`codex`, whose menu is a builtin list; `open` for+ * `opencode`, whose menu is whatever the operator has ticked. */+ menu_kind?: 'fixed' | 'open';+ builtin_models?: string[] | null;+ menu?: { checked?: string[] } | null;+ [key: string]: unknown;+};++export type Probe = {+ reachable: boolean;+ source_id?: string | null;+ model_id?: string | null;+ error?: string | null;+};++export type Runtime = {+ enabled: boolean;+ status: {+ health: string;+ installed_version?: string | null;+ listening?: { host: string; port: number } | null;+ };+ manifest: { resolution?: string };+};++export type Capabilities = { model_hub?: { enabled?: boolean } };++export type RouteHop = { source_id: string; model_id: string };++/**+ * Whether a source is this suite's own — the one namespace declaration, so+ * "ours" cannot be spelled differently by the code that deletes sources and the+ * code that decides which route hops survive the suite.+ *+ * The prefix is the identity, not a heuristic: every create path in the suite+ * carries it, including the ones that expect to fail.+ */+export const isSuiteSource = (source: Source): boolean =>+ source.display_name.startsWith(E2E_SOURCE_PREFIX);++/**+ * The models a backend's routes are keyed by — the set `model_supply` holds+ * once that backend is in Gateway mode.+ *+ * An INSTALLED backend is not the same thing as a backend with a route to open,+ * and the difference is not exotic: `_agent_payload` keys `model_supply` on the+ * builtin list for a `fixed` menu and on `menu.checked` for an `open` one, so an+ * `opencode` whose menu nobody has ticked sits in Gateway mode with an empty+ * supply while a `claude` in Direct mode has a full one.+ *+ * `model_supply` is the server's own answer and is preferred wherever it exists+ * — but it is null outside Gateway mode, so a Direct backend can only be judged+ * before the switch by the menu that BECOMES it, which is what the fallback+ * reconstructs.+ *+ * Deliberately narrower than the row list the page renders: `listedModelIds`+ * adds the selected model and existing route keys, so the surface can show a row+ * for a model `model_supply` does not carry — and `model_supply` is what a route+ * fixture and its guards read.+ */+export const routableModels = (agent: Agent): string[] =>+ agent.model_supply?.map((entry) => entry.model_id)+ ?? (agent.menu_kind === 'fixed' ? agent.builtin_models ?? [] : agent.menu?.checked ?? []);++/** Which body `/settings/models` renders, once the gate and the runtime have+ * already let the tab body render at all. */+export type SurfaceKind = 'gateway' | 'direct-home' | 'direct-no-backend';++/**+ * The page a spec lands on, answered ONCE from the two decisions the product+ * makes in `SettingsModelsPage.tsx`.+ *+ * A precondition is not a filter over instance facts, it is a claim about which+ * SURFACE those facts produce — and the product reaches its three surfaces+ * through two NESTED tests, so a spec that checks only the outer one admits an+ * instance whose page is a different shape. `directEmpty` (no sources AND every+ * backend on Direct) chooses `DirectHome` over the gateway overview; `DirectHome`+ * then renders `.model-hub-direct-empty` — an install prompt with no backend+ * card and no "Switch to gateway" button — when `installedAgents` is empty.+ *+ * Stated as a kind rather than as a boolean because the third case is not a+ * degenerate second one: "no backend installed" and "already a gateway" send+ * their reader to do opposite things, and a spec that reports one as the other+ * is worse than a spec that fails.+ */+export const surfaceKind = (agents: Agent[], sources: Source[]): SurfaceKind => {+ const directEmpty = sources.length === 0 && agents.every((agent) => agent.mode === 'direct');+ if (!directEmpty) return 'gateway';+ return agents.some((agent) => agent.cli_present) ? 'direct-home' : 'direct-no-backend';+};++/**+ * The plan a guarded mutation is refused with, read the way the route actually+ * sends it: `{ok: false, error: "source_in_route_chain", would_remove_hops: [],+ * would_interrupt: []}` — the two lists sit at the TOP level beside `error`,+ * which is a plain string, not an object with a `data` bag.+ *+ * Worth stating because getting it wrong is silent: a reader that looks under+ * `error.data` finds nothing, echoes two empty arrays, is refused a second time,+ * and reports the same `false` a genuinely un-forceable mutation would. That is+ * how a teardown leaves behind every source it was written to remove.+ */+const refusedPlan = (body: unknown): { would_remove_hops: unknown[]; would_interrupt: unknown[] } => {+ const refusal = (body ?? {}) as { would_remove_hops?: unknown[]; would_interrupt?: unknown[] };+ return {+ would_remove_hops: refusal.would_remove_hops ?? [],+ would_interrupt: refusal.would_interrupt ?? [],+ };+};++export type AgentChain = {+ backend: string;+ /** The menu model this chain routes. Named `model_id` on the wire — the+ * server writes `{model_id, chain}`, so a reader keying on `model` finds+ * nothing and quietly treats every existing route as empty. */+ model_id: string;+ chain: { source_id: string; model_id: string; [key: string]: unknown }[];+ [key: string]: unknown;+};++/**+ * The one read failure an operator can act on, spelled as an instruction.+ *+ * Worth lifting out of the generic throw because the intuition it contradicts+ * is a reasonable one: Playwright opens a FRESH browser context and the+ * `request` fixture keeps its own cookie jar, so being signed in to that+ * instance in your own browser carries nothing into a run. The refusal then+ * lands on a precondition read, before any test has named itself, and the+ * status alone reads like the instance is broken.+ *+ * Matched as a family rather than as one string: `vibe/ui_server.py` answers+ * 401 with `remote_access_login_required`, and `ui/src/lib/apiFetch.ts` treats+ * `remote_access_authorization_refresh_required`, `remote_access_revoked` and+ * `remote_access_authorization_unavailable` as the same class — the browser+ * must go and re-authorize. Not one of them is something this suite can do, so+ * what the operator needs to hear is the same sentence for all four.+ */+export const remoteAuthRefusal = (status: number, bodyText: string): string | null => {+ if (status !== 401) return null;+ let error: unknown;+ try {+ error = (JSON.parse(bodyText) as { error?: unknown }).error;+ } catch {+ return null;+ }+ if (typeof error !== 'string' || !error.startsWith('remote_access_')) return null;+ return (+ `The instance at ${BASE_URL} refused an unauthenticated read with \`${error}\`. `+ + 'This suite has no login step: Playwright opens a fresh browser context and its API context '+ + 'keeps a separate cookie jar, so a session in your own browser is not carried into the run. '+ + 'Point it at an endpoint that serves without a remote-access login \u2014 loopback, or the VM\'s '+ + 'own host:port on a network you trust \u2014 rather than at a tunnel fronted by one.'+ );+};++export class HubApi {+ private token: string | null = null;+ private readonly request: APIRequestContext;++ constructor(request: APIRequestContext) {+ this.request = request;+ }++ private async csrf(): Promise<string> {+ if (this.token) return this.token;+ const response = await this.request.get('/api/csrf-token');+ if (!response.ok()) throw new Error(`csrf-token ${response.status()}`);+ const payload = (await response.json()) as { csrf_token?: string };+ if (!payload.csrf_token) throw new Error('csrf-token response carried no token');+ this.token = payload.csrf_token;+ return this.token;+ }++ /**+ * GET returning the parsed body, and THROWING on any non-2xx.+ *+ * The throw is the point. These reads feed the precondition helpers, and an+ * earlier version collapsed every failure to `null` — so a 401, a 500, or a+ * `VIBE_E2E_BASE_URL` aimed at the wrong server all arrived as+ * `modelHubEnabled() === false` and `runtime() === null`, which the helpers+ * correctly treat as "this instance does not have the feature" and skip. A+ * broken run then reported itself as a clean one. An absent capability and an+ * unreachable API are different facts and are no longer spelled the same way.+ */+ async read<T>(path: string): Promise<T> {+ const response = await this.request.get(path);+ if (!response.ok()) {+ const text = await response.text();+ const refusal = remoteAuthRefusal(response.status(), text);+ if (refusal) throw new Error(refusal);+ throw new Error(+ `GET ${path} → ${response.status()} ${response.statusText()}. `+ + `This is the instance at ${BASE_URL} failing a read, not a missing capability: `+ + `${text.slice(0, 300)}`,+ );+ }+ return (await response.json()) as T;+ }++ private async mutate(+ method: 'post' | 'patch' | 'delete' | 'put',+ path: string,+ body?: unknown,+ ): Promise<{ ok: boolean; status: number; body: unknown }> {+ const response = await this.request[method](path, {+ headers: {+ 'X-Vibe-CSRF-Token': await this.csrf(),+ 'Content-Type': 'application/json',+ // A browser stamps `Origin` on every mutating fetch and the server+ // refuses one without it. Playwright's API context does not, so the+ // header is supplied here rather than discovered as a 403 later.+ Origin: BASE_URL,+ },+ ...(body === undefined ? {} : { data: body }),+ });+ let parsed: unknown = null;+ try {+ parsed = await response.json();+ } catch {+ parsed = null;+ }+ return { ok: response.ok(), status: response.status(), body: parsed };+ }++ /**+ * The same projection the browser reads: availability is the backend's to+ * declare, and `GET /api/config` is where it declares it.+ *+ * `/api/config` answers on every instance, capability on or off, so a failure+ * here is never "the feature is missing" — it is the read itself failing, and+ * `read` throws it.+ */+ async capabilities(): Promise<Capabilities> {+ return (await this.read<{ capabilities?: Capabilities }>('/api/config')).capabilities ?? {};+ }++ async modelHubEnabled(): Promise<boolean> {+ return (await this.capabilities()).model_hub?.enabled === true;+ }++ async sources(): Promise<Source[]> {+ return (await this.read<{ sources: Source[] }>('/api/models/sources')).sources ?? [];+ }++ async agents(): Promise<Agent[]> {+ return (await this.read<{ agents: Agent[] }>('/api/models/agents')).agents ?? [];+ }++ /** `null` here means the payload carried no `runtime` — an answered read with+ * nothing installed to describe, not a read that failed. */+ async runtime(): Promise<Runtime | null> {+ return (await this.read<{ runtime?: Runtime }>('/api/models/runtime/status')).runtime ?? null;+ }++ /**+ * Starts the gateway runtime, THROWING when the instance refuses.+ *+ * Named rather than toggled, and reached from `restoreRuntimeRunning`: the+ * caller is teardown, which asks for this precisely when the state it just+ * read may be wrong, and a start is the one request that means the same thing+ * whatever the instance currently believes about itself.+ */+ async startRuntime(): Promise<void> {+ const result = await this.mutate('post', '/api/models/runtime/start');+ if (!result.ok) {+ throw new Error(+ `Starting the gateway runtime failed (${result.status}): ${JSON.stringify(result.body)}.`,+ );+ }+ }++ /**+ * THROWS when the instance refuses the switch, rather than resolving over a+ * non-2xx answer.+ *+ * Both callers are teardown-adjacent (the gateway fixture putting a backend+ * back to direct, A3 un-arranging its blocked stop), so a swallowed failure+ * here reports a clean run while leaving the instance in Gateway mode — the+ * next spec inherits a shape it did not arrange and skips over a surface it+ * was supposed to check. The dirty state is named where it was made.+ */+ async setAgentMode(backend: string, mode: 'hub' | 'direct'): Promise<void> {+ const result = await this.mutate('patch', `/api/models/agents/${backend}/mode`, { mode });+ if (!result.ok) {+ throw new Error(+ `Switching backend ${backend} to ${mode} mode failed (${result.status}): `+ + `${JSON.stringify(result.body)}. The instance may still hold the previous mode.`,+ );+ }+ }++ async chains(backend: string): Promise<AgentChain[]> {+ return (await this.read<{ chains: AgentChain[] }>(`/api/models/agents/${backend}/chains`)).chains ?? [];+ }++ /** Replaces one model's chain outright. Used to arrange the preconditions a+ * guard scenario needs — a source that supplies a live route cannot be+ * removed without the guard, which is the whole point of the scenario. */+ async putAgentChain(backend: string, model: string, hops: RouteHop[]): Promise<boolean> {+ const path = `/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`;+ const first = await this.mutate('put', path, { hops });+ if (first.ok) return true;+ const forced = await this.mutate('put', path, {+ hops,+ force: true,+ ...refusedPlan(first.body),+ });+ return forced.ok;+ }++ /**+ * Runs the backend's dry run down its own chain, and reports what the far end+ * said.+ *+ * This is the only way to make a source's CREDENTIAL fail from outside the+ * product: `POST …/refresh` re-reads the model list, which an upstream that+ * rejects completions still serves, so a refetch leaves the source healthy.+ * Only a real request through the chain reaches `_probe_failure`, and only+ * that writes `needs_action.credential_revoked` — the one state in which a+ * source offers to have its key replaced.+ *+ * Returns `null` when the route has no candidate to try — the chain is empty,+ * cooling, or interrupted by the very failure a previous probe recorded. That+ * is a `409 probe_no_candidate` and carries no verdict, so a caller waiting on+ * a state change must read the SOURCE and use the probe only to drive it.+ */+ async probeAgent(backend: string, model: string): Promise<Probe | null> {+ const result = await this.mutate('post', `/api/models/agents/${backend}/probe`, { model });+ return (result.body as { probe?: Probe } | null)?.probe ?? null;+ }++ /**+ * Creates an api_key source directly, for specs whose subject is what happens+ * AFTER a source exists. `display_name` carries the suite prefix so teardown+ * can find it even if the spec died halfway through.+ *+ * Returns `null` when the instance refused. Callers reach this through+ * `requireSource`, which FAILS on that null: by the time a spec asks, the mock+ * has already answered its own control plane, so a refusal is the product+ * refusing a healthy upstream — not a missing precondition (§5a).+ */+ async createApiKeySource(+ displayName: string,+ baseUrl: string,+ key = 'e2e-key',+ ): Promise<Source | null> {+ const created = await this.mutate('post', '/api/models/sources', {+ kind: 'api_key',+ vendor: 'custom',+ display_name: displayName,+ base_url: baseUrl,+ key,+ accept_unavailable_inventory: true,+ });+ if (!created.ok) return null;+ const body = created.body as { source?: Source } & Partial<Source>;+ return (body?.source ?? (body as Source)) ?? null;+ }++ /**+ * Removes a source, forcing past the route guard when there is one, and+ * THROWS if it is still there afterwards.+ *+ * The forced attempt's result used to be discarded, which made teardown+ * unfalsifiable: a stale guard echo, an engine failure, or a 500 all left the+ * source and its route state behind while cleanup reported success, and the+ * next spec inherited it as a mysterious precondition. A cleanup that cannot+ * say whether it cleaned is worse than none, because it is believed.+ *+ * A 404 is success, not failure: the postcondition is that the source is+ * gone, and one already deleted by a suite sweep satisfies it.+ */+ async deleteSource(id: string): Promise<void> {+ const path = `/api/models/sources/${encodeURIComponent(id)}`;+ const first = await this.mutate('delete', path);+ if (first.ok || first.status === 404) return;+ // A source that still supplies a route is refused until the caller echoes+ // the server's own plan back. Teardown is exactly the caller that means it.+ const forced = await this.mutate('delete', `${path}?force=true`, refusedPlan(first.body));+ if (forced.ok || forced.status === 404) return;+ throw new Error(+ `Could not delete source ${id}: first attempt ${first.status}, forced attempt `+ + `${forced.status} ${JSON.stringify(forced.body)}. It is still on the instance, and every `+ + 'spec after this one inherits it.',+ );+ }++ /**+ * Removes every source this suite created, whatever spec left it behind.+ *+ * Returns quietly when the capability is off — a hub-disabled instance has no+ * `/api/models/*` to sweep, and that is the one case where nothing to clean is+ * a fact about the instance rather than a failed read.+ */+ async removeSuiteSources(): Promise<void> {+ if (!(await this.modelHubEnabled())) return;+ // Every match is attempted before any failure is raised: the gateway+ // fixture leaves two sources behind, and a first delete that throws used+ // to strand the second on the shared instance — poisoning the source+ // ordering and routing preconditions of every later spec — alongside the+ // failure that already stopped this one.+ const failures: string[] = [];+ for (const source of await this.sources()) {+ if (!isSuiteSource(source)) continue;+ try {+ await this.deleteSource(source.id);+ } catch (error) {+ failures.push(`${source.id}: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ if (failures.length) {+ throw new Error(+ `Suite-source sweep left ${failures.length} source(s) on the instance:\n `+ + failures.join('\n '),+ );+ }+ }+}diff --git a/ui/e2e/support/copy.ts b/ui/e2e/support/copy.tsnew file mode 100644index 000000000..0c4b6e96c--- /dev/null+++ b/ui/e2e/support/copy.ts@@ -0,0 +1,71 @@+// The suite's selector vocabulary.+//+// Model Hub product code carries no `data-testid`, and this lane may not add+// one. What it does carry is user-visible copy: every control is reachable by+// its accessible name, and every name comes from `src/i18n/en.json`. Reading+// the shipped bundle instead of pasting the strings means a copy change breaks+// the test at the key, where the diff is legible, rather than at a locator that+// silently stops matching.+//+// The bundle is not plain nesting: leaves may carry dots of their own+// (`addKey.field.apiKey` is a string AND `addKey.field.apiKey.reveal` exists+// beside it), which is what i18next's progressive lookup allows. `resolve`+// reproduces that rule — longest literal segment first, then descend — so a key+// resolves here exactly as it does in the browser.+import { readFileSync } from 'node:fs';++type Bundle = { [key: string]: string | Bundle };+type Vars = Record<string, string | number>;++const bundle = JSON.parse(+ readFileSync(new URL('../../src/i18n/en.json', import.meta.url), 'utf8'),+) as Bundle;++const resolve = (node: string | Bundle | undefined, segments: string[]): string | undefined => {+ if (node === undefined) return undefined;+ if (segments.length === 0) return typeof node === 'string' ? node : undefined;+ if (typeof node === 'string') return undefined;+ for (let take = segments.length; take >= 1; take -= 1) {+ const found = resolve(node[segments.slice(0, take).join('.')], segments.slice(take));+ if (found !== undefined) return found;+ }+ return undefined;+};++const interpolate = (template: string, vars?: Vars): string =>+ template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (whole, name: string) =>+ vars && name in vars ? String(vars[name]) : whole);++/** The rendered string for `key`, or `null` when the bundle has no such key. */+export const copyOrNull = (key: string, vars?: Vars): string | null => {+ const count = vars?.count;+ const candidates = typeof count === 'number'+ ? [`${key}_${new Intl.PluralRules('en-US').select(count)}`, key]+ : [key];+ for (const candidate of candidates) {+ const template = resolve(bundle, candidate.split('.'));+ if (template !== undefined) return interpolate(template, vars);+ }+ return null;+};++/**+ * The rendered string for `key`. Throws when the key is missing, because a+ * locator built from `undefined` matches nothing and reports "element not+ * found" — an absent key has to fail as an absent key.+ */+export const copy = (key: string, vars?: Vars): string => {+ const text = copyOrNull(key, vars);+ if (text === null) throw new Error(`i18n key missing from src/i18n/en.json: ${key}`);+ return text;+};++/** Whether the shipped bundle defines `key`. Used by the copy-hygiene checks. */+export const hasCopy = (key: string): boolean => copyOrNull(key) !== null;++/** `settings.models.` prefix, since every key this suite reads lives under it. */+export const hub = (key: string, vars?: Vars): string => copy(`settings.models.${key}`, vars);++/** Nullable form of {@link hub}. */+export const hubOrNull = (key: string, vars?: Vars): string | null =>+ copyOrNull(`settings.models.${key}`, vars);diff --git a/ui/e2e/support/env.ts b/ui/e2e/support/env.tsnew file mode 100644index 000000000..588945136--- /dev/null+++ b/ui/e2e/support/env.ts@@ -0,0 +1,132 @@+// The frozen environment vocabulary (test plan §5a) and the reasons a spec+// skips. A skip message names what to start and where the instructions are, so+// a skipped run is actionable rather than mysterious.++const trimSlash = (value: string): string => value.replace(/\/+$/, '');++const NO_BASE_URL =+ 'VIBE_E2E_BASE_URL is not set, and this suite has no default. It creates and '+ + 'deletes sources, rewrites route chains, flips agent modes and stops the gateway '+ + 'on whatever instance it is pointed at, so the instance has to be named on purpose. '+ + 'Point it at a hermetic instance of your own — never at the vibe service you use — '+ + 'and name that same instance in VIBE_E2E_DESTRUCTIVE_TARGET. '+ + 'See ui/e2e/README.md § "Against a local hermetic instance".';++/** The name of the consent variable, quoted often enough below to be worth one+ * spelling. */+const CONSENT = 'VIBE_E2E_DESTRUCTIVE_TARGET';++/** The port the packaged service listens on unless its operator moved it+ * (`setup_port`, config/v2_config.py). */+const PACKAGED_PORT = '5123';++const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]', '::1', '0.0.0.0']);++/**+ * The one target refused outright, and the only one the suite can recognize+ * without being told: the packaged default ON THIS MACHINE.+ *+ * Scoped to loopback deliberately. `5123` on this host is the port the `vibe`+ * the operator uses is listening on right now; the same number on someone+ * else's host is just a port, and refusing it would be this file guessing about+ * a machine it cannot see — which is the failure mode the rest of the check+ * exists to avoid.+ */+const isPackagedLocalService = (url: URL): boolean =>+ LOOPBACK.has(url.hostname) && url.port === PACKAGED_PORT;++const REFUSED_PACKAGED_PORT =+ `The target is loopback port ${PACKAGED_PORT}, which is where the packaged service listens `+ + 'unless its operator moved it — so it is almost certainly the vibe you use. This suite '+ + 'force-deletes sources, rewrites route chains, flips agent modes and stops the gateway, '+ + 'and no consent makes that address acceptable: the likeliest way to reach it is pasting '+ + 'the URL of the UI you have open. Start the hermetic instance on any other port. '+ + 'See ui/e2e/README.md § "Against a local hermetic instance".';++const notAUrl = (name: string, raw: string): string =>+ `${name} is not an http(s) URL: ${raw}.`;++/** One spelling for both variables, so `http://host:5199/` and `http://host:5199`+ * are the same target rather than a mismatch the operator has to debug. */+const normalize = (raw: string): string | null => {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return null;+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;+ return trimSlash(url.toString());+};++const withoutConsent = (target: string, state: string): string =>+ `${CONSENT} ${state}, and this suite runs only against the instance it names. `+ + `Set ${CONSENT}=${target} to state that what is at ${target} — its sources, its route `+ + 'chains, its agent modes, its gateway — is disposable. Nothing a running instance '+ + 'reports says whether it is; a hermetic one and the one you work on serve the same '+ + 'API, so the only party who can answer is you. The variable names the target rather '+ + 'than being a flag so that an answer given for one instance does not quietly carry '+ + 'over to the next one VIBE_E2E_BASE_URL is pointed at. '+ + 'See ui/e2e/README.md § "Against a local hermetic instance".';++/**+ * The instance under test, admitted only once it has been named twice.+ *+ * `VIBE_E2E_BASE_URL` deliberately has no fallback: a default of+ * `http://127.0.0.1:5123` is where a developer's real `vibe` listens, so an+ * accidental `npm run e2e` would mutate production state — and a README warning+ * does not run. But a required variable only proves the operator typed A url,+ * not that they typed a disposable one, and this suite is destructive on every+ * axis the Model Hub has. So the target must also be consented to by name, and+ * the one address that is recognizably the local service is refused outright.+ */+export const BASE_URL = ((): string => {+ const raw = process.env.VIBE_E2E_BASE_URL?.trim();+ if (!raw) throw new Error(NO_BASE_URL);+ const target = normalize(raw);+ if (!target) throw new Error(notAUrl('VIBE_E2E_BASE_URL', raw));+ if (isPackagedLocalService(new URL(target))) throw new Error(REFUSED_PACKAGED_PORT);+ const declared = process.env[CONSENT]?.trim();+ const consented = declared ? normalize(declared) : null;+ if (consented !== target) {+ throw new Error(+ withoutConsent(+ target,+ !declared ? 'is not set' : consented ? `names ${consented}` : `is ${declared}, which is not an http(s) URL`,+ ),+ );+ }+ return target;+})();++/**+ * The mock upstream provider's origin. This lane reaches it ONLY over HTTP —+ * the Python module is the pytest lane's and is never imported here. Specs that+ * need a controllable upstream skip when it is absent.+ */+export const MOCK_UPSTREAM_URL = process.env.VIBE_E2E_MOCK_UPSTREAM_URL+ ? trimSlash(process.env.VIBE_E2E_MOCK_UPSTREAM_URL)+ : null;++export const NO_MOCK_UPSTREAM =+ 'VIBE_E2E_MOCK_UPSTREAM_URL is not set, so no controllable upstream is available. '+ + 'The driver that serves this contract is the pytest lane\'s '+ + '(tests/e2e/drivers/mock_llm_upstream.py) and does not ship in this PR; any server '+ + 'implementing the §5a control plane will do. See ui/e2e/README.md § "The mock upstream".';++/**+ * A source's Base URL as typed into the dialog. The mock serves `/v1/models`,+ * `/v1/messages`, `/v1/responses` and `/v1/chat/completions`, and the dialog's+ * own hint says a bare host resolves against the standard `/v1` path — so the+ * bare origin is what a user would type.+ */+export const mockBaseUrl = (): string => {+ if (!MOCK_UPSTREAM_URL) throw new Error(NO_MOCK_UPSTREAM);+ return MOCK_UPSTREAM_URL;+};++/** Display-name prefix every source this suite creates carries, so cleanup can+ * find its own leftovers without guessing at the operator's real sources.+ * Every create path uses it — including the ones that expect to FAIL, because+ * a failure path that accidentally commits still has to be sweepable. */+export const E2E_SOURCE_PREFIX = 'e2e-playwright-';diff --git a/ui/e2e/support/fixtures.ts b/ui/e2e/support/fixtures.tsnew file mode 100644index 000000000..2c7c05363--- /dev/null+++ b/ui/e2e/support/fixtures.ts@@ -0,0 +1,124 @@+// Fixtures shared by every spec, plus the preconditions that decide whether a+// spec can run at all.+//+// The suite drives a live instance, so "can this run?" is a question about the+// instance, not about the code. A precondition that is not met produces a SKIP+// whose message says what to start — never a failure that looks like a bug in+// the product.+//+// The line is drawn where the plan draws it (§5a, discipline tightening): only+// an ENVIRONMENTAL fact may skip — the capability off, the mock absent, the+// runtime not running, no backend CLI installed, an instance whose shape means+// the scenario's surface does not exist. Once those have passed, anything that+// then goes wrong is the product going wrong, and it fails. A source the+// instance will not create, a mode switch that does not take, a forced route+// PUT that is refused: each of those used to skip, and each of them was a+// product failure wearing a missing precondition's clothes.+import { type Locator, test as base, expect } from '@playwright/test';++import { HubApi, type Source } from './api';+import { NO_MOCK_UPSTREAM } from './env';+import { ModelHubPage } from './hub';+import { MockUpstream } from './mock';++type HubFixtures = {+ api: HubApi;+ mock: MockUpstream;+ hub: ModelHubPage;+};++// Playwright calls the second fixture argument `use`; it is positional, so the+// name is ours to pick. It is `provide` here because this repo's ESLint runs+// react-hooks over every `.ts` file, and a bare call to `use(...)` reads as+// React 19's `use()` hook being called outside a component. Suppressing that+// would be suppressing a rule that is doing its job on a name we chose.+export const test = base.extend<HubFixtures>({+ api: async ({ request }, provide) => {+ await provide(new HubApi(request));+ },+ mock: async ({ request }, provide) => {+ await provide(new MockUpstream(request));+ },+ hub: async ({ page }, provide) => {+ await provide(new ModelHubPage(page));+ },+});++export { expect };++/** Skips unless the instance actually has the Model Hub capability on. */+export const requireModelHub = async (api: HubApi): Promise<void> => {+ test.skip(+ !(await api.modelHubEnabled()),+ 'Model Hub is disabled on this instance. Start it with VIBE_MODEL_HUB_ENABLED=1 (see ui/e2e/README.md).',+ );+};++/** Skips unless a controllable upstream is configured AND answering. */+export const requireMockUpstream = async (mock: MockUpstream): Promise<void> => {+ test.skip(!(await mock.reachable()), NO_MOCK_UPSTREAM);+};++/**+ * The product's own running predicate, not a stricter one of the suite's.+ *+ * `runtimeIsRunning` in `src/components/settings/models/runtimeLifecycle.ts`+ * accepts `degraded` alongside `ok`, and it has to: a gateway serving in its+ * supported degraded state renders the full surface. Insisting on exactly `ok`+ * here reported such an instance as switched off and skipped every source,+ * routing, guard, usage, and logs spec — nearly the whole suite, silently.+ */+export const runtimeIsRunning = (health: string | undefined): boolean =>+ health === 'ok' || health === 'degraded';++/** Skips unless the gateway runtime is installed and running — the precondition+ * for anything that adds a source or serves a route. */+export const requireRuntimeRunning = async (api: HubApi): Promise<void> => {+ const runtime = await api.runtime();+ test.skip(+ !runtimeIsRunning(runtime?.status?.health),+ 'The gateway runtime is not running on this instance. Turn the model gateway on first (see ui/e2e/README.md).',+ );+};++/**+ * Creates a source a spec needs before it can begin, and FAILS if the instance+ * will not make one.+ *+ * Deliberately not a skip. By the time this runs, every environmental+ * precondition has passed — the capability is on, the runtime is up, and the+ * mock has answered its own control plane — so an instance that then refuses a+ * source it was handed a healthy upstream for has done something wrong, and+ * saying so is what the suite is for.+ */+export const requireSource = async (+ api: HubApi,+ displayName: string,+ baseUrl: string,+): Promise<Source> => {+ const source = await api.createApiKeySource(displayName, baseUrl);+ expect(source, `the instance refused to create the precondition source ${displayName}`).not.toBeNull();+ return source!;+};++/**+ * Asserts that `locator` IS on the page and does NOT say `text`.+ *+ * Both halves, always, because the second is meaningless without the first: a+ * negated text assertion is satisfied by an element that says something else AND+ * by an element that is not there at all, and those are opposite verdicts. "The+ * surviving model is not re-announced as new" passes just as green when the+ * refetch dropped the survivor along with the model it was supposed to drop —+ * the row is gone, so it contains nothing, so it does not contain "New".+ *+ * Kept as one call rather than as a convention to write two, so that the+ * presence cannot be the line that gets left out.+ */+export const expectVisibleWithout = async (+ locator: Locator,+ text: string | RegExp,+ options?: { timeout?: number },+): Promise<void> => {+ await expect(locator).toBeVisible(options);+ await expect(locator).not.toContainText(text, options);+};diff --git a/ui/e2e/support/gateway.ts b/ui/e2e/support/gateway.tsnew file mode 100644index 000000000..786332829--- /dev/null+++ b/ui/e2e/support/gateway.ts@@ -0,0 +1,214 @@+// The two preconditions the Model Hub's own surfaces impose, as fixtures.+//+// `hubSurface` — the page a spec lands on is not a constant. `modelsSurfaceKind`+// sends `/settings/models` to the DIRECT HOME when every backend is on Direct+// *and* the instance holds no sources, and that home has no source list and no+// Add API key button: its only control is "Switch to gateway". A machine's very+// first source arrives by adopting the gateway, which is C6-direct-home's+// subject. So every spec on this `test` gets one anchor source when the instance+// has none, and the anchor leaves with the test that needed it. Without it a+// suite passes its first spec, deletes its own source in teardown, and every+// later spec times out looking for a button that is no longer on the page.+//+// `gateway` — a backend in Gateway mode with sources of the suite's own to route+// through. Route rows, the priority button, and every supply guard exist only+// for a Gateway-mode backend. Arranging that by clicking would make each of+// those specs a mode-switch test as well, and would report the mode switch's+// failures under their names.+import type { Agent, Source } from './api';+import { routableModels, surfaceKind } from './api';+import { E2E_SOURCE_PREFIX, mockBaseUrl, NO_MOCK_UPSTREAM } from './env';+import { expect, requireModelHub, requireMockUpstream, requireRuntimeRunning, requireSource, test as base } from './fixtures';+import { anthropicInventory } from './mock';+import { restoreNativeSources } from './restore';++export type Gateway = {+ /** A backend that is in Gateway mode for the duration of the test. */+ backend: string;+ /** One model of that backend — the one its route rows are keyed by. */+ model: string;+ /** Two api_key sources this suite owns outright and may route through. */+ sources: Source[];+};++// `provide` rather than Playwright's usual `use` — see the note in fixtures.ts.+export const test = base.extend<{ hubSurface: void; gateway: Gateway }>({+ hubSurface: [+ async ({ api, mock }, provide, testInfo) => {+ // First, because this is an auto fixture: it runs before the suite's own+ // `beforeEach` guards, so it cannot lean on them. A disabled capability+ // turns every `/api/models/*` read below into the gate's 404 — which+ // `read()` (correctly) throws on — and reports a skip-with-reason as a+ // failure in every B, D, and G spec at once. The runtime and mock guards+ // are here for the same reason: the anchor below CREATES a source, which+ // a stopped runtime refuses, and a spec whose only problem is a+ // documented environmental precondition should skip, not fail.+ await requireModelHub(api);+ await requireRuntimeRunning(api);+ const sources = await api.sources();+ const agents = await api.agents();+ // The product's own condition, asked through the one declaration that+ // owns it: anything other than the gateway surface needs the anchor, and+ // BOTH direct forms do — an instance with no backend installed renders+ // the install prompt, which has no source list either.+ const directEmpty = surfaceKind(agents, sources) !== 'gateway';+ const anchorName = `${E2E_SOURCE_PREFIX}surface-anchor`;+ let anchor: Source | null = null;+ try {+ if (directEmpty) {+ testInfo.skip(!(await mock.reachable()), NO_MOCK_UPSTREAM);+ // A healthy baseline, because the previous test may have left the mock+ // rejecting everything — and an anchor that cannot be created would+ // report the last test's mock state as this test's missing precondition.+ await mock.configure({ auth: 'ok', protocol: 'anthropic', models_endpoint: 'ok' });+ anchor = await requireSource(api, anchorName, mockBaseUrl());+ }+ await provide();+ } finally {+ // By NAME, not only by the id a successful create returned: the server+ // persists the source before its response leaves, so a POST whose+ // response is lost rejects `requireSource` above — with the anchor+ // already on the instance and no id in hand. The prefix sweep catches+ // that path; the id delete covers the ordinary one without re-listing.+ if (anchor) {+ await api.deleteSource(anchor.id);+ } else if (directEmpty) {+ for (const source of await api.sources()) {+ if (source.display_name === anchorName) await api.deleteSource(source.id);+ }+ }+ }+ },+ { auto: true },+ ],++ gateway: async ({ api, mock }, provide, testInfo) => {+ // Same ordering rule as `hubSurface`: this fixture is initialized before+ // the suite's `beforeEach` guards run, so it owns its own preconditions.+ // Without the mock URL `configure` below throws, and without a running+ // runtime every source create is refused — both documented skip states,+ // not failures.+ await requireModelHub(api);+ await requireMockUpstream(mock);+ await requireRuntimeRunning(api);+ await mock.configure({+ auth: 'ok',+ protocol: 'anthropic',+ models_endpoint: 'ok',+ models: anthropicInventory(['e2e-route-1', 'e2e-route-2']),+ });+ // `requireSource`, not a skip: the mock has answered its control plane by+ // this point, so a refused source is the product refusing a healthy+ // upstream (§5a) — even though the fixture's own teardown still has to run.+ let created: Source[] = [];+ // From here on the instance has been changed, so every exit — including+ // the `skip`s below, which throw — has to go through the teardown. A skip+ // that returned early used to leave a backend in Gateway mode and two+ // sources behind for whatever ran next.+ let switched: string | null = null;+ // The Direct→Gateway switch is not mode-only on a machine whose CLI holds+ // a native login: `set_agent_mode` appends a `native_cli` subscription+ // source as part of the transition, and the prefix sweep below would leave+ // it — with its placement — on the instance for every later spec. The+ // snapshot is what separates that import from a native source the instance+ // already had; what it is NOT is the test of whether a source is native.+ let sourcesBeforeSwitch: Set<string> | null = null;+ try {+ created = [+ await requireSource(api, `${E2E_SOURCE_PREFIX}route-a`, mockBaseUrl()),+ await requireSource(api, `${E2E_SOURCE_PREFIX}route-b`, mockBaseUrl()),+ ];++ const agents = await api.agents();+ // What this fixture owes its specs is a backend with a ROUTE to open, and+ // that is two facts, not one. The CLI has to be installed, because the+ // product's own surface filters uninstalled backends out+ // (`installedAgents`) and their route rows never render. And the backend+ // has to expose a model, because an `opencode` sitting in Gateway mode+ // with nothing ticked has an empty `model_supply` — so selecting on+ // installation alone would take that one as found and hand every B, D and+ // G spec a backend with no route, while an installed `claude` in Direct+ // mode next to it had a full builtin menu all along.+ const installed = agents.filter((agent: Agent) => agent.cli_present);+ const usable = installed.filter((agent: Agent) => routableModels(agent).length > 0);+ // Still preferred if it qualifies: switching a second backend would change+ // more of the instance than the test needs.+ const alreadyHub = usable.find((agent: Agent) => agent.mode === 'hub');+ const candidate = alreadyHub ?? usable[0];+ testInfo.skip(!installed.length, 'No agent backend is installed on this instance, so none can be put into Gateway mode.');+ // Its own skip, and its own sentence: "installed but with an empty menu"+ // is a different thing to fix than "nothing installed", and a spec that+ // reported the first as the second would send its reader to reinstall a+ // backend that is already there.+ testInfo.skip(+ !candidate,+ `No installed backend (${installed.map((agent: Agent) => agent.backend).join(', ')}) exposes a model to route. `+ + 'Tick at least one model in a backend\'s model menu, or install a backend whose menu is builtin.',+ );+ if (!alreadyHub) {+ sourcesBeforeSwitch = new Set((await api.sources()).map((source) => source.id));+ // Recorded BEFORE the PATCH is awaited, not after it succeeds: the+ // server commits the mode before the response leaves, so a response+ // lost to a timeout or disconnect rejects that await with the instance+ // already mutated. A marker assigned after the await would skip the+ // Direct restore on exactly that path.+ switched = candidate!.backend;+ await api.setAgentMode(candidate!.backend, 'hub');+ }++ const live = (await api.agents()).find((agent: Agent) => agent.backend === candidate!.backend);+ expect(+ live?.mode,+ `Backend ${candidate!.backend} did not take the Gateway-mode switch the instance accepted.`,+ ).toBe('hub');+ // The backend's currently selected model when it is one of the routable+ // ones: a guard that interrupts the model the backend actually runs is the+ // interruption the product is warning about, and B7 reads that warning.+ const supply = live?.model_supply ?? [];+ const model =+ supply.find((entry) => entry.model_id === live?.selected_model_id)?.model_id+ ?? supply[0]?.model_id;+ // An assertion, not a skip, and it stays one now that the candidate was+ // chosen for having a menu: an empty supply here means the backend's menu+ // said it had models and the Gateway-mode projection of that same menu+ // says it has none. That is the product contradicting itself, not a+ // precondition this instance failed to meet.+ expect(+ model,+ `Backend ${candidate!.backend} offered ${routableModels(candidate!).join(', ')} before the `+ + 'Gateway-mode switch, but lists no models after it, so it has no route to open.',+ ).toBeDefined();++ await provide({+ backend: candidate!.backend,+ model: model!,+ sources: created,+ });+ } finally {+ // Put the instance back as it was found: the mode only if this fixture+ // changed it, and always this suite's own sources. Two nested blocks,+ // because the two restorations are independent promises: a mode PUT that+ // throws must not skip the source sweep, or the two route sources+ // outlive the spec and every later surface check inherits them.+ try {+ if (switched) await api.setAgentMode(switched, 'direct');+ } finally {+ // The transition-imported native source (if the switch made one) goes+ // before the prefix sweep, because it does not carry the prefix and the+ // sweep cannot see it. `restoreNativeSources` owns which source that is+ // — by channel, not by "new and unfamiliar" — so this site and A3+ // cannot answer the question differently.+ // Its own finally: a native deletion that still throws must not skip+ // the prefix sweep, or the suite's own route sources outlive the spec+ // alongside the failure that already stopped it.+ try {+ if (sourcesBeforeSwitch) await restoreNativeSources(api, sourcesBeforeSwitch);+ } finally {+ await api.removeSuiteSources();+ }+ }+ }+ },+});++export { expect } from './fixtures';diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.tsnew file mode 100644index 000000000..80083c4b5--- /dev/null+++ b/ui/e2e/support/hub.ts@@ -0,0 +1,252 @@+// Page object for `/settings/models`.+//+// Locator policy, since it is the whole reason this file exists: prefer ARIA+// role + accessible name (the name always read through `copy.ts`, never pasted),+// then the product's own `data-*` hooks (`data-source-id`, `data-route-backend`,+// `data-manage-kind`), and only then a `model-hub-*` class — which is used to+// NAME A SURFACE, never to assert one. Two dialogs can be mounted at once (a+// panel and the guard it raises), and `getByRole('dialog')` cannot tell them+// apart; the class says which one, and every assertion inside it still goes+// through role and copy.+//+// Every attribute selector is built by `attr` below, never by interpolation:+// some of the values are the operator's, not ours.+//+// No `data-testid` is added anywhere: this lane makes zero product-code changes.+import type { Locator, Page } from '@playwright/test';++import { hub } from './copy';++/**+ * One attribute selector, with the value escaped as the CSS string it is.+ *+ * The values here are not all ours. A route row is keyed by a MODEL ID, and for+ * an `open` menu that id is whatever the operator ticked — `ModelHubMenuConfig`+ * takes arbitrary non-credential strings. Pasted into a quoted attribute+ * selector, a `"` closes the string early and the locator either throws as+ * invalid syntax or, worse, still parses and matches something else: a green+ * assertion about a row that is not the row.+ *+ * Escaping per CSS Syntax §4.3.7 — backslash and quote by backslash, control+ * characters by hex — rather than rejecting those ids, because refusing to look+ * at a model the product accepted would be the suite choosing what the product+ * is allowed to contain.+ *+ * A per-character walk rather than a character-class replace: the class it+ * would need is the control characters themselves, and a regex naming them is+ * the one shape `no-control-regex` exists to stop. Suppressing that rule to+ * write the escape would leave the codebase carrying a suppression whose+ * justification is one line long and whose reader has to reconstruct it.+ */+const attr = (name: string, value: string): string => {+ const escaped = Array.from(value, (ch) => {+ const code = ch.codePointAt(0)!;+ if (code <= 0x1f || code === 0x7f) return `\\${code.toString(16)} `;+ return ch === '"' || ch === '\\' ? `\\${ch}` : ch;+ }).join('');+ return `[${name}="${escaped}"]`;+};++export class ModelHubPage {+ readonly page: Page;++ constructor(page: Page) {+ this.page = page;+ }++ async goto(): Promise<void> {+ await this.page.goto('/settings/models');+ }++ /** The page shell. Present whenever the capability gate let the route render. */+ get shell(): Locator {+ return this.page.locator('.model-hub-shell');+ }++ get header(): Locator {+ return this.page.locator('.model-hub-shell-head');+ }++ /** The gateway on/off switch. Its accessible name IS the product's+ * explanation of why it is disabled, so specs read the name, not a tooltip. */+ get runtimeToggle(): Locator {+ return this.header.getByRole('switch');+ }++ async runtimeToggleLabel(): Promise<string> {+ return (await this.runtimeToggle.getAttribute('aria-label')) ?? '';+ }++ get runtimePill(): Locator {+ return this.header.locator('.model-hub-runtime-pill');+ }++ /** The body shown instead of the hub when the gateway is not configurable. */+ get closedState(): Locator {+ return this.page.locator('.model-hub-runtime-closed');+ }++ tab(id: 'hub' | 'usage' | 'logs'): Locator {+ return this.page.getByRole('tab', { name: hub(`shell.tab.${id}`) });+ }++ async openTab(id: 'hub' | 'usage' | 'logs'): Promise<void> {+ await this.tab(id).click();+ }++ /** The home a machine with no sources and every backend on Direct lands on,+ * instead of an empty gateway. */+ get directHome(): Locator {+ return this.page.locator('.model-hub-direct');+ }++ // --- Upstream sources -----------------------------------------------------++ get addApiKeyButton(): Locator {+ return this.page.getByRole('button', { name: hub('upstream.addApiKey') });+ }++ get addSubscriptionButton(): Locator {+ return this.page.getByRole('button', { name: hub('upstream.addSubscription') });+ }++ sourceRow(sourceId: string): Locator {+ return this.page.locator(attr('data-source-id', sourceId));+ }++ sourceRowByName(displayName: string): Locator {+ return this.page.locator('[data-source-id]').filter({ hasText: displayName });+ }++ async openSource(sourceId: string): Promise<void> {+ await this.sourceRow(sourceId).click();+ }++ // --- Gateway routes -------------------------------------------------------++ agentCard(backend: string): Locator {+ return this.page.locator(attr('data-agent-backend', backend));+ }++ routeRow(backend: string, model: string): Locator {+ return this.page.locator(attr('data-route-backend', backend) + attr('data-route-model', model));+ }++ /** The card collapses its model list, so a spec that just needs *a* route+ * takes the first row the card actually shows rather than naming a model+ * that may be hidden behind "N more models". */+ firstRouteRow(backend: string): Locator {+ return this.agentCard(backend).locator('[data-route-model]').first();+ }++ adjustPriorityButton(backend: string): Locator {+ return this.agentCard(backend).getByRole('button', { name: hub('gateway.sourceOrder') });+ }++ // --- Dialogs --------------------------------------------------------------++ /** Add / replace API key. Both modes render the same surface. */+ get addKeyDialog(): Locator {+ return this.page.locator('.model-hub-add-key-dialog');+ }++ get sourceDetailDialog(): Locator {+ return this.page.locator('.model-hub-source-dialog');+ }++ /** The `…` menu on the open source panel, and the two actions behind it. */+ manageMenuTrigger(sourceName: string): Locator {+ return this.sourceDetailDialog.getByRole('button', {+ name: hub('sourceDetail.manage.label', { source: sourceName }),+ exact: true,+ });+ }++ manageItem(kind: 'edit_source' | 'delete_source'): Locator {+ return this.page.locator(attr('data-manage-kind', kind));+ }++ /** One row of the source's model table. The rows carry no id attribute, but+ * the id cell carries `title={model.id}` — an exact match on that is what+ * keeps `claude-3-5` from also selecting `claude-3-5-haiku`. */+ modelRow(modelId: string): Locator {+ return this.sourceDetailDialog+ .locator('.model-hub-source-table-row')+ .filter({ has: this.page.getByTitle(modelId, { exact: true }) });+ }++ /** The pending "add a model by hand" row, before it is committed. */+ get manualDraftRow(): Locator {+ return this.sourceDetailDialog.locator('[data-manual-model-draft]');+ }++ /**+ * The confirm-before-destroy dialog raised from the source panel.+ *+ * The edit dialog shares this class — same surface, same chrome — so a spec+ * that means one of them says which by title. `guardDialog` alone is right+ * only where at most one can be mounted.+ */+ get guardDialog(): Locator {+ return this.page.locator('.model-hub-guard-dialog');+ }++ dialogTitled(title: string): Locator {+ return this.page.locator('.model-hub-guard-dialog').filter({ hasText: title });+ }++ /** The after-the-fact report of a committed source mutation. It shares the+ * guard's chrome — deliberately, since it restates the same facts — but it+ * carries the action it is reporting, which is what tells them apart. */+ mutationReport(action: 'edit' | 'delete'): Locator {+ return this.page.locator(attr('data-source-mutation-report', action));+ }++ get routeDialog(): Locator {+ return this.page.locator('.model-hub-route-dialog');+ }++ get orderDrawer(): Locator {+ return this.page.locator('.model-hub-order-drawer');+ }++ /** Install / adopt the gateway component. It shares the adopt dialog surface+ * with the subscription flow, so the class alone is not enough to name it —+ * the title is what distinguishes the two. */+ get installDialog(): Locator {+ return this.page.locator('.model-hub-adopt-dialog').filter({ hasText: hub('install.title') });+ }+}++/**+ * The button a user would READ as `name`, inside a surface that also has an+ * icon-only close carrying the same accessible name.+ *+ * Every Model Hub surface with a footer does this: the header X takes the+ * footer action's own label as its `aria-label` — `Cancel` on the route dialog+ * and the priority drawer, `Done` on the mutation report. That is right for a+ * screen reader, since the X genuinely does perform that action, and it means a+ * name alone matches two elements, which Playwright refuses in strict mode. The+ * visible one is the one whose own text is the label; the X has none.+ */+export const labelledButton = (scope: Locator, name: string): Locator =>+ scope.getByRole('button', { name, exact: true }).filter({ hasText: name });++/**+ * Fills the add-API-key form. `name` is optional in the product and optional+ * here for the same reason: a spec that does not care about the label should+ * not have to invent one.+ */+export const fillApiKeyForm = async (+ dialog: Locator,+ values: { name?: string; baseUrl: string; apiKey: string; protocol?: string },+): Promise<void> => {+ if (values.name !== undefined) {+ await dialog.getByLabel(hub('addKey.field.name'), { exact: true }).fill(values.name);+ }+ if (values.protocol) {+ await dialog.getByRole('button', { name: values.protocol, exact: true }).click();+ }+ await dialog.getByLabel(hub('addKey.field.baseUrl'), { exact: true }).fill(values.baseUrl);+ await dialog.getByLabel(hub('addKey.field.apiKey'), { exact: true }).fill(values.apiKey);+};diff --git a/ui/e2e/support/mock.ts b/ui/e2e/support/mock.tsnew file mode 100644index 000000000..b523ed684--- /dev/null+++ b/ui/e2e/support/mock.ts@@ -0,0 +1,89 @@+// The mock upstream provider's control plane, reached ONLY over HTTP.+//+// `tests/e2e/drivers/mock_llm_upstream.py` belongs to the pytest lane; this+// lane never imports it. The contract used here is the frozen one from test+// plan §5a: `POST /__control/config` sets behavior, `GET /__control/requests`+// returns `{"requests": [...]}`, `DELETE /__control/requests` resets.+import type { APIRequestContext } from '@playwright/test';++import { MOCK_UPSTREAM_URL } from './env';++export type MockAuthMode = 'ok' | '401' | '403_banned' | '402' | '429' | 'quota_message' | '5xx';+export type MockProtocol = 'anthropic' | 'openai_responses' | 'openai_chat';+export type MockModelsEndpoint = 'ok' | 'http_404' | 'http_500' | 'timeout' | 'malformed_json';++export type MockConfig = {+ auth?: MockAuthMode;+ stream?: 'healthy' | 'interrupt_after_first_output';+ models?: unknown[];+ protocol?: MockProtocol;+ models_endpoint?: MockModelsEndpoint;+};++export type CapturedRequest = {+ method: string;+ path: string;+ headers?: Record<string, string>;+ body?: unknown;+};++export class MockUpstream {+ private readonly request: APIRequestContext;++ constructor(request: APIRequestContext) {+ this.request = request;+ }++ private url(path: string): string {+ if (!MOCK_UPSTREAM_URL) throw new Error('mock upstream URL is not configured');+ return `${MOCK_UPSTREAM_URL}${path}`;+ }++ async configure(config: MockConfig): Promise<void> {+ const response = await this.request.post(this.url('/__control/config'), { data: config });+ if (!response.ok()) {+ throw new Error(`mock upstream refused config (${response.status()}): ${await response.text()}`);+ }+ }++ async resetRequests(): Promise<void> {+ const response = await this.request.delete(this.url('/__control/requests'));+ // A refused reset leaves the previous attempt's history in place, and B6+ // would then read a stale `/v1/` hit as this attempt's — suppressing the+ // #1818 classification the settle is trying to establish. Failing here+ // names the mock as the problem, before any verdict is read from it.+ if (!response.ok()) {+ throw new Error(`mock upstream refused request-log reset (${response.status()}): ${await response.text()}`);+ }+ }++ async requests(): Promise<CapturedRequest[]> {+ const response = await this.request.get(this.url('/__control/requests'));+ if (!response.ok()) throw new Error(`mock upstream request log unavailable (${response.status()})`);+ const payload = (await response.json()) as { requests?: CapturedRequest[] };+ return payload.requests ?? [];+ }++ /** True when the mock answers its control plane — the liveness probe a spec+ * runs before trusting `VIBE_E2E_MOCK_UPSTREAM_URL`. */+ async reachable(): Promise<boolean> {+ if (!MOCK_UPSTREAM_URL) return false;+ try {+ return (await this.request.get(this.url('/__control/requests'), { timeout: 5_000 })).ok();+ } catch {+ return false;+ }+ }+}++/** An inventory in the Anthropic `GET /v1/models` shape, carrying the relay+ * extension fields whose drop scenario B3 documents. The `id` stays typed+ * because B3 reads it back out of storage and compares. */+export const anthropicInventory = (ids: string[]): { id: string; [key: string]: unknown }[] =>+ ids.map((id) => ({+ id,+ type: 'model',+ display_name: `${id} (upstream label)`,+ context_length: 200_000,+ pricing: { input: 3, output: 15 },+ }));diff --git a/ui/e2e/support/restore.ts b/ui/e2e/support/restore.tsnew file mode 100644index 000000000..2e9529589--- /dev/null+++ b/ui/e2e/support/restore.ts@@ -0,0 +1,197 @@+// Putting the shared instance back, declared once.+//+// Every spec here mutates a live instance, so every spec here owes a+// restoration — and each one used to write its own. That is where a whole class+// of defects came from, because a hand-written restoration independently+// re-decides three things, and each of them is easy to answer with a PROXY that+// is usually right:+//+// - WHAT to undo. "Whatever appeared since I looked" is a proxy for "the+// thing my switch imported"; it is correct only while nothing else on the+// instance moves.+// - WHAT to put back. "The chain as I found it" is a proxy for "the chain the+// operator left"; the two differ the moment the suite's own sources have+// been placed into it, which the server does on create.+// - WHETHER it is done. "`enabled` is false" is a proxy for "the runtime is+// stopped"; the runtime has two facts and a failed stop can land one+// without the other.+// - WHOSE failure a failure is. `test.fail()` is a proxy for "this assertion+// is expected to fail"; it marks the whole test, teardown included.+// - WHEN the debt begins. "The state has changed" is a proxy for "I have asked+// for it to change"; the request is already gone by then, so a boundary+// opened on the first is skipped on exactly the path where the second holds.+//+// A proxy can be right about the wrong thing. So the restorations live here,+// stated as POSTCONDITIONS and keyed on identity: what a native source IS, and+// what "running" IS. One declaration each, so a site cannot answer them+// differently, and so the next site added inherits the answer instead of+// picking one.+import type { HubApi, RouteHop, Runtime } from './api';+import { isSuiteSource } from './api';+import { expect, runtimeIsRunning } from './fixtures';++/**+ * Reads the baseline `restoreAgentChain` puts back: the OPERATOR's chain, which+ * is not the same thing as the chain that is there when a spec looks.+ *+ * Adding a source is not an inert act. `_apply_source_placement` walks every+ * backend's menu and appends the new source to each route whose model it+ * matches, so by the time a spec captures its baseline the gateway fixture's+ * own two sources may already be hops in it. Those hops are arrangement, not+ * state: the fixture's sweep deletes the sources that supply them, so they do+ * not outlive the spec either way.+ *+ * Restoring them is worse than pointless, because a spec may delete or rebuild+ * one of those sources mid-body — B7 deletes it to raise the supply guard, B6+ * deletes and recreates it to shake off a sticky cooldown — and `set_agent_chain`+ * rejects a PUT containing ANY unknown source id outright. So one stale+ * suite-owned hop takes every real hop down with it and the route the operator+ * had is gone.+ *+ * Hence the pair: capture and restore live together and are written once,+ * because the defect was capture being re-derived at each site while only the+ * restore was shared.+ */+export const captureAgentChain = async (+ api: HubApi,+ route: { backend: string; model: string },+): Promise<RouteHop[]> => {+ const ours = new Set((await api.sources()).filter(isSuiteSource).map((source) => source.id));+ const chain = (await api.chains(route.backend)).find((entry) => entry.model_id === route.model);+ return (chain?.chain ?? [])+ .filter((hop) => !ours.has(hop.source_id))+ .map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id }));+};++/**+ * Puts one model's route chain back to `original` — including back to EMPTY.+ *+ * Unconditional, where three copies of this used to guard on+ * `original.length`. That guard is the same proxy as the rest of this file: it+ * asks "was there a chain?" when the postcondition is "the chain is what it+ * was", and the one case it gets wrong is the spec that arranged hops onto a+ * route that had none — precisely the arrangement most worth removing. The+ * server treats clearing a route as a first-class mutation (it is what+ * `newly_empty_routes` in `set_agent_chain` exists for), so an empty `original`+ * is a request, not a no-op.+ *+ * A refusal is reported, never swallowed: nothing downstream can reconstruct a+ * displaced chain — the source sweep that follows only deletes rows — so a+ * silent `false` here leaves the instance's routing changed while teardown+ * reads clean.+ */+export const restoreAgentChain = async (+ api: HubApi,+ route: { backend: string; model: string },+ original: RouteHop[],+): Promise<void> => {+ const restored = await api.putAgentChain(route.backend, route.model, original);+ expect(+ restored,+ `Teardown failed to restore the original route chain for ${route.backend}/${route.model} — `+ + "the instance is left with the scenario's arrangement.",+ ).toBe(true);+};++/**+ * Removes the native sources a Direct→Gateway switch imported, identified by+ * WHAT THEY ARE rather than by when they turned up.+ *+ * `supply_channel === 'native_cli'` is the identity: `build_native_migration_source`+ * is the only thing that writes that channel, and every source a user or+ * another session can create meanwhile — the Add API key dialog's — is `hub`.+ * The pre-switch snapshot still narrows it to this switch's own import, so a+ * native source the instance already held is left where it was; what the+ * snapshot no longer does is decide on its own that anything unfamiliar is+ * ours to delete.+ *+ * Every match is attempted before any failure is raised, the same way+ * `removeSuiteSources` does it: a native source supplying a live route refuses+ * until forced and `deleteSource` forces, one already gone is success, and one+ * that genuinely will not go is named rather than silently stranding the ones+ * behind it.+ */+export const restoreNativeSources = async (api: HubApi, before: Set<string>): Promise<void> => {+ const failures: string[] = [];+ for (const source of await api.sources()) {+ if (source.supply_channel !== 'native_cli' || before.has(source.id)) continue;+ try {+ await api.deleteSource(source.id);+ } catch (error) {+ failures.push(`${source.id}: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ if (failures.length) {+ throw new Error(+ `The mode switch's imported native source(s) are still on the instance:\n ${failures.join('\n ')}`,+ );+ }+};++/** The runtime is up when BOTH of its facts say so. Either one alone is a+ * half-answer: a stop that disabled the engine and then failed to persist+ * `enabled=false` reads back as enabled-and-`down`. */+const runtimeIsUp = (runtime: Runtime | null): boolean =>+ runtime?.enabled === true && runtimeIsRunning(runtime?.status?.health);++/**+ * Puts the gateway runtime back to RUNNING — the postcondition, not a sequence+ * of clicks.+ *+ * Reached with an explicit start rather than a toggle, for the reason teardown+ * does not click at all: a toggle asks for the OTHER state, so it is right only+ * if the state it read was, and the partial stop above is exactly the case that+ * makes that read unreliable. `POST /api/models/runtime/start` names the target+ * instead of describing a move away from a guess, and an instance already+ * running is unmoved by it.+ *+ * The API is the authority for "up", not the toggle's aria state: that follows+ * a request the browser may never see answered, and a page that has been closed+ * never sees it at all.+ */+const restoreRuntimeRunning = async (api: HubApi): Promise<void> => {+ let startError: string | null = null;+ if (!runtimeIsUp(await api.runtime())) {+ try {+ await api.startRuntime();+ } catch (error) {+ // Held, not raised: an instance that is already starting refuses a second+ // start, and that refusal is not a failure to restore. Only the state the+ // poll below reads is — and if it reports one, this is the evidence for+ // why.+ startError = error instanceof Error ? error.message : String(error);+ }+ }+ await expect+ .poll(async () => runtimeIsUp(await api.runtime()), {+ timeout: 90_000,+ message:+ 'The gateway runtime is not back up, so every spec after this one runs without it.'+ + (startError ? ` The start request was refused: ${startError}` : ''),+ })+ .toBe(true);+};++/**+ * Runs `body` with the runtime's restoration already owed — the boundary is+ * opened by the act of deciding to stop the gateway, not by the stop succeeding.+ *+ * The postcondition above is only half of a restoration; the other half is WHERE+ * the boundary starts, and a hand-written `try` gets that wrong in a way that+ * reads correct: it is placed where the state has changed ("the gateway is+ * STOPPED at this point"), which puts the click that stops it OUTSIDE. A click+ * dispatches its request before its promise settles, so a page or browser that+ * disconnects mid-flight rejects it with the server still completing the stop —+ * and execution never enters the block that would put it back. The runtime stays+ * down and every later spec skips on a precondition this spec broke.+ *+ * So the mutation has nowhere to live except inside. There is no ordering left+ * to get right, which is the only version of this that a later site inherits.+ */+export const withRuntimeRestored = async <T>(api: HubApi, body: () => Promise<T>): Promise<T> => {+ try {+ return await body();+ } finally {+ await restoreRuntimeRunning(api);+ }+};diff --git a/ui/e2e/tsconfig.json b/ui/e2e/tsconfig.jsonnew file mode 100644index 000000000..e6931aa34--- /dev/null+++ b/ui/e2e/tsconfig.json@@ -0,0 +1,24 @@+{+ "//": "Standalone on purpose. `npm run build` runs `tsc -b`, which resolves the app and vite configs only — the browser bundle must not grow a dependency on a Playwright suite that never ships. Typecheck this project directly: `npx tsc -p e2e/tsconfig.json --noEmit`.",+ "compilerOptions": {+ "target": "ES2023",+ "lib": ["ES2023", "DOM"],+ "module": "ESNext",+ "types": ["node"],+ "skipLibCheck": true,++ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,++ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["**/*.ts", "../playwright.config.ts"]+}diff --git a/ui/e2e/z-selector-escaping.spec.ts b/ui/e2e/z-selector-escaping.spec.tsnew file mode 100644index 000000000..19a66ca4d--- /dev/null+++ b/ui/e2e/z-selector-escaping.spec.ts@@ -0,0 +1,35 @@+// The page object's attribute selectors, against a value the operator chose.+//+// The sibling invariants guard forbids building one of these by interpolation;+// what it cannot do is notice that the helper it points at is wrong. So this+// drives the real `ModelHubPage` accessors over a document of its own, with an+// id carrying the three things a quoted CSS string cannot hold raw — a `"`, a+// `\`, and a control character. Unescaped, the first one alone makes+// `querySelectorAll` throw `is not a valid selector`.+//+// The id is not invented: `ModelHubMenuConfig.checked` takes arbitrary+// non-credential strings, so a route row's `data-route-model` is whatever a+// backend's menu was ticked with.+//+// No instance is contacted — `setContent` is the whole fixture — so this runs+// wherever a browser does.+import { expect, test } from '@playwright/test';++import { ModelHubPage } from './support/hub';++const OPERATOR_CHOSEN = 'vendor/"quoted"\\back\\slash\ttab:1';++test('an attribute selector is escaped, not interpolated', async ({ page }) => {+ await page.setContent(+ '<div data-source-id="plain">PLAIN</div>'+ + `<div data-source-id="${OPERATOR_CHOSEN.replace(/&/g, '&').replace(/"/g, '"')}">CHOSEN</div>`,+ );+ const hub = new ModelHubPage(page);++ // Exactly the one row, and the RIGHT one: an escape that merely stopped the+ // throw could still match both, or the wrong sibling.+ await expect(hub.sourceRow(OPERATOR_CHOSEN)).toHaveCount(1);+ await expect(hub.sourceRow(OPERATOR_CHOSEN)).toHaveText('CHOSEN');+ await expect(hub.sourceRow('plain')).toHaveText('PLAIN');+ await expect(hub.sourceRow('no-such-source')).toHaveCount(0);+});diff --git a/ui/e2e/z-suite-invariants.spec.ts b/ui/e2e/z-suite-invariants.spec.tsnew file mode 100644index 000000000..c9826d2e6--- /dev/null+++ b/ui/e2e/z-suite-invariants.spec.ts@@ -0,0 +1,152 @@+// The boundaries that keep this suite's closed defect classes closed.+//+// Four review rounds went to four classes, and each one arrived as a handful of+// sites that had independently answered the same question — what to put back,+// which surface this instance renders, what a selector's value may contain,+// what a negation means. Every answer was a PROXY: right about the wrong thing,+// and right often enough to look like a convention rather than a defect.+// `support/` now answers each of them once, which repairs the sites that exist.+// This repairs the next one.+//+// A rule here is a tripwire on the exact spelling the class used, not a linter.+// It cannot prove the absence of a defect; what it does is make the sixth member+// of a closed class fail a test instead of costing a review round.+//+// Not a browser test: no fixture is requested, so nothing launches. It runs+// where the files it judges run.+import { readdirSync, readFileSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { expect, test } from '@playwright/test';++import { type Agent, remoteAuthRefusal, type Source, surfaceKind } from './support/api';++const E2E_DIR = dirname(fileURLToPath(import.meta.url));+const SUPPORT_DIR = join(E2E_DIR, 'support');+const SELF = basename(fileURLToPath(import.meta.url));++type Rule = {+ /** What the class looked like when it was written by hand. */+ needle: string | RegExp;+ /** The declaration in `support/` that owns the answer instead. */+ owner: string;+ why: string;+ /** `support` files that legitimately contain the needle — the owner's own. */+ allow?: string[];+};++/** Rules judged over the spec files: what a spec may not decide for itself. */+const SPEC_RULES: Rule[] = [+ {+ needle: 'api.chains(',+ owner: 'captureAgentChain',+ why: 'a baseline read beside the arrangement is the one that keeps hops the spec itself deletes',+ },+ {+ needle: 'supply_channel',+ owner: 'restoreNativeSources',+ why: 'what a native source IS has to have one answer, not one per teardown',+ },+ {+ needle: 'api.startRuntime(',+ owner: 'withRuntimeRestored',+ why: 'a restoration written beside the stop is a boundary that opens after the request has already gone',+ },+ {+ needle: "mode === 'direct'",+ owner: 'surfaceKind',+ why: 'every-backend-direct is only the OUTER of the two tests the product makes, so alone it admits an instance whose page is a different shape',+ },+ {+ needle: /\.not\.(toContainText|toHaveText)\(/,+ owner: 'expectVisibleWithout',+ why: 'a negated text assertion is satisfied by an element that is not there at all, which is the opposite verdict',+ },+];++/** Rules judged over the page object and the specs alike: a selector is built+ * in one place, but a spec reaching past it would have the same problem. */+const SELECTOR_RULES: Rule[] = [+ {+ needle: /\.locator\(\s*`/,+ owner: 'attr',+ why: 'a route row is keyed by an operator-chosen model id, and a quote in it either breaks the selector or silently moves it',+ allow: ['hub.ts'],+ },+];++const offencesIn = (dir: string, files: string[], rules: Rule[]): string[] =>+ files.flatMap((name) => {+ const source = readFileSync(join(dir, name), 'utf8');+ return rules+ .filter((rule) => !rule.allow?.includes(name))+ .filter((rule) => (typeof rule.needle === 'string' ? source.includes(rule.needle) : rule.needle.test(source)))+ .map((rule) => `${name} reaches for \`${rule.needle}\` — use \`${rule.owner}\` from support/: ${rule.why}.`);+ });++test('the suite asks support/ its closed questions', () => {+ // Self-excluded, because the needles are spelled out above. Nothing else is:+ // a new spec is judged the moment it lands in this directory.+ const specs = readdirSync(E2E_DIR).filter((name) => name.endsWith('.spec.ts') && name !== SELF);+ const support = readdirSync(SUPPORT_DIR).filter((name) => name.endsWith('.ts'));+ expect(+ specs.length,+ 'No sibling spec files were found, so this guard would pass over an empty suite.',+ ).toBeGreaterThan(0);+ expect(+ support.length,+ 'No support files were found, so the selector rule would pass over an empty directory.',+ ).toBeGreaterThan(0);++ const offences = [+ ...offencesIn(E2E_DIR, specs, [...SPEC_RULES, ...SELECTOR_RULES]),+ ...offencesIn(SUPPORT_DIR, support, SELECTOR_RULES),+ ];++ expect(offences, offences.join('\n')).toEqual([]);+});++const agent = (mode: 'hub' | 'direct', cliPresent: boolean): Agent =>+ ({ backend: 'claude', mode, cli_present: cliPresent });++test('surfaceKind separates the two direct surfaces, not just direct from gateway', () => {+ const noSources: Source[] = [];+ const oneSource = [{ display_name: 'anything' } as Source];++ // The pair the rule above exists for: identical on the outer test, different+ // pages. The second renders `.model-hub-direct-empty` — no backend card, no+ // way out of Direct mode — so a spec asserting the card there fails on an+ // instance that is merely bare, which is a documented skip.+ expect(surfaceKind([agent('direct', true)], noSources)).toBe('direct-home');+ expect(surfaceKind([agent('direct', false)], noSources)).toBe('direct-no-backend');++ // And the outer test itself, from either side.+ expect(surfaceKind([agent('hub', true)], noSources)).toBe('gateway');+ expect(surfaceKind([agent('direct', true)], oneSource)).toBe('gateway');+ // An instance with no agents at all is bare, not a gateway.+ expect(surfaceKind([], noSources)).toBe('direct-no-backend');+});++test('a remote-access refusal is answered with what to do, not with a status', () => {+ // Four names, one thing the operator can do about any of them. Matching the+ // family rather than the member is what keeps a fifth from arriving as a bare+ // 401 — the product owns this list, and the suite does not get told when it+ // grows.+ for (const error of [+ 'remote_access_login_required',+ 'remote_access_authorization_refresh_required',+ 'remote_access_revoked',+ 'remote_access_authorization_unavailable',+ ]) {+ const message = remoteAuthRefusal(401, JSON.stringify({ ok: false, error }));+ expect(message, error).toContain('no login step');+ expect(message, error).toContain(error);+ }++ // And nothing else is one. A 401 from somewhere else, or any other status,+ // still owes the caller the status and the body the generic throw carries.+ expect(remoteAuthRefusal(401, JSON.stringify({ error: 'csrf_token_invalid' }))).toBeNull();+ expect(remoteAuthRefusal(401, 'Unauthorized')).toBeNull();+ expect(remoteAuthRefusal(500, JSON.stringify({ error: 'remote_access_revoked' }))).toBeNull();+});diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex e047df863..923ddc715 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -58,6 +58,7 @@},"devDependencies": {"@eslint/js": "^9.39.1",+ "@playwright/test": "^1.62.1","@tailwindcss/postcss": "^4.1.18","@testing-library/react": "^16.3.2","@testing-library/user-event": "^14.6.3",@@ -1350,6 +1351,22 @@"url": "https://github.com/sponsors/Boshen"}},+ "node_modules/@playwright/test": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz",+ "integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.62.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/@preact/signals-core": {"version": "1.14.2","resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.2.tgz",@@ -6717,6 +6734,53 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/playwright": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",+ "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.62.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",+ "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright/node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },"node_modules/postcss": {"version": "8.5.15","resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",diff --git a/ui/package.json b/ui/package.jsonindex c6eae7770..4a5810163 100644--- a/ui/package.json+++ b/ui/package.json@@ -16,6 +16,8 @@"preview": "vite preview","test": "vitest run","test:crypto": "vitest run src/lib/vaultCrypto.test.ts",+ "e2e": "playwright test",+ "e2e:headed": "playwright test --headed","validate:catalog": "node scripts/validate-scenario-catalog.mjs","validate:theme": "node scripts/validate-theme.mjs"},@@ -70,6 +72,7 @@},"devDependencies": {"@eslint/js": "^9.39.1",+ "@playwright/test": "^1.62.1","@tailwindcss/postcss": "^4.1.18","@testing-library/react": "^16.3.2","@testing-library/user-event": "^14.6.3",diff --git a/ui/playwright.config.ts b/ui/playwright.config.tsnew file mode 100644index 000000000..767ee2796--- /dev/null+++ b/ui/playwright.config.ts@@ -0,0 +1,44 @@+// Playwright configuration for the Model Hub web-interaction suite.+//+// The suite drives a LIVE Avibe instance over HTTP — there is no `webServer`+// block on purpose. Starting the instance is the operator's step (see+// `e2e/README.md`), because the thing under test is a stateful local runtime+// with an installed gateway engine, not a process a test run may create and+// discard. `VIBE_E2E_BASE_URL` names that instance.+//+// `VIBE_E2E_BASE_URL` has no default, and reading it here is what enforces+// that: the whole run refuses to load without it. See `e2e/support/env.ts` for+// why — the suite mutates the instance it is pointed at, and the port it would+// otherwise default to is a developer's real `vibe`.+import { defineConfig, devices } from '@playwright/test';++import { BASE_URL } from './e2e/support/env';++export default defineConfig({+ testDir: './e2e',+ outputDir: './e2e/.artifacts/test-results',+ // Every spec mutates shared instance state (sources, agent modes, the+ // runtime switch). Parallel workers would race on it, so the suite is serial+ // by construction rather than by luck.+ fullyParallel: false,+ workers: 1,+ forbidOnly: Boolean(process.env.CI),+ retries: 0,+ timeout: 90_000,+ expect: { timeout: 15_000 },+ reporter: [+ ['list'],+ ['html', { outputFolder: './e2e/.artifacts/report', open: 'never' }],+ ],+ use: {+ baseURL: BASE_URL,+ // Pins the language the copy assertions read from `src/i18n/en.json`.+ // i18next detects `localStorage` then `navigator`; a fresh Playwright+ // context has no stored preference, so the navigator locale decides.+ locale: 'en-US',+ trace: 'retain-on-failure',+ screenshot: 'only-on-failure',+ video: 'off',+ },+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],+});diff --git a/ui/vite.config.ts b/ui/vite.config.tsindex bedac5674..8c9f2616b 100644--- a/ui/vite.config.ts+++ b/ui/vite.config.ts@@ -1,6 +1,6 @@import { fileURLToPath, URL } from 'node:url'-import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'+import { configDefaults, defineConfig } from 'vitest/config'// Point the dev proxy at any running Avibe instance — e.g. the Incus regression// environment — with VIBE_UI_BACKEND=http://127.0.0.1:15130 npm run dev, so UI@@ -29,6 +29,14 @@ const backendProxy = () => ({// https://vite.dev/config/export default defineConfig({+ // Vitest's default `include` is `**/*.{test,spec}.?(c|m)[jt]s?(x)`, which+ // matches `e2e/*.spec.ts` as readily as `src/*.test.tsx`. Those files are+ // Playwright's, and calling `test.describe()` under Vitest throws+ // ("Playwright Test did not expect test.describe() to be called here"), so+ // without this the unit suite fails on files it was never meant to collect.+ // Excluding the directory — rather than renaming the specs — keeps the trap+ // disarmed for every Playwright file added later.+ test: { exclude: [...configDefaults.exclude, 'e2e/**'] },plugins: [react()],resolve: {alias: {