refactor(archie,webui,gateway): remove the dashboard, which now ships from archie-frontend
This commit is contained in:
636 files changed
+77
-44027
No files matched your search
@@ -1,21 +1,14 @@
|
||||
# Live reload for the single archie binary during development.
|
||||
#
|
||||
# The frontend has its own loop -- `task dev:ui` runs Vite with HMR and proxies
|
||||
# /api here -- so this watcher deliberately ignores ui/. Watching it would
|
||||
# rebuild the Go binary on every keystroke in a CSS file, and rebuilding on
|
||||
# ui/dist changes would loop against `task ui`.
|
||||
#
|
||||
# Built with `-tags no_ui`: during development Vite serves the frontend
|
||||
# directly with HMR, so embedding ui/dist would only slow down reloads.
|
||||
# Live reload for the single archie binary during development. The dashboard
|
||||
# lives in archie-frontend and runs its own Vite server against this one.
|
||||
root = "."
|
||||
tmp_dir = ".air"
|
||||
|
||||
[build]
|
||||
cmd = "go build -tags no_ui -o ./.air/archie ./cmd/archie"
|
||||
cmd = "go build -o ./.air/archie ./cmd/archie"
|
||||
# `bin` is deprecated in air; entrypoint is the current key.
|
||||
entrypoint = "./.air/archie"
|
||||
include_ext = ["go", "toml", "sql", "yaml", "cedar", "tmpl", "md"]
|
||||
exclude_dir = ["ui", "bin", "docs", ".git", ".task", ".air", "tmp"]
|
||||
exclude_dir = ["bin", "docs", ".git", ".task", ".air", "tmp"]
|
||||
exclude_regex = ["_test\\.go"]
|
||||
stop_on_error = true
|
||||
delay = 400
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ docs/
|
||||
tmp/
|
||||
.playwright-mcp/
|
||||
# A trailing-slash pattern matches only the context root, so this is written to
|
||||
# match a node_modules at any depth: ui/node_modules alone is 200MB and the
|
||||
# agent image compiles Go, which needs none of it.
|
||||
# match a node_modules at any depth; the agent image compiles Go, which needs
|
||||
# none of it.
|
||||
**/node_modules/
|
||||
|
||||
# Stray host-built binaries committed at the repo root.
|
||||
|
||||
@@ -43,15 +43,6 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: false
|
||||
|
||||
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1
|
||||
with:
|
||||
package_json_file: ui/package.json
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Install quality tools
|
||||
run: |
|
||||
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(cat .golangci-version)
|
||||
|
||||
@@ -25,14 +25,6 @@ jobs:
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1
|
||||
with:
|
||||
package_json_file: ui/package.json
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Install quality tools
|
||||
run: |
|
||||
go install github.com/go-task/task/v3/cmd/task@v3.48.0
|
||||
|
||||
@@ -23,10 +23,6 @@ config.production.toml
|
||||
*.png
|
||||
|
||||
# Frontend
|
||||
/ui/node_modules/
|
||||
/ui/.vite/
|
||||
/ui/*.tsbuildinfo
|
||||
/ui/dist/
|
||||
|
||||
# air live-reload
|
||||
/.air/
|
||||
|
||||
@@ -172,12 +172,6 @@ linters:
|
||||
exclusions:
|
||||
generated: lax
|
||||
warn-unused: true
|
||||
# npm dependencies are not this module's code. `flatted`, pulled in
|
||||
# transitively by the dashboard toolchain, ships a Go implementation
|
||||
# alongside its JavaScript, and linting a vendored third-party file fails
|
||||
# the gate on complexity nobody here can fix.
|
||||
paths:
|
||||
- ui/node_modules
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
|
||||
@@ -98,10 +98,6 @@ BasedOnStyles =
|
||||
BasedOnStyles =
|
||||
[archipelago/**]
|
||||
BasedOnStyles =
|
||||
[ui/node_modules/**]
|
||||
BasedOnStyles =
|
||||
[ui/dist/**]
|
||||
BasedOnStyles =
|
||||
[.agents-run/**]
|
||||
BasedOnStyles =
|
||||
[.impeccable/**]
|
||||
|
||||
@@ -60,7 +60,9 @@ services: a core binary starts the extension as a plugin process and dials it.
|
||||
implements them. Every instruction sent to a model is a file in
|
||||
`internal/platform/prompts`, read through that package; never inline a prompt in
|
||||
code. The old `internal/prompts` serves the services until they go.
|
||||
Dashboard work follows `ui/CLAUDE.md`. Workflow YAML and its step vocabulary
|
||||
The dashboard is its own repository, archie-frontend, and ships as its own
|
||||
image; it reaches this backend only through `/api`, `/oauth2` and `/hooks`.
|
||||
Workflow YAML and its step vocabulary
|
||||
are in `WORKFLOWS.md`; the server catalogue is authoritative.
|
||||
|
||||
## Authority
|
||||
@@ -209,20 +211,18 @@ These protect users. Do not weaken them without the maintainer's say-so.
|
||||
```bash
|
||||
task build # binaries into bin/
|
||||
task test # go test -short ./...
|
||||
task ui # dashboard into ui/dist
|
||||
task check # the gate
|
||||
|
||||
go test -short ./internal/domain/workflow -run TestName # one test
|
||||
task dev # every service + Vite at http://localhost:5173, from deployments/dev.toml
|
||||
task e2e:up # seeded local stack; task e2e:check -- all runs the browser checks
|
||||
task dev # archie with live reload on 127.0.0.1:8484
|
||||
```
|
||||
|
||||
`task proto:generate`, `task db:generate` and `task openapi:generate` write
|
||||
the committed generated output for `proto/`, `internal/infrastructure/postgres/`
|
||||
and `api/openapi.yaml`; `task check` runs their check variants and rejects stale
|
||||
output. The e2e stack is not part of the gate.
|
||||
output.
|
||||
|
||||
Requires Go 1.27, Task, golangci-lint, Node, pnpm and Docker. Adopt `task fmt` and
|
||||
Requires Go 1.27, Task, golangci-lint and Docker. Adopt `task fmt` and
|
||||
`go fix` output as-is.
|
||||
|
||||
- `task check` gates the commit: `task check && git commit ...`. Never claim a
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
# Production single-binary image for cmd/archie.
|
||||
# Build: docker build -f Dockerfile.archie --build-arg VERSION=v1.0.0 -t archie:v1.0.0 .
|
||||
|
||||
# ── dashboard ──
|
||||
FROM node:24-trixie-slim AS ui
|
||||
WORKDIR /src/ui
|
||||
RUN corepack enable
|
||||
COPY ui/package.json ui/pnpm-lock.yaml ui/pnpm-workspace.yaml ./
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
pnpm install --frozen-lockfile
|
||||
COPY ui/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
# ── builder ──
|
||||
FROM golang:1.27-trixie AS builder
|
||||
ARG VERSION=dev
|
||||
@@ -18,7 +8,6 @@ WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN --mount=type=cache,target=/go/pkg/mod go mod download
|
||||
COPY . .
|
||||
COPY --from=ui /src/ui/dist ./ui/dist
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 go build -trimpath \
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
# archied — the archie daemon
|
||||
# Run via docker compose alongside NATS.
|
||||
|
||||
FROM node:24-trixie-slim AS dashboard
|
||||
WORKDIR /src/ui
|
||||
RUN corepack enable
|
||||
COPY ui/package.json ui/pnpm-lock.yaml ui/pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY ui/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
FROM golang:1.27-trixie AS builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
@@ -16,7 +8,6 @@ COPY go.mod go.sum ./
|
||||
# them COPY . . makes every commit a cold compile.
|
||||
RUN --mount=type=cache,target=/go/pkg/mod go mod download
|
||||
COPY . .
|
||||
COPY --from=dashboard /src/ui/dist ./ui/dist
|
||||
ARG GATEWAY_VERSION=dev
|
||||
ARG RUNTIME_VERSION=dev
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
|
||||
+15
-100
@@ -64,18 +64,6 @@ tasks:
|
||||
- task: db:generate
|
||||
- git diff --exit-code -- internal/infrastructure/postgres/postgresdb
|
||||
|
||||
pages:generate:
|
||||
desc: Write the dashboard's page catalogue to ui/pages/pages.json
|
||||
dir: ui
|
||||
cmds:
|
||||
- node --experimental-strip-types scripts/pages.ts
|
||||
|
||||
pages:check:
|
||||
desc: Regenerate the page catalogue and reject uncommitted differences
|
||||
cmds:
|
||||
- task: pages:generate
|
||||
- git diff --exit-code -- ui/pages/pages.json
|
||||
|
||||
openapi:generate:
|
||||
desc: Write the API's OpenAPI document to api/openapi.yaml
|
||||
cmds:
|
||||
@@ -103,45 +91,18 @@ tasks:
|
||||
cmds:
|
||||
- golangci-lint run ./...
|
||||
|
||||
ui:deps:
|
||||
desc: Install dashboard dependencies
|
||||
internal: true
|
||||
# Parallel UI checks must share one dependency install.
|
||||
run: once
|
||||
dir: ui
|
||||
cmds:
|
||||
- pnpm install --frozen-lockfile
|
||||
|
||||
ui:
|
||||
desc: Build the dashboard into ui/dist, which the Go build embeds
|
||||
# check builds the dashboard and then build depends on it again; a second
|
||||
# build empties ui/dist under the Go steps that embed it.
|
||||
run: once
|
||||
dir: ui
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- pnpm run build
|
||||
|
||||
test:ui:
|
||||
desc: Test and type-check the dashboard
|
||||
dir: ui
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- pnpm test
|
||||
- pnpm run typecheck
|
||||
|
||||
bench:prreview:
|
||||
desc: Run the PR review benchmark on the configured models and write docs/benchmarks/pr-review-*.md (-- -model ALIAS -judge-model REF; --help for flags)
|
||||
cmds:
|
||||
- go run ./cmd/archied prbench {{.CLI_ARGS}}
|
||||
|
||||
dev:
|
||||
desc: Run archie (with live reload) and Vite at http://localhost:5173
|
||||
deps: [dev:archie, dev:ui]
|
||||
desc: Run archie with live reload on 127.0.0.1:8484; run the dashboard from archie-frontend
|
||||
deps: [dev:archie]
|
||||
|
||||
dev:legacy:
|
||||
desc: Run the legacy multi-service stack and Vite at http://localhost:5173
|
||||
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard, dev:ui]
|
||||
desc: Run the legacy multi-service stack
|
||||
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard]
|
||||
|
||||
dev:tls:
|
||||
desc: Issue the development CA and service certificates deployments/dev.toml names
|
||||
@@ -267,7 +228,7 @@ tasks:
|
||||
echo 'listen = "127.0.0.1:8484"'
|
||||
echo 'state_dir = "{{.ROOT_DIR}}/{{.DIR}}/state"'
|
||||
echo "admin_token_sha256 = \"$(printf dev | sha256sum | cut -d' ' -f1)\""
|
||||
echo "age_identity = \"$(go run -tags no_ui ./cmd/archie -new-age-identity)\""
|
||||
echo "age_identity = \"$(go run ./cmd/archie -new-age-identity)\""
|
||||
echo '[database]'
|
||||
echo 'url = "postgres://archie_runtime:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
|
||||
echo 'owner_url = "postgres://archie_migrator:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
|
||||
@@ -279,42 +240,10 @@ tasks:
|
||||
if command -v air >/dev/null 2>&1; then
|
||||
exec air -build.args_bin="-config,{{.DIR}}/config.toml"
|
||||
fi
|
||||
exec go run -tags no_ui ./cmd/archie -config {{.DIR}}/config.toml
|
||||
|
||||
dev:ui:
|
||||
desc: Run Vite (proxies API requests to 127.0.0.1:8484 by default; override with ARCHIE_DEV_API)
|
||||
dir: ui
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- pnpm run dev
|
||||
|
||||
e2e:smoke:
|
||||
desc: Run the single-binary smoke check against a disposable archie instance (defaults to dev:archie on 127.0.0.1:8484)
|
||||
cmds:
|
||||
- |
|
||||
ARCHIE_SMOKE_URL="${ARCHIE_SMOKE_URL:-http://127.0.0.1:8484}" \
|
||||
ARCHIE_SMOKE_TOKEN="${ARCHIE_SMOKE_TOKEN:-dev}" \
|
||||
node e2e/archie-smoke.cjs
|
||||
|
||||
e2e:up:
|
||||
desc: Start the legacy local multi-service stack without Docker (PostgreSQL 18, services, Vite) and seed it
|
||||
cmds:
|
||||
- bash e2e/stack.sh start
|
||||
- bash e2e/seed.sh
|
||||
|
||||
e2e:down:
|
||||
desc: Stop the legacy local e2e stack
|
||||
cmds:
|
||||
- bash e2e/stack.sh stop
|
||||
|
||||
e2e:check:
|
||||
desc: List legacy browser checks; use -- all or -- CHECK to run, add --headed to watch
|
||||
cmds:
|
||||
- node e2e/run.cjs {{.CLI_ARGS}}
|
||||
exec go run ./cmd/archie -config {{.DIR}}/config.toml
|
||||
|
||||
build:
|
||||
desc: Build archie services and agent binaries
|
||||
deps: [ui]
|
||||
# Static, like the binaries a release ships, so `dist` reuses these
|
||||
# compiled packages and only links again.
|
||||
env:
|
||||
@@ -341,8 +270,6 @@ tasks:
|
||||
- "modules/**/*.yaml"
|
||||
- go.mod
|
||||
- go.sum
|
||||
- "ui/dist/**"
|
||||
- ui/pages/pages.json
|
||||
generates:
|
||||
- "{{.BIN_DIR}}/archied"
|
||||
- "{{.BIN_DIR}}/archie-gateway"
|
||||
@@ -360,7 +287,6 @@ tasks:
|
||||
|
||||
dist:
|
||||
desc: Build the linux/amd64 binaries a release ships into dist/ (VERSION=1.2.3; needs jq)
|
||||
deps: [ui]
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: amd64
|
||||
@@ -398,12 +324,6 @@ tasks:
|
||||
desc: Run the full quality gate
|
||||
# Finish mutations before starting parallel checks.
|
||||
cmds:
|
||||
# Node packages land under ui/, which `go test ./...` walks: installing
|
||||
# them while the parallel checks scan the tree makes a lockfile update
|
||||
# delete Go sources mid-walk. Install first, then fan out. Every Go step
|
||||
# embeds ui/dist, so the dashboard is built before any of them.
|
||||
- task: ui
|
||||
- task: pages:check
|
||||
- task: fmt
|
||||
- task: proto:check
|
||||
- task: db:check
|
||||
@@ -411,9 +331,8 @@ tasks:
|
||||
- task: check:readonly
|
||||
|
||||
wt:check:
|
||||
desc: "Fix, format and check a worktree's Go packages, and the dashboard if ui/ changed (-- ./pkg/... to name packages; default: those changed since main)"
|
||||
# A worktree has no ui/dist, so the Go steps build with no_ui. The full
|
||||
# gate still runs once, on the merged tree.
|
||||
desc: "Fix, format and check a worktree's Go packages (-- ./pkg/... to name packages; default: those changed since main)"
|
||||
# The full gate still runs once, on the merged tree.
|
||||
cmds:
|
||||
- |
|
||||
set -eu
|
||||
@@ -421,7 +340,7 @@ tasks:
|
||||
changed="$( { git diff --name-only "$base"; git ls-files --others --exclude-standard; } | sort -u)"
|
||||
pkgs="{{.CLI_ARGS}}"
|
||||
if [ -z "$pkgs" ]; then
|
||||
pkgs="$(printf '%s\n' "$changed" | grep '\.go$' | grep -v '^ui/' | xargs -r -n1 dirname | sort -u | while read -r d; do [ -d "$d" ] && echo "./$d"; done | tr '\n' ' ')"
|
||||
pkgs="$(printf '%s\n' "$changed" | grep '\.go$' | xargs -r -n1 dirname | sort -u | while read -r d; do [ -d "$d" ] && echo "./$d"; done | tr '\n' ' ')"
|
||||
fi
|
||||
if [ -n "$pkgs" ]; then
|
||||
echo "packages: $pkgs"
|
||||
@@ -429,8 +348,8 @@ tasks:
|
||||
# packages only; see fmt for why go fix runs until it converges.
|
||||
converged=false
|
||||
for pass in 1 2 3 4 5 6 7 8 9 10; do
|
||||
go fix -tags no_ui $pkgs
|
||||
if go fix -tags no_ui -diff $pkgs >/dev/null; then
|
||||
go fix $pkgs
|
||||
if go fix -diff $pkgs >/dev/null; then
|
||||
converged=true
|
||||
break
|
||||
fi
|
||||
@@ -440,14 +359,11 @@ tasks:
|
||||
exit 1
|
||||
fi
|
||||
golangci-lint fmt $pkgs
|
||||
go vet -tags no_ui $pkgs
|
||||
go test -short -tags no_ui $pkgs
|
||||
golangci-lint run --build-tags no_ui $pkgs
|
||||
go vet $pkgs
|
||||
go test -short $pkgs
|
||||
golangci-lint run $pkgs
|
||||
fi
|
||||
if printf '%s\n' "$changed" | grep -q '^ui/'; then
|
||||
"{{.TASK_EXE}}" test:ui
|
||||
fi
|
||||
if [ -z "$pkgs" ] && ! printf '%s\n' "$changed" | grep -q '^ui/'; then
|
||||
if [ -z "$pkgs" ]; then
|
||||
echo "nothing changed since main"
|
||||
fi
|
||||
|
||||
@@ -459,7 +375,6 @@ tasks:
|
||||
- task: lint
|
||||
- task: build
|
||||
- task: test
|
||||
- task: test:ui
|
||||
|
||||
release:
|
||||
desc: "Tag main as a release (RELEASE=major|minor|patch|1.2.3)"
|
||||
|
||||
@@ -87,8 +87,8 @@ schema and serves, which is what an install that has not split the roles does.
|
||||
|
||||
## Running the dashboard
|
||||
|
||||
The standalone UI Service (`archie-ui`) serves the dashboard, not
|
||||
`archied`.
|
||||
The standalone UI Service (`archie-ui`) serves the dashboard's API, not
|
||||
`archied`. The dashboard itself ships from archie-frontend as its own image.
|
||||
It reads the same `config.toml`, dials the Gateway and State Store targets
|
||||
already configured there, and binds `[web].listen` (`127.0.0.1:8484` by
|
||||
default). Start it after the Gateway and the State Store:
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
node_modules/
|
||||
out/
|
||||
-144
@@ -1,144 +0,0 @@
|
||||
# e2e
|
||||
|
||||
Validation of the whole stack, run by hand or by an agent, never by
|
||||
`task check` or CI. It needs PostgreSQL 18, five services, Vite and a browser,
|
||||
which the gate must not. Docker is not needed: without it tasks queue and
|
||||
park, which is useful data for the dashboard.
|
||||
|
||||
| File | What it does |
|
||||
| --- | --- |
|
||||
| `stack.sh` | Starts PostgreSQL 18 (port 55432) and the five services as local processes, then Vite on 5173 |
|
||||
| `seed.sh` | Seeds the stack through the dashboard API; safe to rerun |
|
||||
| `run.cjs` | Runs `checks/*.cjs` in Chromium; screenshots, manifest and `report.html` to `out/<stamp>/` |
|
||||
| `checks/` | One module per behaviour |
|
||||
| `results/` | One committed report per release |
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
task e2e:up # build, start everything, seed
|
||||
task e2e:check # list available checks (no stack needed)
|
||||
task e2e:check -- list # explicitly list checks
|
||||
task e2e:check -- audit-redirect # one check
|
||||
task e2e:check -- all # all checks
|
||||
task e2e:check -- --headed accessibility # watch a check in Chromium
|
||||
task e2e:check -- --headed all # watch every check
|
||||
task e2e:down # stop; e2e/stack.sh reset also deletes the data
|
||||
```
|
||||
|
||||
Headless is the default. `--headed` opens visible Chromium and slows browser
|
||||
actions to 150ms so you can follow them; assertions and saved evidence are the
|
||||
same in both modes. The terminal prints each check before it starts. Headed mode
|
||||
requires a graphical desktop.
|
||||
|
||||
Nothing reads the installed config: `stack.sh` points the XDG directories at
|
||||
`${ARCHIE_DEV_DIR:-~/.local/state/archie-dev}` and writes its overlay from
|
||||
`deployments/dev.toml`. Logs are in its `logs/`. `e2e/stack.sh restart archied`
|
||||
restarts one service. Run `task e2e:down` before starting again: startup refuses
|
||||
occupied service ports and checks that each launched process stays alive.
|
||||
|
||||
The seed creates a local test administrator: `operator@example.test`, password
|
||||
`archie-local-e2e-password`. Use it at `http://localhost:5173`; the browser
|
||||
checks sign in with the same account. These are test fixtures for this
|
||||
loopback-only stack. To use an existing test account, set `ARCHIE_E2E_EMAIL`
|
||||
and `ARCHIE_E2E_PASSWORD` for both seeding and browser checks. Seeding never
|
||||
resets an existing account or deletes test data.
|
||||
|
||||
The first run needs `pnpm install --dir e2e` and `pnpm --dir e2e exec playwright
|
||||
install chromium`. The cloud environment ships Chromium and Playwright
|
||||
preinstalled; run with `NODE_PATH=$(pnpm root -g)`.
|
||||
|
||||
## Mocked settings review
|
||||
|
||||
With the dashboard running on local Vite and the browser dependencies installed,
|
||||
run `node e2e/settings-save.cjs http://127.0.0.1:5173`. Playwright intercepts the
|
||||
API in the browser; this check needs neither sign-in nor a running backend.
|
||||
Set `CHROME_BIN` to use an installed Chromium instead of Playwright's browser.
|
||||
|
||||
## Single-binary smoke check
|
||||
|
||||
Point this check at an already running, disposable `archie` instance with its
|
||||
own PostgreSQL database and no external delivery connectors. Set
|
||||
`ARCHIE_SMOKE_TOKEN` to that instance's bootstrap token and
|
||||
`ARCHIE_SMOKE_URL` to its IPv4 loopback URL (for example
|
||||
`http://127.0.0.1:8080`), then run:
|
||||
|
||||
```bash
|
||||
node e2e/archie-smoke.cjs
|
||||
```
|
||||
|
||||
The check saves a workflow and a one-minute schedule, then verifies that its
|
||||
run links back to the schedule event and appears in the composer. It disables
|
||||
the schedule after the check but leaves records for inspection. The check needs
|
||||
no model or forge. The legacy `task e2e:up` stack is not the target of this check.
|
||||
If Archie is running in WSL and its loopback URL is not reachable from
|
||||
Windows, run the check with Node in the same Linux environment as Archie.
|
||||
If the schedule starts but the run does not finish, check the `events` and
|
||||
`runs` logs; readiness alone does not verify that either worker can claim work.
|
||||
|
||||
## Release evidence
|
||||
|
||||
```bash
|
||||
node e2e/run.cjs --record v1.54.0 all
|
||||
```
|
||||
|
||||
writes `results/v1.54.0.md`, the pass, fail or skip of every check for
|
||||
that release. Commit it with the release. Screenshots stay in `out/`.
|
||||
|
||||
## Writing a check
|
||||
|
||||
A module in `checks/` exports `async ({ page, go, shot, fail, skip, settled, attach, tolerate })`.
|
||||
|
||||
- `go(path)` loads a dashboard route: `waitUntil: 'load'` plus 1200ms.
|
||||
Wait for elements, never for `networkidle`: the event stream never goes idle.
|
||||
- `shot(label)` saves `<check>-<kebab>[-<w>x<h>].png` after a short settle,
|
||||
and records `{file, w, h, check}` in the manifest. The label becomes a slug,
|
||||
so `shot('/')` becomes `routes-home.png`; a viewport other than the
|
||||
1440x900 default adds a suffix (`-390x844`). Repeated labels get `-2`,
|
||||
`-3`, so the test runner keeps every capture.
|
||||
- `fail(msg)` records a problem without stopping.
|
||||
- `skip(reason)` stops the check and records a skip: a missing
|
||||
precondition, never a failure.
|
||||
- `tolerate(re)` ignores console errors matching `re`, for a response the page survives by design.
|
||||
- `attach(name, data)` saves a non-image artifact as `<check>-<name>`.
|
||||
- `settled(sel?)` waits for a selector or URL, then settles briefly.
|
||||
It is the test runner's wait; checks need no capture wrapper or
|
||||
ad-hoc sleeps around screenshots.
|
||||
|
||||
Each check gets a fresh page at 1440x900 with the login `storageState`;
|
||||
a check that needs a phone viewport resizes it itself to 390x844.
|
||||
Those are the only two viewports in use. A throw, a `fail`, or any
|
||||
console or page error fails the check. One module covers one behaviour.
|
||||
Families share a prefix: `audit-*` for the audit page (redirect,
|
||||
filters, revert, runtime, views-export, retention-live, phone), and
|
||||
`workflow-*` for the canvas (loading, validation, phone-layout, logic).
|
||||
`chat-composer` covers chat input, and `chat-dock-*` covers the chat dock (pin,
|
||||
drag-cancel, layout, resize, drafts, picker, phone).
|
||||
|
||||
`routes` loads every static route and flags text with stray leading,
|
||||
trailing or doubled spaces. `seeded` checks the seed is visible.
|
||||
`routes` visits `/logs` but the whitespace lint skips it: log lines are
|
||||
data, not copy.
|
||||
|
||||
## Output
|
||||
|
||||
Every run writes `out/<stamp>/` with the screenshots,
|
||||
`results.json` (the manifest: `{check, ok, ms, problems, artifacts[]}`,
|
||||
plus `skipped`/`skipReason` for skips) and `report.html`. The report is a
|
||||
self-contained test record with the commit, totals and one row per check (status,
|
||||
time, message and that check's artifacts, screenshots inline). `attach(name, data)`
|
||||
adds a non-image artifact to the current check; a failed check also gets a
|
||||
`failure` screenshot.
|
||||
|
||||
Exits: 0 when every check passes or skips, 1 when any check fails,
|
||||
2 when the test runner itself errors. `ARCHIE_E2E_URL` points the run at
|
||||
a dashboard other than `http://localhost:5173`.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
| --- | --- | --- |
|
||||
| State Store exits: server is older than PostgreSQL 18 | another server answered | `stack.sh` uses port 55432; set `ARCHIE_DEV_PGPORT` if another process holds that port |
|
||||
| Startup says a port is in use | a stack or another process already owns it | Run `task e2e:down`, then `task e2e:up`; inspect any remaining listener with `ss -ltnp` |
|
||||
| `pkill -f` kills your own shell (exit 144) | `pkill -f` matched its own command line | `stack.sh stop` or `restart`, which kill by PID |
|
||||
| Postgres aborts in the cloud | `/tmp/claude-0` is reset to mode 700 | `stack.sh` keeps the root cluster in `/var/lib/archie-dev` |
|
||||
@@ -1,75 +0,0 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { setTimeout: delay } = require("node:timers/promises");
|
||||
|
||||
async function main() {
|
||||
assert.ok(process.env.ARCHIE_SMOKE_URL, "Set ARCHIE_SMOKE_URL to a disposable Archie stack");
|
||||
const origin = new URL(process.env.ARCHIE_SMOKE_URL);
|
||||
const token = process.env.ARCHIE_SMOKE_TOKEN;
|
||||
assert.equal(origin.protocol, "http:");
|
||||
assert.equal(origin.hostname, "127.0.0.1", "Use a disposable Archie stack on IPv4 loopback");
|
||||
assert.ok(token, "Set ARCHIE_SMOKE_TOKEN to the disposable stack's admin token");
|
||||
|
||||
async function request(path, { method = "GET", body, authenticated = true, status = 200 } = {}) {
|
||||
const response = await fetch(new URL(path, origin), {
|
||||
method,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
...(authenticated && { Authorization: `Bearer ${token}` }),
|
||||
...(body !== undefined && { "Content-Type": "application/json" }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}).catch((err) => {
|
||||
throw new Error(`${method} ${path}: could not reach Archie at ${origin.origin}: ${err.cause?.message || err.message}`, { cause: err });
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}: expected HTTP ${status}, got ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const ready = await request("/readyz", { authenticated: false });
|
||||
assert.equal(ready.ready, true, "Archie is not ready");
|
||||
await request("/api/workflows", { authenticated: false, status: 401 });
|
||||
|
||||
const name = `smoke-${randomUUID()}`;
|
||||
const saved = await request("/api/workflows", {
|
||||
method: "POST",
|
||||
status: 201,
|
||||
body: { name, body: `repository: none\nsteps:\n - id: notify\n type: run.notify\n settings: {title: ${name}}\n` },
|
||||
});
|
||||
const trigger = { name, workflow_id: saved.id, every: "1m" };
|
||||
const created = await request("/api/triggers", { method: "POST", body: trigger, status: 201 });
|
||||
try {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let last = "no scheduled run";
|
||||
while (Date.now() < deadline) {
|
||||
const recent = await request("/api/runs");
|
||||
const run = recent.find((row) => row.workflow_id === saved.id);
|
||||
if (run) {
|
||||
last = `run ${run.id}: ${run.state}`;
|
||||
assert.ok(!["failed", "cancelled"].includes(run.state), `${last}: ${run.error || "no error returned"}`);
|
||||
if (run.state === "succeeded") {
|
||||
const trail = await request(`/api/runs/${run.id}`);
|
||||
assert.equal(trail.run.workflow_version, saved.version, "Run used the wrong workflow version");
|
||||
assert.equal(trail.origin?.trigger_id, created.id, "Run trail is missing the schedule trigger");
|
||||
assert.ok(trail.origin?.event_id, "Run trail is missing the originating event");
|
||||
assert.equal(trail.origin.declared_event_type, "schedule.tick");
|
||||
const messages = await request("/api/composer/messages");
|
||||
assert.equal(messages.filter((m) => m.run_id === run.id && m.title === name).length, 1,
|
||||
"Expected one composer notification linked to the run");
|
||||
console.log(`Schedule, run trail and composer notification verified for ${run.id}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await delay(1_000);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${name}: ${last}`);
|
||||
} finally {
|
||||
await request(`/api/triggers/${created.id}`, { method: "PUT", body: { ...trigger, disabled: true } });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
// Keyboard and phone access: the task dialog fits and tabs in order, pages
|
||||
// title correctly, the skip link and palette focus main content, and
|
||||
// query-only tab switches keep focus where it is. Then the audit's two
|
||||
// static sweeps (#1767): no unnamed controls on any route, and every keyboard
|
||||
// focus stop's indicator clears 3:1 against the background behind it.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await go('/tasks');
|
||||
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
|
||||
await page.getByRole('option', { name: 'New task', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'New task' });
|
||||
await dialog.waitFor();
|
||||
await settled();
|
||||
const bounds = await dialog.boundingBox();
|
||||
assert.ok(bounds.y >= 0 && bounds.y + bounds.height <= 844, 'New task dialog extends outside viewport');
|
||||
await shot('phone-task-dialog-top');
|
||||
const start = dialog.getByRole('button', { name: 'Start task', exact: true });
|
||||
await start.scrollIntoViewIfNeeded();
|
||||
const button = await start.boundingBox();
|
||||
assert.ok(button.y >= 0 && button.y + button.height <= 844, 'Start task cannot be reached by scrolling');
|
||||
await shot('phone-task-dialog');
|
||||
const close = dialog.getByRole('button', { name: 'Close', exact: true });
|
||||
await dialog.getByRole('button', { name: 'Cancel', exact: true }).focus();
|
||||
await page.keyboard.press('Tab');
|
||||
assert.ok(await close.evaluate(el => el === document.activeElement), 'Close is missing from keyboard tab order');
|
||||
const closeBounds = await close.boundingBox();
|
||||
assert.ok(closeBounds.y >= 0 && closeBounds.y + closeBounds.height <= 844, 'Close cannot be reached by keyboard');
|
||||
await page.keyboard.press('Escape');
|
||||
for (const [path, title] of [['/tasks', 'Tasks'], ['/events', 'Events'], ['/account', 'Your account'], ['/settings/models', 'Models | Instance'], ['/org/models', 'Models | Organisation']]) {
|
||||
await go(path);
|
||||
assert.equal(await page.title(), `${title} | Archie`);
|
||||
}
|
||||
await page.keyboard.press('Tab');
|
||||
const skip = page.getByRole('link', { name: 'Skip to main content', exact: true });
|
||||
assert.ok(await skip.evaluate(el => el === document.activeElement), 'Skip link is not the first keyboard stop');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content');
|
||||
await page.getByRole('button', { name: 'Sections', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Tasks', exact: true }).click();
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'route navigation did not focus main');
|
||||
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
|
||||
await page.getByRole('option', { name: 'Events', exact: true }).click();
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'palette navigation did not focus main');
|
||||
// The conversation panel is only open on some entries to this page; the
|
||||
// focus check below needs it closed either way.
|
||||
const hide = page.getByRole('button', { name: 'Hide conversation', exact: true });
|
||||
if (await hide.count()) await hide.click();
|
||||
const tab = page.getByRole('tab', { name: /^Map/ });
|
||||
await tab.click();
|
||||
assert.ok(await tab.evaluate(el => el === document.activeElement), 'query-only navigation stole focus');
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
|
||||
// Unnamed controls: every visible input, textarea, select, button or
|
||||
// widget role on each static route needs an accessible name (accname
|
||||
// order: labelledby, label, content, value, placeholder, title).
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
const unnamed = await page.evaluate(() => {
|
||||
const name = (el) => {
|
||||
const by = el.getAttribute('aria-labelledby');
|
||||
if (by) {
|
||||
const t = by.split(/\s+/).map((id) => (document.getElementById(id)?.textContent || '')).join(' ').trim();
|
||||
if (t) return t;
|
||||
}
|
||||
const al = el.getAttribute('aria-label');
|
||||
if (al && al.trim()) return al.trim();
|
||||
if (el.id) {
|
||||
const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
||||
if (l && l.textContent.trim()) return l.textContent.trim();
|
||||
}
|
||||
const wrap = el.closest('label');
|
||||
if (wrap && wrap.textContent.trim()) return wrap.textContent.trim();
|
||||
if (el.tagName === 'BUTTON' || el.getAttribute('role') === 'button' || el.getAttribute('role') === 'tab' || el.getAttribute('role') === 'switch') return el.textContent.trim();
|
||||
if (el.tagName === 'INPUT') {
|
||||
const t = (el.getAttribute('type') || 'text').toLowerCase();
|
||||
if (t === 'submit' || t === 'button' || t === 'reset') return el.value.trim();
|
||||
if (t === 'image') return (el.getAttribute('alt') || '').trim();
|
||||
}
|
||||
return (el.getAttribute('placeholder') || el.getAttribute('title') || '').trim();
|
||||
};
|
||||
return [...document.querySelectorAll('button, input, textarea, select, [role="button"], [role="tab"], [role="switch"], [role="checkbox"]')]
|
||||
.filter((el) => el.type !== 'hidden' && el.getClientRects().length)
|
||||
.filter((el) => !name(el))
|
||||
.map((el) => `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}: ${el.outerHTML.slice(0, 120)}`);
|
||||
});
|
||||
for (const u of unnamed) fail(`unnamed control on ${r}: ${u}`);
|
||||
}
|
||||
|
||||
// Focus contrast: Tab through each static route; the focused element's
|
||||
// outline or ring must clear 3:1 against the effective background behind it.
|
||||
const focusProbe = () => page.evaluate(() => {
|
||||
const el = document.activeElement;
|
||||
if (!el || el === document.body || el === document.documentElement) return null;
|
||||
const cs = getComputedStyle(el);
|
||||
const parse = (c) => {
|
||||
c = String(c).trim();
|
||||
let m = c.match(/rgba?\(([^)]+)\)/);
|
||||
if (m) {
|
||||
const p = m[1].split(',').map(Number);
|
||||
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
|
||||
}
|
||||
m = c.match(/^#([0-9a-f]{3,8})$/i);
|
||||
if (m) {
|
||||
let h = m[1];
|
||||
if (h.length === 3 || h.length === 4) h = [...h].map((x) => x + x).join('');
|
||||
const n = parseInt(h.slice(0, 6), 16);
|
||||
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const bgBehind = (start) => {
|
||||
for (let n = start; n; n = n.parentElement) {
|
||||
const c = parse(getComputedStyle(n).backgroundColor);
|
||||
if (c && c.a > 0) return c;
|
||||
}
|
||||
return { r: 255, g: 255, b: 255, a: 1 };
|
||||
};
|
||||
// An outer ring or outline is painted over the parent's background; an
|
||||
// inset one over the element's own. Score against whichever is higher.
|
||||
const bgSelf = bgBehind(el);
|
||||
const bgParent = bgBehind(el.parentElement);
|
||||
const over = (fg, bg) => {
|
||||
const a = fg.a + bg.a * (1 - fg.a);
|
||||
if (a === 0) return { r: 0, g: 0, b: 0 };
|
||||
return { r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / a, g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / a, b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / a };
|
||||
};
|
||||
const lum = (c) => {
|
||||
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
||||
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
|
||||
};
|
||||
const ratio = (c1, c2) => {
|
||||
const l1 = lum(c1), l2 = lum(c2);
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
};
|
||||
let fg = null;
|
||||
// The ring lives in --tw-ring-shadow on :focus-visible; read the var
|
||||
// directly, then fall back to outline, any shadow layer, focus border.
|
||||
if (el.matches(':focus-visible')) {
|
||||
const m = cs.getPropertyValue('--tw-ring-shadow').match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/i);
|
||||
if (m) { const c = parse(m[0]); if (c && c.a > 0) fg = c; }
|
||||
}
|
||||
if (!fg && cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) fg = parse(cs.outlineColor === 'currentcolor' ? cs.color : cs.outlineColor);
|
||||
if (!fg && cs.boxShadow && cs.boxShadow !== 'none') {
|
||||
for (const m of cs.boxShadow.matchAll(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/gi)) {
|
||||
const c = parse(m[0]);
|
||||
if (c && c.a > 0) { fg = c; break; }
|
||||
}
|
||||
}
|
||||
if (!fg && el.matches(':focus-visible') && parseFloat(cs.borderTopWidth) > 0) {
|
||||
const c = parse(cs.borderTopColor);
|
||||
if (c && c.a > 0) fg = c;
|
||||
}
|
||||
const sig = `${el.tagName}#${el.id}:${(el.textContent || '').trim().slice(0, 30)}`;
|
||||
if (!fg) return { sig, ratio: 0 };
|
||||
return { sig, ratio: Math.max(ratio(over(fg, bgSelf), bgSelf), ratio(over(fg, bgParent), bgParent)) };
|
||||
});
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
let prev = '';
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await page.keyboard.press('Tab');
|
||||
const info = await focusProbe();
|
||||
if (!info || info.sig === prev) break;
|
||||
prev = info.sig;
|
||||
if (info.ratio < 3) fail(`focus indicator under 3:1 on ${r} at ${info.sig} (ratio ${info.ratio.toFixed(2)})`);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,113 +0,0 @@
|
||||
// Audit filters are server-evaluated through the URL contract: search,
|
||||
// category, time range, back/forward restore, denied, and the actor filter.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail }) => {
|
||||
const { requestMatching, waitForUrl } = trackAudit(page);
|
||||
|
||||
await go('/org/audit');
|
||||
const status = await page.evaluate(async () => (await fetch('/api/auth/status')).json());
|
||||
const actor = status?.user?.id;
|
||||
assert.ok(actor, 'signed-in identity has no id');
|
||||
|
||||
const search = page.getByLabel('Search events', { exact: true });
|
||||
let request = await requestMatching(
|
||||
() => search.fill('repository'),
|
||||
(u) => u.searchParams.get('q') === 'repository',
|
||||
);
|
||||
assert.ok(request, 'search issued no matching /api/audit request');
|
||||
await waitForUrl((u) => u.searchParams.get('q') === 'repository');
|
||||
assert.equal((await search.inputValue()), 'repository');
|
||||
|
||||
await go('/org/audit');
|
||||
request = await requestMatching(
|
||||
() => page.getByRole('button', { name: 'Runtime', exact: true }).click(),
|
||||
(u) => u.searchParams.get('categories') === 'runtime',
|
||||
);
|
||||
assert.ok(request, 'category filter issued no matching /api/audit request');
|
||||
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
|
||||
assert.equal(
|
||||
await page.getByRole('button', { name: 'Runtime', exact: true }).getAttribute('aria-pressed'),
|
||||
'true',
|
||||
);
|
||||
|
||||
// Time: Any time drops the window from the request rather than guessing one.
|
||||
await page.getByRole('combobox', { name: 'Time range', exact: true }).click();
|
||||
request = await requestMatching(
|
||||
() => page.getByRole('option', { name: 'Any time', exact: true }).click(),
|
||||
(u) => u.searchParams.get('from') === null && u.searchParams.get('categories') === 'runtime',
|
||||
);
|
||||
assert.ok(request, 'Any time issued no matching /api/audit request');
|
||||
await waitForUrl((u) => u.searchParams.get('since') === 'any');
|
||||
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Any time');
|
||||
|
||||
// Back/forward restore the controls the URL describes.
|
||||
const backRequest = page.waitForRequest(
|
||||
(r) => {
|
||||
const u = new URL(r.url());
|
||||
return u.pathname === '/api/audit' && u.searchParams.get('categories') === 'runtime' && !!u.searchParams.get('from');
|
||||
},
|
||||
{ timeout: 8000 },
|
||||
);
|
||||
await page.goBack();
|
||||
await backRequest;
|
||||
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime' && u.searchParams.get('since') === null);
|
||||
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Last 30 days');
|
||||
assert.equal(
|
||||
await page.getByRole('button', { name: 'Runtime', exact: true }).getAttribute('aria-pressed'),
|
||||
'true',
|
||||
'back did not restore the category toggle',
|
||||
);
|
||||
const forwardRequest = page.waitForRequest(
|
||||
(r) => {
|
||||
const u = new URL(r.url());
|
||||
return u.pathname === '/api/audit' && u.searchParams.get('categories') === 'runtime' && u.searchParams.get('from') === null;
|
||||
},
|
||||
{ timeout: 8000 },
|
||||
);
|
||||
await page.goForward();
|
||||
await forwardRequest;
|
||||
await waitForUrl((u) => u.searchParams.get('since') === 'any');
|
||||
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Any time');
|
||||
|
||||
// Denied reaches the server through the same URL contract as the other
|
||||
// filters. It must both update the URL and issue a request.
|
||||
await go('/org/audit');
|
||||
const denied = page.getByRole('button', { name: 'Denied', exact: true });
|
||||
request = await requestMatching(
|
||||
() => denied.click(),
|
||||
(u) => u.searchParams.get('outcome') === 'denied',
|
||||
3000,
|
||||
);
|
||||
const deniedUrl = new URL(page.url());
|
||||
if (!request || deniedUrl.searchParams.get('outcome') !== 'denied') {
|
||||
await shot('denied');
|
||||
fail(
|
||||
`Denied filter did not reach the server: URL ${page.url()} has outcome=${deniedUrl.searchParams.get('outcome') ?? 'absent'}, ` +
|
||||
`aria-pressed=${await denied.getAttribute('aria-pressed')}, no /api/audit request with outcome=denied`,
|
||||
);
|
||||
} else {
|
||||
assert.equal(await denied.getAttribute('aria-pressed'), 'true');
|
||||
}
|
||||
|
||||
// Advanced actor filter: server-evaluated, in the URL, shown as a chip.
|
||||
await go('/org/audit');
|
||||
await page.getByRole('button', { name: 'Filters', exact: true }).click();
|
||||
const actorInput = page.getByLabel('Actor', { exact: true });
|
||||
request = await requestMatching(
|
||||
async () => {
|
||||
await actorInput.fill(actor);
|
||||
await actorInput.press('Enter');
|
||||
},
|
||||
(u) => u.searchParams.get('actor') === actor,
|
||||
);
|
||||
assert.ok(request, 'advanced actor filter issued no matching /api/audit request');
|
||||
await waitForUrl((u) => u.searchParams.get('actor') === actor);
|
||||
assert.match(
|
||||
await page.locator('ul[aria-label="Active filters"] li', { hasText: 'Actor:' }).first().innerText(),
|
||||
new RegExp(actor),
|
||||
);
|
||||
await shot('filters');
|
||||
await page.keyboard.press('Escape');
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
// The audit page at phone width: secondary columns collapse, and the list,
|
||||
// an expanded row and the filters dialog fit without horizontal overflow.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled }) => {
|
||||
trackAudit(page);
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await go('/org/audit');
|
||||
const assertNoOverflow = async (label) => {
|
||||
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
innerWidth,
|
||||
}));
|
||||
if (scrollWidth > innerWidth) {
|
||||
fail(`${label} overflows 390px: documentElement.scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
|
||||
}
|
||||
};
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
await assertNoOverflow('audit list');
|
||||
assert.equal(
|
||||
await page.locator('thead th', { hasText: 'Target' }).first().evaluate((el) => getComputedStyle(el).display),
|
||||
'none',
|
||||
'secondary columns are still rendered on the phone',
|
||||
);
|
||||
await shot('list');
|
||||
|
||||
const phoneRow = page.locator('[data-row-key]').first();
|
||||
await phoneRow.focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await settled();
|
||||
assert.equal(await phoneRow.getAttribute('aria-expanded'), 'true', 'phone row did not expand');
|
||||
await assertNoOverflow('expanded change set');
|
||||
await shot('expanded');
|
||||
|
||||
await page.getByRole('button', { name: 'Filters', exact: true }).click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('advanced filters');
|
||||
await shot('filters');
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
// A deep link to the old history route redirects to the audit page keeping
|
||||
// section, actor, since and the hash, and the feed loads with filter chips.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail }) => {
|
||||
const { lastRequest } = trackAudit(page);
|
||||
|
||||
await go('/org/audit');
|
||||
const status = await page.evaluate(async () => (await fetch('/api/auth/status')).json());
|
||||
const actor = status?.user?.id;
|
||||
assert.ok(actor, 'signed-in identity has no id');
|
||||
|
||||
const deepLink = `/settings/history?section=container-runtime-policies&actor=${encodeURIComponent(actor)}&since=30d#deep`;
|
||||
await go(deepLink);
|
||||
assert.match(page.url(), /\/org\/audit\?/, 'history did not redirect to the audit route');
|
||||
assert.match(page.url(), /section=container-runtime-policies/, 'redirect dropped section');
|
||||
assert.match(page.url(), new RegExp(`actor=${encodeURIComponent(actor)}`), 'redirect dropped actor');
|
||||
assert.match(page.url(), /since=30d/, 'redirect dropped since');
|
||||
assert.match(page.url(), /#deep$/, 'redirect dropped the hash');
|
||||
const redirected = lastRequest();
|
||||
assert.ok(redirected, 'the redirect issued no /api/audit request');
|
||||
assert.equal(redirected.searchParams.get('kind'), 'container-runtime-policies');
|
||||
assert.equal(redirected.searchParams.get('actor'), actor);
|
||||
|
||||
// The feed must be readable before anything below can mean anything. A 500
|
||||
// here is the whole page: say what the server answered instead of timing out.
|
||||
const probe = await page.evaluate(async () => {
|
||||
const response = await fetch('/api/audit?limit=1');
|
||||
return { status: response.status, body: await response.text() };
|
||||
});
|
||||
if (probe.status !== 200) {
|
||||
await shot('unavailable');
|
||||
fail(`GET /api/audit returned ${probe.status}: ${probe.body.slice(0, 200)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const kindChip = page.locator('ul[aria-label="Active filters"] li', { hasText: 'Kind:' });
|
||||
await kindChip.first().waitFor({ timeout: 8000 });
|
||||
assert.match(await kindChip.first().innerText(), /Container runtime policies/, 'kind chip missing its catalog title');
|
||||
assert.match(
|
||||
await page.locator('ul[aria-label="Active filters"] li', { hasText: 'Actor:' }).first().innerText(),
|
||||
new RegExp(actor),
|
||||
'actor chip missing',
|
||||
);
|
||||
await shot('redirect');
|
||||
await go('/org/audit');
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
await shot('desktop');
|
||||
};
|
||||
@@ -1,148 +0,0 @@
|
||||
// Audit retention reads the stored resource, the live tail prepends new rows
|
||||
// without a reload and holds them behind a button while scrolled away, and a
|
||||
// retention save persists. The save stays last: it must not stop the rest.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled }) => {
|
||||
const { loadCount } = trackAudit(page);
|
||||
|
||||
await go('/org/audit');
|
||||
const resourceResponse = await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`);
|
||||
assert.equal(resourceResponse.status(), 200, 'audit-retention resource is unreadable');
|
||||
const retentionResource = await resourceResponse.json();
|
||||
const retentionHours = (value) => {
|
||||
const match = String(value || '').match(/^(\d+)h$/);
|
||||
return match ? Number(match[1]) : 0;
|
||||
};
|
||||
const originalHours = retentionHours(retentionResource.resource.value.runtime_event_retention);
|
||||
|
||||
const openRetention = async () => {
|
||||
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Retention', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await dialog.waitFor();
|
||||
await dialog.getByLabel('Runtime event retention (hours)', { exact: true }).waitFor();
|
||||
return dialog;
|
||||
};
|
||||
|
||||
let retentionDialog = await openRetention();
|
||||
assert.match(await retentionDialog.innerText(), /Audit retention/);
|
||||
assert.equal(
|
||||
await retentionDialog.getByLabel('Runtime event retention (hours)', { exact: true }).inputValue(),
|
||||
String(originalHours),
|
||||
'retention dialog did not read the stored resource',
|
||||
);
|
||||
await retentionDialog.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await retentionDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
|
||||
assert.ok(!(await retentionDialog.isVisible().catch(() => false)), 'Cancel left the retention dialog open');
|
||||
|
||||
// ---- live tail -----------------------------------------------------------
|
||||
await go('/org/audit');
|
||||
await page.evaluate(() => window.scrollTo(0, 0));
|
||||
await settled();
|
||||
const topKey = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
|
||||
const loadsBeforeWrite = loadCount();
|
||||
let resource = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
|
||||
const toggleRetention = async () => {
|
||||
const current = retentionHours(resource.resource.value.runtime_event_retention);
|
||||
const next = current === 2160 ? 2161 : 2160;
|
||||
const written = await page.request.post(
|
||||
`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention/commands/replace`,
|
||||
{
|
||||
headers: { 'X-Archie-CSRF': '1', Origin: new URL(page.url()).origin },
|
||||
data: { value: { runtime_event_retention: `${next}h` }, expected_version: resource.resource.version },
|
||||
},
|
||||
);
|
||||
const body = await written.text();
|
||||
assert.equal(written.status(), 200, `retention write answered ${written.status()}: ${body.slice(0, 200)}`);
|
||||
resource = JSON.parse(body);
|
||||
};
|
||||
|
||||
await toggleRetention();
|
||||
let liveKey = null;
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
const key = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
|
||||
if (key !== topKey) {
|
||||
liveKey = key;
|
||||
break;
|
||||
}
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
if (!liveKey) {
|
||||
fail('live tail did not show a new row within 12s of a write');
|
||||
await shot('live');
|
||||
} else {
|
||||
assert.equal(loadCount(), loadsBeforeWrite, 'the live row required a page reload');
|
||||
assert.match(
|
||||
await page.locator(`[data-row-key="${liveKey}"]`).innerText(),
|
||||
/audit-retention/i,
|
||||
'the live row is not the write that caused it',
|
||||
);
|
||||
await shot('live');
|
||||
}
|
||||
|
||||
// Scrolled away, a new event is held behind a button instead of jumping the
|
||||
// list under the operator.
|
||||
await page.evaluate(() => window.scrollTo(0, 900));
|
||||
await settled();
|
||||
const scrolledTo = await page.evaluate(() => window.scrollY);
|
||||
assert.ok(scrolledTo > 80, 'the feed is too short to test held new events');
|
||||
const heldTop = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
|
||||
await toggleRetention();
|
||||
const heldButton = page.getByRole('button', { name: /^\d+ new events?$/ }).first();
|
||||
let held = false;
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
if ((await heldButton.count()) && (await heldButton.isVisible().catch(() => false))) {
|
||||
held = true;
|
||||
break;
|
||||
}
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
if (!held) {
|
||||
fail('held new events did not appear while scrolled away');
|
||||
await shot('held');
|
||||
} else {
|
||||
assert.equal(
|
||||
await page.locator('[data-row-key]').first().getAttribute('data-row-key'),
|
||||
heldTop,
|
||||
'a new row was prepended while the operator was scrolled away',
|
||||
);
|
||||
await shot('held');
|
||||
await heldButton.click();
|
||||
await page.waitForFunction(
|
||||
(top) => document.querySelector('[data-row-key]')?.getAttribute('data-row-key') !== top,
|
||||
heldTop,
|
||||
{ timeout: 8000 },
|
||||
).catch(() => {});
|
||||
await settled();
|
||||
assert.notEqual(
|
||||
await page.locator('[data-row-key]').first().getAttribute('data-row-key'),
|
||||
heldTop,
|
||||
'showing held events did not prepend the new row',
|
||||
);
|
||||
assert.ok((await page.evaluate(() => window.scrollY)) < 10, 'showing held events did not return to the top');
|
||||
}
|
||||
|
||||
// ---- retention: save -----------------------------------------------------
|
||||
// Kept last: the page error this currently raises must not stop the rest.
|
||||
await go('/org/audit');
|
||||
retentionDialog = await openRetention();
|
||||
const hoursField = retentionDialog.getByLabel('Runtime event retention (hours)', { exact: true });
|
||||
const beforeSave = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
|
||||
const beforeHours = retentionHours(beforeSave.resource.value.runtime_event_retention);
|
||||
const wanted = beforeHours === 2160 ? 2161 : 2160;
|
||||
await hoursField.fill(String(wanted));
|
||||
await retentionDialog.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await retentionDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
|
||||
const stillOpen = await retentionDialog.isVisible().catch(() => false);
|
||||
const afterSave = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
|
||||
const afterHours = retentionHours(afterSave.resource.value.runtime_event_retention);
|
||||
if (stillOpen || afterHours !== wanted) {
|
||||
await shot('retention-save');
|
||||
fail(
|
||||
`retention save did not complete: dialog ${stillOpen ? 'stayed open' : 'closed'}, ` +
|
||||
`stored retention is ${afterHours}h (wanted ${wanted}h), URL ${page.url()}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
// A revertable change set expands to its Before/After diff, offers one Revert
|
||||
// action whose dialog cancels cleanly, and toggles from the keyboard.
|
||||
const assert = require('node:assert/strict');
|
||||
const { DEFAULT_WINDOW_MS, trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled }) => {
|
||||
trackAudit(page);
|
||||
|
||||
await go('/org/audit');
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
const from = new Date(Date.now() - DEFAULT_WINDOW_MS).toISOString();
|
||||
// The feed page size is 100: only rows in this response are rendered.
|
||||
const feed = await page.evaluate(
|
||||
async (iso) => (await fetch(`/api/audit?limit=100&from=${encodeURIComponent(iso)}`)).json(),
|
||||
from,
|
||||
);
|
||||
const records = feed.records || [];
|
||||
assert.ok(records.length, 'the seeded feed is empty');
|
||||
|
||||
const changeSet = records.find(
|
||||
(row) =>
|
||||
row.target?.kind === 'resource' &&
|
||||
(row.detail?.fields || []).length > 0 &&
|
||||
(row.detail?.version ?? 0) > 1,
|
||||
);
|
||||
if (!changeSet) {
|
||||
fail('no revertable settings change set in the feed; cannot exercise the diff or Revert');
|
||||
return;
|
||||
}
|
||||
|
||||
const row = page.locator(`[data-row-key="${changeSet.id}"]`);
|
||||
await row.waitFor();
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await row.locator('td').first().click();
|
||||
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'click did not expand the change set');
|
||||
const detail = row.locator('xpath=following-sibling::tr[1]');
|
||||
await detail.getByText('Before:', { exact: false }).first().waitFor();
|
||||
assert.match(await detail.innerText(), /After:/, 'expanded change set has no after value');
|
||||
assert.equal(
|
||||
await detail.getByRole('button', { name: /^Revert \S/ }).count(),
|
||||
0,
|
||||
'the audit diff offers a per-field revert',
|
||||
);
|
||||
const revertAll = page.getByRole('button', { name: 'Revert', exact: true });
|
||||
assert.ok((await revertAll.count()) > 0, 'no Revert action on a revertable change set');
|
||||
await shot('change-set');
|
||||
|
||||
await revertAll.first().click();
|
||||
const dialog = page.getByRole('alertdialog');
|
||||
await dialog.waitFor();
|
||||
assert.match(await dialog.innerText(), /Revert this change\?/);
|
||||
assert.match(await dialog.innerText(), /previous version opens for review/i);
|
||||
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await dialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
|
||||
assert.ok(!(await dialog.isVisible().catch(() => false)), 'Cancel left the revert dialog open');
|
||||
assert.equal(
|
||||
await page.getByRole('region', { name: 'Unsaved changes' }).count(),
|
||||
0,
|
||||
'Cancel touched the save bar',
|
||||
);
|
||||
|
||||
// Enter is the keyboard equivalent of clicking the row.
|
||||
await row.click();
|
||||
assert.equal(await row.getAttribute('aria-expanded'), 'false', 'the row did not collapse');
|
||||
await row.focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await settled();
|
||||
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'Enter did not expand the change set');
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
// A runtime event with a task target expands to its metadata and links to
|
||||
// the task. The seed's work requests park and record the event; the feed is
|
||||
// filtered to it so settings noise cannot push it off the page. Without it
|
||||
// there is nothing to exercise, so the check skips instead of failing.
|
||||
const assert = require('node:assert/strict');
|
||||
const { DEFAULT_WINDOW_MS, trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, skip }) => {
|
||||
trackAudit(page);
|
||||
|
||||
await go('/org/audit?kind=parked');
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
const from = new Date(Date.now() - DEFAULT_WINDOW_MS).toISOString();
|
||||
// The feed page size is 100: only rows in this response are rendered.
|
||||
const feed = await page.evaluate(
|
||||
async (iso) => (await fetch(`/api/audit?limit=100&kind=parked&from=${encodeURIComponent(iso)}`)).json(),
|
||||
from,
|
||||
);
|
||||
const records = feed.records || [];
|
||||
const runtime = records.find((row) => row.category === 'runtime' && row.target?.kind === 'task' && row.target?.id);
|
||||
if (!runtime) {
|
||||
skip('no runtime event with a task target in the feed');
|
||||
}
|
||||
|
||||
const row = page.locator(`[data-row-key="${runtime.id}"]`);
|
||||
await row.waitFor();
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await row.locator('td').first().click();
|
||||
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'runtime row did not expand');
|
||||
const detail = row.locator('xpath=following-sibling::tr[1]');
|
||||
await detail.locator('dl dt', { hasText: 'Target' }).first().waitFor();
|
||||
assert.match(await detail.innerText(), /Table/, 'runtime metadata has no table row');
|
||||
const link = detail.getByRole('link', { name: runtime.target.label || runtime.target.id, exact: true });
|
||||
assert.equal(await link.count(), 1, 'runtime target is not a link');
|
||||
assert.equal(await link.getAttribute('href'), `/tasks/${runtime.target.id}`);
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
// Audit saved views round-trip through the URL, and CSV/JSON exports carry
|
||||
// the resolved window and arrive as attachments.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit, exportOnce } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled }) => {
|
||||
const { waitForUrl } = trackAudit(page);
|
||||
|
||||
await go('/org/audit');
|
||||
await page.getByRole('button', { name: 'Runtime', exact: true }).click();
|
||||
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
|
||||
|
||||
const viewName = `e2e-view-${Date.now()}`;
|
||||
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Save view…', exact: true }).click();
|
||||
const saveDialog = page.getByRole('dialog');
|
||||
await saveDialog.waitFor();
|
||||
await saveDialog.getByLabel('Name', { exact: true }).fill(viewName);
|
||||
await saveDialog.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await settled();
|
||||
await saveDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
|
||||
|
||||
const savedView = page.getByRole('combobox', { name: 'Saved view', exact: true });
|
||||
await savedView.waitFor();
|
||||
assert.equal((await savedView.innerText()).trim(), viewName);
|
||||
await shot('saved-view');
|
||||
|
||||
await page.getByRole('button', { name: 'Runtime', exact: true }).click();
|
||||
await waitForUrl((u) => u.searchParams.get('categories') === null);
|
||||
await savedView.click();
|
||||
await page.getByRole('option', { name: viewName, exact: true }).click();
|
||||
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
|
||||
assert.equal((await savedView.innerText()).trim(), viewName, 'applying the saved view did not restore it');
|
||||
|
||||
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Delete view', exact: true }).click();
|
||||
await savedView.waitFor({ state: 'detached', timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await savedView.count(), 0, 'deleting the saved view left it in the picker');
|
||||
|
||||
await go('/org/audit');
|
||||
await page.getByRole('button', { name: 'Export', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'CSV', exact: true }).waitFor();
|
||||
await shot('export');
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const csvBody = await exportOnce(page, fail, 'CSV', 'csv');
|
||||
if (csvBody !== null) assert.ok(csvBody.split('\n')[0].trim().length > 0, 'CSV export is empty');
|
||||
const jsonBody = await exportOnce(page, fail, 'JSON', 'json');
|
||||
if (jsonBody !== null) assert.ok(jsonBody.trimStart().startsWith('['), 'JSON export is not an array');
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
// An isolated catalogue entry keeps the check independent of the live source.
|
||||
await page.route('**/api/extensions/catalogue', route => route.fulfill({ json: [{
|
||||
name: 'preview-extension', display_name: 'Preview extension', description: 'An extension to preview.',
|
||||
contract: 'workflow', group: 'platform', latest: '1.0.0', default_version: '1.0.0',
|
||||
versions: [{ version: '1.0.0', digest: 'preview-digest', registered: true, settings: [] }],
|
||||
}] }));
|
||||
await page.setViewportSize({ width: 390, height: 600 });
|
||||
await go('/settings/extensions?tab=marketplace');
|
||||
const opener = page.getByRole('button', { name: 'Details for Preview extension' });
|
||||
const preview = page.getByRole('dialog', { name: 'Preview extension' });
|
||||
const version = preview.getByRole('combobox', { name: 'Version' });
|
||||
const close = preview.getByRole('button', { name: 'Close' });
|
||||
|
||||
await opener.click();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
assert.ok(await version.evaluate(el => el === document.activeElement));
|
||||
await shot('version-focus');
|
||||
const { clearance, ring } = await version.evaluate(el => {
|
||||
let scroll = el.parentElement;
|
||||
while (getComputedStyle(scroll).overflowY !== 'auto') scroll = scroll.parentElement;
|
||||
const bounds = scroll.getBoundingClientRect();
|
||||
const field = el.getBoundingClientRect();
|
||||
const css = getComputedStyle(el);
|
||||
return {
|
||||
clearance: Math.min(field.left - bounds.left, bounds.left + scroll.clientWidth - field.right),
|
||||
ring: Math.max(3, parseFloat(css.outlineWidth) + parseFloat(css.outlineOffset)),
|
||||
};
|
||||
});
|
||||
assert.ok(clearance + 0.1 >= ring, `Version focus ring: ${clearance}px clearance for ${ring}px ring`);
|
||||
|
||||
await page.keyboard.press('Space');
|
||||
const options = page.getByRole('listbox');
|
||||
await options.waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await options.waitFor({ state: 'hidden' });
|
||||
await preview.waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await preview.waitFor({ state: 'detached' });
|
||||
assert.ok(await opener.evaluate(el => el === document.activeElement));
|
||||
|
||||
await opener.click();
|
||||
await close.click();
|
||||
await preview.waitFor({ state: 'detached' });
|
||||
assert.ok(await opener.evaluate(el => el === document.activeElement));
|
||||
};
|
||||
@@ -1,70 +0,0 @@
|
||||
// The chat composer: IME confirmation never submits the draft, Shift+Enter
|
||||
// inserts a newline, ordinary Enter submits and clears, and # attaches a task.
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
tolerate(/api\/tasks/);
|
||||
await go('/events');
|
||||
const composer = page.getByRole('combobox', { name: 'Message Archie', exact: true });
|
||||
await composer.waitFor();
|
||||
await composer.fill('Composition in progress');
|
||||
const sent = [];
|
||||
await page.route('**/api/chat/stream', async route => {
|
||||
sent.push(route.request().postDataJSON().text);
|
||||
await route.fulfill({ contentType: 'text/event-stream', body: 'data: {"type":"done","text":"Test response"}\n\n' });
|
||||
});
|
||||
for (const event of [{ isComposing: true }, { keyCode: 229 }]) {
|
||||
await composer.dispatchEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...event });
|
||||
assert.equal(await composer.inputValue(), 'Composition in progress', 'IME confirmation submitted the draft');
|
||||
}
|
||||
assert.equal(sent.length, 0);
|
||||
await composer.press('Shift+Enter');
|
||||
assert.ok((await composer.inputValue()).includes('\n'), 'Shift+Enter no longer inserts a newline');
|
||||
await composer.fill('Ordinary Enter submits');
|
||||
const request = page.waitForRequest('**/api/chat/stream');
|
||||
await composer.press('Enter');
|
||||
assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits');
|
||||
assert.equal(await composer.inputValue(), '');
|
||||
|
||||
let failTasks = true;
|
||||
await page.route('**/api/tasks?*', async route => {
|
||||
if (failTasks) return route.fulfill({ status: 500, contentType: 'text/plain', body: 'task store down' });
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify([
|
||||
{ id: 1861, title: "Chat composer: '#' context dropdown", status: 'running' },
|
||||
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
const tasksPalette = page.getByRole('listbox', { name: 'Tasks' });
|
||||
await composer.fill('Look at #');
|
||||
await tasksPalette.getByRole('alert').waitFor();
|
||||
assert.equal(await tasksPalette.getByRole('option').count(), 0);
|
||||
|
||||
failTasks = false;
|
||||
await tasksPalette.getByRole('button', { name: 'Retry' }).click();
|
||||
await tasksPalette.getByRole('option').first().waitFor();
|
||||
assert.equal(await tasksPalette.getByRole('option').count(), 2);
|
||||
|
||||
await composer.press('Escape');
|
||||
await tasksPalette.waitFor({ state: 'hidden' });
|
||||
|
||||
await composer.fill('Look at #184 now');
|
||||
await composer.evaluate(el => el.setSelectionRange(12, 12));
|
||||
await composer.dispatchEvent('input');
|
||||
await tasksPalette.getByRole('option').first().waitFor();
|
||||
assert.equal(await tasksPalette.getByRole('option').count(), 1);
|
||||
await composer.press('Tab');
|
||||
await tasksPalette.waitFor({ state: 'hidden' });
|
||||
assert.equal(await composer.inputValue(), 'Look at now');
|
||||
await page.getByRole('list', { name: 'Attached tasks' }).getByText('#1842').waitFor();
|
||||
|
||||
const tagged = page.waitForRequest('**/api/chat/stream');
|
||||
await composer.press('Enter');
|
||||
const text = (await tagged).postDataJSON().text;
|
||||
assert.ok(text.startsWith('Look at now') && text.includes('#1842 Retry stalled task runs'), text);
|
||||
assert.equal(await page.getByRole('list', { name: 'Attached tasks' }).count(), 0);
|
||||
await shot('chat-composition');
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
// Each conversation keeps its own unsent text and attached tasks. Starting a
|
||||
// new chat opens an empty composer, switching back restores the earlier
|
||||
// draft, and hiding and reopening the conversation loses nothing.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await page.route('**/api/tasks?*', (route) =>
|
||||
route.fulfill({ contentType: 'application/json', body: JSON.stringify([{ id: 1861, title: 'Task picker', status: 'running' }]) }),
|
||||
);
|
||||
await h.load(page, go);
|
||||
await h.expand(page);
|
||||
const composer = h.composerOf(page);
|
||||
const tags = page.getByRole('list', { name: 'Attached tasks' });
|
||||
|
||||
await composer.fill('draft for the first chat');
|
||||
await composer.fill('#');
|
||||
await page.getByRole('listbox', { name: 'Tasks' }).getByRole('option').first().click();
|
||||
await tags.getByText('#1861').waitFor();
|
||||
await composer.fill('draft for the first chat');
|
||||
|
||||
await page.getByRole('button', { name: 'New chat' }).click();
|
||||
await h.until(async () => (await composer.inputValue()) === '' && (await tags.count()) === 0, 'a new chat inherited the first chat draft');
|
||||
await composer.fill('draft for the second chat');
|
||||
|
||||
await h.hideOf(page).click();
|
||||
await h.expand(page);
|
||||
assert.equal(await composer.inputValue(), 'draft for the second chat', 'hiding the conversation lost the draft');
|
||||
|
||||
const pick = async (index) => {
|
||||
await page.getByRole('combobox', { name: 'Conversation' }).click();
|
||||
await page.getByRole('option').nth(index).click();
|
||||
};
|
||||
await pick(1);
|
||||
await h.until(async () => (await composer.inputValue()) === 'draft for the first chat', 'switching back did not restore the first draft');
|
||||
await tags.getByText('#1861').waitFor();
|
||||
await shot('first-chat-draft');
|
||||
|
||||
await pick(0);
|
||||
await h.until(async () => (await composer.inputValue()) === 'draft for the second chat', 'switching forward did not restore the second draft');
|
||||
assert.equal(await tags.count(), 0, 'the first chat task tag leaked into the second chat');
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
// A drag the browser cancels (a touch turned into a scroll, a lost pointer)
|
||||
// leaves the dock where it was: nothing pins, nothing stays offset, and the
|
||||
// next drag still works.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
module.exports = async ({ page, go }) => {
|
||||
await h.load(page, go);
|
||||
await h.expand(page);
|
||||
const dock = h.dockOf(page);
|
||||
const before = await dock.boundingBox();
|
||||
const header = dock.locator('div.cursor-grab');
|
||||
|
||||
await h.dragTo(page, 1430);
|
||||
const dragging = await dock.getAttribute('style');
|
||||
assert.ok(/translate/.test(dragging || ''), 'the drag never started, so cancelling it proves nothing');
|
||||
await header.dispatchEvent('pointercancel');
|
||||
await page.mouse.up();
|
||||
|
||||
await h.until(async () => !/translate/.test((await dock.getAttribute('style')) || ''), 'the dock stayed offset after the drag was cancelled');
|
||||
assert.deepEqual(await dock.boundingBox(), before, 'cancelling the drag moved the dock');
|
||||
assert.equal((await h.saved(page)).side, null, 'a cancelled drag pinned the dock');
|
||||
|
||||
await h.dragTo(page, 1430);
|
||||
await page.mouse.up();
|
||||
await h.until(async () => (await h.saved(page)).side === 'right', 'a drag after a cancelled one did not pin');
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
// The saved dock layout: a stored mode and width are honoured, widths outside
|
||||
// the allowed range are clamped, unreadable JSON falls back to a usable
|
||||
// floating dock that saves again, and visiting phone width never overwrites
|
||||
// the desktop choice.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
tolerate(/JSON|SyntaxError/);
|
||||
const dock = h.dockOf(page);
|
||||
|
||||
await h.load(page, go, JSON.stringify({ mode: 'left', w: 500 }));
|
||||
await h.expand(page);
|
||||
let box = await dock.boundingBox();
|
||||
h.near(box.x, 0, 'saved left pin');
|
||||
h.near(box.width, 500, 'saved width');
|
||||
assert.ok((await h.mainRect(page)).x >= 499, 'page did not reflow beside the restored dock');
|
||||
|
||||
await h.load(page, go, JSON.stringify({ mode: 'right', w: -4 }));
|
||||
await h.expand(page);
|
||||
h.near((await dock.boundingBox()).width, 320, 'a negative width clamps to the minimum');
|
||||
|
||||
await h.load(page, go, JSON.stringify({ mode: 'right', w: 9999 }));
|
||||
await h.expand(page);
|
||||
h.near((await dock.boundingBox()).width, 720, 'a huge width clamps to the maximum');
|
||||
|
||||
await h.load(page, go, '{broken');
|
||||
await h.expand(page);
|
||||
box = await dock.boundingBox();
|
||||
assert.ok(box.height < 900 && box.x > 0 && box.x + box.width < 1440, 'unreadable layout did not fall back to a floating dock');
|
||||
await h.composerOf(page).fill('still usable');
|
||||
await h.dragTo(page, 1430);
|
||||
await page.mouse.up();
|
||||
await h.until(async () => (await h.saved(page)).mode === 'right', 'the dock did not save a layout over the unreadable one');
|
||||
await shot('recovered');
|
||||
|
||||
await h.load(page, go, JSON.stringify({ mode: 'left', w: 460 }));
|
||||
const layout = await h.stored(page);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await h.expand(page);
|
||||
box = await dock.boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= 390, 'the dock overflows the phone viewport');
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
assert.equal(await h.stored(page), layout, 'visiting phone width rewrote the saved layout');
|
||||
await h.until(async () => Math.abs((await dock.boundingBox()).width - 460) <= 1, 'the desktop layout did not return after phone width');
|
||||
};
|
||||
@@ -1,41 +0,0 @@
|
||||
// The chat dock at phone width: the bar and the open conversation fit the
|
||||
// screen on a few pages, a stored desktop pin is ignored, the composer stays
|
||||
// reachable, and the dock adds no sideways scroll. The page's own overflow is
|
||||
// phone-overflow's to report, so the dock is measured against the page
|
||||
// without it.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const fits = async (label) => {
|
||||
const { scroll, bare, inner } = await page.evaluate(() => {
|
||||
const root = document.querySelector('aside[aria-label="Chat with Archie"]').parentElement;
|
||||
const scroll = document.documentElement.scrollWidth;
|
||||
root.style.display = 'none';
|
||||
const bare = document.documentElement.scrollWidth;
|
||||
root.style.display = '';
|
||||
return { scroll, bare, inner: window.innerWidth };
|
||||
});
|
||||
assert.ok(scroll <= Math.max(bare, inner), `${label}: the dock widens the page (${scroll} > ${Math.max(bare, inner)})`);
|
||||
const box = await h.dockOf(page).boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= inner, `${label}: dock leaves the screen (${box.x}..${box.x + box.width})`);
|
||||
assert.ok(box.y >= 0 && box.y + box.height <= 844, `${label}: dock leaves the screen vertically`);
|
||||
};
|
||||
|
||||
for (const path of ['/events', '/account', '/org/agents']) {
|
||||
await h.load(page, go, JSON.stringify({ side: 'right', width: 420 }));
|
||||
await go(path);
|
||||
await fits(`${path} collapsed`);
|
||||
await h.expand(page);
|
||||
await fits(`${path} open`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.style.getPropertyValue('--chat-pin-r')), '0px', `${path}: the page reserved room for a pin on a phone`);
|
||||
const composer = await h.composerOf(page).boundingBox();
|
||||
assert.ok(composer.y + composer.height <= 844 && composer.x >= 0 && composer.x + composer.width <= 390, `${path}: composer is off screen`);
|
||||
assert.equal(await h.dividerOf(page).count(), 0, `${path}: a phone shows the pin divider`);
|
||||
await h.composerOf(page).fill('A long unbroken line '.repeat(20));
|
||||
await fits(`${path} long draft`);
|
||||
await shot(path);
|
||||
}
|
||||
};
|
||||
@@ -1,59 +0,0 @@
|
||||
// The # task picker by keyboard: arrows move the selection and wrap, Enter
|
||||
// attaches the selected task, Escape closes the picker and leaves the
|
||||
// conversation open, and an IME confirmation Enter never picks.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
const tasks = [
|
||||
{ id: 1861, title: 'Task picker', status: 'running' },
|
||||
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
|
||||
{ id: 1830, title: 'Filter forge text', status: 'queued' },
|
||||
];
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await page.route('**/api/tasks?*', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(tasks) }));
|
||||
await h.load(page, go);
|
||||
await h.expand(page);
|
||||
const composer = h.composerOf(page);
|
||||
const palette = page.getByRole('listbox', { name: 'Tasks' });
|
||||
const options = palette.getByRole('option');
|
||||
const selected = () => options.evaluateAll((els) => els.findIndex((el) => el.getAttribute('aria-selected') === 'true'));
|
||||
const tags = page.getByRole('list', { name: 'Attached tasks' });
|
||||
|
||||
await composer.fill('Look at #');
|
||||
await options.first().waitFor();
|
||||
assert.equal(await options.count(), 3);
|
||||
assert.equal(await selected(), 0);
|
||||
await shot('picker');
|
||||
|
||||
await composer.press('ArrowDown');
|
||||
assert.equal(await selected(), 1);
|
||||
assert.equal(await composer.getAttribute('aria-activedescendant'), 'slash-palette-option-1');
|
||||
await composer.press('ArrowUp');
|
||||
await composer.press('ArrowUp');
|
||||
assert.equal(await selected(), 2, 'ArrowUp from the first row did not wrap to the last');
|
||||
await composer.press('ArrowDown');
|
||||
assert.equal(await selected(), 0, 'ArrowDown from the last row did not wrap to the first');
|
||||
await composer.press('ArrowDown');
|
||||
|
||||
for (const event of [{ isComposing: true }, { keyCode: 229 }]) {
|
||||
await composer.dispatchEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...event });
|
||||
assert.equal(await options.count(), 3, 'an IME confirmation closed the picker');
|
||||
assert.equal(await tags.count(), 0, 'an IME confirmation attached a task');
|
||||
}
|
||||
|
||||
await composer.press('Enter');
|
||||
await palette.waitFor({ state: 'hidden' });
|
||||
await tags.getByText('#1842').waitFor();
|
||||
assert.equal(await tags.getByRole('listitem').count(), 1);
|
||||
assert.equal(await composer.inputValue(), 'Look at ', 'the # token stayed in the text');
|
||||
assert.ok(await composer.evaluate((el) => document.activeElement === el), 'focus left the composer');
|
||||
|
||||
await composer.fill('Look at #');
|
||||
await options.first().waitFor();
|
||||
await composer.press('Escape');
|
||||
await palette.waitFor({ state: 'hidden' });
|
||||
assert.equal(await h.hideOf(page).isVisible(), true, 'Escape on the picker also closed the conversation');
|
||||
await composer.press('Escape');
|
||||
await h.hideOf(page).waitFor({ state: 'hidden' });
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
// Pinning the chat dock: dragging its header to an edge pins it there and the
|
||||
// page reflows beside it; double-clicking the header unpins it; hiding the
|
||||
// conversation gives the page back its width; the choice survives a reload.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await h.load(page, go);
|
||||
await h.expand(page);
|
||||
const dock = h.dockOf(page);
|
||||
const free = await h.mainRect(page);
|
||||
const floating = await dock.boundingBox();
|
||||
assert.ok(floating.height < 900, 'the dock starts as a floating card');
|
||||
|
||||
await h.dragTo(page, 1430);
|
||||
await page.mouse.up();
|
||||
await h.until(async () => (await h.saved(page)).side === 'right', 'dragging to the right edge did not pin right');
|
||||
const right = await dock.boundingBox();
|
||||
h.near(right.x + right.width, 1440, 'right pin touches the right edge');
|
||||
h.near(right.height, 900, 'a pinned dock is full height');
|
||||
const reflowed = await h.mainRect(page);
|
||||
assert.ok(reflowed.x + reflowed.width <= right.x + 1, `page content runs under the pinned dock: ${reflowed.x + reflowed.width} > ${right.x}`);
|
||||
assert.ok(reflowed.width < free.width, 'the page did not give up any width');
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), 'pinning made the page scroll sideways');
|
||||
await shot('pinned-right');
|
||||
|
||||
await page.reload();
|
||||
await h.expand(page);
|
||||
await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'the right pin did not survive a reload');
|
||||
|
||||
await h.hideOf(page).click();
|
||||
await h.until(async () => Math.abs((await h.mainRect(page)).width - free.width) <= 1, 'hiding the conversation kept the page narrowed');
|
||||
await h.expand(page);
|
||||
await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'reopening did not restore the pin');
|
||||
|
||||
const strip = await h.grip(page);
|
||||
await page.mouse.dblclick(strip.x, strip.y);
|
||||
await h.until(async () => (await h.saved(page)).side === null, 'double-clicking the header did not unpin');
|
||||
assert.ok((await dock.boundingBox()).height < 900, 'an unpinned dock is a floating card again');
|
||||
h.near((await h.mainRect(page)).width, free.width, 'the page returns to its full width');
|
||||
|
||||
await h.dragTo(page, 10);
|
||||
await page.mouse.up();
|
||||
await h.until(async () => (await h.saved(page)).side === 'left', 'dragging to the left edge did not pin left');
|
||||
const left = await dock.boundingBox();
|
||||
h.near(left.x, 0, 'left pin touches the left edge');
|
||||
assert.ok((await h.mainRect(page)).x >= left.x + left.width - 1, 'page content runs under the left-pinned dock');
|
||||
await shot('pinned-left');
|
||||
|
||||
await page.mouse.dblclick((await h.grip(page)).x, (await h.grip(page)).y);
|
||||
await h.until(async () => (await h.saved(page)).side === null, 'double-clicking did not unpin the left pin');
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
// The pinned dock's divider is a keyboard separator: the arrow toward the
|
||||
// page widens the dock, the arrow away narrows it, both stop at the allowed
|
||||
// range, and the width is saved.
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('./helpers/chat-dock.cjs');
|
||||
|
||||
const width = (page) => h.dockOf(page).boundingBox().then((b) => Math.round(b.width));
|
||||
const value = (page) => h.dividerOf(page).getAttribute('aria-valuenow').then(Number);
|
||||
|
||||
module.exports = async ({ page, go }) => {
|
||||
const divider = h.dividerOf(page);
|
||||
for (const [side, grow, shrink] of [['right', 'ArrowLeft', 'ArrowRight'], ['left', 'ArrowRight', 'ArrowLeft']]) {
|
||||
await h.load(page, go, JSON.stringify({ side, width: 420 }));
|
||||
await h.expand(page);
|
||||
await divider.focus();
|
||||
assert.equal(await value(page), 420);
|
||||
assert.equal(await divider.getAttribute('aria-valuemin'), '320');
|
||||
|
||||
await page.keyboard.press(grow);
|
||||
await h.until(async () => (await value(page)) === 436 && (await width(page)) === 436, `${side}: ${grow} did not widen by 16`);
|
||||
await page.keyboard.press(shrink);
|
||||
await page.keyboard.press(shrink);
|
||||
await h.until(async () => (await value(page)) === 404 && (await width(page)) === 404, `${side}: ${shrink} did not narrow by 16`);
|
||||
assert.equal((await h.saved(page)).width, 404, `${side}: the width was not saved`);
|
||||
|
||||
await page.keyboard.press('ArrowUp');
|
||||
assert.equal(await value(page), 404, `${side}: a vertical arrow resized the dock`);
|
||||
|
||||
for (let i = 0; i < 12; i++) await page.keyboard.press(shrink);
|
||||
await h.until(async () => (await width(page)) === 320, `${side}: the dock narrowed past its minimum`);
|
||||
assert.equal(await value(page), 320);
|
||||
|
||||
for (let i = 0; i < 30; i++) await page.keyboard.press(grow);
|
||||
await h.until(async () => (await width(page)) === 720, `${side}: the dock widened past its maximum`);
|
||||
assert.equal(await value(page), 720);
|
||||
}
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
// Real local API records; workflow edits stay unsaved and the test agent retires.
|
||||
const assert = require('node:assert/strict');
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
const base = process.env.ARCHIE_E2E_URL || 'http://localhost:5173';
|
||||
const headers = { 'X-Archie-CSRF': '1', Origin: base };
|
||||
let agent;
|
||||
const command = async (name, display_name = '') => {
|
||||
const response = await page.request.post(`${base}/api/identities/${agent.id}/${name}`, {
|
||||
headers, data: { expected_version: agent.version, display_name },
|
||||
});
|
||||
assert.equal(response.ok(), true, await response.text());
|
||||
agent = await response.json();
|
||||
};
|
||||
const openSettings = async () => {
|
||||
await go('/workflows/implement');
|
||||
const runPicker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
if (await runPicker.count()) { await runPicker.click(); await page.getByRole('option', { name: 'Definition', exact: true }).click(); }
|
||||
await page.locator('.vue-flow__node').filter({ hasText: 'Workflow' }).first().click();
|
||||
return page.getByRole('combobox', { name: 'Execution identity', exact: true });
|
||||
};
|
||||
try {
|
||||
const created = await page.request.post(`${base}/api/identities`, {
|
||||
headers, data: { display_name: `E2E execution agent ${Date.now()}`, kind: 'bot' },
|
||||
});
|
||||
assert.equal(created.ok(), true, await created.text());
|
||||
agent = await created.json();
|
||||
const trigger = await openSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
|
||||
await trigger.click();
|
||||
await page.getByRole('option', { name: agent.display_name, exact: true }).click();
|
||||
assert.match(await trigger.innerText(), new RegExp(agent.display_name));
|
||||
await shot('named-execution-identity');
|
||||
await command('rename', agent.display_name + ' renamed');
|
||||
await page.reload();
|
||||
const renamed = await openSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
|
||||
await renamed.click();
|
||||
await page.getByRole('option', { name: agent.display_name, exact: true }).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await command('suspend');
|
||||
await page.reload();
|
||||
const suspended = await openSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
|
||||
await suspended.click();
|
||||
assert.equal(await page.getByRole('option', { name: agent.display_name, exact: true }).and(page.locator(':not([data-disabled])')).count(), 0);
|
||||
} finally {
|
||||
if (agent && agent.lifecycle !== 'retired') await command('retire');
|
||||
}
|
||||
};
|
||||
@@ -1,103 +0,0 @@
|
||||
// Shared setup for the audit-* checks: feed request tracking, URL waits,
|
||||
// and the export download-or-popup accept. One behaviour per check module;
|
||||
// this file holds only what several of them need.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const DEFAULT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function isAudit(u) {
|
||||
return u.pathname === '/api/audit';
|
||||
}
|
||||
|
||||
// Installs request tracking on a fresh check page. Returns the helpers the
|
||||
// audit checks share; a check destructures only what it uses.
|
||||
function trackAudit(page) {
|
||||
page.setDefaultTimeout(10000);
|
||||
const auditRequests = [];
|
||||
page.on('request', (request) => {
|
||||
try {
|
||||
const url = new URL(request.url());
|
||||
if (isAudit(url) || url.pathname === '/api/audit/export') auditRequests.push(url);
|
||||
} catch {
|
||||
// A non-URL request cannot be an audit call.
|
||||
}
|
||||
});
|
||||
let loads = 0;
|
||||
page.on('load', () => (loads += 1));
|
||||
|
||||
const requestMatching = async (action, predicate, timeout = 6000) => {
|
||||
const waiter = page
|
||||
.waitForRequest(
|
||||
(request) => {
|
||||
try {
|
||||
const url = new URL(request.url());
|
||||
return (isAudit(url) || url.pathname === '/api/audit/export') && predicate(url);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
{ timeout },
|
||||
)
|
||||
.catch(() => null);
|
||||
await action();
|
||||
return waiter;
|
||||
};
|
||||
|
||||
const waitForUrl = (predicate, timeout = 8000) =>
|
||||
page.waitForURL((url) => predicate(new URL(url)), { timeout });
|
||||
|
||||
const lastRequest = () => auditRequests[auditRequests.length - 1] || null;
|
||||
const loadCount = () => loads;
|
||||
|
||||
return { requestMatching, waitForUrl, lastRequest, loadCount };
|
||||
}
|
||||
|
||||
// Export resolves its window at click time and opens a tab. A successful
|
||||
// export arrives as an attachment download; a failed one stays visible in
|
||||
// that tab, so the check accepts either and reads the response from it.
|
||||
async function exportOnce(page, fail, label, extension) {
|
||||
await page.getByRole('button', { name: 'Export', exact: true }).click();
|
||||
const item = page.getByRole('menuitem', { name: label, exact: true });
|
||||
await item.waitFor();
|
||||
const downloadP = page.waitForEvent('download', { timeout: 15000 }).then((download) => ({ download })).catch(() => null);
|
||||
const popupP = page.waitForEvent('popup', { timeout: 15000 }).then((popup) => ({ popup })).catch(() => null);
|
||||
await item.click();
|
||||
const settled = await Promise.race([downloadP, popupP]);
|
||||
if (!settled) {
|
||||
fail(`${label} export neither downloaded nor opened a tab`);
|
||||
return null;
|
||||
}
|
||||
if (settled.popup) {
|
||||
await settled.popup.waitForLoadState('load').catch(() => {});
|
||||
const url = new URL(settled.popup.url());
|
||||
assert.equal(url.pathname, '/api/audit/export', `${label} opened ${url.href}`);
|
||||
assert.equal(url.searchParams.get('format'), extension);
|
||||
assert.ok(url.searchParams.get('from'), `${label} export has no explicit start`);
|
||||
assert.ok(url.searchParams.get('to'), `${label} export has no explicit end`);
|
||||
const response = await page.request.get(url.href);
|
||||
const body = await response.text();
|
||||
if (response.status() !== 200) {
|
||||
fail(`${label} export failed (${response.status()}): ${body.slice(0, 200)}`);
|
||||
return null;
|
||||
}
|
||||
if (!new RegExp(`attachment;.*\\.${extension}`).test(response.headers()['content-disposition'] || '')) {
|
||||
fail(`${label} export opened a tab without an attachment filename`);
|
||||
return null;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
if (!new RegExp(`\\.${extension}$`).test(settled.download.suggestedFilename())) {
|
||||
fail(`${label} export did not download a .${extension} file`);
|
||||
return null;
|
||||
}
|
||||
const failure = await settled.download.failure();
|
||||
if (failure) {
|
||||
fail(`${label} download failed: ${failure}`);
|
||||
return null;
|
||||
}
|
||||
const saved = await settled.download.path();
|
||||
return saved ? fs.readFileSync(saved, 'utf8') : '';
|
||||
}
|
||||
|
||||
module.exports = { DEFAULT_WINDOW_MS, isAudit, trackAudit, exportOnce };
|
||||
@@ -1,63 +0,0 @@
|
||||
// Shared handles for the chat dock checks: the dock's own storage key, its
|
||||
// landmarks, and the pointer gestures that pin it.
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const KEY = 'archie.chat.dock.v2';
|
||||
|
||||
const dockOf = (page) => page.getByRole('complementary', { name: 'Chat with Archie' });
|
||||
const composerOf = (page) => page.getByRole('combobox', { name: 'Message Archie', exact: true });
|
||||
const hideOf = (page) => page.getByRole('button', { name: 'Hide conversation' });
|
||||
const dividerOf = (page) => page.getByRole('separator', { name: 'Resize chat' });
|
||||
|
||||
const stored = (page) => page.evaluate((key) => localStorage.getItem(key), KEY);
|
||||
const saved = async (page) => JSON.parse(await stored(page));
|
||||
|
||||
// Loads /events with the given stored layout (a string, or null for none).
|
||||
async function load(page, go, layout = null) {
|
||||
await go('/events');
|
||||
await page.evaluate(([key, value]) => (value === null ? localStorage.removeItem(key) : localStorage.setItem(key, value)), [KEY, layout]);
|
||||
await go('/events');
|
||||
}
|
||||
|
||||
// Focusing the composer is how the operator opens the conversation.
|
||||
async function expand(page) {
|
||||
await composerOf(page).focus();
|
||||
await hideOf(page).waitFor();
|
||||
}
|
||||
|
||||
// Retries an assertion until it holds: the dock settles over a few frames.
|
||||
async function until(check, message, timeout = 5000) {
|
||||
const end = Date.now() + timeout;
|
||||
let last;
|
||||
for (;;) {
|
||||
try {
|
||||
const ok = await check();
|
||||
if (ok) return;
|
||||
last = ok;
|
||||
} catch (e) {
|
||||
last = e;
|
||||
}
|
||||
if (Date.now() > end) throw new Error(`${message}${last instanceof Error ? `: ${last.message}` : ''}`);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
|
||||
const near = (a, b, message, tolerance = 1) => assert.ok(Math.abs(a - b) <= tolerance, `${message}: ${a} is not within ${tolerance} of ${b}`);
|
||||
|
||||
// The empty strip at the top of the header, where a drag starts.
|
||||
async function grip(page) {
|
||||
const box = await dockOf(page).boundingBox();
|
||||
return { x: box.x + box.width / 2, y: box.y + 8 };
|
||||
}
|
||||
|
||||
async function dragTo(page, x, steps = 10) {
|
||||
const from = await grip(page);
|
||||
await page.mouse.move(from.x, from.y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x, from.y, { steps });
|
||||
return from;
|
||||
}
|
||||
|
||||
const mainRect = (page) => page.locator('#main-content').boundingBox();
|
||||
|
||||
module.exports = { KEY, dockOf, composerOf, hideOf, dividerOf, stored, saved, load, expand, until, near, grip, dragTo, mainRect };
|
||||
@@ -1,18 +0,0 @@
|
||||
// Shared by the org-* and setup checks: acting in a seeded org and the 404s a
|
||||
// fresh org's pages are built to survive.
|
||||
const ORG = { home: 'org-sys', beta: 'org-beta', outsider: 'org-gamma' };
|
||||
|
||||
// A new org has written no documents, and the instance-only reads answer
|
||||
// not found outside the system org.
|
||||
const ABSENT = /status of 404.*\/api\/(control-plane|schedules|identities)/;
|
||||
|
||||
// Selects an org the way the topbar does, over the page's own session.
|
||||
async function selectOrg(page, id) {
|
||||
const origin = new URL(page.url() === 'about:blank' ? 'http://localhost:5173' : page.url()).origin;
|
||||
return page.request.put(`${origin}/api/orgs/current`, {
|
||||
headers: { 'X-Archie-CSRF': '1', Origin: origin },
|
||||
data: { id },
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { ORG, ABSENT, selectOrg };
|
||||
@@ -1,19 +0,0 @@
|
||||
// The dashboard's static routes, read from the router source so a new page is
|
||||
// swept automatically. Parameterised and redirect routes are skipped.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function staticRoutes() {
|
||||
const src = fs.readFileSync(path.join(__dirname, '../../../ui/src/router/index.ts'), 'utf8');
|
||||
const out = [];
|
||||
for (const line of src.split('\n')) {
|
||||
if (/redirect:/.test(line)) continue;
|
||||
const m = line.match(/path: "([^"]*)"/);
|
||||
if (!m || m[1].includes(':')) continue;
|
||||
if (m[1].startsWith('/')) out.push(m[1]);
|
||||
else if (m[1]) out.push('/org/' + m[1]);
|
||||
}
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
module.exports = { staticRoutes };
|
||||
@@ -1,103 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const org = { id: 'example-org', name: 'Example', version: 1 };
|
||||
const user = { id: '11111111-1111-4111-8111-111111111111', name: 'Alex Rivera', kind: 'user' };
|
||||
const other = { id: '22222222-2222-4222-8222-222222222222', name: user.name, kind: 'user' };
|
||||
const bot = { id: '33333333-3333-4333-8333-333333333333', name: 'Nightly bot', kind: 'bot' };
|
||||
const missing = { id: '44444444-4444-4444-8444-444444444444' };
|
||||
const target = { id: '55555555-5555-4555-8555-555555555555', name: 'Riley Singh', kind: 'user' };
|
||||
|
||||
const member = (actor) => ({
|
||||
identity_id: actor.id, display_name: actor.name, kind: actor.kind, role: 'viewer', status: 'active',
|
||||
});
|
||||
|
||||
// An audit actor link must resolve the exact user, not another member with the same name.
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
const at = new Date().toISOString();
|
||||
const records = [user, bot, missing].map((actor, i) => ({
|
||||
id: `audit-${i}`, at, category: 'runtime', kind: 'task', action: 'task.retry', severity: 'info', outcome: 'success',
|
||||
actor, summary: `Task audit ${i}`,
|
||||
target: i === 1 ? { kind: 'identity', id: target.id, label: target.name } : { kind: 'task', id: String(i + 1) },
|
||||
}));
|
||||
await page.route('**/api/**', async (route) => {
|
||||
const { pathname: path, searchParams } = new URL(route.request().url());
|
||||
const version = Number(searchParams.get('version')) || 2;
|
||||
const fixtures = {
|
||||
'/api/auth/status': { user: { id: 'operator', display_name: 'Operator' }, setup_required: false },
|
||||
'/api/capabilities': { sections: { settings: false } },
|
||||
'/api/orgs': { current: org.id, orgs: [org] },
|
||||
[`/api/orgs/${org.id}/members`]: { members: [member(user), { ...member(other), status: 'suspended' }, member(target)] },
|
||||
[`/api/orgs/${org.id}/member-candidates`]: { identities: [] },
|
||||
[`/api/orgs/${org.id}/history`]: { events: [{ id: 'history', kind: 'org', old_name: 'Previous', new_name: org.name, at, actor_id: user.id, actor_name: user.name }] },
|
||||
'/api/audit': { records },
|
||||
'/api/access/decisions': { decisions: [{ at, principal: user.id, outcome: 'allowed', action: 'read', kind: 'task', resource: '1', level: 'org', policies: [], count: 1 }] },
|
||||
'/api/alerts': { alerts: [] },
|
||||
'/api/proposals/example': { id: 'example', title: 'Example proposal', kind: 'policy', state: 'rejected', proposed_by_id: bot.id, answered_by_id: user.id, actions: [], created_at: at },
|
||||
'/api/runs/example': {
|
||||
run: { id: 'example', workflow: 'Example run', state: 'succeeded', created_at: at, finished_at: at }, stages: [],
|
||||
actions: [{ decision: { id: 'decision', level: 'ask', action: { connector: 'example', name: 'act' }, at, refused_by: 'policy-rule' }, approval: { state: 'approved', answered_by: user.name, answered_by_id: user.id, answered_via: 'web' } }],
|
||||
},
|
||||
'/api/approvals': [],
|
||||
'/api/policies/hard-rules': { version, body: '// example', created_at: at, created_by: user.id, versions: [{ version: 2 }, { version: 1 }] },
|
||||
'/api/policies/change-request': { version: 1, body: '', created_at: at, created_by: '00000000-0000-5000-8000-000000000001' },
|
||||
'/api/workflows': [{ id: 'workflow', name: 'Example workflow', version: 1, body: 'steps: []', created_by: user.id, created_at: at, enabled: true }],
|
||||
'/api/workflow-drafts': [],
|
||||
'/api/workflow-stats': [],
|
||||
'/api/triggers': [],
|
||||
};
|
||||
if (path === '/api/stream') return route.fulfill({ status: 200, contentType: 'text/event-stream', body: ': ready\n\n' });
|
||||
await route.fulfill({ json: fixtures[path] ?? {} });
|
||||
});
|
||||
await go('/org/audit');
|
||||
await page.getByText(user.name, { exact: true }).filter({ visible: true }).waitFor();
|
||||
const link = page.getByRole('link', { name: user.name, exact: true });
|
||||
assert.equal(await link.count(), 1, 'the visible audit user name should be a link');
|
||||
assert.equal(await page.getByRole('link', { name: bot.name, exact: true }).count(), 0);
|
||||
assert.equal(await page.getByRole('link', { name: missing.id, exact: true }).count(), 0);
|
||||
const targetLink = page.getByRole('link', { name: target.name, exact: true });
|
||||
const targetHref = await targetLink.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
assert.equal(targetHref && new URL(targetHref, page.url()).searchParams.get('member'), target.id, 'an audit identity target should link to its user');
|
||||
await shot('audit-actor');
|
||||
await link.click();
|
||||
await page.waitForURL((url) => url.pathname === '/org/members' && url.searchParams.get('member') === user.id);
|
||||
await page.getByRole('heading', { name: 'Members' }).waitFor();
|
||||
const row = page.getByRole('row').filter({ hasText: user.name });
|
||||
await row.first().waitFor();
|
||||
assert.equal(await row.count(), 1);
|
||||
assert.match(await row.innerText(), /\bactive\b/);
|
||||
await shot('target-member');
|
||||
await page.getByRole('link', { name: 'All members' }).click();
|
||||
await page.getByRole('button', { name: `Suspend ${user.name}` }).waitFor();
|
||||
assert.equal(await row.count(), 2);
|
||||
await go(`/org/members?org=${org.id}&member=${missing.id}`);
|
||||
await page.getByText('Member not found in this organisation', { exact: true }).waitFor();
|
||||
|
||||
const unresolved = [];
|
||||
for (const [path, ready] of [
|
||||
['/proposals/example', () => page.getByText('Rejected by', { exact: true }).waitFor()],
|
||||
['/runs/example', () => page.getByText('Refused by policy-rule', { exact: true }).waitFor()],
|
||||
['/controls', () => page.getByRole('textbox', { name: 'Hard rules', exact: true }).waitFor()],
|
||||
['/org', () => page.getByRole('heading', { name: 'Name changes' }).waitFor()],
|
||||
['/org/decisions', () => page.getByRole('cell', { name: 'Allowed' }).waitFor()],
|
||||
['/workflows', () => page.getByRole('link', { name: 'Example workflow', exact: true }).waitFor()],
|
||||
]) {
|
||||
await go(path);
|
||||
await ready();
|
||||
const credit = page.getByRole('link', { name: user.name, exact: true });
|
||||
const href = await credit.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
if (!href || new URL(href, page.url()).searchParams.get('member') !== user.id) unresolved.push(path);
|
||||
assert.equal(await page.getByRole('link', { name: bot.id, exact: true }).count(), 0);
|
||||
assert.equal(await page.getByRole('link', { name: 'policy-rule', exact: true }).count(), 0);
|
||||
if (path === '/controls') {
|
||||
await page.getByText('System', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByText('00000000-0000-5000-8000-000000000001', { exact: true }).count(), 0);
|
||||
assert.equal(await page.getByRole('link', { name: 'System', exact: true }).count(), 0);
|
||||
await page.getByRole('combobox', { name: 'Hard rules version' }).click();
|
||||
await page.getByRole('option', { name: 'Version 1' }).click();
|
||||
await page.getByRole('textbox', { name: 'Hard rules, version 1' }).waitFor();
|
||||
const oldHref = await credit.getAttribute('href', { timeout: 1500 }).catch(() => null);
|
||||
if (!oldHref || new URL(oldHref, page.url()).searchParams.get('member') !== user.id) unresolved.push('/controls (previous version)');
|
||||
}
|
||||
}
|
||||
assert.deepEqual(unresolved, [], 'attribution should display the user name linked by ID');
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
const assert=require('node:assert/strict');
|
||||
module.exports=async({page,go,shot,tolerate})=>{
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.route('**/api/access/policies',async route=>{await new Promise(r=>setTimeout(r,2200));await route.continue()});
|
||||
await go('/access/policies');
|
||||
assert.equal(await page.getByText('No policies yet.',{exact:true}).count(),0);
|
||||
await page.getByText('Loading policies…',{exact:true}).waitFor({state:'hidden'});
|
||||
await page.route('**/api/tasks?**',async route=>{
|
||||
if(new URL(route.request().url()).searchParams.has('workflow')) await route.fulfill({status:200,contentType:'application/json',body:'unreadable response'});
|
||||
else await route.continue();
|
||||
});
|
||||
await go('/workflows/implement');
|
||||
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor();
|
||||
await page.getByRole('tab',{name:/^Runs/}).click();
|
||||
assert.equal(await page.getByText('No runs yet',{exact:true}).count(),0);
|
||||
await page.unroute('**/api/tasks?**');
|
||||
await page.getByRole('button',{name:'Retry runs',exact:true}).click();
|
||||
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor({state:'hidden'});
|
||||
await shot('recovered');
|
||||
// A failed list read is an error, never the empty state (#1767): force each
|
||||
// page's list API to 500 and check its empty-state copy stays hidden.
|
||||
const failList = async (pattern,path,emptyTexts,errorSel='[role=alert]')=>{
|
||||
await page.route(pattern,route=>route.fulfill({status:200,contentType:'application/json',body:'unreadable response'}));
|
||||
await go(path);
|
||||
await page.locator(errorSel).first().waitFor();
|
||||
for(const text of emptyTexts) assert.equal(await page.getByText(text,{exact:true}).count(),0,`${path} shows its empty state ("${text}") while the list read fails`);
|
||||
await page.unroute(pattern);
|
||||
};
|
||||
await failList('**/api/tasks*','/tasks',['No tasks yet'],'text=Archie is not responding');
|
||||
await failList('**/api/captures*','/events',['No captures yet']);
|
||||
await failList('**/api/event-types*','/events',['No event types yet']);
|
||||
await failList('**/api/tokens*','/account',['No tokens yet']);
|
||||
await failList('**/api/access/policies*','/org/policies',['No policies yet']);
|
||||
await shot('failed-reads-show-errors');
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
// The save response is mocked; this checks the page's save path without changing models.
|
||||
const assert=require('node:assert/strict');
|
||||
module.exports=async({page,go,shot})=>{
|
||||
let submitted;
|
||||
await page.route('**/api/control-plane/resources/model-aliases/commands/replace',async route=>{
|
||||
submitted=route.request().postDataJSON();
|
||||
await route.fulfill({json:{resource:{kind:'model-aliases',version:submitted.expected_version+1,value:submitted.value}}});
|
||||
});
|
||||
await go('/access/models');
|
||||
await page.getByLabel('New alias',{exact:true}).fill('e2e-test');
|
||||
await page.getByRole('button',{name:'Add alias',exact:true}).click();
|
||||
await page.getByLabel('e2e-test',{exact:true}).fill('test/model');
|
||||
await page.getByRole('button',{name:'Review and save',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Save',exact:true}).click();
|
||||
await page.getByRole('heading',{name:/^Review \d/}).waitFor({state:'hidden'});
|
||||
assert.equal(submitted?.value['e2e-test'],'test/model');
|
||||
await shot('saved');
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
// The organisation pages: each loads its form in the selected org, and the old
|
||||
// settings audit route lands on the organisation's audit page.
|
||||
const assert = require('node:assert/strict');
|
||||
const { trackAudit } = require('./helpers/audit-helpers.cjs');
|
||||
|
||||
const PAGES = [
|
||||
{ path: '/org/channels', heading: 'Channels', text: 'Chat session defaults' },
|
||||
{ path: '/org/scheduling-policy', heading: 'Scheduling policy', text: 'Retries and polling' },
|
||||
{ path: '/org/alerts', heading: 'Alert webhook', text: 'Webhook severity' },
|
||||
];
|
||||
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
for (const { path, heading, text } of PAGES) {
|
||||
await go(path);
|
||||
await page.getByRole('heading', { name: heading, exact: true }).waitFor();
|
||||
await page.getByText(text, { exact: true }).first().waitFor();
|
||||
assert.equal(new URL(page.url()).pathname, path);
|
||||
await shot(path);
|
||||
}
|
||||
|
||||
trackAudit(page);
|
||||
await go('/org/audit');
|
||||
await page.getByRole('heading', { name: 'Audit', exact: true }).first().waitFor();
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
await shot('/org/audit');
|
||||
await go('/settings/audit?since=7d');
|
||||
assert.equal(new URL(page.url()).pathname, '/org/audit', '/settings/audit did not redirect');
|
||||
assert.equal(new URL(page.url()).searchParams.get('since'), '7d', 'redirect dropped the query');
|
||||
await page.locator('[data-row-key]').first().waitFor();
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
// A non-system org can arm a schedule trigger: the schedule source's built-in
|
||||
// mapping is readable there, so a binding on it is accepted. The editor's own
|
||||
// schedule list is instance-only, so the binding is written over the API.
|
||||
const assert = require('node:assert/strict');
|
||||
const { ORG, ABSENT, selectOrg } = require('./helpers/org-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
tolerate(ABSENT);
|
||||
await go('/');
|
||||
assert.equal((await selectOrg(page, ORG.beta)).status(), 204);
|
||||
await go('/workflows/feasibility');
|
||||
const origin = new URL(page.url()).origin;
|
||||
const headers = { 'X-Archie-CSRF': '1', Origin: origin };
|
||||
const created = await page.request.post(`${origin}/api/bindings`, {
|
||||
headers,
|
||||
data: {
|
||||
name: 'e2e schedule trigger', matcher: { source: 'schedule' }, mapping_id: 'schedule-fired',
|
||||
filter: 'schedule_id == "issue-discovery"', workflow: 'feasibility', repo_param: '', owner: '', repo: '', inputs: {},
|
||||
},
|
||||
});
|
||||
try {
|
||||
assert.equal(created.status(), 201, `binding on the built-in schedule mapping refused: ${await created.text()}`);
|
||||
const binding = await created.json();
|
||||
assert.equal(binding.org_id, ORG.beta);
|
||||
await go('/workflows/feasibility');
|
||||
await page.getByText('Starts when').first().waitFor();
|
||||
await shot('beta-trigger');
|
||||
} finally {
|
||||
if (created.ok()) await page.request.delete(`${origin}/api/bindings/${(await created.json()).id}`, { headers });
|
||||
}
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
// The sidebar org switcher: choosing a member org reloads the dashboard into it,
|
||||
// Tasks and Workflows then show only that org's work, and the API refuses an
|
||||
// org the caller is not a member of.
|
||||
const assert = require('node:assert/strict');
|
||||
const { ORG, ABSENT, selectOrg } = require('./helpers/org-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
tolerate(ABSENT);
|
||||
await go('/tasks');
|
||||
await page.getByText('Fix flaky login test').first().waitFor();
|
||||
const picker = page.getByRole('button', { name: /^Organisation: / });
|
||||
await picker.waitFor();
|
||||
const offered = await (async () => {
|
||||
await picker.click();
|
||||
await page.getByRole('menuitem').first().waitFor();
|
||||
const names = (await page.getByRole('menuitem').allInnerTexts()).map(t => t.trim().split('\n').pop().trim());
|
||||
await page.keyboard.press('Escape');
|
||||
return names;
|
||||
})();
|
||||
assert.deepEqual(offered.sort(), ['Beta', 'System'], 'selector must offer exactly the orgs the caller belongs to');
|
||||
await go('/workflows');
|
||||
await page.getByText('Parked', { exact: true }).first().waitFor();
|
||||
await shot('home-org-workflows');
|
||||
|
||||
await picker.click();
|
||||
await Promise.all([page.waitForEvent('load'), page.getByRole('menuitem', { name: 'Beta' }).click()]);
|
||||
await settled('/workflows');
|
||||
await page.getByRole('button', { name: /^Organisation: / }).waitFor();
|
||||
assert.equal(await page.getByText('Parked', { exact: true }).count(), 0, 'workflow run counts leaked across orgs');
|
||||
await shot('beta-workflows');
|
||||
await go('/tasks');
|
||||
await page.getByText('No tasks yet').waitFor();
|
||||
assert.equal(await page.getByText('Fix flaky login test').count(), 0, 'tasks leaked across orgs');
|
||||
await shot('beta-tasks');
|
||||
|
||||
// The selector never writes an org the caller is outside of; the server decides.
|
||||
const refused = await selectOrg(page, ORG.outsider);
|
||||
assert.equal(refused.status(), 403, 'selecting a non-member org must be forbidden');
|
||||
await go('/tasks');
|
||||
await page.getByText('No tasks yet').waitFor();
|
||||
assert.equal((await selectOrg(page, ORG.home)).status(), 204);
|
||||
await go('/tasks');
|
||||
await page.getByText('Fix flaky login test').first().waitFor();
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
// Phone-width sweep of the views the November audit flagged (#1757): at
|
||||
// 390x844 each must fit without horizontal scroll or clipped controls. The
|
||||
// topbar (with its instance badge) is on every page; /account holds the
|
||||
// token form, /org/agents the agent rows and the grants card, /events the
|
||||
// sources table, the event-type rule editor and the mapping editor dialog.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const assertNoOverflow = async (label) => {
|
||||
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
innerWidth: window.innerWidth,
|
||||
}));
|
||||
if (scrollWidth > innerWidth) {
|
||||
fail(`${label} overflows 390px: scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
|
||||
}
|
||||
};
|
||||
|
||||
const visit = async (path, label, waitFor) => {
|
||||
await go(path);
|
||||
if (waitFor) await settled(waitFor);
|
||||
await assertNoOverflow(label);
|
||||
await shot(label);
|
||||
};
|
||||
|
||||
await visit('/account', 'account-tokens', 'text=API tokens');
|
||||
await visit('/org/agents', 'org-agents', 'text=Credential grants');
|
||||
|
||||
await go('/events');
|
||||
await settled('[role=tab]');
|
||||
await assertNoOverflow('events');
|
||||
await shot('events');
|
||||
|
||||
// The seeded event type's rule editor (RuleEditor's condition row) opens
|
||||
// from the Edit button on its row.
|
||||
const editType = page.locator('button[aria-label^="Edit "]').first();
|
||||
if (await editType.count()) {
|
||||
await editType.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('event-type rule editor');
|
||||
await shot('rule-editor');
|
||||
await page.keyboard.press('Escape');
|
||||
await settled();
|
||||
}
|
||||
|
||||
// The mappings tab's editor dialog carries the payload tree.
|
||||
await page.getByRole('tab', { name: 'Map' }).click();
|
||||
await settled('text=New mapping');
|
||||
await assertNoOverflow('mappings list');
|
||||
const editMapping = page.locator('button', { hasText: 'Edit' }).first();
|
||||
if (await editMapping.count()) {
|
||||
await editMapping.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('mapping editor dialog');
|
||||
await shot('mapping-editor');
|
||||
}
|
||||
|
||||
// Every static route fits 390px (#1767): horizontal scroll fails.
|
||||
for (const r of staticRoutes()) {
|
||||
await visit(r, `route ${r}`, null);
|
||||
}
|
||||
};
|
||||
@@ -1,80 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, fail, shot }) => {
|
||||
const opener = page.getByRole('button', { name: 'New policy', exact: true });
|
||||
const editor = page.getByRole('dialog', { name: /New policy|draft-policy/ });
|
||||
const confirm = page.getByRole('alertdialog', { name: 'Discard unsaved changes?' });
|
||||
const id = editor.getByRole('textbox', { name: 'Policy id' });
|
||||
const cedar = editor.getByRole('textbox', { name: 'Cedar policy' });
|
||||
const dismissals = {
|
||||
Close: () => editor.getByRole('button', { name: 'Close', exact: true }).click({ timeout: 2000 }),
|
||||
Cancel: () => editor.getByRole('button', { name: 'Cancel', exact: true }).click({ timeout: 2000 }),
|
||||
Escape: () => page.keyboard.press('Escape'),
|
||||
Backdrop: () => page.mouse.click(8, 8),
|
||||
};
|
||||
const focused = (field) => field.evaluate(el => el === document.activeElement);
|
||||
const closed = async () => {
|
||||
await page.locator('[role="alertdialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
await page.locator('[role="dialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
assert.ok(await focused(opener), 'focus did not return to New policy');
|
||||
};
|
||||
const cases = async (scenario, rows, run) => {
|
||||
for (const row of rows) {
|
||||
// A failed modal must not block the next independently tested path.
|
||||
await go('/org/policies');
|
||||
try { await run(row); } catch (error) { fail(`${scenario} ${row}: ${error.message}`); }
|
||||
}
|
||||
};
|
||||
|
||||
await cases('Mobile', ['focus clearance'], async () => {
|
||||
await page.setViewportSize({ width: 390, height: 600 });
|
||||
await opener.click();
|
||||
for (const field of [id, cedar]) {
|
||||
// Opening focuses the ID; Tab past the level selector to reach Cedar.
|
||||
if (field === cedar) {
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Tab');
|
||||
}
|
||||
assert.ok(await focused(field), 'keyboard focus did not reach the policy field');
|
||||
const { name, clearance, ring } = await field.evaluate(el => {
|
||||
const form = el.closest('form');
|
||||
const bounds = form.getBoundingClientRect();
|
||||
const field = el.getBoundingClientRect();
|
||||
const css = getComputedStyle(el);
|
||||
return {
|
||||
name: el.getAttribute('aria-label'),
|
||||
clearance: Math.min(field.left - bounds.left, field.top - bounds.top,
|
||||
bounds.left + form.clientWidth - field.right, bounds.top + form.clientHeight - field.bottom),
|
||||
ring: Math.max(3, parseFloat(css.outlineWidth) + parseFloat(css.outlineOffset)),
|
||||
};
|
||||
});
|
||||
if (clearance + 0.1 < ring) fail(`${name} focus ring: ${clearance}px clearance for ${ring}px ring`);
|
||||
await shot(name);
|
||||
}
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
|
||||
await cases('Clean', Object.keys(dismissals), async (action) => {
|
||||
await opener.click();
|
||||
await dismissals[action]();
|
||||
await closed();
|
||||
});
|
||||
|
||||
await cases('Dirty', Object.keys(dismissals), async (action) => {
|
||||
await opener.click();
|
||||
await id.pressSequentially('draft-policy');
|
||||
await dismissals[action]();
|
||||
const keep = confirm.getByRole('button', { name: 'Keep editing' });
|
||||
await keep.waitFor({ timeout: 2000 });
|
||||
if (action === 'Escape') await page.keyboard.press('Escape');
|
||||
else await keep.click({ timeout: 2000 });
|
||||
await page.locator('[role="alertdialog"]').waitFor({ state: 'detached', timeout: 2000 });
|
||||
assert.equal(await id.inputValue(), 'draft-policy');
|
||||
assert.ok(await editor.evaluate(el => el.contains(document.activeElement)), 'focus did not return to the editor');
|
||||
await dismissals[action]();
|
||||
await confirm.getByRole('button', { name: 'Discard changes' }).click({ timeout: 2000 });
|
||||
await closed();
|
||||
await opener.click();
|
||||
assert.equal(await id.inputValue(), '', 'discarded policy reappeared on reopen');
|
||||
});
|
||||
};
|
||||
@@ -1,112 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const waiting = {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
title: 'Correct the workflow',
|
||||
kind: 'workflow_change',
|
||||
state: 'pending',
|
||||
needs: 'owner',
|
||||
actions: [],
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
// Keep the last successful result and protect its tab from competing reads.
|
||||
module.exports = async ({ page, go, shot, tolerate }) => {
|
||||
const now = new Date();
|
||||
await page.clock.install({ time: now });
|
||||
await page.clock.pauseAt(new Date(now.getTime() + 60_000));
|
||||
tolerate(/503.*\/api\/proposals/);
|
||||
|
||||
const pendingURL = '**/api/proposals?state=pending';
|
||||
let current = waiting;
|
||||
let failNext;
|
||||
await page.route(pendingURL, async route => {
|
||||
if (failNext) {
|
||||
const failing = failNext;
|
||||
failNext = undefined;
|
||||
await failing;
|
||||
await route.fulfill({ status: 503, contentType: 'application/problem+json', json: { detail: 'Could not refresh proposals' } });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ json: [current] });
|
||||
});
|
||||
|
||||
await go('/proposals');
|
||||
const proposal = page.getByRole('link', { name: waiting.title, exact: true });
|
||||
const sort = page.getByRole('columnheader', { name: 'Proposal', exact: true });
|
||||
await proposal.waitFor();
|
||||
await sort.getByRole('button').press('Enter');
|
||||
await proposal.focus();
|
||||
|
||||
const failure = Promise.withResolvers();
|
||||
failNext = failure.promise;
|
||||
const refresh = page.waitForRequest(pendingURL);
|
||||
await page.clock.runFor(5000);
|
||||
await refresh;
|
||||
assert.equal(await proposal.isVisible(), true, 'the row should stay visible during a refresh');
|
||||
failure.resolve();
|
||||
|
||||
const error = page.getByRole('alert').filter({ hasText: 'Could not refresh proposals' });
|
||||
await error.waitFor();
|
||||
assert.equal(await proposal.isVisible(), true, 'a failed refresh must not replace the table');
|
||||
assert.equal(await sort.getAttribute('aria-sort'), 'ascending', 'the table should keep the operator’s sort');
|
||||
assert.equal(await proposal.evaluate(link => link === document.activeElement), true, 'the row should keep keyboard focus');
|
||||
await shot('failed-refresh-retains-table');
|
||||
|
||||
current = { ...waiting, title: 'Workflow correction updated' };
|
||||
await error.getByRole('button', { name: 'Retry' }).click();
|
||||
await page.getByRole('link', { name: current.title, exact: true }).waitFor();
|
||||
await error.waitFor({ state: 'hidden' });
|
||||
assert.equal(await sort.getAttribute('aria-sort'), 'ascending');
|
||||
|
||||
// A failed read belongs to its filter, not to the newly selected tab.
|
||||
failNext = Promise.resolve();
|
||||
await page.clock.runFor(5000);
|
||||
await error.waitFor();
|
||||
const published = Promise.withResolvers();
|
||||
await page.route('**/api/proposals?state=published', async route => {
|
||||
await published.promise;
|
||||
await route.fulfill({ json: [] });
|
||||
});
|
||||
const publishedTab = page.getByRole('tab', { name: 'Published' });
|
||||
await publishedTab.click();
|
||||
const loading = page.getByRole('status', { name: 'Loading proposals' });
|
||||
assert.equal(await loading.isVisible(), true, 'a new tab must not inherit the previous tab’s error');
|
||||
assert.equal(await error.isVisible(), false);
|
||||
assert.equal(await page.getByRole('table').count(), 0, 'rows from the previous tab must not appear');
|
||||
published.resolve();
|
||||
const empty = page.getByText('No proposals', { exact: true });
|
||||
await empty.waitFor();
|
||||
|
||||
// A slow read must still take effect after a background poll ticks.
|
||||
const slow = Promise.withResolvers();
|
||||
const stale = Promise.withResolvers();
|
||||
let first = true;
|
||||
await page.route(pendingURL, async route => {
|
||||
const read = first ? slow : stale;
|
||||
first = false;
|
||||
await read.promise;
|
||||
await route.fulfill({ json: [waiting] });
|
||||
});
|
||||
const switched = page.waitForRequest(pendingURL);
|
||||
await page.getByRole('tab', { name: 'Waiting' }).click();
|
||||
await switched;
|
||||
await page.clock.runFor(5000);
|
||||
slow.resolve();
|
||||
await proposal.waitFor({ timeout: 3000 }).catch(() => {
|
||||
assert.fail('a slow read must render its result even after a background poll ticks');
|
||||
});
|
||||
|
||||
// A late response for Waiting cannot replace the Published result.
|
||||
const nextPoll = page.waitForRequest(pendingURL);
|
||||
await page.clock.runFor(5000);
|
||||
await nextPoll;
|
||||
await publishedTab.click();
|
||||
await empty.waitFor();
|
||||
const response = page.waitForResponse(pendingURL);
|
||||
stale.resolve();
|
||||
await (await response).finished();
|
||||
await page.clock.runFor(50);
|
||||
assert.equal(await proposal.isVisible(), false, 'a response for the previous tab must not replace the current one');
|
||||
assert.equal(await empty.isVisible(), true);
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
// Repositories and connections say what stops them serving work: the seeded
|
||||
// repository has no connection, and the seeded connection's forge is not enabled.
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await go('/org/repositories');
|
||||
await page.getByText('acme/widgets', { exact: true }).first().waitFor();
|
||||
await page.getByText('No connection', { exact: true }).waitFor();
|
||||
await shot('repositories');
|
||||
|
||||
await go('/org/connections');
|
||||
await page.getByText('github.com', { exact: true }).first().waitFor();
|
||||
await page.getByText('Forge not enabled', { exact: true }).waitFor();
|
||||
await shot('connections');
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
// Every static route loads without errors, renders, and shows no text with
|
||||
// stray leading, trailing or doubled spaces.
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail }) => {
|
||||
const stray = new Map();
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
await shot(r);
|
||||
// Log lines are data, not copy.
|
||||
if (r === '/logs') continue;
|
||||
const bad = await page.evaluate(() => [...document.querySelectorAll('body *')]
|
||||
.filter((el) => !el.children.length && !el.closest('pre,code,textarea,.xterm') && el.getClientRects().length && !getComputedStyle(el).whiteSpace.startsWith('pre'))
|
||||
.map((el) => el.textContent)
|
||||
.filter((t) => t.trim() && (t !== t.trim() || / /.test(t.trim()))));
|
||||
for (const t of bad) {
|
||||
const key = JSON.stringify(t.length > 60 ? t.slice(0, 60) + '…' : t);
|
||||
stray.set(key, (stray.get(key) || new Set()).add(r));
|
||||
}
|
||||
}
|
||||
for (const [text, where] of stray) fail(`stray whitespace ${text} on ${[...where].join(', ')}`);
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
// The seed (e2e/seed.sh) is visible where an operator would look for it.
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await go('/tasks');
|
||||
await page.getByText('Fix flaky login test').first().waitFor({ timeout: 10000 });
|
||||
await shot('tasks');
|
||||
await go('/events');
|
||||
await page.getByText('e2e-hook').first().waitFor({ timeout: 10000 });
|
||||
await shot('events');
|
||||
};
|
||||
@@ -1,32 +0,0 @@
|
||||
// Draft edits only: no saved configuration is changed.
|
||||
const assert = require('node:assert/strict');
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await go('/settings/channels');
|
||||
const workspace = page.getByLabel('Workspace', { exact: true });
|
||||
assert.equal(await page.getByRole('region', { name: 'Unsaved changes' }).count(), 0, 'unsaved bar before any edit');
|
||||
await workspace.fill('/srv/e2e-workspace');
|
||||
await page.getByRole('link', { name: 'Models', exact: true }).click();
|
||||
await page.getByRole('heading', { name: 'Models' }).waitFor();
|
||||
await page.getByRole('link', { name: 'Channels', exact: true }).click();
|
||||
assert.equal(await page.getByLabel('Workspace', { exact: true }).inputValue(), '/srv/e2e-workspace', 'edit lost on navigation');
|
||||
const form = await page.getByText('Chat session defaults', { exact: true }).evaluate(el => el.closest('[data-slot="card"]').getBoundingClientRect().width);
|
||||
assert.ok(form <= 850, `settings form stretched to ${form}px`);
|
||||
const review = page.getByRole('button', { name: 'Review and save', exact: true });
|
||||
await review.scrollIntoViewIfNeeded();
|
||||
const unobscured = await review.evaluate(el => { const r=el.getBoundingClientRect(); const hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2); return hit && el.contains(hit); });
|
||||
assert.ok(unobscured, 'Review and save is covered');
|
||||
await review.click();
|
||||
await page.getByRole('heading', { name: /^Review \d/ }).waitFor();
|
||||
await page.getByText('/srv/e2e-workspace', { exact: false }).last().waitFor();
|
||||
await shot('review');
|
||||
await page.getByRole('button', { name: 'Discard all', exact: true }).click();
|
||||
assert.equal(await page.getByRole('region', { name: 'Unsaved changes' }).count(), 0);
|
||||
assert.equal(await page.getByLabel('Workspace', { exact: true }).inputValue(), '', 'discard kept the edit');
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.getByLabel('Workspace', { exact: true }).fill('/srv/e2e-workspace');
|
||||
const mobileReview=page.getByRole('button',{name:'Review and save',exact:true});
|
||||
await mobileReview.scrollIntoViewIfNeeded();
|
||||
assert.ok(await mobileReview.evaluate(el=>{const r=el.getBoundingClientRect();return el.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2))}), 'mobile save action covered');
|
||||
await shot('mobile');
|
||||
await page.getByRole('button',{name:'Discard',exact:true}).click();
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
// The setup checklist reads the selected org: an org with no model to run gets a
|
||||
// Model step that leads to the page that fixes it.
|
||||
const assert = require('node:assert/strict');
|
||||
const { ORG, ABSENT, selectOrg } = require('./helpers/org-helpers.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
tolerate(ABSENT);
|
||||
await go('/');
|
||||
await page.getByPlaceholder('Describe a task').waitFor();
|
||||
assert.equal(await page.getByRole('link', { name: 'Model', exact: true }).count(), 0, 'an org with a model got a Model step');
|
||||
assert.equal((await selectOrg(page, ORG.beta)).status(), 204);
|
||||
await go('/');
|
||||
await page.getByText('Setup', { exact: true }).waitFor();
|
||||
const model = page.getByRole('link', { name: 'Model', exact: true });
|
||||
await model.waitFor();
|
||||
assert.equal(await model.getAttribute('href'), '/org/models');
|
||||
await shot('beta-dashboard');
|
||||
await model.click();
|
||||
await settled('/org/models');
|
||||
await shot('model-page');
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
const assert=require('node:assert/strict');
|
||||
module.exports=async({page,go,shot})=>{
|
||||
await go('/tasks');
|
||||
const base=new URL(page.url()).origin;
|
||||
const tasks=await (await page.request.get(base+'/api/tasks')).json();
|
||||
const task=tasks.find(t=>t.status==='parked' && t.attempt>0);
|
||||
assert.ok(task,'seeded stack has no parked attempt to inspect');
|
||||
const state=await (await page.request.get(`${base}/api/tasks/${task.id}/attempts`)).json();
|
||||
assert.ok(state.attempts.some(a=>a.attempt===state.current_attempt),'claimed current attempt missing');
|
||||
await go(`/tasks/${task.id}`);
|
||||
assert.equal(await page.getByText(`Attempt ${state.current_attempt} is not recorded`,{exact:true}).count(),0);
|
||||
const logs=await (await page.request.get(`${base}/api/tasks/${task.id}/logs?attempt=${state.current_attempt}&level=ERROR&limit=1`)).json();
|
||||
await page.getByRole('button',{name:'Jump to log line',exact:true}).click();
|
||||
if(logs.entries?.[0]?.id){
|
||||
await page.locator(`[data-row-key="${logs.entries[0].id}"]`).waitFor();
|
||||
await page.waitForFunction(id=>document.activeElement?.getAttribute('data-row-key')===String(id),logs.entries[0].id);
|
||||
}else{
|
||||
await page.getByText('No error log line was recorded for this attempt.',{exact:true}).waitFor();
|
||||
}
|
||||
await shot('attempt');
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
// A parked task whose blocker has a fix links to the page that supplies it, from
|
||||
// Needs attention on the dashboard and from the Stage Rail on the task page.
|
||||
// The seed's work requests park for want of a repository connection.
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled, skip }) => {
|
||||
await go('/');
|
||||
const tasks = await page.evaluate(async () => (await fetch('/api/tasks?limit=100')).json());
|
||||
if (!tasks.some((task) => task.status === 'parked')) skip('no parked task');
|
||||
const parked = tasks.find((task) => task.status === 'parked' && task.recovery);
|
||||
assert.ok(parked, 'no parked task in the list carries a recovery link');
|
||||
const { label, link } = parked.recovery;
|
||||
|
||||
const row = page.getByRole('link', { name: parked.title, exact: true }).locator('xpath=ancestor::*[.//a[normalize-space()="' + label + '"]][1]');
|
||||
const fromDashboard = row.getByRole('link', { name: label, exact: true });
|
||||
await fromDashboard.waitFor();
|
||||
assert.equal(await fromDashboard.getAttribute('href'), link);
|
||||
await shot('needs-attention');
|
||||
await fromDashboard.click();
|
||||
await settled(link);
|
||||
|
||||
await go(`/tasks/${parked.id}`);
|
||||
const fromRail = page.getByRole('complementary', { name: 'Task details' }).getByRole('link', { name: label, exact: true });
|
||||
await fromRail.waitFor();
|
||||
assert.equal(await fromRail.getAttribute('href'), link);
|
||||
await shot('stage-rail');
|
||||
await fromRail.click();
|
||||
await settled(link);
|
||||
};
|
||||
@@ -1,14 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await page.route('**/api/control-plane/resources/workflow-definitions', async route => {
|
||||
await new Promise(resolve => setTimeout(resolve, 2200));
|
||||
await route.continue();
|
||||
});
|
||||
await go('/workflows');
|
||||
assert.equal(await page.getByText('No workflows', { exact: true }).count(), 0, 'loading presented as empty');
|
||||
await page.getByText('Loading workflows…', { exact: true }).waitFor({ state: 'hidden' });
|
||||
await page.getByRole('link', { name: /^implement/ }).click();
|
||||
assert.equal(await page.getByText(/workflow implement has no steps/).count(), 0, 'late definition left an empty canvas');
|
||||
await page.locator('.vue-flow__node').filter({ hasText: 'Repository' }).first().waitFor();
|
||||
await shot('loaded');
|
||||
};
|
||||
@@ -1,121 +0,0 @@
|
||||
// Workflow definition behaviour at desktop width: legacy title IDs migrate
|
||||
// to slugs, invalid expressions flag the node and toolbar alike, a pinned
|
||||
// historical run keeps its original step IDs inspectable, and handoff
|
||||
// targets round-trip between the step form and YAML.
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled }) => {
|
||||
await page.route('**/api/control-plane/resources/workflow-drafts', async route => {
|
||||
const response = await route.fetch();
|
||||
const data = await response.json();
|
||||
data.resource.value = { drafts: [] };
|
||||
await route.fulfill({ json: data });
|
||||
});
|
||||
const panTo = async node => {
|
||||
const flow = page.locator('.vue-flow');
|
||||
await flow.hover();
|
||||
for (let adjustment = 0; adjustment < 3; adjustment++) {
|
||||
const target = await node.boundingBox(), viewport = await flow.boundingBox();
|
||||
const delta = target.y + target.height / 2 - viewport.y - viewport.height / 2;
|
||||
if (Math.abs(delta) < 30) break;
|
||||
await page.mouse.wheel(0, delta * 2);
|
||||
await settled();
|
||||
}
|
||||
};
|
||||
// Reproduce a previously stored title ID without changing the test server.
|
||||
await go('/workflows');
|
||||
const response = await page.request.get(new URL('/api/control-plane/resources/workflow-definitions', page.url()).href);
|
||||
const resource = await response.json();
|
||||
const definition = resource.resource.value.definitions.find(entry => entry.id === 'feasibility');
|
||||
definition.yaml = definition.yaml.replace(/\bid: assess\b/, 'id: Write a Product Requirement Document').replaceAll('steps.assess.', 'steps.Write a Product Requirement Document.');
|
||||
await page.route('**/api/control-plane/resources/workflow-definitions', route => route.fulfill({ json: resource }));
|
||||
await go('/workflows/feasibility');
|
||||
await page.getByRole('tab', { name: 'History', exact: true }).click();
|
||||
const yaml = await page.getByLabel('Workflow YAML', { exact: true }).inputValue();
|
||||
assert.ok(yaml.includes('id: write-a-product-requirement-document'));
|
||||
assert.ok(yaml.includes('steps.write-a-product-requirement-document.result'));
|
||||
assert.ok(!yaml.includes('steps.Write a Product Requirement Document'));
|
||||
await page.getByRole('tab', { name: 'Canvas', exact: true }).first().click();
|
||||
const definitionPicker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
if (await definitionPicker.count()) { await definitionPicker.click(); await page.getByRole('option', { name: 'Definition', exact: true }).click(); }
|
||||
const approval = page.locator('.vue-flow__node').filter({ hasText: 'Approval' }).first();
|
||||
await panTo(approval);
|
||||
await approval.click();
|
||||
const chip = approval.getByRole('button', { name: 'write-a-product-requirement-document', exact: true });
|
||||
await chip.waitFor();
|
||||
await chip.click();
|
||||
assert.match(await approval.getByLabel('Plan', { exact: true }).inputValue(), /steps\.write-a-product-requirement-document\.summary/);
|
||||
await shot('legacy-reference');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('tab', { name: 'History', exact: true }).click();
|
||||
const field = page.getByLabel('Workflow YAML', { exact: true });
|
||||
await field.fill((await field.inputValue()).replace('type: repo.prepare', 'type: repo.prepare\n when: not-a-valid-expression'));
|
||||
await page.getByRole('tab', { name: 'Canvas', exact: true }).first().click();
|
||||
const problem = page.locator('.vue-flow__node').filter({ hasText: 'Prepare worktree' }).first().locator('svg.text-danger');
|
||||
await problem.waitFor();
|
||||
const toolbarProblem = page.getByRole('status').filter({ has: page.locator('svg') });
|
||||
assert.equal(await problem.evaluate(el => getComputedStyle(el).color), await toolbarProblem.evaluate(el => getComputedStyle(el).color));
|
||||
const invalidPage = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth, width: innerWidth,
|
||||
}));
|
||||
assert.equal(invalidPage.scrollWidth, invalidPage.width, 'invalid toolbar overflows');
|
||||
await shot('validation');
|
||||
// A pinned historical run keeps its original step IDs and remains inspectable.
|
||||
const snapshot = definition.yaml;
|
||||
await page.route('**/api/tasks?*', route => {
|
||||
const workflow = new URL(route.request().url()).searchParams.get('workflow');
|
||||
return workflow === 'feasibility'
|
||||
? route.fulfill({ json: [{ id: 999999, workflow, title: 'Historical run', status: 'failed', workflow_definition_yaml: snapshot }] })
|
||||
: route.continue();
|
||||
});
|
||||
await page.route('**/api/tasks/999999/*?*', route => route.fulfill({ json: {} }));
|
||||
await page.route('**/api/tasks/999999/debug', route => route.fulfill({ json: {} }));
|
||||
await page.route('**/api/tasks/999999/attempts', route => route.fulfill({ json: { attempts: [{ attempt: 1, stages: [{ name: 'Write a Product Requirement Document', status: 'failed', error: 'Historical failure' }] }] } }));
|
||||
await go('/workflows/feasibility');
|
||||
const picker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
await picker.waitFor();
|
||||
assert.match(await picker.innerText(), /Run #999999/);
|
||||
const root = await page.locator('.vue-flow__node[data-id="workflow"]').boundingBox();
|
||||
const pinnedCanvas = await page.locator('.workflow-canvas').boundingBox();
|
||||
assert.ok(root.y >= pinnedCanvas.y, 'historical workflow header clipped above canvas');
|
||||
await shot('run-picker');
|
||||
await page.locator('.vue-flow').hover();
|
||||
await page.mouse.wheel(0, 550);
|
||||
await settled();
|
||||
const historicalStep = page.locator('.vue-flow__node').filter({ hasText: 'Write a Product Requirement Document' }).first();
|
||||
await panTo(historicalStep);
|
||||
await historicalStep.click();
|
||||
await page.getByText('Historical failure', { exact: true }).first().waitFor();
|
||||
await shot('historical-run');
|
||||
await page.keyboard.press('Escape');
|
||||
await picker.click();
|
||||
await page.getByRole('option', { name: 'Definition', exact: true }).click();
|
||||
assert.equal(await picker.innerText(), 'Definition');
|
||||
await shot('definition-picker');
|
||||
await go('/workflows/triage');
|
||||
const runPicker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
if (await runPicker.count()) { await runPicker.click(); await page.getByRole('option', { name: 'Definition', exact: true }).click(); }
|
||||
await page.locator('.vue-flow').hover();
|
||||
await page.mouse.wheel(0, 650);
|
||||
await settled();
|
||||
const handoff = page.locator('.vue-flow__node').filter({ hasText: 'Hand off' }).first();
|
||||
await panTo(handoff);
|
||||
await handoff.click();
|
||||
const target = handoff.getByLabel('Workflow', { exact: true });
|
||||
await target.waitFor();
|
||||
assert.equal(await target.inputValue(), '{{ steps.classify.result.workflow }}');
|
||||
await target.fill('{{ steps.classify.result.alternative }}');
|
||||
await target.press('Home');
|
||||
await shot('dynamic-handoff');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('tab', { name: 'History', exact: true }).click();
|
||||
assert.ok((await page.getByLabel('Workflow YAML', { exact: true }).inputValue()).includes('steps.classify.result.alternative'));
|
||||
await page.getByRole('tab', { name: 'Canvas', exact: true }).first().click();
|
||||
await panTo(handoff);
|
||||
await handoff.click();
|
||||
await target.fill('implement');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('tab', { name: 'History', exact: true }).click();
|
||||
assert.ok((await page.getByLabel('Workflow YAML', { exact: true }).inputValue()).includes('workflow: implement'));
|
||||
};
|
||||
@@ -1,101 +0,0 @@
|
||||
// The workflow canvas at phone width: no page scroll, a clean topbar, lanes
|
||||
// inside the canvas, zoom controls below the graph, step and run dialogs
|
||||
// that fit, YAML without page scroll, and a pinned run header that stays
|
||||
// visible.
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
// The list is a page at phone width: rows open the workflow, and the
|
||||
// enabled switch is on the row and on the workflow page.
|
||||
await go('/workflows');
|
||||
const row = page.getByRole('link', { name: /^implement/ });
|
||||
await row.waitFor();
|
||||
const listWidth = await page.evaluate(() => ({ scrollWidth: document.documentElement.scrollWidth, width: innerWidth }));
|
||||
assert.equal(listWidth.scrollWidth, listWidth.width, 'workflow list scrolls horizontally');
|
||||
await shot('list');
|
||||
await page.getByRole('switch', { name: 'implement enabled' }).waitFor();
|
||||
await row.click();
|
||||
await page.waitForURL(/\/workflows\/implement$/);
|
||||
await page.locator('.workflow-canvas').waitFor();
|
||||
await page.getByRole('switch', { name: 'implement enabled' }).waitFor();
|
||||
await go('/workflows?workflow=implement');
|
||||
assert.match(page.url(), /\/workflows\/implement$/, 'legacy ?workflow= link did not reach the workflow page');
|
||||
for (const workflow of ['implement', 'feasibility']) {
|
||||
await go(`/workflows/${workflow}`);
|
||||
const canvas = page.locator('.workflow-canvas');
|
||||
await canvas.waitFor();
|
||||
const dimensions = await page.evaluate(() => ({
|
||||
height: innerHeight, width: innerWidth,
|
||||
scrollHeight: document.documentElement.scrollHeight,
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
}));
|
||||
assert.equal(dimensions.scrollHeight, dimensions.height, 'workflow page scrolls vertically');
|
||||
assert.equal(dimensions.scrollWidth, dimensions.width, 'workflow page scrolls horizontally');
|
||||
const topbar = page.locator('header').first();
|
||||
const bar = await topbar.boundingBox();
|
||||
assert.equal(bar.y, 0, 'blank band above topbar');
|
||||
assert.equal(await topbar.evaluate(el => getComputedStyle(el).backdropFilter), 'none');
|
||||
assert.ok(!await canvas.getByText('Works on a repository', { exact: true }).count());
|
||||
const run = page.getByRole('button', { name: new RegExp(`^(Run|Test) ${workflow}$`) });
|
||||
assert.ok(await run.isVisible(), 'Run hidden on phone');
|
||||
const box = await canvas.boundingBox();
|
||||
const start = await page.locator('.vue-flow__node[data-id="start"]').boundingBox();
|
||||
assert.ok(start.y >= box.y && start.y < box.y + box.height, 'start is outside initial viewport');
|
||||
const nodes = await page.locator('.vue-flow__node').evaluateAll(elements => elements.map(el => ({
|
||||
left: el.getBoundingClientRect().left, right: el.getBoundingClientRect().right,
|
||||
})));
|
||||
assert.ok(nodes.every(node => node.left >= box.x && node.right <= box.x + box.width), 'branch lanes clipped horizontally');
|
||||
const controls = await page.getByRole('group', { name: 'Zoom', exact: true }).boundingBox();
|
||||
const covered = await page.locator('.vue-flow__node').evaluateAll((elements, c) => elements.some((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.left < c.x + c.width && r.right > c.x && r.top < c.y + c.height && r.bottom > c.y;
|
||||
}), controls);
|
||||
assert.ok(!covered, 'zoom controls cover a step');
|
||||
await shot(workflow);
|
||||
const step = page.locator('.vue-flow__node').filter({ hasText: 'Prepare worktree' }).first();
|
||||
assert.match(await step.innerText(), /^\d+\.\s+Prepare worktree$/);
|
||||
await step.click();
|
||||
const dialog = page.locator('[role="dialog"][data-slot="dialog-content"]');
|
||||
await dialog.waitFor();
|
||||
const dialogBox = await dialog.boundingBox();
|
||||
assert.ok(dialogBox.x >= 0 && dialogBox.x + dialogBox.width <= 390, 'step editor exceeds phone width');
|
||||
const input = dialog.getByRole('textbox').first();
|
||||
if (await input.count()) assert.ok(await input.evaluate(el => el.getBoundingClientRect().height) >= 24, 'step form scaled down');
|
||||
await shot(`${workflow}-step`);
|
||||
await page.keyboard.press('Escape');
|
||||
await run.click();
|
||||
await page.locator('[role="dialog"][data-slot="dialog-content"]').waitFor();
|
||||
await shot(`${workflow}-run`);
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
// YAML must not make the page scroll at phone width.
|
||||
await go('/workflows/feasibility');
|
||||
await page.getByRole('tab', { name: 'History', exact: true }).click();
|
||||
await settled();
|
||||
const yamlPage = await page.evaluate(() => ({
|
||||
scrollHeight: document.documentElement.scrollHeight, height: innerHeight,
|
||||
}));
|
||||
assert.equal(yamlPage.scrollHeight, yamlPage.height, 'YAML causes page scroll');
|
||||
await page.getByRole('tab', { name: 'Canvas', exact: true }).first().click();
|
||||
// A pinned historical run keeps its header visible on the canvas.
|
||||
const response = await page.request.get(new URL('/api/control-plane/resources/workflow-definitions', page.url()).href);
|
||||
const resource = await response.json();
|
||||
const snapshot = resource.resource.value.definitions.find(entry => entry.id === 'feasibility').yaml;
|
||||
await page.route('**/api/tasks?*', route => {
|
||||
const workflow = new URL(route.request().url()).searchParams.get('workflow');
|
||||
return workflow === 'feasibility'
|
||||
? route.fulfill({ json: [{ id: 999999, workflow, title: 'Historical run', status: 'failed', workflow_definition_yaml: snapshot }] })
|
||||
: route.continue();
|
||||
});
|
||||
await page.route('**/api/tasks/999999/*?*', route => route.fulfill({ json: {} }));
|
||||
await page.route('**/api/tasks/999999/debug', route => route.fulfill({ json: {} }));
|
||||
await page.route('**/api/tasks/999999/attempts', route => route.fulfill({ json: { attempts: [{ attempt: 1, stages: [] }] } }));
|
||||
await go('/workflows/feasibility');
|
||||
const picker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
await picker.waitFor();
|
||||
assert.match(await picker.innerText(), /Run #999999/);
|
||||
const root = await page.locator('.vue-flow__node[data-id="workflow"]').boundingBox();
|
||||
const pinnedCanvas = await page.locator('.workflow-canvas').boundingBox();
|
||||
assert.ok(root.y >= pinnedCanvas.y, 'historical workflow header clipped above canvas');
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
module.exports = async ({ page, go, shot }) => {
|
||||
await go('/workflows/implement');
|
||||
const runPicker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
|
||||
if (await runPicker.count()) { await runPicker.click(); await page.getByRole('option', { name: 'Definition', exact: true }).click(); }
|
||||
await page.locator('.vue-flow__node').filter({hasText:'Prepare worktree'}).first().click();
|
||||
const more=page.getByRole('button',{name:'More',exact:true}).filter({hasText:'More'});
|
||||
if (await more.getAttribute('aria-expanded')==='false') await more.click();
|
||||
const condition=page.getByLabel('Run only when', {exact:true});
|
||||
await condition.fill('what');
|
||||
await page.getByRole('alert').filter({hasText:'when must name'}).first().waitFor();
|
||||
await condition.fill('task.title');
|
||||
await page.getByRole('alert').filter({hasText:'when must name'}).first().waitFor({state:'hidden'});
|
||||
const backoff=page.getByLabel('Retry backoff',{exact:true});
|
||||
await backoff.fill('yes');
|
||||
await page.getByText('Enter a number zero or greater.',{exact:true}).waitFor();
|
||||
await backoff.fill('0.5');
|
||||
await page.getByLabel('Run only when',{exact:true}).focus();
|
||||
await page.getByText('Enter a number zero or greater.',{exact:true}).waitFor({state:'hidden'});
|
||||
await page.getByRole('combobox',{name:'Unit',exact:true}).selectOption('m');
|
||||
await page.getByRole('tab',{name:'History',exact:true}).click();
|
||||
assert.match(await page.getByLabel('Workflow YAML',{exact:true}).inputValue(), /backoff: 30s/);
|
||||
await shot('validated');
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"name": "archie-e2e",
|
||||
"private": true,
|
||||
"description": "Validation of a running local stack; never part of the gate",
|
||||
"scripts": {
|
||||
"check": "node run.cjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "1.64.0"
|
||||
},
|
||||
"packageManager": "pnpm@12.10.1"
|
||||
}
|
||||
Generated
-191
@@ -1,191 +0,0 @@
|
||||
---
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
configDependencies: {}
|
||||
packageManagerDependencies:
|
||||
pnpm:
|
||||
specifier: 12.10.1
|
||||
version: 12.10.1
|
||||
|
||||
packages:
|
||||
|
||||
'@pnpm/exe.android-arm64@12.10.1':
|
||||
resolution: {integrity: sha512-CVTlHPwNvadQCJD9bGSMzWIhFX8QpjtqC2c27dhdnn/9iKzEjZ3qL62o3gHpKbIuo6qn4WxTKRoaokgNdReBig==}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@pnpm/exe.android-x64@12.10.1':
|
||||
resolution: {integrity: sha512-NFiYLIaodY7da0XIebwcU3JoP7IK/lzF7zgKSSP+9H+QcFnQ1GDfBkuBKCYJzZ+Xu0WH54neIPLBBCaOjaaauA==}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@pnpm/exe.darwin-arm64@12.10.1':
|
||||
resolution: {integrity: sha512-0O8tdQ8ijlPJudXspLMTcitMkdBEz6uUflazL5uQE0WMs85oQIp0U+5hfEktMFB64QqEhjqlvvujTwbzdr9oMg==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@pnpm/exe.darwin-x64@12.10.1':
|
||||
resolution: {integrity: sha512-ud+1/uZOKEo8P/AsPynOJc/LNwfI0j6WwCElibj71rU9l4nIBnsSn+wWTIPZPkZ4BBSH5+82azSnAARMyJ1lNA==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@pnpm/exe.freebsd-x64@12.10.1':
|
||||
resolution: {integrity: sha512-mj9PE5rf8uAfQQ2K66HSATMSut+lNiB4eSqFd5+azFVCMnxNSy/32xpZQJT21PhnN3Y4qbK+iKHe5nWAxSuRhw==}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@pnpm/exe.linux-arm64-musl@12.10.1':
|
||||
resolution: {integrity: sha512-xba+00wZJ8Um6rBJJjWl88uJj0tydB8dtomvjlCLvi0uL32vpa9CRP8Vv26FIXvbiZ1bo2RCzYt/eChxJVV52w==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@pnpm/exe.linux-arm64@12.10.1':
|
||||
resolution: {integrity: sha512-oBdMp69ScC9UnniG4qZAQVr2fBDSXjm4yk/72vkEVyrlwS23yMxcRQl7Qdo3sgXPAygY6TWnPRKm4rXzjoyW7w==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@pnpm/exe.linux-ppc64@12.10.1':
|
||||
resolution: {integrity: sha512-Yyb3wu09h3c7mLme270uHFiVaAIUHC411Ru9LIU2BKUIstrGlXa9OqqVWoXaRgYRdFdOFknkwG7GNn6ygwLbnw==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@pnpm/exe.linux-riscv64@12.10.1':
|
||||
resolution: {integrity: sha512-PdkeUFFkybknnGkWP0H22eMpIiS4OZXL5BcQzF4lh+vmrW3IaC2HOkbANKgot/PKO0Kl77pzA/6PKFxgbgfXIQ==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@pnpm/exe.linux-s390x@12.10.1':
|
||||
resolution: {integrity: sha512-1okKuHKJwJPAbofDxfhZWAUxEWtee4ZSf7Pah8kcvocaJkf2WxFJ5KVTiNIvDml5GLidDQsgf7Pcf/WHbCak7Q==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@pnpm/exe.linux-x64-musl@12.10.1':
|
||||
resolution: {integrity: sha512-e6IqzVNkPa7srFKJKnY23uWJ+qz0LaRWiTUo/sHfFXRRMRzB5uNOr6qWWip/jqhdGwU91n9J7LrEYZ6e0tRczw==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@pnpm/exe.linux-x64@12.10.1':
|
||||
resolution: {integrity: sha512-ZByV0DRgWzGaDSjT5ddRBASdwz+r/qPMYh7o6RGmPQjtRGNFbSl94xY2DcAM8mqCOZJUUDtAXQ+wpBXcdpKlkg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@pnpm/exe.win32-arm64@12.10.1':
|
||||
resolution: {integrity: sha512-I7QZHcjioG7orFeCRUFUHByJ1G0zFPnAlaGGyrUvb6MGkv5oeNwNPl7t+Gp+7zHfnMcgLGJ1a+Wfim0IDw3lOw==}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@pnpm/exe.win32-x64@12.10.1':
|
||||
resolution: {integrity: sha512-4WJFdp58EKlCj0zLobrXU0vpszSZIr4X/3y/uNbAQqGW0zE+VdruZB0gFc3L2kzsUzVwTYbaCn+XEhnCYSAlTg==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
pnpm@12.10.1:
|
||||
resolution: {integrity: sha512-ukCjfrGjcNYP6oxM8dNkwTvMzvUY6YrSvO6VT1OdONo3RY5YJho/pV4GUjRQ6g//+fSXsTW+QfLBXBZCusrObA==}
|
||||
engines: {node: '>=18.*'}
|
||||
hasBin: true
|
||||
|
||||
snapshots:
|
||||
|
||||
'@pnpm/exe.android-arm64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.android-x64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.darwin-arm64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.darwin-x64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.freebsd-x64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-arm64-musl@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-arm64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-ppc64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-riscv64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-s390x@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-x64-musl@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.linux-x64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.win32-arm64@12.10.1':
|
||||
optional: true
|
||||
|
||||
'@pnpm/exe.win32-x64@12.10.1':
|
||||
optional: true
|
||||
|
||||
pnpm@12.10.1:
|
||||
optionalDependencies:
|
||||
'@pnpm/exe.android-arm64': 12.10.1
|
||||
'@pnpm/exe.android-x64': 12.10.1
|
||||
'@pnpm/exe.darwin-arm64': 12.10.1
|
||||
'@pnpm/exe.darwin-x64': 12.10.1
|
||||
'@pnpm/exe.freebsd-x64': 12.10.1
|
||||
'@pnpm/exe.linux-arm64': 12.10.1
|
||||
'@pnpm/exe.linux-arm64-musl': 12.10.1
|
||||
'@pnpm/exe.linux-ppc64': 12.10.1
|
||||
'@pnpm/exe.linux-riscv64': 12.10.1
|
||||
'@pnpm/exe.linux-s390x': 12.10.1
|
||||
'@pnpm/exe.linux-x64': 12.10.1
|
||||
'@pnpm/exe.linux-x64-musl': 12.10.1
|
||||
'@pnpm/exe.win32-arm64': 12.10.1
|
||||
'@pnpm/exe.win32-x64': 12.10.1
|
||||
|
||||
---
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
playwright:
|
||||
specifier: 1.64.0
|
||||
version: 1.64.0
|
||||
|
||||
packages:
|
||||
|
||||
playwright-core@1.64.0:
|
||||
resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
playwright@1.64.0:
|
||||
resolution: {integrity: sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
snapshots:
|
||||
|
||||
playwright-core@1.64.0: {}
|
||||
|
||||
playwright@1.64.0:
|
||||
dependencies:
|
||||
playwright-core: 1.64.0
|
||||
-186
@@ -1,186 +0,0 @@
|
||||
// Drive the dashboard of a running local stack (e2e/stack.sh) in Chromium. Each module in checks/ exports async ({ page, go, shot, fail, skip, settled }).
|
||||
// A check fails on a thrown error or any console or page error. skip(reason)
|
||||
// records a skip for a missing precondition and never fails.
|
||||
//
|
||||
// node e2e/run.cjs [--headed] [--record VERSION] [list | all | check ...]
|
||||
//
|
||||
// Screenshots, results.json (the manifest) and report.html (the run report) go to
|
||||
// e2e/out/<stamp>/. --record also writes e2e/results/VERSION.md, the committed
|
||||
// evidence for a release.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const DESKTOP = { width: 1440, height: 900 };
|
||||
|
||||
// Stable label naming: kebab-case, so a route like /org/members becomes
|
||||
// org-members and / becomes home.
|
||||
function slug(label) {
|
||||
return String(label).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'home';
|
||||
}
|
||||
|
||||
class SkipCheck extends Error {}
|
||||
|
||||
const base = process.env.ARCHIE_E2E_URL || 'http://localhost:5173';
|
||||
const args = process.argv.slice(2);
|
||||
const headed = args.includes('--headed');
|
||||
if (headed) args.splice(args.indexOf('--headed'), 1);
|
||||
let record = '';
|
||||
if (args[0] === '--record') {
|
||||
record = args[1];
|
||||
if (!record || record.startsWith('-')) {
|
||||
console.error('Usage: --record VERSION all|check ...');
|
||||
process.exit(1);
|
||||
}
|
||||
args.splice(0, 2);
|
||||
}
|
||||
const available = fs.readdirSync(path.join(__dirname, 'checks')).filter((f) => f.endsWith('.cjs')).map((f) => f.slice(0, -4)).sort();
|
||||
if (!args.length || (args.length === 1 && args[0] === 'list')) {
|
||||
console.log(`Available browser checks:\n${available.map(name => ` ${name}`).join('\n')}\n\nRun: task e2e:check -- <check ...>\nAll: task e2e:check -- all\nWatch: task e2e:check -- --headed <check ...>`);
|
||||
process.exit(0);
|
||||
}
|
||||
const names = args.length === 1 && args[0] === 'all' ? available : args;
|
||||
const unknown = names.filter(name => !available.includes(name));
|
||||
if (unknown.length) {
|
||||
console.error(`Unknown checks: ${unknown.join(', ')}. Run task e2e:check to list available checks.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const { chromium } = require('playwright');
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const out = path.join(__dirname, 'out', stamp);
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: !headed, slowMo: headed ? 150 : 0 });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
||||
const login = await context.request.post(base + '/api/auth/login', {
|
||||
headers: { 'X-Archie-CSRF': '1', Origin: base },
|
||||
data: { email: process.env.ARCHIE_E2E_EMAIL || 'operator@example.test', password: process.env.ARCHIE_E2E_PASSWORD || 'archie-local-e2e-password' },
|
||||
});
|
||||
if (!login.ok()) {
|
||||
const error = `Test account sign-in failed (${login.status()}): ${await login.text()}`;
|
||||
await browser.close();
|
||||
throw new Error(error);
|
||||
}
|
||||
const storageState = await context.storageState();
|
||||
await context.close();
|
||||
const results = [];
|
||||
for (const name of names) {
|
||||
console.log(`run ${name}`);
|
||||
const check = require(path.join(__dirname, 'checks', name + '.cjs'));
|
||||
// A fresh page per check: open event streams pile up across navigations.
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, storageState });
|
||||
const errors = [];
|
||||
const notes = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
page.on('console', (m) => {
|
||||
if (m.type() !== 'error') return;
|
||||
const url = m.location().url;
|
||||
errors.push(url ? `${m.text()} (${url})` : m.text());
|
||||
});
|
||||
// Wait for load, never networkidle: the event stream never goes idle.
|
||||
const go = async (p) => { await page.goto(base + p, { waitUntil: 'load' }); await page.waitForTimeout(1200); };
|
||||
// Harness-owned wait: wait for a selector or URL, then settle briefly.
|
||||
const settled = async (sel, timeout = 10000) => {
|
||||
if (sel) {
|
||||
if (/^https?:/.test(sel)) await page.waitForURL(sel, { timeout });
|
||||
else if (sel.startsWith('/')) await page.waitForURL('**' + sel, { timeout });
|
||||
else await page.locator(sel).first().waitFor({ timeout });
|
||||
}
|
||||
await page.waitForTimeout(150);
|
||||
};
|
||||
const artifacts = [];
|
||||
// <check>-<kebab>[-<w>x<h>].png; the viewport suffix marks non-desktop
|
||||
// shots. A short settle precedes every capture so checks need no capture
|
||||
// wrapper of their own. Every capture is kept: a repeated label gets -2, -3...
|
||||
const shot = async (label) => {
|
||||
await page.waitForTimeout(150);
|
||||
const vp = page.viewportSize() || DESKTOP;
|
||||
const suffix = (vp.width === DESKTOP.width && vp.height === DESKTOP.height) ? '' : `-${vp.width}x${vp.height}`;
|
||||
const stem = `${name}-${slug(label)}${suffix}`;
|
||||
let file = `${stem}.png`;
|
||||
for (let n = 2; fs.existsSync(path.join(out, file)); n++) file = `${stem}-${n}.png`;
|
||||
await page.screenshot({ path: path.join(out, file) });
|
||||
artifacts.push({ file });
|
||||
return file;
|
||||
};
|
||||
// Keep a non-image artifact for this case: written as <check>-<name>.
|
||||
const attach = (fileName, data) => {
|
||||
const file = `${name}-${fileName}`;
|
||||
fs.writeFileSync(path.join(out, file), data);
|
||||
artifacts.push({ file });
|
||||
};
|
||||
const fail = (msg) => notes.push(msg);
|
||||
// Drop console errors matching re: a response the page is designed to survive.
|
||||
const tolerated = [];
|
||||
const tolerate = (re) => tolerated.push(re);
|
||||
const skip = (reason) => { throw new SkipCheck(reason || 'precondition missing'); };
|
||||
const started = Date.now();
|
||||
let error = '';
|
||||
let skipped = '';
|
||||
try { await check({ page, go, shot, fail, skip, settled, attach, tolerate }); } catch (e) {
|
||||
if (e instanceof SkipCheck) skipped = e.message;
|
||||
else error = String(e && e.message || e);
|
||||
}
|
||||
if (error || notes.length) await shot('failure').catch(() => {});
|
||||
await page.close();
|
||||
const problems = skipped ? [] : [error, ...notes, ...errors.filter((e) => !tolerated.some((re) => re.test(e)))].filter(Boolean);
|
||||
const result = { check: name, ok: problems.length === 0, ms: Date.now() - started, problems, artifacts };
|
||||
if (skipped) { result.skipped = true; result.skipReason = skipped; }
|
||||
results.push(result);
|
||||
console.log(`${skipped ? 'SKIP' : problems.length ? 'FAIL' : 'ok '} ${name}${skipped ? ` (${skipped})` : problems.length ? '\n ' + problems.join('\n ') : ''}`);
|
||||
}
|
||||
await browser.close();
|
||||
fs.writeFileSync(path.join(out, 'results.json'), JSON.stringify(results, null, 2));
|
||||
const commit = require('child_process').execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: __dirname, encoding: 'utf8' }).trim();
|
||||
fs.writeFileSync(path.join(out, 'report.html'), report(results, { time: new Date().toISOString(), commit }));
|
||||
if (record) writeRecord(record, results);
|
||||
console.log(`evidence: ${out}`);
|
||||
process.exit(results.every((r) => r.ok) ? 0 : 1);
|
||||
})().catch((e) => { console.error(e); process.exit(2); });
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
// One self-contained page per run: a test plan and verification record. Each
|
||||
// case carries the artifacts its own run produced; images are inlined.
|
||||
function report(results, meta) {
|
||||
const status = (r) => (r.skipped ? 'SKIP' : r.ok ? 'ok' : 'FAIL');
|
||||
const count = (s) => results.filter((r) => status(r) === s).length;
|
||||
const artifact = (a) => {
|
||||
const data = fs.readFileSync(path.join(out, a.file));
|
||||
if (!a.file.endsWith('.png')) return `<a href="${esc(a.file)}">${esc(a.file)}</a>`;
|
||||
const src = `data:image/png;base64,${data.toString('base64')}`;
|
||||
return `<figure><img src="${src}" alt="${esc(a.file)}" title="${esc(a.file)}"></figure>`;
|
||||
};
|
||||
const rows = results.map((r) => {
|
||||
const s = status(r);
|
||||
const msg = r.skipped ? [r.skipReason] : r.problems;
|
||||
return `<tr class="${s}"><td>${esc(r.check)}</td><td class="st">${s}</td><td>${r.ms}ms</td>`
|
||||
+ `<td>${msg.map((m) => `<pre>${esc(m)}</pre>`).join('')}</td>`
|
||||
+ `<td class="art">${r.artifacts.map(artifact).join('')}</td></tr>`;
|
||||
}).join('\n');
|
||||
return `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>e2e ${esc(meta.time)}</title>
|
||||
<style>body{font:14px system-ui,sans-serif;margin:1em}table{border-collapse:collapse;width:100%}td,th{border-top:1px solid #ccc;padding:.4em;vertical-align:top;text-align:left}pre{margin:0 0 .3em;white-space:pre-wrap;font-size:12px}.st{font-weight:600}.ok .st{color:#060}.FAIL .st{color:#a00}.SKIP .st{color:#668}.FAIL{background:#fff3f3}.art{display:flex;flex-wrap:wrap;gap:.5em;border:0}figure{margin:0}.art img{width:150px;border:1px solid #ccc;cursor:zoom-in}.art img.big{position:fixed;inset:2vh 2vw;width:96vw;height:96vh;object-fit:contain;background:#fff;z-index:9;cursor:zoom-out}</style>
|
||||
</head><body><h1>e2e ${esc(meta.time)}</h1>
|
||||
<p>commit ${esc(meta.commit)} against ${esc(base)}: ${results.length} cases, ${count('ok')} ok, ${count('FAIL')} FAIL, ${count('SKIP')} SKIP</p>
|
||||
<table><tr><th>Case</th><th>Status</th><th>Time</th><th>Message</th><th>Artifacts</th></tr>
|
||||
${rows}
|
||||
</table>
|
||||
<script>document.addEventListener('click',e=>{if(e.target.matches('.art img'))e.target.classList.toggle('big')})</script>
|
||||
</body></html>
|
||||
`;
|
||||
}
|
||||
|
||||
function writeRecord(version, results) {
|
||||
const dir = path.join(__dirname, 'results');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const rows = results.map((r) => `| ${r.check} | ${r.skipped ? 'skip' : r.ok ? 'pass' : 'fail'} | ${r.problems.join('<br>').replace(/\|/g, '\\|') || ''} |`);
|
||||
const passed = results.filter((r) => r.ok).length;
|
||||
fs.writeFileSync(path.join(dir, `${version}.md`), [
|
||||
`# ${version}`, '',
|
||||
`Run ${new Date().toISOString()} against ${base}: ${passed} of ${results.length} checks passed.`, '',
|
||||
'| Check | Result | Problems |', '| --- | --- | --- |', ...rows, '',
|
||||
].join('\n'));
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Seed a running local stack (e2e/stack.sh) through the dashboard's own HTTP
|
||||
# API, so the seed exercises real validation. Safe to run again: each step
|
||||
# skips what already exists.
|
||||
set -euo pipefail
|
||||
|
||||
base=${ARCHIE_E2E_API:-http://localhost:8484}
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
cookie=$(mktemp)
|
||||
trap 'rm -f "$cookie"' EXIT
|
||||
H=(-b "$cookie" -c "$cookie" -H 'Content-Type: application/json' -H 'X-Archie-CSRF: 1' -H "Origin: $base")
|
||||
|
||||
get() { curl -fsS -b "$cookie" "$base$1"; }
|
||||
post() { curl -fsS -X POST "$base$1" "${H[@]}" -d "$2"; }
|
||||
# jq-free JSON reads: py EXPR, with the parsed body as d.
|
||||
py() { python3 -c "import sys, json; d = json.load(sys.stdin); print($1)"; }
|
||||
|
||||
# This account belongs only to the isolated local test stack.
|
||||
email=${ARCHIE_E2E_EMAIL:-operator@example.test}
|
||||
password=${ARCHIE_E2E_PASSWORD:-archie-local-e2e-password}
|
||||
account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}")
|
||||
if [ "$(get /api/auth/status | py 'd["setup_required"]')" = "True" ]; then
|
||||
post /api/auth/setup "$account" >/dev/null
|
||||
else
|
||||
if ! post /api/auth/login "$account" >/dev/null; then
|
||||
echo "Test account sign-in failed. Set ARCHIE_E2E_EMAIL and ARCHIE_E2E_PASSWORD to this test stack's account credentials." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Repository policy. archied applies it live; the pause lets the watch publish it.
|
||||
if ! get /api/control-plane/resources/repository-policies | grep -q '"widgets"'; then
|
||||
version=$(get /api/control-plane/resources/repository-policies | py 'd["resource"]["version"]')
|
||||
post /api/control-plane/resources/repository-policies/commands/replace \
|
||||
"{\"value\":[{\"owner\":\"acme\",\"name\":\"widgets\",\"base\":\"main\"}],\"expected_version\":$version}" >/dev/null
|
||||
sleep 5
|
||||
fi
|
||||
|
||||
# Work requests. Without Docker they park within a minute, which fills
|
||||
# Needs you, Quality gates and the task pages.
|
||||
tasks=$(get /api/tasks)
|
||||
for t in "Fix flaky login test" "Add retry to webhook sender" "Document the gate" "Speed up the CI cache" "Recovery probe"; do
|
||||
grep -qF "\"$t\"" <<<"$tasks" && continue
|
||||
post /api/work-requests "{\"repository\":\"acme/widgets\",\"workflow\":\"triage\",\"title\":\"$t\",\"instructions\":\"Do it.\"}" >/dev/null
|
||||
done
|
||||
|
||||
# An unsigned capture source with one delivery, an event type, a mapping and
|
||||
# a binding left pending approval.
|
||||
src=e2e-hook
|
||||
if ! get /api/sources | grep -q "\"$src\""; then
|
||||
post /api/sources "{\"path\":\"$src\"}" >/dev/null
|
||||
post "/api/sources/$src/signing" '{"signed":false}' >/dev/null
|
||||
post "/api/sources/$src/approve-unsigned" '{}' >/dev/null
|
||||
bash "$here/../tools/webhook-send.sh" --url "$base" --source "$src" --kind github-issue --quiet >/dev/null
|
||||
fi
|
||||
et=$(get /api/event-types | py '"".join(t["id"] for t in (d.get("event_types", []) if isinstance(d, dict) else d) if t["name"] == "issue-opened")')
|
||||
if [ -z "$et" ]; then
|
||||
et=$(post /api/event-types "{\"source\":\"$src\",\"name\":\"issue-opened\",\"rule\":{\"headers\":[],\"payload\":[{\"path\":\"action\",\"op\":\"equals\",\"value\":\"opened\"}]},\"example\":{\"headers\":{},\"body\":\"{\\\"action\\\":\\\"opened\\\",\\\"issue\\\":{\\\"title\\\":\\\"x\\\"}}\"}}" | py 'd["id"]')
|
||||
fi
|
||||
if ! get /api/bindings | grep -q '"e2e-binding"'; then
|
||||
mapping=$(post /api/mappings "{\"name\":\"e2e-issue\",\"source_hint\":\"$src\",\"event_type_id\":\"$et\",\"fields\":[{\"name\":\"title\",\"path\":\"issue.title\",\"type\":\"string\",\"required\":true}]}" | py 'd["id"]')
|
||||
post /api/bindings "{\"name\":\"e2e-binding\",\"matcher\":{\"source\":\"$src\"},\"mapping_id\":\"$mapping\",\"workflow\":\"feasibility\",\"owner\":\"acme\",\"repo\":\"widgets\"}" >/dev/null
|
||||
fi
|
||||
|
||||
# Two more orgs: the operator owns Beta, so the org selector offers it; Gamma
|
||||
# belongs to an identity the operator is not a member of, so selecting it is refused.
|
||||
orgs=$(get /api/orgs)
|
||||
if ! grep -q '"org-beta"' <<<"$orgs"; then
|
||||
operator=$(get /api/identities | py '"".join(i["id"] for i in d["identities"] if i["display_name"] == "E2E operator")')
|
||||
post /api/orgs "{\"id\":\"org-beta\",\"name\":\"Beta\",\"owner_identity\":\"$operator\"}" >/dev/null
|
||||
fi
|
||||
if ! grep -q '"org-gamma"' <<<"$orgs"; then
|
||||
outsider=$(post /api/identities '{"display_name":"E2E outsider","kind":"user"}' | py 'd["id"]')
|
||||
post /api/orgs "{\"id\":\"org-gamma\",\"name\":\"Gamma\",\"owner_identity\":\"$outsider\"}" >/dev/null
|
||||
fi
|
||||
|
||||
echo "seeded: $(get /api/tasks | py 'len(d.get("tasks", d) if isinstance(d, dict) else d)') tasks"
|
||||
@@ -1,141 +0,0 @@
|
||||
// Run against local Vite only: node e2e/settings-save.cjs [http://127.0.0.1:5173]
|
||||
// Every API request is intercepted; no real settings can be changed.
|
||||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
const { chromium } = require('playwright');
|
||||
|
||||
const base = new URL(process.argv[2] ?? 'http://127.0.0.1:5173');
|
||||
assert.equal(base.hostname, '127.0.0.1', 'use a local Vite server');
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
|
||||
async function scenario(t, path) {
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_BIN });
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const provider = { id, name: 'Example', class: 'openai', base_url: 'https://provider.example' };
|
||||
const saved = {
|
||||
'/api/settings/agent-models': { default: { provider_id: id, model: 'original' } },
|
||||
'/api/settings/model-providers': [provider],
|
||||
'/api/settings/model-classes': [{ class: 'openai' }],
|
||||
'/api/settings/model-policy': { workflow_aliases: null, chat_aliases: null },
|
||||
'/api/settings/instructions': { text: 'Original instructions' },
|
||||
};
|
||||
const moduleWrites = {
|
||||
'/api/settings/agent-model': (body) => (saved['/api/settings/agent-models'].default = body),
|
||||
[`/api/settings/model-providers/${id}`]: (body) => Object.assign(provider, body),
|
||||
'/api/settings/model-policy': (body) => (saved['/api/settings/model-policy'] = body),
|
||||
'/api/settings/instructions': (body) => (saved['/api/settings/instructions'] = { text: body.text.trim() }),
|
||||
'/api/settings/agent-model/test': (body) => ({ model: body.model, answer: 'Ready' }),
|
||||
};
|
||||
const writes = [];
|
||||
const failed = new Set();
|
||||
const legacy = [];
|
||||
await page.route('**/*', async (r) => {
|
||||
const request = r.request();
|
||||
const url = new URL(request.url());
|
||||
if (url.origin !== base.origin) return r.abort();
|
||||
const path = url.pathname;
|
||||
if (!path.startsWith('/api/')) return r.continue();
|
||||
if (path.startsWith('/api/control-plane/')) legacy.push(path);
|
||||
if (request.method() !== 'GET') {
|
||||
const body = request.postDataJSON();
|
||||
writes.push([request.method(), path, body]);
|
||||
if (failed.delete(path)) {
|
||||
return r.fulfill({ status: 503, contentType: 'application/problem+json', body: '{"detail":"Save temporarily unavailable"}' });
|
||||
}
|
||||
if (moduleWrites[path]) return r.fulfill({ json: moduleWrites[path](body) });
|
||||
return r.fulfill({ status: 404 });
|
||||
}
|
||||
const context = {
|
||||
'/api/auth/status': { setup_required: false, user: { id: 'u', display_name: 'Operator', kind: 'operator' }, instance: 'archie' },
|
||||
'/api/authentication': { public_url: base.origin, oidc_issuer: '', oidc_client_id: '', oidc_audience: '', trusted_proxies: [] },
|
||||
'/api/capabilities': { sections: { chat: false } },
|
||||
'/api/orgs': { orgs: [{ id: 'test', name: 'Test', role: 'owner', version: 1 }], current: 'test', instance_admin: true },
|
||||
'/api/alerts': { alerts: [] },
|
||||
'/api/credentials': [],
|
||||
};
|
||||
return r.fulfill({ json: saved[path] ?? context[path] ?? {} });
|
||||
});
|
||||
await page.goto(new URL(path, base).href);
|
||||
return { page, writes, failed, saved, legacy };
|
||||
}
|
||||
|
||||
async function review(page) {
|
||||
await page.getByRole('button', { name: 'Review and save', exact: true }).click({ timeout: 3500 });
|
||||
return page.getByRole('dialog');
|
||||
}
|
||||
|
||||
test('Models reviews only staged edits and retries only the unfinished writes', async (t) => {
|
||||
const { page, writes, failed, legacy } = await scenario(t, '/settings/models');
|
||||
const alias = page.locator('#model-default');
|
||||
await alias.fill('new-model');
|
||||
await page.getByRole('button', { name: /Example/ }).click();
|
||||
await page.getByLabel('Name for Example').fill('Renamed');
|
||||
await page.getByLabel('Aliases workflows may use').fill('default');
|
||||
await page.getByLabel('Aliases chat may use').fill('default');
|
||||
const nav = page.getByRole('navigation', { name: 'Instance', exact: true });
|
||||
await nav.getByRole('link', { name: 'Authentication', exact: true }).click();
|
||||
await nav.getByRole('link', { name: 'Models', exact: true }).click();
|
||||
assert.equal(await alias.inputValue(), 'new-model');
|
||||
const dialog = await review(page);
|
||||
await dialog.getByText('new-model', { exact: false }).waitFor();
|
||||
await dialog.getByText('Renamed', { exact: false }).waitFor();
|
||||
await dialog.getByRole('button', { name: 'Revert chat', exact: true }).click();
|
||||
assert.deepEqual(writes, [], 'editing and opening the review must not write');
|
||||
|
||||
const providerPath = `/api/settings/model-providers/${id}`;
|
||||
failed.add(providerPath);
|
||||
const confirm = dialog.getByRole('button', { name: 'Save', exact: true });
|
||||
await confirm.click();
|
||||
await dialog.getByText('Save temporarily unavailable').waitFor();
|
||||
const aliasWrite = ['PUT', '/api/settings/agent-model', { provider_id: id, model: 'new-model' }];
|
||||
const providerWrite = ['PUT', providerPath, { name: 'Renamed', class: 'openai', base_url: 'https://provider.example' }];
|
||||
const policyWrite = ['PUT', '/api/settings/model-policy', { workflow_aliases: ['default'], chat_aliases: null }];
|
||||
assert.deepEqual(writes, [aliasWrite, providerWrite], 'stop after the rejected write');
|
||||
assert.equal(await dialog.getByText('new-model', { exact: false }).count(), 0, 'successful alias is no longer staged');
|
||||
await confirm.click();
|
||||
await dialog.waitFor({ state: 'hidden' });
|
||||
assert.deepEqual(writes, [aliasWrite, providerWrite, providerWrite, policyWrite]);
|
||||
assert.deepEqual(legacy, []);
|
||||
});
|
||||
|
||||
test('Testing a model runs immediately without saving its draft', async (t) => {
|
||||
const { page, writes } = await scenario(t, '/settings/models');
|
||||
await page.locator('#model-default').fill('try-this');
|
||||
await page.getByRole('button', { name: 'Test', exact: true }).click();
|
||||
await page.getByText('try-this answered “Ready”').waitFor();
|
||||
const dialog = await review(page);
|
||||
await dialog.getByText('After: try-this').waitFor();
|
||||
assert.deepEqual(writes, [['POST', '/api/settings/agent-model/test', { provider_id: id, model: 'try-this' }]]);
|
||||
});
|
||||
|
||||
test('Instructions can be discarded or retried from the review', async (t) => {
|
||||
const { page, writes, saved, failed, legacy } = await scenario(t, '/org/instructions');
|
||||
const text = page.getByRole('textbox', { name: 'Instructions' });
|
||||
await text.fill('Discard me');
|
||||
let dialog = await review(page);
|
||||
await dialog.getByText('Discard me', { exact: false }).waitFor();
|
||||
await dialog.getByRole('button', { name: 'Discard all' }).click();
|
||||
assert.equal(await text.inputValue(), 'Original instructions');
|
||||
await text.fill('New instructions');
|
||||
dialog = await review(page);
|
||||
const path = '/api/settings/instructions';
|
||||
assert.deepEqual(writes, [], 'discard and review do not write');
|
||||
const confirm = dialog.getByRole('button', { name: 'Save', exact: true });
|
||||
saved[path].text = 'Changed in another tab';
|
||||
await confirm.click();
|
||||
await dialog.getByText('Changed elsewhere. Latest values loaded.').waitFor();
|
||||
await dialog.getByText('Changed in another tab').waitFor();
|
||||
assert.deepEqual(writes, [], 'a newer value needs another review before it is overwritten');
|
||||
failed.add(path);
|
||||
await confirm.click();
|
||||
await dialog.getByText('Save temporarily unavailable').waitFor();
|
||||
const command = ['PUT', path, { text: 'New instructions' }];
|
||||
assert.deepEqual(writes, [command]);
|
||||
await confirm.click();
|
||||
await dialog.waitFor({ state: 'hidden' });
|
||||
assert.deepEqual(writes, [command, command]);
|
||||
assert.equal(saved[path].text, 'New instructions');
|
||||
assert.deepEqual(legacy, []);
|
||||
});
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run the whole stack as local processes against a throwaway PostgreSQL 18,
|
||||
# for manual and scripted checks. Never part of the gate. Nothing here reads
|
||||
# the installed config: XDG paths point into the dev directory.
|
||||
#
|
||||
# e2e/stack.sh start | stop | restart <service> | status | reset
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo=$(cd "$(dirname "$0")/.." && pwd)
|
||||
dir=${ARCHIE_DEV_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/archie-dev}
|
||||
pgport=${ARCHIE_DEV_PGPORT:-55432}
|
||||
services=(archie-state-store archie-gateway archied archie-messaging archie-ui)
|
||||
|
||||
# initdb refuses root, and postgres cannot traverse root's home.
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
pgdata=/var/lib/archie-dev/pg
|
||||
as_pg() { runuser -u postgres -- "$@"; }
|
||||
else
|
||||
pgdata=$dir/pg
|
||||
as_pg() { "$@"; }
|
||||
fi
|
||||
|
||||
export XDG_CONFIG_HOME=$dir/config XDG_DATA_HOME=$dir/data XDG_STATE_HOME=$dir/state
|
||||
|
||||
pgbin() {
|
||||
local d
|
||||
for d in /usr/lib/postgresql/18/bin "$(dirname "$(command -v postgres 2>/dev/null || echo /x/x)")"; do
|
||||
if [ -x "$d/postgres" ] && "$d/postgres" --version | grep -q ' 18\.'; then
|
||||
echo "$d"
|
||||
return
|
||||
fi
|
||||
done
|
||||
echo "PostgreSQL 18 server not found" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
check_process() {
|
||||
local pid
|
||||
if [ ! -f "$dir/pids/$1" ] || ! pid=$(cat "$dir/pids/$1") || ! kill -0 "$pid" 2>/dev/null; then
|
||||
echo "$1 exited; see $dir/logs/$1.log" >&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
wait_port() {
|
||||
for _ in $(seq 1 "${3:-60}"); do
|
||||
check_process "$2" || return 1
|
||||
(echo >"/dev/tcp/127.0.0.1/$1") 2>/dev/null && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "$2 did not listen on $1; see $dir/logs/$2.log" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
start_pg() {
|
||||
local bin
|
||||
bin=$(pgbin)
|
||||
if [ ! -f "$pgdata/PG_VERSION" ]; then
|
||||
mkdir -p "$pgdata"
|
||||
[ "$(id -u)" -ne 0 ] || chown postgres "$pgdata"
|
||||
as_pg "$bin/initdb" -D "$pgdata" -U archie --auth=trust >/dev/null
|
||||
fi
|
||||
if ! as_pg "$bin/pg_ctl" -D "$pgdata" status >/dev/null 2>&1; then
|
||||
as_pg "$bin/pg_ctl" -D "$pgdata" -w -l "$pgdata/server.log" \
|
||||
-o "-p $pgport -k $pgdata -c listen_addresses=127.0.0.1" start >/dev/null
|
||||
fi
|
||||
"$bin/psql" -h 127.0.0.1 -p "$pgport" -U archie -d postgres -qtAc \
|
||||
"SELECT 1 FROM pg_database WHERE datname = 'archie'" | grep -q 1 ||
|
||||
"$bin/createdb" -h 127.0.0.1 -p "$pgport" -U archie archie
|
||||
}
|
||||
|
||||
prepare() {
|
||||
mkdir -p "$dir"/{bin,logs,pids} "$XDG_CONFIG_HOME/archie" "$XDG_DATA_HOME" "$XDG_STATE_HOME"
|
||||
[ -f "$XDG_CONFIG_HOME/archie/config.toml" ] || cp "$repo/config.example.toml" "$XDG_CONFIG_HOME/archie/config.toml"
|
||||
# The services serve from the least-privilege role and migrate as the schema
|
||||
# owner; initdb's archie role is the throwaway server's superuser only.
|
||||
sed -e "s#^database_url = .*#database_url = \"postgres://archie_runtime@127.0.0.1:$pgport/archie?sslmode=disable\"#" \
|
||||
-e "s#^migration_database_url = .*#migration_database_url = \"postgres://archie_migrator@127.0.0.1:$pgport/archie?sslmode=disable\"#" \
|
||||
"$repo/deployments/dev.toml" >"$dir/dev.toml"
|
||||
local version
|
||||
version=$(git -C "$repo" describe --tags --exact-match --match 'v[0-9]*' 2>/dev/null || true)
|
||||
version=${version#v}
|
||||
[ -n "$version" ] || version="dev+$(git -C "$repo" rev-parse --short=12 HEAD)"
|
||||
task --dir "$repo" dev:tls
|
||||
task --dir "$repo" --force build BIN_DIR="$dir/bin" GATEWAY_VERSION="$version" RUNTIME_VERSION="$version"
|
||||
}
|
||||
|
||||
# spawn NAME DIR CMD...: a detached session leader, so stop takes its children.
|
||||
spawn() {
|
||||
local name=$1 cwd=$2
|
||||
shift 2
|
||||
rm -f "$dir/pids/$name"
|
||||
setsid -f bash -c 'cd "$1" && echo $$ >"$2" && shift 2 && exec "$@"' _ "$cwd" "$dir/pids/$name" "$@" \
|
||||
</dev/null >"$dir/logs/$name.log" 2>&1 9>&-
|
||||
for _ in $(seq 1 50); do
|
||||
[ ! -f "$dir/pids/$name" ] || { check_process "$name"; return; }
|
||||
sleep 0.1
|
||||
done
|
||||
echo "$name did not start; see $dir/logs/$name.log" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
start_service() {
|
||||
spawn "$1" "$repo" "$dir/bin/$1" -config-overlay "$dir/dev.toml"
|
||||
}
|
||||
|
||||
# provision_roles creates the least-privilege roles the stack connects as. The
|
||||
# throwaway server runs with trust auth, so the role URLs' passwords are never
|
||||
# checked; they are here only because provision sets the role password it reads.
|
||||
provision_roles() {
|
||||
"$dir/bin/archie-state-store" provision \
|
||||
-admin-url "postgres://archie@127.0.0.1:$pgport/archie?sslmode=disable" \
|
||||
-runtime-url "postgres://archie_runtime:e2e@127.0.0.1:$pgport/archie?sslmode=disable" \
|
||||
-migration-url "postgres://archie_migrator:e2e@127.0.0.1:$pgport/archie?sslmode=disable"
|
||||
}
|
||||
|
||||
stop_pid() {
|
||||
local f=$1 pid
|
||||
[ -f "$f" ] || return 0
|
||||
pid=$(cat "$f")
|
||||
if kill -- "-$pid" 2>/dev/null; then
|
||||
for _ in $(seq 1 20); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done
|
||||
kill -9 -- "-$pid" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$f"
|
||||
}
|
||||
|
||||
start() {
|
||||
local port
|
||||
for port in 9091 8585 8586 8587 8485 8484 5173; do
|
||||
if (echo >"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
|
||||
echo "Port $port is already in use. Run task e2e:down before task e2e:up; if it stays occupied, inspect its owner with ss -ltnp." >&2
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
trap 'trap - ERR; stop' ERR
|
||||
prepare
|
||||
start_pg 9>&-
|
||||
provision_roles
|
||||
start_service archie-state-store
|
||||
wait_port 9091 archie-state-store 90
|
||||
local s
|
||||
for s in archie-gateway archied archie-messaging archie-ui; do start_service "$s"; done
|
||||
wait_port 8585 archie-gateway
|
||||
wait_port 8586 archie-messaging
|
||||
wait_port 8485 archied
|
||||
wait_port 8484 archie-ui
|
||||
[ -d "$repo/ui/node_modules" ] || (cd "$repo/ui" && pnpm install --frozen-lockfile >/dev/null)
|
||||
spawn vite "$repo/ui" pnpm exec vite --host 127.0.0.1 --port 5173 --strictPort
|
||||
wait_port 5173 vite
|
||||
for s in "${services[@]}" vite; do check_process "$s"; done
|
||||
trap - ERR
|
||||
echo "dashboard: http://localhost:5173 logs: $dir/logs"
|
||||
}
|
||||
|
||||
stop() {
|
||||
local f
|
||||
for f in "$dir"/pids/*; do stop_pid "$f"; done
|
||||
if [ -f "$pgdata/PG_VERSION" ]; then
|
||||
as_pg "$(pgbin)/pg_ctl" -D "$pgdata" -m fast stop >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
# Keep concurrent invocations from replacing each other's process records.
|
||||
mkdir -p "$dir"
|
||||
exec 9>"$dir/stack.lock"
|
||||
flock -n 9 || { echo "Another e2e stack command is running" >&2; exit 1; }
|
||||
|
||||
case ${1:-} in
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
restart)
|
||||
stop_pid "$dir/pids/${2:?service}"
|
||||
start_service "$2"
|
||||
;;
|
||||
status)
|
||||
for f in "$dir"/pids/*; do
|
||||
[ -f "$f" ] || continue
|
||||
if kill -0 "$(cat "$f")" 2>/dev/null; then echo "up $(basename "$f")"; else echo "down $(basename "$f")"; fi
|
||||
done
|
||||
;;
|
||||
reset)
|
||||
stop
|
||||
rm -rf "$dir" "$pgdata"
|
||||
;;
|
||||
*)
|
||||
echo "usage: $0 start | stop | restart <service> | status | reset" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
+10
-27
@@ -3,10 +3,8 @@ package archie
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -50,10 +48,9 @@ type gate struct {
|
||||
problem string
|
||||
}
|
||||
|
||||
// newGate returns a closed gate over the operational handler and the dashboard
|
||||
// build its assets come from.
|
||||
func newGate(ops http.Handler, dist fs.FS) *gate {
|
||||
return &gate{ops: ops, setup: setupSurface(ops, dist)}
|
||||
// newGate returns a closed gate over the operational handler.
|
||||
func newGate(ops http.Handler) *gate {
|
||||
return &gate{ops: ops, setup: setupSurface(ops)}
|
||||
}
|
||||
|
||||
func (g *gate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -112,9 +109,9 @@ func serveSurface(checks *health.Registry, g *gate) *http.ServeMux {
|
||||
}
|
||||
|
||||
// setupSurface answers the routes the setup page needs and refuses the rest.
|
||||
func setupSurface(ops http.Handler, dist fs.FS) http.Handler {
|
||||
func setupSurface(ops http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !setupRequest(r, dist) {
|
||||
if !setupRequest(r) {
|
||||
httpjson.Error(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
@@ -122,31 +119,17 @@ func setupSurface(ops http.Handler, dist fs.FS) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// setupRequest is the whole routing decision while the gate is closed: the setup
|
||||
// page, the files it loads, and the two account operations it calls. Nothing else
|
||||
// passes, so neither a deep link into the SPA nor a setup route called with the
|
||||
// wrong method reaches a handler.
|
||||
func setupRequest(r *http.Request, dist fs.FS) bool {
|
||||
// setupRequest is the whole routing decision while the gate is closed: the two
|
||||
// account operations the dashboard's setup page calls. Nothing else passes, so
|
||||
// a setup route called with the wrong method never reaches a handler.
|
||||
func setupRequest(r *http.Request) bool {
|
||||
switch r.URL.Path {
|
||||
case setUpAccountPath:
|
||||
return r.Method == http.MethodPost
|
||||
case authStatusPath:
|
||||
return r.Method == http.MethodGet || r.Method == http.MethodHead
|
||||
}
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
return false
|
||||
}
|
||||
return r.URL.Path == "/" || builtFile(r.URL.Path, dist)
|
||||
}
|
||||
|
||||
// builtFile reports whether path names a file in the dashboard build. A route
|
||||
// inside the SPA does not, so a deep link cannot be served the setup page.
|
||||
func builtFile(path string, dist fs.FS) bool {
|
||||
if dist == nil {
|
||||
return false
|
||||
}
|
||||
info, err := fs.Stat(dist, strings.TrimPrefix(path, "/"))
|
||||
return err == nil && !info.IsDir()
|
||||
return false
|
||||
}
|
||||
|
||||
// setupLookup reads whether owner setup is still required. Durable state is the
|
||||
|
||||
@@ -11,11 +11,9 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/dashboard"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
@@ -57,19 +55,13 @@ func (r *reached) paths() []string {
|
||||
return append([]string(nil), r.seen...)
|
||||
}
|
||||
|
||||
// testServer builds the surface Run serves, with a stand-in for the API beside
|
||||
// the real dashboard handler. The stand-in answers the routes the setup page
|
||||
// calls and records every other route a request can reach.
|
||||
// testServer builds the surface Run serves, with a stand-in for the API. The
|
||||
// stand-in answers the routes the setup page calls and records every other
|
||||
// route a request can reach.
|
||||
func testServer(t *testing.T) (*http.ServeMux, *reached, *gate) {
|
||||
t.Helper()
|
||||
hit := &reached{}
|
||||
dist := fstest.MapFS{
|
||||
"index.html": {Data: []byte("<html>archie setup</html>")},
|
||||
"favicon.svg": {Data: []byte("<svg>")},
|
||||
"assets/app.js": {Data: []byte("console.log(1)")},
|
||||
}
|
||||
ops := http.NewServeMux()
|
||||
dashboard.Routes(ops, dist)
|
||||
ops.HandleFunc("GET "+authStatusPath, func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"setup_required":true,"user":null}`))
|
||||
})
|
||||
@@ -86,7 +78,7 @@ func testServer(t *testing.T) (*http.ServeMux, *reached, *gate) {
|
||||
|
||||
checks := health.NewRegistry()
|
||||
checks.Register("database", func(context.Context) error { return nil })
|
||||
g := newGate(ops, dist)
|
||||
g := newGate(ops)
|
||||
return serveSurface(checks, g), hit, g
|
||||
}
|
||||
|
||||
@@ -112,16 +104,10 @@ func TestClosedGateServesOnlySetup(t *testing.T) {
|
||||
admin bool
|
||||
status int
|
||||
body string
|
||||
// servedAsPage marks a response the dashboard handler writes, which must
|
||||
// keep the CSP that stops chat-rendered Markdown loading a remote image.
|
||||
servedAsPage bool
|
||||
}{
|
||||
{name: "auth status", method: http.MethodGet, path: authStatusPath, status: http.StatusOK, body: `"setup_required":true`},
|
||||
{name: "auth status by head", method: http.MethodHead, path: authStatusPath, status: http.StatusOK},
|
||||
{name: "set up the owner", method: http.MethodPost, path: setUpAccountPath, status: http.StatusCreated},
|
||||
{name: "the setup page", method: http.MethodGet, path: "/", status: http.StatusOK, body: "archie setup", servedAsPage: true},
|
||||
{name: "a script the page loads", method: http.MethodGet, path: "/assets/app.js", status: http.StatusOK, body: "console.log(1)", servedAsPage: true},
|
||||
{name: "the page icon", method: http.MethodGet, path: "/favicon.svg", status: http.StatusOK, body: "<svg>", servedAsPage: true},
|
||||
{name: "liveness", method: http.MethodGet, path: "/healthz", status: http.StatusOK, body: "ok\n"},
|
||||
|
||||
// From here down nothing reaches a handler, credential or not.
|
||||
@@ -139,9 +125,8 @@ func TestClosedGateServesOnlySetup(t *testing.T) {
|
||||
{name: "setup by GET", method: http.MethodGet, path: setUpAccountPath, status: http.StatusNotFound},
|
||||
{name: "status by POST", method: http.MethodPost, path: authStatusPath, status: http.StatusNotFound},
|
||||
{name: "status with a trailing slash", method: http.MethodGet, path: authStatusPath + "/", status: http.StatusNotFound},
|
||||
{name: "the page by POST", method: http.MethodPost, path: "/", status: http.StatusNotFound},
|
||||
{name: "a script by POST", method: http.MethodPost, path: "/assets/app.js", status: http.StatusNotFound},
|
||||
{name: "a file the build has no name for", method: http.MethodGet, path: "/assets/missing.js", status: http.StatusNotFound},
|
||||
{name: "the root path", method: http.MethodGet, path: "/", status: http.StatusNotFound},
|
||||
{name: "a dashboard asset", method: http.MethodGet, path: "/assets/app.js", status: http.StatusNotFound},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
@@ -157,12 +142,6 @@ func TestClosedGateServesOnlySetup(t *testing.T) {
|
||||
if got := hit.count(); got != 0 {
|
||||
t.Fatalf("%s %s: %d operational handlers ran, want none (reached %v)", tc.method, tc.path, got, hit.paths())
|
||||
}
|
||||
if tc.servedAsPage {
|
||||
// Mirrors the dashboard's own header: the setup page must not lose it.
|
||||
if got := rec.Header().Get("Content-Security-Policy"); got != "img-src 'self' data:" {
|
||||
t.Fatalf("%s %s: Content-Security-Policy = %q, want the dashboard's", tc.method, tc.path, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -187,7 +166,6 @@ func TestOpenGateServesOperations(t *testing.T) {
|
||||
{name: "OpenAPI document", method: http.MethodGet, path: "/api/openapi", status: http.StatusOK, handled: 1},
|
||||
{name: "sign in", method: http.MethodPost, path: "/api/auth/login", status: http.StatusOK, handled: 1},
|
||||
{name: "OIDC sign in", method: http.MethodGet, path: "/oauth2/login", status: http.StatusOK, handled: 1},
|
||||
{name: "a route inside the SPA", method: http.MethodGet, path: "/tasks", status: http.StatusOK, body: "archie setup"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/platform/deletions"
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/internal/platform/hub"
|
||||
"github.com/samcharles93/archie-core/internal/platform/pg"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
@@ -33,7 +34,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/chat"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/dashboard"
|
||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
@@ -42,7 +42,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/modules/proposals"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
)
|
||||
|
||||
// deletionRecordRetry is how often an incomplete record of a committed deletion
|
||||
@@ -277,9 +276,9 @@ func wire(log *slog.Logger, cfg Config, db *sqlx.DB, draining *atomic.Bool, metr
|
||||
hear: hear, judge: judge, engine: engine, chat: talk, proposals: proposed,
|
||||
notes: remember, auditLog: auditLog, db: db, bundleLog: log.With("module", "bundles"), live: live,
|
||||
}.register(api)
|
||||
dashboard.Routes(mux, ui.DistDirFS)
|
||||
mux.HandleFunc("/", unclaimed)
|
||||
|
||||
g := newGate(mux, ui.DistDirFS)
|
||||
g := newGate(mux)
|
||||
served := http.Handler(serveSurface(checks, g))
|
||||
if metrics != nil {
|
||||
served = metrics.Middleware(served)
|
||||
@@ -297,6 +296,12 @@ func wire(log *slog.Logger, cfg Config, db *sqlx.DB, draining *atomic.Bool, metr
|
||||
}, nil
|
||||
}
|
||||
|
||||
// unclaimed answers a path no module registered. The dashboard is served
|
||||
// separately, so every such path is a JSON 404.
|
||||
func unclaimed(w http.ResponseWriter, _ *http.Request) {
|
||||
httpjson.Error(w, http.StatusNotFound, "no such route")
|
||||
}
|
||||
|
||||
func wireMemory(db *sqlx.DB, log *slog.Logger, stateDir string, checks *health.Registry) (*memory.Module, error) {
|
||||
// The record of deletions outlives this process and its database, so the
|
||||
// log exists before anything can be deleted: an instance that has run this
|
||||
|
||||
File renamed without changes.
@@ -2,38 +2,40 @@ package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/prompts"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/ui/pages"
|
||||
)
|
||||
|
||||
// DashboardPage describes one dashboard surface so the chat agent can both
|
||||
// understand what each place is for and point the operator there. It is the
|
||||
// catalogue the dashboard's own navigation renders from (ui/pages), so a page
|
||||
// the assistant can name is a page the operator can reach.
|
||||
// understand what each place is for and point the operator there.
|
||||
type DashboardPage struct {
|
||||
// Path is the route (e.g. "/tasks"). It is what the browser hash becomes.
|
||||
Path string
|
||||
Path string `json:"path"`
|
||||
// Label is the human name the navigation shows (e.g. "Tasks").
|
||||
Label string
|
||||
Label string `json:"label"`
|
||||
// Description is a one-line plain-language explanation of what the page
|
||||
// shows, so the agent can answer "where do I go for that?" correctly.
|
||||
Description string
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// dashboardPages is a snapshot of the dashboard's page catalogue, taken when
|
||||
// the dashboard moved to its own repository. This service is being replaced,
|
||||
// so the snapshot is not kept in step with the dashboard.
|
||||
//
|
||||
//go:embed dashboard_pages.json
|
||||
var dashboardPages []byte
|
||||
|
||||
// DashboardPages returns the dashboard's page catalogue, in its own order.
|
||||
func DashboardPages() ([]DashboardPage, error) {
|
||||
catalogue, err := pages.All()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]DashboardPage, 0, len(catalogue))
|
||||
for _, p := range catalogue {
|
||||
out = append(out, DashboardPage{Path: p.Path, Label: p.Label, Description: p.Description})
|
||||
var out []DashboardPage
|
||||
if err := json.Unmarshal(dashboardPages, &out); err != nil {
|
||||
return nil, fmt.Errorf("dashboard pages: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAssetsFallbackStopsAtAPI(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"/api/control-plane/unknown", http.StatusNotFound},
|
||||
{"/tasks/12", http.StatusOK},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.path, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
new(Server).assets().ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, tt.path, nil))
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status %d, want %d", rec.Code, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package webui
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -12,8 +11,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/klauspost/compress/gzhttp"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/audit"
|
||||
@@ -28,7 +25,6 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
@@ -395,45 +391,12 @@ func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}
|
||||
|
||||
// assets serves the embedded dashboard, falling back to index.html so client
|
||||
// routes deep-link correctly. An unserved /api path is a 404, never the page.
|
||||
// Under the no_ui build tag the assets are absent and a plain explanation is
|
||||
// served instead of a confusing 404.
|
||||
// assets answers every path no handler claimed. The dashboard ships as its own
|
||||
// image, and this service does not serve it.
|
||||
func (s *Server) assets() http.Handler {
|
||||
if ui.DistDirFS == nil {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "dashboard not built into this binary (no_ui)", http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
files := http.FileServerFS(ui.DistDirFS)
|
||||
return gzhttp.GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
http.Error(w, "this archied does not serve "+r.URL.Path, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if _, err := fs.Stat(ui.DistDirFS, trimLeadingSlash(r.URL.Path)); err != nil {
|
||||
r = r.Clone(r.Context())
|
||||
r.URL.Path = "/"
|
||||
}
|
||||
// Asset names carry a content hash, so a cached copy never goes stale;
|
||||
// index.html names the current hashes and must always be revalidated.
|
||||
if strings.HasPrefix(r.URL.Path, "/assets/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
func trimLeadingSlash(p string) string {
|
||||
if len(p) > 0 && p[0] == '/' {
|
||||
return p[1:]
|
||||
}
|
||||
if p == "" {
|
||||
return "."
|
||||
}
|
||||
return p
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "this service does not serve "+r.URL.Path, http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
// healthDetailedRoute is the instance health report.
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
// Package dashboard serves the single binary's SPA: index.html and its
|
||||
// assets from the embedded build. Every other route belongs to a module.
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
)
|
||||
|
||||
const page = "index.html"
|
||||
|
||||
// csp is the browser-side backstop for chat-rendered Markdown: no remote
|
||||
// image may load, so a reply cannot leak data through an image request. It
|
||||
// is image-only on purpose; every other directive would risk breaking the
|
||||
// SPA's scripts and styles.
|
||||
const csp = "img-src 'self' data:"
|
||||
|
||||
// Routes serves the SPA from dist on mux. A path under /api/ that no module
|
||||
// claimed is a JSON 404, never the page. With no build embedded, the page
|
||||
// says how to build it.
|
||||
//
|
||||
// One pattern serves both: a method-scoped fallback beside the /api/ catch-all
|
||||
// is a ServeMux conflict, since Go matches the more general pattern for the
|
||||
// methods the other doesn't name.
|
||||
func Routes(mux *http.ServeMux, dist fs.FS) {
|
||||
mux.Handle("/", handler(dist))
|
||||
}
|
||||
|
||||
func handler(dist fs.FS) http.Handler {
|
||||
if dist == nil {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
httpjson.Error(w, http.StatusNotFound, "no such route")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Security-Policy", csp)
|
||||
http.Error(w, "this binary was built without the dashboard; run task ui and rebuild", http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
files := http.FileServerFS(dist)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
httpjson.Error(w, http.StatusNotFound, "no such route")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Security-Policy", csp)
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
w.Header().Set("Allow", "GET, HEAD")
|
||||
http.Error(w, "the dashboard is read-only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
name := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if name != "" && name != page {
|
||||
if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() {
|
||||
if strings.HasPrefix(name, "assets/") {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Every other path is a route inside the SPA.
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeFileFS(w, r, dist, page)
|
||||
})
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
// TestRoutesServeThePageBesideTheAPICatchAll guards a boot-time panic: a
|
||||
// method-scoped "GET /" fallback cannot sit beside the "/api/" catch-all on one
|
||||
// ServeMux, so the binary crashed on start with the dashboard built in. It also
|
||||
// pins what each path answers: an unclaimed API path is a JSON 404 rather than
|
||||
// the page, and the page is read-only.
|
||||
func TestRoutesServeThePageBesideTheAPICatchAll(t *testing.T) {
|
||||
dist := fstest.MapFS{
|
||||
page: &fstest.MapFile{Data: []byte("<html>archie</html>")},
|
||||
"assets/app-1.js": &fstest.MapFile{Data: []byte("console.log(1)")},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
dist fs.FS
|
||||
method string
|
||||
path string
|
||||
wantStatus int
|
||||
wantContent string
|
||||
// wantCSP pins the image-only Content-Security-Policy backstop on
|
||||
// every non-API response (#2073); API fallbacks must not carry it.
|
||||
wantCSP string
|
||||
}{
|
||||
{name: "the page serves a client route", dist: dist, method: http.MethodGet, path: "/runs/42", wantStatus: http.StatusOK, wantContent: "<html>archie</html>", wantCSP: "img-src 'self' data:"},
|
||||
{name: "an asset serves as itself", dist: dist, method: http.MethodGet, path: "/assets/app-1.js", wantStatus: http.StatusOK, wantContent: "console.log(1)", wantCSP: "img-src 'self' data:"},
|
||||
{name: "an unclaimed API path is JSON", dist: dist, method: http.MethodGet, path: "/api/nope", wantStatus: http.StatusNotFound, wantContent: "no such route"},
|
||||
{name: "an API path denies every method", dist: dist, method: http.MethodPost, path: "/api/nope", wantStatus: http.StatusNotFound, wantContent: "no such route"},
|
||||
{name: "the page is read-only", dist: dist, method: http.MethodPost, path: "/runs", wantStatus: http.StatusMethodNotAllowed, wantContent: "read-only", wantCSP: "img-src 'self' data:"},
|
||||
{name: "a build without the dashboard says how to make it", method: http.MethodGet, path: "/runs", wantStatus: http.StatusNotFound, wantContent: "task ui", wantCSP: "img-src 'self' data:"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
Routes(mux, tt.dist)
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
|
||||
if w.Code != tt.wantStatus {
|
||||
t.Fatalf("status = %d, want %d", w.Code, tt.wantStatus)
|
||||
}
|
||||
if body := w.Body.String(); !strings.Contains(body, tt.wantContent) {
|
||||
t.Fatalf("body = %q, want it to contain %q", body, tt.wantContent)
|
||||
}
|
||||
if csp := w.Header().Get("Content-Security-Policy"); csp != tt.wantCSP {
|
||||
t.Fatalf("Content-Security-Policy = %q, want %q", csp, tt.wantCSP)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package dashboard serves the dashboard's live event stream.
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
|
||||
+1
-10
@@ -44,14 +44,6 @@ go install "github.com/bufbuild/buf/cmd/buf@$BUF_VERSION"
|
||||
go install "google.golang.org/protobuf/cmd/protoc-gen-go@$PROTOC_GEN_GO_VERSION"
|
||||
go install "google.golang.org/grpc/cmd/protoc-gen-go-grpc@$PROTOC_GEN_GO_GRPC_VERSION"
|
||||
|
||||
# PostgreSQL 18 for e2e/stack.sh, which runs its own cluster. Never for
|
||||
# tests: they use fakes.
|
||||
if [ ! -x /usr/lib/postgresql/18/bin/postgres ]; then
|
||||
$SUDO apt-get install -y --no-install-recommends postgresql-common
|
||||
$SUDO /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
|
||||
$SUDO apt-get install -y --no-install-recommends postgresql-18
|
||||
fi
|
||||
|
||||
# Commit and PR attribution stays off, matching local settings.
|
||||
mkdir -p "$HOME/.claude"
|
||||
settings="$HOME/.claude/settings.json"
|
||||
@@ -77,11 +69,10 @@ git config --global user.email sam@catlow.tech
|
||||
# tools onto the default PATH instead.
|
||||
$SUDO ln -sf /usr/local/go/bin/* "$GOBIN"/* /usr/local/bin/
|
||||
|
||||
# Warm module and pnpm caches when the checkout is already present.
|
||||
# Warm the module cache when the checkout is already present.
|
||||
repo=${CLAUDE_PROJECT_DIR:-$PWD}
|
||||
if [ -f "$repo/go.mod" ] && grep -q archie-core "$repo/go.mod"; then
|
||||
(cd "$repo" && go mod download && go -C tools mod download)
|
||||
(cd "$repo/ui" && corepack enable pnpm && pnpm install --frozen-lockfile)
|
||||
fi
|
||||
|
||||
go version
|
||||
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
# UI agent rules
|
||||
|
||||
These rules supplement the repository root's AGENTS.md. Its authority, service
|
||||
boundaries, security invariants, issue workflow and commit gate still apply.
|
||||
CLAUDE.md points here so both agents use one policy.
|
||||
|
||||
## Scope
|
||||
|
||||
The dashboard is Vue 3, TypeScript, Pinia and Vue Router, with Tailwind and
|
||||
vendored shadcn-vue components backed by Reka UI. It talks to the control plane
|
||||
through src/lib/api.ts. The server owns contracts, authorisation and durable
|
||||
state; the UI presents them and submits operator choices.
|
||||
|
||||
- Fix broken behaviour with the smallest complete change. Finish existing
|
||||
features before adding new ones. Do not add an abstraction or dependency for a
|
||||
few lines of code.
|
||||
- Read the affected callers and existing components before editing. Keep feature
|
||||
state and behaviour in its feature folder; shared code must have real
|
||||
consumers. Do not extract production helpers solely to make them testable.
|
||||
- Preserve server vocabulary and typed wire values. Do not invent local status,
|
||||
action or model catalogues when the server supplies them.
|
||||
- Keep requests in src/lib/api.ts and shared live updates in the existing store.
|
||||
Preserve its authentication, CSRF, timeout and error handling.
|
||||
- Keep unavailable, loading, empty and failed states distinct. Show failures
|
||||
where they occur; an unreadable list must not look like an empty one.
|
||||
- Async views must discard stale responses after their task, attempt or route
|
||||
changes. A setting must save through the API and show its applied state.
|
||||
- Build in safety. Edits go to a draft and reach the running workflow only when
|
||||
you publish.
|
||||
- Never lose work silently. If two things can write the same state (for example,
|
||||
Archie and the operator), lock one out or merge them; never let one silently
|
||||
overwrite the other.
|
||||
- Phone width is a real target. No global CSS rule may deform controls. Desktop
|
||||
layouts must collapse cleanly: dropdowns instead of side lists, stacked panes,
|
||||
and nothing overlapping the canvas.
|
||||
|
||||
## Routing and layout
|
||||
|
||||
- Routes are files. `src/pages/` mirrors the URL: a list is `index.vue`, its
|
||||
detail is `[id].vue`, and a section's shared frame is `<name>.vue` beside the
|
||||
`<name>/` folder. Nav label, description, `section` and `navPath` go in the
|
||||
page's `definePage` meta; `pages.json` is generated from it.
|
||||
- A page's own code lives beside it: `components/` for `.vue` files (excluded
|
||||
from routing) and `lib/` for modules. Code used by several pages goes in
|
||||
`src/components`, `src/lib` or `src/stores`, never in another page's folder.
|
||||
- Layouts are `src/layouts`, chosen by `meta.layout`. Change shared chrome there,
|
||||
not in a page.
|
||||
- State that picks a view (a tab, a step) is a route, not `?tab=`. Query strings
|
||||
carry filters and selections only.
|
||||
|
||||
## Product scope
|
||||
|
||||
- Respect the existing feature set. New features honour instructions, policies,
|
||||
grants and the access model (ReBAC/ABAC with Cedar). An agent tool never
|
||||
reaches further than its caller could through the dashboard.
|
||||
- Agentic automation, not a coding agent. A repository is one optional input to
|
||||
a workflow, not the frame for anything.
|
||||
- Smallest change first. Reuse what exists, such as the change-review list,
|
||||
drafts and the existing MCP bridge, before adding new mechanism.
|
||||
|
||||
## Components and interaction
|
||||
|
||||
- Build pages only from components/ui and the page frame in src/base (PageHeader
|
||||
for a page title and its actions, CodeView for code or a payload with a copy
|
||||
button). Use Section for a titled card, SettingRow for a setting, MetadataList
|
||||
for label/value pairs, and DataTable for a table with optional columns. Use
|
||||
Item for a list row, Field for a form field, Badge and StatusDot for state,
|
||||
and Timestamp for times. Use MoreMenu for overflow actions, Empty for empty
|
||||
states (including an empty value or result), ReadError for a failed read, and
|
||||
Skeleton while loading. Use Trace for an agent's steps and
|
||||
CodeBlockCopyButton to copy an ID or value. Use the type scale (text-caption,
|
||||
text-label, text-title) instead of pixel sizes.
|
||||
Never hand-roll a card, heading, caption, status dot, copy button or date
|
||||
format; if a pattern is missing, add it to components/ui with a real consumer
|
||||
first.
|
||||
- Add and update components/ui components with the shadcn-vue CLI, never by
|
||||
writing or copying them by hand: `pnpm dlx shadcn-vue@latest add <name>` from
|
||||
`ui/`, or the component's registry URL when the maintainer names one. Search
|
||||
the registry before writing a missing pattern yourself, and write one only
|
||||
when no registry has it. The CLI runs through `pnpm dlx`, so it never joins
|
||||
the application's dependencies.
|
||||
- Reuse components/ui and surrounding composition patterns before writing new
|
||||
markup.
|
||||
- Use semantic theme tokens, existing variants and cn() for conditional classes.
|
||||
Support both themes, compact density and reduced motion.
|
||||
- Keep controls compact and contextual. Use on-demand panels and inline
|
||||
hover/focus icon actions rather than permanent chrome. Do not repeat labels in
|
||||
explanatory text or add controls without working behaviour.
|
||||
- Text states a problem or an action, nothing else. Delete lines that only
|
||||
describe what the screen already shows (for example, "Compared with the
|
||||
current definition", "Same as the current definition", "Refreshed every 5
|
||||
seconds", "Showing recent matches…", "Live only").
|
||||
- Do not label a control that explains itself. A switch needs no "Enabled"
|
||||
beside it, and `+` needs no "New workflow" next to it. Put the name in the
|
||||
accessible name or tooltip.
|
||||
- Option labels do not repeat their category. Under "Checks", list "Repository",
|
||||
"Diff size" and "Diff rules", not "Repository gate".
|
||||
- Name things after what you are working with. The page sets context, so use
|
||||
"Restore default" not "Restore shipped workflows".
|
||||
- No filler or guidance text. Delete empty-state essays, hints that repeat the
|
||||
label, and sentences explaining how the UI works. Don't say the UI hides
|
||||
secret values when the control only displays credential names.
|
||||
- Use Archie's product names. The editor helper is "Build with Archie" or
|
||||
"Iterate with Archie", never generic terms like "Ask bar".
|
||||
- Actions live where their scope lives. Bulk or instance-wide actions (for
|
||||
example, restoring defaults) belong on the settings page for that area, not in
|
||||
a working view's header menu.
|
||||
- No side panels for editing workflows. Settings, trigger and steps expand in
|
||||
place on the canvas, one at a time, with the main field first and the rest
|
||||
tucked away.
|
||||
- Editor and live view are one surface. Runs show on the same cards you edit.
|
||||
- Use Select components for a known set of options. Avoid native selects and
|
||||
free text. Use the same button and badge styles as the settings pages.
|
||||
- Preserve keyboard operation, visible focus, accessible names, dialog titles
|
||||
and table semantics. A hover action must also be reachable by keyboard.
|
||||
- Keep filtering and pagination consistent with the server. State limitations
|
||||
such as sorting only loaded rows when they affect the operator's decision.
|
||||
- `@ui-sdk/vue` and `@ui-sdk/core` are adopted incrementally alongside
|
||||
`components/ui` (`shadcn-vue` / Reka UI) for high-value interactive
|
||||
components and custom behaviours. Before writing or editing `@ui-sdk` code,
|
||||
read `node_modules/@ui-sdk/core/skills/ui-sdk/SKILL.md` and
|
||||
`node_modules/@ui-sdk/vue/docs/llms.txt` (and `core.md` / `rendering.md` when
|
||||
building a custom primitive). Give every `@ui-sdk` control a clear accessible
|
||||
name, sync state through change callbacks, and mark destructive actions with
|
||||
`data-agent-confirm`.
|
||||
|
||||
## Tests
|
||||
|
||||
The default is no new test. Add one for a reproduced bug or a change to a
|
||||
security boundary or workflow contract, following the root policy. A regression
|
||||
must fail on the relevant assertion before the fix.
|
||||
|
||||
- Test observable behaviour with realistic inputs. Do not test source text,
|
||||
imports, wiring, constants, defaults, type shapes, CSS classes, copied labels,
|
||||
fakes or call order. A fake may support a behaviour test; it is not the
|
||||
subject.
|
||||
- Use one table-driven test per behaviour. Extend its cases rather than adding
|
||||
tests for each branch. Retain meaningful edge cases; reducing the count alone
|
||||
is not a cleanup.
|
||||
- Keep tests fast and cheap to maintain. Test helpers and fixtures belong in
|
||||
test/, never in production code solely for tests.
|
||||
- For mirrored control-plane validators, extend the shared fixture at
|
||||
internal/infrastructure/controlplanestore/testdata/dashboard-validators.json
|
||||
rather than duplicating accept/reject cases in UI-only tests.
|
||||
- Use browser checks for rendered behaviour. Matching a Vue file with a regex
|
||||
does not verify the rendered result. Mocked API checks verify UI behaviour,
|
||||
not live service integration; report that distinction.
|
||||
|
||||
## Verification and delivery
|
||||
|
||||
```bash
|
||||
pnpm test # behaviour tests
|
||||
pnpm run typecheck # TypeScript and Vue checks
|
||||
pnpm run build # rebuild the embedded dashboard
|
||||
pnpm audit # after dependency changes
|
||||
```
|
||||
|
||||
- Run task check from the repository root before committing; stage only the
|
||||
task's own paths. Follow the root's commit and push rules.
|
||||
- ui/dist is build output: `task build` and CI build it before embedding it.
|
||||
Never commit it.
|
||||
- Reuse a running dev server for browser checks. Verify changed interactions,
|
||||
not just a screenshot or successful HTTP response.
|
||||
- Track work and follow-ups as Gitea issues (`tea`). Keep rules here only when
|
||||
they change a decision; do not add task history or Markdown TODO lists.
|
||||
|
||||
## Working with you
|
||||
|
||||
- A clear direction is the go-ahead. Act in the same turn; do not restate the
|
||||
plan, offer options, or ask whether to proceed.
|
||||
- Say each correction once. When you correct something, fix every instance and
|
||||
record the rule here so you do not repeat it.
|
||||
- Delegate to pi workers when asked, and verify their output. Check for overlap
|
||||
before merging, rerun their checks on the combined result, and fix what they
|
||||
find.
|
||||
@@ -1 +0,0 @@
|
||||
AGENTS.md
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"$schema": "https://shadcn-vue.com/schema.json",
|
||||
"style": "reka-nova",
|
||||
"typescript": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/style.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"pointer": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"composables": "@/composables"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
//go:build !no_ui
|
||||
|
||||
// Package ui embeds the built dashboard in dist/. `task ui` builds it, and
|
||||
// `task build` and CI build it before any Go build that embeds it.
|
||||
package ui
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
//go:embed all:dist
|
||||
var distDir embed.FS
|
||||
|
||||
// DistDirFS is the built dashboard rooted at dist/, or nil when the binary
|
||||
// was built with the no_ui tag.
|
||||
var DistDirFS, _ = fs.Sub(distDir, "dist")
|
||||
@@ -1,11 +0,0 @@
|
||||
//go:build no_ui
|
||||
|
||||
package ui
|
||||
|
||||
import "io/fs"
|
||||
|
||||
// DistDirFS is deliberately nil under the no_ui build tag so the dashboard is
|
||||
// not bundled. archie-agent has no use for it, and leaving it out keeps the
|
||||
// per-task container image smaller. internal/webui serves an explanatory page
|
||||
// rather than failing when this is nil.
|
||||
var DistDirFS fs.FS
|
||||
@@ -1,44 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Archie</title>
|
||||
<script>
|
||||
// Set before the first paint so a reload does not flash the wrong
|
||||
// palette or layout. Kept in sync with the appearance Pinia store;
|
||||
// blocked site data falls back to the OS theme, comfortable spacing and
|
||||
// the system motion preference.
|
||||
(function () {
|
||||
var theme = "dark";
|
||||
try {
|
||||
theme = matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
} catch (e) {
|
||||
/* dark stands */
|
||||
}
|
||||
try {
|
||||
var storedTheme = localStorage.getItem("archie.theme");
|
||||
if (storedTheme === "light" || storedTheme === "dark") {
|
||||
theme = storedTheme;
|
||||
}
|
||||
if (localStorage.getItem("archie.density") === "compact") {
|
||||
document.documentElement.dataset.density = "compact";
|
||||
}
|
||||
if (localStorage.getItem("archie.motion") === "reduced") {
|
||||
document.documentElement.dataset.motion = "reduced";
|
||||
}
|
||||
} catch (e) {
|
||||
/* default stands */
|
||||
}
|
||||
document.documentElement.dataset.theme = theme;
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"name": "archie-ui",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test --experimental-strip-types test/*.test.ts",
|
||||
"typecheck": "vue-tsc --build --force"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/ibm-plex-sans": "^5.3.0",
|
||||
"@fontsource/ibm-plex-mono": "^5.3.0",
|
||||
"@lucide/vue": "^1.61.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/vue-form": "^1.33.5",
|
||||
"@ui-sdk/core": "0.1.0-beta.16",
|
||||
"@ui-sdk/vue": "0.1.0-beta.16",
|
||||
"@vue-flow/background": "^1.3.2",
|
||||
"@vue-flow/core": "^1.48.2",
|
||||
"@vueuse/core": "^15.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.5.1",
|
||||
"pinia": "^4.0.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.5",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.2",
|
||||
"shiki": "^4.5.0",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"unified": "^11.0.5",
|
||||
"vue": "^3.5.42",
|
||||
"vue-router": "^5.3.1",
|
||||
"vue-sonner": "^2.0.9",
|
||||
"yaml": "^2.9.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/hast": "^3.0.5",
|
||||
"@types/node": "^26.6.4",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"typescript": "~6.0.3",
|
||||
"vite": "^8.3.0",
|
||||
"vue-tsc": "^3.3.11"
|
||||
},
|
||||
"packageManager": "pnpm@12.10.1"
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Package pages is the dashboard's page catalogue: every route the operator can
|
||||
// reach, with the label its navigation shows and the one-line description the
|
||||
// assistant reads when it points someone at a page.
|
||||
//
|
||||
// pages.json is generated from the dashboard's own route table by
|
||||
// `task pages:generate`, and `task check` rejects it when stale, so the
|
||||
// catalogue cannot list a page the dashboard lost or miss one it gained.
|
||||
package pages
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
//go:embed pages.json
|
||||
var file []byte
|
||||
|
||||
// Page is one destination in the dashboard.
|
||||
type Page struct {
|
||||
// Path is the route, and what the browser's history entry becomes.
|
||||
Path string `json:"path"`
|
||||
// Label is the name the navigation shows.
|
||||
Label string `json:"label"`
|
||||
// Description says what the page is for, so the assistant can answer
|
||||
// "where do I go for that?" without guessing.
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// All returns the catalogue in the dashboard's own order.
|
||||
func All() ([]Page, error) {
|
||||
var out []Page
|
||||
if err := json.Unmarshal(file, &out); err != nil {
|
||||
return nil, fmt.Errorf("dashboard pages: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Generated
-3254
File diff suppressed because it is too large.
Load diff
@@ -1,5 +0,0 @@
|
||||
allowBuilds:
|
||||
vue-demi: true
|
||||
minimumReleaseAgeExclude:
|
||||
- '@ui-sdk/core@0.1.0-beta.16'
|
||||
- '@ui-sdk/vue@0.1.0-beta.16'
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#51a580"><path d="M2 21h4l8-18h-4z"/><path d="M14.9 5.03 22 21h-4l-5.1-11.47z"/><path d="M10.47 15h3.06l1.11 2.5H9.36z"/></svg>
|
||||
|
Before Width: | Height: | Size: 217 B |
@@ -1,24 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.9 KiB |
@@ -1,130 +0,0 @@
|
||||
// Writes pages/pages.json from the file-based pages under src/pages/ and the
|
||||
// redirect table in src/router/redirects.ts.
|
||||
//
|
||||
// The dashboard's pages are the routes it serves, so deriving the catalogue
|
||||
// from them is what stops the assistant naming a page the dashboard lost or
|
||||
// missing one it gained. `task pages:check` fails when the committed file is
|
||||
// stale, which is what makes a new route carry a catalogue entry.
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import ts from "typescript";
|
||||
import { createRoutesContext, resolveOptions } from "vue-router/unplugin";
|
||||
|
||||
import { redirects } from "../src/router/redirects.ts";
|
||||
|
||||
type Meta = { label?: string; description?: string; nav?: boolean };
|
||||
export type Page = { path: string; label: string; description: string };
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const uiRoot = join(here, "..");
|
||||
|
||||
// dynamic is true for a route the operator reaches with an id in it; the
|
||||
// assistant cannot name one, so it stays out of the catalogue.
|
||||
const dynamic = (path: string): boolean => path.includes(":");
|
||||
|
||||
function readDefinePageMeta(file: string): Meta | undefined {
|
||||
const sfc = readFileSync(file, "utf8");
|
||||
const scriptMatch = sfc.match(/<script\b[^>]*\bsetup\b[^>]*>([\s\S]*?)<\/script>/);
|
||||
if (!scriptMatch) return undefined;
|
||||
|
||||
const sf = ts.createSourceFile(file, scriptMatch[1], ts.ScriptTarget.Latest, true);
|
||||
let meta: Meta | undefined;
|
||||
|
||||
const propName = (name: ts.PropertyName): string | undefined => {
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (
|
||||
ts.isCallExpression(node) &&
|
||||
ts.isIdentifier(node.expression) &&
|
||||
node.expression.text === "definePage" &&
|
||||
node.arguments.length > 0 &&
|
||||
ts.isObjectLiteralExpression(node.arguments[0])
|
||||
) {
|
||||
for (const prop of node.arguments[0].properties) {
|
||||
if (
|
||||
ts.isPropertyAssignment(prop) &&
|
||||
propName(prop.name) === "meta" &&
|
||||
ts.isObjectLiteralExpression(prop.initializer)
|
||||
) {
|
||||
const parsed: Meta = {};
|
||||
for (const field of prop.initializer.properties) {
|
||||
if (!ts.isPropertyAssignment(field)) continue;
|
||||
const key = propName(field.name);
|
||||
if (key === "label" && ts.isStringLiteral(field.initializer)) {
|
||||
parsed.label = field.initializer.text;
|
||||
} else if (key === "description" && ts.isStringLiteral(field.initializer)) {
|
||||
parsed.description = field.initializer.text;
|
||||
} else if (key === "nav") {
|
||||
if (field.initializer.kind === ts.SyntaxKind.FalseKeyword) parsed.nav = false;
|
||||
if (field.initializer.kind === ts.SyntaxKind.TrueKeyword) parsed.nav = true;
|
||||
}
|
||||
}
|
||||
meta = parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
|
||||
visit(sf);
|
||||
return meta;
|
||||
}
|
||||
|
||||
const collected: Page[] = [];
|
||||
|
||||
const opts = resolveOptions({
|
||||
root: uiRoot,
|
||||
routesFolder: "src/pages",
|
||||
exclude: ["**/components/**"],
|
||||
dts: false,
|
||||
extendRoute(route) {
|
||||
const file = route.components.get("default");
|
||||
if (!file) return;
|
||||
const path = route.fullPath;
|
||||
if (!path || dynamic(path)) return;
|
||||
const meta = readDefinePageMeta(file);
|
||||
if (meta?.label && meta.nav !== false) {
|
||||
collected.push({
|
||||
path,
|
||||
label: meta.label,
|
||||
description: meta.description ?? "",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const ctx = createRoutesContext(opts);
|
||||
await ctx.scanPages(false);
|
||||
ctx.generateRoutes();
|
||||
|
||||
for (const route of redirects) {
|
||||
const meta = route.meta as Meta | undefined;
|
||||
if (meta?.label && meta.nav !== false && route.path && !dynamic(route.path)) {
|
||||
collected.push({
|
||||
path: route.path,
|
||||
label: meta.label,
|
||||
description: meta.description ?? "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Shell routes and their index children share a path (for example /org and
|
||||
// /controls), so the first label for a path wins rather than listing it twice.
|
||||
const seen = new Set<string>();
|
||||
const pages = collected
|
||||
.filter((page) => {
|
||||
if (seen.has(page.path)) return false;
|
||||
seen.add(page.path);
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
const target = join(uiRoot, "pages", "pages.json");
|
||||
writeFileSync(target, `${JSON.stringify(pages, null, 2)}\n`);
|
||||
|
||||
console.log(`pages: ${pages.length} written to ${target}`);
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { START_LOCATION, useRoute, useRouter } from "vue-router";
|
||||
|
||||
import AccountEntry from "@/accounts/AccountEntry.vue";
|
||||
import { useAccountsStore } from "@/accounts/accounts";
|
||||
|
||||
import ChatDock from "@/chat/ChatDock.vue";
|
||||
import CommandPalette from "@/components/command-palette/CommandPalette.vue";
|
||||
import AccountMenu from "@/components/topbar/AccountMenu.vue";
|
||||
import OrgCrumb from "@/components/topbar/OrgCrumb.vue";
|
||||
import ChatTopbarButton from "@/chat/ChatTopbarButton.vue";
|
||||
import AppSidebar from "@/components/AppSidebar.vue";
|
||||
import SectionCrumb from "@/components/topbar/SectionCrumb.vue";
|
||||
import Brand from "@/components/topbar/Brand.vue";
|
||||
import Logo from "@/components/topbar/Logo.vue";
|
||||
import ConnectionPill from "@/components/topbar/ConnectionPill.vue";
|
||||
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
|
||||
import { layoutComponent, resolveLayout } from "@/layouts";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { hiddenPaths, navTree } from "@/lib/nav";
|
||||
import { pageTitle } from "@/lib/page-title";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import { Toaster } from "vue-sonner";
|
||||
import "vue-sonner/style.css";
|
||||
|
||||
const reauthenticate=new URLSearchParams(window.location.search).has("reauth");
|
||||
const accounts=useAccountsStore();
|
||||
const session = useSessionStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const canvasLayout = computed(() => resolveLayout(route.meta) === "canvas");
|
||||
const hidden = computed(() => hiddenPaths(session.sections));
|
||||
const sectionLink = computed(() =>
|
||||
route.meta.nav === false && typeof route.meta.navPath === "string"
|
||||
? route.meta.navPath
|
||||
: undefined,
|
||||
);
|
||||
const detailCrumb = computed(() => {
|
||||
if (route.meta.nav !== false || !("id" in route.params) || !route.params.id) return "";
|
||||
const id = String(route.params.id);
|
||||
return route.name === "run" ? id.slice(0, 8) : id;
|
||||
});
|
||||
// The redirect below must not run during the router's first navigation: route
|
||||
// is still the start location then, so a deep link would be replaced by the
|
||||
// landing page before it resolves.
|
||||
const routerReady = ref(false);
|
||||
void router.isReady().then(() => {
|
||||
routerReady.value = true;
|
||||
});
|
||||
const main = ref<HTMLElement | null>(null);
|
||||
// A page the caller may not open is not reachable by URL either: the nav drops
|
||||
// it, so a bookmark or a chat link must not land on a form whose saves the
|
||||
// control plane refuses.
|
||||
watch([() => route.path, hidden], () => {
|
||||
if (!routerReady.value) return;
|
||||
if (!hidden.value.includes(typeof route.meta.navPath === "string" ? route.meta.navPath : route.path)) return;
|
||||
// Home may be hidden too, so land on the first destination that is served.
|
||||
const first = navTree(hidden.value).flatMap((node) => (node.kind === "link" ? [node.entry] : node.items))[0];
|
||||
void router.replace(first ? first.path : "/account");
|
||||
});
|
||||
// The tab keeps the served page's title until the router has resolved the
|
||||
// address the browser opened: writing one for the start location reads as a
|
||||
// missing page for as long as that takes.
|
||||
watch(() => [route.path, accounts.instance, routerReady.value], () => {
|
||||
const scope = route.meta.org ? "Organisation" : route.meta.settings ? "Instance" : "";
|
||||
const title = pageTitle(routerReady.value, typeof route.meta.label === "string" ? route.meta.label : "", scope, accounts.instance ?? "", errors.base.notFound.title);
|
||||
if (title) document.title = title;
|
||||
}, { immediate: true });
|
||||
// A page load keeps focus at the top so the skip link is the first keyboard
|
||||
// stop; later navigations move focus to the new page.
|
||||
router.afterEach(async (to, from) => {
|
||||
if (from === START_LOCATION || to.path === from.path) return;
|
||||
await nextTick();
|
||||
main.value?.focus({ preventScroll: true });
|
||||
});
|
||||
|
||||
onMounted(() => {void accounts.load();});
|
||||
// A failed startup read retries on an interval, so a proxy or daemon that
|
||||
// comes back does not need a manual reload.
|
||||
let retryTimer: ReturnType<typeof setInterval> | undefined;
|
||||
watch(() => accounts.error, (message) => {
|
||||
if (message && retryTimer === undefined) retryTimer = setInterval(() => void accounts.load(), 5000);
|
||||
if (!message && retryTimer !== undefined) { clearInterval(retryTimer); retryTimer = undefined; }
|
||||
});
|
||||
onBeforeUnmount(() => { if (retryTimer !== undefined) clearInterval(retryTimer); });
|
||||
watch(() => accounts.status?.user, (user) => {
|
||||
if (!user || reauthenticate) return;
|
||||
session.initialize();
|
||||
// Asked for once, after the shell is up: the nav paints immediately and
|
||||
// loses the entries this process cannot back a moment later, rather than
|
||||
// holding the page behind a request. A failed read hides nothing.
|
||||
void session.loadCapabilities();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main v-if="!accounts.status" class="mx-auto flex min-h-[90dvh] max-w-md flex-col justify-center px-5 py-10">
|
||||
<Card class="gap-0 px-6 py-6 shadow-sm">
|
||||
<div class="mb-2"><Logo /></div>
|
||||
<template v-if="accounts.error">
|
||||
<h1 class="text-title font-medium">{{ errors.app.unreachable }}</h1>
|
||||
<Alert variant="destructive" class="mt-4"><AlertDescription>{{ accounts.error }}</AlertDescription></Alert>
|
||||
<p class="text-caption mt-3 text-fg-muted">{{ errors.app.retrying }}</p>
|
||||
</template>
|
||||
<p v-else class="mt-2" role="status">Connecting to Archie…</p>
|
||||
</Card>
|
||||
</main>
|
||||
<AccountEntry v-else-if="!accounts.status.user || accounts.status.setup_required || reauthenticate" />
|
||||
<TooltipProvider v-else :delay-duration="350">
|
||||
<SidebarProvider class="bg-[var(--workspace)]">
|
||||
<a href="#main-content" class="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-4 focus:z-[60] focus:rounded-md focus:bg-card focus:px-3 focus:py-2">Skip to main content</a>
|
||||
<AppSidebar :hidden="hidden" />
|
||||
<SidebarInset class="min-w-0 bg-[var(--workspace)] md:ml-[var(--chat-pin-l,0px)] md:mr-[var(--chat-pin-r,0px)]" :class="canvasLayout && 'max-md:h-dvh'">
|
||||
<header class="bg-card border-border-strong sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b px-3 shadow-[var(--shadow-sm)] sm:px-4">
|
||||
<Brand />
|
||||
<Breadcrumb class="max-md:min-w-0">
|
||||
<BreadcrumbList class="flex-nowrap gap-1 sm:gap-1">
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem><OrgCrumb /></BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem><SectionCrumb :hidden="hidden" :link="sectionLink" /></BreadcrumbItem>
|
||||
<template v-if="detailCrumb">
|
||||
<BreadcrumbSeparator class="max-md:hidden" />
|
||||
<BreadcrumbItem class="min-w-0 max-md:hidden"><BreadcrumbPage class="truncate" :class="route.name === 'run' && 'font-mono'">{{ detailCrumb }}</BreadcrumbPage></BreadcrumbItem>
|
||||
</template>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
<div class="ml-auto flex shrink-0 items-center gap-4 max-sm:gap-1">
|
||||
<ConnectionPill />
|
||||
<CommandPalette :hidden="hidden" />
|
||||
<ChatTopbarButton v-if="session.sections?.chat !== false" />
|
||||
<span><AccountMenu /></span>
|
||||
</div>
|
||||
</header>
|
||||
<div id="main-content" ref="main" tabindex="-1" class="@container scroll-mt-16 w-full flex-1 px-6 py-5 pb-[calc(var(--chat-dock-clear,6rem)+1rem)] outline-none max-lg:p-4 max-lg:pb-[calc(var(--chat-dock-clear,6rem)+1rem)]"
|
||||
:class="canvasLayout && 'max-md:flex max-md:min-h-0 max-md:flex-col'">
|
||||
<!--
|
||||
Keyed on the path and its parameters but not the query: a query-only
|
||||
change is an entry state, so the page keeps the operator's filters,
|
||||
while two different :id values get fresh instances -- without that
|
||||
the second id diffs the first one in place and the previous task's
|
||||
open tab stays open on the next.
|
||||
-->
|
||||
<RouterView v-slot="{ Component, route }">
|
||||
<component :is="layoutComponent(route.meta)">
|
||||
<component :is="Component" :key="route.path" />
|
||||
</component>
|
||||
</RouterView>
|
||||
</div>
|
||||
</SidebarInset>
|
||||
<ChatDock v-if="session.sections?.chat !== false" />
|
||||
</SidebarProvider>
|
||||
<Toaster position="bottom-right" rich-colors close-button />
|
||||
</TooltipProvider>
|
||||
</template>
|
||||
@@ -1,135 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import Logo from "@/components/topbar/Logo.vue";
|
||||
import { computed, ref } from "vue";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { api, ApiError, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { passkeysAvailable, useAccountsStore, usePasskey } from "./accounts";
|
||||
|
||||
const accounts = useAccountsStore();
|
||||
const recovery = ref(false);
|
||||
const recoveryCode = ref("");
|
||||
const publicURL = ref("");
|
||||
const currentOrigin = window.location.origin;
|
||||
const name = ref("");
|
||||
const email = ref("");
|
||||
const password = ref("");
|
||||
const busy = ref(false);
|
||||
const error = ref("");
|
||||
const notice = ref("");
|
||||
const ownerCreated = ref(false);
|
||||
const setup = computed(() => accounts.status?.setup_required === true);
|
||||
const passkey = computed(() => passkeysAvailable(accounts.status?.public_url ?? ""));
|
||||
|
||||
async function submit() {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
notice.value = "";
|
||||
try {
|
||||
if (ownerCreated.value) {
|
||||
await openAccountWhenReady();
|
||||
return;
|
||||
}
|
||||
if (recovery.value) {
|
||||
await api.recoverAccount(email.value, recoveryCode.value, password.value);
|
||||
recovery.value = false;
|
||||
password.value = "";
|
||||
notice.value = "Password changed.";
|
||||
return;
|
||||
}
|
||||
if (setup.value) {
|
||||
await api.setupAccount({
|
||||
public_url: publicURL.value.trim(),
|
||||
display_name: name.value,
|
||||
email: email.value,
|
||||
password: password.value,
|
||||
});
|
||||
password.value = "";
|
||||
ownerCreated.value = true;
|
||||
await openAccountWhenReady();
|
||||
return;
|
||||
}
|
||||
await api.signIn(email.value, password.value);
|
||||
password.value = "";
|
||||
window.location.assign(new URLSearchParams(window.location.search).has("reauth") ? "/account" : "/");
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
if (!ownerCreated.value) await accounts.load();
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openAccountWhenReady(): Promise<void> {
|
||||
const deadline = Date.now() + 15_000;
|
||||
// Setup creates the owner before Archie opens its operational routes.
|
||||
for (;;) {
|
||||
try {
|
||||
await api.passkeys();
|
||||
window.location.assign("/account?welcome=1");
|
||||
return;
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof ApiError) || cause.status !== 404) throw cause;
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Archie hasn't finished starting. Try opening your account again.");
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 500));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function signInPasskey() {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await usePasskey(false);
|
||||
window.location.assign("/");
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="mx-auto flex min-h-[90dvh] max-w-md flex-col justify-center px-5 py-10">
|
||||
<Card class="gap-0 py-6 px-6 shadow-sm">
|
||||
<div class="mb-2"><Logo /></div>
|
||||
<h1 class="text-title font-medium">
|
||||
{{
|
||||
setup ? "Set up Archie" : recovery ? "Recover your account" : "Sign in"
|
||||
}}
|
||||
</h1>
|
||||
<div v-if="ownerCreated" class="mt-6 space-y-4">
|
||||
<p role="status">Your account is ready. Archie is starting.</p>
|
||||
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<Button v-if="!busy" class="w-full" @click="submit">Open your account</Button>
|
||||
</div>
|
||||
<form v-else class="mt-6 space-y-4" @submit.prevent="submit">
|
||||
<div v-if="setup" class="flex flex-col gap-1.5">
|
||||
<Label for="instance-url">Instance URL</Label>
|
||||
<Input id="instance-url" v-model="publicURL" type="url" :placeholder="currentOrigin" aria-describedby="instance-url-help" required />
|
||||
<p id="instance-url-help" class="text-caption text-fg-muted">Use the public address people will sign in at. You can't change it after adding a passkey.</p>
|
||||
</div>
|
||||
<Label v-if="setup" class="block space-y-1.5 text-label" for="account-name">Your name<Input id="account-name" v-model="name" autocomplete="name" required maxlength="200" /></Label>
|
||||
<Label class="block space-y-1.5 text-label" for="account-email">Email<Input id="account-email" v-model="email" type="email" autocomplete="username" :spellcheck="false" required /></Label>
|
||||
<Label v-if="recovery" class="block space-y-1.5 text-label" for="recovery-code">Recovery code<Input id="recovery-code" v-model="recoveryCode" autocomplete="off" required /></Label>
|
||||
<Label class="block space-y-1.5 text-label" for="account-password">{{ recovery ? "New password" : "Password" }}<Input id="account-password" v-model="password" type="password" :autocomplete="setup || recovery ? 'new-password' : 'current-password'" :minlength="setup || recovery ? 15 : undefined" maxlength="1024" required /></Label>
|
||||
<p v-if="setup" class="text-caption text-fg-muted">At least 15 characters.</p>
|
||||
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<Alert v-if="notice" class="mt-4"><AlertDescription>{{ notice }}</AlertDescription></Alert>
|
||||
<Button type="submit" class="w-full" :disabled="busy">{{ busy ? "Please wait…" : setup ? "Create account" : recovery ? "Reset password" : "Sign in" }}</Button>
|
||||
</form>
|
||||
<div v-if="!setup && !recovery" class="mt-4 flex flex-col gap-2">
|
||||
<Button v-if="passkey" variant="outline" :disabled="busy" @click="signInPasskey">Sign in with a passkey</Button>
|
||||
<Button v-if="accounts.status?.oidc" variant="outline" as-child><a href="/oauth2/login">Sign in with OIDC</a></Button>
|
||||
</div>
|
||||
<Button v-if="!setup" variant="link" class="mt-3" :disabled="busy" @click="recovery = !recovery; error = ''">{{ recovery ? "Back to sign in" : "Use a recovery code" }}</Button>
|
||||
</Card>
|
||||
</main>
|
||||
</template>
|
||||
@@ -1,29 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { ref } from "vue";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { api, classifyActionError, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { ROLE_LABELS, ROLES } from "@/org/org";
|
||||
const emit=defineEmits<{created:[]}>();
|
||||
// Owner is granted from the member table, not when creating an account.
|
||||
const assignable = ROLES.filter((role) => role !== "owner");
|
||||
const name=ref("");const email=ref("");const password=ref("");const role=ref("viewer");const busy=ref(false);const error=ref("");const sessionExpired=ref(false);
|
||||
async function create(){busy.value=true;error.value="";try{await api.createAccount({display_name:name.value,email:email.value,password:password.value,role:role.value});name.value=email.value=password.value="";emit("created")}catch(cause){error.value=describeError(cause, errors.common.unknown);sessionExpired.value=classifyActionError(cause).kind==="session-expired"}finally{busy.value=false}}
|
||||
</script>
|
||||
<template>
|
||||
<Section title="Create a local account">
|
||||
<form class="grid gap-3 sm:grid-cols-2" @submit.prevent="create">
|
||||
<Label for="new-account-name" class="block space-y-1 text-label">Name<Input id="new-account-name" v-model="name" required maxlength="200" autocomplete="off" /></Label>
|
||||
<Label for="new-account-email" class="block space-y-1 text-label">Email<Input id="new-account-email" v-model="email" type="email" required autocomplete="off" :spellcheck="false" /></Label>
|
||||
<Label for="new-account-password" class="block space-y-1 text-label">Initial password<Input id="new-account-password" v-model="password" type="password" required minlength="15" maxlength="1024" autocomplete="new-password" /></Label>
|
||||
<div class="block space-y-1 text-label"><Label for="new-account-role">Role</Label><Select v-model="role"><SelectTrigger id="new-account-role" class="w-full"><SelectValue /></SelectTrigger><SelectContent><SelectItem v-for="choice in assignable" :key="choice" :value="choice">{{ ROLE_LABELS[choice] }}</SelectItem></SelectContent></Select></div>
|
||||
<Alert v-if="error" variant="destructive" class="sm:col-span-2"><AlertDescription>{{error}}<a v-if="sessionExpired" class="underline" href="/?reauth=1"> Sign in again</a></AlertDescription></Alert>
|
||||
<Button type="submit" :disabled="busy" class="justify-self-start sm:col-span-2">Create account</Button>
|
||||
</form>
|
||||
</Section>
|
||||
</template>
|
||||
@@ -1,120 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useIntervalFn } from "@vueuse/core";
|
||||
import QRCode from "qrcode";
|
||||
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Item, ItemActions, ItemContent, ItemGroup } from "@/components/ui/item";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type ChannelLink, type ChannelLinks } from "@/lib/api";
|
||||
|
||||
/** Links the signed-in account to the channel accounts it answers approvals
|
||||
* from. Shown only while an installed connector can link. */
|
||||
const props = defineProps<{ welcome?: boolean }>();
|
||||
|
||||
interface Pending {
|
||||
url: string;
|
||||
qr: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const links = ref<ChannelLinks | null>(null);
|
||||
const pending = ref<Record<string, Pending>>({});
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
|
||||
const label = (connector: string) => connector.charAt(0).toUpperCase() + connector.slice(1);
|
||||
const linkedOn = (connector: string): ChannelLink[] => links.value?.linked.filter((l) => l.connector === connector) ?? [];
|
||||
const waiting = computed(() => Object.keys(pending.value).length > 0);
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
links.value = await api.channelLinks();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
return;
|
||||
}
|
||||
settle();
|
||||
}
|
||||
|
||||
/** A code that was used or ran out stops waiting. */
|
||||
function settle(): void {
|
||||
for (const connector of Object.keys(pending.value)) {
|
||||
const fresh = linkedOn(connector).some((l) => Date.parse(l.linked_at) >= pending.value[connector]!.expiresAt - CODE_LIFETIME_MS);
|
||||
if (fresh || Date.now() >= pending.value[connector]!.expiresAt) delete pending.value[connector];
|
||||
}
|
||||
if (!waiting.value) stop();
|
||||
}
|
||||
|
||||
/** Matches the server's link code lifetime. */
|
||||
const CODE_LIFETIME_MS = 10 * 60 * 1000;
|
||||
const { pause: stop, resume: poll } = useIntervalFn(() => void load(), 2_000, { immediate: false });
|
||||
|
||||
async function run(action: () => Promise<void>): Promise<void> {
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const begin = (connector: string) =>
|
||||
run(async () => {
|
||||
const start = await api.beginChannelLink(connector);
|
||||
pending.value[connector] = {
|
||||
url: start.url,
|
||||
qr: await QRCode.toDataURL(start.url, { margin: 1, width: 192 }),
|
||||
expiresAt: Date.parse(start.expires_at),
|
||||
};
|
||||
poll();
|
||||
});
|
||||
|
||||
/** Hides a code the operator no longer wants to use. */
|
||||
function cancel(connector: string): void {
|
||||
delete pending.value[connector];
|
||||
if (!waiting.value) stop();
|
||||
}
|
||||
|
||||
const unlink = (link: ChannelLink) =>
|
||||
run(async () => {
|
||||
await api.unlinkChannel(link.connector, link.subject);
|
||||
await load();
|
||||
});
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section v-if="links?.connectors.length || error" :title="props.welcome ? 'Link your channels' : 'Linked accounts'">
|
||||
<Alert v-if="error" variant="destructive" class="mb-3"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<ItemGroup v-if="links" class="gap-3">
|
||||
<div v-for="connector in links.connectors" :key="connector" class="space-y-2">
|
||||
<Item v-for="link in linkedOn(connector)" :key="link.subject" as="li" variant="outline" size="xs">
|
||||
<ItemContent class="min-w-0 truncate">{{ label(connector) }}: Linked as {{ link.name || link.subject }}</ItemContent>
|
||||
<ItemActions>
|
||||
<Button variant="ghost" size="sm" class="text-danger" :disabled="busy" @click="unlink(link)">Unlink</Button>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
<div v-if="pending[connector]" class="flex flex-wrap items-center gap-4">
|
||||
<img :src="pending[connector].qr" :alt="`QR code to link ${label(connector)}`" width="192" height="192" class="rounded-md bg-white" />
|
||||
<div class="space-y-2">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button as-child><a :href="pending[connector].url" target="_blank" rel="noopener">Open in {{ label(connector) }}</a></Button>
|
||||
<Button variant="ghost" @click="cancel(connector)">Cancel</Button>
|
||||
</div>
|
||||
<p class="text-caption text-fg-muted">Scan the code or open the link, then press Start.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button v-else-if="!linkedOn(connector).length" :disabled="busy" @click="begin(connector)">Link your {{ label(connector) }}</Button>
|
||||
<Button v-else variant="outline" size="sm" :disabled="busy" @click="begin(connector)">Link another {{ label(connector) }} account</Button>
|
||||
</div>
|
||||
</ItemGroup>
|
||||
</Section>
|
||||
</template>
|
||||
@@ -1,128 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Item, ItemGroup } from "@/components/ui/item";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { Copy, Plus, X } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
|
||||
interface PersonalToken {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
expires_at: string | null;
|
||||
last_used_at: string | null;
|
||||
}
|
||||
|
||||
const lifetimes = [
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
{ days: 0, label: "No expiry" },
|
||||
];
|
||||
|
||||
const available = ref(false);
|
||||
const tokens = ref<PersonalToken[]>([]);
|
||||
const created = ref("");
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
const name = ref("");
|
||||
const days = ref(30);
|
||||
|
||||
async function run(action: () => Promise<void>): Promise<void> {
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const load = () =>
|
||||
run(async () => {
|
||||
const result = await api.tokens<{ tokens: PersonalToken[]; available: boolean }>();
|
||||
available.value = result?.available ?? false;
|
||||
tokens.value = result?.tokens ?? [];
|
||||
});
|
||||
|
||||
const create = () =>
|
||||
run(async () => {
|
||||
created.value = (await api.createToken(name.value.trim(), Number(days.value)))?.token ?? "";
|
||||
name.value = "";
|
||||
await load();
|
||||
});
|
||||
|
||||
const copy = () => navigator.clipboard.writeText(created.value);
|
||||
|
||||
// The token is kept until the next Revoke: Reka closes the dialog before the
|
||||
// action's click runs, so clearing it on close would drop the revoke.
|
||||
const pending = ref<PersonalToken | null>(null);
|
||||
const dialogOpen = ref(false);
|
||||
const revoke = (id: string) =>
|
||||
run(async () => {
|
||||
await api.revokeToken(id);
|
||||
await load();
|
||||
});
|
||||
const confirmRevoke = () => {
|
||||
if (pending.value) revoke(pending.value.id);
|
||||
};
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section title="API tokens" description="Personal bearer tokens for CLI and API access.">
|
||||
<p v-if="!available && !busy && !error" class="text-label text-fg-subtle">Personal tokens need a signed-in person.</p>
|
||||
<ReadError v-if="error" :message="error" retry-label="Retry" class="mb-3" @retry="load" />
|
||||
<Card v-if="created" size="sm" class="mb-3">
|
||||
<p class="text-caption text-fg-subtle">Copy this token now. You can't view it again.</p>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<Input :model-value="created" readonly aria-label="New token" @focus="($event.target as HTMLInputElement).select()" />
|
||||
<Button variant="outline" size="sm" aria-label="Copy token" @click="copy"><Copy /></Button>
|
||||
<Button variant="ghost" size="sm" aria-label="Dismiss" @click="created = ''"><X /></Button>
|
||||
</div>
|
||||
</Card>
|
||||
<ItemGroup v-if="tokens.length" aria-label="API tokens" class="mb-3">
|
||||
<Item v-for="token in tokens" :key="token.id" as="li" variant="outline" size="xs">
|
||||
<span class="flex-1 truncate text-label">{{ token.name || token.id.slice(0, 12) }}</span>
|
||||
<span class="text-caption text-fg-subtle">Created <Timestamp :at="token.created_at" /></span>
|
||||
<span class="text-caption text-fg-subtle">Expires <Timestamp v-if="token.expires_at" :at="token.expires_at" /><template v-else>Never</template></span>
|
||||
<span class="text-caption text-fg-subtle">Last used <Timestamp v-if="token.last_used_at" :at="token.last_used_at" /><template v-else>Never</template></span>
|
||||
<Button variant="ghost" size="sm" class="text-danger" :disabled="busy" @click="pending = token; dialogOpen = true">Revoke</Button>
|
||||
</Item>
|
||||
</ItemGroup>
|
||||
<form v-if="available" class="flex flex-wrap items-center gap-2" @submit.prevent="create">
|
||||
<Input v-model="name" class="min-w-40 flex-1" maxlength="40" required placeholder="Token name" aria-label="Token name" />
|
||||
<Select :model-value="String(days)" @update:model-value="(v) => (days = Number(v))">
|
||||
<SelectTrigger size="sm" class="w-28" aria-label="Lifetime"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="option in lifetimes" :key="option.days" :value="String(option.days)">{{ option.label }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button type="submit" size="sm" :disabled="busy || !name.trim()"><Plus data-icon="inline-start" />New token</Button>
|
||||
</form>
|
||||
</Section>
|
||||
<AlertDialog :open="dialogOpen" @update:open="(v: boolean) => { dialogOpen = v; }">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Revoke token?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Revoke "{{ pending?.name || pending?.id.slice(0, 12) }}"? Anything using it stops working immediately.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction @click="confirmRevoke">Revoke token</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</template>
|
||||
@@ -1,58 +0,0 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref } from "vue";
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
|
||||
interface AccountUser {id:string;display_name:string;kind:string}
|
||||
interface AuthStatus {setup_required:boolean;user:AccountUser|null;oidc:boolean;public_url:string;instance?:string}
|
||||
export const useAccountsStore=defineStore("accounts",()=>{
|
||||
const status=ref<AuthStatus|null>(null);
|
||||
const error=ref("");
|
||||
async function load():Promise<void>{try{status.value=await api.authStatus<AuthStatus>();error.value=""}catch(cause){error.value=describeError(cause, errors.common.unknown)}}
|
||||
async function signOut():Promise<void>{try{await api.signOut()}catch(cause){error.value=describeError(cause, errors.common.unknown);return}window.location.assign("/")}
|
||||
// Empty for the default instance, which needs no label.
|
||||
const instance=computed(()=>{const name=status.value?.instance||"";return name==="archie"?"":name});
|
||||
return {status,error,instance,load,signOut};
|
||||
});
|
||||
|
||||
export function passkeysAvailable(publicURL:string):boolean{
|
||||
if (!window.isSecureContext || !window.PublicKeyCredential) return false;
|
||||
try{const url=new URL(publicURL);return url.origin===window.location.origin && (url.protocol==="https:"||url.hostname==="localhost")}catch{return false}
|
||||
}
|
||||
|
||||
// WebAuthn JSON conversion is native in current browsers. These conversions
|
||||
// preserve support for browsers that implement credentials but not JSON helpers.
|
||||
function decode(value:string):ArrayBuffer{
|
||||
const bytes=Uint8Array.from(atob(value.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0));return bytes.buffer;
|
||||
}
|
||||
function encode(value:ArrayBuffer|null):string|null{
|
||||
if(value===null)return null;
|
||||
return btoa(String.fromCharCode(...new Uint8Array(value))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");
|
||||
}
|
||||
export async function usePasskey(registration:boolean,name=""):Promise<void>{
|
||||
const options=await api.beginPasskey<{publicKey:Record<string,unknown>}>(registration);
|
||||
const key=options.publicKey;
|
||||
key.challenge=decode(key.challenge as string);
|
||||
if(registration){const user=key.user as Record<string,unknown>;user.id=decode(user.id as string)}
|
||||
for(const list of ["excludeCredentials","allowCredentials"]){for(const entry of (key[list] as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}}
|
||||
const credential=(registration?await navigator.credentials.create({publicKey:key as unknown as PublicKeyCredentialCreationOptions}):await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions})) as PublicKeyCredential|null;
|
||||
if(!credential)throw new Error(errors.accounts.passkey.noneSelected);
|
||||
await api.finishPasskey(registration,credentialJSON(credential),name);
|
||||
}
|
||||
|
||||
function credentialJSON(credential:PublicKeyCredential){
|
||||
const response=credential.response;
|
||||
const common={clientDataJSON:encode(response.clientDataJSON)};
|
||||
const data=response instanceof AuthenticatorAttestationResponse?{...common,attestationObject:encode(response.attestationObject),transports:response.getTransports()}:{...common,authenticatorData:encode((response as AuthenticatorAssertionResponse).authenticatorData),signature:encode((response as AuthenticatorAssertionResponse).signature),userHandle:encode((response as AuthenticatorAssertionResponse).userHandle)};
|
||||
return {id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:data,clientExtensionResults:credential.getClientExtensionResults(),authenticatorAttachment:credential.authenticatorAttachment};
|
||||
}
|
||||
|
||||
/** Has the signed-in person's authenticator sign the challenge in options, and returns the assertion as the server reads it. */
|
||||
export async function getAssertion(options:{publicKey:Record<string,unknown>}):Promise<unknown>{
|
||||
const key=options.publicKey;
|
||||
key.challenge=decode(key.challenge as string);
|
||||
for(const entry of (key.allowCredentials as {id:string|ArrayBuffer}[]|undefined)??[]){entry.id=decode(entry.id as string)}
|
||||
const credential=await navigator.credentials.get({publicKey:key as unknown as PublicKeyCredentialRequestOptions}) as PublicKeyCredential|null;
|
||||
if(!credential)throw new Error(errors.accounts.passkey.noneSelected);
|
||||
return credentialJSON(credential);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/** Access decisions as the dashboard reads them from /api/access/decisions:
|
||||
* one recorded outcome, coalesced per minute into a count. */
|
||||
export interface AccessDecision {
|
||||
principal: string;
|
||||
org: string;
|
||||
action: string;
|
||||
kind: string;
|
||||
resource: string;
|
||||
outcome: "allowed" | "denied";
|
||||
level: string;
|
||||
policies: string[];
|
||||
at: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface AccessDecisionsResponse {
|
||||
decisions: AccessDecision[];
|
||||
/** Whether older decisions match beyond this page. */
|
||||
more: boolean;
|
||||
}
|
||||
|
||||
/** The resource column: the kind and id together, or just the kind. */
|
||||
export function decisionResource(d: AccessDecision): string {
|
||||
return d.resource ? `${d.kind}/${d.resource}` : d.kind;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
CodeBlock,
|
||||
CodeBlockActions,
|
||||
CodeBlockContent,
|
||||
CodeBlockCopyButton,
|
||||
CodeBlockLine,
|
||||
CodeBlockToken,
|
||||
useHighlightedCode,
|
||||
} from "@/components/ui/code-block";
|
||||
|
||||
/**
|
||||
* Code or a payload with a copy button that appears on hover or focus. The
|
||||
* text is shown verbatim and wrapped: stored payloads are mostly long unbroken
|
||||
* tokens (URLs, hashes, base64), which must not push the panel past its edge.
|
||||
* A language the highlighter does not know renders plain.
|
||||
*/
|
||||
const props = defineProps<{ code: string; lang?: string; class?: string }>();
|
||||
|
||||
const lines = useHighlightedCode(
|
||||
() => props.code,
|
||||
() => props.lang || "text",
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<CodeBlock :class="cn('bg-muted', props.class)">
|
||||
<CodeBlockActions>
|
||||
<CodeBlockCopyButton :value="code" />
|
||||
</CodeBlockActions>
|
||||
<CodeBlockContent wrap class="max-h-[60vh] pe-10 text-caption">
|
||||
<CodeBlockLine v-for="(line, index) in lines" :key="index">
|
||||
<CodeBlockToken v-for="(token, i) in line" :key="i" :token="token" />
|
||||
</CodeBlockLine>
|
||||
</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</template>
|
||||
@@ -1,35 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Search, X } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
|
||||
import { useSysQuery } from "@/lib/sys-query";
|
||||
|
||||
const props = defineProps<{
|
||||
/** The control's accessible name, like "Filter guards". */
|
||||
label: string;
|
||||
/** What the list accepts, comma separated, for the title. */
|
||||
fields: string;
|
||||
/** A condition in the list's own vocabulary, shown until something is typed. */
|
||||
example: string;
|
||||
}>();
|
||||
|
||||
const { query, draft, commit, clear } = useSysQuery();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form class="w-56 max-sm:w-full" @submit.prevent="commit">
|
||||
<InputGroup>
|
||||
<InputGroupAddon><Search /></InputGroupAddon>
|
||||
<InputGroupInput
|
||||
v-model="draft"
|
||||
:aria-label="label"
|
||||
:placeholder="example"
|
||||
:title="`Filter on ${fields}`"
|
||||
/>
|
||||
<InputGroupAddon v-if="query" align="inline-end">
|
||||
<Button type="button" variant="ghost" size="icon-xs" aria-label="Clear filter" title="Clear filter" @click="clear"><X /></Button>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
</form>
|
||||
</template>
|
||||
@@ -1,80 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { computed } from "vue";
|
||||
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import { fmtValue, LEVEL_COLOR, levelKind, rowClass, type LogEntry } from "@/lib/log";
|
||||
import { shortTime } from "@/lib/format";
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
|
||||
const appearance = useAppearanceStore();
|
||||
|
||||
/**
|
||||
* Log entries as a table: time, level, stage, service and message, with an
|
||||
* entry's remaining fields opened beneath it. The task log and the
|
||||
* instance-wide log page render the same entries through it.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
entries: LogEntry[];
|
||||
rowKey: (entry: LogEntry) => string;
|
||||
storageKey: string;
|
||||
/** Fields the page itself already names, such as the task it is about. */
|
||||
omit?: string[];
|
||||
/** Shows service and component columns by default, for logs spanning
|
||||
* services; a task's own log shows its stage instead. */
|
||||
services?: boolean;
|
||||
/** Opens with the newest entry first; the Time header flips it. */
|
||||
newestFirst?: boolean;
|
||||
}>(),
|
||||
{ omit: () => [], services: false, newestFirst: false },
|
||||
);
|
||||
|
||||
// Entries arrive in log order, which is the order to sort time by: equal
|
||||
// timestamps keep the order they were written in.
|
||||
const position = computed(() => new Map(props.entries.map((entry, i) => [entry, i])));
|
||||
|
||||
const columns: DataTableColumn<LogEntry>[] = [
|
||||
{ id: "time", label: "Time", fixed: true, width: "9rem", sort: (e) => position.value.get(e) ?? 0 },
|
||||
{ id: "level", label: "Level", fixed: true, width: "6rem" },
|
||||
{ id: "service", label: "Service", hidden: !props.services, width: "8rem" },
|
||||
{ id: "component", label: "Component", hidden: !props.services, width: "9rem" },
|
||||
{ id: "stage", label: "Stage", hidden: props.services, width: "9rem" },
|
||||
{ id: "message", label: "Message", fixed: true, width: "auto", class: "whitespace-normal" },
|
||||
];
|
||||
// received_at restates the time; the rest have columns.
|
||||
const shown = new Set(["received_at", "stage", "service", "component", ...props.omit]);
|
||||
const field = (entry: LogEntry, name: string) => fmtValue(entry.fields?.[name] ?? "");
|
||||
const details = (entry: LogEntry) =>
|
||||
Object.entries(entry.fields ?? {})
|
||||
.filter(([k]) => !shown.has(k))
|
||||
.map(([label, value]) => ({ label, value: fmtValue(value), mono: true }));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DataTable
|
||||
:columns="columns"
|
||||
:rows="entries"
|
||||
:row-key="rowKey"
|
||||
:storage-key="storageKey"
|
||||
:row-class="(e) => rowClass(e.level)"
|
||||
:initial-sort="newestFirst ? { id: 'time', desc: true } : undefined"
|
||||
sticky-header
|
||||
>
|
||||
<template #cell-time="{ row }"><span class="font-mono text-caption text-fg-subtle">{{ shortTime(row.time, appearance.timeZone) }}</span></template>
|
||||
<template #cell-level="{ row }">
|
||||
<span class="text-micro font-semibold tracking-[0.04em]" :class="LEVEL_COLOR[levelKind(row.level)]">{{ (row.level || "info").toUpperCase() }}</span>
|
||||
</template>
|
||||
<template #cell-service="{ row }"><span class="block max-w-40 truncate font-mono text-caption text-fg-muted">{{ field(row, "service") }}</span></template>
|
||||
<template #cell-component="{ row }"><span class="block max-w-48 truncate font-mono text-caption text-fg-muted">{{ field(row, "component") }}</span></template>
|
||||
<template #cell-stage="{ row }"><span class="block max-w-48 truncate font-mono text-caption text-fg-muted" :title="field(row, 'stage')">{{ field(row, "stage") }}</span></template>
|
||||
<template #cell-message="{ row }">
|
||||
<span class="font-mono text-caption [overflow-wrap:anywhere]">{{ row.message || row.msg || "" }}</span>
|
||||
<span v-if="details(row).length" class="ml-2 text-caption text-fg-subtle">{{ details(row).length }} field{{ details(row).length === 1 ? "" : "s" }}</span>
|
||||
</template>
|
||||
<template #detail="{ row }">
|
||||
<MetadataList v-if="details(row).length" :rows="details(row)" class="text-caption" />
|
||||
<span v-else class="text-caption text-fg-subtle">No fields</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
</template>
|
||||
@@ -1,13 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** Every page's title, with its actions on the same line. */
|
||||
defineProps<{ title: string }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="mb-4 flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<h1 class="text-title leading-tight font-semibold tracking-tight sm:text-title sm:leading-7">{{ title }}</h1>
|
||||
<div v-if="$slots.default" class="flex flex-wrap items-center gap-2">
|
||||
<slot />
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -1,43 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ShieldQuestion } from "@lucide/vue";
|
||||
import { ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { describeError } from "@/lib/api";
|
||||
import { answerAsk } from "./state";
|
||||
import type { ChatAsk } from "./types";
|
||||
|
||||
const props = defineProps<{ ask: ChatAsk }>();
|
||||
|
||||
const error = ref("");
|
||||
// The last answer tried, so a failed answer can be retried from the error.
|
||||
let lastAnswer = false;
|
||||
|
||||
async function answer(approve: boolean): Promise<void> {
|
||||
lastAnswer = approve;
|
||||
try {
|
||||
await answerAsk(props.ask, approve);
|
||||
error.value = "";
|
||||
} catch (err) {
|
||||
error.value = describeError(err, errors.chat.ask.answer);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ReadError v-if="error" :message="error" retry-label="Retry answer" class="mt-2" @retry="answer(lastAnswer)" />
|
||||
<Item variant="outline" size="sm" class="mt-2" role="group" :aria-label="ask.prompt">
|
||||
<ItemMedia variant="icon"><ShieldQuestion /></ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>Allow {{ ask.prompt }}?</ItemTitle>
|
||||
<ItemDescription v-if="ask.detail" class="font-mono text-caption break-all">{{ ask.detail }}</ItemDescription>
|
||||
</ItemContent>
|
||||
<ItemActions class="flex-wrap">
|
||||
<Button size="sm" variant="outline" @click="answer(false)">Deny</Button>
|
||||
<Button size="sm" @click="answer(true)">Approve</Button>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
</template>
|
||||
@@ -1,60 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Menu, SquarePen } from "@lucide/vue";
|
||||
import { computed, ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import ChatSessionActions from "./ChatSessionActions.vue";
|
||||
import ChatSessionList from "./ChatSessionList.vue";
|
||||
import { sessionTitle } from "./session";
|
||||
import { useEscapeLayer } from "./escape";
|
||||
import { currentSession, newChat, sessions } from "./state";
|
||||
|
||||
/**
|
||||
* One row for everything that is not the conversation: the drawer of
|
||||
* conversations, which one is open, and icon controls on the right. The dock
|
||||
* fills the slots: `start` before the drawer button, `actions` before the more
|
||||
* menu, and `end` last.
|
||||
*/
|
||||
const drawer = ref(false);
|
||||
useEscapeLayer(drawer);
|
||||
|
||||
const title = computed(() => {
|
||||
const open = sessions.value.find((s) => s.session_id === currentSession.value);
|
||||
return open ? sessionTitle(open) : "New chat";
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center gap-0.5 px-2 py-1.5">
|
||||
<slot name="start" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="flex-none"
|
||||
aria-label="Conversations"
|
||||
:aria-expanded="drawer"
|
||||
@click="drawer = true"
|
||||
>
|
||||
<Menu />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Conversations</TooltipContent>
|
||||
</Tooltip>
|
||||
<span class="min-w-0 flex-1 truncate px-1 text-label font-medium" :title="title">{{ title }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="New chat" @click="newChat">
|
||||
<SquarePen />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>New chat</TooltipContent>
|
||||
</Tooltip>
|
||||
<slot name="actions" />
|
||||
<ChatSessionActions />
|
||||
<slot name="end" />
|
||||
<ChatSessionList v-if="drawer" @close="drawer = false" />
|
||||
</div>
|
||||
</template>
|
||||
Loaded 100 of 636 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user