From 772c2d70f1c086aed7e3872ca749750442798995 Mon Sep 17 00:00:00 2001 From: Surya Prashanth <5310329+Prashant-Surya@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:53:48 +0530 Subject: [PATCH 1/5] test(e2e): drive every app feature from the browser, plus opt-in model flows Core flows (the app and admin Playwright projects) cover sign-in, signup, password reset, email proof, workspaces, projects and members, settings, allowed sites, connectors, home, tasks, the task page, inbox, bots, routines and the admin console, model-free on a private stack whose provider keys are blanked. Bugs the flows found are marked knownBug (test.fail) until their fix lands; E2E_SHOW_BUGS=1 runs them red. Model flows (the models project, E2E_MODELS=1) run real tasks, a follow-up, a fork, a Markdown document with its verification, clarifying questions, a bot's chat, evals, publish and drafter, and a routine's run on a real provider key: `just e2e-models`, or by hand from the E2E model flows workflow (secret E2E_ANTHROPIC_API_KEY). stack.sh waits for Postgres over TCP so migrations never meet the init server, and removes the stack's frames on exit. ADR-081 amended in place. --- .github/workflows/e2e-models.yml | 100 +++++++ .github/workflows/e2e.yml | 11 +- HANDOFF.md | 2 +- STATE.md | 2 +- docs/adr/081-playwright-smoke-flows.md | 77 ++++++ justfile | 20 +- web/e2e/admin/bots-routines.spec.ts | 186 +++++++++++++ web/e2e/admin/login.spec.ts | 122 +++++++++ web/e2e/admin/models-spend-audit.spec.ts | 196 +++++++++++++ web/e2e/admin/overview.spec.ts | 35 +++ web/e2e/admin/tasks.spec.ts | 126 +++++++++ web/e2e/admin/users.spec.ts | 229 ++++++++++++++++ web/e2e/admin/workspaces-projects.spec.ts | 117 ++++++++ web/e2e/allowed-sites.spec.ts | 66 +++++ web/e2e/bots-configure.spec.ts | 258 +++++++++++++++++ web/e2e/bots-tabs.spec.ts | 263 ++++++++++++++++++ web/e2e/connectors.spec.ts | 185 +++++++++++++ web/e2e/fixtures.ts | 101 ++++++- web/e2e/global-setup.ts | 89 +++--- web/e2e/home.spec.ts | 320 ++++++++++++++++++++++ web/e2e/inbox.spec.ts | 255 +++++++++++++++++ web/e2e/models/bots.spec.ts | 155 +++++++++++ web/e2e/models/routines.spec.ts | 71 +++++ web/e2e/models/tasks.spec.ts | 208 ++++++++++++++ web/e2e/password-reset.spec.ts | 72 +++++ web/e2e/project-members.spec.ts | 294 ++++++++++++++++++++ web/e2e/project-settings.spec.ts | 207 ++++++++++++++ web/e2e/projects.spec.ts | 158 ++++++++++- web/e2e/routines.spec.ts | 266 ++++++++++++++++++ web/e2e/seed.ts | 31 +-- web/e2e/settings.spec.ts | 223 ++++++++++++++- web/e2e/shell.spec.ts | 157 +++++++++++ web/e2e/sign-in.spec.ts | 28 ++ web/e2e/signup.spec.ts | 69 +++++ web/e2e/stack.sh | 54 +++- web/e2e/support/accounts.ts | 121 ++++++++ web/e2e/support/api.ts | 120 ++++++++ web/e2e/support/mailbox.ts | 77 ++++++ web/e2e/support/runs.ts | 98 +++++++ web/e2e/task-page.spec.ts | 216 +++++++++++++++ web/e2e/tasks.spec.ts | 246 +++++++++++++++++ web/e2e/verify-email.spec.ts | 75 +++++ web/e2e/workspaces.spec.ts | 253 +++++++++++++++++ web/playwright.config.ts | 72 +++-- 44 files changed, 5914 insertions(+), 117 deletions(-) create mode 100644 .github/workflows/e2e-models.yml create mode 100644 web/e2e/admin/bots-routines.spec.ts create mode 100644 web/e2e/admin/login.spec.ts create mode 100644 web/e2e/admin/models-spend-audit.spec.ts create mode 100644 web/e2e/admin/overview.spec.ts create mode 100644 web/e2e/admin/tasks.spec.ts create mode 100644 web/e2e/admin/users.spec.ts create mode 100644 web/e2e/admin/workspaces-projects.spec.ts create mode 100644 web/e2e/allowed-sites.spec.ts create mode 100644 web/e2e/bots-configure.spec.ts create mode 100644 web/e2e/bots-tabs.spec.ts create mode 100644 web/e2e/connectors.spec.ts create mode 100644 web/e2e/home.spec.ts create mode 100644 web/e2e/inbox.spec.ts create mode 100644 web/e2e/models/bots.spec.ts create mode 100644 web/e2e/models/routines.spec.ts create mode 100644 web/e2e/models/tasks.spec.ts create mode 100644 web/e2e/password-reset.spec.ts create mode 100644 web/e2e/project-members.spec.ts create mode 100644 web/e2e/project-settings.spec.ts create mode 100644 web/e2e/routines.spec.ts create mode 100644 web/e2e/shell.spec.ts create mode 100644 web/e2e/signup.spec.ts create mode 100644 web/e2e/support/accounts.ts create mode 100644 web/e2e/support/api.ts create mode 100644 web/e2e/support/mailbox.ts create mode 100644 web/e2e/support/runs.ts create mode 100644 web/e2e/task-page.spec.ts create mode 100644 web/e2e/tasks.spec.ts create mode 100644 web/e2e/verify-email.spec.ts create mode 100644 web/e2e/workspaces.spec.ts diff --git a/.github/workflows/e2e-models.yml b/.github/workflows/e2e-models.yml new file mode 100644 index 0000000..71d0bfc --- /dev/null +++ b/.github/workflows/e2e-models.yml @@ -0,0 +1,100 @@ +# The model flows (ADR-081, amended 2026-11-22): `just e2e-models` on a fresh runner. The same private +# stack as the core flows (e2e.yml), but the worker holds a provider key and Playwright runs only its +# `models` project: real tasks, a follow-up, a fork, a document and its verification, questions, a +# bot's chat, evals and drafter, a routine's run, each on a real model. The verification needs a +# frame, so the job also starts the compose egress proxy and builds the base frame image, as the +# nightly frame tests do. A run spends about twenty cents, so it never runs on a schedule or a PR: +# by hand only (Actions -> E2E model flows -> Run workflow). +# It needs the repository secret E2E_ANTHROPIC_API_KEY, and stops at its first step without one. +name: E2E model flows + +on: + workflow_dispatch: + +concurrency: + group: e2e-models-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + flows: + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + # The key rides only the steps that need it, never the dependency installs. + steps: + - name: Check the provider key + env: + PRISMOID_WORKER_ANTHROPIC_API_KEY: ${{ secrets.E2E_ANTHROPIC_API_KEY }} + run: | + if [ -z "$PRISMOID_WORKER_ANTHROPIC_API_KEY" ]; then + echo "::error::Set the repository secret E2E_ANTHROPIC_API_KEY to run the model flows." + exit 1 + fi + + - uses: actions/checkout@v7 + + - name: Install uv + uses: astral-sh/setup-uv@v7 + with: + python-version: "3.12" + + - name: Install backend deps + working-directory: backend + run: uv sync --frozen + + # No version: the action reads the root package.json's packageManager pin (pnpm 12, ADR-071). + - name: Install pnpm + uses: pnpm/action-setup@v6 + + - name: Install node + uses: actions/setup-node@v7 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install the JS workspace + run: pnpm install --frozen-lockfile + + - name: Install Chromium for Playwright + working-directory: web + run: pnpm exec playwright install --with-deps --only-shell chromium + + # A document's verification runs in a throwaway frame: frames join the compose frame network, + # which the egress proxy creates (its control port, 3129, is the worker setting's default), and + # boot the base frame image, built here so the first receipt does not wait on a build. + - name: The frame network, its egress proxy and the base frame image + working-directory: backend + run: | + docker compose -f deploy/compose.yaml up -d --wait egress-proxy + uv run python -c "from prismoid.ai.frames.docker_driver import ensure_image; print(ensure_image('base'))" + + # The runner sets CI, which turns on a retry, forbids test.only and writes the HTML report. + - name: The model flows + env: + PRISMOID_WORKER_ANTHROPIC_API_KEY: ${{ secrets.E2E_ANTHROPIC_API_KEY }} + run: uvx --from rust-just just e2e-models + + # The upload is not masked the way the log is: a file that carries the key never leaves the + # runner. No file should (the key never reaches the browser, and the logs print no headers). + - name: Drop any file that carries the key + if: failure() + env: + PRISMOID_WORKER_ANTHROPIC_API_KEY: ${{ secrets.E2E_ANTHROPIC_API_KEY }} + run: | + grep -rlF -- "$PRISMOID_WORKER_ANTHROPIC_API_KEY" \ + web/playwright-report web/test-results web/e2e/.state/logs 2>/dev/null \ + | while read -r leaked; do echo "::warning::dropped $leaked: it carries the key"; rm -f "$leaked"; done + + - name: Keep the report, traces and stack logs + if: failure() + uses: actions/upload-artifact@v7 + with: + name: e2e-models-report + path: | + web/playwright-report/ + web/test-results/ + web/e2e/.state/logs/ + retention-days: 14 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 0d99039..246644e 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -1,8 +1,9 @@ -# The browser smoke flows (ADR-081): `just e2e` on a fresh runner. It starts its own Postgres and -# Silo (S3) containers, the worker and the API, builds and serves the web app, and drives sign-in, a -# project, settings, the design-system page and a task record in Chromium. No flow calls a model, -# so the job needs no secret and runs the same on a fork. Not on every PR: nightly, or by hand -# (Actions -> E2E smoke flows -> Run workflow). +# The browser flows (ADR-081): `just e2e` on a fresh runner. It starts its own Postgres and Silo +# (S3) containers, the worker and the API, builds and serves the web app and the operator console, +# and drives every surface a person reaches without a model run in Chromium. Every provider key is +# blanked and no flow calls a model, so the job needs no secret and runs the same on a fork. Not on +# every PR: nightly, or by hand (Actions -> E2E smoke flows -> Run workflow). The flows that call a +# real model run separately, by hand only: e2e-models.yml. name: E2E smoke flows on: diff --git a/HANDOFF.md b/HANDOFF.md index 3c7a579..3ac6ea8 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -128,7 +128,7 @@ Metric: **IPT — Interventions Per Task** (unplanned human touches; designed ga | `@testing-library/user-event` (14.6.10, web + blocks dev, exact) | Drive a component with real event sequences: typing, Tab, Enter, Space, arrow keys (ADR-079) | the same DOM test files | Fires the keydown, input and keyup chain a browser does, so keyboard paths are tested as they run. `fireEvent` alone rejected: one synthetic event per call misses focus moves and default actions | | `@vitest/coverage-v8` (4.1.12, web + blocks dev, exact, matches `vitest`) | `pnpm test:coverage` in `web/` and `packages/blocks/` (ADR-079) | `web/vitest.config.ts` · `packages/blocks/vitest.config.ts` | V8 coverage needs no instrumenting build step. istanbul rejected: a transform per file for the same numbers | | `pytest-cov` (dev; brings `coverage`) + CI-only tools, never installed into the project: `pip-audit` and `pip-licenses` (uvx, exact pins), `gitleaks` (pinned release binary, checksum-verified), `staticcheck` and `govulncheck` (`go run`, exact pins) | Coverage of the unit and integration suites with a no-regression floor in the job summary; the `security` job's vulnerability, secret and license gates; sandbar's static analysis (ADR-080) | `backend/pyproject.toml` (`[tool.coverage]`) · `.github/workflows/ci.yml` · `backend/tools/license_gate.py` | pytest-cov is the standard pytest driver for coverage.py and combines xdist workers' data itself; coverage.py's `greenlet` concurrency sees the ORM's async lines. The scanners are the ecosystems' own (PyPA, the Go team) or the de facto standard (gitleaks), run at a pinned version so a gate does not move under a PR. Rejected: a hosted coverage service (a third party for one number) and the gitleaks Action (needs a license key for organisations) | -| `@playwright/test` (1.65.1, web dev, exact; Apache-2.0) + Chromium's headless shell (downloaded by `playwright install`, never by `pnpm install`) | The browser smoke flows: sign-in, a project, settings, `/ds` and a held task record against a real API and worker, no model (ADR-081) | `web/playwright.config.ts` · `web/e2e/**` · `just e2e` · `.github/workflows/e2e.yml` (nightly) | Microsoft's runner, with role locators that read like the Testing Library queries the DOM tests use; one runner for the flows and their traces. Cypress rejected (runs inside the page, a second way of writing tests). Not in the frame image: the frame's browser stays the sidecar's CDP pipe (ADR-066) | +| `@playwright/test` (1.65.1, web dev, exact; Apache-2.0) + Chromium's headless shell (downloaded by `playwright install`, never by `pnpm install`) | The browser flows: every surface a person reaches without a model run, the operator console included, against a real API and worker with no model; and, opt-in, the model flows on a real provider key (ADR-081, amended 2026-11-22) | `web/playwright.config.ts` · `web/e2e/**` · `just e2e` · `just e2e-models` · `.github/workflows/e2e.yml` (nightly) · `.github/workflows/e2e-models.yml` (by hand) | Microsoft's runner, with role locators that read like the Testing Library queries the DOM tests use; one runner for the flows and their traces. Cypress rejected (runs inside the page, a second way of writing tests). Not in the frame image: the frame's browser stays the sidecar's CDP pipe (ADR-066) | | `googleapis/release-please-action` (v5, CI only, Apache-2.0; never installed into the project) | Release PRs, on a manual run only: reads the conventional commits on main, bumps `version.txt`, `backend/pyproject.toml`, `backend/uv.lock` and `prismoid.__version__`, writes the CHANGELOG section; tags (a draft GitHub release) only on a manual run with `tag` checked, publishes nothing (ADR-082) | `.github/workflows/release.yml` · `release-please-config.json` · `.release-please-manifest.json` | Google's maintained tool for exactly this, driven by the commit convention the repo already follows, and the version stays readable in the tree with no build or runtime dependency. git-cliff rejected (a changelog generator only: the bump, the PR and the tag would be ours to script); hatch-vcs rejected (a new build dependency, and a build outside a git checkout needs the version passed in) | | `pgsty/silo` (container image, `RELEASE.2026-10-26T00-00-00Z` pinned by digest; AGPL-3.0-or-later; never a Python or JS package) | The self-hosted S3 store: the dev stack, CI, the nightly frame tests, `just e2e` and the single-host `minio` profile; its bundled `mcli` makes the buckets (ADR-083) | `backend/deploy/compose.yaml` · `deploy/compose.prod.yaml` · `web/e2e/stack.sh` | A maintained fork of the MinIO server, whose own images are gone: the same S3 API, `MINIO_*` settings, health routes and on-disk format, so existing volumes open as they are. The frozen `bitnamilegacy/minio` archive, SeaweedFS and Garage (different systems, different layouts), RustFS (early) and Chainguard's MinIO (unpinnable free tier) rejected. Production may point `S3_*` at any S3 instead | | `searxng/searxng` (container image, pinned by digest; AGPL-3.0; never a Python or JS package) | The self-hosted search engine behind `web.search`: `just searxng` in dev and the opt-in `search` profile of the single-host stack (ADR-047) | `deploy/compose.prod.yaml` (`searxng`) · `deploy/searxng/settings.yml` · `justfile` | Prismoid speaks its HTTP JSON API at arm's length and ships none of it (ADR-047 names it the self-host engine). It publishes no port; the worker reaches it on the compose network. A keyed engine (Brave, Tavily) needs no container and stays the other way to turn search on | diff --git a/STATE.md b/STATE.md index 1f3c49c..bd63e66 100644 --- a/STATE.md +++ b/STATE.md @@ -115,7 +115,7 @@ cannot pass a dry run with Caddy's `local_certs`. | Before a workstream merges | `just test`: the whole backend suite, integration tests included (needs `just up`; refuses while `just dev` runs) | | A sandbar change | `just sandbar-check` | | A user-visible change | One real run: `just smoke` or the CLI flow. An agent, prompt or skill change adds `just evals` | -| The drills | Nightly in CI: evals, `just perf`, `just e2e`, the frame integration tests. Weekly: `just chaos`. On demand: `just load`, `just endurance`, `just backup-restore`, `just fresh-clone`, `just range` | +| The drills | Nightly in CI: evals, `just perf`, `just e2e` (the browser flows over every surface reachable without a model run, the operator console included; a flow marked `knownBug` names a bug still open, ADR-081), the frame integration tests. Weekly: `just chaos`. On demand: `just e2e-models` (the browser flows on a real model; needs a provider key, also Actions -> E2E model flows), `just load`, `just endurance`, `just backup-restore`, `just fresh-clone`, `just range` | Red means stop and fix it before new work. diff --git a/docs/adr/081-playwright-smoke-flows.md b/docs/adr/081-playwright-smoke-flows.md index 1ecd3b2..3e4b596 100644 --- a/docs/adr/081-playwright-smoke-flows.md +++ b/docs/adr/081-playwright-smoke-flows.md @@ -53,3 +53,80 @@ regression, or a contract mismatch between the SPA and the API could pass every downloaded by `playwright install`, not by `pnpm install`. - A flow that needs a run (a delivered answer, a gate) waits for a model seam; until then the task record flow covers the record's rendering only. + +## Amendment 2026-11-22 - every feature that needs no model, the console included + +The five smoke flows grow into the browser suite for every surface a person reaches without a model +run: sign-in, signup, the password reset and the address proof, the shell, settings (memory, API +keys, the workspace and its members), workspaces and their invites, the home composer up to its +send, the task list, a held or cancelled task's page, projects with their people, invite links and +settings, routines, the inbox, bots up to publish (configure, memory, channels, the chat surface +without a message), connectors and allowed sites, and the operator console. Point 2 stands for +these core flows (the `app` and `admin` projects): none calls a model, so a core flow still never +sends the composer with When = Now, never sends in a held task's composer, and never fires a +routine that is not held. The model flows below are a separate project with their own run. + +1. **A fresh account per flow.** A flow that changes an account (a reset revokes every session, a + workspace switch rebinds one) or asserts an empty state signs up its own through the API + (`e2e/support/accounts.ts`), so no flow depends on another's rows and a rerun on the same + database never collides. The shared seed stays for the flows that only read. `stack.sh` widens + the per-address signup, login and reset burst buckets on its private stack only; against a + stack someone else runs, `call` waits out a 429. +2. **Emailed codes come from the API's log.** In dev the console mail backend prints each email to + the API's stdout, which `stack.sh` writes to `E2E_API_LOG`; `e2e/support/mailbox.ts` reads the + reset, verification and invite codes from there. Without that log the mail flows skip. +3. **The operator console is its own project.** Playwright serves the console bundle + (`APP_TARGET=admin`) beside the product on `E2E_ADMIN_WEB_PORT`, and `stack.sh` adds its origin + to CORS. The operator scope has no web door outside local mode, so global setup grants it the + way an operator grants the first one, `prismoid admin bootstrap`, which needs the API's + database URL; without it the console flows skip. +4. **A known bug is a flow expected to fail.** `knownBug(reason)` marks a flow that asserts the + right behaviour and fails until the bug is fixed (`test.fail`), so a fix shows as an unexpected + pass and the mark comes off in the same change. `E2E_SHOW_BUGS=1` runs them as ordinary flows. +5. **Two runs against one stack.** `E2E_REUSE_WEB=1` keeps web servers already listening, and + `E2E_STATE_DIR` moves the seed file, so runs in parallel never share one. + +## Amendment 2026-11-22 - the model flows, on a real model, by hand + +The core flows above prove every surface up to a model's answer. What happens after it (a run's +thread, a document and its receipt, questions, a bot's reply) had no browser flow at all, so a +contract break between the stream, the worker and the task page passed every gate. Those flows +now exist, run against a real model, and stay out of every automatic run. + +1. **A third project, `models`, defined only with `E2E_MODELS=1`.** Its flows live in + `web/e2e/models/` and use `e2e/support/runs.ts`; the `app` project ignores the folder, and + without the variable the project does not exist, so `just e2e`, `pnpm e2e` and the nightly job + never see it. `just e2e-models` runs it alone on the same private stack. Each flow gets four + minutes, and each wait for a run its own two. +2. **A real provider key, never a fake model.** The rejection of a fake model behind the worker + stands: the model flows use the provider the product uses, through the catalog `stack.sh` + seeds. `stack.sh` refuses to start the model run without a key in the environment + (`PRISMOID_WORKER_ANTHROPIC_API_KEY`, or the OpenAI or Google one), and the core run now blanks + all three (an exported empty value beats a key in `backend/.env`), so a core flow cannot reach a + model even by accident. +3. **Flows that settle on paper.** Every flow is small enough to finish without a Machine: a + question and its answer, a follow-up (the same task's next turn), a fork launched by a + direction, a Markdown document opened in the reader with its verification receipt, a round of + clarifying questions (Clarifying questions = Always opens one batch deterministically), a bot's + chat reply, its selection evals turning green and the publish they unlock, the bot drafter, and + a routine's Run now delivering to its owner. The document's verification runs in a throwaway + frame (not a Machine) on the compose frame network, so `stack.sh` refuses the model run without + that network (`just up` makes it, with its egress proxy), and the workflow starts the proxy and + builds the base frame image first, as the nightly frame tests do. A Word, PDF or spreadsheet + deliverable takes a Machine, slower and dearer (a Word file took 53 s and 16 model calls), so + those stay out. `stack.sh` removes any frame container wearing its instance label when it ends. +4. **Assert what the server records, not the model's words.** A flow waits on a status, a message + row or a version, and asserts words only where any sane answer must carry them (Paris for the + capital of France). An unsourced note may come back unverified, so the receipt's presence is + asserted, never its verdict. The question helper follows the panel rather than a fixed count, + because the model writes the questions. +5. **By hand, from its own workflow.** `.github/workflows/e2e-models.yml` runs `just e2e-models` on + `workflow_dispatch` only, with the repository secret `E2E_ANTHROPIC_API_KEY`, and stops at its + first step without it. A run costs about twenty cents on the shipped catalog. Before uploading + the report it drops any file that carries the key. A fork has no secrets, so it cannot run it. + +Not covered yet: a run that takes a Machine (shell work, files in Word, PDF, spreadsheet, deck or +code, the screen, Live now), steering and pause (a run settles before a person can steer it), fleet +mode, approvals (they need a connector or a destructive tool), a bot's proposals, work cards and Save +as file, the template share and install that publish unlocks, connector authorization against a live +MCP server, and memory a delivered task writes (the extractor decides, so a flow cannot count on it). diff --git a/justfile b/justfile index 9cf183b..82a61c8 100644 --- a/justfile +++ b/justfile @@ -298,14 +298,26 @@ web-local port="8100": web-gen: pnpm gen -# Playwright over sign-in, a project, settings, /ds and a task record (ADR-081), on a private -# Postgres + Silo (S3) + worker + API and the built web app, all removed when it ends. No model is -# called, and it is not part of `check`. Arguments go to `playwright test`. -# the browser smoke flows against a private stack +# Playwright over every surface reachable without a model run, the operator console included +# (ADR-081), on a private Postgres + Silo (S3) + worker + API and both built web apps, all removed +# when it ends. Every provider key is blanked, so no model can be called, and it is not part of +# `check`. Arguments go to `playwright test`. +# the browser flows against a private stack [working-directory: '..'] e2e *ARGS: bash web/e2e/stack.sh {{ARGS}} +# The model flows (ADR-081, amended 2026-11-22): Playwright's `models` project sends real work to a +# real model on the same private stack - tasks, a follow-up, a fork, a document and its +# verification, questions, a bot's chat, evals and drafter, a routine's run. Needs a provider key +# in the environment (PRISMOID_WORKER_ANTHROPIC_API_KEY, or the OpenAI or Google one) and the +# compose frame network (`just up`), and spends about twenty cents a run; never nightly, by hand or +# from Actions -> E2E model flows. +# the browser flows that call a real model (needs a provider key) +[working-directory: '..'] +e2e-models *ARGS: + E2E_MODELS=1 bash web/e2e/stack.sh --project=models {{ARGS}} + # the web half of the gate - typecheck (typegen + tsc), oxlint, the token + radius + dash guards, # the contrast audit, unit tests: turbo's `check` task runs them all, for web and the workspace # packages it depends on (@prismoid/blocks) - turbo.json, ADR-071 diff --git a/web/e2e/admin/bots-routines.spec.ts b/web/e2e/admin/bots-routines.spec.ts new file mode 100644 index 0000000..726b265 --- /dev/null +++ b/web/e2e/admin/bots-routines.spec.ts @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { signUp } from "../support/accounts"; +import { call, createBot, createHeldRoutine, stamp } from "../support/api"; +import { escapeRegExp, expect, knownBug, test, toast } from "../fixtures"; + +// Bots and routines across the system. A bot is observed read-only, and reading its instructions is +// itself an audited act. A routine has one operator verb, pause, which needs a reason and tells the +// owner. The routines here hold (posture "hold", a yearly When), so nothing fires during a run. + +test.describe("console bots", () => { + test("finds a fresh draft bot and reading its instructions is audited", async ({ + adminPage: page, + }) => { + const owner = await signUp("e2e-admin-bots"); + const name = `heron-${stamp()}`; + const instructions = "Summarize the field notes in three short bullet points."; + await createBot(owner.token, { name, instructions }); + + await page.goto("/bots"); + await page.getByRole("textbox", { name: "Search bot name…" }).fill(name); + const main = page.getByRole("main"); + const row = main.getByRole("link", { name: new RegExp(`^${escapeRegExp(name)} `) }); + await expect(row).toHaveCount(1); + // Every bot row carries its eval state; once the search has landed this is the only row. + await expect(main.getByRole("link", { name: / evals / })).toHaveCount(1); + for (const fact of ["v1", "draft", "evals untested", owner.email, "personal"]) + await expect(row).toContainText(fact); + + // The status chips: a draft is a draft, and nothing else. + await main.getByRole("button", { name: "Draft", exact: true }).click(); + await expect(page).toHaveURL(/status=draft/); + await expect(row).toHaveCount(1); + for (const other of ["Published", "Archived"]) { + await main.getByRole("button", { name: other, exact: true }).click(); + await expect(main.getByText(`No matches for “${name}”`)).toBeVisible(); + } + await main.getByRole("button", { name: "All", exact: true }).click(); + await expect(row).toHaveCount(1); + + await row.click(); + await expect(page).toHaveURL(/\/bots\/[0-9a-f-]{36}$/); + const botId = new URL(page.url()).pathname.split("/").pop()!; + await expect(main.getByRole("heading", { name, level: 1 })).toBeVisible(); + await expect(main.getByRole("heading", { name: "Instructions", level: 2 })).toBeVisible(); + await expect(main.getByText(instructions)).toBeVisible(); + await expect( + main.getByText("Reading a bot's instructions is recorded in the audit trail."), + ).toBeVisible(); + + await main.getByRole("tab", { name: "Versions" }).click(); + await expect(main.getByRole("tab", { name: "Versions", selected: true })).toBeVisible(); + const version = main.getByRole("listitem").filter({ hasText: "v1" }); + await expect(version).toContainText("head"); + await expect(version).toContainText("draft"); + await expect(main.getByText(instructions)).toBeHidden(); + + // The read left a row on the audit trail, naming the bot. + await page.goto("/audit"); + const entry = page + .getByRole("main") + .getByRole("listitem") + .filter({ hasText: "bot.view" }) + .filter({ has: page.getByRole("link", { name: `bot:${botId}` }) }); + await expect(entry.first()).toBeVisible(); + await entry + .first() + .getByRole("link", { name: `bot:${botId}` }) + .click(); + await expect(page).toHaveURL(new RegExp(`/bots/${botId}$`)); + }); +}); + +/** + * A fresh person's held routine, found on the console's list by its unique name: typed into the + * search box, or opened from a link that already carries the search. + */ +async function routineOnList(page: Page, via: "typed" | "link") { + const owner = await signUp("e2e-admin-routines"); + const name = `Tide report ${stamp()}`; + const routine = await createHeldRoutine(owner.token, { + name, + instruction: "Summarize the tide tables.", + }); + const search = page.getByRole("textbox", { name: "Search routine names…" }); + if (via === "typed") { + await page.goto("/routines"); + await search.fill(name); + } else { + await page.goto(`/routines?q=${encodeURIComponent(name)}`); + await expect(search).toHaveValue(name); + } + // Every routine row counts its runs. Once the search has landed (the box debounces), this is + // the only such row, so nothing after this races a refetch. + const rows = page + .getByRole("main") + .getByRole("listitem") + .filter({ hasText: /\d+ runs?/ }); + const row = rows.filter({ hasText: name }); + await expect(row).toHaveCount(1); + await expect(rows.filter({ hasNotText: name })).toHaveCount(0); + return { owner, name, routine, row }; +} + +/** Opens the pause dialog from the row's nested pause button. */ +async function openPause(page: Page, name: string) { + await page.getByRole("button", { name: `Pause ${name}`, exact: true }).click(); + return page.getByRole("dialog", { name: `Pause “${name}”?` }); +} + +test.describe("console routines", () => { + test("an operator pauses a routine with a reason, and the owner is told", async ({ + adminPage: page, + }) => { + const { owner, name, routine, row } = await routineOnList(page, "typed"); + await expect(row).toContainText(owner.email); + await expect(row).toContainText("active"); + + const dialog = await openPause(page, name); + const confirm = dialog.getByRole("button", { name: "Pause routine" }); + await expect(confirm).toBeDisabled(); + const reason = `Runaway schedule draining the budget ${stamp()}`; + await dialog.getByRole("textbox", { name: "Reason" }).fill(reason); + await confirm.click(); + await expect(toast(page, "Paused. Audited, and the owner has the note.")).toBeVisible(); + await expect(dialog).toBeHidden(); + + // The owner's routine is paused, carrying the operator's note. + const seen = await call<{ status: string; paused_reason: string; pause_note: string }>( + `/routines/${routine.id}`, + { token: owner.token }, + ); + expect(seen).toMatchObject({ status: "paused", paused_reason: "admin", pause_note: reason }); + const inbox = await call<{ items: { title: string; body: string }[] }>("/inbox", { + token: owner.token, + }); + const note = inbox.items.find((i) => i.title === `${name} was paused by an operator`); + expect(note?.body).toContain(reason); + + // Read back from the server, the row says paused, with the note, and offers no second pause. + await page.reload(); + await expect(row).toContainText("paused"); + await expect(row).toContainText(`admin: ${reason}`); + await expect(page.getByRole("button", { name: `Pause ${name}`, exact: true })).toHaveCount(0); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Paused", exact: true }).click(); + await expect(page).toHaveURL(/status=paused/); + await expect(row).toHaveCount(1); + await main.getByRole("button", { name: "Active", exact: true }).click(); + await expect(main.getByText(`No matches for “${name}”`)).toBeVisible(); + }); + + test("the pause confirm waits for a reason the server accepts", async ({ adminPage: page }) => { + knownBug( + "web/app/components/admin/confirm.tsx:149 enables the confirm after one character, but " + + "backend/prismoid/api/serializers/admin_routines.py:40 requires a pause reason of at least " + + "3, so a short reason is sent and refused as 'the request body is not valid'", + ); + const { name } = await routineOnList(page, "link"); + const dialog = await openPause(page, name); + await dialog.getByRole("textbox", { name: "Reason" }).fill("ok"); + // Either fix is right: the dialog holds a reason this short back, or the server takes it. + const confirm = dialog.getByRole("button", { name: "Pause routine" }); + if (await confirm.isDisabled()) return; + await confirm.click(); + await expect(toast(page, "Paused. Audited, and the owner has the note.")).toBeVisible(); + }); + + test("a paused routine shows as paused without a reload", async ({ adminPage: page }) => { + knownBug( + "web/app/routes/admin/routines/route.tsx:47 pauses without refreshing the list (the " + + "ResourceList has no refreshMs), so the row still says active and offers Pause until a reload", + ); + const { name, row } = await routineOnList(page, "link"); + const dialog = await openPause(page, name); + await dialog.getByRole("textbox", { name: "Reason" }).fill("Paused while the owner is away"); + await dialog.getByRole("button", { name: "Pause routine" }).click(); + await expect(toast(page, "Paused. Audited, and the owner has the note.")).toBeVisible(); + await expect(row).toContainText("paused"); + }); +}); diff --git a/web/e2e/admin/login.spec.ts b/web/e2e/admin/login.spec.ts new file mode 100644 index 0000000..cb1bd2c --- /dev/null +++ b/web/e2e/admin/login.spec.ts @@ -0,0 +1,122 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { signUp } from "../support/accounts"; +import { call } from "../support/api"; +import { expect, test } from "../fixtures"; + +// The operator console's front door: its own app, whose login refuses any account without the admin +// scope, and whose shell re-proves the scope on every load. The seeded operator's session is shared +// by every console flow, so the sign-out here ends a session this flow opened itself, never that one. +test.describe("operator console sign-in", () => { + test("a signed-out visit lands on the console's own sign-in", async ({ page }) => { + await page.goto("/"); + await expect(page).toHaveURL(/\/login/); + await expect(page.getByRole("heading", { name: "Operator console", level: 1 })).toBeVisible(); + await expect(page.getByText("Sign in with an admin account to manage Prismoid.")).toBeVisible(); + await expect(page.getByText("Admin accounts only")).toBeVisible(); + }); + + test("refuses an account without the admin scope, and leaves no session behind", async ({ + page, + seed, + }) => { + test.skip(!seed.admin, "no operator account"); + const person = await signUp("e2e-admin-login"); + await page.goto("/login"); + await page.getByRole("textbox", { name: "Email" }).fill(person.email); + await page.getByRole("textbox", { name: "Password" }).fill(person.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect( + page.getByText("This console is for operators. Your account doesn't hold the admin scope."), + ).toBeVisible(); + await expect(page).toHaveURL(/\/login/); + + // The refused sign-in opened a session to ask who this is; it must be signed out again, so the + // only live session left is the one signup made. + const seen = await call<{ live_sessions: number }>(`/admin/users/${person.id}`, { + token: seed.admin!.token, + }); + expect(seen.live_sessions).toBe(1); + + await page.goto("/"); + await expect(page).toHaveURL(/\/login/); + }); + + test("a wrong password is refused", async ({ page, seed }) => { + test.skip(!seed.admin, "no operator account"); + await page.goto("/login"); + await page.getByRole("textbox", { name: "Email" }).fill(seed.admin!.email); + await page.getByRole("textbox", { name: "Password" }).fill("not the operator password"); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByText("Invalid email or password.")).toBeVisible(); + }); + + test("the operator signs in through the form, and signing out ends only that session", async ({ + page, + seed, + }) => { + test.skip(!seed.admin, "no operator account"); + const operator = seed.admin!; + await page.goto("/login"); + await page.getByRole("textbox", { name: "Email" }).fill(operator.email); + await page.getByRole("textbox", { name: "Password" }).fill(operator.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page).toHaveURL(/\/$/); + await expect(page.getByRole("heading", { name: "Health" })).toBeVisible(); + + // The sidebar's footer names the operator and signs this browser out in one click. + await page + .getByRole("button", { name: new RegExp(operator.email.replace(/[.+]/g, "\\$&")) }) + .click(); + await expect(page).toHaveURL(/\/login/); + await page.goto("/"); + await expect(page).toHaveURL(/\/login/); + + // The run's shared operator session is a different one, and it is still live. + const me = await call<{ email: string; is_admin: boolean }>("/auth/me", { + token: operator.token, + }); + expect(me).toMatchObject({ email: operator.email, is_admin: true }); + }); + + test("every sidebar section opens its page", async ({ adminPage: page }) => { + await page.goto("/"); + const sections: [string, RegExp, string][] = [ + ["Users", /\/users$/, "Users · Admin · Prismoid"], + ["Workspaces", /\/workspaces$/, "Workspaces · Admin · Prismoid"], + ["Projects", /\/projects$/, "Projects · Admin · Prismoid"], + ["Tasks", /\/tasks$/, "Tasks · Admin · Prismoid"], + ["Bots", /\/bots$/, "Bots · Admin · Prismoid"], + ["Routines", /\/routines$/, "Routines · Admin · Prismoid"], + ["Models", /\/models$/, "Models · Admin · Prismoid"], + ["Spend", /\/spend$/, "Spend · Admin · Prismoid"], + ["Audit", /\/audit$/, "Audit · Admin · Prismoid"], + ["Overview", /:\d+\/$/, "Admin · Prismoid"], + ]; + for (const [label, url, title] of sections) { + await page.getByRole("link", { name: label, exact: true }).click(); + await expect(page).toHaveURL(url); + await expect(page).toHaveTitle(title); + } + // Each page shows its own content, not just a title: spot-check the landmarks. + await expect(page.getByRole("heading", { name: "Health" })).toBeVisible(); + await page.getByRole("link", { name: "Users", exact: true }).click(); + await expect(page.getByRole("textbox", { name: "Search email, name, or ID…" })).toBeVisible(); + await page.getByRole("link", { name: "Tasks", exact: true }).click(); + await expect( + page.getByRole("textbox", { name: "Search title, goal, or task ID…" }), + ).toBeVisible(); + await page.getByRole("link", { name: "Bots", exact: true }).click(); + await expect(page.getByRole("textbox", { name: "Search bot name…" })).toBeVisible(); + await page.getByRole("link", { name: "Routines", exact: true }).click(); + await expect(page.getByRole("textbox", { name: "Search routine names…" })).toBeVisible(); + await page.getByRole("link", { name: "Models", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Doctor" })).toBeVisible(); + await page.getByRole("link", { name: "Spend", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Daily" })).toBeVisible(); + }); +}); diff --git a/web/e2e/admin/models-spend-audit.spec.ts b/web/e2e/admin/models-spend-audit.spec.ts new file mode 100644 index 0000000..808de77 --- /dev/null +++ b/web/e2e/admin/models-spend-audit.spec.ts @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { signUp } from "../support/accounts"; +import { call, stamp } from "../support/api"; +import { expect, test, toast } from "../fixtures"; + +// The model catalog, the ledger and the audit trail. The catalog and the price book are global, so +// a flow only ever changes a model it added itself (a stamped id under a made-up provider): it +// leaves every seeded model, price and route exactly as it found them. An added model starts +// disabled, and the flow leaves it disabled again whatever happens. + +test.describe("console models", () => { + test("the doctor names every model whose provider has no key", async ({ adminPage: page }) => { + await page.goto("/models"); + const main = page.getByRole("main"); + await expect(main.getByRole("heading", { name: "Doctor", level: 2 })).toBeVisible(); + await expect(main.getByText("Catalog healthy")).toHaveCount(0); + // The e2e stack holds no provider key, so the seeded Anthropic models are among the findings. + const finding = main + .getByRole("listitem") + .filter({ hasText: "key-missing" }) + .filter({ hasText: "anthropic:claude-opus-5-5" }); + await expect(finding).toContainText( + "no API key resolves for provider 'anthropic' - every call will 401 mid-run.", + ); + await expect(finding).toContainText("PRISMOID_GATEWAY_ANTHROPIC_API_KEY"); + for (const section of ["Catalog", "Routing table"]) + await expect(main.getByRole("heading", { name: new RegExp(`^${section}`) })).toBeVisible(); + }); + + test("adding a model needs a provider, a model id, a family and a class", async ({ + adminPage: page, + }) => { + await page.goto("/models"); + await page.getByRole("main").getByRole("button", { name: "Add model" }).click(); + const dialog = page.getByRole("dialog", { name: "Add a model" }); + await dialog.getByRole("textbox", { name: "Provider" }).fill("e2e"); + await dialog.getByRole("button", { name: "Add model" }).click(); + await expect( + toast(page, "Provider, model id, family, and at least one class are required."), + ).toBeVisible(); + await expect(dialog).toBeVisible(); + }); + + test("adds a model, switches it on and off, and reprices it", async ({ + adminPage: page, + seed, + }) => { + const modelId = `probe-${stamp()}`; + const ref = `e2e:${modelId}`; + const main = page.getByRole("main"); + try { + await page.goto("/models"); + await main.getByRole("button", { name: "Add model" }).click(); + const dialog = page.getByRole("dialog", { name: "Add a model" }); + await dialog.getByRole("textbox", { name: "Provider" }).fill("e2e"); + await dialog.getByRole("textbox", { name: "Model id" }).fill(modelId); + await dialog.getByRole("textbox", { name: "Family" }).fill("e2e"); + await dialog.getByRole("textbox", { name: "Context window" }).fill("8000"); + await dialog.getByRole("button", { name: "cheap-classifier", exact: true }).click(); + await dialog.getByRole("textbox", { name: "input_token" }).fill("0.000001"); + await dialog.getByRole("textbox", { name: "output_token" }).fill("0.000002"); + await dialog.getByRole("button", { name: "Add model" }).click(); + await expect( + toast(page, "Model added, disabled, and priced. Enable it when you're ready."), + ).toBeVisible(); + await expect(dialog).toBeHidden(); + + // A new model arrives switched off. + const catalogRow = main + .getByRole("listitem") + .filter({ has: page.getByRole("switch", { name: new RegExp(`${ref}$`) }) }); + await expect(catalogRow).toContainText("cheap-classifier"); + await expect(catalogRow).toContainText("8K ctx"); + const enable = main.getByRole("switch", { name: `Enable ${ref}` }); + const disable = main.getByRole("switch", { name: `Disable ${ref}` }); + await expect(enable).not.toBeChecked(); + + await enable.click(); + await expect(disable).toBeChecked(); + await page.reload(); + await expect(disable).toBeChecked(); + await disable.click(); + await expect(enable).not.toBeChecked(); + await page.reload(); + await expect(enable).not.toBeChecked(); + + // The price book: a reprice mints a new version and changes only this model. + const book = main.getByRole("heading", { name: /^Price book · v\d+$/ }); + const before = Number((await book.textContent())!.match(/v(\d+)/)![1]); + const priceRow = main + .getByRole("listitem") + .filter({ hasText: ref }) + .filter({ has: page.getByRole("button", { name: "Edit prices" }) }); + await expect(priceRow).toContainText("input_token = "); + await priceRow.getByRole("button", { name: "Edit prices" }).click(); + const reprice = page.getByRole("dialog", { name: `Reprice ${ref}` }); + const save = reprice.getByRole("button", { name: "Save new version" }); + await expect(save).toBeDisabled(); + await reprice.getByRole("textbox", { name: "input_token" }).fill("0.0000015"); + await save.click(); + const saved = toast( + page, + new RegExp(`^Price book v(\\d+) - ${ref.replace(/[.:-]/g, "\\$&")} repriced\\.$`), + ); + await expect(saved).toBeVisible(); + const after = Number((await saved.textContent())!.match(/v(\d+)/)![1]); + expect(after).toBeGreaterThan(before); + await expect(main.getByRole("heading", { name: `Price book · v${after}` })).toBeVisible(); + await page.reload(); + await expect(priceRow).toContainText(/input_token = 0\.0000015/); + await expect(priceRow).toContainText(/output_token = 0\.000002/); + + // Each change is on the audit trail, against the model. + await page.goto("/audit"); + const trail = page + .getByRole("main") + .getByRole("listitem") + .filter({ hasText: `model:${ref}` }); + await expect(trail.filter({ hasText: "model.add" })).toHaveCount(1); + await expect(trail.filter({ hasText: "model.patch" })).toHaveCount(2); + } finally { + // Whatever failed above, the model this flow added is left switched off. + await call(`/admin/models/${encodeURIComponent(ref)}`, { + method: "PATCH", + token: seed.admin!.token, + body: { enabled: false }, + }).catch(() => undefined); + } + }); +}); + +test.describe("console spend", () => { + test("shows the ledger's tiles and slices the daily chart", async ({ adminPage: page }) => { + await page.goto("/spend"); + const main = page.getByRole("main"); + for (const tile of ["Last 30 days", "This month", "Today", "Calls"]) + await expect(main.getByText(tile, { exact: true })).toBeVisible(); + await expect(main.getByRole("heading", { name: "Daily", level: 2 })).toBeVisible(); + // "By model" is both a slice of the chart and a section of its own. + await expect(main.getByRole("heading", { name: "By model", level: 2 })).toBeVisible(); + await expect(main.getByRole("heading", { name: "Top spenders", level: 2 })).toBeVisible(); + + const total = main.getByRole("button", { name: "Total", exact: true }); + const byModel = main.getByRole("button", { name: "By model", exact: true }); + const byUser = main.getByRole("button", { name: "By user", exact: true }); + await expect(total).toHaveAttribute("aria-pressed", "true"); + await byModel.click(); + await expect(page).toHaveURL(/by=model/); + await expect(byModel).toHaveAttribute("aria-pressed", "true"); + await expect(total).toHaveAttribute("aria-pressed", "false"); + await byUser.click(); + await expect(page).toHaveURL(/by=user/); + await expect(byUser).toHaveAttribute("aria-pressed", "true"); + + // The slice is in the URL, so a pasted link opens the same view. + await page.reload(); + await expect(byUser).toHaveAttribute("aria-pressed", "true"); + await total.click(); + await expect(page).not.toHaveURL(/by=/); + await expect(total).toHaveAttribute("aria-pressed", "true"); + }); +}); + +test.describe("console audit", () => { + test("lists an operator's act with its reason and links to the subject", async ({ + adminPage: page, + seed, + }) => { + const person = await signUp("e2e-admin-audit"); + const reason = `Chargeback under review ${stamp()}`; + // The act happens through the API as the run's operator, so this flow reads only the trail. + await call(`/admin/users/${person.id}/suspend`, { token: seed.admin!.token, body: { reason } }); + await call(`/admin/users/${person.id}/unsuspend`, { token: seed.admin!.token, body: {} }); + + await page.goto("/audit"); + const rows = page.getByRole("main").getByRole("listitem"); + const suspended = rows + .filter({ hasText: "user.suspend" }) + .filter({ has: page.getByRole("link", { name: `user:${person.id}` }) }); + await expect(suspended).toContainText(reason); + await expect(suspended).toContainText(seed.admin!.email); + await expect( + rows + .filter({ hasText: "user.unsuspend" }) + .filter({ has: page.getByRole("link", { name: `user:${person.id}` }) }), + ).toHaveCount(1); + + await suspended.getByRole("link", { name: `user:${person.id}` }).click(); + await expect(page).toHaveURL(new RegExp(`/users/${person.id}$`)); + }); +}); diff --git a/web/e2e/admin/overview.spec.ts b/web/e2e/admin/overview.spec.ts new file mode 100644 index 0000000..0cd26e6 --- /dev/null +++ b/web/e2e/admin/overview.spec.ts @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, test } from "../fixtures"; + +// The console's landing: the worker's health, what is asking for an operator, and spend at a glance. +// The e2e stack holds no provider key, so the catalog doctor always has something to say: every +// enabled model will 401 mid-run, and the Alerts must say so rather than "All quiet". +test.describe("console overview", () => { + test("shows health, the catalog doctor's alert, and spend", async ({ adminPage: page }) => { + await page.goto("/"); + const main = page.getByRole("main"); + await expect(main.getByRole("heading", { name: "Health", level: 2 })).toBeVisible(); + await expect(main.getByText(/worker ok/)).toBeVisible(); + await expect(main.getByText(/migration /)).toBeVisible(); + + await expect(main.getByRole("heading", { name: "Alerts", level: 2 })).toBeVisible(); + const alert = main.getByRole("listitem").filter({ hasText: "catalog-doctor" }); + await expect(alert).toBeVisible(); + await expect(alert).toContainText("warn"); + await expect(alert).toContainText("key-missing"); + await expect(main.getByText("All quiet")).toHaveCount(0); + + await expect(main.getByRole("heading", { name: "Spend", level: 2 })).toBeVisible(); + await expect( + main.getByText(/today · .* this month · .* over 30 days · \d+ calls/), + ).toBeVisible(); + await main.getByRole("link", { name: "Full breakdown" }).click(); + await expect(page).toHaveURL(/\/spend$/); + await expect(page.getByRole("heading", { name: "Daily" })).toBeVisible(); + }); +}); diff --git a/web/e2e/admin/tasks.spec.ts b/web/e2e/admin/tasks.spec.ts new file mode 100644 index 0000000..eb54afd --- /dev/null +++ b/web/e2e/admin/tasks.spec.ts @@ -0,0 +1,126 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { signUp } from "../support/accounts"; +import { call, createHeldTask, stamp } from "../support/api"; +import { expect, test, toast } from "../fixtures"; + +// The task console: every task in the system, searchable and sliced by status, with a peek that +// reads the durable record and an operator's one hard verb, cancel. The tasks here are held (a +// routine fired with posture "hold"), so nothing ever plans or runs and no model is called. + +const SEARCH = "Search title, goal, or task ID…"; + +async function heldTaskOfNewPerson() { + const owner = await signUp("e2e-admin-tasks"); + const task = await createHeldTask(owner.token, `Reconcile the moth survey ${stamp()}`); + return { owner, task }; +} + +test.describe("console tasks", () => { + test("search finds a fresh held task, and the status chips slice the list", async ({ + adminPage: page, + }) => { + const { owner, task } = await heldTaskOfNewPerson(); + await page.goto("/tasks"); + const main = page.getByRole("main"); + const search = page.getByRole("textbox", { name: SEARCH }); + // Every task row names its turn; once a search has reached the server (the box debounces, + // and the search rides the URL, so a reload runs it fresh) this task's row is the only one. + const rows = main.getByRole("listitem").filter({ hasText: /· turn \d+/ }); + const row = rows.filter({ hasText: task.title }); + await search.fill(task.goal); + await expect(page).toHaveURL(/q=/); + await page.reload(); + await expect(search).toHaveValue(task.goal); + await expect(row).toHaveCount(1); + await expect(rows).toHaveCount(1); + await expect(row).toContainText("· held"); + await expect(row.getByRole("img", { name: "Status: queued" })).toBeVisible(); + await expect(row.getByRole("link", { name: owner.email })).toBeVisible(); + + // The id finds it as well. + await search.fill(task.id); + await expect(page).toHaveURL(new RegExp(`q=${task.id}`)); + await page.reload(); + await expect(search).toHaveValue(task.id); + await expect(row).toHaveCount(1); + await expect(rows).toHaveCount(1); + + // A held task has not started: the queued chip keeps it, a delivered-only slice drops it. + await main.getByRole("button", { name: "queued", exact: true }).click(); + await expect(page).toHaveURL(/status=created/); + await expect(row).toHaveCount(1); + await main.getByRole("button", { name: "queued", exact: true }).click(); + await main.getByRole("button", { name: "delivered", exact: true }).click(); + await expect(page).toHaveURL(/status=delivered/); + await expect(main.getByText(`No matches for “${task.id}”`)).toBeVisible(); + await main.getByRole("button", { name: "delivered", exact: true }).click(); + await expect(row).toHaveCount(1); + + // The owner's email leads to their page. + await row.getByRole("link", { name: owner.email }).click(); + await expect(page).toHaveURL(new RegExp(`/users/${owner.id}$`)); + }); + + test("the peek reads the task's status and record", async ({ adminPage: page }) => { + const { owner, task } = await heldTaskOfNewPerson(); + await page.goto(`/tasks?q=${task.id}`); + await page + .getByRole("main") + .getByRole("button", { name: new RegExp(task.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }) + .click(); + await expect(page).toHaveURL(new RegExp(`task=${task.id}`)); + + const peek = page.getByRole("dialog", { name: "Task" }); + await expect(peek.getByText(task.title)).toBeVisible(); + await expect(peek.getByRole("link", { name: owner.email })).toBeVisible(); + await expect(peek.getByText("queued", { exact: true })).toBeVisible(); + // The record's first frame is what was asked. + await expect(peek.getByText(task.goal)).toBeVisible(); + await expect(peek.getByText(/live - re-reading every \d+s/)).toBeVisible(); + + // The peek is in the URL: a reload opens it again. + await page.reload(); + await expect(peek.getByText(task.goal)).toBeVisible(); + await peek.getByRole("button", { name: "Close" }).click(); + await expect(peek).toBeHidden(); + await expect(page).not.toHaveURL(/task=/); + }); + + test("an operator cancels a held task with a reason", async ({ adminPage: page }) => { + const { owner, task } = await heldTaskOfNewPerson(); + await page.goto(`/tasks?task=${task.id}`); + const peek = page.getByRole("dialog", { name: "Task" }); + await expect(peek.getByText("queued", { exact: true })).toBeVisible(); + await peek.getByRole("button", { name: "Cancel task" }).click(); + + const dialog = page.getByRole("dialog", { name: "Cancel this task?" }); + const confirm = dialog.getByRole("button", { name: "Cancel task" }); + await expect(confirm).toBeDisabled(); + const reason = `Runaway spend on a shared key ${stamp()}`; + await dialog.getByRole("textbox", { name: "Reason" }).fill(reason); + await confirm.click(); + await expect(toast(page, "Cancelled. Status is now cancelled.")).toBeVisible(); + await expect(dialog).toBeHidden(); + await expect(peek.getByText("cancelled", { exact: true })).toBeVisible(); + // A settled task has nothing left to cancel. + await expect(peek.getByRole("button", { name: "Cancel task" })).toHaveCount(0); + + // The owner's own view agrees. + const seen = await call<{ status: string }>(`/tasks/${task.id}`, { token: owner.token }); + expect(seen.status).toBe("cancelled"); + + // The act and its reason are on the audit trail. + await page.goto("/audit"); + const entry = page + .getByRole("main") + .getByRole("listitem") + .filter({ hasText: "task.cancel" }) + .filter({ has: page.getByRole("link", { name: `task:${task.id}` }) }); + await expect(entry).toContainText(reason); + }); +}); diff --git a/web/e2e/admin/users.spec.ts b/web/e2e/admin/users.spec.ts new file mode 100644 index 0000000..c716488 --- /dev/null +++ b/web/e2e/admin/users.spec.ts @@ -0,0 +1,229 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { type Account, signIn, signUp } from "../support/accounts"; +import { ApiError, call, stamp } from "../support/api"; +import { escapeRegExp, expect, test, toast } from "../fixtures"; + +// The operator's verbs on a person: suspend, grant or revoke the console, sign out everywhere, and +// revoke one credential at a time. Each flow acts on an account it signs up itself (the user list is +// global and holds every run's accounts), never on the seeded operator. + +/** A fresh person, with a name of their own so their row and header are unmistakable. */ +function target(): Promise { + return signUp("e2e-admin-users", { name: `Una Target ${stamp()}` }); +} + +/** The status a credential gets from the API: 200 while it lives, the refusal's code after. */ +async function statusOf(token: string): Promise { + try { + await call("/auth/me", { token }); + return 200; + } catch (e) { + if (e instanceof ApiError) return e.status; + throw e; + } +} + +/** The person's audit trail, read on their History tab. */ +async function history(page: Page) { + await page.getByRole("tab", { name: "History" }).click(); + return page.getByRole("main").getByRole("listitem"); +} + +test.describe("console users", () => { + test("search finds a fresh account and its page has four tabs", async ({ adminPage: page }) => { + const person = await target(); + await page.goto("/users"); + await page.getByRole("textbox", { name: "Search email, name, or ID…" }).fill(person.email); + const main = page.getByRole("main"); + const row = main.getByRole("link", { name: new RegExp(escapeRegExp(person.email)) }); + await expect(row).toHaveCount(1); + await expect(row).toContainText(person.name); + await expect(row).toContainText("active"); + + // The search is in the URL, so a reload runs it fresh; every user row says when they joined, + // and this account's is the only one left. + await page.reload(); + await expect(row).toBeVisible(); + await expect(main.getByRole("link", { name: / · joined / })).toHaveCount(1); + await row.click(); + await expect(page).toHaveURL(new RegExp(`/users/${person.id}$`)); + await expect(main.getByRole("heading", { name: person.name, level: 1 })).toBeVisible(); + await expect(main.getByText(person.email).first()).toBeVisible(); + for (const name of ["Overview", "Tasks", "Access", "History"]) + await expect(main.getByRole("tab", { name })).toBeVisible(); + await expect(main.getByRole("heading", { name: "Status & actions" })).toBeVisible(); + await expect(main.getByText("1 live session · 0 API keys")).toBeVisible(); + + await main.getByRole("tab", { name: "Tasks" }).click(); + await expect(page).toHaveURL(/tab=tasks/); + await expect(main.getByText("No tasks match the current filters.")).toBeVisible(); + await main.getByRole("tab", { name: "History" }).click(); + await expect(main.getByText("No admin actions on this account yet")).toBeVisible(); + }); + + test("suspend locks the person out, and unsuspend lets them sign in again", async ({ + adminPage: page, + }) => { + const person = await target(); + await page.goto(`/users/${person.id}`); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Suspend" }).click(); + + const dialog = page.getByRole("dialog", { name: `Suspend ${person.email}?` }); + const confirm = dialog.getByRole("button", { name: "Suspend" }); + // The reason is the audit row's whole point: no reason, no suspension. + await expect(confirm).toBeDisabled(); + await dialog.getByRole("textbox", { name: "Reason" }).fill("Card testing from this account"); + await confirm.click(); + await expect(toast(page, "Suspended.")).toBeVisible(); + await expect(dialog).toBeHidden(); + await expect(main.getByText("suspended", { exact: true })).toBeVisible(); + await expect(main.getByRole("button", { name: "Unsuspend" })).toBeVisible(); + + // Locked out: the session they had is dead, and the password no longer opens a new one. + expect(await statusOf(person.token)).toBe(401); + await expect(signIn(person)).rejects.toMatchObject({ status: 403 }); + + // The status chips slice the list by it. + await page.goto(`/users?q=${encodeURIComponent(person.email)}`); + const row = main.getByRole("link", { name: new RegExp(escapeRegExp(person.email)) }); + await expect(row).toContainText("suspended"); + await main.getByRole("button", { name: "Suspended", exact: true }).click(); + await expect(page).toHaveURL(/status=suspended/); + await expect(row).toBeVisible(); + await main.getByRole("button", { name: "Active", exact: true }).click(); + await expect(main.getByText(`No matches for “${person.email}”`)).toBeVisible(); + await main.getByRole("button", { name: "All", exact: true }).click(); + await expect(row).toBeVisible(); + + await row.click(); + await main.getByRole("button", { name: "Unsuspend" }).click(); + const unsuspend = page.getByRole("alertdialog", { name: `Unsuspend ${person.email}?` }); + await unsuspend.getByRole("button", { name: "Unsuspend" }).click(); + await expect(toast(page, "Unsuspended.")).toBeVisible(); + await expect(main.getByText("active", { exact: true })).toBeVisible(); + await expect(main.getByRole("button", { name: "Suspend" })).toBeVisible(); + // Back in, with a new sign-in; the session suspension killed stays dead. + const fresh = await signIn(person); + expect(await statusOf(fresh.token)).toBe(200); + expect(await statusOf(person.token)).toBe(401); + + const rows = await history(page); + await expect(rows.filter({ hasText: "user.suspend" })).toContainText( + "Card testing from this account", + ); + await expect(rows.filter({ hasText: "user.unsuspend" })).toHaveCount(1); + }); + + test("grants the console to an account and takes it back", async ({ adminPage: page, seed }) => { + const person = await target(); + try { + await page.goto(`/users/${person.id}`); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Grant admin" }).click(); + const grant = page.getByRole("alertdialog", { name: `Make ${person.email} an admin?` }); + await expect(grant).toContainText("Admins see every user, task, and ledger row."); + await grant.getByRole("button", { name: "Grant admin" }).click(); + await expect(toast(page, "Admin granted.")).toBeVisible(); + await expect(main.getByText("admin", { exact: true })).toBeVisible(); + const granted = await call<{ is_admin: boolean }>("/auth/me", { token: person.token }); + expect(granted.is_admin).toBe(true); + + await main.getByRole("button", { name: "Revoke admin" }).click(); + const revoke = page.getByRole("alertdialog", { name: `Revoke admin from ${person.email}?` }); + await revoke.getByRole("button", { name: "Revoke admin" }).click(); + await expect(toast(page, "Admin revoked.")).toBeVisible(); + await expect(main.getByRole("button", { name: "Grant admin" })).toBeVisible(); + await expect(main.getByText("admin", { exact: true })).toHaveCount(0); + const revoked = await call<{ is_admin: boolean }>("/auth/me", { token: person.token }); + expect(revoked.is_admin).toBe(false); + + const rows = await history(page); + await expect(rows.filter({ hasText: "admin.grant" })).toHaveCount(1); + await expect(rows.filter({ hasText: "admin.revoke" })).toHaveCount(1); + } finally { + // A failed run must not leave a stray operator behind. + await call(`/admin/users/${person.id}/revoke-admin`, { + token: seed.admin!.token, + body: {}, + }).catch(() => undefined); + } + }); + + test("sign out everywhere ends every session and API key", async ({ adminPage: page }) => { + const person = await target(); + const second = await signIn(person); + const key = await call<{ key: string }>("/auth/api-keys", { + token: person.token, + body: { name: "deploy bot" }, + }); + expect(await statusOf(key.key)).toBe(200); + + await page.goto(`/users/${person.id}`); + const main = page.getByRole("main"); + await expect(main.getByText("2 live sessions · 1 API key")).toBeVisible(); + await main.getByRole("button", { name: "Sign out everywhere" }).click(); + const dialog = page.getByRole("alertdialog", { + name: `Revoke every credential for ${person.email}?`, + }); + await dialog.getByRole("button", { name: "Sign out everywhere" }).click(); + await expect(toast(page, "Revoked 2 sessions and 1 API key.")).toBeVisible(); + await expect(main.getByText("0 live sessions · 0 API keys")).toBeVisible(); + + for (const token of [person.token, second.token, key.key]) + expect(await statusOf(token)).toBe(401); + const rows = await history(page); + await expect(rows.filter({ hasText: "user.revoke_sessions" })).toHaveCount(1); + }); + + test("the Access tab revokes one session and one API key", async ({ adminPage: page }) => { + const person = await target(); + const second = await signIn(person); + const keyName = `ci key ${stamp()}`; + const key = await call<{ key: string }>("/auth/api-keys", { + token: person.token, + body: { name: keyName }, + }); + + await page.goto(`/users/${person.id}?tab=access`); + const main = page.getByRole("main"); + const sessions = main.getByRole("list").filter({ hasText: "signed in" }).getByRole("listitem"); + await expect(sessions).toHaveCount(2); + await expect(sessions.filter({ hasText: "live" })).toHaveCount(2); + + await sessions.first().getByRole("button", { name: "Revoke" }).click(); + const one = page.getByRole("alertdialog", { name: "Revoke this session?" }); + await one.getByRole("button", { name: "Revoke" }).click(); + await expect(toast(page, "Session revoked.")).toBeVisible(); + await expect(sessions.filter({ hasText: "revoked" })).toHaveCount(1); + await expect(sessions.getByRole("button", { name: "Revoke" })).toHaveCount(1); + // Exactly one of the two sessions ended; the other still works. + const alive = [await statusOf(person.token), await statusOf(second.token)].sort(); + expect(alive).toEqual([200, 401]); + + const keyRow = main.getByRole("listitem").filter({ hasText: keyName }); + await expect(keyRow).toContainText("never used"); + await keyRow.getByRole("button", { name: "Revoke" }).click(); + const revokeKey = page.getByRole("alertdialog", { name: `Revoke the key “${keyName}”?` }); + await revokeKey.getByRole("button", { name: "Revoke" }).click(); + await expect(toast(page, "API key revoked.")).toBeVisible(); + await expect(keyRow).toContainText("revoked"); + await expect(keyRow.getByRole("button", { name: "Revoke" })).toHaveCount(0); + expect(await statusOf(key.key)).toBe(401); + + // The overview's counts follow the revokes. + await page.reload(); + await main.getByRole("tab", { name: "Overview" }).click(); + await expect(main.getByText("1 live session · 0 API keys")).toBeVisible(); + + const rows = await history(page); + await expect(rows.filter({ hasText: "user.revoke_session" })).toHaveCount(1); + await expect(rows.filter({ hasText: "user.revoke_api_key" })).toHaveCount(1); + }); +}); diff --git a/web/e2e/admin/workspaces-projects.spec.ts b/web/e2e/admin/workspaces-projects.spec.ts new file mode 100644 index 0000000..68204d4 --- /dev/null +++ b/web/e2e/admin/workspaces-projects.spec.ts @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { signUp } from "../support/accounts"; +import { call, createProject, stamp } from "../support/api"; +import { escapeRegExp, expect, test } from "../fixtures"; + +// The tenants and the folders inside them, observed read-only: a workspace's standing and a +// project's facts, members and tasks. Each flow signs up its own person, whose stamped name makes +// their workspace's row the only one of its kind in a list every run shares. + +test.describe("console workspaces", () => { + test("lists a fresh workspace and opens its standing", async ({ adminPage: page }) => { + const person = await signUp("e2e-admin-ws", { name: `Wren Space ${stamp()}` }); + const workspace = person.workspace; + await page.goto("/workspaces"); + const main = page.getByRole("main"); + // Newest first, and this one was made a moment ago, so it is on the first page. + const row = main.getByRole("link", { name: new RegExp(`^${escapeRegExp(workspace.name)} `) }); + await expect(row).toBeVisible(); + await expect(row).toContainText("1 member"); + await expect(row).toContainText("Personal"); + await expect(row).toContainText("active"); + + await row.click(); + await expect(page).toHaveURL(new RegExp(`/workspaces/${workspace.id}$`)); + await expect(main.getByRole("heading", { name: workspace.name, level: 1 })).toBeVisible(); + const standing = main.getByRole("paragraph").filter({ hasText: "created" }); + await expect(standing).toContainText("Personal"); + await expect(standing).toContainText("active"); + await expect(main.getByRole("heading", { name: "Standing", level: 2 })).toBeVisible(); + await expect(main.getByText(/Members\s*1/)).toBeVisible(); + await expect(main.getByRole("heading", { name: "History", level: 2 })).toBeVisible(); + await expect(main.getByText("No operator actions on this workspace yet")).toBeVisible(); + + await main + .getByRole("navigation", { name: "Breadcrumb" }) + .getByRole("link", { name: "Workspaces" }) + .click(); + await expect(page).toHaveURL(/\/workspaces$/); + }); +}); + +test.describe("console projects", () => { + test("search finds a fresh project and its tabs show facts, members and tasks", async ({ + adminPage: page, + }) => { + const owner = await signUp("e2e-admin-projects", { name: `Otto Owner ${stamp()}` }); + const project = await createProject(owner.token, `Atlas ${stamp()}`); + // A held task filed in the project: a routine fired with posture "hold" mints a real task + // that no worker plans or runs. + const goal = `Inventory the tide pools ${stamp()}`; + const routine = await call<{ id: string }>("/routines", { + token: owner.token, + body: { + name: `Held ${stamp()}`, + instruction: goal, + schedule: { cron: "0 9 1 1 *", timezone: "UTC" }, + posture: "hold", + project_id: project.id, + }, + }); + const fired = await call<{ task_id: string }>(`/routines/${routine.id}/fire`, { + token: owner.token, + body: {}, + }); + const task = await call<{ title: string }>(`/tasks/${fired.task_id}`, { token: owner.token }); + + await page.goto("/projects"); + const search = page.getByRole("textbox", { name: "Search project name or ID…" }); + await search.fill(project.name); + const main = page.getByRole("main"); + // Every project row says when it was made; once the search has landed (the box debounces), + // this project's row is the only one. + const rows = main.getByRole("link", { name: / · created / }); + const row = main.getByRole("link", { name: new RegExp(`^${escapeRegExp(project.name)} `) }); + await expect(row).toHaveCount(1); + await expect(rows).toHaveCount(1); + await expect(row).toContainText(owner.email); + await expect(row).toContainText("1 task"); + // The id finds it too: the search rides the URL, so a reload runs it fresh. + await search.fill(project.id); + await expect(page).toHaveURL(new RegExp(`q=${project.id}`)); + await page.reload(); + await expect(search).toHaveValue(project.id); + await expect(row).toHaveCount(1); + await expect(rows).toHaveCount(1); + await search.fill(`no such project ${stamp()}`); + await expect(main.getByText(/No matches for/)).toBeVisible(); + await search.fill(project.name); + + await row.click(); + await expect(page).toHaveURL(new RegExp(`/projects/${project.id}$`)); + await expect(main.getByRole("heading", { name: project.name, level: 1 })).toBeVisible(); + await expect(main.getByRole("tab", { name: "Overview", selected: true })).toBeVisible(); + await expect(main.getByRole("heading", { name: "Facts", level: 2 })).toBeVisible(); + const facts = main.getByRole("listitem"); + await expect(facts.filter({ hasText: /^Tasks/ })).toContainText("1 task"); + await expect(facts.filter({ hasText: /^Spend this month/ })).toContainText("no budget set"); + + await main.getByRole("tab", { name: "Tasks" }).click(); + await expect(page).toHaveURL(/tab=tasks/); + const taskRow = main.getByRole("listitem").filter({ hasText: task.title }); + await expect(taskRow).toContainText("· held"); + + await main.getByRole("tab", { name: "Members" }).click(); + await expect(page).toHaveURL(/tab=members/); + const ownerRow = main.getByRole("listitem").filter({ hasText: "Owner" }); + await expect(ownerRow).toContainText(owner.name); + await ownerRow.getByRole("link", { name: owner.email }).click(); + await expect(page).toHaveURL(new RegExp(`/users/${owner.id}$`)); + await expect(main.getByRole("heading", { name: owner.name, level: 1 })).toBeVisible(); + }); +}); diff --git a/web/e2e/allowed-sites.spec.ts b/web/e2e/allowed-sites.spec.ts new file mode 100644 index 0000000..8dcd457 --- /dev/null +++ b/web/e2e/allowed-sites.spec.ts @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, knownBug, test } from "./fixtures"; + +// Allowed sites: the hosts the computer's browser opens without asking. A fresh account starts +// with none, and every change is the server's (a reload reads it back). +test.describe("allowed sites", () => { + test("adds a host, keeps it, and revokes it", async ({ accountPage: page }) => { + await page.goto("/allowed-sites"); + await expect(page.getByText("No always-allowed sites.")).toBeVisible(); + + const host = page.getByRole("textbox", { name: "Host" }); + const allow = page.getByRole("button", { name: "Always allow" }); + await expect(allow).toBeDisabled(); + await host.fill("docs.example.org"); + await allow.click(); + + const main = page.getByRole("main"); + await expect(main.getByText("docs.example.org")).toBeVisible(); + await expect(main.getByText("added here")).toBeVisible(); + await expect(host).toHaveValue(""); + + await page.reload(); + await expect(main.getByText("docs.example.org")).toBeVisible(); + await main.getByRole("button", { name: "Revoke" }).click(); + await expect(page.getByText("No always-allowed sites.")).toBeVisible(); + await page.reload(); + await expect(page.getByText("No always-allowed sites.")).toBeVisible(); + }); + + test("refuses what is not a public host name", async ({ accountPage: page }) => { + await page.goto("/allowed-sites"); + const host = page.getByRole("textbox", { name: "Host" }); + const main = page.getByRole("main"); + // The refusal is the server's reason, inline beside the field, and nothing is added. + for (const [typed, reason] of [ + ["localhost", /localhost is never askable/], + ["https://docs.example.org/page", /a host, not a URL/], + ["*.example.org", /wildcards are not allowed/], + ] as const) { + await host.fill(typed); + await page.getByRole("button", { name: "Always allow" }).click(); + await expect(main.getByText(reason)).toBeVisible(); + } + await expect(page.getByText("No always-allowed sites.")).toBeVisible(); + }); + + test("adding a host that is already allowed lists it once", async ({ accountPage: page }) => { + knownBug( + "allowed-sites/route.tsx prepends the row the API returns even when the host was already " + + "allowed (the API answers with the existing row), so the host shows twice until a reload", + ); + await page.goto("/allowed-sites"); + const host = page.getByRole("textbox", { name: "Host" }); + for (let i = 0; i < 2; i++) { + await host.fill("status.example.org"); + await page.getByRole("button", { name: "Always allow" }).click(); + await expect(host).toHaveValue(""); + } + await expect(page.getByRole("main").getByText("status.example.org")).toHaveCount(1); + }); +}); diff --git a/web/e2e/bots-configure.spec.ts b/web/e2e/bots-configure.spec.ts new file mode 100644 index 0000000..f5a555c --- /dev/null +++ b/web/e2e/bots-configure.spec.ts @@ -0,0 +1,258 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, knownBug, test, toast } from "./fixtures"; +import { createBot, stamp } from "./support/api"; + +// Bots: the messenger's list and the Configure tab. Every bot here is a draft with written +// instructions, so nothing asks a model to draft them, and nothing tests evals or publishes. +test.describe("bots: create and configure", () => { + test("creates a draft bot from the empty list", async ({ accountPage: page }) => { + const name = `desk-${stamp()}`; + await page.goto("/bots"); + const main = page.getByRole("main"); + await expect(main.getByText("No bots yet")).toBeVisible(); + await expect(main.getByText("0 bots · 0 pinned to sidebar")).toBeVisible(); + await expect(main.getByText("Pick a bot")).toBeVisible(); + + await main.getByRole("button", { name: "New bot" }).click(); + const dialog = page.getByRole("dialog", { name: "New bot" }); + const create = dialog.getByRole("button", { name: "Create bot" }); + await expect(create).toBeDisabled(); + // Instructions go in before the name: with them written, the offer to have a model draft + // them is gone, so Create can never start the drafter. + await dialog + .getByRole("textbox", { name: "Instructions (optional)" }) + .fill("Review vendor terms in one short paragraph."); + await expect( + dialog.getByRole("checkbox", { name: "Write instructions for me after creating" }), + ).toHaveCount(0); + await dialog.getByRole("textbox", { name: "Name", exact: true }).fill(name); + await expect(create).toBeEnabled(); + + await dialog.getByRole("button", { name: "Advanced" }).click(); + await dialog + .getByRole("textbox", { name: "What does this bot do?" }) + .fill("Reviews vendor contracts"); + await dialog + .getByRole("textbox", { name: "When should it step in?" }) + .fill("a vendor sends new terms"); + await dialog.getByRole("textbox", { name: "What should it refuse?" }).fill("legal advice"); + await expect(dialog.getByRole("textbox", { name: "A goal it should win" })).toBeVisible(); + await create.click(); + + await expect(toast(page, `${name} created as a draft.`)).toBeVisible(); + await expect(page).toHaveURL(new RegExp(`/bots/${name}\\?tab=configure$`)); + await expect(main.getByRole("heading", { name, level: 2 })).toBeVisible(); + await expect(main.getByText(/^draft\s+v1$/)).toBeVisible(); + await expect(main.getByText("evals untested", { exact: true })).toBeVisible(); + await expect(main.getByText("1 bot · 0 pinned to sidebar")).toBeVisible(); + // The routing triple composes the sentence the selector reads; the header shows its job. + await expect(main.getByText("Reviews vendor contracts.", { exact: true })).toBeVisible(); + await expect(main.getByRole("textbox", { name: "What this bot does" })).toHaveValue( + "Reviews vendor contracts", + ); + await expect( + main.getByText(/Routes as: .Reviews vendor contracts\. Load when a vendor sends new terms\./), + ).toBeVisible(); + // Publishing waits for green evals: the evals are offered, Publish is not. + await expect(main.getByRole("button", { name: "Test evals" })).toBeVisible(); + await expect(main.getByRole("button", { name: /^Publish/ })).toHaveCount(0); + + await page.reload(); + await expect(main.getByRole("heading", { name, level: 2 })).toBeVisible(); + await expect(main.getByRole("textbox", { name: "Bot instructions" })).toHaveValue( + "Review vendor terms in one short paragraph.", + ); + }); + + test("refuses a reserved name and a name that names a model", async ({ accountPage: page }) => { + await page.goto("/bots"); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "New bot" }).click(); + const dialog = page.getByRole("dialog", { name: "New bot" }); + await dialog.getByRole("textbox", { name: "Instructions (optional)" }).fill("Answer briefly."); + const nameBox = dialog.getByRole("textbox", { name: "Name", exact: true }); + for (const [typed, reason] of [ + ["assistant", /'assistant' is reserved for Prismoid's own agents/], + ["claude-helper", /'claude-helper' names a model\. A bot is a role/], + ] as const) { + await nameBox.fill(typed); + await dialog.getByRole("button", { name: "Create bot" }).click(); + await expect(page.getByRole("alert").filter({ hasText: reason })).toBeVisible(); + // The dialog stays open with what was typed, so the person can fix the name in place. + await expect(nameBox).toHaveValue(typed); + } + await dialog.getByRole("button", { name: "Close" }).click(); + await expect(main.getByText("No bots yet")).toBeVisible(); + await page.reload(); + await expect(main.getByText("0 bots · 0 pinned to sidebar")).toBeVisible(); + }); + + test("saves the title and the work dials, and keeps them", async ({ + accountPage: page, + account, + }) => { + const { name } = await createBot(account.token, { name: `dials-${stamp()}` }); + await page.goto(`/bots/${name}?tab=configure`); + const main = page.getByRole("main"); + + await main.getByRole("textbox", { name: "Bot title" }).fill("Contracts desk"); + const save = main.getByRole("button", { name: "Save", exact: true }); + await save.click(); + await expect(toast(page, "Title saved.")).toBeVisible(); + // Saved means clean: the Save goes away, so the work dials' Save below is the only one. + await expect(save).toHaveCount(0); + await expect(main.getByText("Contracts desk", { exact: true })).toBeVisible(); + + const ask = main.getByRole("radio", { name: /^Ask/ }); + const oneChat = main.getByRole("radio", { name: /^One chat/ }); + const cap = main.getByRole("textbox", { name: "Cap per task in dollars" }); + await expect(main.getByRole("radio", { name: /^Auto/ })).toHaveAttribute( + "aria-checked", + "true", + ); + await expect(main.getByRole("radio", { name: /^Many chats/ })).toHaveAttribute( + "aria-checked", + "true", + ); + await ask.click(); + await oneChat.click(); + await cap.fill("five"); + await save.click(); + await expect( + page.getByRole("alert").filter({ hasText: "The cap is dollars per task - a number." }), + ).toBeVisible(); + await cap.fill("7.5"); + await save.click(); + await expect(toast(page, "Work dials saved.")).toBeVisible(); + await expect(cap).toHaveValue("7.50"); + await expect(save).toHaveCount(0); + + await page.reload(); + await expect(main.getByRole("textbox", { name: "Bot title" })).toHaveValue("Contracts desk"); + await expect(ask).toHaveAttribute("aria-checked", "true"); + await expect(oneChat).toHaveAttribute("aria-checked", "true"); + await expect(cap).toHaveValue("7.50"); + }); + + test("saving the instructions mints draft v2", async ({ accountPage: page, account }) => { + const { name } = await createBot(account.token, { name: `versions-${stamp()}` }); + await page.goto(`/bots/${name}?tab=configure`); + const main = page.getByRole("main"); + await expect(main.getByText(/^draft\s+v1$/)).toBeVisible(); + + const instructions = main.getByRole("textbox", { name: "Bot instructions" }); + await instructions.fill("Answer in two short sentences, plainly."); + await main.getByRole("button", { name: "Save as draft v2" }).click(); + await expect(toast(page, "Saved as draft v2.")).toBeVisible(); + await expect(main.getByText(/^draft\s+v2$/)).toBeVisible(); + await expect(main.getByRole("button", { name: /^Save as draft/ })).toHaveCount(0); + await expect(main.getByRole("listitem").filter({ hasText: /^v2/ })).toBeVisible(); + await expect(main.getByRole("button", { name: /^Publish/ })).toHaveCount(0); + + await page.reload(); + await expect(main.getByText(/^draft\s+v2$/)).toBeVisible(); + await expect(instructions).toHaveValue("Answer in two short sentences, plainly."); + }); + + test("pins a bot to the sidebar and unpins it", async ({ accountPage: page, account }) => { + const { name } = await createBot(account.token, { name: `pinned-${stamp()}` }); + await page.goto(`/bots/${name}`); + const main = page.getByRole("main"); + // The sidebar's link is named by the bot alone; the list row's link also names its pin. + const sidebarLink = page.getByRole("link", { name, exact: true }); + await expect(sidebarLink).toHaveCount(0); + + await main.getByRole("button", { name: `Pin ${name} to the sidebar` }).click(); + await expect(sidebarLink).toBeVisible(); + await expect(main.getByText("1 bot · 1 pinned to sidebar")).toBeVisible(); + await page.reload(); + await expect(sidebarLink).toBeVisible(); + + await main.getByRole("button", { name: `Unpin ${name} from the sidebar` }).click(); + await expect(sidebarLink).toHaveCount(0); + await expect(main.getByText("1 bot · 0 pinned to sidebar")).toBeVisible(); + await page.reload(); + await expect(main.getByRole("button", { name: `Pin ${name} to the sidebar` })).toBeVisible(); + await expect(sidebarLink).toHaveCount(0); + }); + + test("changes the bot's face and keeps it", async ({ accountPage: page, account }) => { + const { name } = await createBot(account.token, { name: `face-${stamp()}` }); + await page.goto(`/bots/${name}`); + const face = page.getByRole("button", { name: "Change this bot's face" }); + // Toasts are dialogs too: the picker is the one holding the colour row. + const picker = page + .getByRole("dialog") + .filter({ has: page.getByRole("radiogroup", { name: "Icon color" }) }); + const patched = () => + page.waitForResponse( + (r) => r.url().includes(`/v1/bots/${name}`) && r.request().method() === "PATCH" && r.ok(), + ); + + await face.click(); + const rocket = picker.getByRole("button", { name: "rocket", exact: true }); + await expect(rocket).toHaveAttribute("aria-pressed", "false"); + await Promise.all([patched(), rocket.click()]); + await expect(rocket).toHaveAttribute("aria-pressed", "true"); + const hue = picker.getByRole("radio", { name: "Color 3" }); + await Promise.all([patched(), hue.click()]); + await expect(hue).toHaveAttribute("aria-checked", "true"); + + await page.reload(); + await face.click(); + await expect(rocket).toHaveAttribute("aria-pressed", "true"); + await expect(hue).toHaveAttribute("aria-checked", "true"); + await expect(picker.getByRole("button", { name: "Reset" })).toBeVisible(); + }); + + test("search narrows the list", async ({ accountPage: page, account }) => { + const tag = stamp(); + await createBot(account.token, { name: `alpha-${tag}` }); + await createBot(account.token, { name: `beta-${tag}` }); + await page.goto("/bots"); + const main = page.getByRole("main"); + await expect(main.getByText("2 bots · 0 pinned to sidebar")).toBeVisible(); + + const search = main.getByRole("textbox", { name: "Search bots…" }); + await search.fill("beta"); + await expect(main.getByRole("link", { name: new RegExp(`^beta-${tag}`) })).toBeVisible(); + await expect(main.getByRole("link", { name: new RegExp(`^alpha-${tag}`) })).toHaveCount(0); + await expect(main.getByText("1 bot · 0 pinned to sidebar")).toBeVisible(); + + await search.fill("no-such-bot"); + await expect(main.getByText("No matches for “no-such-bot”")).toBeVisible(); + await search.fill(""); + await expect(main.getByText("2 bots · 0 pinned to sidebar")).toBeVisible(); + }); + + test("a search that hides the open bot keeps its pane and the unsaved edit", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/routes/bots/route.tsx:150 - the open bot is looked up in the search-filtered rows, " + + "so a search that excludes it swaps the pane for 'Pick a bot' and clearing the search " + + "remounts the pane, discarding unsaved Configure edits", + ); + const tag = stamp(); + const { name } = await createBot(account.token, { name: `open-${tag}` }); + await createBot(account.token, { name: `other-${tag}` }); + await page.goto(`/bots/${name}?tab=configure`); + const main = page.getByRole("main"); + const instructions = main.getByRole("textbox", { name: "Bot instructions" }); + await instructions.fill("Unsaved edit"); + + const search = main.getByRole("textbox", { name: "Search bots…" }); + await search.fill("other"); + await expect(main.getByRole("link", { name: new RegExp(`^other-${tag}`) })).toBeVisible(); + await expect(main.getByRole("link", { name: new RegExp(`^open-${tag}`) })).toHaveCount(0); + await search.fill(""); + await expect(main.getByRole("link", { name: new RegExp(`^open-${tag}`) })).toBeVisible(); + await expect(instructions).toHaveValue("Unsaved edit"); + }); +}); diff --git a/web/e2e/bots-tabs.spec.ts b/web/e2e/bots-tabs.spec.ts new file mode 100644 index 0000000..f7cb607 --- /dev/null +++ b/web/e2e/bots-tabs.spec.ts @@ -0,0 +1,263 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, knownBug, test, toast } from "./fixtures"; +import { ApiError, call, createBot, stamp } from "./support/api"; + +// A bot's tabs, everything that needs no model: the empty shelves, memory, the webhook door and +// the chat's threads. No message is ever typed into a chat: a sent line asks the bot to answer. + +/** A memory the bot keeps, added by hand through the API. */ +async function teach(token: string, bot: string, text: string): Promise { + await call("/memories", { token, body: { scope: "bot", bot_name: bot, kind: "fact", text } }); +} + +/** Reads a webhook channel's reply feed with its own token: the one thing the token opens. */ +async function readFeed(channelId: string, token: string): Promise { + try { + await call(`/channels/${channelId}/messages`, { token }); + return 200; + } catch (e) { + if (e instanceof ApiError) return e.status; + throw e; + } +} + +test.describe("bots: tabs", () => { + test("each tab opens from the rail and names its empty state", async ({ + accountPage: page, + account, + }) => { + const { name } = await createBot(account.token, { name: `shelves-${stamp()}` }); + await page.goto(`/bots/${name}`); + const main = page.getByRole("main"); + const tab = (label: string) => main.getByRole("tab", { name: label, exact: true }); + await expect(tab("Chat")).toHaveAttribute("aria-selected", "true"); + + await tab("Runs").click(); + await expect(page).toHaveURL(/\?tab=runs$/); + await expect(main.getByText("No runs yet")).toBeVisible(); + + await tab("Artifacts").click(); + await expect(page).toHaveURL(/\?tab=artifacts$/); + await expect(main.getByText("Nothing published yet")).toBeVisible(); + + await tab("Routines").click(); + await expect(page).toHaveURL(/\?tab=routines$/); + await expect(main.getByText("No standing work yet")).toBeVisible(); + await expect(main.getByRole("link", { name: "Open routines…" })).toHaveAttribute( + "href", + "/routines", + ); + + await tab("Access").click(); + await expect(page).toHaveURL(/\?tab=access$/); + await expect(main.getByRole("heading", { name: "Tools" })).toBeVisible(); + await expect(main.getByRole("listitem").filter({ hasText: "ask_user" })).toContainText( + "Ask you questions mid-task", + ); + await expect(main.getByText("No connectors declared")).toBeVisible(); + + // The tab rides the URL: a reload lands on the same tab. + await page.reload(); + await expect(tab("Access")).toHaveAttribute("aria-selected", "true"); + await tab("Chat").click(); + await expect(page).toHaveURL(new RegExp(`/bots/${name}$`)); + }); + + test("teaches a memory and finds it", async ({ accountPage: page, account }) => { + const { name } = await createBot(account.token, { name: `memo-${stamp()}` }); + await page.goto(`/bots/${name}?tab=memory`); + const main = page.getByRole("main"); + await expect(main.getByText("Nothing learned yet")).toBeVisible(); + + await main.getByRole("button", { name: "Add memory" }).click(); + const dialog = page.getByRole("dialog", { name: `Teach ${name} something` }); + const add = dialog.getByRole("button", { name: "Add memory" }); + await expect(add).toBeDisabled(); + await dialog.getByRole("textbox", { name: "Memory" }).fill("The Q3 workbook lives in finance."); + await dialog.getByRole("button", { name: "fact", exact: true }).click(); + await expect(dialog.getByRole("button", { name: "fact", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + await add.click(); + await expect(dialog).toBeHidden(); + + const row = main.getByRole("listitem").filter({ hasText: "The Q3 workbook lives in finance." }); + await expect(row).toContainText("Fact"); + await expect(row).toContainText("added by hand"); + await page.reload(); + await expect(row).toBeVisible(); + + const search = main.getByRole("textbox", { name: "Search memories…" }); + await search.fill("workbook"); + await expect(row).toBeVisible(); + await search.fill("payroll"); + await expect(main.getByText("No matches for “payroll”")).toBeVisible(); + await search.fill(""); + await expect(row).toBeVisible(); + }); + + test("edits a memory in place", async ({ accountPage: page, account }) => { + knownBug( + "backend/prismoid/db/models/memory.py:245 - updated_at's onupdate=func.now() leaves the " + + "attribute expired after the commit, so memory_out (api/serializers/memories.py:83) " + + "lazy-loads it outside the greenlet: PATCH /v1/memories/{id} saves, then answers 500 " + + "(MissingGreenlet) and the row stays in edit mode with 'Couldn't save the memory.'", + ); + const { name } = await createBot(account.token, { name: `memoedit-${stamp()}` }); + await teach(account.token, name, "The Q3 workbook lives in finance."); + await page.goto(`/bots/${name}?tab=memory`); + const main = page.getByRole("main"); + const row = main.getByRole("listitem").filter({ hasText: "The Q3 workbook lives in finance." }); + // The row's verbs show on hover. While it edits, the text sits in an input, so the row is + // found by its provenance line instead. + const editing = main.getByRole("listitem").filter({ hasText: "added by hand" }); + await row.hover(); + await row.getByRole("button", { name: "Edit" }).click(); + await editing.getByRole("textbox").fill("The Q3 workbook lives in the finance project."); + await editing.getByRole("button", { name: "Save" }).click(); + await expect( + main + .getByRole("listitem") + .filter({ hasText: "The Q3 workbook lives in the finance project." }), + ).toBeVisible(); + }); + + test("retires a memory", async ({ accountPage: page, account }) => { + knownBug( + "backend/prismoid/db/models/memory.py:245 - the same expired updated_at: POST " + + "/v1/memories/{id}/retire retires the row, then answers 500 (MissingGreenlet in " + + "memory_out), so the row stays listed with 'Couldn't retire the memory.' until a reload", + ); + const { name } = await createBot(account.token, { name: `memoretire-${stamp()}` }); + await teach(account.token, name, "Invoices go out on the first."); + await page.goto(`/bots/${name}?tab=memory`); + const main = page.getByRole("main"); + const row = main.getByRole("listitem").filter({ hasText: "Invoices go out on the first." }); + await row.hover(); + await row.getByRole("button", { name: "Retire" }).click(); + await expect(main.getByText("Nothing learned yet")).toBeVisible(); + }); + + test("mints a webhook door, disables, rotates and removes it", async ({ + accountPage: page, + account, + }) => { + const { name } = await createBot(account.token, { name: `door-${stamp()}` }); + await page.goto(`/bots/${name}?tab=channels`); + const main = page.getByRole("main"); + await expect(main.getByText("No doors yet")).toBeVisible(); + + await main.getByRole("button", { name: "Add webhook" }).click(); + await expect( + main.getByText("Token, shown once - store it where the caller lives:"), + ).toBeVisible(); + const token = main.getByRole("code").filter({ hasText: /^bc_/ }); + const first = (await token.textContent())!; + const howTo = main.getByText(/^POST \/v1\/channels\/[0-9a-f-]+\/messages/); + const channelId = (await howTo.textContent())!.match(/channels\/([0-9a-f-]+)\//)![1]; + // The token is real: it opens this channel's reply feed (a read, which asks nothing of the bot). + expect(await readFeed(channelId, first)).toBe(200); + + const row = main.getByRole("listitem").filter({ hasText: `${name} webhook` }); + await expect(row).toContainText("active"); + await row.getByRole("button", { name: "Disable" }).click(); + await expect(row).toContainText("disabled"); + await row.getByRole("button", { name: "Enable" }).click(); + await expect(row).toContainText("active"); + await page.reload(); + await expect(row).toContainText("active"); + // A reload forgets the token: it was shown once. + await expect( + main.getByText("Token, shown once - store it where the caller lives:"), + ).toHaveCount(0); + + await row.getByRole("button", { name: "Rotate the token" }).click(); + await expect(toast(page, "Rotated - the old token died this instant.")).toBeVisible(); + await expect(token).toBeVisible(); + const second = (await token.textContent())!; + expect(second).not.toBe(first); + expect(await readFeed(channelId, first)).toBe(401); + expect(await readFeed(channelId, second)).toBe(200); + + await row.getByRole("button", { name: "Remove the channel" }).click(); + await expect(toast(page, "Channel removed, ledger and all.")).toBeVisible(); + await expect(main.getByText("No doors yet")).toBeVisible(); + expect(await readFeed(channelId, second)).toBe(401); + await page.reload(); + await expect(main.getByText("No doors yet")).toBeVisible(); + }); + + test("removing a channel takes its token off the screen", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/routes/bots/channels-tab.tsx:84 - remove() reloads the rows but never clears " + + "`minted`, so 'Token, shown once' keeps showing the removed channel's dead token", + ); + const { name } = await createBot(account.token, { name: `deadtoken-${stamp()}` }); + await page.goto(`/bots/${name}?tab=channels`); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Add webhook" }).click(); + const panel = main.getByText("Token, shown once - store it where the caller lives:"); + await expect(panel).toBeVisible(); + await main.getByRole("button", { name: "Remove the channel" }).click(); + await expect(main.getByText("No doors yet")).toBeVisible(); + await expect(panel).toBeHidden(); + }); + + test("a many-chats bot starts a chat and a second one, without a message", async ({ + accountPage: page, + account, + }) => { + const { name } = await createBot(account.token, { name: `talker-${stamp()}` }); + await page.goto(`/bots/${name}`); + const main = page.getByRole("main"); + await expect(main.getByText(`No conversations with ${name} yet.`)).toBeVisible(); + + await main.getByRole("button", { name: "Start one" }).click(); + const message = main.getByRole("textbox", { name: `Message ${name}` }); + await expect(message).toBeVisible(); + await expect(main.getByText("Say what you need.")).toBeVisible(); + await expect(main.getByRole("button", { name: "Send" })).toBeDisabled(); + // One chat needs no list. + await expect(main.getByText("Chats", { exact: true })).toHaveCount(0); + + await main.getByRole("button", { name: "New chat" }).click(); + await expect(main.getByText("Chats", { exact: true })).toBeVisible(); + // Untitled chats are the rows titled so (the New button shares their accessible name). + await expect(main.getByTitle("Untitled")).toHaveCount(2); + await page.reload(); + await expect(main.getByTitle("Untitled")).toHaveCount(2); + await expect(message).toBeVisible(); + }); + + test("a one-chat bot opens straight into its chat", async ({ accountPage: page, account }) => { + const { name } = await createBot(account.token, { name: `single-${stamp()}` }); + await call(`/bots/${name}`, { + method: "PATCH", + token: account.token, + body: { threads: "one", clear_icon: false, clear_hue: false, clear_title: false }, + }); + await page.goto(`/bots/${name}`); + const main = page.getByRole("main"); + await expect(main.getByRole("textbox", { name: `Message ${name}` })).toBeVisible(); + await expect(main.getByText(`No conversations with ${name} yet.`)).toHaveCount(0); + await expect(main.getByRole("button", { name: "New chat" })).toHaveCount(0); + await page.reload(); + await expect(main.getByRole("textbox", { name: `Message ${name}` })).toBeVisible(); + await expect(main.getByTitle("Untitled")).toHaveCount(0); + }); + + test("a template link that leads nowhere says so, signed out", async ({ page }) => { + await page.goto("/t/bots/bt_doesnotexist"); + await expect(page.getByText("This template is gone")).toBeVisible(); + await expect(page.getByText(/The link was unpublished, or it never existed/)).toBeVisible(); + }); +}); diff --git a/web/e2e/connectors.spec.ts b/web/e2e/connectors.spec.ts new file mode 100644 index 0000000..7515366 --- /dev/null +++ b/web/e2e/connectors.spec.ts @@ -0,0 +1,185 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, openSettings, test } from "./fixtures"; +import { stamp } from "./support/api"; + +// Connectors: the catalog and custom MCP servers. No flow here ever connects a catalog entry or +// retries a probe: those dial real hosts. A custom server lives under the .invalid name, which +// never resolves, so its one probe fails at once and nothing leaves the machine. +test.describe("connectors", () => { + test("the lens chips filter the catalog and ride the URL", async ({ accountPage: page }) => { + await page.goto("/connectors"); + const main = page.getByRole("main"); + const chip = (label: string) => main.getByRole("button", { name: label, exact: true }); + const notion = main.getByRole("button", { name: "Notion: available", exact: true }); + await expect(chip("All")).toHaveAttribute("aria-pressed", "true"); + await expect(notion).toBeVisible(); + + await chip("Connected").click(); + await expect(page).toHaveURL(/\?filter=connected$/); + await expect(chip("Connected")).toHaveAttribute("aria-pressed", "true"); + await expect(chip("All")).toHaveAttribute("aria-pressed", "false"); + // A fresh account has connected nothing. + await expect(main.getByText("No connectors here")).toBeVisible(); + await expect(notion).toHaveCount(0); + + await chip("Available").click(); + await expect(page).toHaveURL(/\?filter=available$/); + await expect(notion).toBeVisible(); + await page.reload(); + await expect(chip("Available")).toHaveAttribute("aria-pressed", "true"); + + await chip("All").click(); + await expect(page).toHaveURL(/\/connectors$/); + }); + + test("search and the category menu narrow the catalog", async ({ accountPage: page }) => { + await page.goto("/connectors"); + const main = page.getByRole("main"); + const card = (name: string) => + main.getByRole("button", { name: `${name}: available`, exact: true }); + const search = main.getByRole("textbox", { name: "Search connectors…" }); + + await search.fill("linear"); + await expect(card("Linear")).toBeVisible(); + await expect(card("Notion")).toHaveCount(0); + await search.fill("zzz-no-such-service"); + await expect(main.getByText("No matches for “zzz-no-such-service”")).toBeVisible(); + await search.fill(""); + await expect(card("Notion")).toBeVisible(); + + await main.getByRole("button", { name: "Filter by category" }).click(); + const menu = page.getByRole("menu", { name: "Filter by category" }); + await expect(menu.getByRole("menuitemradio", { name: "Any" })).toHaveAttribute( + "aria-checked", + "true", + ); + await menu.getByRole("menuitemradio", { name: "Databases" }).click(); + await expect(page).toHaveURL(/\?category=Databases$/); + await expect(card("Neon")).toBeVisible(); + await expect(card("Supabase")).toBeVisible(); + await expect(card("Notion")).toHaveCount(0); + // The trigger wears the category it filters by. + const trigger = main.getByRole("button", { name: "Filter by category" }); + await expect(trigger).toContainText("Databases"); + + await page.reload(); + await expect(card("Neon")).toBeVisible(); + await expect(card("Notion")).toHaveCount(0); + await trigger.click(); + await page.getByRole("menuitemradio", { name: "Any" }).click(); + await expect(page).toHaveURL(/\/connectors$/); + await expect(card("Notion")).toBeVisible(); + }); + + test("a catalog card opens its details", async ({ accountPage: page }) => { + await page.goto("/connectors"); + const main = page.getByRole("main"); + const card = main.getByRole("button", { name: "Notion: available", exact: true }); + // The card's name, not its centre: the card also holds the Connect button, which must + // never be pressed here. + await card.getByText("Notion", { exact: true }).click(); + await expect(page).toHaveURL(/\?connector=notion$/); + + const modal = page.getByRole("dialog", { name: "Notion" }); + await expect(modal.getByText("Notion · Productivity")).toBeVisible(); + await expect( + modal.getByText("Search, read, and create pages and databases in your Notion workspace."), + ).toBeVisible(); + await expect(modal.getByRole("button", { name: "Docs" })).toHaveAttribute( + "href", + /^https:\/\//, + ); + await modal.getByRole("button", { name: "Close" }).click(); + await expect(modal).toBeHidden(); + await expect(page).toHaveURL(/\/connectors$/); + + // The URL is the modal's address: opening it cold shows the same face. + await page.goto("/connectors?connector=notion"); + await expect(page.getByRole("dialog", { name: "Notion" })).toBeVisible(); + }); + + test("adds a custom server, disables and enables it, and removes it", async ({ + accountPage: page, + account, + }) => { + const tag = stamp(); + const name = `Custom ${tag}`; + await page.goto("/connectors"); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Custom connector" }).click(); + const dialog = page.getByRole("dialog", { name: "Add a custom connector" }); + const add = dialog.getByRole("button", { name: "Add", exact: true }); + await expect(add).toBeDisabled(); + await dialog + .getByRole("textbox", { name: "Server URL" }) + .fill(`https://mcp-${tag}.invalid/mcp`); + await dialog.getByRole("textbox", { name: "Name (optional)" }).fill(name); + await add.click(); + + // The add waits on its one probe, which fails on the unresolvable name: the row is kept, + // in error, and the modal opens on it. + const modal = page.getByRole("dialog", { name, exact: true }); + await expect(modal).toBeVisible({ timeout: 30_000 }); + await expect(page).toHaveURL(/\?connector=[0-9a-f-]+$/); + await expect(modal.getByText(`https://mcp-${tag}.invalid/mcp`)).toBeVisible(); + await expect(modal.getByText("Error", { exact: true })).toBeVisible(); + await expect(modal.getByText(/does not resolve/)).toBeVisible(); + + await modal.getByRole("button", { name: "Disable" }).click(); + await expect(modal.getByText("Disabled", { exact: true })).toBeVisible(); + await modal.getByRole("button", { name: "Enable" }).click(); + await expect(modal.getByText("Error", { exact: true })).toBeVisible(); + await expect(modal.getByRole("button", { name: "Disable" })).toBeVisible(); + await modal.getByRole("button", { name: "Close" }).click(); + + // Your own rows are what "Connected" lists, whatever their state. + const row = main.getByRole("button", { name: `${name}: Error`, exact: true }); + await main.getByRole("button", { name: "Connected", exact: true }).click(); + await expect(row).toBeVisible(); + await page.reload(); + await expect(row).toBeVisible(); + + // Settings keeps a roster of the same rows. + const settings = await openSettings(page, account.email); + await settings.getByRole("navigation").getByRole("button", { name: "Connectors" }).click(); + await expect(settings.getByRole("listitem").filter({ hasText: name })).toContainText("Error"); + await page.keyboard.press("Escape"); + await expect(settings).toBeHidden(); + + await row.getByText(name, { exact: true }).click(); + await modal.getByRole("button", { name: `Remove ${name}` }).click(); + await expect(modal).toBeHidden(); + await expect(main.getByText("No connectors here")).toBeVisible(); + await page.reload(); + await expect(main.getByText("No connectors here")).toBeVisible(); + }); + + test("refuses a server inside the network and adds nothing", async ({ accountPage: page }) => { + await page.goto("/connectors?filter=connected"); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Custom connector" }).click(); + const dialog = page.getByRole("dialog", { name: "Add a custom connector" }); + const url = dialog.getByRole("textbox", { name: "Server URL" }); + // The refusal is the server's reason, said where the person is; the dialog stays open. + // (Loopback is refused because this stack keeps the dev-only loopback setting off.) + for (const [typed, reason] of [ + ["https://10.0.0.1/mcp", "that address points inside the network, not at a service"], + ["https://127.0.0.1:9/mcp", "loopback MCP servers are a dev-only setting"], + ["http://127.0.0.1:9/mcp", /^MCP servers must be https/], + ] as const) { + await url.fill(typed); + await dialog.getByRole("button", { name: "Add", exact: true }).click(); + await expect(page.getByRole("alert").filter({ hasText: reason })).toBeVisible(); + await expect(url).toHaveValue(typed); + } + await dialog.getByRole("button", { name: "Close" }).click(); + await expect(main.getByText("No connectors here")).toBeVisible(); + await page.reload(); + await expect(main.getByText("No connectors here")).toBeVisible(); + }); +}); diff --git a/web/e2e/fixtures.ts b/web/e2e/fixtures.ts index d71a976..0b50aca 100644 --- a/web/e2e/fixtures.ts +++ b/web/e2e/fixtures.ts @@ -4,29 +4,45 @@ * See the LICENSE file for details. */ -// The flows' shared test object. `seed` is the account and task global-setup made; a test that -// asks for `signedInPage` starts with the seed's session already in localStorage, where the app -// keeps it, so only the sign-in flow itself drives the form. +// The flows' shared test object. +// - `seed` / `signedInPage`: the account and held task global-setup made, already signed in. For +// flows that only read, or whose edits later flows expect (the existing smoke flows). +// - `account` / `accountPage`: a NEW account for this test alone, signed in. Every flow that changes +// an account, asserts an empty state, or needs a clean slate takes these. +// - `adminPage`: the operator console, signed in as the seeded operator (console flows only). +// Only the sign-in flows drive the form; every other flow starts with the session already in +// localStorage, where the app keeps it. import { test as base, expect, type Page } from "@playwright/test"; +import { type Account, signUp, useSession } from "./support/accounts"; import { readSeed, type Seed } from "./seed"; -// The keys the app reads its session from (app/lib/storage.ts). -const TOKEN_KEY = "prismoid.token"; -const EXPIRES_KEY = "prismoid.expires"; - -export const test = base.extend<{ seed: Seed; signedInPage: Page }>({ +export const test = base.extend<{ + seed: Seed; + signedInPage: Page; + account: Account; + accountPage: Page; + adminPage: Page; +}>({ // Playwright reads a fixture's dependencies from its first argument: this one has none. seed: async ({}, use) => { await use(readSeed()); }, signedInPage: async ({ page, seed }, use) => { - await page.addInitScript( - ([tokenKey, expiresKey, token, expiresAt]) => { - localStorage.setItem(tokenKey, token); - localStorage.setItem(expiresKey, expiresAt); - }, - [TOKEN_KEY, EXPIRES_KEY, seed.token, seed.expiresAt] as const, - ); + await useSession(page, seed); + await use(page); + }, + account: async ({}, use, testInfo) => { + // The test's file name labels the address, so a stray account in a shared database says who made it. + const label = `e2e-${testInfo.titlePath[0].replace(/\.spec\.ts$/, "").replace(/[^a-z0-9]+/gi, "-")}`; + await use(await signUp(label.toLowerCase())); + }, + accountPage: async ({ page, account }, use) => { + await useSession(page, account); + await use(page); + }, + adminPage: async ({ page, seed }, use) => { + test.skip(!seed.admin, "no operator account: the run could not reach the stack's database"); + await useSession(page, seed.admin!); await use(page); }, }); @@ -37,3 +53,58 @@ export { expect }; export function composer(page: Page) { return page.getByRole("textbox", { name: /Describe what you need done/ }); } + +/** Text made safe to embed in a RegExp: accessible names are matched by pattern when they carry more. */ +export function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** The account menu's trigger in the sidebar: its name is the person's initials, name and email. */ +export function accountMenu(page: Page, email: string) { + return page.getByRole("button", { name: new RegExp(escapeRegExp(email)) }); +} + +/** + * A kit Section, by its heading. The section element carries no accessible name of its own, so it + * is the one place a flow finds a region by its tag: by the heading it holds. + */ +export function section(page: Page, title: string) { + return page + .locator("section") + .filter({ has: page.getByRole("heading", { name: title, exact: true }) }); +} + +/** Settings, opened from the account menu. */ +export async function openSettings(page: Page, email: string) { + await accountMenu(page, email).click(); + await page.getByRole("menuitem", { name: "Settings" }).click(); + return page.getByRole("dialog", { name: "Settings" }); +} + +/** + * Marks a flow that a known bug breaks: the flow asserts the right behaviour and is expected to fail + * until the bug is fixed, when Playwright reports it as an unexpected pass so the mark comes off. + * E2E_SHOW_BUGS=1 runs these as ordinary tests, to see each failure for what it is. + */ +export function knownBug(reason: string) { + test.info().annotations.push({ type: "bug", description: reason }); + test.fail(process.env.E2E_SHOW_BUGS !== "1", reason); +} + +/** Pick one value of one composer Options setting: the row opens its choices as a submenu beside it. */ +export async function chooseOption(page: Page, setting: string, value: string) { + await page.getByRole("button", { name: "Options" }).click(); + await page + .getByRole("menu", { name: "Options" }) + .getByRole("menuitem", { name: new RegExp(`^${escapeRegExp(setting)} `) }) + .click(); + await page + .getByRole("menu", { name: new RegExp(`^${escapeRegExp(setting)} `) }) + .getByRole("menuitemradio", { name: new RegExp(`^${escapeRegExp(value)}`) }) + .click(); +} + +/** A toast's text: toasts carry no stable role, so they are found by what they say. */ +export function toast(page: Page, text: string | RegExp) { + return page.getByRole("region", { name: "Notifications" }).getByText(text); +} diff --git a/web/e2e/global-setup.ts b/web/e2e/global-setup.ts index 80076f0..f816f18 100644 --- a/web/e2e/global-setup.ts +++ b/web/e2e/global-setup.ts @@ -4,61 +4,60 @@ * See the LICENSE file for details. */ -// Seeds what the flows read, through the API's own doors: a fresh account (a new email each run, -// so a rerun on the same database never collides) and one task record. The task comes from a -// routine fired with posture "hold": the fire mints an ordinary task that holds until a person -// sends a direction, so it is a real record that no worker ever plans or runs, and no model is -// called. -import { mkdirSync, writeFileSync } from "node:fs"; +// Seeds what the flows share, through the API's own doors: a fresh account (a new email each run, +// so a rerun on the same database never collides) with one held task, and an operator account for +// the console flows. The task comes from a routine fired with posture "hold": the fire mints an +// ordinary task that holds until a person sends a direction, so it is a real record that no worker +// ever plans or runs, and no model is called. The operator scope has no web door outside local +// mode, so it is granted the way an operator grants the first one, `prismoid admin bootstrap`, +// which needs the API's database URL (stack.sh exports it); without it the console flows skip. +import { execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; -import { API_URL, SEED_FILE, call, type Seed } from "./seed"; +import { fileURLToPath } from "node:url"; +import { signIn, signUp } from "./support/accounts"; +import { API_URL, createHeldTask } from "./support/api"; +import { SEED_FILE, type Seed } from "./seed"; -type Session = { token: string; expires_at: string }; -type Fired = { decision: string; task_id: string | null; detail: string }; +const BACKEND = fileURLToPath(new URL("../../backend", import.meta.url)); + +function bootstrapAdmin(email: string): boolean { + if (!process.env.PRISMOID_API_DATABASE_URL) return false; + const venv = `${BACKEND}/.venv/bin/prismoid`; + const [command, args] = existsSync(venv) + ? [venv, ["admin", "bootstrap", "--email", email, "--json"]] + : ["uv", ["run", "prismoid", "admin", "bootstrap", "--email", email, "--json"]]; + execFileSync(command, args, { cwd: BACKEND, stdio: "pipe" }); + return true; +} export default async function globalSetup(): Promise { const health = await fetch(`${API_URL}/healthz`).catch(() => null); if (!health?.ok) throw new Error(`no API at ${API_URL}: start one (just e2e boots its own)`); - const stamp = Date.now().toString(36); - const email = `e2e-${stamp}@example.com`; - const password = "correct horse battery staple"; - const name = "Ada Tester"; - const session = await call("/auth/signup", { - method: "POST", - body: { email, name, password }, - }); - const token = session.token; - + const account = await signUp("e2e"); const goal = "Summarize the tide pool field notes"; - const routine = await call<{ id: string; name: string }>("/routines", { - method: "POST", - token, - body: { - name: `Tide pools ${stamp}`, - instruction: goal, - // A When is required; once a year means the sweep never fires it during a run. - schedule: { cron: "0 9 1 1 *", timezone: "UTC" }, - posture: "hold", - }, - }); - const fired = await call(`/routines/${routine.id}/fire`, { - method: "POST", - token, - body: {}, - }); - if (fired.decision !== "held" || !fired.task_id) { - throw new Error(`the held fire did not mint a task: ${JSON.stringify(fired)}`); - } - const task = await call<{ title: string | null }>(`/tasks/${fired.task_id}`, { token }); + const task = await createHeldTask(account.token, goal); + + const operator = await signUp("e2e-operator", { name: "Olive Operator" }); + // One console session for the run: the login door counts sign-ins per account per minute. + const admin = bootstrapAdmin(operator.email) + ? { + email: operator.email, + password: operator.password, + name: operator.name, + ...(await signIn(operator)), + } + : null; const seed: Seed = { - email, - password, - name, - token, - expiresAt: session.expires_at, - task: { id: fired.task_id, title: task.title ?? goal, goal }, + email: account.email, + password: account.password, + name: account.name, + token: account.token, + expiresAt: account.expiresAt, + task: { id: task.id, title: task.title, goal }, + admin, }; mkdirSync(dirname(SEED_FILE), { recursive: true }); writeFileSync(SEED_FILE, JSON.stringify(seed, null, 2)); diff --git a/web/e2e/home.spec.ts b/web/e2e/home.spec.ts new file mode 100644 index 0000000..cb0b9dc --- /dev/null +++ b/web/e2e/home.spec.ts @@ -0,0 +1,320 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { chooseOption, composer, escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { call, createBot, createHeldTask, stamp } from "./support/api"; + +// The home composer. Sending with When set to Now starts a task that calls a model, so these flows +// never press Submit or Enter with a goal and When = Now: they set dials and read them back, and the +// only submits carry a schedule, which saves a routine instead of starting anything. + +type RoutineRow = { id: string; name: string; posture: string; trigger_kind: string }; +type Listing = { items: T[] }; + +/** + * A yearly schedule typed into the When panel, set while the box is still empty so no keypress in + * the panel can ever send a goal. Once a year keeps the sweep from firing the routine during a run. + */ +async function scheduleYearly(page: Page) { + await page.getByRole("button", { name: "Options" }).click(); + await page.getByRole("menuitem", { name: /^When / }).click(); + await page.getByRole("menuitem", { name: /^Custom schedule or event/ }).click(); + const cron = page.getByRole("textbox", { name: /cron/ }); + await cron.fill("0 9 1 1 *"); + await cron.press("Enter"); + await expect(page.getByRole("button", { name: "Clear schedule" })).toBeVisible(); +} + +/** Attach a small text file through the composer's own file chooser. */ +async function attachNotes(page: Page) { + await page.getByRole("button", { name: "Add files or capture" }).click(); + const chooser = page.waitForEvent("filechooser"); + await page.getByRole("menuitem", { name: "Attach files" }).click(); + await ( + await chooser + ).setFiles({ name: "notes.txt", mimeType: "text/plain", buffer: Buffer.from("hello") }); +} + +/** Submit a goal on a yearly schedule together with something a routine cannot carry. */ +async function submitRefused(page: Page, goal: string, extra: "fleet" | "attachment") { + await scheduleYearly(page); + if (extra === "fleet") await chooseOption(page, "Mode", "Fleet"); + else await attachNotes(page); + await composer(page).fill(goal); + await expect(composer(page)).toHaveValue(goal); + await expect(page.getByRole("button", { name: "Clear schedule" })).toBeVisible(); + await page.getByRole("button", { name: "Submit" }).click(); +} + +const FLEET_REFUSAL = "Routines run standard tasks. Switch the mode dial off fleet first."; +const ATTACHMENT_REFUSAL = /^Routines can't carry attachments yet/; + +test.describe("home composer", () => { + test("a fresh account lands on an empty composer with nothing recent", async ({ + accountPage: page, + }) => { + const listed = page.waitForResponse( + (r) => r.url().includes("/v1/tasks?pinned=false") && r.request().method() === "GET", + ); + await page.goto("/"); + await listed; + // The greeting rotates by time of day, so only its level is stable. + await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); + const submit = page.getByRole("button", { name: "Submit" }); + await expect(composer(page)).toBeFocused(); + await expect(submit).toBeDisabled(); + await composer(page).fill("Outline a reading list"); + await expect(submit).toBeEnabled(); + await composer(page).fill(""); + await expect(submit).toBeDisabled(); + // An account with no tasks keeps the landing pure: no Recent section and no show/hide chrome. + await expect(page.getByRole("heading", { name: "Recent" })).toHaveCount(0); + await expect(page.getByRole("button", { name: /Show recent|Hide/ })).toHaveCount(0); + }); + + test("Options settings show as pills that clear back to the defaults", async ({ + accountPage: page, + }) => { + await page.goto("/"); + const box = page.getByRole("group").filter({ has: composer(page) }); + + await chooseOption(page, "Size", "Brief"); + await expect(box.getByRole("combobox", { name: "Size", exact: true })).toHaveText(/Brief/); + await chooseOption(page, "Deliverable", "Document · PDF"); + await expect(box.getByRole("button", { name: "Deliverable", exact: true })).toHaveText( + /Document · PDF/, + ); + await chooseOption(page, "Clarifying questions", "Never"); + await expect(box.getByRole("combobox", { name: "Clarifying questions" })).toHaveText(/never/i); + await chooseOption(page, "Budget", "$5"); + await expect(box.getByRole("button", { name: /^Budget/ })).toHaveText(/\$5\.00/); + await chooseOption(page, "When", "Every day, 9:00"); + await expect(box.getByRole("button", { name: "When this runs" })).toBeVisible(); + await chooseOption(page, "Mode", "Fleet"); + await expect(box.getByRole("combobox", { name: "Mode", exact: true })).toHaveText(/Fleet/); + // A fleet delivers the chair's table, so the deliverable dial steps aside while it is on. + await expect(box.getByRole("button", { name: "Clear deliverable" })).toHaveCount(0); + await box.getByRole("button", { name: "Clear fleet mode" }).click(); + await expect(box.getByRole("button", { name: "Clear deliverable" })).toBeVisible(); + + for (const name of ["schedule", "size", "deliverable", "clarifying questions", "budget"]) { + await box.getByRole("button", { name: `Clear ${name}` }).click(); + await expect(box.getByRole("button", { name: `Clear ${name}` })).toHaveCount(0); + } + await page.getByRole("button", { name: "Options" }).click(); + const options = page.getByRole("menu", { name: "Options" }); + for (const row of [ + "When Now", + "Mode Standard", + "Size Auto", + "Deliverable Auto", + "Clarifying questions Auto", + "Budget No cap", + ]) + await expect(options.getByRole("menuitem", { name: row, exact: true })).toBeVisible(); + }); + + test("a custom budget takes a typed amount", async ({ accountPage: page }) => { + await page.goto("/"); + await page.getByRole("button", { name: "Options" }).click(); + await page.getByRole("menuitem", { name: /^Budget / }).click(); + await page.getByRole("menuitem", { name: "Custom amount…" }).click(); + const amount = page.getByRole("textbox", { name: "Spend cap in USD" }); + await amount.fill("3.5"); + await amount.press("Enter"); + const pill = page.getByRole("button", { name: /^Budget/ }); + await expect(pill).toHaveText(/\$3\.50/); + await page.getByRole("button", { name: "Clear budget" }).click(); + await expect(page.getByRole("button", { name: "Clear budget" })).toHaveCount(0); + }); + + test("the project picker creates a project inline and remembers it", async ({ + accountPage: page, + account, + }) => { + const name = `Desk ${stamp()}`; + await page.goto("/"); + const picker = page.getByRole("combobox", { name: "Project: where this task will live" }); + await picker.click(); + const popup = page.getByRole("dialog", { name: "Project" }); + await expect(popup.getByRole("option", { name: "No project" })).toBeVisible(); + await popup.getByRole("combobox", { name: "Search or create a project…" }).fill(name); + await popup.getByRole("option", { name: `Create “${name}”` }).click(); + + const chosen = page.getByRole("combobox", { name: `Project: ${name}` }); + await expect(chosen).toBeVisible(); + const projects = await call>("/projects", { token: account.token }); + expect(projects.items.map((p) => p.name)).toContain(name); + + // The last destination is the default next time, and "No project" puts the task back home. + await page.reload(); + await expect(chosen).toBeVisible(); + await chosen.click(); + await page + .getByRole("dialog", { name: "Project" }) + .getByRole("option", { name: "No project" }) + .click(); + await expect(picker).toBeVisible(); + }); + + test("Skills, Bot and Connectors rows pin, clear and link out", async ({ + accountPage: page, + account, + }) => { + // A draft bot is enough for the Bot row to offer it. + const bot = await createBot(account.token, { name: `scout-${stamp()}` }); + await page.goto("/"); + const box = page.getByRole("group").filter({ has: composer(page) }); + + await page.getByRole("button", { name: "Options" }).click(); + await page.getByRole("menuitem", { name: /^Skills / }).click(); + await page.getByRole("menuitemcheckbox", { name: "summarize", exact: true }).click(); + await expect(page.getByRole("menuitem", { name: "Skills 1 pinned" })).toBeVisible(); + await page.keyboard.press("Escape"); + await page.keyboard.press("Escape"); + await expect(box.getByRole("button", { name: "Skills", exact: true })).toHaveText(/1/); + await box.getByRole("button", { name: "Clear skills" }).click(); + await expect(box.getByRole("button", { name: "Clear skills" })).toHaveCount(0); + + await chooseOption(page, "Bot", `${bot.name} (draft)`); + await expect(box.getByRole("button", { name: `Bot: ${bot.name}` })).toBeVisible(); + await box.getByRole("button", { name: "Clear bot" }).click(); + await expect(box.getByRole("button", { name: `Bot: ${bot.name}` })).toHaveCount(0); + + // A fresh account has no connector to attach, so the row points at where one is added. + await page.getByRole("button", { name: "Options" }).click(); + await page.getByRole("menuitem", { name: "Connectors None" }).click(); + await page.getByRole("menuitem", { name: "Add connector…" }).click(); + await expect(page).toHaveURL(/\/connectors$/); + }); + + test("attaching a file shows a chip that removes it", async ({ accountPage: page }) => { + await page.goto("/"); + const submit = page.getByRole("button", { name: "Submit" }); + await attachNotes(page); + const box = page.getByRole("group").filter({ has: composer(page) }); + await expect(box.getByText("notes.txt")).toBeVisible(); + await box.getByRole("button", { name: "Remove" }).click(); + await expect(box.getByText("notes.txt")).toHaveCount(0); + await expect(submit).toBeDisabled(); + }); + + test("Recent lists the account's tasks and hides on request", async ({ + accountPage: page, + account, + }) => { + const task = await createHeldTask(account.token, "Sort the field notes"); + await page.goto("/"); + await expect(page.getByRole("heading", { name: "Recent" })).toBeVisible(); + const main = page.getByRole("main"); + await expect( + main.getByRole("link", { name: new RegExp(escapeRegExp(task.title)) }), + ).toBeVisible(); + + const hide = main.getByRole("button", { name: "Hide" }); + await expect(hide).toHaveAttribute("aria-expanded", "true"); + await hide.click(); + const show = main.getByRole("button", { name: "Show recent" }); + await expect(show).toHaveAttribute("aria-expanded", "false"); + await expect(page.getByRole("heading", { name: "Recent" })).toHaveCount(0); + // Hiding is a preference: it survives a reload. + await page.reload(); + await expect(show).toBeVisible(); + await show.click(); + await expect(page.getByRole("heading", { name: "Recent" })).toBeVisible(); + + await main.getByRole("link", { name: "View all" }).click(); + await expect(page).toHaveURL(/\/tasks$/); + }); +}); + +// Every routine a flow saves is retired after it, pass or fail, so no standing work outlives a run. +test.describe("a scheduled ask saves a routine", () => { + test.afterEach(async ({ account }) => { + const routines = await call>("/routines", { token: account.token }); + for (const r of routines.items) + await call(`/routines/${r.id}/retire`, { token: account.token, body: {} }); + }); + + test("submitting with a schedule saves a routine and starts no task", async ({ + accountPage: page, + account, + }) => { + const goal = `Summarize the week's notes ${stamp()}`; + await page.goto("/"); + await scheduleYearly(page); + await expect(page.getByRole("button", { name: "When this runs" })).toHaveText(/0 9 1 1 \*/); + await composer(page).fill(goal); + await expect(page.getByRole("button", { name: "Clear schedule" })).toBeVisible(); + await page.getByRole("button", { name: "Submit" }).click(); + + // The first fire is stated in the browser's time zone, so only the start of the toast is fixed. + await expect(toast(page, /^Routine saved - /).first()).toBeVisible(); + await expect(page).toHaveURL(/\/routines\?routine=[0-9a-f-]{36}$/); + const id = new URL(page.url()).searchParams.get("routine"); + const pane = page.getByRole("dialog", { name: "Routine" }); + await expect(pane.getByRole("heading", { name: goal })).toBeVisible(); + + const routines = await call>("/routines", { token: account.token }); + expect(routines.items).toHaveLength(1); + expect(routines.items[0]).toMatchObject({ id, name: goal, trigger_kind: "schedule" }); + test.info().annotations.push({ type: "posture", description: routines.items[0].posture }); + // Saved, not sent: the account still has no task at all. + const tasks = await call>("/tasks", { token: account.token }); + expect(tasks.items).toHaveLength(0); + + await page.goto("/routines"); + await expect( + page.getByRole("main").getByRole("button", { name: new RegExp(escapeRegExp(goal)) }), + ).toBeVisible(); + }); + + test("a schedule refuses fleet mode and attachments and saves nothing", async ({ + accountPage: page, + account, + }) => { + await page.goto("/"); + await submitRefused(page, "Compare three vendors", "fleet"); + await expect(toast(page, FLEET_REFUSAL)).toBeVisible(); + await expect(page).toHaveURL(/\/$/); + + await page.goto("/"); + await submitRefused(page, "Read the attached notes", "attachment"); + await expect(toast(page, ATTACHMENT_REFUSAL)).toBeVisible(); + await expect(page).toHaveURL(/\/$/); + const routines = await call>("/routines", { token: account.token }); + expect(routines.items).toHaveLength(0); + }); + + test("a refused fleet schedule keeps the typed goal", async ({ accountPage: page }) => { + knownBug( + "web/app/components/composer/task-composer.tsx:232-235 - the fleet refusal returns instead " + + "of throwing, so composer.tsx:270-272 treats the save as sent and clears the typed goal", + ); + const goal = "Compare three vendors"; + await page.goto("/"); + await submitRefused(page, goal, "fleet"); + await expect(toast(page, FLEET_REFUSAL)).toBeVisible(); + await expect(composer(page)).toHaveValue(goal); + }); + + test("a refused attachment schedule keeps the goal and the file", async ({ + accountPage: page, + }) => { + knownBug( + "web/app/components/composer/task-composer.tsx:237-240 - the attachments refusal returns " + + "instead of throwing, so composer.tsx:270-273 clears the typed goal and the attached file", + ); + const goal = "Read the attached notes"; + await page.goto("/"); + await submitRefused(page, goal, "attachment"); + await expect(toast(page, ATTACHMENT_REFUSAL)).toBeVisible(); + const box = page.getByRole("group").filter({ has: composer(page) }); + await expect(box.getByText("notes.txt")).toBeVisible(); + await expect(composer(page)).toHaveValue(goal); + }); +}); diff --git a/web/e2e/inbox.spec.ts b/web/e2e/inbox.spec.ts new file mode 100644 index 0000000..2e7b619 --- /dev/null +++ b/web/e2e/inbox.spec.ts @@ -0,0 +1,255 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { joinWorkspace, signUp, verifyEmail } from "./support/accounts"; +import { call, createHeldTask, createProject, type HeldTask, stamp } from "./support/api"; +import { mailAvailable } from "./support/mailbox"; +import { expect, knownBug, test } from "./fixtures"; + +// The inbox: notifications on the left, what each is about on the right. A held routine run is +// the knock a flow can make without a model: firing a held routine mints a task and tells its +// owner it is waiting for them. + +/** The sidebar's Inbox entry, whose text carries the unread count beside the word. */ +function inboxEntry(page: Page) { + return page + .getByRole("listitem") + .filter({ has: page.getByRole("link", { name: "Inbox", exact: true }) }); +} + +/** A held run's row in the list, by the routine that holds it. */ +function heldRow(page: Page, task: HeldTask) { + return page + .getByRole("main") + .getByRole("button", { name: new RegExp(`${task.routine.name} is holding a run for you`) }); +} + +/** Two held runs, oldest first: the list shows the newest at the top. */ +async function twoHeld(token: string): Promise<[HeldTask, HeldTask]> { + const older = await createHeldTask(token, `Count the gulls ${stamp()}`); + const newer = await createHeldTask(token, `Count the terns ${stamp()}`); + return [older, newer]; +} + +test("a held run knocks the inbox, and Open task goes to it", async ({ + accountPage: page, + account, +}) => { + const task = await createHeldTask(account.token, `Summarize the tide pool notes ${stamp()}`); + await page.goto("/inbox"); + await expect(inboxEntry(page)).toHaveText(/^Inbox\s*1$/); + + // The first notification is selected on arrival: the right pane says what it is about. + const row = heldRow(page, task); + await expect(row).toHaveAttribute("aria-current", "true"); + const main = page.getByRole("main"); + const title = `${task.routine.name} is holding a run for you`; + await expect(main.getByRole("heading", { level: 2, name: title })).toBeVisible(); + await expect(main.getByText(/^Held runs · /)).toBeVisible(); + await expect(main.getByText(task.goal).first()).toBeVisible(); + + await page.getByRole("button", { name: "Open task" }).click(); + await expect(page).toHaveURL(new RegExp(`/tasks/${task.id}$`)); +}); + +test("reading clears the badge one by one, and Mark all read clears the rest", async ({ + accountPage: page, + account, +}) => { + const [older, newer] = await twoHeld(account.token); + await page.goto("/inbox"); + await expect(inboxEntry(page)).toHaveText(/^Inbox\s*2$/); + await expect(heldRow(page, newer)).toHaveAttribute("aria-current", "true"); + + await heldRow(page, older).click(); + await expect(heldRow(page, older)).toHaveAttribute("aria-current", "true"); + await expect( + page.getByRole("main").getByRole("heading", { + level: 2, + name: `${older.routine.name} is holding a run for you`, + }), + ).toBeVisible(); + await expect(inboxEntry(page)).toHaveText(/^Inbox\s*1$/); + + const markAll = page.getByRole("button", { name: "Mark all read" }); + await markAll.click(); + await expect(markAll).toBeDisabled(); + // The badge moves only after the server took it, so a reload after it reads the server's answer. + await expect(inboxEntry(page)).toHaveText(/^Inbox$/); + await page.reload(); + await expect(inboxEntry(page)).toHaveText(/^Inbox$/); + await expect(page.getByRole("button", { name: "Mark all read" })).toBeDisabled(); +}); + +test("Unread only shows what is left, then the caught-up state", async ({ + accountPage: page, + account, +}) => { + const [older, newer] = await twoHeld(account.token); + await page.goto("/inbox"); + await heldRow(page, older).click(); + await expect(inboxEntry(page)).toHaveText(/^Inbox\s*1$/); + + await page.getByRole("button", { name: "Display options" }).click(); + const unreadOnly = page.getByRole("menuitemcheckbox", { name: /^Unread only/ }); + await expect(unreadOnly).toHaveAccessibleName("Unread only 1"); + await unreadOnly.click(); + await expect(unreadOnly).toBeChecked(); + await page.keyboard.press("Escape"); + await expect(heldRow(page, newer)).toBeVisible(); + await expect(heldRow(page, older)).toBeHidden(); + + await page.getByRole("button", { name: "Mark all read" }).click(); + await expect(page.getByRole("main").getByText("You're all caught up")).toBeVisible(); + await expect(heldRow(page, newer)).toBeHidden(); + + // Taking the view off brings every notification back. + await page.getByRole("button", { name: "Display options" }).click(); + await page.getByRole("menuitemcheckbox", { name: /^Unread only/ }).click(); + await page.keyboard.press("Escape"); + await expect(heldRow(page, newer)).toBeVisible(); + await expect(heldRow(page, older)).toBeVisible(); +}); + +test("the arrow keys move the selection and Enter opens it", async ({ + accountPage: page, + account, +}) => { + const [older, newer] = await twoHeld(account.token); + await page.goto("/inbox"); + await expect(heldRow(page, newer)).toHaveAttribute("aria-current", "true"); + + await page.keyboard.press("ArrowDown"); + await expect(heldRow(page, older)).toHaveAttribute("aria-current", "true"); + await expect(heldRow(page, newer)).toHaveAttribute("aria-current", "false"); + // The last row is the floor: another ArrowDown stays put. + await page.keyboard.press("ArrowDown"); + await expect(heldRow(page, older)).toHaveAttribute("aria-current", "true"); + await page.keyboard.press("ArrowUp"); + await expect(heldRow(page, newer)).toHaveAttribute("aria-current", "true"); + await page.keyboard.press("ArrowDown"); + await expect(heldRow(page, older)).toHaveAttribute("aria-current", "true"); + + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(new RegExp(`/tasks/${older.id}$`)); +}); + +test("Enter on a focused toolbar button works that button, not the selected item", async ({ + accountPage: page, + account, +}) => { + knownBug( + "web/app/routes/inbox/route.tsx:236-246 - the window keydown handler skips only inputs, then opens the selected item " + + "on Enter whatever has focus, so Enter on Filter by kind (or Mark all read) also navigates away", + ); + await createHeldTask(account.token, `Hold the pier survey ${stamp()}`); + await page.goto("/inbox"); + await expect(page.getByRole("button", { name: "Open task" })).toBeVisible(); + + const filter = page.getByRole("button", { name: "Filter by kind" }); + await filter.focus(); + // Start listening before the key: a navigation that commits a moment later still counts. + const navigated = page.waitForURL(/\/tasks\//, { timeout: 3000 }).then( + () => true, + () => false, + ); + await page.keyboard.press("Enter"); + await expect(page.getByRole("menu", { name: "Filter by kind" })).toBeVisible(); + expect(await navigated).toBe(false); + await expect(page).toHaveURL(/\/inbox$/); +}); + +test.describe("project knocks", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + test("Filter by kind lists the kinds present and narrows to one", async ({ + accountPage: page, + account, + }) => { + const host = await signUp("e2e-inbox", { name: "Bea Host" }); + await verifyEmail(host); + await joinWorkspace(host, account); + const project = await createProject(host.token, `Shared shoreline ${stamp()}`); + await call(`/projects/${project.id}/members`, { + token: host.token, + body: { email: account.email, role: "editor" }, + }); + const held = await createHeldTask(account.token, `Hold the dune count ${stamp()}`); + const sharedRow = page + .getByRole("main") + .getByRole("button", { name: new RegExp(`Bea Host added you to ${project.name}`) }); + + await page.goto("/inbox"); + await expect(sharedRow).toBeVisible(); + await expect(heldRow(page, held)).toBeVisible(); + + const filter = page.getByRole("button", { name: "Filter by kind" }); + await filter.click(); + const menu = page.getByRole("menu", { name: "Filter by kind" }); + await expect(menu.getByRole("menuitemradio")).toHaveText([ + "All notifications", + "Projects", + "Held runs", + ]); + await menu.getByRole("menuitemradio", { name: "Held runs" }).click(); + await page.keyboard.press("Escape"); + await expect(heldRow(page, held)).toBeVisible(); + await expect(sharedRow).toBeHidden(); + + await filter.click(); + await menu.getByRole("menuitemradio", { name: "Projects" }).click(); + await page.keyboard.press("Escape"); + await expect(sharedRow).toBeVisible(); + await expect(heldRow(page, held)).toBeHidden(); + + await filter.click(); + await menu.getByRole("menuitemradio", { name: "All notifications" }).click(); + await page.keyboard.press("Escape"); + await expect(sharedRow).toBeVisible(); + await expect(heldRow(page, held)).toBeVisible(); + }); + + test("being added to and removed from a project never shows two identical filters", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/routes/inbox/route.tsx:110-112 + 290-299 - project_shared and project_removed each " + + "get their own 'Projects' filter item, so the menu shows two identical items and either one " + + "hides the other kind's notification (merging them or naming them apart both fix it)", + ); + const host = await signUp("e2e-inbox", { name: "Bea Host" }); + await verifyEmail(host); + await joinWorkspace(host, account); + const project = await createProject(host.token, `Brief stay ${stamp()}`); + await call(`/projects/${project.id}/members`, { + token: host.token, + body: { email: account.email, role: "editor" }, + }); + await call(`/projects/${project.id}/members/${account.id}`, { + token: host.token, + method: "DELETE", + }); + + await page.goto("/inbox"); + const main = page.getByRole("main"); + const added = main.getByRole("button", { name: new RegExp(`added you to ${project.name}`) }); + const removed = main.getByRole("button", { + name: new RegExp(`removed you from ${project.name}`), + }); + await expect(added).toBeVisible(); + await expect(removed).toBeVisible(); + + // Every filter must be one a person can tell apart from the rest. + await page.getByRole("button", { name: "Filter by kind" }).click(); + const menu = page.getByRole("menu", { name: "Filter by kind" }); + await expect(menu.getByRole("menuitemradio", { name: "All notifications" })).toBeVisible(); + const labels = await menu.getByRole("menuitemradio").allTextContents(); + expect(labels.length).toBeGreaterThan(1); + expect(new Set(labels).size, `filters: ${labels.join(", ")}`).toBe(labels.length); + }); +}); diff --git a/web/e2e/models/bots.spec.ts b/web/e2e/models/bots.spec.ts new file mode 100644 index 0000000..7cd33a0 --- /dev/null +++ b/web/e2e/models/bots.spec.ts @@ -0,0 +1,155 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { expect, test, toast } from "../fixtures"; +import { call, createBot, stamp } from "../support/api"; +import { RUN_TIMEOUT } from "../support/runs"; + +// Bots on a real model (the `models` project, E2E_MODELS=1): a reply in the bot's chat, the +// selection evals that gate publishing, and the drafter that writes a bot's instructions. + +type Message = { seq: number; role: string; text: string }; +type Conversation = { id: string }; + +/** A bot that knows tides: routing written, so the evals have something to score. */ +const ROUTING = { + job: "Writes tide-table guides for small boat sailors", + use_when: ["someone wants a written guide to reading a tide table"], + not_for: ["weather forecasts"], +}; + +test.describe("a bot on a real model", () => { + test("answers in its chat, and the conversation is kept", async ({ + accountPage: page, + account, + }) => { + const { name } = await createBot(account.token, { + name: `tides-${stamp()}`, + instructions: "You explain tides to small boat sailors in one short paragraph.", + }); + await page.goto(`/bots/${name}`); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "Start one" }).click(); + const box = main.getByRole("textbox", { name: `Message ${name}` }); + const send = main.getByRole("button", { name: "Send" }); + await expect(send).toBeDisabled(); + const question = "In one sentence, what is a spring tide?"; + await box.fill(question); + await send.click(); + await expect(main.getByText(question)).toBeVisible(); + await expect(box).toHaveValue(""); + + // The reply streams into the chat; the server's copy of it is what the page must show. + let reply = ""; + await expect + .poll( + async () => { + const [conversation] = await call(`/conversations?bot=${name}`, { + token: account.token, + }); + if (!conversation) return ""; + const messages = await call(`/conversations/${conversation.id}/messages`, { + token: account.token, + }); + reply = messages.find((m) => m.role === "bot")?.text ?? ""; + return reply; + }, + { timeout: RUN_TIMEOUT, intervals: [1_000] }, + ) + .not.toBe(""); + // The reply is markdown and the page renders it, so its marks are dropped before matching. + const opening = reply + .replace(/[*_`#>[\]]/g, "") + .split(/\s+/) + .slice(0, 6) + .join(" "); + await expect(main.getByText(opening, { exact: false })).toBeVisible(); + + await page.reload(); + await expect(main.getByText(question)).toBeVisible(); + await expect(main.getByText(opening, { exact: false })).toBeVisible(); + }); + + test("evals that win the bot's own goal turn it green, and it publishes", async ({ + accountPage: page, + }) => { + const name = `guides-${stamp()}`; + await page.goto("/bots"); + const main = page.getByRole("main"); + await main.getByRole("button", { name: "New bot" }).click(); + const dialog = page.getByRole("dialog", { name: "New bot" }); + await dialog + .getByRole("textbox", { name: "Instructions (optional)" }) + .fill("You write short, plain guides to reading tide tables for small boat sailors."); + await dialog.getByRole("textbox", { name: "Name", exact: true }).fill(name); + await dialog.getByRole("button", { name: "Advanced" }).click(); + await dialog.getByRole("textbox", { name: "What does this bot do?" }).fill(ROUTING.job); + await dialog + .getByRole("textbox", { name: "When should it step in?" }) + .fill(ROUTING.use_when[0]); + await dialog.getByRole("textbox", { name: "What should it refuse?" }).fill(ROUTING.not_for[0]); + // A goal plainly asking for the bot's work: the Lead plans it, so the eval can seat the bot. + await dialog + .getByRole("textbox", { name: "A goal it should win" }) + .fill( + "Write me a one-page guide to reading the tide table for my harbour before a dinghy sail.", + ); + await dialog.getByRole("button", { name: "Create bot" }).click(); + await expect(page).toHaveURL(new RegExp(`/bots/${name}\\?tab=configure$`)); + await expect(main.getByText("evals untested", { exact: true })).toBeVisible(); + await expect(main.getByRole("button", { name: /^Publish/ })).toHaveCount(0); + + await main.getByRole("button", { name: "Test evals" }).click(); + await expect(main.getByText("evals green", { exact: true })).toBeVisible({ + timeout: RUN_TIMEOUT, + }); + await expect(main.getByRole("heading", { name: "Selection evals" })).toBeVisible(); + await expect(main.getByText("1/1", { exact: true })).toBeVisible(); + + await main.getByRole("button", { name: "Publish v1" }).click(); + await expect(main.getByText(/^published\s+v1$/)).toBeVisible(); + await expect(main.getByRole("button", { name: /^Publish/ })).toHaveCount(0); + await page.reload(); + await expect(main.getByText(/^published\s+v1$/)).toBeVisible(); + }); + + test("Draft for me writes the instructions as the next draft", async ({ + accountPage: page, + account, + }) => { + // No instructions yet: the drafter writes them from the routing. + const name = `drafted-${stamp()}`; + await call("/bots", { token: account.token, body: { name, ...ROUTING, can_ask_user: true } }); + await page.goto(`/bots/${name}?tab=configure`); + const main = page.getByRole("main"); + const instructions = main.getByRole("textbox", { name: "Bot instructions" }); + await expect(instructions).toHaveValue(""); + await main.getByRole("button", { name: "Draft for me" }).click(); + await expect( + toast(page, "Writing a fuller draft - it lands here in a moment.").first(), + ).toBeVisible(); + + // The draft lands as the next version. The tab re-reads the bot for 40 s only, and the drafter + // takes 20 to 40 s or more, so the flow waits on the server's v2 and then reloads. + test.info().annotations.push({ + type: "bug", + description: + "web/app/routes/bots/configure-tab.tsx:76 polls for 40 s after Draft for me (and Test " + + "evals); a draft that lands later never shows until a reload, though the toast says it " + + "lands here in a moment", + }); + await expect + .poll( + async () => + (await call<{ version: number }>(`/bots/${name}`, { token: account.token })).version, + { timeout: RUN_TIMEOUT, intervals: [2_000] }, + ) + .toBe(2); + await page.reload(); + await expect(main.getByRole("listitem").filter({ hasText: /^v2\s*draft/ })).toBeVisible(); + await expect(main.getByRole("textbox", { name: "Bot instructions" })).not.toHaveValue(""); + }); +}); diff --git a/web/e2e/models/routines.spec.ts b/web/e2e/models/routines.spec.ts new file mode 100644 index 0000000..899cf8e --- /dev/null +++ b/web/e2e/models/routines.spec.ts @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { escapeRegExp, expect, test, toast } from "../fixtures"; +import { call, stamp } from "../support/api"; +import { RUN_TIMEOUT, TASK_URL } from "../support/runs"; + +// A routine fired for real (the `models` project, E2E_MODELS=1): a routine executes nothing itself; +// its fire mints an ordinary task that runs unattended and delivers to its owner. + +type Routine = { id: string; name: string }; + +test.describe("a routine on a real model", () => { + // No standing work outlives the flow, pass or fail. + test.afterEach(async ({ account }) => { + const routines = await call<{ items: Routine[] }>("/routines", { token: account.token }); + for (const r of routines.items) + await call(`/routines/${r.id}/retire`, { token: account.token, body: {} }); + }); + + test("Run now mints a task that runs and delivers to the owner", async ({ + accountPage: page, + account, + }) => { + // Once a year, so the sweep never fires it during the run: only Run now does. + const routine = await call("/routines", { + token: account.token, + body: { + name: `Tide brief ${stamp()}`, + instruction: "In one sentence, name the moon phase that brings spring tides.", + schedule: { cron: "0 9 1 1 *", timezone: "UTC" }, + posture: "auto", + }, + }); + await page.goto(`/routines?routine=${routine.id}`); + const pane = page.getByRole("dialog", { name: "Routine" }); + await expect( + pane.getByText("No fires yet - the ledger starts with the first one."), + ).toBeVisible(); + await pane.getByRole("button", { name: "Run now" }).click(); + await expect(toast(page, "Fired - the run shows below.")).toBeVisible(); + + // Every fire journals a run wearing its reason; a minted one opens the run its task made. + const run = pane.getByRole("button", { name: /^minted manual · .* · task created$/ }); + await expect(run).toBeVisible(); + await run.click(); + await expect(page).toHaveURL(/[?&]run=[0-9a-f-]{36}$/); + const banner = pane.getByRole("banner"); + await expect(banner.getByText("delivered", { exact: true })).toBeVisible({ + timeout: RUN_TIMEOUT, + }); + await expect(pane).toContainText(/moon/i); + await banner.getByRole("button", { name: "Open the full task" }).click(); + await expect(page).toHaveURL(TASK_URL); + await expect( + page.getByRole("main").getByRole("img", { name: "Status: delivered", exact: true }), + ).toBeVisible(); + await expect(page.getByRole("region", { name: "Messages" })).toContainText(/moon/i); + + // An unattended run delivers to its owner: the inbox says so under the routine's name. + await page.goto("/inbox"); + await expect( + page + .getByRole("main") + .getByRole("button", { name: new RegExp(`${escapeRegExp(routine.name)}: delivered`) }), + ).toBeVisible(); + }); +}); diff --git a/web/e2e/models/tasks.spec.ts b/web/e2e/models/tasks.spec.ts new file mode 100644 index 0000000..3accd62 --- /dev/null +++ b/web/e2e/models/tasks.spec.ts @@ -0,0 +1,208 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { chooseOption, composer, escapeRegExp, expect, knownBug, test } from "../fixtures"; +import { call } from "../support/api"; +import { + answerQuestions, + RUN_TIMEOUT, + startTask, + TASK_URL, + taskIdIn, + waitForTask, +} from "../support/runs"; + +// Tasks that run on a real model (the `models` project, E2E_MODELS=1): a question, a follow-up, a +// fork, a Markdown document with its verification, and a round of clarifying questions. Each one is +// small enough to settle in seconds on paper, so none of them boots a Machine; the document's +// verification runs in a throwaway frame, which needs the compose frame network (stack.sh checks). + +function messages(page: Page) { + return page.getByRole("region", { name: "Messages" }); +} + +/** The page header's status icon: its name carries the task's status word. */ +function status(page: Page, word: string) { + return page.getByRole("main").getByRole("img", { name: `Status: ${word}`, exact: true }); +} + +/** One finished turn on the thread: its step summary is a button that opens the step's detail. */ +function turns(page: Page) { + return messages(page).getByRole("button", { name: /^Completed \d+ steps? / }); +} + +test.describe("a task on a real model", () => { + test("a question sent from home comes back answered and is kept", async ({ + accountPage: page, + }) => { + const goal = "What is the capital of France? Answer in one short sentence."; + await page.goto("/"); + await composer(page).fill(goal); + await page.getByRole("button", { name: "Submit" }).click(); + await expect(page).toHaveURL(TASK_URL); + + await expect(status(page, "delivered")).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(messages(page)).toContainText(goal); + await expect(messages(page)).toContainText("Paris"); + await expect(turns(page)).toHaveCount(1); + // The header's spend comes from the ledger: what the run cost, in how many model calls. + await expect( + page.getByRole("main").getByText(/^\$\d+\.\d+ · [1-9]\d* model calls?$/), + ).toBeVisible(); + + // The record replays the same thread after a reload. + await page.reload(); + await expect(status(page, "delivered")).toBeVisible(); + await expect(messages(page)).toContainText("Paris"); + + // Delivery knocks the inbox, and the item opens on the answer. + await page.goto("/inbox"); + const item = page + .getByRole("main") + .getByRole("button", { name: new RegExp(`Delivered: ${escapeRegExp(goal)}`) }); + await item.first().click(); + await expect(page.getByRole("main").getByRole("heading", { level: 2 })).toContainText(goal); + await expect(page.getByRole("main")).toContainText("Paris"); + }); + + test("a follow-up continues the same task as its next turn", async ({ + accountPage: page, + account, + }) => { + const id = await startTask(account.token, "Name one planet in the solar system. One word."); + await waitForTask(account.token, id, "delivered"); + await page.goto(`/tasks/${id}`); + await expect(turns(page)).toHaveCount(1); + + const ask = "Now name a different planet. One word."; + await page.getByRole("textbox", { name: "Ask a follow-up…" }).fill(ask); + await page.getByRole("button", { name: "Submit" }).click(); + await expect(messages(page)).toContainText(ask); + await expect(turns(page)).toHaveCount(2, { timeout: RUN_TIMEOUT }); + await expect(status(page, "delivered")).toBeVisible(); + // A follow-up is never a new task: the same page, the same row, its turn counter moved on. + expect(taskIdIn(page.url())).toBe(id); + expect((await waitForTask(account.token, id, "delivered")).turn).toBe(2); + }); + + test("a fork branches a delivered task, held until a direction launches it", async ({ + accountPage: page, + account, + }) => { + const id = await startTask(account.token, "Name one planet in the solar system. One word."); + await waitForTask(account.token, id, "delivered"); + await page.goto(`/tasks/${id}`); + await page.getByRole("button", { name: "Task actions", exact: true }).click(); + await page + .getByRole("menu", { name: "Task actions" }) + .getByRole("menuitem", { name: "Fork this task" }) + .click(); + + // The branch is a new task carrying the whole conversation, born held. + await expect(page).not.toHaveURL(new RegExp(id)); + await expect(page).toHaveURL(TASK_URL); + const branch = taskIdIn(page.url()); + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toContainText("[Forked]"); + await expect(messages(page).getByRole("status")).toHaveText( + "Held. This branch has not started. Send a direction below to launch it.", + ); + await expect(turns(page)).toHaveCount(1); + + await page + .getByRole("textbox", { name: "Where should this branch go?" }) + .fill("Now name the largest planet. One word."); + await page.getByRole("button", { name: "Submit" }).click(); + await expect(status(page, "delivered")).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(messages(page)).toContainText("Jupiter"); + + // The parent keeps its own thread: one turn, still delivered. + const parent = await waitForTask(account.token, id, "delivered"); + expect(parent.turn).toBe(1); + expect( + (await call<{ status: string }>(`/tasks/${branch}`, { token: account.token })).status, + ).toBe("delivered"); + }); + + test("a Markdown document is published, opened in the reader and verified", async ({ + accountPage: page, + }) => { + await page.goto("/"); + await chooseOption(page, "Deliverable", "Document · Markdown"); + await composer(page).fill( + "Write a three-sentence note on why tide tables matter to small boat sailors.", + ); + await page.getByRole("button", { name: "Submit" }).click(); + await expect(page).toHaveURL(TASK_URL); + + // The published document opens in the reader by itself. + const reader = page.getByRole("region", { name: "Artifact reader" }); + await expect(reader.getByRole("heading", { level: 1 })).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(reader).toContainText(/tide/i); + await expect(status(page, "delivered")).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(messages(page).getByRole("button", { name: /Document/ })).toBeVisible(); + + // The file downloads as Markdown. + const download = page.waitForEvent("download"); + await reader.getByRole("button", { name: "Download" }).click(); + expect((await download).suggestedFilename()).toMatch(/\.md$/); + + // Verification signs after delivery, on its own queue: the thread shows the receipt when it + // lands. An unsourced note may well come back unverified, so the verdict word is not asserted. + await expect(messages(page).getByText(/ · document-suite · judged by /)).toBeVisible({ + timeout: RUN_TIMEOUT, + }); + await expect(messages(page).getByRole("button", { name: "See the receipt" })).toBeVisible(); + }); + + test("the open reader shows the receipt once the check finishes", async ({ + accountPage: page, + }) => { + knownBug( + "web/app/components/artifact/artifact-view.tsx:127-167 fetches the verification once, when " + + "the reader opens (its effect depends on currentId only); the reader opens at publish, " + + "before the check signs, so it keeps 'Not verified yet' after the thread shows the receipt", + ); + await page.goto("/"); + await chooseOption(page, "Deliverable", "Document · Markdown"); + await composer(page).fill("Write two sentences on what a neap tide is."); + await page.getByRole("button", { name: "Submit" }).click(); + const reader = page.getByRole("region", { name: "Artifact reader" }); + await expect(reader.getByRole("heading", { level: 1 })).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(messages(page).getByText(/ · document-suite · judged by /)).toBeVisible({ + timeout: RUN_TIMEOUT, + }); + await expect( + reader.getByText("Not verified yet. The receipt shows here once the check finishes."), + ).toBeHidden(); + }); + + test("clarifying questions open a gate the person answers, then the task delivers", async ({ + accountPage: page, + account, + }) => { + await page.goto("/"); + await chooseOption(page, "Clarifying questions", "Always"); + await composer(page).fill("Recommend one book for me to read next. Answer in one sentence."); + await page.getByRole("button", { name: "Submit" }).click(); + await expect(page).toHaveURL(TASK_URL); + const id = taskIdIn(page.url()); + + // One numbered batch, before any work starts: the header says the task needs its person. + await expect(page.getByRole("main").getByText(/^Needs you\b/)).toBeVisible({ + timeout: RUN_TIMEOUT, + }); + await expect(messages(page)).toContainText("Waiting for your answer"); + const gates = await call<{ kind: string; status: string }[]>(`/gates?task_id=${id}`, { + token: account.token, + }); + expect(gates.map((g) => g.kind)).toEqual(["input"]); + + expect(await answerQuestions(page)).toBeGreaterThan(0); + await expect(status(page, "delivered")).toBeVisible({ timeout: RUN_TIMEOUT }); + await expect(turns(page).last()).toBeVisible(); + }); +}); diff --git a/web/e2e/password-reset.spec.ts b/web/e2e/password-reset.spec.ts new file mode 100644 index 0000000..ffc6b27 --- /dev/null +++ b/web/e2e/password-reset.spec.ts @@ -0,0 +1,72 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { signIn } from "./support/accounts"; +import { call } from "./support/api"; +import { codeIn, mailAvailable, waitForMail } from "./support/mailbox"; +import { composer, expect, test } from "./fixtures"; + +// A forgotten password (ADR-031): the emailed single-use code is the whole authentication, and +// completing a reset revokes every live session. Each flow resets its own account. +test.describe("password reset", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + test("resets the password with the emailed code, then signs in with it", async ({ + page, + account, + }) => { + // A session from before the reset, to prove the reset ends it. + const before = await signIn(account); + + await page.goto("/login"); + await page.getByRole("link", { name: "Forgot your password?" }).click(); + await expect(page.getByRole("heading", { name: "Forgot your password?" })).toBeVisible(); + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("button", { name: "Send reset code" }).click(); + await expect(page.getByText("Check your email")).toBeVisible(); + + const mail = await waitForMail(account.email, /password reset/); + await page.getByRole("button", { name: "I have my code" }).click(); + await expect(page.getByRole("heading", { name: "Reset your password" })).toBeVisible(); + await page.getByRole("textbox", { name: "Reset code" }).fill(codeIn(mail, "cr_")); + const fresh = "a much longer passphrase now"; + await page.getByRole("textbox", { name: "New password" }).fill(fresh); + await page.getByRole("button", { name: "Reset password" }).click(); + await expect(page.getByText("Password updated")).toBeVisible(); + + // Every session from before is gone. + await expect(call("/auth/me", { token: before.token })).rejects.toMatchObject({ status: 401 }); + + await expect(page.getByText(/Every signed-in session was signed out/)).toBeVisible(); + await page.getByRole("button", { name: "Sign in" }).click(); + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("textbox", { name: "Password" }).fill(account.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByText("Invalid email or password.")).toBeVisible(); + await page.getByRole("textbox", { name: "Password" }).fill(fresh); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(composer(page)).toBeVisible(); + }); + + test("a code that was never issued is refused", async ({ page }) => { + await page.goto("/reset-password"); + await page + .getByRole("textbox", { name: "Reset code" }) + .fill("cr_thisCodeWasNeverIssuedByTheServer"); + await page.getByRole("textbox", { name: "New password" }).fill("a much longer passphrase now"); + await page.getByRole("button", { name: "Reset password" }).click(); + await expect( + page.getByText("That code is invalid or has expired. Request a new one."), + ).toBeVisible(); + }); + + test("the reset link prefills the code", async ({ page }) => { + await page.goto("/reset-password?code=cr_prefilledFromTheLink"); + await expect(page.getByRole("textbox", { name: "Reset code" })).toHaveValue( + "cr_prefilledFromTheLink", + ); + }); +}); diff --git a/web/e2e/project-members.spec.ts b/web/e2e/project-members.spec.ts new file mode 100644 index 0000000..6fb55d9 --- /dev/null +++ b/web/e2e/project-members.spec.ts @@ -0,0 +1,294 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { type Account, joinWorkspace, pageFor, signUp, verifyEmail } from "./support/accounts"; +import { call, createProject, stamp } from "./support/api"; +import { mailAvailable } from "./support/mailbox"; +import { expect, section, test } from "./fixtures"; + +// A project's people (ADR-062): the owner adds someone from the workspace by email or hands them +// a single-use invite link, changes their role and removes them. Every person here must belong to +// the owner's workspace first, which takes the emailed workspace invite. +test.describe("project members", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + /** A kit Section is a bare
under an h2: found by its heading, the only name it has. */ + + /** More people, already in the owner's workspace (an owner must prove the address first). */ + async function team(owner: Account, ...names: string[]): Promise { + await verifyEmail(owner); + const people: Account[] = []; + for (const name of names) { + const them = await signUp("e2e-project-members", { name }); + await joinWorkspace(owner, them); + people.push(them); + } + return people; + } + + async function share(owner: Account, projectId: string, email: string, role: string) { + await call(`/projects/${projectId}/members`, { token: owner.token, body: { email, role } }); + } + + test("the owner invites a teammate, who sees the project and a knock in the inbox", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const [mate] = await team(account, "Max Member"); + const project = await createProject(account.token, `Estuary ${stamp()}`); + await page.goto(`/projects/${project.id}`); + await expect(page.getByRole("group", { name: "1 person" })).toBeVisible(); + + // On the Tasks tab the header's Invite is the only one. + await page.getByRole("button", { name: "Invite", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "Invite to this project" }); + const send = dialog.getByRole("button", { name: "Send invite" }); + await expect(send).toBeDisabled(); + await expect(dialog.getByRole("combobox", { name: "Role" })).toHaveText("Editor"); + await dialog.getByRole("textbox", { name: "Email" }).fill(mate.email); + await send.click(); + await expect(dialog).toBeHidden(); + await expect(page.getByRole("group", { name: "2 people" })).toBeVisible(); + await expect(page.getByRole("img", { name: "Max Member" })).toBeVisible(); + + const theirs = await pageFor(browser, mate, baseURL!); + await theirs.goto("/projects"); + await expect( + theirs.getByRole("main").getByRole("link", { name: new RegExp(`${project.name}.*editor`) }), + ).toBeVisible(); + + // The share knocks their inbox, and its Open lands on the project. + await theirs.goto("/inbox"); + const knock = `${account.name} added you to ${project.name}`; + await theirs.getByRole("button", { name: new RegExp(knock) }).click(); + const main = theirs.getByRole("main"); + await expect(main.getByRole("heading", { level: 2, name: knock })).toBeVisible(); + await expect(main.getByText(/^Projects · /)).toBeVisible(); + await theirs.getByRole("button", { name: "Open project" }).click(); + await expect(theirs).toHaveURL(new RegExp(`/projects/${project.id}$`)); + await expect(theirs.getByRole("heading", { level: 1 })).toHaveText(project.name); + await theirs.context().close(); + }); + + test("the owner changes a member's role, then removes them", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const [mate] = await team(account, "Rae Member"); + const project = await createProject(account.token, `Salt marsh ${stamp()}`); + await page.goto(`/projects/${project.id}?tab=settings`); + + // On Settings the People section carries its own Invite beside the header's. + const people = section(page, "People"); + await people.getByRole("button", { name: "Invite", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "Invite to this project" }); + await dialog.getByRole("textbox", { name: "Email" }).fill(mate.email); + await dialog.getByRole("combobox", { name: "Role" }).click(); + await page.getByRole("option", { name: /^Viewer/ }).click(); + await dialog.getByRole("button", { name: "Send invite" }).click(); + await expect(dialog).toBeHidden(); + + const row = people.getByRole("listitem").filter({ hasText: mate.email }); + await expect(row.getByRole("combobox", { name: "Role" })).toHaveText("Viewer"); + await row.getByRole("combobox", { name: "Role" }).click(); + await page.getByRole("option", { name: "Editor" }).click(); + await expect(row.getByRole("combobox", { name: "Role" })).toHaveText("Editor"); + await page.reload(); + await expect(row.getByRole("combobox", { name: "Role" })).toHaveText("Editor"); + + const theirs = await pageFor(browser, mate, baseURL!); + await theirs.goto(`/projects/${project.id}`); + await expect(theirs.getByRole("main").getByText("editor", { exact: true })).toBeVisible(); + + await row.getByRole("button", { name: "Remove Rae Member" }).click(); + await expect(row).toHaveCount(0); + await expect(page.getByRole("group", { name: "1 person" })).toBeVisible(); + await page.reload(); + await expect(people.getByRole("listitem").filter({ hasText: mate.email })).toHaveCount(0); + + // Removed, they no longer see it at all. + await theirs.goto("/projects"); + await expect(theirs.getByRole("main").getByText("No projects yet")).toBeVisible(); + await theirs.context().close(); + }); + + test("a viewer reads the project but gets no composer and no owner controls", async ({ + account, + browser, + baseURL, + }) => { + const [mate] = await team(account, "Vic Viewer"); + const project = await createProject(account.token, `Read only ${stamp()}`); + await share(account, project.id, mate.email, "viewer"); + + const theirs = await pageFor(browser, mate, baseURL!); + await theirs.goto(`/projects/${project.id}`); + const main = theirs.getByRole("main"); + // The viewer's own signals first, so the absences below are not just a slow mount. + await expect(main.getByText("viewer", { exact: true })).toBeVisible(); + await expect(main.getByText("Tasks started in this Project show up here.")).toBeVisible(); + await expect(main.getByRole("textbox", { name: /^Describe what you need done/ })).toHaveCount( + 0, + ); + await expect(main.getByRole("button", { name: "Invite", exact: true })).toHaveCount(0); + await expect(main.getByRole("button", { name: "Change project icon" })).toHaveCount(0); + + await main.getByRole("tab", { name: "Settings" }).click(); + const settings = theirs.getByRole("tabpanel", { name: "Settings" }); + await expect(settings.getByText("No standing instructions yet.")).toBeVisible(); + await expect(settings.getByText("Nothing remembered here yet")).toBeVisible(); + await expect(settings.getByRole("listitem").filter({ hasText: mate.email })).toContainText( + "Viewer", + ); + for (const title of ["Invite links", "General", "Budget", "Danger zone"]) + await expect(settings.getByRole("heading", { name: title, exact: true })).toHaveCount(0); + await expect(settings.getByRole("textbox")).toHaveCount(0); + await expect(settings.getByRole("combobox")).toHaveCount(0); + await theirs.context().close(); + }); + + test.describe("invite links", () => { + /** Mint a link from the owner's Settings tab and return the path it opens. */ + async function createLink(page: Page, role: "Editor" | "Viewer") { + const links = section(page, "Invite links"); + await links.getByRole("button", { name: "Create link" }).click(); + const dialog = page.getByRole("dialog", { name: "Create an invite link" }); + await expect(dialog.getByRole("combobox", { name: "Expires" })).toHaveText("7 days"); + if (role === "Viewer") { + await dialog.getByRole("combobox", { name: "Role" }).click(); + await page.getByRole("option", { name: /^Viewer/ }).click(); + } + await dialog.getByRole("button", { name: "Create link" }).click(); + const field = dialog.getByRole("textbox", { name: "Invite link" }); + await expect(field).toHaveValue(/\/join\/si_[A-Za-z0-9_-]+$/); + await expect(dialog.getByText("This link is shown once.")).toBeVisible(); + const path = new URL(await field.inputValue()).pathname; + await dialog.getByRole("button", { name: "Close" }).click(); + await expect(dialog).toBeHidden(); + return path; + } + + test("a teammate who opens the link signed in joins at its role, once", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const [mate, late] = await team(account, "Lin Linker", "Lou Late"); + const project = await createProject(account.token, `Linked ${stamp()}`); + await page.goto(`/projects/${project.id}?tab=settings`); + const links = section(page, "Invite links"); + await expect(links.getByText(/No invite links yet/)).toBeVisible(); + + const path = await createLink(page, "Viewer"); + const row = links.getByRole("listitem"); + await expect(row).toHaveCount(1); + await expect(row).toContainText("Viewer"); + await expect(row.getByText("Live", { exact: true })).toBeVisible(); + // The list carries the link's state, never its code. + await expect(links.getByText(/si_/)).toHaveCount(0); + + const theirs = await pageFor(browser, mate, baseURL!); + await theirs.goto(path); + await expect(theirs).toHaveURL(new RegExp(`/projects/${project.id}$`)); + await expect(theirs.getByRole("heading", { level: 1 })).toHaveText(project.name); + await expect(theirs.getByRole("main").getByText("viewer", { exact: true })).toBeVisible(); + + await page.reload(); + await expect(row.getByText("Used", { exact: true })).toBeVisible(); + await expect(row.getByRole("button", { name: /^Revoke / })).toHaveCount(0); + await expect( + section(page, "People").getByRole("listitem").filter({ hasText: mate.email }), + ).toBeVisible(); + + // Single use: a second person holding the same link is turned away. + const lateTab = await pageFor(browser, late, baseURL!); + await lateTab.goto(path); + await expect(lateTab.getByRole("heading", { level: 1, name: "Couldn't join" })).toBeVisible(); + await lateTab.context().close(); + await theirs.context().close(); + }); + + test("signed out, the link goes through sign-in and then joins", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const [mate] = await team(account, "Sid Signin"); + const project = await createProject(account.token, `Via login ${stamp()}`); + await page.goto(`/projects/${project.id}?tab=settings`); + const path = await createLink(page, "Editor"); + + const context = await browser.newContext({ baseURL }); + const anon = await context.newPage(); + await anon.goto(path); + await expect(anon).toHaveURL( + new RegExp( + `/login\\?next=${encodeURIComponent(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, + ), + ); + await anon.getByRole("textbox", { name: "Email" }).fill(mate.email); + await anon.getByRole("textbox", { name: "Password" }).fill(mate.password); + await anon.getByRole("button", { name: "Sign in" }).click(); + await expect(anon).toHaveURL(new RegExp(`/projects/${project.id}$`)); + await expect(anon.getByRole("main").getByText("editor", { exact: true })).toBeVisible(); + await context.close(); + + await page.reload(); + await expect(section(page, "Invite links").getByText("Used", { exact: true })).toBeVisible(); + }); + + test("a revoked link stops working", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const [mate] = await team(account, "Ren Revoked"); + const project = await createProject(account.token, `Revoked ${stamp()}`); + await page.goto(`/projects/${project.id}?tab=settings`); + const links = section(page, "Invite links"); + const kept = await createLink(page, "Viewer"); + const revoked = await createLink(page, "Editor"); + await expect(links.getByRole("listitem")).toHaveCount(2); + + await links.getByRole("button", { name: "Revoke editor link" }).click(); + const editorRow = links.getByRole("listitem").filter({ hasText: "Editor" }); + await expect(editorRow.getByText("Revoked", { exact: true })).toBeVisible(); + await expect( + links + .getByRole("listitem") + .filter({ hasText: "Viewer" }) + .getByText("Live", { exact: true }), + ).toBeVisible(); + await page.reload(); + await expect(editorRow.getByText("Revoked", { exact: true })).toBeVisible(); + + const theirs = await pageFor(browser, mate, baseURL!); + await theirs.goto(revoked); + await expect(theirs.getByRole("heading", { level: 1, name: "Couldn't join" })).toBeVisible(); + // The link left alive still lets them in. + await theirs.goto(kept); + await expect(theirs).toHaveURL(new RegExp(`/projects/${project.id}$`)); + await theirs.context().close(); + }); + }); +}); + +test("a link that was never issued says it couldn't join", async ({ accountPage: page }) => { + await page.goto("/join/si_bogus"); + await expect(page.getByRole("heading", { level: 1, name: "Couldn't join" })).toBeVisible(); + await expect(page.getByText("this invite is invalid or has expired")).toBeVisible(); + await page.getByRole("button", { name: "Go home" }).click(); + await expect(page).toHaveURL(/\/$/); + await expect(page.getByRole("textbox", { name: /Describe what you need done/ })).toBeVisible(); +}); diff --git a/web/e2e/project-settings.spec.ts b/web/e2e/project-settings.spec.ts new file mode 100644 index 0000000..074e4d1 --- /dev/null +++ b/web/e2e/project-settings.spec.ts @@ -0,0 +1,207 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { joinWorkspace, pageFor, signUp, verifyEmail } from "./support/accounts"; +import { createProject, stamp } from "./support/api"; +import { mailAvailable } from "./support/mailbox"; +import { expect, knownBug, section, test, toast } from "./fixtures"; + +// A project's Settings tab, as its owner sees it. Each setting saves on its own Save, which +// appears only while that field differs from the server, so several can be on screen at once. + +/** A kit Section is a bare
under an h2: found by its heading, the only name it has. */ + +/** The settings row holding this textbox: its Save sits beside it. */ +function rowOf(page: Page, textbox: string) { + return page + .getByRole("tabpanel", { name: "Settings" }) + .getByRole("listitem") + .filter({ has: page.getByRole("textbox", { name: textbox }) }); +} + +async function openSettings(page: Page, projectId: string) { + await page.goto(`/projects/${projectId}?tab=settings`); + await expect(page.getByRole("tab", { name: "Settings" })).toHaveAttribute( + "aria-selected", + "true", + ); +} + +test("renames the project, and the new name is the one everywhere", async ({ + accountPage: page, + account, +}) => { + const project = await createProject(account.token, `Kelp census ${stamp()}`); + await openSettings(page, project.id); + const row = rowOf(page, "Project name"); + const name = row.getByRole("textbox", { name: "Project name" }); + await expect(name).toHaveValue(project.name); + // A resting field offers nothing to save. + await expect(row.getByRole("button", { name: "Save" })).toHaveCount(0); + + const renamed = `Kelp forest census ${stamp()}`; + await name.fill(renamed); + await row.getByRole("button", { name: "Save" }).click(); + await expect(toast(page, "Saved.")).toBeVisible(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(renamed); + await expect(row.getByRole("button", { name: "Save" })).toHaveCount(0); + + await page.reload(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(renamed); + await expect(name).toHaveValue(renamed); + await page.goto("/projects"); + await expect( + page.getByRole("main").getByRole("link", { name: new RegExp(renamed) }), + ).toBeVisible(); +}); + +test("saves the project's instructions", async ({ accountPage: page, account }) => { + const project = await createProject(account.token, `Reef notes ${stamp()}`); + await openSettings(page, project.id); + const instructions = section(page, "Instructions"); + const text = instructions.getByRole("textbox", { name: "Project instructions" }); + await expect(instructions.getByRole("button", { name: "Save" })).toHaveCount(0); + + await text.fill("Cite sources.\nUK English."); + await instructions.getByRole("button", { name: "Save" }).click(); + await expect(toast(page, "Saved.")).toBeVisible(); + await expect(instructions.getByRole("button", { name: "Save" })).toHaveCount(0); + + await page.reload(); + await expect(text).toHaveValue("Cite sources.\nUK English."); +}); + +test("sets a monthly budget, then clears it", async ({ accountPage: page, account }) => { + const project = await createProject(account.token, `Budgeted ${stamp()}`); + await openSettings(page, project.id); + const budget = section(page, "Budget"); + const row = rowOf(page, "Budget in USD"); + const input = row.getByRole("textbox", { name: "Budget in USD" }); + await expect(budget.getByText("spent this month · no ceiling")).toBeVisible(); + + await input.fill("25"); + await row.getByRole("button", { name: "Save" }).click(); + await expect(toast(page, "Saved.")).toBeVisible(); + await expect(budget.getByText(/of \$25\.00 this month/)).toBeVisible(); + await expect(row.getByRole("button", { name: "Save" })).toHaveCount(0); + + await page.reload(); + await expect(budget.getByText(/of \$25\.00 this month/)).toBeVisible(); + // The server writes the ceiling with its own precision; it is the same 25. + expect(Number(await input.inputValue())).toBe(25); + + // An empty field clears the ceiling rather than saving zero. + await input.fill(""); + await row.getByRole("button", { name: "Save" }).click(); + await expect(budget.getByText("spent this month · no ceiling")).toBeVisible(); + await page.reload(); + await expect(input).toHaveValue(""); + await expect(budget.getByText("spent this month · no ceiling")).toBeVisible(); +}); + +test("adds a project memory that says who wrote it", async ({ accountPage: page, account }) => { + const project = await createProject(account.token, `Remembered ${stamp()}`); + await openSettings(page, project.id); + const memory = section(page, "Project memory"); + const add = memory.getByRole("button", { name: "Add" }); + await expect(add).toBeDisabled(); + + const note = `The tide tables live in the shared drive ${stamp()}.`; + await memory.getByRole("textbox", { name: "Add a project memory" }).fill(note); + await add.click(); + const row = memory.getByRole("listitem").filter({ hasText: note }); + await expect(row).toBeVisible(); + await expect(row.getByText(/added by you/)).toBeVisible(); + await expect(memory.getByRole("textbox", { name: "Add a project memory" })).toHaveValue(""); + + await page.reload(); + await expect(memory.getByRole("listitem").filter({ hasText: note })).toBeVisible(); +}); + +test("each Save keeps the other fields' unsaved edits", async ({ accountPage: page, account }) => { + knownBug( + "web/app/routes/projects.$id/route.tsx:576-577 - SettingsTab.save() echoes BOTH name and " + + "budget from the server after any save, so saving the name throws away an unsaved budget edit", + ); + const project = await createProject(account.token, `Two edits ${stamp()}`); + await openSettings(page, project.id); + const nameRow = rowOf(page, "Project name"); + const budgetRow = rowOf(page, "Budget in USD"); + const instructions = section(page, "Instructions"); + + const renamed = `Two edits renamed ${stamp()}`; + await nameRow.getByRole("textbox", { name: "Project name" }).fill(renamed); + await budgetRow.getByRole("textbox", { name: "Budget in USD" }).fill("40"); + await instructions.getByRole("textbox", { name: "Project instructions" }).fill("Be brief."); + // Three dirty fields, three Saves: each belongs to its own section. + await expect( + page.getByRole("tabpanel", { name: "Settings" }).getByRole("button", { name: "Save" }), + ).toHaveCount(3); + + await nameRow.getByRole("button", { name: "Save" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(renamed); + await expect(instructions.getByRole("button", { name: "Save" })).toBeVisible(); + await expect(budgetRow.getByRole("textbox", { name: "Budget in USD" })).toHaveValue("40"); + await expect(budgetRow.getByRole("button", { name: "Save" })).toBeVisible(); +}); + +test.describe("ownership", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + test("transfers the project to a workspace member, and the old owner becomes an editor", async ({ + accountPage: page, + account, + browser, + baseURL, + }) => { + const heir = await signUp("e2e-project-settings", { name: "Hal Heir" }); + await verifyEmail(account); + await joinWorkspace(account, heir); + const project = await createProject(account.token, `Handed over ${stamp()}`); + await openSettings(page, project.id); + + const settings = page.getByRole("tabpanel", { name: "Settings" }); + await settings.getByRole("button", { name: "Transfer ownership" }).click(); + const dialog = page.getByRole("dialog", { name: "Transfer ownership" }); + const confirm = dialog.getByRole("button", { name: "Transfer ownership" }); + await expect(confirm).toBeDisabled(); + await dialog.getByRole("textbox", { name: "New owner's email" }).fill(heir.email); + await confirm.click(); + await expect(toast(page, "Ownership transferred.")).toBeVisible(); + await expect(dialog).toBeHidden(); + + // The old owner stays on as an editor, and every owner-only control is gone. + const main = page.getByRole("main"); + await expect(main.getByText("editor", { exact: true })).toBeVisible(); + for (const title of ["General", "Budget", "Danger zone", "Invite links"]) + await expect(settings.getByRole("heading", { name: title, exact: true })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Change project icon" })).toHaveCount(0); + await expect(main.getByRole("button", { name: "Invite", exact: true })).toHaveCount(0); + const people = section(page, "People"); + await expect(people.getByRole("listitem").filter({ hasText: heir.email })).toContainText( + "Owner", + ); + await expect(people.getByRole("listitem").filter({ hasText: account.email })).toContainText( + "Editor", + ); + + await page.reload(); + await expect(main.getByText("editor", { exact: true })).toBeVisible(); + await expect(settings.getByRole("heading", { name: "Danger zone" })).toHaveCount(0); + + // The new owner holds the owner's controls. + const theirs = await pageFor(browser, heir, baseURL!); + await openSettings(theirs, project.id); + await expect(theirs.getByRole("main").getByText("owner", { exact: true })).toBeVisible(); + await expect( + theirs + .getByRole("tabpanel", { name: "Settings" }) + .getByRole("heading", { name: "Danger zone" }), + ).toBeVisible(); + await theirs.context().close(); + }); +}); diff --git a/web/e2e/projects.spec.ts b/web/e2e/projects.spec.ts index acd8e50..2d4240d 100644 --- a/web/e2e/projects.spec.ts +++ b/web/e2e/projects.spec.ts @@ -4,7 +4,12 @@ * See the LICENSE file for details. */ -import { expect, test } from "./fixtures"; +import { joinWorkspace, signUp, verifyEmail } from "./support/accounts"; +import { call, createProject, stamp } from "./support/api"; +import { mailAvailable } from "./support/mailbox"; +import { expect, section, test } from "./fixtures"; + +/** A kit Section is a bare
under an h2: found by its heading, the only name it has. */ test("creates a project and opens it from the list", async ({ signedInPage: page }) => { const name = `Field research ${Date.now().toString(36)}`; @@ -31,3 +36,154 @@ test("creates a project and opens it from the list", async ({ signedInPage: page .click(); await expect(page).toHaveURL(projectUrl); }); + +test("a fresh account has no projects, and search narrows the list", async ({ + accountPage: page, + account, +}) => { + await page.goto("/projects"); + const main = page.getByRole("main"); + await expect(main.getByText("No projects yet")).toBeVisible(); + + const tag = stamp(); + await createProject(account.token, `Tide pools ${tag}`); + await createProject(account.token, `Lighthouse ${tag}`); + await page.reload(); + await expect(main.getByRole("link", { name: new RegExp(`Tide pools ${tag}`) })).toBeVisible(); + await expect(main.getByRole("link", { name: new RegExp(`Lighthouse ${tag}`) })).toBeVisible(); + + // The search is the server's: only the matching project stays. + const search = page.getByRole("textbox", { name: "Search projects…" }); + await search.fill("Lighthouse"); + await expect(main.getByRole("link", { name: new RegExp(`Lighthouse ${tag}`) })).toBeVisible(); + await expect(main.getByRole("link", { name: new RegExp(`Tide pools ${tag}`) })).toBeHidden(); + + await search.fill(`nothing-called-${tag}`); + await expect(main.getByText(`No matches for “nothing-called-${tag}”`)).toBeVisible(); + await expect(main.getByText("No projects yet")).toBeHidden(); + + await search.fill(""); + await expect(main.getByRole("link", { name: new RegExp(`Tide pools ${tag}`) })).toBeVisible(); +}); + +test.describe("projects shared with you", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + test("groups the list by role, and the grouping survives a reload", async ({ + accountPage: page, + account, + }) => { + // Someone else's workspace holds one project they share for editing and one for reading; + // joining it moves this account there, where it then makes a project of its own. + const host = await signUp("e2e-projects", { name: "Bea Host" }); + await verifyEmail(host); + await joinWorkspace(host, account); + const tag = stamp(); + const edited = await createProject(host.token, `Shared draft ${tag}`); + const read = await createProject(host.token, `Shared notes ${tag}`); + await call(`/projects/${edited.id}/members`, { + token: host.token, + body: { email: account.email, role: "editor" }, + }); + await call(`/projects/${read.id}/members`, { + token: host.token, + body: { email: account.email, role: "viewer" }, + }); + const own = await createProject(account.token, `My own ${tag}`); + + await page.goto("/projects"); + const main = page.getByRole("main"); + await expect( + main.getByRole("link", { name: new RegExp(`Shared draft ${tag}.*editor`) }), + ).toBeVisible(); + await expect( + main.getByRole("link", { name: new RegExp(`Shared notes ${tag}.*viewer`) }), + ).toBeVisible(); + await expect( + main.getByRole("link", { name: new RegExp(`My own ${tag}.*owner`) }), + ).toBeVisible(); + + await page.getByRole("button", { name: "Display options" }).click(); + await page.getByRole("menuitemradio", { name: "Role" }).click(); + await page.keyboard.press("Escape"); + await expect(page).toHaveURL(/[?&]group=role/); + + // Ownership first, then participation; each project sits under its own role. + await expect(main.getByRole("heading", { level: 2 })).toHaveText([ + "owners", + "editors", + "viewers", + ]); + await expect( + section(page, "owners").getByRole("link", { name: new RegExp(own.name) }), + ).toBeVisible(); + await expect( + section(page, "editors").getByRole("link", { name: new RegExp(edited.name) }), + ).toBeVisible(); + await expect( + section(page, "viewers").getByRole("link", { name: new RegExp(read.name) }), + ).toBeVisible(); + + // The grouping rides the URL, so a reload keeps it; None takes it off again. + await page.reload(); + await expect(main.getByRole("heading", { level: 2 })).toHaveText([ + "owners", + "editors", + "viewers", + ]); + await page.getByRole("button", { name: "Display options" }).click(); + await page.getByRole("menuitemradio", { name: "None" }).click(); + await page.keyboard.press("Escape"); + await expect(page).not.toHaveURL(/group=role/); + await expect(main.getByRole("heading", { level: 2 })).toHaveCount(0); + await expect(main.getByRole("link", { name: new RegExp(read.name) })).toBeVisible(); + }); +}); + +test("the project page shows its tabs, and the owner's icon pick persists", async ({ + accountPage: page, + account, +}) => { + const project = await createProject(account.token, `Harbour survey ${stamp()}`); + await page.goto(`/projects/${project.id}`); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(project.name); + + const tabs = page.getByRole("tablist"); + await expect(tabs.getByRole("tab")).toHaveText(["Tasks", "Artifacts", "Settings"]); + await expect(tabs.getByRole("tab", { name: "Tasks" })).toHaveAttribute("aria-selected", "true"); + + await tabs.getByRole("tab", { name: "Artifacts" }).click(); + const artifacts = page.getByRole("tabpanel", { name: "Artifacts" }); + await expect(artifacts.getByText("No artifacts yet")).toBeVisible(); + await expect(artifacts.getByRole("textbox", { name: "Search artifacts…" })).toBeVisible(); + + await tabs.getByRole("tab", { name: "Settings" }).click(); + await expect(page.getByRole("tabpanel", { name: "Settings" })).toBeVisible(); + + // The face is the owner's to change: pick a glyph and a colour, each saved as it lands. + await page.getByRole("button", { name: "Change project icon" }).click(); + const picker = page + .getByRole("dialog") + .filter({ has: page.getByRole("textbox", { name: "Search icons…" }) }); + const saved = () => + page.waitForResponse( + (r) => r.url().endsWith(`/v1/projects/${project.id}`) && r.request().method() === "PATCH", + ); + let patched = saved(); + await picker.getByRole("button", { name: "rocket", exact: true }).click(); + expect((await patched).ok()).toBe(true); + patched = saved(); + await picker.getByRole("radio", { name: "Color 3" }).click(); + expect((await patched).ok()).toBe(true); + await expect( + picker.getByRole("button", { name: "rocket", exact: true, pressed: true }), + ).toBeVisible(); + + await page.reload(); + await page.getByRole("button", { name: "Change project icon" }).click(); + await expect( + picker.getByRole("button", { name: "rocket", exact: true, pressed: true }), + ).toBeVisible(); + await expect(picker.getByRole("radio", { name: "Color 3" })).toBeChecked(); + await expect(picker.getByRole("radio", { name: "Neutral" })).not.toBeChecked(); +}); diff --git a/web/e2e/routines.spec.ts b/web/e2e/routines.spec.ts new file mode 100644 index 0000000..405be12 --- /dev/null +++ b/web/e2e/routines.spec.ts @@ -0,0 +1,266 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { call, createHeldRoutine, type Routine, stamp } from "./support/api"; +import { expect, knownBug, test, toast } from "./fixtures"; + +// Routines (ADR-048): standing work that mints an ordinary task on every fire. Nothing here may +// start a run, so a routine is fired only when its posture is hold (an event routine made in the +// dialog, or one made through the API with posture hold): a held fire mints a task that waits. +// A schedule routine made in the dialog runs on its own, so its When is a far-off yearly cron and +// the flow retires it before it ends. + +const FAR_CRON = "0 9 1 1 *"; + +/** The routine's detail peek. Toasts are dialogs too, hence the exact name. */ +function peekOf(page: Page) { + return page.getByRole("dialog", { name: "Routine", exact: true }); +} + +/** The list's row for a routine: its name, its When, then its status last. */ +function listRow(page: Page, name: string) { + return page.getByRole("main").getByRole("button", { name: new RegExp(`^${name} `) }); +} + +async function openNewRoutine(page: Page) { + await page.getByRole("button", { name: "New routine" }).click(); + return page.getByRole("dialog", { name: "New routine" }); +} + +/** Run now on a held routine (the only kind a flow may fire), once its peek is open. */ +async function runNow(page: Page) { + await peekOf(page).getByRole("button", { name: "Run now" }).click(); +} + +test("the New routine dialog needs a name, an instruction and a When", async ({ + accountPage: page, +}) => { + await page.goto("/routines"); + await expect(page.getByRole("main").getByText("No routines yet")).toBeVisible(); + + const dialog = await openNewRoutine(page); + const save = dialog.getByRole("button", { name: "Save routine" }); + await expect(dialog.getByText("Pick a When - a routine needs one.")).toBeVisible(); + await expect(save).toBeDisabled(); + await dialog.getByRole("textbox", { name: "Name" }).fill(`Briefing ${stamp()}`); + await expect(save).toBeDisabled(); + await dialog.getByRole("textbox", { name: "Instruction" }).fill("Summarize the week's tasks."); + await expect(save).toBeDisabled(); + + // Every way to say When reads back as one line beside Save. + for (const [preset, line] of [ + ["Every weekday, 9:00", "cron 0 9 * * 1-5"], + ["Every day, 9:00", "cron 0 9 * * *"], + ["Every hour", "cron 0 * * * *"], + ["Mondays, 9:00", "cron 0 9 * * 1"], + ] as const) { + await dialog.getByRole("button", { name: preset }).click(); + await expect(dialog.getByText(line, { exact: true })).toBeVisible(); + await expect(save).toBeEnabled(); + } + await dialog.getByPlaceholder(/^cron, e\.g\./).fill("30 8 * * 1-5"); + await expect(dialog.getByText("cron 30 8 * * 1-5", { exact: true })).toBeVisible(); + await dialog.getByPlaceholder(/^every, e\.g\./).fill("4h"); + await expect(dialog.getByText("every 4h", { exact: true })).toBeVisible(); + await expect(dialog.getByPlaceholder(/^cron, e\.g\./)).toHaveValue(""); + + // The events lane replaces the schedule; event routines say they start held. + await dialog.getByRole("button", { name: "a task delivers" }).click(); + await expect(dialog.getByText("when task.delivered", { exact: true })).toBeVisible(); + await expect(dialog.getByText(/Event routines start held/)).toBeVisible(); + await expect(dialog.getByPlaceholder(/^every, e\.g\./)).toHaveValue(""); + await dialog.getByRole("button", { name: "a task fails" }).click(); + await expect( + dialog.getByText("when task.delivered or task.failed", { exact: true }), + ).toBeVisible(); + await dialog.getByRole("button", { name: "a task delivers" }).click(); + await dialog.getByRole("button", { name: "a task fails" }).click(); + await expect(dialog.getByText("Pick a When - a routine needs one.")).toBeVisible(); + await expect(save).toBeDisabled(); + + // Closing saves nothing. + await dialog.getByRole("button", { name: "Close" }).click(); + await expect(dialog).toBeHidden(); + await expect(page.getByRole("main").getByText("No routines yet")).toBeVisible(); +}); + +test("refuses a cron the server cannot read, with its reason", async ({ accountPage: page }) => { + await page.goto("/routines"); + const dialog = await openNewRoutine(page); + await dialog.getByRole("textbox", { name: "Name" }).fill(`Broken clock ${stamp()}`); + await dialog.getByRole("textbox", { name: "Instruction" }).fill("Never mind."); + await dialog.getByPlaceholder(/^cron, e\.g\./).fill("99 99 * * *"); + await dialog.getByRole("button", { name: "Save routine" }).click(); + await expect(toast(page, "cron rejected: Bad minute")).toBeVisible(); + // The dialog stays with the draft, and nothing was saved. + await expect(dialog).toBeVisible(); + await expect(dialog.getByPlaceholder(/^cron, e\.g\./)).toHaveValue("99 99 * * *"); + await dialog.getByRole("button", { name: "Close" }).click(); + await expect(page.getByRole("main").getByText("No routines yet")).toBeVisible(); +}); + +test("saves a schedule routine, pauses, resumes and retires it", async ({ accountPage: page }) => { + const name = `Yearly review ${stamp()}`; + await page.goto("/routines"); + const dialog = await openNewRoutine(page); + await dialog.getByRole("textbox", { name: "Name" }).fill(name); + await dialog.getByRole("textbox", { name: "Instruction" }).fill("Review the year's projects."); + await dialog.getByPlaceholder(/^cron, e\.g\./).fill(FAR_CRON); + await dialog.getByRole("textbox", { name: "Budget per run" }).fill("1.50"); + await dialog.getByRole("button", { name: "Save routine" }).click(); + await expect(toast(page, /^Routine saved - cron 0 9 1 1 \*, first fire /)).toBeVisible(); + + // Saving opens its peek, deep-linked by id. + const peek = peekOf(page); + await expect(peek.getByRole("heading", { level: 2, name })).toBeVisible(); + await expect(page).toHaveURL(/\/routines\?routine=[0-9a-f-]{36}$/); + const url = page.url(); + await expect(peek.getByText(`When: cron ${FAR_CRON}`)).toBeVisible(); + await expect(peek.getByText("$1.50 / run")).toBeVisible(); + await expect( + peek.getByText("No fires yet - the ledger starts with the first one."), + ).toBeVisible(); + + await page.reload(); + await expect(page).toHaveURL(url); + await expect(peek.getByRole("heading", { level: 2, name })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(peek).toBeHidden(); + await expect(page).toHaveURL(/\/routines$/); + await expect(listRow(page, name)).toHaveAccessibleName(new RegExp(`cron 0 9 1 1 \\* .*active$`)); + + await listRow(page, name).click(); + await peek.getByRole("button", { name: "Pause" }).click(); + await expect(toast(page, "Paused.")).toBeVisible(); + await expect(peek.getByRole("button", { name: "Resume" })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(listRow(page, name)).toHaveAccessibleName(/paused$/); + + await listRow(page, name).click(); + await peek.getByRole("button", { name: "Resume" }).click(); + await expect(toast(page, "Resumed - next fire recomputed.")).toBeVisible(); + await expect(peek.getByRole("button", { name: "Pause" })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(listRow(page, name)).toHaveAccessibleName(/active$/); + + // Retiring closes the peek and keeps the row, retired, with no way to fire it again. + await listRow(page, name).click(); + await peek.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Retire routine" }).click(); + await expect(toast(page, "Retired - the run history stays.")).toBeVisible(); + await expect(peek).toBeHidden(); + await expect(listRow(page, name)).toHaveAccessibleName(/retired$/); + await page.reload(); + await listRow(page, name).click(); + await expect(peek.getByRole("heading", { level: 2, name })).toBeVisible(); + await expect(peek.getByRole("button", { name: "Run now" })).toHaveCount(0); + await expect(peek.getByRole("button", { name: "Pause" })).toHaveCount(0); +}); + +test("an event routine is held, and Run now mints a held run that opens in the sheet", async ({ + accountPage: page, +}) => { + const name = `Delivery digest ${stamp()}`; + await page.goto("/routines"); + const dialog = await openNewRoutine(page); + await dialog.getByRole("textbox", { name: "Name" }).fill(name); + await dialog.getByRole("textbox", { name: "Instruction" }).fill("Digest what was delivered."); + await dialog.getByRole("button", { name: "a task delivers" }).click(); + await dialog.getByRole("button", { name: "Save routine" }).click(); + await expect(toast(page, "Routine saved - when task.delivered.")).toBeVisible(); + + const peek = peekOf(page); + await expect(peek.getByRole("heading", { level: 2, name })).toBeVisible(); + // Held is what makes Run now safe here: the fire mints a task that waits for a person. + await expect( + peek.getByText("When: when task.delivered · runs wait for your release"), + ).toBeVisible(); + + await runNow(page); + await expect(toast(page, "Fired - the run shows below.")).toBeVisible(); + const run = peek.getByRole("button", { name: /^held manual · / }); + await expect(run).toHaveCount(1); + + // A run opens its task in the same sheet, with the way back. + await run.click(); + await expect(page).toHaveURL(/[?&]run=[0-9a-f-]{36}/); + await expect(peek.getByText(`${name} · run`)).toBeVisible(); + await expect(peek.getByText("Digest what was delivered.")).toBeVisible(); + await peek.getByRole("button", { name: "Back to the routine" }).click(); + await expect(page).not.toHaveURL(/run=/); + await expect(peek.getByRole("heading", { level: 2, name })).toBeVisible(); + + await page.keyboard.press("Escape"); + await expect(listRow(page, name)).toHaveAccessibleName(/when task\.delivered active$/); +}); + +test("a fire token fires a held routine until it is revoked", async ({ + accountPage: page, + account, +}) => { + const routine: Routine = await createHeldRoutine(account.token, { + name: `Webhook ${stamp()}`, + instruction: "Note the webhook's arrival.", + }); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto(`/routines?routine=${routine.id}`); + const peek = peekOf(page); + await expect(peek.getByRole("heading", { level: 2, name: routine.name })).toBeVisible(); + + await peek.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Mint fire token…" }).click(); + await expect(toast(page, /^Fire token copied\. Shown once/)).toBeVisible(); + const token = await page.evaluate(() => navigator.clipboard.readText()); + expect(token).toMatch(/^rt_/); + + // The token alone opens the routine's fire door. + const fired = await call<{ decision: string }>(`/routines/${routine.id}/fire`, { + token, + body: {}, + }); + expect(fired.decision).toBe("held"); + await page.reload(); + await expect(peek.getByRole("button", { name: /^held api · / })).toBeVisible(); + + await peek.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Revoke fire token" }).click(); + await expect(toast(page, "Fire door closed.")).toBeVisible(); + await expect(call(`/routines/${routine.id}/fire`, { token, body: {} })).rejects.toMatchObject({ + status: 401, + }); +}); + +test("Run now on a routine whose season is over says the fire was skipped", async ({ + accountPage: page, + account, +}) => { + knownBug( + "web/app/routes/routines/route.tsx:297 - Run now toasts 'Fired - the run shows below.' for " + + "every answer, even a skipped fire that minted nothing (here skipped_season, which retires it)", + ); + // A held routine allowed one run, which it has already had: the next fire is skipped. + const routine = await call("/routines", { + token: account.token, + body: { + name: `One season ${stamp()}`, + instruction: "Only once.", + schedule: { cron: FAR_CRON, timezone: "UTC" }, + posture: "hold", + max_runs: 1, + }, + }); + await call(`/routines/${routine.id}/fire`, { token: account.token, body: {} }); + await page.goto(`/routines?routine=${routine.id}`); + const peek = peekOf(page); + await expect(peek.getByRole("button", { name: /^held manual · / })).toBeVisible(); + + await runNow(page); + // The answer lands first: the routine retires, so Run now goes away. + await expect(peek.getByRole("button", { name: "Run now" })).toHaveCount(0); + // A toast that has already shown cannot be waited away, so this reads it once, no retry. + expect(await toast(page, "Fired - the run shows below.").count()).toBe(0); +}); diff --git a/web/e2e/seed.ts b/web/e2e/seed.ts index 10ea19b..4d6562d 100644 --- a/web/e2e/seed.ts +++ b/web/e2e/seed.ts @@ -4,13 +4,15 @@ * See the LICENSE file for details. */ -// What the flows share: one account and one task record, made through the API before any test -// runs (global-setup.ts) and read back by every spec. Nothing here calls a model. +// What the flows share: one account with one held task, made through the API before any test runs +// (global-setup.ts) and read back by every spec, plus the operator account the console flows sign in +// with when the stack let global-setup make one. Nothing here calls a model. import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; -export const API_URL = process.env.E2E_API_URL ?? "http://127.0.0.1:8304"; -export const SEED_FILE = fileURLToPath(new URL("./.state/seed.json", import.meta.url)); +/** E2E_STATE_DIR moves the run's state, so two runs against one stack never share a seed file. */ +const STATE_DIR = process.env.E2E_STATE_DIR ?? fileURLToPath(new URL("./.state", import.meta.url)); +export const SEED_FILE = `${STATE_DIR}/seed.json`; export type Seed = { email: string; @@ -20,27 +22,10 @@ export type Seed = { expiresAt: string; /** A routine fired with posture "hold": its task exists, is held, and never runs. */ task: { id: string; title: string; goal: string }; + /** An account holding the operator scope, or null when this process cannot grant one. */ + admin: { email: string; password: string; name: string; token: string; expiresAt: string } | null; }; export function readSeed(): Seed { return JSON.parse(readFileSync(SEED_FILE, "utf8")) as Seed; } - -/** One API call with the seed's bearer; throws on any status outside 2xx, naming the body. */ -export async function call( - path: string, - init: { method?: string; token?: string; body?: unknown } = {}, -): Promise { - const response = await fetch(`${API_URL}/v1${path}`, { - method: init.method ?? "GET", - headers: { - "content-type": "application/json", - ...(init.token ? { authorization: `Bearer ${init.token}` } : {}), - }, - body: init.body === undefined ? undefined : JSON.stringify(init.body), - }); - const text = await response.text(); - if (!response.ok) - throw new Error(`${init.method ?? "GET"} ${path} -> ${response.status}: ${text}`); - return (text ? JSON.parse(text) : undefined) as T; -} diff --git a/web/e2e/settings.spec.ts b/web/e2e/settings.spec.ts index 173ca13..6999107 100644 --- a/web/e2e/settings.spec.ts +++ b/web/e2e/settings.spec.ts @@ -4,7 +4,9 @@ * See the LICENSE file for details. */ -import { expect, test } from "./fixtures"; +import type { Locator } from "@playwright/test"; +import { call, stamp } from "./support/api"; +import { accountMenu, expect, knownBug, openSettings, test, toast } from "./fixtures"; test("edits the profile name in settings and keeps it", async ({ signedInPage: page, seed }) => { await page.goto("/"); @@ -44,3 +46,222 @@ test("switches the appearance to dark", async ({ signedInPage: page, seed }) => await page.keyboard.press("Escape"); await expect(settings).toBeHidden(); }); + +// The flows below each take a fresh account: they change what the account keeps (its timezone, +// memories, keys, workspace name), or read an empty state the shared account no longer has. +test.describe("settings on a fresh account", () => { + /** The rail names Account's General and Workspace's General alike; Workspace's is the second. */ + const workspaceGeneral = (settings: Locator) => + settings.getByRole("button", { name: "General", exact: true }).nth(1); + + test("saves the timezone and keeps it", async ({ accountPage: page, account }) => { + await page.goto("/"); + let settings = await openSettings(page, account.email); + const zone = settings.getByRole("combobox", { name: "Timezone" }); + await expect(zone).toHaveText("UTC"); + await zone.click(); + await page.getByRole("option", { name: "Europe/Paris", exact: true }).click(); + await expect(toast(page, "Timezone saved.")).toBeVisible(); + await expect(zone).toHaveText("Europe/Paris"); + + await page.reload(); + settings = await openSettings(page, account.email); + await expect(settings.getByRole("combobox", { name: "Timezone" })).toHaveText("Europe/Paris"); + }); + + test("adds memories by hand and finds them by search", async ({ accountPage: page, account }) => { + await page.goto("/"); + let settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Memory", exact: true }).click(); + await expect(settings.getByText("Nothing remembered yet")).toBeVisible(); + + const add = async (text: string, kind: string) => { + await settings.getByRole("button", { name: "Add memory" }).click(); + const dialog = page.getByRole("dialog", { name: "Add a memory" }); + await dialog.getByRole("textbox", { name: "Memory" }).fill(text); + await dialog.getByRole("button", { name: kind, exact: true }).click(); + await dialog.getByRole("button", { name: "Add memory" }).click(); + await expect(dialog).toBeHidden(); + }; + await add("Prefers tide tables in metric units.", "preference"); + await add("The field station is on the north shore.", "fact"); + const rows = settings.getByRole("listitem"); + await expect(rows).toHaveCount(2); + const tides = rows.filter({ hasText: "Prefers tide tables in metric units." }); + await expect(tides).toContainText("Preference"); + await expect(tides).toContainText("added by you"); + await expect(rows.filter({ hasText: "The field station" })).toContainText("Fact"); + + // Search narrows the list to what matches, and says so when nothing does. + const search = settings.getByRole("textbox", { name: "Search memories…" }); + await search.fill("north shore"); + await expect(rows).toHaveCount(1); + await expect(rows).toContainText("The field station is on the north shore."); + await search.fill("volcano"); + await expect(settings.getByText("No matches for “volcano”")).toBeVisible(); + await search.fill(""); + await expect(rows).toHaveCount(2); + + await page.reload(); + settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Memory", exact: true }).click(); + await expect(tides).toContainText("Preference"); + await expect(rows).toHaveCount(2); + }); + + test("edits a memory in place", async ({ accountPage: page, account }) => { + knownBug( + "backend/prismoid/api/serializers/memories.py:83 reads updated_at after " + + "operations/memory.py:174 committed and expired it, so PATCH /v1/memories/{id} answers " + + "500 (MissingGreenlet) although the edit is saved; the row stays open in edit mode", + ); + await call("/memories", { + token: account.token, + body: { scope: "user", kind: "preference", text: "Prefers tide tables in metric units." }, + }); + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Memory", exact: true }).click(); + const rows = settings.getByRole("listitem"); + await rows.hover(); + await rows.getByRole("button", { name: "Edit" }).click(); + // The edit box has no label of its own, so it is the row's only textbox. + const box = rows.getByRole("textbox"); + await expect(box).toHaveValue("Prefers tide tables in metric units."); + await box.fill("Prefers tide tables in feet."); + await rows.getByRole("button", { name: "Save" }).click(); + + await expect(box).toBeHidden(); + await expect(rows).toContainText("Prefers tide tables in feet."); + await page.reload(); + const reopened = await openSettings(page, account.email); + await reopened.getByRole("button", { name: "Memory", exact: true }).click(); + await expect(reopened.getByRole("listitem")).toContainText("Prefers tide tables in feet."); + }); + + test("retires a memory", async ({ accountPage: page, account }) => { + knownBug( + "backend/prismoid/api/serializers/memories.py:83 reads updated_at after " + + "operations/memory.py:186 committed and expired it, so POST /v1/memories/{id}/retire " + + "answers 500 (MissingGreenlet) although the memory is retired; the row stays listed", + ); + await call("/memories", { + token: account.token, + body: { scope: "user", kind: "fact", text: "The field station is on the north shore." }, + }); + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Memory", exact: true }).click(); + const row = settings.getByRole("listitem").filter({ hasText: "The field station" }); + await row.hover(); + await row.getByRole("button", { name: "Retire" }).click(); + + await expect(row).toBeHidden(); + await expect(settings.getByText("Nothing remembered yet")).toBeVisible(); + await page.reload(); + const reopened = await openSettings(page, account.email); + await reopened.getByRole("button", { name: "Memory", exact: true }).click(); + await expect(reopened.getByText("Nothing remembered yet")).toBeVisible(); + }); + + test("creates an API key that works, then revokes it", async ({ accountPage: page, account }) => { + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "API keys", exact: true }).click(); + await expect(settings.getByText("No API keys yet")).toBeVisible(); + + await settings.getByRole("button", { name: "New key" }).click(); + const dialog = page.getByRole("dialog", { name: "New API key" }); + await dialog.getByRole("textbox", { name: "Name" }).fill("Tide station CLI"); + await dialog.getByRole("button", { name: "Create key" }).click(); + const shown = page.getByRole("dialog", { name: "Copy your key now" }); + const key = (await shown.getByText(/^ck_/).textContent())?.trim() ?? ""; + expect(key).toMatch(/^ck_/); + await shown.getByRole("button", { name: "Done" }).click(); + await expect(shown).toBeHidden(); + + // The key is a real credential: the API answers it as this person. + const me = await call<{ email: string }>("/auth/me", { token: key }); + expect(me.email).toBe(account.email); + + const row = settings.getByRole("listitem").filter({ hasText: "Tide station CLI" }); + await expect(row).toBeVisible(); + await row.getByRole("button", { name: "Revoke" }).click(); + await expect(row).toContainText("revoked"); + await expect(row.getByRole("button", { name: "Revoke" })).toBeHidden(); + await expect(call("/auth/me", { token: key })).rejects.toMatchObject({ status: 401 }); + }); + + test("renames the workspace and the switcher wears the name", async ({ + accountPage: page, + account, + }) => { + const name = `Tide Lab ${stamp()}`; + const slug = `tide-lab-${stamp()}`; + await page.goto("/"); + let settings = await openSettings(page, account.email); + await workspaceGeneral(settings).click(); + const save = settings.getByRole("button", { name: "Save" }); + await expect(settings.getByRole("textbox", { name: "Name" })).toHaveValue( + account.workspace.name, + ); + await expect(save).toBeDisabled(); + await settings.getByRole("textbox", { name: "Name" }).fill(name); + await settings.getByRole("textbox", { name: "Slug" }).fill(slug); + await save.click(); + await expect(toast(page, "Workspace saved.")).toBeVisible(); + + await page.keyboard.press("Escape"); + await expect(settings).toBeHidden(); + await expect(page.getByRole("button", { name: "Switch workspace" })).toContainText(name); + + await page.reload(); + await expect(page.getByRole("button", { name: "Switch workspace" })).toContainText(name); + settings = await openSettings(page, account.email); + await workspaceGeneral(settings).click(); + await expect(settings.getByRole("textbox", { name: "Name" })).toHaveValue(name); + await expect(settings.getByRole("textbox", { name: "Slug" })).toHaveValue(slug); + }); + + test("lists the builtin skills", async ({ accountPage: page, account }) => { + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Skills", exact: true }).click(); + await expect(settings.getByRole("heading", { name: "Skills" })).toBeVisible(); + for (const skill of ["analyze", "research", "report", "summarize"]) { + await expect(settings.getByText(skill, { exact: true })).toBeVisible(); + } + }); + + test("the connectors pane starts empty and hands off to the connectors page", async ({ + accountPage: page, + account, + }) => { + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Connectors", exact: true }).click(); + await expect(settings.getByText("No connectors yet")).toBeVisible(); + await settings.getByRole("button", { name: "Open connectors" }).click(); + // The dialog puts itself away, or the page would open inert behind it. + await expect(settings).toBeHidden(); + await expect(page).toHaveURL(/\/connectors$/); + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toHaveText("Connectors"); + }); + + test("the help pane opens from the rail and from the account menu", async ({ + accountPage: page, + account, + }) => { + await page.goto("/"); + const settings = await openSettings(page, account.email); + await settings.getByRole("button", { name: "Get help", exact: true }).click(); + await expect(settings.getByRole("heading", { name: "Get help" })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(settings).toBeHidden(); + + // With no support address configured, the menu's Get help opens the same pane. + await accountMenu(page, account.email).click(); + await page.getByRole("menuitem", { name: "Get help" }).click(); + await expect(settings.getByRole("heading", { name: "Get help" })).toBeVisible(); + }); +}); diff --git a/web/e2e/shell.spec.ts b/web/e2e/shell.spec.ts new file mode 100644 index 0000000..0ad68b9 --- /dev/null +++ b/web/e2e/shell.spec.ts @@ -0,0 +1,157 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { createHeldTask } from "./support/api"; +import { accountMenu, composer, escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; + +// The app shell: the sidebar's nav, its collapse, the global chords, the account menu and the +// recent-task rows. Every flow runs on a fresh account, so its sidebar holds only what it made. + +/** A recent-task row's link in the sidebar: its name is the status mark's label, then the title. */ +function taskLink(page: Page, title: string) { + return page.getByRole("link", { name: new RegExp(`${escapeRegExp(title)}$`) }); +} + +test.describe("app shell", () => { + test("every sidebar nav link reaches its page", async ({ accountPage: page }) => { + await page.goto("/allowed-sites"); + const crumbs = page.getByRole("navigation", { name: "Breadcrumb" }); + for (const name of [ + "Inbox", + "Tasks", + "Projects", + "Routines", + "Bots", + "Connectors", + "Allowed sites", + ]) { + await page.getByRole("link", { name, exact: true }).click(); + await expect(crumbs).toHaveText(name); + } + // Home is the landing: no trail, the composer. + await page.getByRole("link", { name: "Home", exact: true }).click(); + await expect(page).toHaveURL(/\/$/); + await expect(composer(page)).toBeVisible(); + await expect(crumbs).toBeHidden(); + }); + + test("the sidebar collapses to its rail and back, by button and by chord", async ({ + accountPage: page, + }) => { + await page.goto("/tasks"); + const switcher = page.getByRole("button", { name: "Switch workspace" }); + const expand = page.getByRole("button", { name: "Expand sidebar" }); + await expect(switcher).toBeVisible(); + + await page.getByRole("button", { name: "Toggle Sidebar", exact: true }).click(); + await expect(expand).toBeVisible(); + await expect(switcher).toBeHidden(); + await expand.click(); + await expect(switcher).toBeVisible(); + await expect(expand).toBeHidden(); + + await page.keyboard.press("ControlOrMeta+b"); + await expect(expand).toBeVisible(); + await page.keyboard.press("ControlOrMeta+b"); + await expect(switcher).toBeVisible(); + }); + + test("the new-task chord goes home from any page", async ({ accountPage: page }) => { + await page.goto("/routines"); + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toHaveText("Routines"); + await page.keyboard.press("ControlOrMeta+Shift+O"); + await expect(page).toHaveURL(/\/$/); + await expect(composer(page)).toBeVisible(); + }); + + test("the account menu's Usage opens Settings on the usage pane", async ({ + accountPage: page, + account, + }) => { + await page.goto("/"); + await accountMenu(page, account.email).click(); + await page.getByRole("menuitem", { name: "Usage" }).click(); + const settings = page.getByRole("dialog", { name: "Settings" }); + await expect(settings.getByRole("heading", { name: "Usage" })).toBeVisible(); + await expect(settings.getByRole("button", { name: "Usage" })).toHaveAttribute( + "aria-current", + "true", + ); + await expect(settings.getByText("No projects yet")).toBeVisible(); + }); + + test("renames a recent task in place and keeps the name", async ({ + accountPage: page, + account, + }) => { + const task = await createHeldTask(account.token, "Summarize the tide pool field notes"); + await page.goto("/allowed-sites"); + await expect(taskLink(page, task.title)).toBeVisible(); + + await page.getByRole("button", { name: `Task actions for ${task.title}` }).click(); + await page.getByRole("menuitem", { name: "Rename" }).click(); + const field = page.getByRole("textbox", { name: "Task name" }); + await expect(field).toHaveValue(task.title); + await field.fill("Tide pool notes, renamed"); + await field.press("Enter"); + await expect(taskLink(page, "Tide pool notes, renamed")).toBeVisible(); + + await page.reload(); + await expect(taskLink(page, "Tide pool notes, renamed")).toBeVisible(); + await expect(taskLink(page, task.title)).toBeHidden(); + }); + + test("pins a recent task above the rest and unpins it", async ({ + accountPage: page, + account, + }) => { + const task = await createHeldTask(account.token, "Summarize the tide pool field notes"); + await page.goto("/allowed-sites"); + const pinned = page.getByText("Pinned", { exact: true }); + await expect(pinned).toBeHidden(); + + await page.getByRole("button", { name: `Task actions for ${task.title}` }).click(); + await page.getByRole("menuitem", { name: "Pin" }).click(); + await expect(pinned).toBeVisible(); + // The only task moved, so the recent group is gone with it. + await expect(page.getByText("Recent tasks", { exact: true })).toBeHidden(); + + await page.reload(); + await expect(pinned).toBeVisible(); + await page.getByRole("button", { name: `Task actions for ${task.title}` }).click(); + await page.getByRole("menuitem", { name: "Unpin" }).click(); + await expect(pinned).toBeHidden(); + await expect(page.getByText("Recent tasks", { exact: true })).toBeVisible(); + + await page.reload(); + await expect(pinned).toBeHidden(); + await expect(taskLink(page, task.title)).toBeVisible(); + }); + + test("a held task the server will not delete stays listed", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/components/tasks/task-window.tsx:206 drops the row before the DELETE answers and " + + "never puts it back when the server refuses (409 for a task that is not settled), so the " + + "sidebar hides a task that still exists until the next navigation", + ); + const task = await createHeldTask(account.token, "Summarize the tide pool field notes"); + await page.goto("/allowed-sites"); + await page.getByRole("button", { name: `Task actions for ${task.title}` }).click(); + await page.getByRole("menuitem", { name: "Delete" }).click(); + const confirm = page.getByRole("alertdialog", { name: "Delete this task?" }); + await confirm.getByRole("button", { name: "Delete task" }).click(); + + // The refusal is said out loud... + await expect(toast(page, "cancel the task before deleting it")).toBeVisible(); + await expect(confirm).toBeHidden(); + // ...and the task, which still exists, is still listed. + await expect(taskLink(page, task.title)).toBeVisible(); + }); +}); diff --git a/web/e2e/sign-in.spec.ts b/web/e2e/sign-in.spec.ts index dc1c38a..45fde15 100644 --- a/web/e2e/sign-in.spec.ts +++ b/web/e2e/sign-in.spec.ts @@ -35,4 +35,32 @@ test.describe("sign-in", () => { await page.goto("/tasks"); await expect(page).toHaveURL(/\/login/); }); + + // The page signs in a fresh account (not the shared one): the login door counts sign-ins per + // account, and this run's other form sign-ins already spend the shared account's. + test("a signed-out deep link comes back to its page after sign-in", async ({ page, account }) => { + await page.goto("/projects"); + await expect(page).toHaveURL(/\/login\?next=%2Fprojects$/); + await expect(page.getByRole("heading", { name: "Welcome back" })).toBeVisible(); + + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("textbox", { name: "Password" }).fill(account.password); + await page.getByRole("button", { name: "Sign in" }).click(); + + await expect(page).toHaveURL(/\/projects$/); + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toHaveText("Projects"); + }); + + test("the form's account link opens signup and keeps the way back", async ({ page }) => { + await page.goto("/projects"); + await expect(page).toHaveURL(/\/login\?next=%2Fprojects$/); + await page.getByRole("link", { name: "Create an account" }).click(); + + // Someone without an account yet still lands where the link was taking them once they have one. + await expect(page).toHaveURL(/\/signup\?next=%2Fprojects$/); + await expect(page.getByRole("heading", { name: "Create your account" })).toBeVisible(); + await page.getByRole("link", { name: "Sign in" }).click(); + await expect(page).toHaveURL(/\/login\?next=%2Fprojects$/); + await expect(page.getByRole("heading", { name: "Welcome back" })).toBeVisible(); + }); }); diff --git a/web/e2e/signup.spec.ts b/web/e2e/signup.spec.ts new file mode 100644 index 0000000..16d0de8 --- /dev/null +++ b/web/e2e/signup.spec.ts @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { PASSWORD } from "./support/accounts"; +import { stamp } from "./support/api"; +import { mailAvailable, waitForMail } from "./support/mailbox"; +import { accountMenu, composer, expect, knownBug, test } from "./fixtures"; + +// Signup from the form: the person gets an account, their own workspace and a session at once, and +// the address is proved later by the emailed link. Every flow signs up an address of its own. +test.describe("signup", () => { + test("creates an account from the form and emails a verification link", async ({ page }) => { + const email = `e2e-signup-${stamp()}@example.com`; + await page.goto("/signup"); + await expect(page.getByRole("heading", { name: "Create your account" })).toBeVisible(); + await page.getByRole("textbox", { name: "Name" }).fill("Sam Signup"); + await page.getByRole("textbox", { name: "Email" }).fill(email); + await page.getByRole("textbox", { name: "Password" }).fill(PASSWORD); + await expect(page.getByRole("textbox", { name: "Invite code (optional)" })).toHaveValue(""); + await page.getByRole("button", { name: "Create account" }).click(); + + await expect(composer(page)).toBeVisible(); + await expect(accountMenu(page, email)).toContainText("Sam Signup"); + // A new person starts in a workspace of their own. + await expect(page.getByRole("button", { name: "Switch workspace" })).toContainText( + "Sam Signup's workspace", + ); + // The email is read from the stack's log; a stack whose log this run cannot read still proves + // the form above. + if (mailAvailable()) { + const mail = await waitForMail(email, /Verify your email/); + expect(mail.body).toContain("/verify-email#ev_"); + } + }); + + test("a short password is refused before anything is sent", async ({ page }) => { + await page.goto("/signup"); + await page.getByRole("textbox", { name: "Name" }).fill("Sam Signup"); + await page.getByRole("textbox", { name: "Email" }).fill(`e2e-signup-${stamp()}@example.com`); + await page.getByRole("textbox", { name: "Password" }).fill("too short"); + await page.getByRole("button", { name: "Create account" }).click(); + await expect(page.getByText("Use at least 12 characters.")).toBeVisible(); + await expect(page).toHaveURL(/\/signup$/); + }); + + test("an address that already has an account is refused in words", async ({ page, account }) => { + // The API refuses an existing address with a deliberately vague 403 (it never confirms which + // addresses exist), so the form owes the person its own written sentence, not the server's. + knownBug( + "web/app/routes/signup/route.tsx:57 maps only a 409 to written copy, but the API refuses an " + + "existing address with a 403 (backend/prismoid/operations/auth.py:168), so the form shows " + + 'the raw lowercase "that email cannot be registered" and the 409 branch is dead code', + ); + await page.goto("/signup"); + await page.getByRole("textbox", { name: "Name" }).fill("Sam Signup"); + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("textbox", { name: "Password" }).fill(PASSWORD); + const refused = page.waitForResponse((r) => r.url().endsWith("/v1/auth/signup")); + await page.getByRole("button", { name: "Create account" }).click(); + expect((await refused).status()).toBe(403); + // The refusal keeps the person on the form, signed out, with a sentence of the form's own. + await expect(page).toHaveURL(/\/signup$/); + await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled(); + await expect(page.getByText("that email cannot be registered", { exact: true })).toHaveCount(0); + }); +}); diff --git a/web/e2e/stack.sh b/web/e2e/stack.sh index ce8c3e0..d3c7847 100755 --- a/web/e2e/stack.sh +++ b/web/e2e/stack.sh @@ -9,9 +9,18 @@ # app itself, playwright.config.ts) and tears everything down again, pass or fail. # # Its ports sit away from the dev stack's (5433, 9000, 8100, 5173), so both can run at once; move -# them with E2E_PG_PORT, E2E_MINIO_PORT, E2E_API_PORT and E2E_WEB_PORT. E2E_STACK=external skips -# the boot and runs the flows against the API at E2E_API_URL. Arguments go to `playwright test`. -# No provider key is needed: no flow asks a model for anything. +# them with E2E_PG_PORT, E2E_MINIO_PORT, E2E_API_PORT, E2E_WEB_PORT and E2E_ADMIN_WEB_PORT (the +# operator console, its own bundle). E2E_STACK=external skips the boot and runs the flows against +# the API at E2E_API_URL; the flows that read email (E2E_API_LOG) or need an operator account +# (PRISMOID_API_DATABASE_URL, for `prismoid admin bootstrap`) skip themselves when those are unset. +# Arguments go to `playwright test`. +# +# Models: by default every provider key is blanked for the worker and the API (an exported empty +# value beats a key in backend/.env), so no core flow can reach a model even by accident. +# E2E_MODELS=1 (`just e2e-models`) keeps the keys in the environment, refuses to start without one, +# and defines Playwright's `models` project, whose flows send real work to a real model. A document's +# verification runs in a throwaway frame on the compose frame network, so it also refuses to start +# without that network (`just up` makes it, with the egress proxy that guards it). set -euo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd)" @@ -20,10 +29,12 @@ PG_PORT="${E2E_PG_PORT:-55574}" MINIO_PORT="${E2E_MINIO_PORT:-55584}" API_PORT="${E2E_API_PORT:-8304}" WEB_PORT="${E2E_WEB_PORT:-5304}" +ADMIN_WEB_PORT="${E2E_ADMIN_WEB_PORT:-5305}" SILO_IMAGE="pgsty/silo:RELEASE.2026-10-26T00-00-00Z@sha256:7bb2aff6b89efe1cb1303c10fc21d579447434ed06649ac9ec05a5e2dbf30ad7" LOGS="${E2E_LOGS:-$ROOT/web/e2e/.state/logs}" export E2E_API_URL="${E2E_API_URL:-http://127.0.0.1:$API_PORT}" export E2E_WEB_PORT="$WEB_PORT" +export E2E_ADMIN_WEB_PORT="$ADMIN_WEB_PORT" run_flows() { cd "$ROOT/web" @@ -36,6 +47,24 @@ if [ "${E2E_STACK:-}" = "external" ]; then exit fi +KEYS=(PRISMOID_WORKER_ANTHROPIC_API_KEY PRISMOID_WORKER_OPENAI_API_KEY PRISMOID_WORKER_GOOGLE_API_KEY) +if [ "${E2E_MODELS:-}" = "1" ]; then + has_key="" + for key in "${KEYS[@]}"; do [ -n "${!key:-}" ] && has_key=1; done + if [ -z "$has_key" ]; then + echo "e2e: E2E_MODELS=1 needs a provider key in the environment: ${KEYS[*]}" >&2 + exit 1 + fi + if ! docker network inspect prismoid_frame_net >/dev/null 2>&1; then + echo "e2e: the model flows verify documents in a frame, on the network prismoid_frame_net:" >&2 + echo " start it and its egress proxy with \`just up\` (or docker compose -f" >&2 + echo " backend/deploy/compose.yaml up -d --wait egress-proxy)" >&2 + exit 1 + fi +else + for key in "${KEYS[@]}"; do export "$key="; done +fi + PIDS=() cleanup() { local status=$? @@ -46,6 +75,11 @@ cleanup() { wait "$pid" 2>/dev/null || true done docker rm -f "$NAME-pg" "$NAME-minio" >/dev/null 2>&1 || true + # A model run that took a Machine leaves its container behind the worker: every frame wears the + # stack's instance label, so this removes exactly this stack's. + local frames + frames=$(docker ps -aq --filter "label=plane.instance=$NAME" 2>/dev/null || true) + [ -z "$frames" ] || docker rm -f $frames >/dev/null 2>&1 || true [ "$status" -eq 0 ] || echo "e2e: failed - the API and worker logs are in $LOGS" >&2 exit "$status" } @@ -70,7 +104,9 @@ docker run -d --name "$NAME-pg" -p "127.0.0.1:$PG_PORT:5432" \ docker run -d --name "$NAME-minio" -p "127.0.0.1:$MINIO_PORT:9000" \ -e MINIO_ROOT_USER=prismoid -e MINIO_ROOT_PASSWORD=prismoid1234 \ "$SILO_IMAGE" server /data >/dev/null -wait_for 60 docker exec "$NAME-pg" pg_isready -U prismoid -d prismoid +# Over TCP: the image's first boot runs a socket-only server to initialise the database, then +# restarts, and a socket check that answers in between lets the migration hit the restart. +wait_for 60 docker exec "$NAME-pg" pg_isready -h 127.0.0.1 -U prismoid -d prismoid wait_for 60 docker exec "$NAME-minio" mcli ready local docker exec "$NAME-minio" sh -c 'mcli alias set e2e http://127.0.0.1:9000 prismoid prismoid1234 && for b in artifacts snapshots skills; do mcli mb --ignore-existing "e2e/$b"; done' >/dev/null @@ -84,8 +120,16 @@ export PRISMOID_API_DATABASE_URL="postgresql+asyncpg://prismoid:prismoid@127.0.0 export PRISMOID_WORKER_S3_ENDPOINT="http://127.0.0.1:$MINIO_PORT" export PRISMOID_S3_PUBLIC_ENDPOINT="http://127.0.0.1:$MINIO_PORT" export PRISMOID_API_PUBLIC_BASE_URL="$E2E_API_URL" -export PRISMOID_API_CORS_ORIGINS="http://localhost:$WEB_PORT,http://127.0.0.1:$WEB_PORT" +export PRISMOID_API_CORS_ORIGINS="http://localhost:$WEB_PORT,http://127.0.0.1:$WEB_PORT,http://localhost:$ADMIN_WEB_PORT,http://127.0.0.1:$ADMIN_WEB_PORT" export PRISMOID_API_WEB_BASE_URL="http://localhost:$WEB_PORT" +# Every flow that changes an account signs up its own, so one run makes dozens of accounts and +# sign-ins from one address in a few minutes: the per-address burst buckets are widened for this +# private stack only. The per-account lines (the reset and verification mail caps) stay as shipped. +export PRISMOID_AUTH_SIGNUP_RATE_LIMIT_PER_MINUTE=1000 +export PRISMOID_AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=1000 +export PRISMOID_AUTH_RESET_RATE_LIMIT_PER_MINUTE=1000 +# The console mail backend prints each email to the API's stdout: the flows read codes from here. +export E2E_API_LOG="$LOGS/api.log" cd "$ROOT/backend" uv run alembic upgrade head >"$LOGS/migrate.log" 2>&1 diff --git a/web/e2e/support/accounts.ts b/web/e2e/support/accounts.ts new file mode 100644 index 0000000..15e7aba --- /dev/null +++ b/web/e2e/support/accounts.ts @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// People, made through the API's own doors. A flow that changes an account (a reset revokes every +// session, a workspace switch rebinds one, a rename shows up everywhere) signs up its own, so no +// flow can break another and a rerun on the same database never collides. +import type { Browser, Page } from "@playwright/test"; +import { call, stamp } from "./api"; +import { codeIn, waitForMail } from "./mailbox"; + +export const PASSWORD = "correct horse battery staple"; + +// The keys the app reads its session from (app/lib/storage.ts). +const TOKEN_KEY = "prismoid.token"; +const EXPIRES_KEY = "prismoid.expires"; + +export type Account = { + id: string; + email: string; + password: string; + name: string; + token: string; + expiresAt: string; + workspace: { id: string; name: string }; +}; + +type Session = { token: string; expires_at: string; user: { id: string } }; +type Me = { workspace: { id: string; name: string } | null }; + +/** A new person with a personal workspace; `label` becomes part of the email, for a readable trace. */ +export async function signUp( + label = "e2e", + init: { name?: string; inviteCode?: string } = {}, +): Promise { + const email = `${label}-${stamp()}@example.com`; + const name = init.name ?? "Ada Tester"; + const session = await call("/auth/signup", { + body: { + email, + name, + password: PASSWORD, + ...(init.inviteCode ? { invite_code: init.inviteCode } : {}), + }, + }); + const me = await call("/auth/me", { token: session.token }); + if (!me.workspace) throw new Error(`${email} signed up without a workspace`); + return { + id: session.user.id, + email, + password: PASSWORD, + name, + token: session.token, + expiresAt: session.expires_at, + workspace: me.workspace, + }; +} + +/** A fresh session for an existing account: a second device, say, or the one a reset must revoke. */ +export async function signIn(who: { + email: string; + password: string; +}): Promise<{ token: string; expiresAt: string }> { + const session = await call("/auth/login", { + body: { email: who.email, password: who.password }, + }); + return { token: session.token, expiresAt: session.expires_at }; +} + +/** Prove the account's address with the code signup emailed: only a proven address sends invites. */ +export async function verifyEmail(account: Account): Promise { + const mail = await waitForMail(account.email, /Verify your email/); + await call("/auth/me/verify-email", { + token: account.token, + body: { code: codeIn(mail, "ev_") }, + }); +} + +/** + * Bring `member` into `owner`'s workspace: the owner invites by email (proving their address first + * if it is not yet, since only a proven address sends invites), and the member trades the emailed + * code. Project members must belong to the project's workspace first. + */ +export async function joinWorkspace( + owner: Account, + member: Account, + role: "member" | "admin" | "guest" = "member", +): Promise { + const me = await call<{ email_verified: boolean }>("/auth/me", { token: owner.token }); + if (!me.email_verified) await verifyEmail(owner); + await call(`/workspaces/${owner.workspace.id}/invites`, { + token: owner.token, + body: { email: member.email, role }, + }); + const mail = await waitForMail(member.email, /invited/i); + await call("/workspaces/invites/accept", { + token: member.token, + body: { code: codeIn(mail, "oi_") }, + }); +} + +/** Put the account's session where the app looks for it, before any page script runs. */ +export async function useSession(page: Page, account: Pick) { + await page.addInitScript( + ([tokenKey, expiresKey, token, expiresAt]) => { + localStorage.setItem(tokenKey, token); + localStorage.setItem(expiresKey, expiresAt); + }, + [TOKEN_KEY, EXPIRES_KEY, account.token, account.expiresAt] as const, + ); +} + +/** A second browser, signed in as someone else: the other side of a share, an invite or a join. */ +export async function pageFor(browser: Browser, account: Account, baseURL: string): Promise { + const context = await browser.newContext({ baseURL }); + const page = await context.newPage(); + await useSession(page, account); + return page; +} diff --git a/web/e2e/support/api.ts b/web/e2e/support/api.ts new file mode 100644 index 0000000..5b492ab --- /dev/null +++ b/web/e2e/support/api.ts @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// The API's own doors, for arranging what a flow needs before the browser opens: an account, a +// project, a held task. A flow drives the screen it tests; everything around it is set up here, so +// a test never depends on another test's rows. Nothing here calls a model: a task comes from a +// routine fired with posture "hold", which mints a real record that no worker plans or runs. + +export const API_URL = process.env.E2E_API_URL ?? "http://127.0.0.1:8304"; + +export class ApiError extends Error { + constructor( + readonly status: number, + readonly body: string, + message: string, + ) { + super(message); + } +} + +/** One API call; throws ApiError on any status outside 2xx, naming the body. */ +export async function call( + path: string, + init: { method?: string; token?: string; body?: unknown } = {}, +): Promise { + const method = init.method ?? (init.body === undefined ? "GET" : "POST"); + for (let attempt = 0; ; attempt++) { + const response = await fetch(`${API_URL}/v1${path}`, { + method, + headers: { + "content-type": "application/json", + ...(init.token ? { authorization: `Bearer ${init.token}` } : {}), + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }); + const text = await response.text(); + // A stack someone else runs keeps the shipped burst buckets: wait out a 429 rather than fail. + if (response.status === 429 && attempt < 5) { + const wait = Number(response.headers.get("retry-after") ?? "2"); + await new Promise((resolve) => setTimeout(resolve, Math.min(wait, 30) * 1000)); + continue; + } + if (!response.ok) + throw new ApiError(response.status, text, `${method} ${path} -> ${response.status}: ${text}`); + return (text ? JSON.parse(text) : undefined) as T; + } +} + +/** A short suffix that keeps names unique across reruns on the same database. */ +export function stamp(): string { + return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; +} + +export type Project = { id: string; name: string }; + +export function createProject(token: string, name: string): Promise { + return call("/projects", { token, body: { name } }); +} + +export type Routine = { id: string; name: string }; + +/** + * A routine whose fires hold: every fire mints a task that waits for a person, so nothing plans or + * runs. Its When is once a year, so the sweep never fires it during a run. + */ +export function createHeldRoutine( + token: string, + init: { name: string; instruction: string }, +): Promise { + return call("/routines", { + token, + body: { + ...init, + schedule: { cron: "0 9 1 1 *", timezone: "UTC" }, + posture: "hold", + }, + }); +} + +export type HeldTask = { id: string; title: string; goal: string; routine: Routine }; + +/** A real task record that never runs: a held routine, fired once by hand. */ +export async function createHeldTask(token: string, goal: string): Promise { + const routine = await createHeldRoutine(token, { name: `Held ${stamp()}`, instruction: goal }); + const fired = await call<{ decision: string; task_id: string | null }>( + `/routines/${routine.id}/fire`, + { token, body: {} }, + ); + if (fired.decision !== "held" || !fired.task_id) + throw new Error(`the held fire did not mint a task: ${JSON.stringify(fired)}`); + const task = await call<{ title: string | null }>(`/tasks/${fired.task_id}`, { token }); + return { id: fired.task_id, title: task.title ?? goal, goal, routine }; +} + +/** A held task, cancelled: a settled record whose archive, delete and feedback doors are open. */ +export async function createSettledTask(token: string, goal: string): Promise { + const task = await createHeldTask(token, goal); + await call(`/tasks/${task.id}/cancel`, { token, body: {} }); + return task; +} + +export type Bot = { name: string }; + +/** A draft bot with written instructions: creating it asks no model to write them. */ +export function createBot( + token: string, + init: { name: string; instructions?: string; description?: string }, +): Promise { + return call("/bots", { + token, + body: { + instructions: "Answer in one short paragraph.", + can_ask_user: true, + ...init, + }, + }); +} diff --git a/web/e2e/support/mailbox.ts b/web/e2e/support/mailbox.ts new file mode 100644 index 0000000..328a201 --- /dev/null +++ b/web/e2e/support/mailbox.ts @@ -0,0 +1,77 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// The stack's outbox. In dev the API's console mail backend prints every email to its stdout in a +// box (prismoid/mailer.py), and stack.sh writes that stdout to E2E_API_LOG; a flow that needs an +// emailed code (a password reset, an address proof, a workspace invite) reads it from there. On a +// stack whose log this process cannot read, those flows skip themselves (`mailAvailable`). +import { existsSync, readFileSync } from "node:fs"; + +const LOG = process.env.E2E_API_LOG ?? ""; + +export type Mail = { to: string; subject: string; body: string }; + +export function mailAvailable(): boolean { + return LOG !== "" && existsSync(LOG); +} + +/** Every console email in the log, oldest first. */ +function outbox(): Mail[] { + const mails: Mail[] = []; + let current: string[] | null = null; + for (const line of readFileSync(LOG, "utf8").split("\n")) { + if (line.startsWith("┌─") && line.includes("outbound email")) current = []; + else if (line.startsWith("└─") && current) { + const to = + current + .find((l) => l.startsWith("To:")) + ?.slice(3) + .trim() ?? ""; + const subject = + current + .find((l) => l.startsWith("Subject:")) + ?.slice(8) + .trim() ?? ""; + mails.push({ to, subject, body: current.join("\n") }); + current = null; + } else if (current && line.startsWith("│")) current.push(line.slice(1).trim()); + } + return mails; +} + +/** + * The newest email to `to` whose subject matches, waiting for it to land: the API sends after its + * commit, from a background task, so the email trails the response by a moment. + */ +export async function waitForMail( + to: string, + subject: RegExp, + { after = 0, timeoutMs = 15_000 }: { after?: number; timeoutMs?: number } = {}, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const matching = outbox().filter( + (m) => m.to.toLowerCase() === to.toLowerCase() && subject.test(m.subject), + ); + if (matching.length > after) return matching[matching.length - 1]; + if (Date.now() > deadline) throw new Error(`no email to ${to} matching ${subject}`); + await new Promise((resolve) => setTimeout(resolve, 250)); + } +} + +/** How many emails to `to` match so far: pass it as `after` to wait for the next one. */ +export function mailCount(to: string, subject: RegExp): number { + if (!mailAvailable()) return 0; + return outbox().filter((m) => m.to.toLowerCase() === to.toLowerCase() && subject.test(m.subject)) + .length; +} + +/** The first token with this prefix in the email (`cr_`, `ev_`, `oi_`). */ +export function codeIn(mail: Mail, prefix: string): string { + const match = mail.body.match(new RegExp(`${prefix}[A-Za-z0-9_-]+`)); + if (!match) throw new Error(`no ${prefix} code in the email "${mail.subject}"`); + return match[0]; +} diff --git a/web/e2e/support/runs.ts b/web/e2e/support/runs.ts new file mode 100644 index 0000000..ab34e6e --- /dev/null +++ b/web/e2e/support/runs.ts @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// Real runs, for the model flows (e2e/models/) only: each of these asks the stack's model for +// something and spends real money, so no core flow imports this file. A model's words differ run to +// run, so a flow waits on what the server records (a status, a message, a version) and asserts the +// words only where any sane answer must carry them. +import { expect, type Page } from "@playwright/test"; +import { call } from "./api"; + +/** How long one model run may take to settle: seconds on a good day, a minute on a slow provider. */ +export const RUN_TIMEOUT = 120_000; + +export const TASK_URL = /\/tasks\/([0-9a-f-]{36})$/; + +/** The task id in a task page's URL. */ +export function taskIdIn(url: string): string { + const match = new URL(url).pathname.match(TASK_URL); + if (!match) throw new Error(`not a task page: ${url}`); + return match[1]; +} + +type TaskRow = { status: string; turn: number; title: string | null }; + +/** Start a task through the API: the setup for a flow whose subject comes after the first answer. */ +export async function startTask(token: string, goal: string): Promise { + const accepted = await call<{ task_id: string }>("/tasks", { token, body: { goal } }); + return accepted.task_id; +} + +/** Wait until the task's status is one of `want`, and hand back the row. */ +export async function waitForTask( + token: string, + id: string, + want: string | string[], +): Promise { + const statuses = Array.isArray(want) ? want : [want]; + let row: TaskRow | undefined; + await expect + .poll( + async () => { + row = await call(`/tasks/${id}`, { token }); + return row.status; + }, + { timeout: RUN_TIMEOUT, intervals: [1_000] }, + ) + .toMatch(new RegExp(`^(${statuses.join("|")})$`)); + return row!; +} + +/** + * Answer the gate's questions one by one, as a person would: type into a free-text question, take + * the first option of a choice. The model writes the questions, so their number and kinds change + * from run to run (a lone question shows no "1 of 3" counter, and a pick may move on by itself), so + * the flow follows the panel: while it shows, answer the question it asks and wait for the next. + * Returns how many questions were answered. + */ +export async function answerQuestions(page: Page): Promise { + // Only the questions panel offers "Use defaults"; its question is the page's one level-3 heading. + const panel = page.getByRole("button", { name: "Use defaults" }); + const prompt = page.getByRole("main").getByRole("heading", { level: 3 }); + const answer = page.getByRole("button", { name: /^Answer and (continue|submit)$/ }); + await expect(panel).toBeVisible({ timeout: RUN_TIMEOUT }); + let answered = 0; + // Read without waiting: the heading goes the moment the last answer sends. + const question = async () => ((await prompt.count()) ? await prompt.first().textContent() : null); + while ((await panel.isVisible()) && answered < 10) { + const asked = await question(); + const movedOn = async () => !(await panel.isVisible()) || (await question()) !== asked; + const typed = page.getByRole("textbox", { name: "Type your answer…" }); + if (await typed.isVisible()) { + await typed.fill("Whatever you think is best."); + await answer.click(); + } else { + await page.getByRole("button", { name: /^1 / }).click(); + // A lone choice sends itself on the pick; any other waits for the answer button. + if (!(await settles(movedOn, 3_000))) await answer.click(); + } + answered++; + await expect.poll(movedOn).toBe(true); + } + await expect(panel).toBeHidden({ timeout: RUN_TIMEOUT }); + return answered; +} + +/** Whether `check` comes true within `timeout`: for a screen that may or may not move by itself. */ +async function settles(check: () => Promise, timeout: number): Promise { + return expect + .poll(check, { timeout }) + .toBe(true) + .then( + () => true, + () => false, + ); +} diff --git a/web/e2e/task-page.spec.ts b/web/e2e/task-page.spec.ts new file mode 100644 index 0000000..1de3509 --- /dev/null +++ b/web/e2e/task-page.spec.ts @@ -0,0 +1,216 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { + ApiError, + call, + createHeldTask, + createProject, + createSettledTask, + stamp, +} from "./support/api"; + +// The task page on tasks that never run: a held task (it waits for a first direction) and a settled +// one (held, then cancelled). Typing in the page's composer bar would launch the run, so these +// flows only use the header's verbs; Retry sits beside the feedback thumbs and is never pressed. + +/** The header's own menu: the sidebar row of the same task has "Task actions for ". */ +async function taskMenu(page: Page) { + await page.getByRole("button", { name: "Task actions", exact: true }).click(); + return page.getByRole("menu", { name: "Task actions" }); +} + +function breadcrumb(page: Page) { + return page.getByRole("navigation", { name: "Breadcrumb" }); +} + +async function statusOf(id: string, token: string): Promise<number> { + return call(`/tasks/${id}`, { token }).then( + () => 200, + (e: ApiError) => e.status, + ); +} + +test.describe("task page", () => { + test("renames a held task and keeps the name", async ({ accountPage: page, account }) => { + const task = await createHeldTask(account.token, "Draft the quarterly plan"); + const name = `Plan ${stamp()}`; + await page.goto(`/tasks/${task.id}`); + await (await taskMenu(page)).getByRole("menuitem", { name: "Rename" }).click(); + + const dialog = page.getByRole("dialog", { name: "Rename task" }); + const field = dialog.getByRole("textbox", { name: "Task name" }); + await expect(field).toHaveValue(task.title); + await field.fill(name); + await dialog.getByRole("button", { name: "Save" }).click(); + await expect(dialog).toBeHidden(); + await expect(breadcrumb(page)).toContainText(name); + + await page.reload(); + await expect(breadcrumb(page)).toContainText(name); + // The label changes; the ask on the thread stays as written. + await expect(page.getByRole("region", { name: "Messages" })).toContainText(task.goal); + }); + + test("cancelling a held task settles it", async ({ accountPage: page, account }) => { + const task = await createHeldTask(account.token, "Draft the quarterly plan"); + await page.goto(`/tasks/${task.id}`); + const main = page.getByRole("main"); + await expect(main.getByRole("img", { name: "Status: queued" })).toBeVisible(); + let menu = await taskMenu(page); + await expect(menu.getByRole("menuitem", { name: "Archive" })).toBeDisabled(); + await expect(menu.getByRole("menuitem", { name: "Delete" })).toBeDisabled(); + await menu.getByRole("menuitem", { name: "Cancel task" }).click(); + + await expect(main.getByRole("img", { name: "Status: cancelled" })).toBeVisible(); + // Settled: the bar now offers a follow-up, and the answer carries its response actions. + await expect(main.getByRole("textbox", { name: "Ask a follow-up…" })).toBeVisible(); + const actions = main.getByRole("group", { name: "Response actions" }); + for (const name of ["Copy", "Good response", "Bad response"]) + await expect(actions.getByRole("button", { name, exact: true })).toBeVisible(); + + menu = await taskMenu(page); + await expect(menu.getByRole("menuitem", { name: "Cancel task" })).toHaveCount(0); + await expect(menu.getByRole("menuitem", { name: "Archive" })).toBeEnabled(); + await expect(menu.getByRole("menuitem", { name: "Delete" })).toBeEnabled(); + await page.keyboard.press("Escape"); + + await page.reload(); + await expect(main.getByRole("img", { name: "Status: cancelled" })).toBeVisible(); + }); + + test("a thumbs-up on a settled answer is kept", async ({ accountPage: page, account }) => { + const task = await createSettledTask(account.token, "Compare the vendors"); + await page.goto(`/tasks/${task.id}`); + const actions = page.getByRole("group", { name: "Response actions" }); + const good = actions.getByRole("button", { name: "Good response" }); + const bad = actions.getByRole("button", { name: "Bad response" }); + await expect(good).toHaveAttribute("aria-pressed", "false"); + // The thumb presses at once, before the server has it: wait for the save before reloading, + // or the reload cancels it in flight. + const saved = page.waitForResponse( + (r) => r.url().endsWith(`/tasks/${task.id}/feedback`) && r.request().method() === "POST", + ); + await good.click(); + await expect(good).toHaveAttribute("aria-pressed", "true"); + await expect(bad).toHaveAttribute("aria-pressed", "false"); + expect((await saved).ok()).toBe(true); + + await page.reload(); + await expect(good).toHaveAttribute("aria-pressed", "true"); + }); + + test("deletes a settled task from its menu", async ({ accountPage: page, account }) => { + const task = await createSettledTask(account.token, "Compare the vendors"); + await page.goto(`/tasks/${task.id}`); + await (await taskMenu(page)).getByRole("menuitem", { name: "Delete" }).click(); + + const confirm = page.getByRole("alertdialog", { name: "Delete this task?" }); + await expect(confirm).toContainText(task.title); + await confirm.getByRole("button", { name: "Delete task" }).click(); + await expect(page).toHaveURL(/\/tasks$/); + await expect(page.getByText("Nothing here yet")).toBeVisible(); + expect(await statusOf(task.id, account.token)).toBe(404); + }); + + test("archives a settled task from its menu", async ({ accountPage: page, account }) => { + const task = await createSettledTask(account.token, "Compare the vendors"); + await page.goto(`/tasks/${task.id}`); + await (await taskMenu(page)).getByRole("menuitem", { name: "Archive" }).click(); + await expect((await taskMenu(page)).getByRole("menuitem", { name: "Unarchive" })).toBeVisible(); + await page.keyboard.press("Escape"); + + const listed = page + .getByRole("main") + .getByRole("link", { name: new RegExp(escapeRegExp(task.title)) }); + await page.goto("/tasks"); + await expect(page.getByText("Nothing here yet")).toBeVisible(); + await page.goto("/tasks?archived=1"); + await expect(page.getByRole("button", { name: "Remove filter Archived" })).toBeVisible(); + await expect(listed).toBeVisible(); + }); + + test("forking makes a held branch and opens it", async ({ accountPage: page, account }) => { + const task = await createHeldTask(account.token, "Compare the vendors"); + await page.goto(`/tasks/${task.id}`); + await (await taskMenu(page)).getByRole("menuitem", { name: "Fork this task" }).click(); + + await expect(page).not.toHaveURL(new RegExp(task.id)); + await expect(page).toHaveURL(/\/tasks\/[0-9a-f-]{36}$/); + const childId = page.url().split("/").pop()!; + await expect(breadcrumb(page)).toContainText(`[Forked] ${task.title}`); + const thread = page.getByRole("region", { name: "Messages" }); + await expect(thread.getByRole("link", { name: task.goal })).toBeVisible(); + await expect(thread.getByRole("status").last()).toContainText(/Held\. .*has not started/); + + const child = await call<{ status: string; title: string }>(`/tasks/${childId}`, { + token: account.token, + }); + expect(child).toMatchObject({ status: "created", title: `[Forked] ${task.title}` }); + }); + + test("sharing moves a personal task into a project", async ({ accountPage: page, account }) => { + const project = await createProject(account.token, `Bench ${stamp()}`); + const task = await createSettledTask(account.token, "Compare the vendors"); + await page.goto(`/tasks/${task.id}`); + await page.getByRole("button", { name: "Share this task" }).click(); + const popover = page.getByRole("dialog").filter({ hasText: "Only you can see this" }); + await popover.getByRole("button", { name: `Move to ${project.name}` }).click(); + await page.getByRole("button", { name: `Move it to ${project.name}` }).click(); + + await expect(toast(page, `Moved to ${project.name}`)).toBeVisible(); + const canonical = `/projects/${project.id}/tasks/${task.id}`; + await expect(page).toHaveURL(new RegExp(`${canonical}$`)); + await expect(breadcrumb(page).getByRole("link", { name: project.name })).toBeVisible(); + + // A project task's old personal address lands on its project address. + await page.goto(`/tasks/${task.id}`); + await expect(page).toHaveURL(new RegExp(`${canonical}$`)); + await expect(breadcrumb(page).getByRole("link", { name: project.name })).toBeVisible(); + }); + + test("the plan and outputs rail toggles and stays toggled", async ({ + accountPage: page, + account, + }) => { + const task = await createHeldTask(account.token, "Draft the quarterly plan"); + await page.goto(`/tasks/${task.id}`); + const toggle = page.getByRole("button", { name: "Toggle plan and artifacts" }); + const rail = page.getByRole("main").getByRole("complementary"); + await expect(toggle).toHaveAttribute("aria-pressed", "true"); + await expect(rail.getByRole("button", { name: "Progress" })).toBeVisible(); + await expect(rail.getByText("No plan yet")).toBeVisible(); + await expect(rail.getByRole("button", { name: "Outputs" })).toBeVisible(); + await expect(rail.getByText("Nothing published yet")).toBeVisible(); + + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-pressed", "false"); + await expect(rail).toHaveCount(0); + await page.reload(); + await expect(toggle).toHaveAttribute("aria-pressed", "false"); + await expect(rail).toHaveCount(0); + await toggle.click(); + await expect(rail.getByText("No plan yet")).toBeVisible(); + }); + + test("a held task is not offered a pause it cannot take", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/routes/tasks.$id/task-menu.tsx:78 - the menu offers Pause on any live task, but " + + "backend/prismoid/operations/steering.py:505 pauses only a running or waiting one, so a " + + "held task's Pause answers 422 'cannot pause a task that is created'", + ); + const task = await createHeldTask(account.token, "Draft the quarterly plan"); + await page.goto(`/tasks/${task.id}`); + const menu = await taskMenu(page); + await expect(menu.getByRole("menuitem", { name: "Cancel task" })).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Pause" })).toHaveCount(0); + }); +}); diff --git a/web/e2e/tasks.spec.ts b/web/e2e/tasks.spec.ts new file mode 100644 index 0000000..36e8118 --- /dev/null +++ b/web/e2e/tasks.spec.ts @@ -0,0 +1,246 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { + ApiError, + call, + createHeldTask, + createProject, + createSettledTask, + stamp, +} from "./support/api"; + +// The task list. Every flow signs up its own account, so what the list shows is exactly the tasks +// the flow made: held ones (never planned or run) and settled ones (held, then cancelled), which are +// the only tasks archive and delete accept. + +/** A task's row in the list, by its title. */ +function row(page: Page, title: string) { + return page.getByRole("main").getByRole("link", { name: new RegExp(escapeRegExp(title)) }); +} + +/** One status group of the list: its sections carry no name, so they are found by their heading. */ +function group(page: Page, label: string) { + return page + .getByRole("main") + .locator("section") + .filter({ has: page.getByRole("heading", { name: label, exact: true }) }); +} + +/** The total a status group's header states beside its name. */ +function groupCount(page: Page, label: string) { + return group(page, label).getByText(/^\d+$/); +} + +/** Tick a row's checkbox: it shows only while the row is hovered, and the row's own hit area takes + * the click (the box itself ignores the pointer), so the click is forced onto the hovered box. */ +async function select(page: Page, title: string) { + await row(page, title).hover(); + await page + .getByRole("main") + .getByRole("checkbox", { name: `Select ${title}` }) + .click({ force: true }); +} + +async function filter(page: Page, item: string) { + await page.getByRole("button", { name: "Filter", exact: true }).click(); + await page + .getByRole("menu", { name: "Filter" }) + .getByRole("menuitemradio", { name: item }) + .click(); + await page.keyboard.press("Escape"); +} + +test.describe("task list", () => { + test("a fresh account has nothing listed", async ({ accountPage: page }) => { + await page.goto("/tasks"); + await expect(page.getByText("Nothing here yet")).toBeVisible(); + await expect(page.getByText("Start something new.")).toBeVisible(); + }); + + test("tasks sit in their status groups and search narrows them", async ({ + accountPage: page, + account, + }) => { + const held = await createHeldTask(account.token, "Draft the quarterly plan"); + const settled = await createSettledTask(account.token, "Compare the vendors"); + await page.goto("/tasks"); + + // A held task has not started: the list files it under In progress and calls it queued. + await expect(group(page, "In progress").getByRole("link")).toHaveCount(1); + await expect(group(page, "In progress").getByRole("link")).toContainText(held.title); + await expect(group(page, "In progress").getByRole("link")).toContainText("queued"); + await expect(groupCount(page, "In progress")).toHaveText("1"); + await expect(group(page, "Failed & cancelled").getByRole("link")).toContainText(settled.title); + await expect(group(page, "Failed & cancelled").getByRole("link")).toContainText("cancelled"); + + const search = page.getByRole("textbox", { name: "Search tasks…" }); + // The routine name is the start of each title and carries its own stamp. + await search.fill(held.title.split(" · ")[0]); + await expect(row(page, held.title)).toBeVisible(); + await expect(row(page, settled.title)).toHaveCount(0); + await search.fill(`nothing-${stamp()}`); + await expect(page.getByText(/^No matches for “nothing-/)).toBeVisible(); + await search.fill(""); + await expect(row(page, settled.title)).toBeVisible(); + await expect(row(page, held.title)).toBeVisible(); + }); + + test("the Filter menu narrows the list and its chips undo it", async ({ + accountPage: page, + account, + }) => { + const project = await createProject(account.token, `Bench ${stamp()}`); + const held = await createHeldTask(account.token, "Draft the quarterly plan"); + const settled = await createSettledTask(account.token, "Compare the vendors"); + await call(`/tasks/${settled.id}/move`, { + token: account.token, + body: { project_id: project.id }, + }); + await page.goto("/tasks"); + await expect(row(page, held.title)).toBeVisible(); + + await filter(page, "Failed & cancelled"); + const statusChip = page.getByRole("button", { + name: "Remove filter Status: Failed & cancelled", + }); + await expect(statusChip).toBeVisible(); + await expect(row(page, held.title)).toHaveCount(0); + await expect(row(page, settled.title)).toBeVisible(); + await statusChip.click(); + await expect(row(page, held.title)).toBeVisible(); + + await filter(page, "Fleet"); + await expect(page.getByRole("button", { name: "Remove filter Mode: fleet" })).toBeVisible(); + await expect(page.getByText("Nothing here yet")).toBeVisible(); + await page.getByRole("button", { name: "Remove filter Mode: fleet" }).click(); + await expect(row(page, held.title)).toBeVisible(); + + await filter(page, project.name); + await expect( + page.getByRole("button", { name: `Remove filter Project: ${project.name}` }), + ).toBeVisible(); + await expect(row(page, settled.title)).toBeVisible(); + await expect(row(page, held.title)).toHaveCount(0); + + await page.getByRole("button", { name: "Filter", exact: true }).click(); + await page.getByRole("menuitem", { name: "Clear filters" }).click(); + await expect(page.getByRole("button", { name: /^Remove filter/ })).toHaveCount(0); + await expect(row(page, held.title)).toBeVisible(); + await expect(row(page, settled.title)).toBeVisible(); + }); + + test("Display options lay the list out as a board and regroup it", async ({ + accountPage: page, + account, + }) => { + const held = await createHeldTask(account.token, "Draft the quarterly plan"); + const settled = await createSettledTask(account.token, "Compare the vendors"); + await page.goto("/tasks"); + await expect(row(page, held.title)).toBeVisible(); + + const display = async (item: string) => { + await page.getByRole("button", { name: "Display options" }).click(); + await page + .getByRole("menu", { name: "Display options" }) + .getByRole("menuitemradio", { name: item, exact: true }) + .click(); + await page.keyboard.press("Escape"); + }; + const main = page.getByRole("main"); + await display("Board"); + await expect(main.getByRole("region", { name: "In progress" })).toContainText(held.title); + await expect(main.getByRole("region", { name: "Failed & cancelled" })).toContainText( + settled.title, + ); + await expect(main.getByRole("region", { name: "Delivered" })).toBeVisible(); + + await display("Mode"); + await expect(main.getByRole("region", { name: "standard" })).toContainText(held.title); + await expect(main.getByRole("region", { name: "standard" })).toContainText(settled.title); + + // One flat list: no group headings at all. + await display("List"); + await display("None"); + await expect(main.getByRole("heading", { level: 2 })).toHaveCount(0); + await expect(row(page, held.title)).toBeVisible(); + await expect(row(page, settled.title)).toBeVisible(); + }); + + test("bulk archive files a settled task away and unarchive brings it back", async ({ + accountPage: page, + account, + }) => { + const settled = await createSettledTask(account.token, "Compare the vendors"); + await page.goto("/tasks"); + await select(page, settled.title); + const main = page.getByRole("main"); + await expect(main.getByText("1 selected")).toBeVisible(); + await main.getByRole("button", { name: "Archive", exact: true }).click(); + await expect(toast(page, "Archived 1 task.")).toBeVisible(); + await expect(row(page, settled.title)).toHaveCount(0); + await expect(page.getByText("Nothing here yet")).toBeVisible(); + + await filter(page, "Archived"); + const archivedChip = page.getByRole("button", { name: "Remove filter Archived" }); + await expect(archivedChip).toBeVisible(); + await select(page, settled.title); + await main.getByRole("button", { name: "Unarchive", exact: true }).click(); + await expect(toast(page, "Unarchived 1 task.")).toBeVisible(); + await expect(row(page, settled.title)).toHaveCount(0); + + await archivedChip.click(); + await expect(row(page, settled.title)).toBeVisible(); + await page.reload(); + await expect(row(page, settled.title)).toBeVisible(); + }); + + test("bulk delete removes a settled task for good", async ({ accountPage: page, account }) => { + const gone = await createSettledTask(account.token, "Compare the vendors"); + const kept = await createSettledTask(account.token, "Price the hardware"); + await page.goto("/tasks"); + await select(page, gone.title); + await page.getByRole("main").getByRole("button", { name: "Delete", exact: true }).click(); + + const confirm = page.getByRole("alertdialog", { name: "Delete 1 task?" }); + await confirm.getByRole("button", { name: "Delete", exact: true }).click(); + await expect(toast(page, "Deleted 1 task.")).toBeVisible(); + await expect(row(page, gone.title)).toHaveCount(0); + await page.reload(); + await expect(row(page, kept.title)).toBeVisible(); + await expect(row(page, gone.title)).toHaveCount(0); + const status = await call(`/tasks/${gone.id}`, { token: account.token }).then( + () => 200, + (e: ApiError) => e.status, + ); + expect(status).toBe(404); + }); + + test("the archived view counts the archive, not the active list", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/components/tasks/task-browser/browser.tsx:288 - the status counts effect leaves " + + "filters.archived (and refreshTick) out of its deps, so switching to Archived keeps the " + + "active totals in the group headers", + ); + const tasks = []; + for (const goal of ["Compare the vendors", "Price the hardware", "Book the venue"]) + tasks.push(await createSettledTask(account.token, goal)); + await call(`/tasks/${tasks[0].id}/archive`, { token: account.token, body: {} }); + await page.goto("/tasks"); + await expect(group(page, "Failed & cancelled").getByRole("link")).toHaveCount(2); + await expect(groupCount(page, "Failed & cancelled")).toHaveText("2"); + + await filter(page, "Archived"); + await expect(group(page, "Failed & cancelled").getByRole("link")).toHaveCount(1); + await expect(row(page, tasks[0].title)).toBeVisible(); + await expect(groupCount(page, "Failed & cancelled")).toHaveText("1"); + }); +}); diff --git a/web/e2e/verify-email.spec.ts b/web/e2e/verify-email.spec.ts new file mode 100644 index 0000000..7f88183 --- /dev/null +++ b/web/e2e/verify-email.spec.ts @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { call } from "./support/api"; +import { codeIn, mailAvailable, mailCount, waitForMail } from "./support/mailbox"; +import { composer, expect, test } from "./fixtures"; + +type Me = { email_verified: boolean }; + +// The emailed verification link (ADR-031): its single-use ev_ code rides the URL fragment, is +// posted once by a signed-in page, and waits through sign-in for a signed-out one. Each flow proves +// the address of its own fresh account. +test.describe("verify email", () => { + test("the emailed link proves the address of the signed-in person", async ({ + accountPage: page, + account, + }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + const code = codeIn(await waitForMail(account.email, /Verify your email/), "ev_"); + await page.goto(`/verify-email#${code}`); + await expect(page.getByRole("heading", { name: "Email verified" })).toBeVisible(); + await expect(page.getByText("Your email address is verified.")).toBeVisible(); + // The code leaves the address bar once read, so it never lands in history. + await expect(page).toHaveURL(/\/verify-email$/); + expect((await call<Me>("/auth/me", { token: account.token })).email_verified).toBe(true); + + await page.getByRole("button", { name: "Continue" }).click(); + await expect(composer(page)).toBeVisible(); + }); + + test("a link without a code offers a fresh one", async ({ accountPage: page, account }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + await waitForMail(account.email, /Verify your email/); + const sent = mailCount(account.email, /Verify your email/); + await page.goto("/verify-email"); + await expect(page.getByRole("heading", { name: "Verify your email" })).toBeVisible(); + await expect(page.getByText(/That link has expired\./)).toBeVisible(); + await page.getByRole("button", { name: "Resend" }).click(); + await expect(page.getByText("Sent. Check your email.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Resend" })).toBeHidden(); + // The resend is a real email with a fresh code, not only a message on the page. + const fresh = await waitForMail(account.email, /Verify your email/, { after: sent }); + expect(codeIn(fresh, "ev_")).toMatch(/^ev_/); + }); + + test("a code the server never issued is treated as expired", async ({ + accountPage: page, + account, + }) => { + await page.goto("/verify-email#ev_thisCodeWasNeverIssuedByTheServer"); + await expect(page.getByRole("heading", { name: "Verify your email" })).toBeVisible(); + await expect(page.getByText(/That link has expired\./)).toBeVisible(); + await expect(page.getByRole("button", { name: "Resend" })).toBeVisible(); + expect((await call<Me>("/auth/me", { token: account.token })).email_verified).toBe(false); + }); + + test("signed out, the link waits through sign-in and then verifies", async ({ + page, + account, + }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + const code = codeIn(await waitForMail(account.email, /Verify your email/), "ev_"); + await page.goto(`/verify-email#${code}`); + await expect(page).toHaveURL(/\/login\?next=%2Fverify-email$/); + await page.getByRole("textbox", { name: "Email" }).fill(account.email); + await page.getByRole("textbox", { name: "Password" }).fill(account.password); + await page.getByRole("button", { name: "Sign in" }).click(); + + await expect(page.getByRole("heading", { name: "Email verified" })).toBeVisible(); + expect((await call<Me>("/auth/me", { token: account.token })).email_verified).toBe(true); + }); +}); diff --git a/web/e2e/workspaces.spec.ts b/web/e2e/workspaces.spec.ts new file mode 100644 index 0000000..0f812db --- /dev/null +++ b/web/e2e/workspaces.spec.ts @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import type { Page } from "@playwright/test"; +import { joinWorkspace, pageFor, PASSWORD, signUp, verifyEmail } from "./support/accounts"; +import { call, stamp } from "./support/api"; +import { codeIn, mailAvailable, waitForMail } from "./support/mailbox"; +import { composer, expect, knownBug, openSettings, test, toast } from "./fixtures"; + +// Workspaces (ADR-061): the tenant. A person founds their own, switches between the ones they +// belong to, and brings others in by an emailed invite. A switch or a join rebinds the session, so +// every flow runs on fresh accounts, and each person carries a name of their own so "landed in the +// other workspace" can be told from "stayed home". + +const WEB = "http://localhost:5304"; + +/** The switcher's face: the workspace this session works in, and the person's role there. */ +function switcher(page: Page) { + return page.getByRole("button", { name: "Switch workspace" }); +} + +/** Settings, on the Members pane. */ +async function openMembers(page: Page, email: string) { + const settings = await openSettings(page, email); + await settings.getByRole("button", { name: "Members", exact: true }).click(); + await expect(settings.getByRole("heading", { name: "Members" })).toBeVisible(); + return settings; +} + +/** Invite `email` to the owner's workspace through the API and read the emailed oi_ code. */ +async function inviteCode(owner: { token: string; workspace: { id: string } }, email: string) { + await call(`/workspaces/${owner.workspace.id}/invites`, { + token: owner.token, + body: { email, role: "member" }, + }); + return codeIn(await waitForMail(email, /invited/i), "oi_"); +} + +test.describe("workspaces", () => { + test("founds a workspace, lands in it, and switches back", async ({ + accountPage: page, + account, + }) => { + const name = `Tide Lab ${stamp()}`; + await page.goto("/"); + await expect(switcher(page)).toContainText(account.workspace.name); + + await switcher(page).click(); + await page.getByRole("menuitem", { name: "Create workspace" }).click(); + const dialog = page.getByRole("dialog", { name: "Create workspace" }); + await dialog.getByRole("textbox", { name: "Workspace name" }).fill(name); + await dialog.getByRole("button", { name: "Create" }).click(); + // The switch reloads the page fully, into the new workspace, as its owner. + await expect(switcher(page)).toContainText(name); + await expect(switcher(page)).toContainText("owner"); + await expect(composer(page)).toBeVisible(); + + await switcher(page).click(); + await expect(page.getByRole("menuitemradio", { name: new RegExp(name) })).toBeChecked(); + await page.getByRole("menuitemradio", { name: new RegExp(account.workspace.name) }).click(); + await expect(switcher(page)).toContainText(account.workspace.name); + await page.reload(); + await expect(switcher(page)).toContainText(account.workspace.name); + }); + + test.describe("invites", () => { + test("an owner with a proven address invites by email and revokes it", async ({ + accountPage: page, + account, + }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + await verifyEmail(account); + const invitee = `e2e-workspaces-invitee-${stamp()}@example.com`; + await page.goto("/"); + const settings = await openMembers(page, account.email); + await settings.getByRole("button", { name: "Invite" }).click(); + const dialog = page.getByRole("dialog", { name: "Invite to this workspace" }); + await expect(dialog.getByRole("combobox", { name: "Role" })).toHaveText("Member"); + await dialog.getByRole("textbox", { name: "Email" }).fill(invitee); + await dialog.getByRole("button", { name: "Send invite" }).click(); + await expect(toast(page, "Invite sent.")).toBeVisible(); + await expect(dialog).toBeHidden(); + + await expect(settings.getByRole("heading", { name: "Pending invites" })).toBeVisible(); + const row = settings.getByRole("listitem").filter({ hasText: invitee }); + await expect(row).toContainText("member"); + await waitForMail(invitee, /invited/i); + + await row.getByRole("button", { name: "Revoke" }).click(); + await expect(row).toBeHidden(); + await expect(settings.getByRole("heading", { name: "Pending invites" })).toBeHidden(); + await page.reload(); + const reopened = await openMembers(page, account.email); + await expect(reopened.getByText(invitee)).toBeHidden(); + }); + + test("an unproven address cannot invite, and the dialog keeps what was typed", async ({ + accountPage: page, + account, + }) => { + knownBug( + "web/app/components/workspace/workspace-members.tsx:180 closes the invite dialog and " + + "clears the email whatever the answer: onInvite's run() swallows the refusal into a " + + "toast and resolves, so a refused invite looks sent and the typed address is lost", + ); + const invitee = `e2e-workspaces-invitee-${stamp()}@example.com`; + await page.goto("/"); + const settings = await openMembers(page, account.email); + await settings.getByRole("button", { name: "Invite" }).click(); + const dialog = page.getByRole("dialog", { name: "Invite to this workspace" }); + await dialog.getByRole("textbox", { name: "Email" }).fill(invitee); + await dialog.getByRole("button", { name: "Send invite" }).click(); + await expect(toast(page, "Verify your email before you invite anyone.")).toBeVisible(); + await expect(settings.getByRole("heading", { name: "Pending invites" })).toBeHidden(); + + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("textbox", { name: "Email" })).toHaveValue(invitee); + }); + + test("a signed-in invitee accepts the emailed link", async ({ browser, account }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + await verifyEmail(account); + const invitee = await signUp("e2e-workspaces", { name: "Ivy Invitee" }); + const code = await inviteCode(account, invitee.email); + const page = await pageFor(browser, invitee, WEB); + + await page.goto(`/invite/${code}`); + await expect(page).toHaveURL(`${WEB}/`); + await expect(switcher(page)).toContainText(account.workspace.name); + await expect(switcher(page)).toContainText("member"); + await page.context().close(); + }); + + test("a signed-out invitee signs up through the link and joins", async ({ page, account }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + await verifyEmail(account); + const email = `e2e-workspaces-new-${stamp()}@example.com`; + const code = await inviteCode(account, email); + + await page.goto(`/invite/${code}`); + await expect(page).toHaveURL(`/signup?invite=${code}`); + await expect(page.getByRole("textbox", { name: "Invite code (optional)" })).toHaveValue(code); + await page.getByRole("textbox", { name: "Name" }).fill("Ivy Invitee"); + await page.getByRole("textbox", { name: "Email" }).fill(email); + await page.getByRole("textbox", { name: "Password" }).fill(PASSWORD); + await page.getByRole("button", { name: "Create account" }).click(); + + await expect(composer(page)).toBeVisible(); + await expect(switcher(page)).toContainText(account.workspace.name); + await expect(switcher(page)).toContainText("member"); + const members = await call<{ user: { email: string } }[]>( + `/workspaces/${account.workspace.id}/members`, + { token: account.token }, + ); + expect(members.map((m) => m.user.email)).toContain(email); + }); + + test("joins with a code from the switcher", async ({ accountPage: page, account }) => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + const owner = await signUp("e2e-workspaces", { name: "Olga Owner" }); + await verifyEmail(owner); + const code = await inviteCode(owner, account.email); + await page.goto("/"); + + await switcher(page).click(); + await page.getByRole("menuitem", { name: "Join with a code" }).click(); + const dialog = page.getByRole("dialog", { name: "Join with a code" }); + const field = dialog.getByRole("textbox", { name: "Invite code" }); + // A code that was never issued is refused inside the dialog, in the server's words. + await field.fill("oi_thisCodeWasNeverIssuedByTheServer"); + await dialog.getByRole("button", { name: "Join" }).click(); + await expect(dialog.getByText("this invite is invalid or has expired")).toBeVisible(); + await expect(field).toHaveAttribute("aria-invalid", "true"); + + await field.fill(code); + await dialog.getByRole("button", { name: "Join" }).click(); + await expect(switcher(page)).toContainText(owner.workspace.name); + await expect(switcher(page)).toContainText("member"); + }); + }); + + test.describe("members", () => { + test.skip(!mailAvailable(), "needs the stack's mail log (E2E_API_LOG)"); + + test("the owner changes a member's role, then removes them", async ({ + accountPage: page, + account, + }) => { + await verifyEmail(account); + const member = await signUp("e2e-workspaces", { name: "Mo Member" }); + await joinWorkspace(account, member); + await page.goto("/"); + let settings = await openMembers(page, account.email); + + const role = settings.getByRole("combobox", { name: "Role for Mo Member" }); + await expect(role).toHaveText("Member"); + await role.click(); + await page.getByRole("option", { name: "Admin", exact: true }).click(); + await expect(role).toHaveText("Admin"); + await page.reload(); + settings = await openMembers(page, account.email); + await expect(settings.getByRole("combobox", { name: "Role for Mo Member" })).toHaveText( + "Admin", + ); + + const row = settings.getByRole("listitem").filter({ hasText: member.email }); + await row.getByRole("button", { name: "Remove" }).click(); + const confirm = page.getByRole("alertdialog", { name: `Remove ${member.email}?` }); + await confirm.getByRole("button", { name: "Remove" }).click(); + await expect(toast(page, "Removed.")).toBeVisible(); + await expect(row).toBeHidden(); + const members = await call<{ user: { email: string } }[]>( + `/workspaces/${account.workspace.id}/members`, + { token: account.token }, + ); + expect(members.map((m) => m.user.email)).not.toContain(member.email); + }); + + test("a member leaves and is back in their own workspace", async ({ + accountPage: page, + account, + }) => { + const owner = await signUp("e2e-workspaces", { name: "Olga Owner" }); + await verifyEmail(owner); + // Accepting moves this person's session into the owner's workspace. + await joinWorkspace(owner, account); + await page.goto("/"); + await expect(switcher(page)).toContainText(owner.workspace.name); + + const settings = await openMembers(page, account.email); + // A member manages nobody: no invite, and only their own row has a verb. + await expect(settings.getByRole("button", { name: "Invite" })).toBeHidden(); + await expect(settings.getByRole("button", { name: "Remove" })).toBeHidden(); + await settings + .getByRole("listitem") + .filter({ hasText: account.email }) + .getByRole("button", { name: "Leave" }) + .click(); + const confirm = page.getByRole("alertdialog", { name: "Leave this workspace?" }); + await confirm.getByRole("button", { name: "Leave" }).click(); + + await expect(switcher(page)).toContainText(account.workspace.name); + const members = await call<{ user: { email: string } }[]>( + `/workspaces/${owner.workspace.id}/members`, + { token: owner.token }, + ); + expect(members.map((m) => m.user.email)).not.toContain(account.email); + }); + }); +}); diff --git a/web/playwright.config.ts b/web/playwright.config.ts index 8e714f0..79ca282 100644 --- a/web/playwright.config.ts +++ b/web/playwright.config.ts @@ -6,37 +6,77 @@ import { defineConfig, devices } from "@playwright/test"; -// The smoke flows (ADR-081): a real browser against a real API and worker, with no model behind -// them. `just e2e` boots a private stack (web/e2e/stack.sh) and runs this; against a stack you -// already run, set E2E_API_URL and call `pnpm e2e`. The web app is built for that API and served -// as the static SPA it ships as, because the dev server's dependency optimizer reloads the page -// mid-test on a cold cache. +// The browser flows (ADR-081): a real browser against a real API and worker. The core projects +// (`app`, `admin`) run with no model behind them: `just e2e` boots a private stack (web/e2e/stack.sh) +// with every provider key blanked and runs them; against a stack you already run, set E2E_API_URL +// and call `pnpm e2e`. The `models` project (e2e/models/) exists only with E2E_MODELS=1: its flows +// send real work to a real model and spend a few cents each, so `just e2e-models` runs it alone, on +// demand, with the stack's worker holding a provider key. Both web apps are built for that API and served +// as the static SPAs they ship as, because the dev server's dependency optimizer reloads the page +// mid-test on a cold cache: the product on E2E_WEB_PORT, the operator console (its own bundle, +// APP_TARGET=admin) on E2E_ADMIN_WEB_PORT. E2E_REUSE_WEB=1 keeps servers already listening there. const API_URL = process.env.E2E_API_URL ?? "http://127.0.0.1:8304"; const WEB_PORT = Number(process.env.E2E_WEB_PORT ?? 5304); +const ADMIN_WEB_PORT = Number(process.env.E2E_ADMIN_WEB_PORT ?? 5305); const WEB_URL = `http://localhost:${WEB_PORT}`; +const ADMIN_WEB_URL = `http://localhost:${ADMIN_WEB_PORT}`; +const reuseExistingServer = process.env.E2E_REUSE_WEB === "1"; +const withModels = process.env.E2E_MODELS === "1"; export default defineConfig({ testDir: "./e2e", globalSetup: "./e2e/global-setup.ts", - // One worker: the flows share one account and the API's per-person auth buckets. + // One worker: the shared seed account's flows edit it in order, and one stack serves the run. + // Every flow that changes an account signs up its own (fixtures.ts), so the order never leaks. workers: 1, fullyParallel: false, forbidOnly: !!process.env.CI, retries: process.env.CI ? 1 : 0, - timeout: 30_000, + timeout: 45_000, expect: { timeout: 10_000 }, reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : [["list"]], use: { - baseURL: WEB_URL, trace: "retain-on-failure", screenshot: "only-on-failure", }, - projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }], - webServer: { - command: `react-router build && vite preview --port ${WEB_PORT} --strictPort --outDir build/client`, - url: WEB_URL, - env: { VITE_PRISMOID_API_URL: API_URL }, - reuseExistingServer: false, - timeout: 180_000, - }, + projects: [ + { + name: "app", + testIgnore: [/admin\//, /models\//], + use: { ...devices["Desktop Chrome"], baseURL: WEB_URL }, + }, + { + name: "admin", + testMatch: /admin\/.*\.spec\.ts/, + use: { ...devices["Desktop Chrome"], baseURL: ADMIN_WEB_URL }, + }, + // A model run settles in seconds, but a flow waits on several of them, and a provider has slow + // minutes: each flow gets four minutes, each wait for a run its own long timeout. + ...(withModels + ? [ + { + name: "models", + testMatch: /models\/.*\.spec\.ts/, + timeout: 240_000, + use: { ...devices["Desktop Chrome"], baseURL: WEB_URL }, + }, + ] + : []), + ], + webServer: [ + { + command: `react-router build && vite preview --port ${WEB_PORT} --strictPort --outDir build/client`, + url: WEB_URL, + env: { VITE_PRISMOID_API_URL: API_URL }, + reuseExistingServer, + timeout: 180_000, + }, + { + command: `react-router build && vite preview --port ${ADMIN_WEB_PORT} --strictPort --outDir build-admin/client`, + url: ADMIN_WEB_URL, + env: { VITE_PRISMOID_API_URL: API_URL, APP_TARGET: "admin" }, + reuseExistingServer, + timeout: 180_000, + }, + ], }); From 684ab8837e269f0741031352c9f1e98ecc460a43 Mon Sep 17 00:00:00 2001 From: Surya Prashanth <5310329+Prashant-Surya@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:17:36 +0530 Subject: [PATCH 2/5] fix: the bugs the browser flows found, each flow's knownBug mark lifted Backend - memory: PATCH and retire answered 500 after saving. The ORM fetches a server default after an INSERT but not an UPDATE, so updated_at stayed expired and the serializer lazy-loaded it outside the greenlet (MissingGreenlet). update/retire now read it back inside the session. Web - composer: a refused send (no goal, fleet or attachments on a routine) resolved, so the composer cleared the typed goal and files; refusals now reject. - signup: an address the API refuses (a deliberately vague 403) gets the form's own sentence instead of the raw server words. - workspace invite: a refused invite closed the dialog and lost the address. - routines: Run now said "Fired" for a skipped fire; the toast now reads the decision (fire-note.ts). - allowed sites: an already-allowed host was listed twice. - bot channels: removing a channel kept showing its dead token. - admin: the reason dialog takes the door's minimum (3 for a routine pause), and the list refreshes after a pause (useKeysetList.refresh). - inbox: the list's keys stand aside for any focused control (keys.ts), and added-to/removed-from a project share one Projects filter. - project settings: saving one field no longer wipes an unsaved edit in the other. - task menu: Pause only for a running or waiting task, Resume only when paused. - sidebar: a refused delete puts the task back. - bots: a search no longer closes (and remounts) the open bot's pane; Draft for me and Test evals re-read until the result lands, not for 40 s. - task browser: the status totals recount on Archived. - reader: a verdict that lands while the reader is open re-reads the receipt. --- backend/prismoid/operations/memory.py | 12 ++- .../integration/memory/test_memories_api.py | 4 + web/app/components/admin/confirm.dom.test.tsx | 62 ++++++++++++++++ web/app/components/admin/confirm.tsx | 6 +- web/app/components/admin/resource-list.tsx | Bin 6776 -> 6942 bytes .../artifact/artifact-view.dom.test.tsx | 10 +++ web/app/components/artifact/artifact-view.tsx | 23 ++++++ .../composer/task-composer.dom.test.tsx | 15 ++++ web/app/components/composer/task-composer.tsx | 29 ++++---- .../tasks/task-browser/browser.dom.test.tsx | 30 +++++++- .../components/tasks/task-browser/browser.tsx | 4 +- .../components/tasks/task-window.dom.test.tsx | 7 +- web/app/components/tasks/task-window.tsx | 31 ++++---- .../workspace/workspace-members.dom.test.tsx | 16 ++++ .../workspace/workspace-members.test.tsx | 2 +- .../workspace/workspace-members.tsx | 23 ++++-- web/app/lib/paging.dom.test.tsx | 15 ++++ web/app/lib/paging.ts | 48 ++++++------ web/app/routes/admin/routines/route.tsx | 8 +- .../routes/allowed-sites/route.dom.test.tsx | 13 ++++ web/app/routes/allowed-sites/route.tsx | 3 +- web/app/routes/bots/authoring-mark.ts | 25 +++++++ web/app/routes/bots/channels-tab.dom.test.tsx | 18 ++++- web/app/routes/bots/channels-tab.tsx | 2 + web/app/routes/bots/configure-tab.tsx | 29 +++----- web/app/routes/bots/route.dom.test.tsx | 9 +++ web/app/routes/bots/route.tsx | 7 +- .../bots/use-authoring-poll.dom.test.tsx | 69 ++++++++++++++++++ web/app/routes/bots/use-authoring-poll.ts | 32 ++++++++ web/app/routes/inbox/inbox.dom.test.tsx | 35 +++++++++ web/app/routes/inbox/keys.dom.test.ts | 40 ++++++++++ web/app/routes/inbox/keys.ts | 24 ++++++ web/app/routes/inbox/route.tsx | 26 ++++--- .../routes/projects.$id/route.dom.test.tsx | 15 ++++ web/app/routes/projects.$id/route.tsx | 6 +- web/app/routes/routines/fire-note.test.ts | 36 +++++++++ web/app/routes/routines/fire-note.ts | 31 ++++++++ web/app/routes/routines/route.dom.test.tsx | 21 ++++++ web/app/routes/routines/route.tsx | 16 +++- web/app/routes/signup/route.dom.test.tsx | 16 ++++ web/app/routes/signup/route.tsx | 22 ++++-- web/app/routes/tasks.$id/reader-pane.tsx | 1 + web/app/routes/tasks.$id/task-menu.test.ts | 28 +++++-- web/app/routes/tasks.$id/task-menu.tsx | 41 +++++++---- web/e2e/admin/bots-routines.spec.ts | 20 ++--- web/e2e/allowed-sites.spec.ts | 6 +- web/e2e/bots-configure.spec.ts | 7 +- web/e2e/bots-tabs.spec.ts | 17 +---- web/e2e/home.spec.ts | 10 +-- web/e2e/inbox.spec.ts | 11 +-- web/e2e/models/bots.spec.ts | 21 +----- web/e2e/models/tasks.spec.ts | 7 +- web/e2e/project-settings.spec.ts | 6 +- web/e2e/routines.spec.ts | 9 +-- web/e2e/settings.spec.ts | 12 +-- web/e2e/shell.spec.ts | 7 +- web/e2e/signup.spec.ts | 8 +- web/e2e/task-page.spec.ts | 7 +- web/e2e/tasks.spec.ts | 7 +- web/e2e/workspaces.spec.ts | 7 +- 60 files changed, 804 insertions(+), 268 deletions(-) create mode 100644 web/app/components/admin/confirm.dom.test.tsx create mode 100644 web/app/routes/bots/authoring-mark.ts create mode 100644 web/app/routes/bots/use-authoring-poll.dom.test.tsx create mode 100644 web/app/routes/bots/use-authoring-poll.ts create mode 100644 web/app/routes/inbox/keys.dom.test.ts create mode 100644 web/app/routes/inbox/keys.ts create mode 100644 web/app/routes/routines/fire-note.test.ts create mode 100644 web/app/routes/routines/fire-note.ts diff --git a/backend/prismoid/operations/memory.py b/backend/prismoid/operations/memory.py index 7c3ee96..f2fea96 100644 --- a/backend/prismoid/operations/memory.py +++ b/backend/prismoid/operations/memory.py @@ -171,7 +171,7 @@ async def update( row.text = body if kind is not None: row.kind = kind.value - await session.commit() + await _commit_redated(session, row) return row @@ -183,11 +183,19 @@ async def retire(session: AsyncSession, actor: Actor, memory_id: uuid.UUID) -> M await _authorise(session, actor, row, write=True) row.status = MemoryStatus.RETIRED.value - await session.commit() + await _commit_redated(session, row) logfire.info("memory {id} retired", id=str(memory_id)) return row +async def _commit_redated(session: AsyncSession, row: Memory) -> None: + """Commit an edit and read back the `updated_at` Postgres re-dated it to. The ORM fetches a + server default after an INSERT but not after an UPDATE, so the column is left expired, and the + serializer's read of it would lazy-load outside the async greenlet (a 500 on a saved edit).""" + await session.commit() + await session.refresh(row, ["updated_at"]) + + async def _authorise(session: AsyncSession, actor: Actor, row: Memory, *, write: bool) -> None: """The lane's gate, given a fetched row. User rows 404 for anyone else (existence is privileged); project rows defer to `Project.get_for` (which 404s strangers, 403s viewers on diff --git a/backend/tests/integration/memory/test_memories_api.py b/backend/tests/integration/memory/test_memories_api.py index 063738f..a297b65 100644 --- a/backend/tests/integration/memory/test_memories_api.py +++ b/backend/tests/integration/memory/test_memories_api.py @@ -18,6 +18,7 @@ import pytest +from prismoid.api.serializers.memories import memory_out from prismoid.db.models.memory import Memory, MemoryKind, MemoryScope, MemoryStatus from prismoid.db.models.project_member import ProjectMember from prismoid.db.session import session_scope @@ -57,9 +58,12 @@ async def test_user_scope_is_private_and_retire_keeps_the_row() -> None: edited = await ops.update(session, alice, row.id, text="Prefers one-page memos.") assert edited.text == "Prefers one-page memos." + # The API serializes the row it gets back: its re-dated updated_at must already be loaded. + assert memory_out(edited).updated_at >= row.created_at retired = await ops.retire(session, alice, row.id) assert retired.status == MemoryStatus.RETIRED.value + assert memory_out(retired).status == MemoryStatus.RETIRED.value assert await ops.list_memories(session, alice, scope=MemoryScope.USER) == [], "active list hides it" lineage = await ops.list_memories(session, alice, scope=MemoryScope.USER, status=None) assert [m.id for m in lineage] == [row.id], "retire keeps the row - nothing is deleted" diff --git a/web/app/components/admin/confirm.dom.test.tsx b/web/app/components/admin/confirm.dom.test.tsx new file mode 100644 index 0000000..cad12ff --- /dev/null +++ b/web/app/components/admin/confirm.dom.test.tsx @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// @vitest-environment happy-dom +// A verb that takes prose: the confirm waits for a reason as long as its door accepts, and sends +// it trimmed. +import { cleanup, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ReasonDialog } from "./confirm"; + +afterEach(() => { + cleanup(); + document.body.innerHTML = ""; +}); + +function mount(onConfirm: (reason: string) => Promise<void>, minLength?: number) { + render( + <ReasonDialog + trigger="Pause" + title="Pause it?" + description="It stops." + placeholder="Why?" + confirmLabel="Pause routine" + minLength={minLength} + onConfirm={onConfirm} + />, + ); +} + +describe("ReasonDialog", () => { + it("waits for a reason of the door's minimum length, then sends it trimmed", async () => { + const user = userEvent.setup(); + const onConfirm = vi.fn(async () => {}); + mount(onConfirm, 3); + await user.click(screen.getByRole("button", { name: "Pause" })); + const dialog = await screen.findByRole("dialog"); + const confirm = within(dialog).getByRole("button", { name: "Pause routine" }); + expect(within(dialog).getByText("At least 3 characters.")).toBeTruthy(); + await user.type(within(dialog).getByRole("textbox", { name: "Reason" }), " ab "); + expect(confirm.hasAttribute("disabled")).toBe(true); + await user.type(within(dialog).getByRole("textbox", { name: "Reason" }), "c"); + expect(confirm.hasAttribute("disabled")).toBe(false); + await user.click(confirm); + await waitFor(() => expect(onConfirm).toHaveBeenCalledWith("ab c")); + }); + + it("takes any reason at all by default, with no hint", async () => { + const user = userEvent.setup(); + mount(vi.fn(async () => {})); + await user.click(screen.getByRole("button", { name: "Pause" })); + const dialog = await screen.findByRole("dialog"); + await user.type(within(dialog).getByRole("textbox", { name: "Reason" }), "x"); + expect( + within(dialog).getByRole("button", { name: "Pause routine" }).hasAttribute("disabled"), + ).toBe(false); + expect(within(dialog).queryByText(/^At least/)).toBeNull(); + }); +}); diff --git a/web/app/components/admin/confirm.tsx b/web/app/components/admin/confirm.tsx index 2e91e7c..e08f875 100644 --- a/web/app/components/admin/confirm.tsx +++ b/web/app/components/admin/confirm.tsx @@ -133,6 +133,7 @@ export function ReasonDialog({ description, placeholder, confirmLabel, + minLength = 1, onConfirm, }: { /** A label for the stock danger-outline trigger, or the trigger element itself. */ @@ -141,12 +142,14 @@ export function ReasonDialog({ description: ReactNode; placeholder: string; confirmLabel: string; + /** The shortest reason the door accepts (its serializer's min_length): the confirm waits for it. */ + minLength?: number; onConfirm: (reason: string) => Promise<void>; }) { const [open, setOpen] = useState(false); const [reason, setReason] = useState(""); const [busy, setBusy] = useState(false); - const ready = reason.trim().length > 0; + const ready = reason.trim().length >= minLength; async function run() { if (!ready) return; @@ -197,6 +200,7 @@ export function ReasonDialog({ value={reason} onChange={(e) => setReason(e.currentTarget.value)} placeholder={placeholder} + hint={minLength > 1 ? `At least ${minLength} characters.` : undefined} autoResize autoFocus /> diff --git a/web/app/components/admin/resource-list.tsx b/web/app/components/admin/resource-list.tsx index 2c74375068e190b1e832e0a65991943291fc8564..2227a57605a8cc7fc4c3438a814a602a7bdab27c 100644 GIT binary patch delta 219 zcmexiGS6&-JZHUQo<e3`PG(*zmx6+VmV!cAYEhCxc}9M5szOSBevv|AUU7M9QL#c^ zzCuxcxk7ScPEN5xLQ!g3QEG8Uf<g&UI90bOH8Dk@BqLQJC$qRjy;vaw$k$WQ(g&Ie z)MTZgky(<OYo!pP16E+APz}@sHo!_uK|@o))=nXyC_gu|IMt>sKQqNnp?0$&XB#`G h4ounR?E)v+d36x_fGQd!xEN7|CO1fkPhKc_9RQc{Ng)6L delta 48 zcmbPd_QPa@Jg1PBK9_<*QGU6Vf<|UZYOa++$mT7aZS0$!1y8b1HjomZY#{j=NWTLB Dd07xA diff --git a/web/app/components/artifact/artifact-view.dom.test.tsx b/web/app/components/artifact/artifact-view.dom.test.tsx index 023b0cc..1c70b86 100644 --- a/web/app/components/artifact/artifact-view.dom.test.tsx +++ b/web/app/components/artifact/artifact-view.dom.test.tsx @@ -164,6 +164,16 @@ describe("ArtifactView receipt and history", () => { expect(await screen.findByText(/Not verified yet/)).toBeDefined(); }); + it("a verdict that lands while the reader is open re-reads the receipt", async () => { + const get = serve({ verification: null }); + const { rerender } = render(<ArtifactView artifactId="a1" />); + expect(await screen.findByText(/Not verified yet/)).toBeDefined(); + get.mockRestore(); + serve(); + rerender(<ArtifactView artifactId="a1" verdict="pass" />); + await waitFor(() => expect(screen.queryByText(/Not verified yet/)).toBeNull()); + }); + it("viewing an older version refetches it, and the host is not told of a new head", async () => { const user = userEvent.setup(); const v2 = art({ id: "a2", revision: 2, sha256: "bbb" }); diff --git a/web/app/components/artifact/artifact-view.tsx b/web/app/components/artifact/artifact-view.tsx index fb2ebe6..853c2e7 100644 --- a/web/app/components/artifact/artifact-view.tsx +++ b/web/app/components/artifact/artifact-view.tsx @@ -86,6 +86,7 @@ export function ArtifactView({ onArtifactChanged, chrome = "full", readOnly = false, + verdict, }: { artifactId: string; hostActions?: ReactNode; @@ -97,6 +98,9 @@ export function ArtifactView({ chrome?: "full" | "bare"; /** The reader may not write (a Project viewer): no edit, no restore, no label. */ readOnly?: boolean; + /** The head's verdict as the host's live stream saw it. The receipt signs after publish, on its + * own queue, so it usually lands after the reader opened: a new verdict re-reads it here. */ + verdict?: string | null; }) { // The id being VIEWED - moves along the lineage via the version picker or a save. const [currentId, setCurrentId] = useState(artifactId); @@ -165,6 +169,25 @@ export function ArtifactView({ }; }, [currentId]); + // The verdict the open read already reflects; only a new one re-reads the receipt, and only + // for the head (an older version's receipt is its own). + const verdictRead = useRef(verdict); + useEffect(() => { + if (!verdict || verdict === verdictRead.current || currentId !== artifactId) return; + verdictRead.current = verdict; + let cancelled = false; + unwrap( + api.GET("/v1/artifacts/{artifact_id}/verification", { + params: { path: { artifact_id: artifactId } }, + }), + ) + .then((verification) => !cancelled && setState((s) => ({ ...s, verification }))) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [verdict, currentId, artifactId]); + if (state.loading) { return ( <> diff --git a/web/app/components/composer/task-composer.dom.test.tsx b/web/app/components/composer/task-composer.dom.test.tsx index 86d4e5c..3341b2c 100644 --- a/web/app/components/composer/task-composer.dom.test.tsx +++ b/web/app/components/composer/task-composer.dom.test.tsx @@ -141,6 +141,21 @@ describe("TaskComposer sending", () => { expect(screen.getByText("plan.pdf")).toBeTruthy(); }); + it("a file sent with no goal is refused and stays attached", async () => { + const user = userEvent.setup(); + const err = vi.spyOn(toast, "error").mockImplementation((() => "") as never); + mount(); + await user.upload( + document.querySelector("input[type=file]") as HTMLInputElement, + new File(["x"], "plan.pdf"), + ); + await screen.findByText("plan.pdf"); + await user.click(screen.getByRole("button", { name: "Submit" })); + await waitFor(() => expect(err).toHaveBeenCalledWith("Describe the task to start.")); + expect(post).not.toHaveBeenCalled(); + expect(screen.getByText("plan.pdf")).toBeTruthy(); + }); + it("any other failure falls back to a plain message", async () => { const user = userEvent.setup(); const err = vi.spyOn(toast, "error").mockImplementation((() => "") as never); diff --git a/web/app/components/composer/task-composer.tsx b/web/app/components/composer/task-composer.tsx index 7f96ca9..870de2f 100644 --- a/web/app/components/composer/task-composer.tsx +++ b/web/app/components/composer/task-composer.tsx @@ -100,6 +100,13 @@ function unprocessableReason(e: unknown, attached: Attachment[]): string | undef const noStartHook = () => {}; +/** Refuse a send before it leaves: say why, and reject, so the composer keeps what was typed and + * attached (it clears its draft only on a resolved send, composer.tsx). */ +function refuse(reason: string): never { + toast.error(reason); + throw new Error(reason); +} + export function TaskComposer({ options, initialProject = null, @@ -220,25 +227,16 @@ export function TaskComposer({ async function start({ text, attachments }: { text: string; attachments: Attachment[] }) { const goal = text.trim(); - if (!goal) { - toast.error("Describe the task to start."); - return; - } - setBusy(true); + if (!goal) refuse("Describe the task to start."); // A standing When branches here: the SAME payload posts as a routine (the constitution - // the composer, saved instead of sent). Fleet seats and attachments have no standing // shape yet, so the refusal is honest and immediate rather than a 422 later. if (when.mode !== "now") { - if (mode === "fleet") { - setBusy(false); - toast.error("Routines run standard tasks. Switch the mode dial off fleet first."); - return; - } - if (attachments.length) { - setBusy(false); - toast.error("Routines can't carry attachments yet - each run starts fresh."); - return; - } + if (mode === "fleet") + refuse("Routines run standard tasks. Switch the mode dial off fleet first."); + if (attachments.length) + refuse("Routines can't carry attachments yet - each run starts fresh."); + setBusy(true); try { const saved = await unwrap( api.POST("/v1/routines", { @@ -271,6 +269,7 @@ export function TaskComposer({ } return; } + setBusy(true); const body: TaskCreateIn = { goal, mode, diff --git a/web/app/components/tasks/task-browser/browser.dom.test.tsx b/web/app/components/tasks/task-browser/browser.dom.test.tsx index 9b32141..972c831 100644 --- a/web/app/components/tasks/task-browser/browser.dom.test.tsx +++ b/web/app/components/tasks/task-browser/browser.dom.test.tsx @@ -8,7 +8,7 @@ // The task browser, driven: status groups with their true counts, the debounced search sending // its query, bulk select (checkbox, Select all, Ctrl+A, Escape) then archive or confirmed // delete on the wire, an empty list, and the other groupings and the board layout. -import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { createMemoryRouter, RouterProvider } from "react-router"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -102,6 +102,34 @@ describe("TaskBrowser lists", () => { expect(screen.getByText("fleet")).toBeDefined(); }); + it("switching to Archived recounts the headers for the archived rows", async () => { + const router = createMemoryRouter( + [ + { + path: "*", + element: ( + <TaskWindowProvider initial={{ pins: [], recents: [] }}> + <TaskBrowser syncToUrl /> + </TaskWindowProvider> + ), + }, + ], + { initialEntries: ["/"] }, + ); + render(<RouterProvider router={router} />); + await screen.findByText("Goal r1"); + const counted = (): { archived?: boolean }[] => + get.mock.calls + .filter((c: unknown[]) => c[0] === "/v1/tasks/counts") + .map( + (c: unknown[]) => (c[1] as { params: { query: { archived?: boolean } } }).params.query, + ); + await waitFor(() => expect(counted().length).toBeGreaterThan(0)); + expect(counted().some((q) => q.archived)).toBe(false); + await act(() => router.navigate("/?archived=1")); + await waitFor(() => expect(counted().some((q) => q.archived === true)).toBe(true)); + }); + it("the search box sends the settled query to the server", async () => { const user = userEvent.setup(); mount(); diff --git a/web/app/components/tasks/task-browser/browser.tsx b/web/app/components/tasks/task-browser/browser.tsx index d661685..589504e 100644 --- a/web/app/components/tasks/task-browser/browser.tsx +++ b/web/app/components/tasks/task-browser/browser.tsx @@ -284,8 +284,10 @@ export function TaskBrowser({ live = false; window.clearInterval(id); }; + // The lists' own deps (archived and the bulk refresh lever included), so the totals always + // count the rows the headers sit over. // eslint-disable-next-line react-hooks/exhaustive-deps -- scope is identity-fresh; its parts are the deps - }, [byStatus, dq, filters.project, filters.mode, projectId]); + }, [byStatus, ...filterDeps]); const groupCount = (g: GroupDef) => counts === null ? null : g.statuses.reduce((n, s) => n + (counts[s] ?? 0), 0); diff --git a/web/app/components/tasks/task-window.dom.test.tsx b/web/app/components/tasks/task-window.dom.test.tsx index 6ab5a56..91679a1 100644 --- a/web/app/components/tasks/task-window.dom.test.tsx +++ b/web/app/components/tasks/task-window.dom.test.tsx @@ -196,7 +196,7 @@ describe("TaskWindowProvider", () => { expect(del.mock.calls[0][1]).toEqual({ params: { path: { task_id: "r1" } } }); }); - it("a failed delete returns false", async () => { + it("a failed delete returns false and puts the row back where it was", async () => { vi.spyOn(toast, "error").mockImplementation((() => "") as never); vi.spyOn(api, "DELETE").mockImplementation((() => Promise.reject(new Error("x"))) as never); const { result } = hook(SEED); @@ -205,6 +205,11 @@ describe("TaskWindowProvider", () => { ok = await result.current.remove("r1"); }); expect(ok).toBe(false); + expect(result.current.recents.map((r) => r.id)).toEqual(["r1", "r2"]); + await act(async () => { + await result.current.remove("p1"); + }); + expect(result.current.pins.map((r) => r.id)).toEqual(["p1"]); }); it("patch writes what a live surface knows into the matching row", async () => { diff --git a/web/app/components/tasks/task-window.tsx b/web/app/components/tasks/task-window.tsx index c68d1ad..12f227f 100644 --- a/web/app/components/tasks/task-window.tsx +++ b/web/app/components/tasks/task-window.tsx @@ -202,19 +202,24 @@ export function TaskWindowProvider({ } }, []); - const remove = useCallback(async (id: string): Promise<boolean> => { - // Drop the row immediately; a delete is a decision, and a lingering row reads as failure. - // On error the window refetches on the next navigation, so a false optimistic removal heals. - setPins((current) => current.filter((item) => item.id !== id)); - setRecents((current) => current.filter((item) => item.id !== id)); - try { - await unwrap(api.DELETE("/v1/tasks/{task_id}", { params: { path: { task_id: id } } })); - return true; - } catch (error) { - toastError(error, "Couldn't delete the task."); - return false; - } - }, []); + const remove = useCallback( + async (id: string): Promise<boolean> => { + // Drop the row immediately; a delete is a decision, and a lingering row reads as failure. + // A refusal (a live task answers 409) puts it back where it was: the task still exists. + const row = [...pins, ...recents].find((item) => item.id === id); + setPins((current) => current.filter((item) => item.id !== id)); + setRecents((current) => current.filter((item) => item.id !== id)); + try { + await unwrap(api.DELETE("/v1/tasks/{task_id}", { params: { path: { task_id: id } } })); + return true; + } catch (error) { + if (row) (row.pinned ? setPins : setRecents)((current) => insertByRecency(current, row)); + toastError(error, "Couldn't delete the task."); + return false; + } + }, + [pins, recents], + ); const latest = useMemo(() => mergeTaskWindow(pins, recents), [pins, recents]); const value = useMemo( diff --git a/web/app/components/workspace/workspace-members.dom.test.tsx b/web/app/components/workspace/workspace-members.dom.test.tsx index 20c8c42..f331bec 100644 --- a/web/app/components/workspace/workspace-members.dom.test.tsx +++ b/web/app/components/workspace/workspace-members.dom.test.tsx @@ -103,6 +103,22 @@ describe("WorkspaceMembersPanel", () => { ); }); + it("a refused invite keeps the dialog open with the typed address", async () => { + post.mockImplementation((() => failure(422, "that address cannot be invited")) as never); + const user = userEvent.setup(); + render(<WorkspaceMembersPanel />); + await screen.findByText("Person bob"); + await user.click(screen.getByRole("button", { name: "Invite" })); + const dialog = await screen.findByRole("dialog"); + const email = within(dialog).getByRole("textbox", { name: "Email" }); + await user.type(email, "ada@example.com"); + await user.click(within(dialog).getByRole("button", { name: "Send invite" })); + await waitFor(() => expect(toast.error).toHaveBeenCalled()); + expect(toast.success).not.toHaveBeenCalled(); + expect(screen.getByRole("dialog")).toBeTruthy(); + expect((email as HTMLInputElement).value).toBe("ada@example.com"); + }); + it("revokes a pending invite", async () => { const user = userEvent.setup(); render(<WorkspaceMembersPanel />); diff --git a/web/app/components/workspace/workspace-members.test.tsx b/web/app/components/workspace/workspace-members.test.tsx index 03020d8..574aceb 100644 --- a/web/app/components/workspace/workspace-members.test.tsx +++ b/web/app/components/workspace/workspace-members.test.tsx @@ -18,7 +18,7 @@ const noop = () => {}; const handlers = { onRole: noop, onRemove: noop, - onInvite: noop, + onInvite: async () => true, onRevoke: noop, onLeave: noop, onTransfer: noop, diff --git a/web/app/components/workspace/workspace-members.tsx b/web/app/components/workspace/workspace-members.tsx index 6394bd4..886f112 100644 --- a/web/app/components/workspace/workspace-members.tsx +++ b/web/app/components/workspace/workspace-members.tsx @@ -42,7 +42,7 @@ import { useMe } from "./use-workspace"; type Member = components["schemas"]["WorkspaceMemberOut"]; type Invite = components["schemas"]["WorkspaceInviteOut"]; -type Act<A extends unknown[] = []> = (...a: A) => void | Promise<void>; +type Act<A extends unknown[] = []> = (...a: A) => void | Promise<unknown>; export function MembersView({ myId, @@ -62,7 +62,8 @@ export function MembersView({ invites: Invite[]; onRole: Act<[actorId: string, role: string]>; onRemove: Act<[actorId: string]>; - onInvite: Act<[email: string, role: string]>; + /** Resolves true once the invite is sent; a refusal (already toasted) resolves false. */ + onInvite: (email: string, role: string) => Promise<boolean>; onRevoke: Act<[inviteId: string]>; onLeave: Act; onTransfer: Act<[actorId: string]>; @@ -167,7 +168,13 @@ export function MembersView({ ); } -function InviteDialog({ role, onInvite }: { role: string; onInvite: Act<[string, string]> }) { +function InviteDialog({ + role, + onInvite, +}: { + role: string; + onInvite: (email: string, role: string) => Promise<boolean>; +}) { const [open, setOpen] = useState(false); const [email, setEmail] = useState(""); const [as, setAs] = useState("member"); @@ -176,7 +183,8 @@ function InviteDialog({ role, onInvite }: { role: string; onInvite: Act<[string, async function send() { setBusy(true); try { - await onInvite(email.trim(), as); + // A refused invite keeps the dialog and the typed address, so the person can fix and resend. + if (!(await onInvite(email.trim(), as))) return; setOpen(false); setEmail(""); } finally { @@ -273,13 +281,18 @@ export function WorkspaceMembersPanel() { if (!workspace) return <NoWorkspaceState />; if (!members) return <LoadingState />; + /** Call a door, say how it went, reload the roster: true when it went through. */ const run = (fn: () => Promise<unknown>, fail: string, ok?: string) => fn().then( () => { if (ok) toast.success(ok); load(); + return true; + }, + (e) => { + toastError(e, fail); + return false; }, - (e) => toastError(e, fail), ); const member = (actor_id: string) => ({ params: { path: { workspace_id: workspace.id, actor_id } }, diff --git a/web/app/lib/paging.dom.test.tsx b/web/app/lib/paging.dom.test.tsx index a7ee9b6..9adba67 100644 --- a/web/app/lib/paging.dom.test.tsx +++ b/web/app/lib/paging.dom.test.tsx @@ -167,4 +167,19 @@ describe("useKeysetList", () => { }); await waitFor(() => expect(ids(result.current.items)).toEqual(["c", "b", "a"])); }); + + it("refresh() re-reads the head on demand, with no poll set", async () => { + let n = 0; + const fetchPage = vi.fn(async () => { + n += 1; + return n === 1 + ? { items: [row("b", "2"), row("a", "1")], next_cursor: null } + : { items: [row("c", "3"), row("b", "2")], next_cursor: null }; + }); + const { result } = setup(fetchPage); + await waitFor(() => expect(result.current.items?.length).toBe(2)); + await act(() => result.current.refresh()); + expect(fetchPage).toHaveBeenCalledTimes(2); + expect(ids(result.current.items)).toEqual(["c", "b", "a"]); + }); }); diff --git a/web/app/lib/paging.ts b/web/app/lib/paging.ts index 1eafede..8e45dbe 100644 --- a/web/app/lib/paging.ts +++ b/web/app/lib/paging.ts @@ -58,7 +58,8 @@ export function mutateLoaded<T>(current: T[] | null, fn: (items: T[]) => T[]): T * - `loadMore()` appends the next page, id-deduped. * - `refreshMs` keeps the HEAD live: page one is re-read and spliced over the loaded head at * the keyset boundary, so already-loaded tail pages survive the poll. Status changes happen - * to recent tasks, and recent is exactly what page one holds (newest-first). + * to recent tasks, and recent is exactly what page one holds (newest-first). `refresh()` is + * the same re-read on demand: after a mutation whose answer carries no row to `mutate` in. * - `initial` seeds from a route loader so hydration paints data, not a spinner. */ export function useKeysetList<T extends { id: string }>(opts: { @@ -111,30 +112,33 @@ export function useKeysetList<T extends { id: string }>(opts: { // eslint-disable-next-line react-hooks/exhaustive-deps -- deps ARE the dependency list }, [enabled, ...deps]); + const refresh = useCallback(async () => { + const token = seq.current; + try { + const page = await fetchRef.current(null); + if (token !== seq.current) return; // the query changed mid-flight + setItems((cur) => { + if (cur === null) return page.items; + const next = spliceHead(cur, page.items, orderRef.current); + // With no surviving tail the list IS page one - adopt its cursor, or new rows + // past the page boundary would be unreachable until a reload. + if (next.length === page.items.length && cursorRef.current === null) { + setCursor(page.next_cursor ?? null); + } + return next; + }); + } catch { + /* transient - keep what we have */ + } + }, []); + useEffect(() => { if (!refreshMs || !enabled) return; - const id = window.setInterval(async () => { - if (document.hidden) return; - const token = seq.current; - try { - const page = await fetchRef.current(null); - if (token !== seq.current) return; // the query changed mid-flight - setItems((cur) => { - if (cur === null) return page.items; - const next = spliceHead(cur, page.items, orderRef.current); - // With no surviving tail the list IS page one - adopt its cursor, or new rows - // past the page boundary would be unreachable until a reload. - if (next.length === page.items.length && cursorRef.current === null) { - setCursor(page.next_cursor ?? null); - } - return next; - }); - } catch { - /* transient - keep what we have */ - } + const id = window.setInterval(() => { + if (!document.hidden) void refresh(); }, refreshMs); return () => window.clearInterval(id); - }, [refreshMs, enabled]); + }, [refreshMs, enabled, refresh]); const loadMore = useCallback(async () => { const at = cursorRef.current; @@ -160,5 +164,5 @@ export function useKeysetList<T extends { id: string }>(opts: { setItems((cur) => mutateLoaded(cur, fn)); }, []); - return { items, loadMore, loadingMore, hasMore: cursor !== null, mutate }; + return { items, loadMore, loadingMore, hasMore: cursor !== null, mutate, refresh }; } diff --git a/web/app/routes/admin/routines/route.tsx b/web/app/routes/admin/routines/route.tsx index 6d2e54f..93bdda4 100644 --- a/web/app/routes/admin/routines/route.tsx +++ b/web/app/routes/admin/routines/route.tsx @@ -27,7 +27,7 @@ export function meta() { const STATUS_TONE = { active: "success", paused: "warning", retired: "muted" } as const; -function PauseVerb({ r }: { r: RoutineRow }) { +function PauseVerb({ r, onPaused }: { r: RoutineRow; onPaused: () => void }) { return ( // Only stops the row's click; the dialog's own trigger is the control. <span role="presentation" onClick={(e) => e.stopPropagation()}> @@ -44,6 +44,7 @@ function PauseVerb({ r }: { r: RoutineRow }) { description="Its clock and doors stop immediately; the owner is told, with your reason, and only they can resume it." placeholder="Why is the operator stopping this routine?" confirmLabel="Pause routine" + minLength={3} onConfirm={async (reason) => { try { await unwrap( @@ -53,6 +54,7 @@ function PauseVerb({ r }: { r: RoutineRow }) { }), ); toast.success("Paused. Audited, and the owner has the note."); + onPaused(); } catch (e) { toastError(e, "Couldn't pause it."); throw e; @@ -80,7 +82,7 @@ const config: ResourceListConfig<RoutineRow> = { orderKey: (r) => r.created_at, rowKey: (r) => r.id, onRow: () => undefined, // observation rows; the one verb rides inline - row: (r) => ( + row: (r, list) => ( <> <AlarmClock className="text-muted-foreground size-4 shrink-0" /> <span className="min-w-0 flex-1"> @@ -102,7 +104,7 @@ const config: ResourceListConfig<RoutineRow> = { {r.last_fired_at ? ` · last ${ago(r.last_fired_at)}` : ""} </span> <Pill tone={STATUS_TONE[r.status as keyof typeof STATUS_TONE] ?? "muted"}>{r.status}</Pill> - {r.status === "active" && <PauseVerb r={r} />} + {r.status === "active" && <PauseVerb r={r} onPaused={() => void list.refresh()} />} </> ), search: { placeholder: "Search routine names…", topbar: true }, diff --git a/web/app/routes/allowed-sites/route.dom.test.tsx b/web/app/routes/allowed-sites/route.dom.test.tsx index 9d79e55..d6549c8 100644 --- a/web/app/routes/allowed-sites/route.dom.test.tsx +++ b/web/app/routes/allowed-sites/route.dom.test.tsx @@ -70,6 +70,19 @@ describe("AllowedSites", () => { expect((screen.getByRole("textbox", { name: "Host" }) as HTMLInputElement).value).toBe(""); }); + it("a host already allowed comes back as its row and is listed once", async () => { + const user = userEvent.setup(); + post.mockImplementation((() => reply(200, row("1", "docs.vendor.com"))) as never); + mount([row("1", "docs.vendor.com")]); + await user.type(screen.getByRole("textbox", { name: "Host" }), "docs.vendor.com"); + await user.click(screen.getByRole("button", { name: "Always allow" })); + await waitFor(() => expect(post).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect((screen.getByRole("textbox", { name: "Host" }) as HTMLInputElement).value).toBe(""), + ); + expect(screen.getAllByText("docs.vendor.com")).toHaveLength(1); + }); + it("a 422 puts the server's words under the field and typing clears them", async () => { const user = userEvent.setup(); post.mockImplementation((() => diff --git a/web/app/routes/allowed-sites/route.tsx b/web/app/routes/allowed-sites/route.tsx index a4f6e12..3c28ba6 100644 --- a/web/app/routes/allowed-sites/route.tsx +++ b/web/app/routes/allowed-sites/route.tsx @@ -97,7 +97,8 @@ export default function AllowedSites({ loaderData }: Route.ComponentProps) { setFieldError(null); try { const row = await unwrap(api.POST("/v1/egress-allowances", { body: { host: trimmed } })); - setRows((cur) => [row, ...cur]); + // An already-allowed host comes back as its existing row: move it to the top, never twice. + setRows((cur) => [row, ...cur.filter((r) => r.id !== row.id)]); setHost(""); } catch (e) { if (e instanceof ApiError && e.status === 422 && e.fields?.host) { diff --git a/web/app/routes/bots/authoring-mark.ts b/web/app/routes/bots/authoring-mark.ts new file mode 100644 index 0000000..cfe0192 --- /dev/null +++ b/web/app/routes/bots/authoring-mark.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// What an authoring job changes on the bot's rows when it lands: the drafter mints the next +// version, a selection-eval run writes the draft's verdict and report. The Configure tab re-reads +// the bot until this mark moves, so the result shows however long the worker takes. + +type Row = { version: number; eval_status: string; eval_report?: unknown }; + +export function authoringMark(b: { newest: Row; draftAhead?: Row | null; head: Row }): string { + const working = b.draftAhead ?? b.head; + return JSON.stringify([ + b.newest.version, + working.version, + working.eval_status, + working.eval_report, + ]); +} + +/** How long the tab keeps re-reading for a job whose mark never moves (a re-run that scored the + * same): long past any drafter or eval run, never forever. */ +export const AUTHORING_CAP_MS = 180_000; diff --git a/web/app/routes/bots/channels-tab.dom.test.tsx b/web/app/routes/bots/channels-tab.dom.test.tsx index b1d561f..4095574 100644 --- a/web/app/routes/bots/channels-tab.dom.test.tsx +++ b/web/app/routes/bots/channels-tab.dom.test.tsx @@ -8,7 +8,7 @@ // A bot's Channels tab, driven: the list shows each door's status and limits, Add webhook mints // one and shows its token once, rotate swaps the token, disable/enable hit the right verb, and // remove deletes the door. -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api } from "~/lib/api/client"; @@ -130,4 +130,20 @@ describe("Channel actions", () => { }); expect(await screen.findByText("No doors yet")).toBeTruthy(); }); + + it("removing a door takes its shown-once token away with it", async () => { + const user = userEvent.setup(); + rows = [channel("c1"), channel("c2")]; + post.mockResolvedValueOnce(ok(channel("c1", { token: "bc_new" })) as never); + del.mockImplementationOnce((() => { + rows = [channel("c2")]; + return Promise.resolve(ok({})); + }) as never); + render(<ChannelsTab name="scout" projectId={null} />); + await user.click((await screen.findAllByRole("button", { name: "Rotate the token" }))[0]); + expect(await screen.findByText("bc_new")).toBeTruthy(); + await user.click(screen.getAllByRole("button", { name: "Remove the channel" })[0]); + await waitFor(() => expect(screen.queryByText("Door c1")).toBeNull()); + expect(screen.queryByText("bc_new")).toBeNull(); + }); }); diff --git a/web/app/routes/bots/channels-tab.tsx b/web/app/routes/bots/channels-tab.tsx index c365372..138f2fc 100644 --- a/web/app/routes/bots/channels-tab.tsx +++ b/web/app/routes/bots/channels-tab.tsx @@ -87,6 +87,8 @@ export function ChannelsTab({ name, projectId }: { name: string; projectId: stri api.DELETE("/v1/channels/{channel_id}", { params: { path: { channel_id: id } } }), ); toast.success("Channel removed, ledger and all."); + // Its token died with it: stop showing it. + setMinted((cur) => (cur?.id === id ? null : cur)); await reload(); } catch (e) { toastError(e, "Couldn't remove it."); diff --git a/web/app/routes/bots/configure-tab.tsx b/web/app/routes/bots/configure-tab.tsx index 86c5486..58ff760 100644 --- a/web/app/routes/bots/configure-tab.tsx +++ b/web/app/routes/bots/configure-tab.tsx @@ -10,7 +10,7 @@ // per case why the pill is the colour it is; versions below. import { FlaskConical, Sparkles, Upload } from "lucide-react"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useRevalidator } from "react-router"; import { toast } from "@prismoid/blocks/toast"; import { Pill, Rows, Section } from "~/components/kit"; @@ -24,6 +24,8 @@ import { cn } from "~/lib/utils"; import type { BotHead } from "./route"; import { Editor } from "./bot-editor"; import { ShareTemplate } from "./share-template"; +import { authoringMark } from "./authoring-mark"; +import { useAuthoringPoll } from "./use-authoring-poll"; type CaseRow = { goal: string; expected: string; chosen: string; ok: boolean }; @@ -68,25 +70,12 @@ export function ConfigureTab({ } } - // The authoring jobs: both run on the worker and land back on this row, so the - // gesture here is start-then-poll - a few quiet revalidations, never a spinner takeover. - // ONE interval, cleared on unmount and restarted (not stacked) by a second click; one - // revalidation per tick (`onChanged` is the same revalidator one level up). - const [pollingUntil, setPollingUntil] = useState(0); - function pollResult() { - setPollingUntil(Date.now() + 40_000); - } - useEffect(() => { - if (pollingUntil <= Date.now()) return; - const timer = window.setInterval(() => { - if (Date.now() >= pollingUntil) { - setPollingUntil(0); - return; - } - revalidator.revalidate(); - }, 5000); - return () => window.clearInterval(timer); - }, [pollingUntil, revalidator]); + // The authoring jobs: both run on the worker and land back on this row, so the gesture here + // is start-then-poll - quiet revalidations until the result lands, never a spinner takeover. + const pollResult = useAuthoringPoll( + authoringMark({ head, newest, draftAhead }), + revalidator.revalidate, + ); async function draftForMe() { try { diff --git a/web/app/routes/bots/route.dom.test.tsx b/web/app/routes/bots/route.dom.test.tsx index af6af82..9fd810d 100644 --- a/web/app/routes/bots/route.dom.test.tsx +++ b/web/app/routes/bots/route.dom.test.tsx @@ -147,6 +147,15 @@ describe("Bot list", () => { expect(screen.getByText("0 bots · 0 pinned to sidebar")).toBeTruthy(); }); + it("a search that leaves the open bot out narrows the list and keeps its pane", async () => { + const user = userEvent.setup(); + mount([bot("alpha"), bot("beta", { description: "Reviews contracts" })], "alpha", "?tab=runs"); + await screen.findByRole("heading", { name: "alpha" }); + await user.type(screen.getByPlaceholderText("Search bots…"), "contracts"); + expect(screen.queryByRole("link", { name: /alpha/ })).toBeNull(); + expect(screen.getByRole("heading", { name: "alpha" })).toBeTruthy(); + }); + it("filters rows by name or description as you type", async () => { const user = userEvent.setup(); mount([bot("alpha"), bot("beta", { description: "Reviews contracts" })]); diff --git a/web/app/routes/bots/route.tsx b/web/app/routes/bots/route.tsx index f25bac3..1b9223f 100644 --- a/web/app/routes/bots/route.tsx +++ b/web/app/routes/bots/route.tsx @@ -143,11 +143,14 @@ export default function Bots({ loaderData }: Route.ComponentProps) { const revalidator = useRevalidator(); const [q, setQ] = useState(""); const needle = q.trim().toLowerCase(); - const rows = heads(items).filter( + const all = heads(items); + const rows = all.filter( (r) => !needle || r.head.name.includes(needle) || r.head.description.toLowerCase().includes(needle), ); - const current = selected ? rows.find((r) => r.head.name === selected) : undefined; + // The open bot comes from every bot, not the search's rows: a search narrows the list and + // never closes the pane (or remounts it, which threw away unsaved Configure edits). + const current = selected ? all.find((r) => r.head.name === selected) : undefined; const pinnedCount = rows.filter((r) => r.head.pinned).length; return ( diff --git a/web/app/routes/bots/use-authoring-poll.dom.test.tsx b/web/app/routes/bots/use-authoring-poll.dom.test.tsx new file mode 100644 index 0000000..5fa6d2b --- /dev/null +++ b/web/app/routes/bots/use-authoring-poll.dom.test.tsx @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// @vitest-environment happy-dom +// The authoring poll re-reads until the job lands (the mark moves), however long that takes, and +// gives up only at the cap. +import { act, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AUTHORING_CAP_MS, authoringMark } from "./authoring-mark"; +import { useAuthoringPoll } from "./use-authoring-poll"; + +beforeEach(() => { + vi.useFakeTimers(); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe("useAuthoringPoll", () => { + it("keeps re-reading past a minute, and stops once the mark moves", () => { + const revalidate = vi.fn(); + const { result, rerender } = renderHook(({ mark }) => useAuthoringPoll(mark, revalidate), { + initialProps: { mark: "v1" }, + }); + act(() => result.current()); + act(() => vi.advanceTimersByTime(60_000)); + expect(revalidate).toHaveBeenCalledTimes(12); + rerender({ mark: "v2" }); + act(() => vi.advanceTimersByTime(60_000)); + expect(revalidate).toHaveBeenCalledTimes(12); + }); + + it("gives up at the cap when the mark never moves", () => { + const revalidate = vi.fn(); + const { result } = renderHook(() => useAuthoringPoll("same", revalidate)); + act(() => result.current()); + act(() => vi.advanceTimersByTime(AUTHORING_CAP_MS + 10_000)); + const calls = revalidate.mock.calls.length; + act(() => vi.advanceTimersByTime(60_000)); + expect(revalidate).toHaveBeenCalledTimes(calls); + }); + + it("does nothing until started", () => { + const revalidate = vi.fn(); + renderHook(() => useAuthoringPoll("v1", revalidate)); + act(() => vi.advanceTimersByTime(60_000)); + expect(revalidate).not.toHaveBeenCalled(); + }); +}); + +describe("authoringMark", () => { + const row = (version: number, eval_status = "untested", eval_report: unknown = null) => ({ + version, + eval_status, + eval_report, + }); + + it("moves when the drafter mints a version or an eval run writes a verdict", () => { + const before = authoringMark({ head: row(1), newest: row(1) }); + expect(authoringMark({ head: row(1), newest: row(2), draftAhead: row(2) })).not.toBe(before); + expect(authoringMark({ head: row(1, "green", { passed: 1 }), newest: row(1) })).not.toBe( + before, + ); + expect(authoringMark({ head: row(1), newest: row(1) })).toBe(before); + }); +}); diff --git a/web/app/routes/bots/use-authoring-poll.ts b/web/app/routes/bots/use-authoring-poll.ts new file mode 100644 index 0000000..3778cf6 --- /dev/null +++ b/web/app/routes/bots/use-authoring-poll.ts @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// Start-then-poll for the authoring jobs (Draft for me, Test evals): both run on the worker and +// land back on the bot's rows, so the tab re-reads them every few seconds until the rows' mark +// (authoring-mark.ts) moves off what it was at the click, or the cap passes. ONE interval, cleared +// on unmount and restarted (not stacked) by a second click. +import { useEffect, useState } from "react"; +import { AUTHORING_CAP_MS } from "./authoring-mark"; + +const EVERY_MS = 5000; + +/** Returns `start`: call it once the job is accepted. */ +export function useAuthoringPoll(mark: string, revalidate: () => void): () => void { + const [waiting, setWaiting] = useState<{ mark: string; until: number } | null>(null); + useEffect(() => { + if (!waiting) return; + if (mark !== waiting.mark) { + setWaiting(null); // the job landed + return; + } + const timer = window.setInterval(() => { + if (Date.now() >= waiting.until) setWaiting(null); + else revalidate(); + }, EVERY_MS); + return () => window.clearInterval(timer); + }, [waiting, mark, revalidate]); + return () => setWaiting({ mark, until: Date.now() + AUTHORING_CAP_MS }); +} diff --git a/web/app/routes/inbox/inbox.dom.test.tsx b/web/app/routes/inbox/inbox.dom.test.tsx index 6caebe5..dfec257 100644 --- a/web/app/routes/inbox/inbox.dom.test.tsx +++ b/web/app/routes/inbox/inbox.dom.test.tsx @@ -40,6 +40,7 @@ const items = [ item("b"), item("c", { read: true }), item("q", { kind: "question", title: "Report asks: which quarter?", payload: {} }), + item("r", { kind: "project_removed", title: "Removed r", payload: {}, read: true }), ]; let post: ReturnType<typeof vi.spyOn>; @@ -114,6 +115,40 @@ describe("Inbox triage", () => { expect(screen.getByText("project page")).toBeDefined(); }); + it("Enter on a focused toolbar button is that button's, never the list's", async () => { + const user = userEvent.setup(); + const router = mount(); + (await screen.findByRole("button", { name: "Filter by kind" })).focus(); + await user.keyboard("{Enter}"); + expect(await screen.findByRole("menuitemradio", { name: "All notifications" })).toBeDefined(); + expect(router.state.location.pathname).toBe("/inbox"); + }); + + it("added to and removed from a project share one Projects filter", async () => { + const user = userEvent.setup(); + mount(); + await user.click(await screen.findByRole("button", { name: "Filter by kind" })); + const radios = await screen.findAllByRole("menuitemradio"); + expect(radios.map((r) => r.textContent).sort()).toEqual([ + "All notifications", + "Projects", + "Questions", + ]); + screen.getByRole("menuitemradio", { name: "Projects" }).focus(); + await user.keyboard("{Enter}"); + await waitFor(() => expect(rows()).toHaveLength(4)); + expect( + rows() + .map((r) => r.textContent) + .join(" "), + ).toContain("Removed r"); + expect( + rows() + .map((r) => r.textContent) + .join(" "), + ).not.toContain("which quarter"); + }); + it("a question knock wears its own kind in the detail pane", async () => { const user = userEvent.setup(); mount(); diff --git a/web/app/routes/inbox/keys.dom.test.ts b/web/app/routes/inbox/keys.dom.test.ts new file mode 100644 index 0000000..439a7a5 --- /dev/null +++ b/web/app/routes/inbox/keys.dom.test.ts @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// @vitest-environment happy-dom +import { afterEach, describe, expect, it } from "vitest"; +import { listOwnsKeys, ROW_ATTR } from "./keys"; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +function el(html: string): Element { + document.body.innerHTML = html; + return document.querySelector("[data-target]") ?? document.body; +} + +describe("listOwnsKeys", () => { + it("the page itself, and anything with no keys of its own, leaves them to the list", () => { + expect(listOwnsKeys(document.body)).toBe(true); + expect(listOwnsKeys(el("<main><p data-target>hi</p></main>"))).toBe(true); + expect(listOwnsKeys(null)).toBe(true); + }); + + it("a notification row leaves them to the list", () => { + expect(listOwnsKeys(el(`<button ${ROW_ATTR}><span data-target>row</span></button>`))).toBe( + true, + ); + }); + + it("a control with keys of its own keeps them", () => { + expect(listOwnsKeys(el('<input data-target aria-label="x" />'))).toBe(false); + expect(listOwnsKeys(el("<button data-target>Filter by kind</button>"))).toBe(false); + expect(listOwnsKeys(el('<div role="menuitemradio" data-target>All</div>'))).toBe(false); + expect(listOwnsKeys(el('<div role="separator" tabindex="0" data-target></div>'))).toBe(false); + expect(listOwnsKeys(el('<div contenteditable="true" data-target></div>'))).toBe(false); + }); +}); diff --git a/web/app/routes/inbox/keys.ts b/web/app/routes/inbox/keys.ts new file mode 100644 index 0000000..f58ac45 --- /dev/null +++ b/web/app/routes/inbox/keys.ts @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// Who owns a key press on the inbox. The list's keyboard (↑/↓ move the selection, Enter opens it) +// listens on the window, so it must stand aside whenever focus sits in a control with keys of its +// own: a text field, a toolbar button, an open menu, the pane's resize handle. It acts only on the +// page itself or on a notification row. + +/** Marks a notification row: focus on one still leaves the keys to the list. */ +export const ROW_ATTR = "data-inbox-row"; + +const OWN_KEYS = + 'input, textarea, select, button, a[href], [contenteditable=""], [contenteditable="true"], ' + + '[role="button"], [role="link"], [role^="menuitem"], [role="tab"], [role="separator"], ' + + '[tabindex]:not([tabindex="-1"])'; + +export function listOwnsKeys(target: EventTarget | null): boolean { + if (!(target instanceof Element)) return true; + if (target.closest(`[${ROW_ATTR}]`)) return true; + return target.closest(OWN_KEYS) === null; +} diff --git a/web/app/routes/inbox/route.tsx b/web/app/routes/inbox/route.tsx index c34ecb6..b39b3b6 100644 --- a/web/app/routes/inbox/route.tsx +++ b/web/app/routes/inbox/route.tsx @@ -76,6 +76,7 @@ import { routineTarget, } from "./target"; import type { Route } from "./+types/route"; +import { listOwnsKeys, ROW_ATTR } from "./keys"; // The list pane is a real pane: draggable width (the divider IS the slider), persisted, // double-click restores the default. The topbar's divider + icon cluster ride the same @@ -98,7 +99,8 @@ type Item = Awaited<ReturnType<typeof clientLoader>>["items"][number]; // The wire kinds, with the glyph and the human word for each. "All" and "Unread" are views, // not kinds - the chips mix both, the way Linear's inbox filters read. -const KIND_META: Record<string, { label: string; icon: typeof HelpCircle }> = { +// `filter` folds a kind under another kind's filter item, so the menu never shows two the same. +const KIND_META: Record<string, { label: string; icon: typeof HelpCircle; filter?: string }> = { task_completed: { label: "Delivered", icon: CheckCircle2 }, // Approval gates write this kind; the item points at its gate // and the task pane answers it in place. @@ -109,7 +111,7 @@ const KIND_META: Record<string, { label: string; icon: typeof HelpCircle }> = { budget: { label: "Budget", icon: CircleDollarSign }, project_shared: { label: "Projects", icon: FolderKanban }, // Removed from a Project: no open affordance - the room is not this person's any more. - project_removed: { label: "Projects", icon: FolderKanban }, + project_removed: { label: "Projects", icon: FolderKanban, filter: "project_shared" }, // Someone other than the owner asked a bot for work; Open lands on the bot's chat, where the // card's Start / Not now decide it. card_waiting: { label: "Bot requests", icon: Bot }, @@ -131,6 +133,11 @@ const SETTLED_META: Record<string, { label: string; icon: typeof HelpCircle }> = could_not: { label: "Couldn't do it", icon: CircleSlash }, }; +/** The filter item a kind sits under: its own, or the one its meta folds it into. */ +function filterOf(kind: string): string { + return KIND_META[kind]?.filter ?? kind; +} + function metaOf(item: Item) { const ending = (item.payload as { ending?: string } | null)?.ending; return (item.kind === "task_completed" && ending && SETTLED_META[ending]) || KIND_META[item.kind]; @@ -190,9 +197,12 @@ export default function InboxRoute({ loaderData }: Route.ComponentProps) { }; const unreadCount = items.filter((i) => !i.read).length; - const kindsPresent = useMemo(() => new Set(items.map((i) => i.kind)), [items]); + const kindsPresent = useMemo(() => new Set(items.map((i) => filterOf(i.kind))), [items]); const visible = useMemo( - () => items.filter((i) => (kind === "all" || i.kind === kind) && (!unreadOnly || !i.read)), + () => + items.filter( + (i) => (kind === "all" || filterOf(i.kind) === kind) && (!unreadOnly || !i.read), + ), [items, kind, unreadOnly], ); const selected = visible.find((i) => i.id === selectedId) ?? null; @@ -234,11 +244,8 @@ export default function InboxRoute({ loaderData }: Route.ComponentProps) { // `[]` would have stapled the first render's stale `visible`/`selected` onto the closure. const onKeyRef = useRef<(e: KeyboardEvent) => void>(() => {}); onKeyRef.current = (e: KeyboardEvent) => { - if (e.target instanceof HTMLElement) { - const tag = e.target.tagName; - if (tag === "INPUT" || tag === "TEXTAREA" || e.target.isContentEditable) return; - } if (e.key !== "ArrowDown" && e.key !== "ArrowUp" && e.key !== "Enter") return; + if (!listOwnsKeys(e.target)) return; const idx = visible.findIndex((i) => i.id === selectedId); if (e.key === "Enter") { if (selected) openTarget(selected); @@ -288,7 +295,7 @@ export default function InboxRoute({ loaderData }: Route.ComponentProps) { <MenuRadioGroup value={kind} onValueChange={setKind}> <MenuRadioItem value="all" label="All notifications" /> {Object.entries(KIND_META) - .filter(([k]) => kindsPresent.has(k)) + .filter(([k, meta]) => !meta.filter && kindsPresent.has(k)) .map(([k, meta]) => ( <MenuRadioItem key={k} @@ -372,6 +379,7 @@ export default function InboxRoute({ loaderData }: Route.ComponentProps) { return ( <li key={item.id}> <button + {...{ [ROW_ATTR]: "" }} onClick={() => select(item)} onDoubleClick={() => openTarget(item)} aria-current={selectedId === item.id} diff --git a/web/app/routes/projects.$id/route.dom.test.tsx b/web/app/routes/projects.$id/route.dom.test.tsx index 37463d5..a17f990 100644 --- a/web/app/routes/projects.$id/route.dom.test.tsx +++ b/web/app/routes/projects.$id/route.dom.test.tsx @@ -169,6 +169,21 @@ describe("Settings", () => { expect(patchBody()).toMatchObject({ clear_budget: true }); }); + it("saving the name keeps a budget edit not saved yet", async () => { + const user = userEvent.setup(); + mount({ tab: "settings", proj: project({ budget_usd: "10" }) }); + const budget = await screen.findByRole("textbox", { name: "Budget in USD" }); + await user.clear(budget); + await user.type(budget, "40"); + const name = screen.getByRole("textbox", { name: "Project name" }); + await user.clear(name); + await user.type(name, "Atlas 2{Enter}"); + await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); + expect(patchBody()).not.toHaveProperty("budget_usd"); + await waitFor(() => expect((name as HTMLInputElement).value).toBe("Atlas 2")); + expect((budget as HTMLInputElement).value).toBe("40"); + }); + it("shows the month's spend against the ceiling", async () => { mount({ tab: "settings", proj: project({ budget_usd: "10" }) }); expect(await screen.findByText(/this month/)).toBeTruthy(); diff --git a/web/app/routes/projects.$id/route.tsx b/web/app/routes/projects.$id/route.tsx index e0e5f75..f9405dd 100644 --- a/web/app/routes/projects.$id/route.tsx +++ b/web/app/routes/projects.$id/route.tsx @@ -572,9 +572,9 @@ function SettingsTab({ }, }), ); - // Echo the canonical values back ("25" saved as "25.0000" must not stay dirty). - setName(updated.name); - setBudget(updated.budget_usd ?? ""); + // Echo only what was SENT, canonical ("25" -> "25.0000"): the other field keeps its edit. + if (body.name !== undefined) setName(updated.name); + if (body.budget_usd !== undefined || body.clear_budget) setBudget(updated.budget_usd ?? ""); revalidator.revalidate(); toast.success("Saved."); } catch (e) { diff --git a/web/app/routes/routines/fire-note.test.ts b/web/app/routes/routines/fire-note.test.ts new file mode 100644 index 0000000..03a3ae5 --- /dev/null +++ b/web/app/routes/routines/fire-note.test.ts @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +import { describe, expect, it } from "vitest"; +import { fireNote } from "./fire-note"; + +describe("fireNote", () => { + it("a mint fired", () => { + expect(fireNote({ decision: "minted", detail: "" })).toEqual({ + tone: "success", + text: "Fired - the run shows below.", + }); + }); + + it("a hold made a task that waits for its release", () => { + expect(fireNote({ decision: "held", detail: "" }).tone).toBe("success"); + }); + + it("a stand-down says nothing fired, and why", () => { + expect(fireNote({ decision: "skipped_season", detail: "max_runs reached" })).toEqual({ + tone: "info", + text: "Not fired (skipped season) - the run shows below.", + }); + expect(fireNote({ decision: "superseded", detail: "" }).text).toMatch(/^Not fired/); + }); + + it("an error names its detail", () => { + expect(fireNote({ decision: "error", detail: "no budget" })).toEqual({ + tone: "error", + text: "The fire failed: no budget", + }); + }); +}); diff --git a/web/app/routes/routines/fire-note.ts b/web/app/routes/routines/fire-note.ts new file mode 100644 index 0000000..320a213 --- /dev/null +++ b/web/app/routes/routines/fire-note.ts @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2026-present Plane Software, Inc. and contributors + * SPDX-License-Identifier: AGPL-3.0-only + * See the LICENSE file for details. + */ + +// What Run now says once the server has decided the fire. The fire door answers 202 whatever it +// decided (a refused fire is a result wearing its journaled reason), so the words come from the +// decision, never from the status: only a mint or a hold made a task. + +import type { components } from "~/lib/api/types.gen"; +import { decisionLabel } from "./streaks"; + +type FireOut = components["schemas"]["FireOut"]; + +export type FireNote = { tone: "success" | "info" | "error"; text: string }; + +export function fireNote(out: Pick<FireOut, "decision" | "detail">): FireNote { + if (out.decision === "minted") return { tone: "success", text: "Fired - the run shows below." }; + if (out.decision === "held") + return { tone: "success", text: "Fired - the task waits below until you release it." }; + if (out.decision === "error") + return { + tone: "error", + text: out.detail ? `The fire failed: ${out.detail}` : "The fire failed.", + }; + return { + tone: "info", + text: `Not fired (${decisionLabel(out.decision)}) - the run shows below.`, + }; +} diff --git a/web/app/routes/routines/route.dom.test.tsx b/web/app/routes/routines/route.dom.test.tsx index a8f9be6..436de5a 100644 --- a/web/app/routes/routines/route.dom.test.tsx +++ b/web/app/routes/routines/route.dom.test.tsx @@ -67,6 +67,14 @@ const run = (id: string, decision: string, over: Record<string, unknown> = {}) = const ok = (data: unknown) => Promise.resolve({ data, error: undefined, response: new Response(null, { status: 200 }) }); +/** The fire door's 202: what the gate decided, and the task when it made one. */ +const fired = (decision: string) => ({ + run_id: "run1", + decision, + task_id: decision === "minted" ? "t1" : null, + detail: "", +}); + let detail: Row; let runs: unknown[]; let get: ReturnType<typeof vi.spyOn>; @@ -194,6 +202,7 @@ describe("Routine peek verbs", () => { it("Run now fires, toasts and reloads the ledger", async () => { const user = userEvent.setup(); const success = vi.spyOn(toast, "success"); + post.mockImplementation((() => ok(fired("minted"))) as never); mount([row("a")], "/routines?routine=a"); await user.click(await screen.findByRole("button", { name: "Run now" })); await waitFor(() => expect(posted("/v1/routines/{routine_id}/fire")).toHaveLength(1)); @@ -206,6 +215,18 @@ describe("Routine peek verbs", () => { }); }); + it("Run now on a fire the gate stood down says nothing fired", async () => { + const user = userEvent.setup(); + const success = vi.spyOn(toast, "success"); + const info = vi.spyOn(toast, "info"); + post.mockImplementation((() => ok(fired("skipped_season"))) as never); + mount([row("a")], "/routines?routine=a"); + await user.click(await screen.findByRole("button", { name: "Run now" })); + await waitFor(() => + expect(info).toHaveBeenCalledWith("Not fired (skipped season) - the run shows below."), + ); + expect(success).not.toHaveBeenCalled(); + }); it("Pause sends an empty body; a paused routine offers Resume and shows its note", async () => { const user = userEvent.setup(); mount([row("a")], "/routines?routine=a"); diff --git a/web/app/routes/routines/route.tsx b/web/app/routes/routines/route.tsx index c136ead..a8293ed 100644 --- a/web/app/routes/routines/route.tsx +++ b/web/app/routes/routines/route.tsx @@ -45,6 +45,7 @@ import { useKeysetList } from "~/lib/paging"; import type { components } from "~/lib/api/types.gen"; import type { Route } from "./+types/route"; import { collapseRuns, decisionLabel, type RunRow } from "./streaks"; +import { fireNote } from "./fire-note"; import { NewRoutine } from "./new-routine"; type RoutineRow = components["schemas"]["RoutineOut"]; @@ -261,11 +262,13 @@ function RoutinePeek({ if (detail === null) return <LoadingState label="Opening the routine…" />; const r = detail; - const act = async (fn: () => Promise<unknown>, done: string) => { + /** Call a door, then say so: a fixed line, or one read off what the door answered. */ + const act = async <T,>(fn: () => Promise<T>, done: string | ((answer: T) => void)) => { setBusy(true); try { - await fn(); - toast.success(done); + const answer = await fn(); + if (typeof done === "string") toast.success(done); + else done(answer); reload(); onChanged?.(); } catch (e) { @@ -294,7 +297,12 @@ function RoutinePeek({ onClick={() => act( () => unwrap(api.POST("/v1/routines/{routine_id}/fire", path)), - "Fired - the run shows below.", + (fired) => { + const note = fireNote(fired); + ({ success: toast.success, info: toast.info, error: toast.error })[note.tone]( + note.text, + ); + }, ).then(() => setRunsBump((b) => b + 1)) } /> diff --git a/web/app/routes/signup/route.dom.test.tsx b/web/app/routes/signup/route.dom.test.tsx index 310f8dd..a6f9937 100644 --- a/web/app/routes/signup/route.dom.test.tsx +++ b/web/app/routes/signup/route.dom.test.tsx @@ -134,8 +134,24 @@ describe("signups paused", () => { await user.click(screen.getByRole("button", { name: "Create account" })); expect(await screen.findByRole("heading", { name: "Signups are paused" })).toBeTruthy(); }); + + it("a refused address gets the form's own sentence, never the server's vague one", async () => { + vi.spyOn(api, "POST").mockImplementation((() => + failure(403, "forbidden", "that email cannot be registered")) as never); + const user = userEvent.setup(); + mount(); + await user.type(await screen.findByLabelText(/^Name/), "Ada"); + await user.type(screen.getByLabelText(/^Email/), "ada@example.com"); + await user.type(screen.getByLabelText(/^Password/), "a-long-enough-password"); + await user.click(screen.getByRole("button", { name: "Create account" })); + expect(await screen.findByText(EMAIL_REFUSED)).toBeTruthy(); + expect(screen.queryByText("that email cannot be registered")).toBeNull(); + }); }); +const EMAIL_REFUSED = + "That email can't be used to sign up. If it already has an account, sign in instead."; + describe("the consent line", () => { it("links Terms and Privacy Policy to the configured URLs", async () => { state.config = { diff --git a/web/app/routes/signup/route.tsx b/web/app/routes/signup/route.tsx index 85c054a..58bec23 100644 --- a/web/app/routes/signup/route.tsx +++ b/web/app/routes/signup/route.tsx @@ -45,8 +45,10 @@ type ActionResult = { paused?: boolean; }; -/** What a refused signup shows: field errors, the paused page, or a message. */ -function refusal(e: ApiError) { +/** What a refused signup shows: field errors, the paused page, or a message. Any other 403 is the + * server's deliberately vague refusal of the address (it never says whether an account exists), + * or, with an invite, of an address the invite was not sent to: the form says so in its own words. */ +function refusal(e: ApiError, invited: boolean) { if (e.status === 422 && e.fields) { return data<ActionResult>({ fieldErrors: e.fields, formError: null }, { status: 422 }); } @@ -54,11 +56,15 @@ function refusal(e: ApiError) { return data<ActionResult>({ fieldErrors: {}, formError: null, paused: true }, { status: 403 }); } const formError = - e.status === 409 - ? "An account with that email already exists." - : e.status === 429 - ? `Too many attempts. Try again in ${e.retryAfter ?? 30}s.` - : e.message; + e.status === 403 + ? invited + ? "That email can't use this invite. Use the address it was sent to, or sign in if that email already has an account." + : "That email can't be used to sign up. If it already has an account, sign in instead." + : e.status === 409 + ? "An account with that email already exists." + : e.status === 429 + ? `Too many attempts. Try again in ${e.retryAfter ?? 30}s.` + : e.message; return data<ActionResult>({ fieldErrors: {}, formError }, { status: e.status }); } @@ -91,7 +97,7 @@ export async function clientAction({ request }: Route.ClientActionArgs) { throw redirect(next); } catch (e) { if (e instanceof Response) throw e; - if (e instanceof ApiError) return refusal(e); + if (e instanceof ApiError) return refusal(e, Boolean(invite)); return data<ActionResult>( { fieldErrors: {}, formError: "Something went wrong. Please try again." }, { status: 500 }, diff --git a/web/app/routes/tasks.$id/reader-pane.tsx b/web/app/routes/tasks.$id/reader-pane.tsx index 4118807..7d28808 100644 --- a/web/app/routes/tasks.$id/reader-pane.tsx +++ b/web/app/routes/tasks.$id/reader-pane.tsx @@ -257,6 +257,7 @@ export function ReaderPane({ onDownloadInfo={setDownload} onArtifactChanged={onArtifactChanged} readOnly={readOnly} + verdict={verdict} /> </div> </section> diff --git a/web/app/routes/tasks.$id/task-menu.test.ts b/web/app/routes/tasks.$id/task-menu.test.ts index d9b044d..b57a378 100644 --- a/web/app/routes/tasks.$id/task-menu.test.ts +++ b/web/app/routes/tasks.$id/task-menu.test.ts @@ -8,12 +8,16 @@ // detail read says what the caller may do (`can_edit`, `can_curate`, `is_creator`) and the // menu believes it - a viewer never meets a Pause that answers 403. import { describe, expect, it } from "vitest"; +import type { TaskStatus } from "~/lib/api/events"; import { menuVerbs } from "./task-menu"; describe("menuVerbs", () => { it("the creator of a task in their own Project: everything", () => { - expect(menuVerbs({ live: true, canEdit: true, canCurate: true, isCreator: true })).toEqual({ + expect( + menuVerbs({ status: "running", canEdit: true, canCurate: true, isCreator: true }), + ).toEqual({ control: true, + toggle: "pause", fork: true, rename: true, archive: true, @@ -22,14 +26,15 @@ describe("menuVerbs", () => { }); it("the Project owner tidies (archive, delete) but did not name the work (no rename)", () => { - const v = menuVerbs({ live: false, canEdit: true, canCurate: true, isCreator: false }); + const v = menuVerbs({ status: "delivered", canEdit: true, canCurate: true, isCreator: false }); expect(v).toMatchObject({ rename: false, archive: true, delete: true, fork: true }); }); it("an editor writes into the Project, and curates nothing of anyone else's", () => { - const v = menuVerbs({ live: true, canEdit: true, canCurate: false, isCreator: false }); + const v = menuVerbs({ status: "running", canEdit: true, canCurate: false, isCreator: false }); expect(v).toEqual({ control: true, + toggle: "pause", fork: true, rename: false, archive: false, @@ -38,9 +43,10 @@ describe("menuVerbs", () => { }); it("a viewer is offered nothing that writes", () => { - const v = menuVerbs({ live: true, canEdit: false, canCurate: false, isCreator: false }); + const v = menuVerbs({ status: "running", canEdit: false, canCurate: false, isCreator: false }); expect(v).toEqual({ control: false, + toggle: null, fork: false, rename: false, archive: false, @@ -50,7 +56,17 @@ describe("menuVerbs", () => { it("pause, resume and cancel are for a live task only", () => { expect( - menuVerbs({ live: false, canEdit: true, canCurate: true, isCreator: true }).control, - ).toBe(false); + menuVerbs({ status: "delivered", canEdit: true, canCurate: true, isCreator: true }), + ).toMatchObject({ control: false, toggle: null }); + }); + + it("pause stops only a running or waiting task, and resume only a paused one", () => { + const at = (status: TaskStatus) => + menuVerbs({ status, canEdit: true, canCurate: true, isCreator: true }); + expect(at("waiting")).toMatchObject({ control: true, toggle: "pause" }); + expect(at("paused")).toMatchObject({ control: true, toggle: "resume" }); + // A held task (created, not started) and one still planning can be cancelled, never paused. + expect(at("created")).toMatchObject({ control: true, toggle: null }); + expect(at("planning")).toMatchObject({ control: true, toggle: null }); }); }); diff --git a/web/app/routes/tasks.$id/task-menu.tsx b/web/app/routes/tasks.$id/task-menu.tsx index 1266e1a..d368802 100644 --- a/web/app/routes/tasks.$id/task-menu.tsx +++ b/web/app/routes/tasks.$id/task-menu.tsx @@ -71,11 +71,22 @@ export type TaskAccess = { }; /** Which verbs the ⋯ menu offers - only the ones the server would accept for THIS person, so a - * viewer never meets a Pause that answers 403. Pause/resume/cancel are also a live-task-only - * affair; the fork is offered whenever the caller may write. */ -export function menuVerbs(a: TaskAccess & { live: boolean }) { + * viewer never meets a Pause that answers 403. Cancel is for any live task; pause only stops a + * running or waiting one (a held or planning task answers 422) and resume only a paused one; the + * fork is offered whenever the caller may write. */ +export function menuVerbs(a: TaskAccess & { status: TaskStatus }) { + const control = !TERMINAL.has(a.status) && a.canEdit; + const stoppable = a.status === "running" || a.status === "waiting"; return { - control: a.live && a.canEdit, + control, + /** The one of pause and resume the server would take now, if either. */ + toggle: !control + ? null + : stoppable + ? ("pause" as const) + : a.status === "paused" + ? ("resume" as const) + : null, fork: a.canEdit, rename: a.isCreator, archive: a.canCurate, @@ -83,6 +94,11 @@ export function menuVerbs(a: TaskAccess & { live: boolean }) { }; } +const TOGGLE = { + pause: { icon: Pause, label: "Pause" }, + resume: { icon: Play, label: "Resume" }, +} as const; + export function TaskMenu({ onFork, taskId, @@ -111,7 +127,8 @@ export function TaskMenu({ const [renaming, setRenaming] = useState(false); const [deleting, setDeleting] = useState(false); const live = !TERMINAL.has(status); - const verbs = menuVerbs({ ...access, live }); + const verbs = menuVerbs({ ...access, status }); + const toggle = verbs.toggle; async function toggleArchive() { try { @@ -152,17 +169,11 @@ export function TaskMenu({ <MenuContent align="end"> {verbs.control && onControl && ( <> - {status === "paused" ? ( - <MenuItem - icon={<Icon icon={Play} />} - label="Resume" - onClick={() => onControl("resume")} - /> - ) : ( + {toggle && ( <MenuItem - icon={<Icon icon={Pause} />} - label="Pause" - onClick={() => onControl("pause")} + icon={<Icon icon={TOGGLE[toggle].icon} />} + label={TOGGLE[toggle].label} + onClick={() => onControl(toggle)} /> )} <MenuItem diff --git a/web/e2e/admin/bots-routines.spec.ts b/web/e2e/admin/bots-routines.spec.ts index 726b265..b3ea173 100644 --- a/web/e2e/admin/bots-routines.spec.ts +++ b/web/e2e/admin/bots-routines.spec.ts @@ -7,7 +7,7 @@ import type { Page } from "@playwright/test"; import { signUp } from "../support/accounts"; import { call, createBot, createHeldRoutine, stamp } from "../support/api"; -import { escapeRegExp, expect, knownBug, test, toast } from "../fixtures"; +import { escapeRegExp, expect, test, toast } from "../fixtures"; // Bots and routines across the system. A bot is observed read-only, and reading its instructions is // itself an audited act. A routine has one operator verb, pause, which needs a reason and tells the @@ -156,26 +156,20 @@ test.describe("console routines", () => { }); test("the pause confirm waits for a reason the server accepts", async ({ adminPage: page }) => { - knownBug( - "web/app/components/admin/confirm.tsx:149 enables the confirm after one character, but " + - "backend/prismoid/api/serializers/admin_routines.py:40 requires a pause reason of at least " + - "3, so a short reason is sent and refused as 'the request body is not valid'", - ); const { name } = await routineOnList(page, "link"); const dialog = await openPause(page, name); - await dialog.getByRole("textbox", { name: "Reason" }).fill("ok"); - // Either fix is right: the dialog holds a reason this short back, or the server takes it. + // The door takes a reason of three characters or more: a shorter one is held back here. + const reason = dialog.getByRole("textbox", { name: "Reason" }); const confirm = dialog.getByRole("button", { name: "Pause routine" }); - if (await confirm.isDisabled()) return; + await expect(dialog.getByText("At least 3 characters.")).toBeVisible(); + await reason.fill("ok"); + await expect(confirm).toBeDisabled(); + await reason.fill("ok!"); await confirm.click(); await expect(toast(page, "Paused. Audited, and the owner has the note.")).toBeVisible(); }); test("a paused routine shows as paused without a reload", async ({ adminPage: page }) => { - knownBug( - "web/app/routes/admin/routines/route.tsx:47 pauses without refreshing the list (the " + - "ResourceList has no refreshMs), so the row still says active and offers Pause until a reload", - ); const { name, row } = await routineOnList(page, "link"); const dialog = await openPause(page, name); await dialog.getByRole("textbox", { name: "Reason" }).fill("Paused while the owner is away"); diff --git a/web/e2e/allowed-sites.spec.ts b/web/e2e/allowed-sites.spec.ts index 8dcd457..b2e2e3a 100644 --- a/web/e2e/allowed-sites.spec.ts +++ b/web/e2e/allowed-sites.spec.ts @@ -4,7 +4,7 @@ * See the LICENSE file for details. */ -import { expect, knownBug, test } from "./fixtures"; +import { expect, test } from "./fixtures"; // Allowed sites: the hosts the computer's browser opens without asking. A fresh account starts // with none, and every change is the server's (a reload reads it back). @@ -50,10 +50,6 @@ test.describe("allowed sites", () => { }); test("adding a host that is already allowed lists it once", async ({ accountPage: page }) => { - knownBug( - "allowed-sites/route.tsx prepends the row the API returns even when the host was already " + - "allowed (the API answers with the existing row), so the host shows twice until a reload", - ); await page.goto("/allowed-sites"); const host = page.getByRole("textbox", { name: "Host" }); for (let i = 0; i < 2; i++) { diff --git a/web/e2e/bots-configure.spec.ts b/web/e2e/bots-configure.spec.ts index f5a555c..8c3da62 100644 --- a/web/e2e/bots-configure.spec.ts +++ b/web/e2e/bots-configure.spec.ts @@ -4,7 +4,7 @@ * See the LICENSE file for details. */ -import { expect, knownBug, test, toast } from "./fixtures"; +import { expect, test, toast } from "./fixtures"; import { createBot, stamp } from "./support/api"; // Bots: the messenger's list and the Configure tab. Every bot here is a draft with written @@ -234,11 +234,6 @@ test.describe("bots: create and configure", () => { accountPage: page, account, }) => { - knownBug( - "web/app/routes/bots/route.tsx:150 - the open bot is looked up in the search-filtered rows, " + - "so a search that excludes it swaps the pane for 'Pick a bot' and clearing the search " + - "remounts the pane, discarding unsaved Configure edits", - ); const tag = stamp(); const { name } = await createBot(account.token, { name: `open-${tag}` }); await createBot(account.token, { name: `other-${tag}` }); diff --git a/web/e2e/bots-tabs.spec.ts b/web/e2e/bots-tabs.spec.ts index f7cb607..badb2f8 100644 --- a/web/e2e/bots-tabs.spec.ts +++ b/web/e2e/bots-tabs.spec.ts @@ -4,7 +4,7 @@ * See the LICENSE file for details. */ -import { expect, knownBug, test, toast } from "./fixtures"; +import { expect, test, toast } from "./fixtures"; import { ApiError, call, createBot, stamp } from "./support/api"; // A bot's tabs, everything that needs no model: the empty shelves, memory, the webhook door and @@ -103,12 +103,6 @@ test.describe("bots: tabs", () => { }); test("edits a memory in place", async ({ accountPage: page, account }) => { - knownBug( - "backend/prismoid/db/models/memory.py:245 - updated_at's onupdate=func.now() leaves the " + - "attribute expired after the commit, so memory_out (api/serializers/memories.py:83) " + - "lazy-loads it outside the greenlet: PATCH /v1/memories/{id} saves, then answers 500 " + - "(MissingGreenlet) and the row stays in edit mode with 'Couldn't save the memory.'", - ); const { name } = await createBot(account.token, { name: `memoedit-${stamp()}` }); await teach(account.token, name, "The Q3 workbook lives in finance."); await page.goto(`/bots/${name}?tab=memory`); @@ -129,11 +123,6 @@ test.describe("bots: tabs", () => { }); test("retires a memory", async ({ accountPage: page, account }) => { - knownBug( - "backend/prismoid/db/models/memory.py:245 - the same expired updated_at: POST " + - "/v1/memories/{id}/retire retires the row, then answers 500 (MissingGreenlet in " + - "memory_out), so the row stays listed with 'Couldn't retire the memory.' until a reload", - ); const { name } = await createBot(account.token, { name: `memoretire-${stamp()}` }); await teach(account.token, name, "Invoices go out on the first."); await page.goto(`/bots/${name}?tab=memory`); @@ -197,10 +186,6 @@ test.describe("bots: tabs", () => { accountPage: page, account, }) => { - knownBug( - "web/app/routes/bots/channels-tab.tsx:84 - remove() reloads the rows but never clears " + - "`minted`, so 'Token, shown once' keeps showing the removed channel's dead token", - ); const { name } = await createBot(account.token, { name: `deadtoken-${stamp()}` }); await page.goto(`/bots/${name}?tab=channels`); const main = page.getByRole("main"); diff --git a/web/e2e/home.spec.ts b/web/e2e/home.spec.ts index cb0b9dc..f3a5c9c 100644 --- a/web/e2e/home.spec.ts +++ b/web/e2e/home.spec.ts @@ -5,7 +5,7 @@ */ import type { Page } from "@playwright/test"; -import { chooseOption, composer, escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { chooseOption, composer, escapeRegExp, expect, test, toast } from "./fixtures"; import { call, createBot, createHeldTask, stamp } from "./support/api"; // The home composer. Sending with When set to Now starts a task that calls a model, so these flows @@ -291,10 +291,6 @@ test.describe("a scheduled ask saves a routine", () => { }); test("a refused fleet schedule keeps the typed goal", async ({ accountPage: page }) => { - knownBug( - "web/app/components/composer/task-composer.tsx:232-235 - the fleet refusal returns instead " + - "of throwing, so composer.tsx:270-272 treats the save as sent and clears the typed goal", - ); const goal = "Compare three vendors"; await page.goto("/"); await submitRefused(page, goal, "fleet"); @@ -305,10 +301,6 @@ test.describe("a scheduled ask saves a routine", () => { test("a refused attachment schedule keeps the goal and the file", async ({ accountPage: page, }) => { - knownBug( - "web/app/components/composer/task-composer.tsx:237-240 - the attachments refusal returns " + - "instead of throwing, so composer.tsx:270-273 clears the typed goal and the attached file", - ); const goal = "Read the attached notes"; await page.goto("/"); await submitRefused(page, goal, "attachment"); diff --git a/web/e2e/inbox.spec.ts b/web/e2e/inbox.spec.ts index 2e7b619..c3a7693 100644 --- a/web/e2e/inbox.spec.ts +++ b/web/e2e/inbox.spec.ts @@ -8,7 +8,7 @@ import type { Page } from "@playwright/test"; import { joinWorkspace, signUp, verifyEmail } from "./support/accounts"; import { call, createHeldTask, createProject, type HeldTask, stamp } from "./support/api"; import { mailAvailable } from "./support/mailbox"; -import { expect, knownBug, test } from "./fixtures"; +import { expect, test } from "./fixtures"; // The inbox: notifications on the left, what each is about on the right. A held routine run is // the knock a flow can make without a model: firing a held routine mints a task and tells its @@ -142,10 +142,6 @@ test("Enter on a focused toolbar button works that button, not the selected item accountPage: page, account, }) => { - knownBug( - "web/app/routes/inbox/route.tsx:236-246 - the window keydown handler skips only inputs, then opens the selected item " + - "on Enter whatever has focus, so Enter on Filter by kind (or Mark all read) also navigates away", - ); await createHeldTask(account.token, `Hold the pier survey ${stamp()}`); await page.goto("/inbox"); await expect(page.getByRole("button", { name: "Open task" })).toBeVisible(); @@ -217,11 +213,6 @@ test.describe("project knocks", () => { accountPage: page, account, }) => { - knownBug( - "web/app/routes/inbox/route.tsx:110-112 + 290-299 - project_shared and project_removed each " + - "get their own 'Projects' filter item, so the menu shows two identical items and either one " + - "hides the other kind's notification (merging them or naming them apart both fix it)", - ); const host = await signUp("e2e-inbox", { name: "Bea Host" }); await verifyEmail(host); await joinWorkspace(host, account); diff --git a/web/e2e/models/bots.spec.ts b/web/e2e/models/bots.spec.ts index 7cd33a0..50fdd2f 100644 --- a/web/e2e/models/bots.spec.ts +++ b/web/e2e/models/bots.spec.ts @@ -132,24 +132,11 @@ test.describe("a bot on a real model", () => { toast(page, "Writing a fuller draft - it lands here in a moment.").first(), ).toBeVisible(); - // The draft lands as the next version. The tab re-reads the bot for 40 s only, and the drafter - // takes 20 to 40 s or more, so the flow waits on the server's v2 and then reloads. - test.info().annotations.push({ - type: "bug", - description: - "web/app/routes/bots/configure-tab.tsx:76 polls for 40 s after Draft for me (and Test " + - "evals); a draft that lands later never shows until a reload, though the toast says it " + - "lands here in a moment", + // The draft lands as the next version, and the tab re-reads the bot until it does, however + // long the drafter takes: no reload. + await expect(main.getByRole("listitem").filter({ hasText: /^v2\s*draft/ })).toBeVisible({ + timeout: RUN_TIMEOUT, }); - await expect - .poll( - async () => - (await call<{ version: number }>(`/bots/${name}`, { token: account.token })).version, - { timeout: RUN_TIMEOUT, intervals: [2_000] }, - ) - .toBe(2); - await page.reload(); - await expect(main.getByRole("listitem").filter({ hasText: /^v2\s*draft/ })).toBeVisible(); await expect(main.getByRole("textbox", { name: "Bot instructions" })).not.toHaveValue(""); }); }); diff --git a/web/e2e/models/tasks.spec.ts b/web/e2e/models/tasks.spec.ts index 3accd62..7994b9c 100644 --- a/web/e2e/models/tasks.spec.ts +++ b/web/e2e/models/tasks.spec.ts @@ -5,7 +5,7 @@ */ import type { Page } from "@playwright/test"; -import { chooseOption, composer, escapeRegExp, expect, knownBug, test } from "../fixtures"; +import { chooseOption, composer, escapeRegExp, expect, test } from "../fixtures"; import { call } from "../support/api"; import { answerQuestions, @@ -161,11 +161,6 @@ test.describe("a task on a real model", () => { test("the open reader shows the receipt once the check finishes", async ({ accountPage: page, }) => { - knownBug( - "web/app/components/artifact/artifact-view.tsx:127-167 fetches the verification once, when " + - "the reader opens (its effect depends on currentId only); the reader opens at publish, " + - "before the check signs, so it keeps 'Not verified yet' after the thread shows the receipt", - ); await page.goto("/"); await chooseOption(page, "Deliverable", "Document · Markdown"); await composer(page).fill("Write two sentences on what a neap tide is."); diff --git a/web/e2e/project-settings.spec.ts b/web/e2e/project-settings.spec.ts index 074e4d1..55974c5 100644 --- a/web/e2e/project-settings.spec.ts +++ b/web/e2e/project-settings.spec.ts @@ -8,7 +8,7 @@ import type { Page } from "@playwright/test"; import { joinWorkspace, pageFor, signUp, verifyEmail } from "./support/accounts"; import { createProject, stamp } from "./support/api"; import { mailAvailable } from "./support/mailbox"; -import { expect, knownBug, section, test, toast } from "./fixtures"; +import { expect, section, test, toast } from "./fixtures"; // A project's Settings tab, as its owner sees it. Each setting saves on its own Save, which // appears only while that field differs from the server, so several can be on screen at once. @@ -123,10 +123,6 @@ test("adds a project memory that says who wrote it", async ({ accountPage: page, }); test("each Save keeps the other fields' unsaved edits", async ({ accountPage: page, account }) => { - knownBug( - "web/app/routes/projects.$id/route.tsx:576-577 - SettingsTab.save() echoes BOTH name and " + - "budget from the server after any save, so saving the name throws away an unsaved budget edit", - ); const project = await createProject(account.token, `Two edits ${stamp()}`); await openSettings(page, project.id); const nameRow = rowOf(page, "Project name"); diff --git a/web/e2e/routines.spec.ts b/web/e2e/routines.spec.ts index 405be12..0d256cc 100644 --- a/web/e2e/routines.spec.ts +++ b/web/e2e/routines.spec.ts @@ -6,7 +6,7 @@ import type { Page } from "@playwright/test"; import { call, createHeldRoutine, type Routine, stamp } from "./support/api"; -import { expect, knownBug, test, toast } from "./fixtures"; +import { expect, test, toast } from "./fixtures"; // Routines (ADR-048): standing work that mints an ordinary task on every fire. Nothing here may // start a run, so a routine is fired only when its posture is hold (an event routine made in the @@ -181,7 +181,7 @@ test("an event routine is held, and Run now mints a held run that opens in the s ).toBeVisible(); await runNow(page); - await expect(toast(page, "Fired - the run shows below.")).toBeVisible(); + await expect(toast(page, "Fired - the task waits below until you release it.")).toBeVisible(); const run = peek.getByRole("button", { name: /^held manual · / }); await expect(run).toHaveCount(1); @@ -238,10 +238,6 @@ test("Run now on a routine whose season is over says the fire was skipped", asyn accountPage: page, account, }) => { - knownBug( - "web/app/routes/routines/route.tsx:297 - Run now toasts 'Fired - the run shows below.' for " + - "every answer, even a skipped fire that minted nothing (here skipped_season, which retires it)", - ); // A held routine allowed one run, which it has already had: the next fire is skipped. const routine = await call<Routine>("/routines", { token: account.token, @@ -261,6 +257,7 @@ test("Run now on a routine whose season is over says the fire was skipped", asyn await runNow(page); // The answer lands first: the routine retires, so Run now goes away. await expect(peek.getByRole("button", { name: "Run now" })).toHaveCount(0); + await expect(toast(page, "Not fired (skipped season) - the run shows below.")).toBeVisible(); // A toast that has already shown cannot be waited away, so this reads it once, no retry. expect(await toast(page, "Fired - the run shows below.").count()).toBe(0); }); diff --git a/web/e2e/settings.spec.ts b/web/e2e/settings.spec.ts index 6999107..c90247f 100644 --- a/web/e2e/settings.spec.ts +++ b/web/e2e/settings.spec.ts @@ -6,7 +6,7 @@ import type { Locator } from "@playwright/test"; import { call, stamp } from "./support/api"; -import { accountMenu, expect, knownBug, openSettings, test, toast } from "./fixtures"; +import { accountMenu, expect, openSettings, test, toast } from "./fixtures"; test("edits the profile name in settings and keeps it", async ({ signedInPage: page, seed }) => { await page.goto("/"); @@ -110,11 +110,6 @@ test.describe("settings on a fresh account", () => { }); test("edits a memory in place", async ({ accountPage: page, account }) => { - knownBug( - "backend/prismoid/api/serializers/memories.py:83 reads updated_at after " + - "operations/memory.py:174 committed and expired it, so PATCH /v1/memories/{id} answers " + - "500 (MissingGreenlet) although the edit is saved; the row stays open in edit mode", - ); await call("/memories", { token: account.token, body: { scope: "user", kind: "preference", text: "Prefers tide tables in metric units." }, @@ -140,11 +135,6 @@ test.describe("settings on a fresh account", () => { }); test("retires a memory", async ({ accountPage: page, account }) => { - knownBug( - "backend/prismoid/api/serializers/memories.py:83 reads updated_at after " + - "operations/memory.py:186 committed and expired it, so POST /v1/memories/{id}/retire " + - "answers 500 (MissingGreenlet) although the memory is retired; the row stays listed", - ); await call("/memories", { token: account.token, body: { scope: "user", kind: "fact", text: "The field station is on the north shore." }, diff --git a/web/e2e/shell.spec.ts b/web/e2e/shell.spec.ts index 0ad68b9..372fb88 100644 --- a/web/e2e/shell.spec.ts +++ b/web/e2e/shell.spec.ts @@ -6,7 +6,7 @@ import type { Page } from "@playwright/test"; import { createHeldTask } from "./support/api"; -import { accountMenu, composer, escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { accountMenu, composer, escapeRegExp, expect, test, toast } from "./fixtures"; // The app shell: the sidebar's nav, its collapse, the global chords, the account menu and the // recent-task rows. Every flow runs on a fresh account, so its sidebar holds only what it made. @@ -136,11 +136,6 @@ test.describe("app shell", () => { accountPage: page, account, }) => { - knownBug( - "web/app/components/tasks/task-window.tsx:206 drops the row before the DELETE answers and " + - "never puts it back when the server refuses (409 for a task that is not settled), so the " + - "sidebar hides a task that still exists until the next navigation", - ); const task = await createHeldTask(account.token, "Summarize the tide pool field notes"); await page.goto("/allowed-sites"); await page.getByRole("button", { name: `Task actions for ${task.title}` }).click(); diff --git a/web/e2e/signup.spec.ts b/web/e2e/signup.spec.ts index 16d0de8..33343c7 100644 --- a/web/e2e/signup.spec.ts +++ b/web/e2e/signup.spec.ts @@ -7,7 +7,7 @@ import { PASSWORD } from "./support/accounts"; import { stamp } from "./support/api"; import { mailAvailable, waitForMail } from "./support/mailbox"; -import { accountMenu, composer, expect, knownBug, test } from "./fixtures"; +import { accountMenu, composer, expect, test } from "./fixtures"; // Signup from the form: the person gets an account, their own workspace and a session at once, and // the address is proved later by the emailed link. Every flow signs up an address of its own. @@ -49,11 +49,6 @@ test.describe("signup", () => { test("an address that already has an account is refused in words", async ({ page, account }) => { // The API refuses an existing address with a deliberately vague 403 (it never confirms which // addresses exist), so the form owes the person its own written sentence, not the server's. - knownBug( - "web/app/routes/signup/route.tsx:57 maps only a 409 to written copy, but the API refuses an " + - "existing address with a 403 (backend/prismoid/operations/auth.py:168), so the form shows " + - 'the raw lowercase "that email cannot be registered" and the 409 branch is dead code', - ); await page.goto("/signup"); await page.getByRole("textbox", { name: "Name" }).fill("Sam Signup"); await page.getByRole("textbox", { name: "Email" }).fill(account.email); @@ -64,6 +59,7 @@ test.describe("signup", () => { // The refusal keeps the person on the form, signed out, with a sentence of the form's own. await expect(page).toHaveURL(/\/signup$/); await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled(); + await expect(page.getByText(/^That email can't be used to sign up\. /)).toBeVisible(); await expect(page.getByText("that email cannot be registered", { exact: true })).toHaveCount(0); }); }); diff --git a/web/e2e/task-page.spec.ts b/web/e2e/task-page.spec.ts index 1de3509..64e4563 100644 --- a/web/e2e/task-page.spec.ts +++ b/web/e2e/task-page.spec.ts @@ -5,7 +5,7 @@ */ import type { Page } from "@playwright/test"; -import { escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { escapeRegExp, expect, test, toast } from "./fixtures"; import { ApiError, call, @@ -202,11 +202,6 @@ test.describe("task page", () => { accountPage: page, account, }) => { - knownBug( - "web/app/routes/tasks.$id/task-menu.tsx:78 - the menu offers Pause on any live task, but " + - "backend/prismoid/operations/steering.py:505 pauses only a running or waiting one, so a " + - "held task's Pause answers 422 'cannot pause a task that is created'", - ); const task = await createHeldTask(account.token, "Draft the quarterly plan"); await page.goto(`/tasks/${task.id}`); const menu = await taskMenu(page); diff --git a/web/e2e/tasks.spec.ts b/web/e2e/tasks.spec.ts index 36e8118..7d3660c 100644 --- a/web/e2e/tasks.spec.ts +++ b/web/e2e/tasks.spec.ts @@ -5,7 +5,7 @@ */ import type { Page } from "@playwright/test"; -import { escapeRegExp, expect, knownBug, test, toast } from "./fixtures"; +import { escapeRegExp, expect, test, toast } from "./fixtures"; import { ApiError, call, @@ -225,11 +225,6 @@ test.describe("task list", () => { accountPage: page, account, }) => { - knownBug( - "web/app/components/tasks/task-browser/browser.tsx:288 - the status counts effect leaves " + - "filters.archived (and refreshTick) out of its deps, so switching to Archived keeps the " + - "active totals in the group headers", - ); const tasks = []; for (const goal of ["Compare the vendors", "Price the hardware", "Book the venue"]) tasks.push(await createSettledTask(account.token, goal)); diff --git a/web/e2e/workspaces.spec.ts b/web/e2e/workspaces.spec.ts index 0f812db..a702f8a 100644 --- a/web/e2e/workspaces.spec.ts +++ b/web/e2e/workspaces.spec.ts @@ -8,7 +8,7 @@ import type { Page } from "@playwright/test"; import { joinWorkspace, pageFor, PASSWORD, signUp, verifyEmail } from "./support/accounts"; import { call, stamp } from "./support/api"; import { codeIn, mailAvailable, waitForMail } from "./support/mailbox"; -import { composer, expect, knownBug, openSettings, test, toast } from "./fixtures"; +import { composer, expect, openSettings, test, toast } from "./fixtures"; // Workspaces (ADR-061): the tenant. A person founds their own, switches between the ones they // belong to, and brings others in by an emailed invite. A switch or a join rebinds the session, so @@ -101,11 +101,6 @@ test.describe("workspaces", () => { accountPage: page, account, }) => { - knownBug( - "web/app/components/workspace/workspace-members.tsx:180 closes the invite dialog and " + - "clears the email whatever the answer: onInvite's run() swallows the refusal into a " + - "toast and resolves, so a refused invite looks sent and the typed address is lost", - ); const invitee = `e2e-workspaces-invitee-${stamp()}@example.com`; await page.goto("/"); const settings = await openMembers(page, account.email); From 1cfd728dd7807bca85f6794eebd9f731e8949014 Mon Sep 17 00:00:00 2001 From: Surya Prashanth <5310329+Prashant-Surya@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:28:08 +0530 Subject: [PATCH 3/5] fix(web): the reader re-reads a receipt per artifact, not once per pane The verdict the reader had already read was remembered without its artifact, and the pane does not remount ArtifactView when it opens another one. After one document signed `pass`, a second one (a follow-up's revised head, another deliverable) that also signed `pass` never re-read its receipt and kept "Not verified yet". The remembered verdict now belongs to an artifact id and resets when the pane moves on. DESIGN.md names the verdict hand-off. --- web/DESIGN.md | 3 ++- .../artifact/artifact-view.dom.test.tsx | 15 +++++++++++++++ web/app/components/artifact/artifact-view.tsx | 16 +++++++++++----- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/web/DESIGN.md b/web/DESIGN.md index a18c4b5..13cd034 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -401,7 +401,8 @@ viewport height, and each pane wears its own header on the same h-14 line: window (the close first, then Download). The download link rides ArtifactView's one fetch (`onDownloadInfo`, always the viewed version; `showDownload={false}` suppresses the in-row copy); the verdict rides the route's live shelf, so the badge flips the - moment the receipt frame lands. The pane renders ArtifactView with `chrome="bare"`: + moment the receipt frame lands, and the pane hands it to ArtifactView (`verdict`), whose + receipt re-reads on a new one instead of keeping "Not verified yet". The pane renders ArtifactView with `chrome="bare"`: no PageHeader block inside the content — the band IS the identity. **ONE vertical scroll — the page's/pane's, for every kind** (2026-08-07, twice): a diff --git a/web/app/components/artifact/artifact-view.dom.test.tsx b/web/app/components/artifact/artifact-view.dom.test.tsx index 1c70b86..6d58d39 100644 --- a/web/app/components/artifact/artifact-view.dom.test.tsx +++ b/web/app/components/artifact/artifact-view.dom.test.tsx @@ -174,6 +174,21 @@ describe("ArtifactView receipt and history", () => { await waitFor(() => expect(screen.queryByText(/Not verified yet/)).toBeNull()); }); + it("a second document's verdict re-reads its own receipt, whatever the first one said", async () => { + let get = serve(); + const { rerender } = render(<ArtifactView artifactId="a1" verdict="pass" />); + await screen.findByRole("heading", { name: "Quarterly notes" }); + expect(screen.queryByText(/Not verified yet/)).toBeNull(); + get.mockRestore(); + get = serve({ artifact: art({ id: "a2" }), verification: null }); + rerender(<ArtifactView artifactId="a2" />); + expect(await screen.findByText(/Not verified yet/)).toBeDefined(); + get.mockRestore(); + serve({ artifact: art({ id: "a2" }) }); + rerender(<ArtifactView artifactId="a2" verdict="pass" />); + await waitFor(() => expect(screen.queryByText(/Not verified yet/)).toBeNull()); + }); + it("viewing an older version refetches it, and the host is not told of a new head", async () => { const user = userEvent.setup(); const v2 = art({ id: "a2", revision: 2, sha256: "bbb" }); diff --git a/web/app/components/artifact/artifact-view.tsx b/web/app/components/artifact/artifact-view.tsx index 853c2e7..8f72fc7 100644 --- a/web/app/components/artifact/artifact-view.tsx +++ b/web/app/components/artifact/artifact-view.tsx @@ -169,12 +169,18 @@ export function ArtifactView({ }; }, [currentId]); - // The verdict the open read already reflects; only a new one re-reads the receipt, and only - // for the head (an older version's receipt is its own). - const verdictRead = useRef(verdict); + // The verdict the open read already reflects, per artifact (the view is not remounted when the + // host opens another): only a new one re-reads the receipt, and only for the head (an older + // version's receipt is its own). + const verdictRead = useRef({ id: artifactId, verdict }); useEffect(() => { - if (!verdict || verdict === verdictRead.current || currentId !== artifactId) return; - verdictRead.current = verdict; + const read = verdictRead.current; + if (read.id !== artifactId) { + verdictRead.current = { id: artifactId, verdict }; // another artifact: its open read is the base + return; + } + if (!verdict || verdict === read.verdict || currentId !== artifactId) return; + verdictRead.current = { id: artifactId, verdict }; let cancelled = false; unwrap( api.GET("/v1/artifacts/{artifact_id}/verification", { From 48e1b6d7dcdcc6550cfc6a7178da2ac602c68a2d Mon Sep 17 00:00:00 2001 From: Surya Prashanth <5310329+Prashant-Surya@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:30:20 +0530 Subject: [PATCH 4/5] docs(web): the admin list hands its rows a refresh --- web/app/components/admin/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/app/components/admin/README.md b/web/app/components/admin/README.md index 14c4bd6..cd9b5bd 100644 --- a/web/app/components/admin/README.md +++ b/web/app/components/admin/README.md @@ -44,7 +44,8 @@ the config states only what is resource-shaped: renders when filters exist. Ship exactly what the wire supports - never fake a dimension the API can't filter. - **Keyset paging** - `useKeysetList` wiring (`app/lib/paging.ts`), `LoadMore`, optional - head-refresh polling via `refreshMs`. + head-refresh polling via `refreshMs`, and the same re-read on demand: `row(item, { refresh })` + hands it to an inline verb whose door answers no row (the routine pause). - **States** - `LoadingState`, `EmptyState` (the search-miss variant names the query). - **Row chrome** - the `Rows` list, hover wash, and the link (`rowTo`) or action (`onRow`) wrapper; the config's `row` renders only the content between them. The config type is a From f7dbfe3c37f432810dcd2188d5a3d6f33f68b808 Mon Sep 17 00:00:00 2001 From: Surya Prashanth <5310329+Prashant-Surya@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:01:40 +0530 Subject: [PATCH 5/5] test(e2e): escape regex input with the one complete helper Two admin specs escaped a value for a RegExp by hand and skipped backslashes (CodeQL js/incomplete-sanitization). Every spec now uses fixtures.escapeRegExp, including two that inlined a full copy of it. --- web/e2e/admin/login.spec.ts | 6 ++---- web/e2e/admin/models-spend-audit.spec.ts | 4 ++-- web/e2e/admin/tasks.spec.ts | 4 ++-- web/e2e/project-members.spec.ts | 6 ++---- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/web/e2e/admin/login.spec.ts b/web/e2e/admin/login.spec.ts index cb1bd2c..a1961fa 100644 --- a/web/e2e/admin/login.spec.ts +++ b/web/e2e/admin/login.spec.ts @@ -6,7 +6,7 @@ import { signUp } from "../support/accounts"; import { call } from "../support/api"; -import { expect, test } from "../fixtures"; +import { escapeRegExp, expect, test } from "../fixtures"; // The operator console's front door: its own app, whose login refuses any account without the admin // scope, and whose shell re-proves the scope on every load. The seeded operator's session is shared @@ -69,9 +69,7 @@ test.describe("operator console sign-in", () => { await expect(page.getByRole("heading", { name: "Health" })).toBeVisible(); // The sidebar's footer names the operator and signs this browser out in one click. - await page - .getByRole("button", { name: new RegExp(operator.email.replace(/[.+]/g, "\\$&")) }) - .click(); + await page.getByRole("button", { name: new RegExp(escapeRegExp(operator.email)) }).click(); await expect(page).toHaveURL(/\/login/); await page.goto("/"); await expect(page).toHaveURL(/\/login/); diff --git a/web/e2e/admin/models-spend-audit.spec.ts b/web/e2e/admin/models-spend-audit.spec.ts index 808de77..9b4f6ce 100644 --- a/web/e2e/admin/models-spend-audit.spec.ts +++ b/web/e2e/admin/models-spend-audit.spec.ts @@ -6,7 +6,7 @@ import { signUp } from "../support/accounts"; import { call, stamp } from "../support/api"; -import { expect, test, toast } from "../fixtures"; +import { escapeRegExp, expect, test, toast } from "../fixtures"; // The model catalog, the ledger and the audit trail. The catalog and the price book are global, so // a flow only ever changes a model it added itself (a stamped id under a made-up provider): it @@ -105,7 +105,7 @@ test.describe("console models", () => { await save.click(); const saved = toast( page, - new RegExp(`^Price book v(\\d+) - ${ref.replace(/[.:-]/g, "\\$&")} repriced\\.$`), + new RegExp(`^Price book v(\\d+) - ${escapeRegExp(ref)} repriced\\.$`), ); await expect(saved).toBeVisible(); const after = Number((await saved.textContent())!.match(/v(\d+)/)![1]); diff --git a/web/e2e/admin/tasks.spec.ts b/web/e2e/admin/tasks.spec.ts index eb54afd..eb3a03c 100644 --- a/web/e2e/admin/tasks.spec.ts +++ b/web/e2e/admin/tasks.spec.ts @@ -6,7 +6,7 @@ import { signUp } from "../support/accounts"; import { call, createHeldTask, stamp } from "../support/api"; -import { expect, test, toast } from "../fixtures"; +import { escapeRegExp, expect, test, toast } from "../fixtures"; // The task console: every task in the system, searchable and sliced by status, with a peek that // reads the durable record and an operator's one hard verb, cancel. The tasks here are held (a @@ -71,7 +71,7 @@ test.describe("console tasks", () => { await page.goto(`/tasks?q=${task.id}`); await page .getByRole("main") - .getByRole("button", { name: new RegExp(task.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }) + .getByRole("button", { name: new RegExp(escapeRegExp(task.title)) }) .click(); await expect(page).toHaveURL(new RegExp(`task=${task.id}`)); diff --git a/web/e2e/project-members.spec.ts b/web/e2e/project-members.spec.ts index 6fb55d9..707f496 100644 --- a/web/e2e/project-members.spec.ts +++ b/web/e2e/project-members.spec.ts @@ -8,7 +8,7 @@ import type { Page } from "@playwright/test"; import { type Account, joinWorkspace, pageFor, signUp, verifyEmail } from "./support/accounts"; import { call, createProject, stamp } from "./support/api"; import { mailAvailable } from "./support/mailbox"; -import { expect, section, test } from "./fixtures"; +import { escapeRegExp, expect, section, test } from "./fixtures"; // A project's people (ADR-062): the owner adds someone from the workspace by email or hands them // a single-use invite link, changes their role and removes them. Every person here must belong to @@ -232,9 +232,7 @@ test.describe("project members", () => { const anon = await context.newPage(); await anon.goto(path); await expect(anon).toHaveURL( - new RegExp( - `/login\\?next=${encodeURIComponent(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, - ), + new RegExp(`/login\\?next=${escapeRegExp(encodeURIComponent(path))}$`), ); await anon.getByRole("textbox", { name: "Email" }).fill(mate.email); await anon.getByRole("textbox", { name: "Password" }).fill(mate.password);