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/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/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/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/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 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, minLength?: number) { + render( + , + ); +} + +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; }) { 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 2c74375..2227a57 100644 Binary files a/web/app/components/admin/resource-list.tsx and b/web/app/components/admin/resource-list.tsx differ diff --git a/web/app/components/artifact/artifact-view.dom.test.tsx b/web/app/components/artifact/artifact-view.dom.test.tsx index 023b0cc..6d58d39 100644 --- a/web/app/components/artifact/artifact-view.dom.test.tsx +++ b/web/app/components/artifact/artifact-view.dom.test.tsx @@ -164,6 +164,31 @@ 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(); + expect(await screen.findByText(/Not verified yet/)).toBeDefined(); + get.mockRestore(); + serve(); + rerender(); + 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(); + 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(); + expect(await screen.findByText(/Not verified yet/)).toBeDefined(); + get.mockRestore(); + serve({ artifact: art({ id: "a2" }) }); + rerender(); + 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..8f72fc7 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,31 @@ export function ArtifactView({ }; }, [currentId]); + // 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(() => { + 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", { + 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: ( + + + + ), + }, + ], + { initialEntries: ["/"] }, + ); + render(); + 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 => { - // 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 => { + // 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(); + 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(); 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: A) => void | Promise; +type Act = (...a: A) => void | Promise; 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; 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; +}) { 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 ; if (!members) return ; + /** Call a door, say how it went, reload the roster: true when it went through. */ const run = (fn: () => Promise, 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(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(opts: { @@ -111,30 +112,33 @@ export function useKeysetList(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(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. 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 = { orderKey: (r) => r.created_at, rowKey: (r) => r.id, onRow: () => undefined, // observation rows; the one verb rides inline - row: (r) => ( + row: (r, list) => ( <> @@ -102,7 +104,7 @@ const config: ResourceListConfig = { {r.last_fired_at ? ` · last ${ago(r.last_fired_at)}` : ""} {r.status} - {r.status === "active" && } + {r.status === "active" && 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(); + 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; @@ -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("

hi

"))).toBe(true); + expect(listOwnsKeys(null)).toBe(true); + }); + + it("a notification row leaves them to the list", () => { + expect(listOwnsKeys(el(``))).toBe( + true, + ); + }); + + it("a control with keys of its own keeps them", () => { + expect(listOwnsKeys(el(''))).toBe(false); + expect(listOwnsKeys(el(""))).toBe(false); + expect(listOwnsKeys(el('
All
'))).toBe(false); + expect(listOwnsKeys(el('
'))).toBe(false); + expect(listOwnsKeys(el('
'))).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>["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 = { +// `filter` folds a kind under another kind's filter item, so the menu never shows two the same. +const KIND_META: Record = { 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 = { 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 = 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) { {Object.entries(KIND_META) - .filter(([k]) => kindsPresent.has(k)) + .filter(([k, meta]) => !meta.filter && kindsPresent.has(k)) .map(([k, meta]) => (