Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f341719ef | ||
|
|
5de9272281 | ||
|
|
a6d468bd2c | ||
|
|
b0f2c72b5f | ||
|
|
e586ab9bd9 | ||
|
|
68415f805b | ||
|
|
a4bfa3117f | ||
|
|
8935783371 | ||
|
|
cf56840df9 | ||
|
|
1c5c906cbb | ||
|
|
ac12301818 | ||
|
|
84dba6d670 | ||
|
|
ff83b6c7da | ||
|
|
a328ef5ea7 | ||
|
|
7d366e6368 | ||
|
|
5ea1e38f25 | ||
|
|
d99bb75fc2 | ||
|
|
d79415cbb3 | ||
|
|
1eea4eb8d8 | ||
|
|
385f51f3ba | ||
|
|
540a7ec96b | ||
|
|
4e79d3cd81 | ||
|
|
cbfd4404c1 | ||
|
|
50820b8b40 | ||
|
|
502a3e4f2c | ||
|
|
b57b55f3e1 | ||
|
|
06c662042b | ||
|
|
461669b3fb | ||
|
|
9580a7b2df | ||
|
|
86f9ac5603 | ||
|
|
6a91ce30e3 | ||
|
|
aa3bae9020 | ||
|
|
ba46789226 | ||
|
|
4e494ce4fd | ||
|
|
8c6158e8e3 | ||
|
|
b4cfe050fa | ||
|
|
a199700878 | ||
|
|
2a46b355db | ||
|
|
a50dce2755 | ||
|
|
8dbd319bba | ||
|
|
67e230a647 | ||
|
|
ad155e269c | ||
|
|
f268d0e3eb | ||
|
|
a779ab4667 | ||
|
|
e6aacc899d | ||
|
|
4dab218b75 | ||
|
|
622924ed53 | ||
|
|
6c43b53590 | ||
|
|
e66e53c817 | ||
|
|
a71be39076 | ||
|
|
5ec9fd0bc3 | ||
|
|
80d9af42b5 | ||
|
|
dcb002304b | ||
|
|
196bf4c2e8 | ||
|
|
0e47623a6b | ||
|
|
90be5a5490 | ||
|
|
1a2e786ca8 | ||
|
|
d34ea9e943 | ||
|
|
310997c3ae | ||
|
|
7acd1bc5a1 |
No files matched your search
@@ -7,3 +7,4 @@ node_modules
|
||||
**/*.log
|
||||
data
|
||||
keys
|
||||
**/*.tsbuildinfo
|
||||
+36
-12
@@ -1,17 +1,41 @@
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
## Optional overrides: copy to .env and uncomment the settings you need.
|
||||
## Every setting has a default (shown below), so liqa runs without a .env file.
|
||||
##
|
||||
## Lines starting with "##" are descriptions.
|
||||
## Lines starting with "# " are settings: remove the "# " to enable one.
|
||||
|
||||
# Directory (relative to cwd) containing *.json key descriptors
|
||||
KEYS_DIR=keys
|
||||
## production in the Docker image; also selects the default CORS origins
|
||||
# NODE_ENV=development
|
||||
# PORT=3000
|
||||
|
||||
# SQLite database path
|
||||
DB_PATH=data/sessions.db
|
||||
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
||||
## Vite dev server (http://localhost:5173) in development, the compose port
|
||||
## (http://localhost:13000) in production
|
||||
# CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
# Playwright executable (set in Docker; leave empty to use system default)
|
||||
## SQLite database path
|
||||
# DB_PATH=data/liqa.db
|
||||
|
||||
## Stored scenario files and run artifacts (downloads, failure dumps, traces)
|
||||
# FILES_DIR=data/files
|
||||
## Days to keep run artifacts before they are deleted
|
||||
# FILE_RUN_EXPIRATION_DAYS=7
|
||||
## When expired files are deleted (cron expression)
|
||||
# FILE_CLEANUP_CRON=0 3 * * *
|
||||
|
||||
## Close open sessions that have been idle for longer than this many minutes
|
||||
# SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||
## Delete closed sessions whose updatedAt is older than this many days
|
||||
# SESSION_DELETE_CLOSED_DAYS=7
|
||||
|
||||
## Playwright trace recording for scenario runs: on | retain-on-failure | off
|
||||
## (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
||||
# PLAYWRIGHT_TRACE_MODE=off
|
||||
|
||||
## Chromium binary to use instead of Playwright's own (not needed in Docker,
|
||||
## which ships Playwright's chromium-headless-shell)
|
||||
# PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
|
||||
# Session lifecycle
|
||||
# Close open sessions that have been idle for longer than this many minutes
|
||||
SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||
# Delete closed sessions whose updatedAt is older than this many days
|
||||
SESSION_DELETE_CLOSED_DAYS=7
|
||||
## Directory with the built client to serve at / (the Docker image sets it to
|
||||
## "client"; leave unset to not serve the UI, e.g. when using the Vite dev server)
|
||||
# CLIENT_DIR=client
|
||||
+10
@@ -1,5 +1,6 @@
|
||||
# runtime
|
||||
/data
|
||||
server/data/
|
||||
.env
|
||||
*.log
|
||||
|
||||
@@ -12,3 +13,12 @@ server/dist
|
||||
client/dist
|
||||
*storybook.log
|
||||
storybook-static
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
# organization
|
||||
TODO.md
|
||||
|
||||
# IDE/editor
|
||||
.vscode/
|
||||
.idea/
|
||||
.github/
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 1.20.0 - 2026-09-30
|
||||
|
||||
Changes since 1.19.3:
|
||||
|
||||
### Added
|
||||
|
||||
- Database migrations: the SQLite schema is now managed by TypeORM migrations (`server/src/database/migrations/`) instead of `synchronize`. The Docker container applies pending migrations before starting the server, and the server refuses to start while migrations are pending.
|
||||
- `npm -w server run migration:run`, `migration:show` and `migration:generate` scripts; the workflow for schema changes is described in `docs/development.md`.
|
||||
- A test that fails when an entity changes without a matching migration.
|
||||
|
||||
### Changed
|
||||
|
||||
- Databases created before migrations (by `synchronize`) are adopted automatically: the initial migration is recorded as applied without changing them.
|
||||
- Tests now build their database from the migrations instead of `synchronize`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Startup failures were logged but the process exited with code 0; they now exit with code 1.
|
||||
|
||||
## 1.19.3 - 2026-09-30
|
||||
|
||||
Changes since 1.19.2:
|
||||
|
||||
### Changed
|
||||
|
||||
- The Docker image runs with `NODE_ENV=production`.
|
||||
- The origins allowed to call the API cross-origin depend on `NODE_ENV`: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) in development, the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) in production. The new `CORS_ORIGINS` setting (comma separated) overrides both. A `NODE_ENV=development` in `.env` overrides the image's production mode.
|
||||
- `.env` is optional: compose loads it only when it exists, and every setting in `.env.example` is commented out and shows its default.
|
||||
|
||||
### Removed
|
||||
|
||||
- The unused `KEYS_DIR` setting and the `./keys` mount in `compose.yaml`.
|
||||
|
||||
## 1.19.2 - 2026-09-30
|
||||
|
||||
Changes since 1.19.1:
|
||||
|
||||
### Fixed
|
||||
|
||||
- Running a scenario from its detail page could preselect the first environment in the list instead of the scenario's default environment, depending on whether the environment list or the scenario loaded first. The default environment is now chosen when the run modal opens.
|
||||
- Made the run status filter test deterministic; it could fail when the scheduler picked up the test's pending run mid-test.
|
||||
|
||||
## 1.19.1 - 2026-09-30
|
||||
|
||||
Changes since 1.19.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- Upgraded to Node.js 24: the Docker image is based on `node:24-slim`, and the root `package.json` declares `"engines": { "node": ">=24" }`.
|
||||
- The server reads the app name and version (startup log, Swagger, MCP server info, `APP_NAME`/`APP_VERSION`) from the workspace root `package.json`. Previously local runs reported the server workspace's own `liqa-server` / `1.0.0`; the server workspace no longer has a version.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Tests using a local HTTP server bind to `127.0.0.1` instead of `localhost`, which could resolve to an unreachable `::1` inside Docker containers.
|
||||
|
||||
## 1.19.0 - 2026-09-30
|
||||
|
||||
Changes since 1.18.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking (deployment):** the whole application now runs from a single image and container. The server serves the built client itself (new `CLIENT_DIR` setting, set by the image) next to the API, MCP and Swagger, so the UI moved from http://localhost:13001 to **http://localhost:13000**. The root `Dockerfile` replaces `server/Dockerfile`, `client/Dockerfile` and `client/nginx.conf`, and `compose.yaml` has a single `liqa` service. When upgrading, run `docker compose up -d --build --remove-orphans` to remove the old `server` and `client` containers.
|
||||
- The image uses Playwright's headless-only Chromium build (`chromium-headless-shell`, always matching the installed Playwright version) with only the libraries it needs, instead of Debian's desktop `chromium` package. Fonts are now DejaVu and Liberation (metric-compatible with Arial/Times) instead of Noto. Together with clearing the npm cache, this shrinks the image from 1.76 GB to 1.07 GB.
|
||||
|
||||
## 1.18.0 - 2026-09-30
|
||||
|
||||
Changes since 1.17.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a central import: `POST /import`, an Import page in the UI, and the `import_yaml` MCP tool. It takes YAML made of `---`-separated documents, each holding one exported item or a list of items (JSON is accepted too), with any mix of environments, credentials, snippets and scenarios. All items are validated before anything is imported, and they are imported in dependency order (environments, credentials, snippets, scenarios), so a scenario can reference an environment or credential from the same file.
|
||||
|
||||
### Changed
|
||||
|
||||
- The Import buttons on the scenario, snippet, credential and environment list pages use the central import. When the file holds exactly one item of the page's kind, that item is opened; otherwise the Import page shows everything that was imported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Scenario exports that included the environment or credentials were not valid YAML (all entities were written into one document). Each entity is now a separate `---` document.
|
||||
|
||||
## 1.17.0 - 2026-09-30
|
||||
|
||||
Changes since 1.16.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Files can be deleted from a run: a delete button (with confirmation) in the Files section of the run detail page, `DELETE /scenarios/:id/runs/:runId/files/:fileId`, and the `delete_run_file` MCP tool. The stored file is removed once no scenario or run references it.
|
||||
|
||||
## 1.16.1 - 2026-09-30
|
||||
|
||||
Changes since 1.16.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- Playwright traces are now off by default (`PLAYWRIGHT_TRACE_MODE` defaults to `off`), since a trace often reaches ~10 MB per run. Traces can still be enabled per run in the run modal, via `traceMode` in `POST /scenarios/:id/run`, or for all runs by setting `PLAYWRIGHT_TRACE_MODE`.
|
||||
|
||||
## 1.16.0 - 2026-09-30
|
||||
|
||||
Changes since 1.15.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenarios and snippets are now versioned, starting at version 1. A scenario's version goes up when its name, description, default environment, timeout or steps change; a snippet's when its alias, title, description or code changes. Saving without changes does not create a new version. Credential assignments and scenario files are not versioned.
|
||||
- Each run records the scenario version it runs. The run modal has a version picker (latest by default), `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `version`, and "Repeat run" reuses the run's version.
|
||||
- `context.runSnippet("alias@N")` pins version N of a snippet; `runSnippet("alias")` keeps using the latest. The scenario page's "Used Snippets" section shows which snippets are pinned.
|
||||
- Version numbers are shown on the scenario, snippet and run pages and in the scenario and run lists.
|
||||
- Added `GET /scenarios/:id/versions[/:version]` and `GET /snippets/:id/versions[/:version]`, and the `list_scenario_versions`, `get_scenario_version`, `list_snippet_versions` and `get_snippet_version` MCP tools.
|
||||
- Scenario and snippet exports accept `?version=N` (the `export_scenario` MCP tool takes `version`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking:** scenario and snippet exports now include `version`, and imports require it. An import restores that exact version by id + version: an existing version is left untouched, and a new one is stored under its number and becomes the latest when it is higher than the current latest. Export files from earlier releases need a `version` field added before they can be imported.
|
||||
- Scenario exports now include scenario and step timeouts.
|
||||
- Runs keep their own copy of the steps they were created with. Editing or deleting a step no longer changes past runs, and deleting a step no longer deletes its results from past runs. Existing run steps are backfilled from the current steps on startup.
|
||||
|
||||
## 1.15.0 - 2026-09-30
|
||||
|
||||
Changes since 1.14.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario runs now record a Playwright trace (screenshots and DOM snapshots) and upload it to the run's files as `trace.zip` when the run finishes. Open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
- Added the `PLAYWRIGHT_TRACE_MODE` setting (`on` (default), `retain-on-failure`, or `off`) that controls which traces are kept.
|
||||
- Added a "Playwright trace" option to the run modal to override the trace mode for a single run. It defaults to the server's `PLAYWRIGHT_TRACE_MODE`, served by the new `GET /scenarios/run-defaults` endpoint.
|
||||
- `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `traceMode`. The trace mode is stored on the run, shown on the run detail page, and reused by "Repeat run".
|
||||
|
||||
### Changed
|
||||
|
||||
- The run modals on the scenario list and scenario detail pages now share one component.
|
||||
- `server/data/` is now git-ignored.
|
||||
|
||||
## 1.14.0 - 2026-09-30
|
||||
|
||||
Changes since 1.13.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Repeat run" button on the scenario run detail page that starts a new run of the same scenario with the same environment and "save session" setting, then navigates to it. The button is disabled when the run's environment has since been deleted.
|
||||
|
||||
## 1.13.0 - 2026-09-30
|
||||
|
||||
Changes since 1.12.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added credential CRUD tools to the MCP server: `list_credentials`, `get_credential`, `create_credential`, `update_credential`, and `delete_credential`. Combined with the existing `add_scenario_credential` tool, credentials can now be created and attached to scenarios entirely via MCP.
|
||||
|
||||
## 1.12.0 - 2026-09-16
|
||||
|
||||
Changes since 1.11.0:
|
||||
|
||||
### Added
|
||||
|
||||
- When a scenario or snippet step fails, a full-page screenshot and the current page HTML are captured and uploaded as run artifacts, so failures can be diagnosed from the run's file list.
|
||||
|
||||
## 1.11.0 - 2026-09-15
|
||||
|
||||
Changes since 1.10.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added export of a scenario as a standalone, plug-and-play Playwright e2e test project (zip archive with `package.json`, `playwright.config.ts`, `test.spec.ts`, `README.md`, `.env`, `credentials.json`, `snippets/*.js`, and any attached scenario files) that runs entirely independently of the liqa backend. Available as a "Export e2e test" button on the scenario detail page, `GET /scenarios/:id/export-e2e`, and the `export_e2e_test` MCP tool.
|
||||
- The exported test only bundles the credentials, snippets, and attached files actually referenced (directly or transitively) by the scenario's steps.
|
||||
- Added a "Used Snippets" section on the scenario detail page listing the snippets referenced by the scenario's steps, linking to each snippet's detail page. Backed by `GET /scenarios/:id/used-snippets`.
|
||||
|
||||
## 1.10.1 - 2026-09-15
|
||||
|
||||
Changes since 1.10.0:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.runSnippet()` now logs "Snippet started"/"finished"/"failed" entries, matching the automatic step start/pass/fail logging.
|
||||
|
||||
### Changed
|
||||
|
||||
- Reworked the Markdown log export format: each log entry is now its own `## [level] timestamp` section with the message as its body, instead of a single large table.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Run logs could persist out of call order (e.g. a snippet's "started" log appearing after its "finished" log) because writes were fire-and-forget and raced against each other. Log entries now carry a per-run sequence number assigned in call order, and queries/exports sort by it.
|
||||
|
||||
## 1.10.0 - 2026-09-15
|
||||
|
||||
Changes since 1.9.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Download logs" button on the scenario run detail page: opens a modal to choose Markdown (default) or CSV, then downloads the run's logs in that format.
|
||||
- Added `GET /scenarios/:id/run/:runId/logs/export?format=csv|md` backend endpoint to export a run's logs.
|
||||
|
||||
## 1.9.1 - 2026-09-15
|
||||
|
||||
Changes since 1.9.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario run logs now include an automatic entry when a step starts and when it finishes (pass or fail), so step boundaries are visible in run logs even for steps that don't call `context.log`/`context.assert` themselves.
|
||||
|
||||
## 1.9.0 - 2026-09-15
|
||||
|
||||
Changes since 1.8.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added `context.assert(fn, description)` for scenario/snippet script steps: runs the given function, requires it to return `true`, logs the outcome (`log` on success, `error` on failure or exception), and throws to stop the step on failure.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented `context.assert` in `docs/scenario.md`.
|
||||
|
||||
## 1.8.0 - 2026-09-15
|
||||
|
||||
Changes since 1.7.1:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.downloadFile()` now accepts `data:` URIs, so scenario steps can save in-script generated content (e.g. a credential JWT) as a run artifact without a network fetch.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented the full scenario step `context` file API (`getScenarioFiles`, `downloadFile`) in `docs/scenario.md`.
|
||||
|
||||
## 1.7.1 - 2026-04-21
|
||||
|
||||
Changes since 1.7.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added MCP tools to upload, list, and fetch scenario files using base64 content payloads.
|
||||
- Added MCP tools to list run artifacts and fetch run artifact content with metadata.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented MCP binary content handling for scenario files and run artifacts.
|
||||
|
||||
## 1.7.0 - 2026-04-21
|
||||
|
||||
Changes since 1.6.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added scenario file storage and run artifact support on the backend.
|
||||
- Added file management UI for scenarios and run details, including artifact lists.
|
||||
- Added snippet CRUD tools to the MCP server.
|
||||
|
||||
### Changed
|
||||
|
||||
- Added dynamic page titles based on the active client content.
|
||||
- Extended the scenarios list to show the latest run status and timestamp.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Exposed file expiry metadata in scenario and run file responses.
|
||||
- Disabled expired download actions in the UI while keeping the action visible.
|
||||
@@ -0,0 +1,55 @@
|
||||
# liqa
|
||||
|
||||
liqa is a browser automation and QA service for web applications. It stores **scenarios** (ordered Playwright steps), **snippets** (reusable code run via `context.runSnippet`), **environments**, **credentials** and **sessions**, and runs scenarios in headless Chromium. Scenarios and snippets are versioned; each run records the scenario version it executed.
|
||||
|
||||
It is an npm workspace with two packages:
|
||||
|
||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM; the schema is managed by migrations in `server/src/database/migrations/` (see "Database migrations" in `docs/development.md`). Any entity change needs a generated migration - `test/migrations.spec.ts` fails otherwise. REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
||||
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
||||
|
||||
## Docs
|
||||
|
||||
- [README.md](README.md) - overview
|
||||
- [docs/architecture.md](docs/architecture.md) - services and modules
|
||||
- [docs/development.md](docs/development.md) - local setup, running, testing, Docker
|
||||
- [docs/scenario.md](docs/scenario.md) - scenario execution, script `context` API, versioning, export/import, Playwright traces
|
||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [CHANGELOG.md](CHANGELOG.md) - release notes per version
|
||||
- [Dockerfile](Dockerfile) - single image: builds client and server, runtime serves both
|
||||
- [.env.example](.env.example) - all configuration variables (validated in `server/src/config/app.config.ts`)
|
||||
|
||||
## Default deployment (docker compose)
|
||||
|
||||
`compose.yaml` at the repo root runs a single `liqa` container, built from the root `Dockerfile`, at http://localhost:13000. The server serves everything: the UI at `/` (the built client, via `CLIENT_DIR`), the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. It reads `.env` if present (optional - every setting has a default) and mounts `./data` (SQLite DB `data/liqa.db` + stored files).
|
||||
|
||||
Rebuild and restart: `docker compose up -d --build`. Check with `docker compose ps`, `curl localhost:13000/health` and `docker compose logs liqa`.
|
||||
|
||||
The live database is `data/liqa.db`. The container applies pending migrations before starting the server, so back it up before deploying a release with new migrations.
|
||||
|
||||
## Code quality
|
||||
|
||||
Before committing, run and pass all of these (and report the results):
|
||||
|
||||
```bash
|
||||
# server
|
||||
cd server && npm run lint && npx tsc --noEmit -p tsconfig.json && npm test && npm run build
|
||||
# client
|
||||
cd client && npm run lint && npm run build
|
||||
```
|
||||
|
||||
- Lint must stay clean in both packages (no errors, no warnings).
|
||||
- Don't run prettier over whole existing files; several aren't prettier-clean and it produces unrelated diffs. Format only new files or the lines you changed.
|
||||
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
||||
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
||||
|
||||
## Committing a new version
|
||||
|
||||
When asked to commit:
|
||||
|
||||
1. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on the changes: patch for fixes and small behavior/default tweaks, minor for new features, major for breaking changes (e.g. changed API or export/import formats that old clients or files can't use).
|
||||
2. Run the code quality checks above.
|
||||
3. Bump `version` in the root `package.json` and in both places at the top of `package-lock.json` (the root entry and `packages[""]`). `server/package.json` and `client/package.json` keep their own versions; don't bump them.
|
||||
4. Add a `## <version> - <YYYY-MM-DD>` entry at the top of `CHANGELOG.md` ("Changes since <previous version>:", then `### Added` / `### Changed` / `### Fixed`). Mark breaking changes with **Breaking:**.
|
||||
5. Update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions).
|
||||
6. Build the commit message with the `/git-commit` skill if it is available, following its format and rules. Otherwise use a conventional commit message (`type(scope): subject`, then a bullet list body). Either way, put the version bump in the body as a bullet (e.g. `- bump version to <version>`), not in the subject line. This overrides the skill's rule of putting versions in the subject. Then make the commit with that message.
|
||||
7. **After committing, ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Single image serving the whole application: the NestJS server (API, MCP,
|
||||
# scheduler) also serves the built client, so one container is enough.
|
||||
|
||||
# ── Client build ──────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS client-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Root lockfile + workspace manifest so npm ci can resolve the full graph
|
||||
COPY package*.json ./
|
||||
COPY client/package.json ./client/
|
||||
RUN npm ci -w client
|
||||
|
||||
COPY client ./client
|
||||
RUN npm run -w client build
|
||||
|
||||
# ── Server build ──────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS server-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci -w server
|
||||
|
||||
COPY server/nest-cli.json ./server/
|
||||
COPY server/tsconfig*.json ./server/
|
||||
COPY server/src ./server/src
|
||||
RUN npm run -w server build
|
||||
|
||||
# ── Runtime ───────────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS runtime
|
||||
|
||||
# Runtime only: in the build stages it would make npm ci skip devDependencies
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Shared libraries chrome-headless-shell links against (from `ldd`), plus
|
||||
# fontconfig and basic fonts for text rendering. Playwright's `--with-deps`
|
||||
# would also pull in xvfb (with Mesa/LLVM) and extra font packages, which
|
||||
# headless-only use doesn't need.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
fontconfig \
|
||||
fonts-dejavu-core \
|
||||
fonts-liberation \
|
||||
libasound2 \
|
||||
libatk-bridge2.0-0 \
|
||||
libatk1.0-0 \
|
||||
libatspi2.0-0 \
|
||||
libdbus-1-3 \
|
||||
libexpat1 \
|
||||
libgbm1 \
|
||||
libglib2.0-0 \
|
||||
libnspr4 \
|
||||
libnss3 \
|
||||
libx11-6 \
|
||||
libxcb1 \
|
||||
libxcomposite1 \
|
||||
libxdamage1 \
|
||||
libxext6 \
|
||||
libxfixes3 \
|
||||
libxkbcommon0 \
|
||||
libxrandr2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
|
||||
# Playwright's headless-only Chromium build, matching the installed Playwright
|
||||
# version. All browser launches are headless, so the full desktop Chromium
|
||||
# (GTK, Mesa/LLVM, icon themes) isn't needed.
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
RUN npm ci --omit=dev -w server \
|
||||
&& npx playwright install --only-shell chromium \
|
||||
&& npm cache clean --force
|
||||
|
||||
COPY --from=server-build /app/server/dist ./dist
|
||||
COPY --from=client-build /app/client/dist ./client
|
||||
|
||||
# Serve the built client at / (see server/src/common/client-static.ts)
|
||||
ENV CLIENT_DIR=client
|
||||
|
||||
# Runtime directory (SQLite DB and stored files, mounted as a volume)
|
||||
RUN mkdir -p data
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# Apply pending database migrations, then start the server (which refuses to
|
||||
# start while migrations are pending)
|
||||
CMD ["sh", "-c", "node dist/database/migrate && exec node dist/main"]
|
||||
@@ -1,46 +1,40 @@
|
||||
# liquio-qa-bot
|
||||
# liqa
|
||||
|
||||
A headless QA automation service for Liquio environments. Exposes an **MCP (Model Context Protocol)** server that lets AI agents define, run, and monitor multi-step browser test scenarios using [Playwright](https://playwright.dev/).
|
||||
A browser automation and QA service for web applications. It stores multi-step browser scenarios, runs them with [Playwright](https://playwright.dev/) in headless Chromium, and keeps their results, logs and artifacts. Scenarios are managed from a web UI, a REST API, or an **MCP (Model Context Protocol)** server that lets AI agents define, run and debug them.
|
||||
|
||||
---
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
||||
|
||||
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The bot manages four core concepts:
|
||||
|
||||
| Concept | Description |
|
||||
|---|---|
|
||||
| **Environment** | A named set of URLs for a deployment target (e.g. `liquio-diia-stg`) |
|
||||
| **Key** | A JSON descriptor in `keys/` that points to an EDS key file + password |
|
||||
| **Session** | Saved browser state (cookies + localStorage) produced by a login |
|
||||
| **Scenario** | An ordered list of steps that run in sequence against a shared browser instance |
|
||||
| **Scenario** | An ordered list of steps (async Playwright JS) that run in sequence in one browser. Versioned: every content change creates a new version |
|
||||
| **Run** | One execution of a scenario version in an environment, with per-step status and output, logs, and run files (downloads, failure screenshots, Playwright traces) |
|
||||
| **Snippet** | Reusable, versioned code called from steps with `context.runSnippet("alias")` (or `"alias@N"` for a specific version) |
|
||||
| **Environment** | A named set of key/value settings for a deployment target (URLs etc.), read with `context.getEnv(key)` |
|
||||
| **Credential** | Secret data (e.g. a key file and password), assigned to scenarios under an alias and read with `context.getCredential(alias)` |
|
||||
| **Session** | Saved browser state (cookies + localStorage), e.g. kept from a run with "save session" |
|
||||
|
||||
Scenarios, snippets, environments and credentials can be exported as YAML and imported back (one file may hold several of them).
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
## Documentation
|
||||
|
||||
See [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
---
|
||||
|
||||
## Key descriptors
|
||||
|
||||
See [docs/key-descriptors.md](docs/key-descriptors.md).
|
||||
|
||||
---
|
||||
|
||||
## MCP tools
|
||||
|
||||
See [docs/mcp.md](docs/mcp.md).
|
||||
|
||||
---
|
||||
|
||||
## Scenario execution
|
||||
|
||||
See [docs/scenario.md](docs/scenario.md).
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
See [docs/development.md](docs/development.md) for setup, running, testing, linting, and Docker instructions.
|
||||
- [docs/architecture.md](docs/architecture.md) - components, data model, client
|
||||
- [docs/scenario.md](docs/scenario.md) - runs, the script `context` API, versioning, import/export, Playwright traces
|
||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [docs/development.md](docs/development.md) - setup, configuration, running, testing, linting, Docker
|
||||
- [CHANGELOG.md](CHANGELOG.md) - release notes
|
||||
@@ -1,19 +0,0 @@
|
||||
# ── Build stage ───────────────────────────────────────────────────────────────
|
||||
FROM node:22-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy root lockfile + workspace manifests so npm ci can resolve the full graph
|
||||
COPY package*.json ./
|
||||
COPY client/package.json ./client/
|
||||
RUN npm ci -w client
|
||||
|
||||
COPY client ./client
|
||||
RUN npm run -w client build
|
||||
|
||||
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
||||
FROM nginx:alpine AS runtime
|
||||
|
||||
COPY --from=builder /app/client/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
@@ -4,10 +4,12 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build",
|
||||
"test:compile": "tsc --noEmit",
|
||||
"test:storybook": "vitest run --project storybook",
|
||||
"lint": "eslint src .storybook",
|
||||
"lint:fix": "eslint src .storybook --fix",
|
||||
@@ -15,6 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@tanstack/react-query": "^5.99.0",
|
||||
"highlight.js": "^11.11.1",
|
||||
"i18next": "^26.0.4",
|
||||
"lucide-react": "^1.7.0",
|
||||
|
||||
@@ -95,6 +95,12 @@
|
||||
background: var(--color-secondary-hover);
|
||||
}
|
||||
|
||||
.navSeparator {
|
||||
height: var(--border-width);
|
||||
background: var(--color-border);
|
||||
margin: var(--space-2) var(--space-2);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
|
||||
+46
-27
@@ -1,7 +1,7 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces } from 'lucide-react';
|
||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import styles from './App.module.css';
|
||||
import { SidePanel, ThemeSwitcher } from './ui';
|
||||
@@ -11,13 +11,19 @@ const EnvironmentsPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
||||
);
|
||||
const EnvironmentDetailPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentDetailPage').then((m) => ({ default: m.EnvironmentDetailPage })),
|
||||
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
|
||||
default: m.EnvironmentDetailPage,
|
||||
})),
|
||||
);
|
||||
const CreateEnvironmentPage = lazy(() =>
|
||||
import('./pages/environment/CreateEnvironmentPage').then((m) => ({ default: m.CreateEnvironmentPage })),
|
||||
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
|
||||
default: m.CreateEnvironmentPage,
|
||||
})),
|
||||
);
|
||||
const EditEnvironmentPage = lazy(() =>
|
||||
import('./pages/environment/EditEnvironmentPage').then((m) => ({ default: m.EditEnvironmentPage })),
|
||||
import('./pages/environment/EditEnvironmentPage').then((m) => ({
|
||||
default: m.EditEnvironmentPage,
|
||||
})),
|
||||
);
|
||||
|
||||
const SessionsPage = lazy(() =>
|
||||
@@ -46,9 +52,7 @@ const EditStepPage = lazy(() =>
|
||||
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
|
||||
);
|
||||
|
||||
const RunsPage = lazy(() =>
|
||||
import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })),
|
||||
);
|
||||
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
|
||||
const RunDetailPage = lazy(() =>
|
||||
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
|
||||
);
|
||||
@@ -60,13 +64,17 @@ const CredentialsPage = lazy(() =>
|
||||
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
|
||||
);
|
||||
const CreateCredentialPage = lazy(() =>
|
||||
import('./pages/credential/CreateCredentialPage').then((m) => ({ default: m.CreateCredentialPage })),
|
||||
import('./pages/credential/CreateCredentialPage').then((m) => ({
|
||||
default: m.CreateCredentialPage,
|
||||
})),
|
||||
);
|
||||
const EditCredentialPage = lazy(() =>
|
||||
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
|
||||
);
|
||||
const CredentialDetailPage = lazy(() =>
|
||||
import('./pages/credential/CredentialDetailPage').then((m) => ({ default: m.CredentialDetailPage })),
|
||||
import('./pages/credential/CredentialDetailPage').then((m) => ({
|
||||
default: m.CredentialDetailPage,
|
||||
})),
|
||||
);
|
||||
|
||||
const SnippetsPage = lazy(() =>
|
||||
@@ -81,14 +89,20 @@ const EditSnippetPage = lazy(() =>
|
||||
const SnippetDetailPage = lazy(() =>
|
||||
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
|
||||
);
|
||||
const ImportPage = lazy(() =>
|
||||
import('./pages/import/ImportPage').then((m) => ({ default: m.ImportPage })),
|
||||
);
|
||||
|
||||
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
|
||||
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: true })[] = [
|
||||
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ separator: true },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ separator: true },
|
||||
{ path: '/import', labelKey: 'nav.import', Icon: Upload },
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
@@ -106,18 +120,22 @@ export default function App() {
|
||||
>
|
||||
<div className={styles.sideContent}>
|
||||
<nav className={styles.nav}>
|
||||
{NAV.map(({ path, labelKey, Icon }) => (
|
||||
<NavLink
|
||||
key={path}
|
||||
to={path}
|
||||
className={({ isActive }) =>
|
||||
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
|
||||
}
|
||||
>
|
||||
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
|
||||
{t(labelKey)}
|
||||
</NavLink>
|
||||
))}
|
||||
{NAV.map((item, index) =>
|
||||
'separator' in item ? (
|
||||
<div key={`separator-${index}`} className={styles.navSeparator} />
|
||||
) : (
|
||||
<NavLink
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={({ isActive }) =>
|
||||
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
|
||||
}
|
||||
>
|
||||
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
|
||||
{t(item.labelKey)}
|
||||
</NavLink>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className={styles.sideFooter}>
|
||||
@@ -150,6 +168,7 @@ export default function App() {
|
||||
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
|
||||
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
|
||||
<Route path="/snippets" element={<SnippetsPage />} />
|
||||
<Route path="/import" element={<ImportPage />} />
|
||||
<Route path="/snippets/new" element={<CreateSnippetPage />} />
|
||||
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
|
||||
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
|
||||
|
||||
+153
-47
@@ -2,6 +2,10 @@ import type {
|
||||
PaginatedResponse,
|
||||
Credential,
|
||||
Environment,
|
||||
FileMetadata,
|
||||
FileListResponse,
|
||||
ImportResult,
|
||||
RunDefaults,
|
||||
ScenarioCredential,
|
||||
Session,
|
||||
Scenario,
|
||||
@@ -9,20 +13,32 @@ import type {
|
||||
ScenarioRunDetail,
|
||||
ScenarioRunStep,
|
||||
ScenarioStep,
|
||||
ScenarioVersion,
|
||||
Snippet,
|
||||
SnippetVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from './types';
|
||||
import { emitApiErrorToast } from '../lib/toast-events';
|
||||
|
||||
// API calls are versioned under /api/v1 by default.
|
||||
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
|
||||
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(/\/$/, '');
|
||||
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
|
||||
/\/$/,
|
||||
'',
|
||||
);
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!(init?.body instanceof FormData) && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...init?.headers },
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message || 'Network request failed';
|
||||
@@ -73,12 +89,6 @@ export const credentials = {
|
||||
exportCredential(id: string): Promise<unknown> {
|
||||
return request(`/credentials/${id}/export`);
|
||||
},
|
||||
importCredential(payload: unknown): Promise<Credential> {
|
||||
return request('/credentials/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Snippets ──────────────────────────────────────────────────────────────────
|
||||
@@ -90,7 +100,9 @@ export const snippets = {
|
||||
get(id: string): Promise<Snippet> {
|
||||
return request(`/snippets/${id}`);
|
||||
},
|
||||
create(payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string }): Promise<Snippet> {
|
||||
create(
|
||||
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
|
||||
): Promise<Snippet> {
|
||||
return request('/snippets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
@@ -108,15 +120,12 @@ export const snippets = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/snippets/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
versions(id: string): Promise<SnippetVersion[]> {
|
||||
return request(`/snippets/${id}/versions`);
|
||||
},
|
||||
exportSnippet(id: string): Promise<unknown> {
|
||||
return request(`/snippets/${id}/export`);
|
||||
},
|
||||
importSnippet(payload: unknown): Promise<Snippet> {
|
||||
return request('/snippets/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Environments ──────────────────────────────────────────────────────────────
|
||||
@@ -128,13 +137,16 @@ export const environments = {
|
||||
get(id: string): Promise<Environment> {
|
||||
return request(`/environments/${id}`);
|
||||
},
|
||||
create(name: string, data: Environment['data']): Promise<Environment> {
|
||||
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
|
||||
return request('/environments', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, data }),
|
||||
body: JSON.stringify({ name, description, data }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>,
|
||||
): Promise<Environment> {
|
||||
return request(`/environments/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -146,19 +158,18 @@ export const environments = {
|
||||
exportEnvironment(id: string): Promise<unknown> {
|
||||
return request(`/environments/${id}/export`);
|
||||
},
|
||||
importEnvironment(payload: unknown): Promise<Environment> {
|
||||
return request('/environments/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const sessions = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'id',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(id: string): Promise<Session> {
|
||||
return request(`/sessions/${id}`);
|
||||
@@ -171,19 +182,29 @@ export const sessions = {
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarios = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'updatedAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(
|
||||
`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
|
||||
return request(`/scenarios/${id}`);
|
||||
},
|
||||
create(name: string): Promise<Scenario> {
|
||||
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
|
||||
return request('/scenarios', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name }),
|
||||
body: JSON.stringify({ name, description, environmentId }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>,
|
||||
): Promise<Scenario> {
|
||||
return request(`/scenarios/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -192,12 +213,25 @@ export const scenarios = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/scenarios/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
run(id: string, environmentId: string): Promise<ScenarioRun> {
|
||||
run(
|
||||
id: string,
|
||||
environmentId: string,
|
||||
saveSession?: boolean,
|
||||
traceMode?: TraceMode,
|
||||
/** Scenario version to run; omit for the latest. */
|
||||
version?: number,
|
||||
): Promise<ScenarioRun> {
|
||||
return request(`/scenarios/${id}/run`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ environmentId }),
|
||||
body: JSON.stringify({ environmentId, saveSession, traceMode, version }),
|
||||
});
|
||||
},
|
||||
versions(id: string): Promise<ScenarioVersion[]> {
|
||||
return request(`/scenarios/${id}/versions`);
|
||||
},
|
||||
runDefaults(): Promise<RunDefaults> {
|
||||
return request('/scenarios/run-defaults');
|
||||
},
|
||||
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}`);
|
||||
},
|
||||
@@ -211,14 +245,25 @@ export const scenarios = {
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
},
|
||||
exportScenario(id: string): Promise<string> {
|
||||
return request(`/scenarios/${id}/export`);
|
||||
exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] } = {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
},
|
||||
): Promise<string> {
|
||||
const params = new URLSearchParams();
|
||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||
for (const cid of options.credentialIds) {
|
||||
params.append('credentialIds', cid);
|
||||
}
|
||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||
},
|
||||
importScenario(payload: unknown): Promise<Scenario> {
|
||||
return request('/scenarios/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
exportE2eTestUrl(id: string): string {
|
||||
return `${BASE_URL}/scenarios/${id}/export-e2e`;
|
||||
},
|
||||
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
||||
return request(`/scenarios/${id}/used-snippets`);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -229,12 +274,10 @@ export const runs = {
|
||||
page = 1,
|
||||
limit = 20,
|
||||
status?: string,
|
||||
): Promise<
|
||||
PaginatedResponse<
|
||||
ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }
|
||||
>
|
||||
> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { scenario: { id: string; name: string } }>> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
|
||||
if (status) q.set('status', status);
|
||||
return request(`/scenarios/runs?${q}`);
|
||||
},
|
||||
@@ -242,13 +285,20 @@ export const runs = {
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
return request(
|
||||
`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
|
||||
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
|
||||
},
|
||||
exportLogs(scenarioId: string, runId: string, format: 'csv' | 'md'): Promise<string> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}/logs/export?format=${format}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Credentials ──────────────────────────────────────────────────────
|
||||
@@ -274,12 +324,14 @@ export const scenarioCredentials = {
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export const steps = {
|
||||
@@ -302,3 +354,57 @@ export const steps = {
|
||||
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Files ────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarioFiles = {
|
||||
upload(scenarioId: string, file: File, expiresAt?: Date): Promise<FileMetadata> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (expiresAt) form.append('expiresAt', expiresAt.toISOString());
|
||||
return request(`/scenarios/${scenarioId}/files`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
},
|
||||
list(scenarioId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/files/${fileId}/content`;
|
||||
},
|
||||
};
|
||||
|
||||
// ── Run Files ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const runFiles = {
|
||||
list(scenarioId: string, runId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, runId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`;
|
||||
},
|
||||
remove(scenarioId: string, runId: string, fileId: string): Promise<void> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files/${fileId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Import ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const imports = {
|
||||
/**
|
||||
* Imports any mix of environments, credentials, snippets and scenarios from
|
||||
* YAML (`---`-separated documents, each one item or a list of items).
|
||||
*/
|
||||
yaml(text: string): Promise<ImportResult> {
|
||||
return request('/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/yaml' },
|
||||
body: text,
|
||||
});
|
||||
},
|
||||
};
|
||||
+102
-3
@@ -16,6 +16,7 @@ export interface EnvironmentData {
|
||||
export interface Environment {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
data: EnvironmentData;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -40,10 +41,29 @@ export interface Snippet {
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SnippetVersion {
|
||||
id: string;
|
||||
snippetId: string;
|
||||
version: number;
|
||||
alias: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** A snippet referenced by a scenario's steps. */
|
||||
export interface UsedSnippet extends Snippet {
|
||||
/** Version pinned via runSnippet('alias@N'), or null for the latest. */
|
||||
pinnedVersion: number | null;
|
||||
}
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type SessionStatus = 'open' | 'closed';
|
||||
@@ -66,6 +86,7 @@ export interface ScenarioStep {
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -82,14 +103,48 @@ export interface ScenarioCredential {
|
||||
export interface Scenario {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
environmentId?: string | null;
|
||||
timeoutSeconds?: number | null;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
steps?: ScenarioStep[];
|
||||
scenarioCredentials?: ScenarioCredential[];
|
||||
lastRunStatus?: ScenarioRunStatus | null;
|
||||
lastRunAt?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ScenarioStepSnapshot {
|
||||
id: string | null;
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
}
|
||||
|
||||
export interface ScenarioVersion {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
version: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
environmentId: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
steps: ScenarioStepSnapshot[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type ScenarioRunStatus = 'pending' | 'in_progress' | 'pass' | 'fail';
|
||||
|
||||
export type TraceMode = 'on' | 'retain-on-failure' | 'off';
|
||||
|
||||
export interface RunDefaults {
|
||||
traceMode: TraceMode;
|
||||
}
|
||||
|
||||
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
|
||||
|
||||
export type LogLevel = 'log' | 'warn' | 'error';
|
||||
@@ -97,8 +152,15 @@ export type LogLevel = 'log' | 'warn' | 'error';
|
||||
export interface ScenarioRun {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
environmentId: string;
|
||||
environmentId: string | null;
|
||||
sessionId?: string | null;
|
||||
saveSession: boolean;
|
||||
traceMode: TraceMode | null;
|
||||
/** Scenario version the run executes; null for runs created before versioning. */
|
||||
scenarioVersion: number | null;
|
||||
scenario?: Pick<Scenario, 'id' | 'name'>;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
session?: { id: string; sessionName: string };
|
||||
status: ScenarioRunStatus;
|
||||
stepRuns?: ScenarioRunStep[];
|
||||
createdAt: string;
|
||||
@@ -108,8 +170,12 @@ export interface ScenarioRun {
|
||||
export interface ScenarioRunStep {
|
||||
id: string;
|
||||
runId: string;
|
||||
scenarioStepId: string;
|
||||
scenarioStep: ScenarioStep;
|
||||
/** Live step this run step came from; null once that step is deleted. */
|
||||
scenarioStepId: string | null;
|
||||
// Step content as of the run's scenario version
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
status: RunStepStatus;
|
||||
order: number;
|
||||
description: string | null;
|
||||
@@ -131,3 +197,36 @@ export interface ScenarioRunDetail extends ScenarioRun {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
logs: ScenarioRunLog[];
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FileMetadata {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface FileListResponse {
|
||||
items: FileMetadata[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ── Import ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type ImportKind = 'environment' | 'credential' | 'snippet' | 'scenario';
|
||||
|
||||
export interface ImportedItem {
|
||||
kind: ImportKind;
|
||||
id: string;
|
||||
name: string;
|
||||
/** Version stored for versioned kinds (snippets, scenarios). */
|
||||
version?: number;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
imported: ImportedItem[];
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Trash2 } from 'lucide-react';
|
||||
import { Modal, Button } from '../../ui';
|
||||
|
||||
export interface DeleteConfirmationModalProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
isDeleting: boolean;
|
||||
}
|
||||
|
||||
export function DeleteConfirmationModal({
|
||||
open,
|
||||
title,
|
||||
message,
|
||||
onClose,
|
||||
onConfirm,
|
||||
isDeleting,
|
||||
}: DeleteConfirmationModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={title}
|
||||
onClose={() => !isDeleting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isDeleting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={onConfirm} disabled={isDeleting}>
|
||||
<Trash2 size={14} />
|
||||
{t('common.button_delete')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.radioRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.radioRow input[type='radio'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Download } from 'lucide-react';
|
||||
import { Modal, Button } from '../../ui';
|
||||
import styles from './ExportLogsModal.module.css';
|
||||
|
||||
export type LogExportFormat = 'md' | 'csv';
|
||||
|
||||
export interface ExportLogsModalProps {
|
||||
open: boolean;
|
||||
format: LogExportFormat;
|
||||
onFormatChange: (format: LogExportFormat) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportLogsModal({
|
||||
open,
|
||||
format,
|
||||
onFormatChange,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportLogsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('runs.export_logs_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('runs.export_logs_format')}</h4>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'md'}
|
||||
onChange={() => onFormatChange('md')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_md')}</span>
|
||||
</label>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'csv'}
|
||||
onChange={() => onFormatChange('csv')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_csv')}</span>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
.exportModal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.scenarioMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-primary);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.metaLabel {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-primary-fg);
|
||||
opacity: 0.7;
|
||||
min-width: 4rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.metaValue {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-primary-fg);
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.checkboxRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkboxRow input[type='checkbox'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Upload } from 'lucide-react';
|
||||
import { Modal, Button, UuidBadge } from '../../ui';
|
||||
import type { Scenario, ScenarioCredential } from '../../api';
|
||||
import styles from './ExportScenarioModal.module.css';
|
||||
|
||||
export interface ExportScenarioModalProps {
|
||||
open: boolean;
|
||||
scenario: Scenario | null;
|
||||
scenarioCredentials: ScenarioCredential[];
|
||||
environment: Pick<{ id: string; name: string }, 'id' | 'name'> | null;
|
||||
includeEnvironment: boolean;
|
||||
onIncludeEnvironmentChange: (v: boolean) => void;
|
||||
includedCredentialIds: Set<string>;
|
||||
onCredentialToggle: (id: string, checked: boolean) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportScenarioModal({
|
||||
open,
|
||||
scenario,
|
||||
scenarioCredentials,
|
||||
environment,
|
||||
includeEnvironment,
|
||||
onIncludeEnvironmentChange,
|
||||
includedCredentialIds,
|
||||
onCredentialToggle,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.export_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{scenario && (
|
||||
<div className={styles.exportModal}>
|
||||
<div className={styles.scenarioMeta}>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_name')}</span>
|
||||
<span className={styles.metaValue}>{scenario.name}</span>
|
||||
</div>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_id')}</span>
|
||||
<span className={styles.metaValue}>
|
||||
<UuidBadge id={scenario.id} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{environment && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_environment')}</h4>
|
||||
<label className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeEnvironment}
|
||||
onChange={(e) => onIncludeEnvironmentChange(e.target.checked)}
|
||||
/>
|
||||
<span>{environment.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenarioCredentials.length > 0 && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_credentials')}</h4>
|
||||
{scenarioCredentials.map((sc) => (
|
||||
<label key={sc.credentialId} className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includedCredentialIds.has(sc.credentialId)}
|
||||
onChange={(e) => onCredentialToggle(sc.credentialId, e.target.checked)}
|
||||
/>
|
||||
<span>{sc.credential?.name ?? sc.alias}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Play } from 'lucide-react';
|
||||
import { Modal, Button, Select } from '../../ui';
|
||||
import type { Environment, ScenarioVersion, TraceMode } from '../../api';
|
||||
|
||||
const TRACE_MODES: TraceMode[] = ['on', 'retain-on-failure', 'off'];
|
||||
|
||||
export interface RunScenarioModalProps {
|
||||
open: boolean;
|
||||
environments: Environment[];
|
||||
selectedEnvId: string;
|
||||
onEnvSelect: (envId: string) => void;
|
||||
saveSessionFlag: boolean;
|
||||
onSaveSessionChange: (flag: boolean) => void;
|
||||
/** Scenario versions, newest first; empty while loading. */
|
||||
versions: Pick<ScenarioVersion, 'version' | 'createdAt'>[];
|
||||
/** Selected version, or null for the latest. */
|
||||
selectedVersion: number | null;
|
||||
onVersionChange: (version: number | null) => void;
|
||||
traceMode: TraceMode;
|
||||
defaultTraceMode: TraceMode | null;
|
||||
onTraceModeChange: (mode: TraceMode) => void;
|
||||
onClose: () => void;
|
||||
onRun: () => void;
|
||||
isRunning: boolean;
|
||||
actionLabel?: string;
|
||||
}
|
||||
|
||||
export function RunScenarioModal({
|
||||
open,
|
||||
environments,
|
||||
selectedEnvId,
|
||||
onEnvSelect,
|
||||
saveSessionFlag,
|
||||
onSaveSessionChange,
|
||||
versions,
|
||||
selectedVersion,
|
||||
onVersionChange,
|
||||
traceMode,
|
||||
defaultTraceMode,
|
||||
onTraceModeChange,
|
||||
onClose,
|
||||
onRun,
|
||||
isRunning,
|
||||
actionLabel,
|
||||
}: RunScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !isRunning && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isRunning}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onRun} disabled={isRunning || !selectedEnvId}>
|
||||
<Play size={14} />
|
||||
{actionLabel || t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{environments.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => onEnvSelect(e.target.value)}
|
||||
options={environments.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_version_label')}
|
||||
value={selectedVersion == null ? '' : String(selectedVersion)}
|
||||
onChange={(e) => onVersionChange(e.target.value ? Number(e.target.value) : null)}
|
||||
options={[
|
||||
{
|
||||
value: '',
|
||||
label: versions[0]
|
||||
? t('scenarios.run_modal_version_latest_n', { version: versions[0].version })
|
||||
: t('scenarios.run_modal_version_latest'),
|
||||
},
|
||||
...versions.map((v) => ({
|
||||
value: String(v.version),
|
||||
label: `v${v.version} — ${new Date(v.createdAt).toLocaleString()}`,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
marginTop: '1rem',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => onSaveSessionChange(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_trace_label')}
|
||||
value={traceMode}
|
||||
onChange={(e) => onTraceModeChange(e.target.value as TraceMode)}
|
||||
options={TRACE_MODES.map((mode) => ({
|
||||
value: mode,
|
||||
label:
|
||||
t(`scenarios.trace_mode_${mode.replace(/-/g, '_')}`) +
|
||||
(mode === defaultTraceMode ? ` ${t('scenarios.trace_mode_default_suffix')}` : ''),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
|
||||
export { ExportScenarioModal } from './ExportScenarioModal';
|
||||
export type { ExportScenarioModalProps } from './ExportScenarioModal';
|
||||
export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
export { ExportLogsModal } from './ExportLogsModal';
|
||||
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ChangeEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { imports } from '../api';
|
||||
import type { ImportedItem, ImportKind } from '../api';
|
||||
import { useToast } from '../ui';
|
||||
|
||||
/** Detail page path of an imported item. */
|
||||
export function importedItemPath(item: ImportedItem): string {
|
||||
return `/${item.kind}s/${item.id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a file input `onChange` handler that imports the chosen YAML file
|
||||
* through the central import. When the file holds exactly one item of `kind`
|
||||
* (e.g. a scenario export with its environment), opens that item; otherwise
|
||||
* opens the import page with the full result.
|
||||
*/
|
||||
export function useImportFile(kind: ImportKind) {
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const result = await imports.yaml(await file.text());
|
||||
const own = result.imported.filter((item) => item.kind === kind);
|
||||
if (own.length === 1) {
|
||||
if (result.imported.length > 1) {
|
||||
toast.success(t('import.imported_count', { count: result.imported.length }));
|
||||
}
|
||||
navigate(importedItemPath(own[0]));
|
||||
} else {
|
||||
navigate('/import', { state: { results: [{ fileName: file.name, result }] } });
|
||||
}
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const APP_NAME = 'Liqa';
|
||||
|
||||
/**
|
||||
* Sets document.title to "<title> | Liqa" for the current page.
|
||||
* Pass undefined or empty string to fall back to just "Liqa".
|
||||
*/
|
||||
export function usePageTitle(title: string | null | undefined): void {
|
||||
useEffect(() => {
|
||||
const prev = document.title;
|
||||
document.title = title ? `${title} | ${APP_NAME}` : APP_NAME;
|
||||
return () => {
|
||||
document.title = prev;
|
||||
};
|
||||
}, [title]);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { scenarios } from '../api';
|
||||
import type { RunDefaults } from '../api';
|
||||
|
||||
// Server run defaults don't change while the app is open; fetch them once
|
||||
let cached: Promise<RunDefaults> | null = null;
|
||||
|
||||
/**
|
||||
* Returns the server-configured defaults for new scenario runs, or null
|
||||
* while they are loading (or if the request failed).
|
||||
*/
|
||||
export function useRunDefaults(): RunDefaults | null {
|
||||
const [defaults, setDefaults] = useState<RunDefaults | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
cached ??= scenarios.runDefaults().catch((err: unknown) => {
|
||||
cached = null;
|
||||
throw err;
|
||||
});
|
||||
cached.then((d) => !cancelled && setDefaults(d)).catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return defaults;
|
||||
}
|
||||
@@ -1,4 +1,17 @@
|
||||
{
|
||||
"common": {
|
||||
"button_cancel": "Cancel",
|
||||
"button_confirm": "Confirm",
|
||||
"button_delete": "Delete",
|
||||
"confirm_delete_credential": "Are you sure you want to delete this credential?",
|
||||
"confirm_delete_environment": "Are you sure you want to delete this environment?",
|
||||
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
|
||||
"confirm_delete_step": "Are you sure you want to delete this step?",
|
||||
"confirm_delete_session": "Are you sure you want to delete this session?",
|
||||
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
|
||||
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
|
||||
"save_session": "Save session"
|
||||
},
|
||||
"errors": {
|
||||
"not_found": "Not found",
|
||||
"not_found_session": "Session {{id}} does not exist or has been deleted.",
|
||||
@@ -15,12 +28,32 @@
|
||||
"keys": "Keys",
|
||||
"sessions": "Sessions",
|
||||
"scenarios": "Scenarios",
|
||||
"runs": "Runs"
|
||||
"runs": "Runs",
|
||||
"import": "Import"
|
||||
},
|
||||
"import": {
|
||||
"title": "Import",
|
||||
"action_choose": "Choose files",
|
||||
"description": "Import exported environments, credentials, snippets and scenarios. Each YAML file may hold several items as ---separated documents, and each document may hold one item or a list of items. JSON files work too.",
|
||||
"description_validation": "Every item in a file is checked before anything is imported: if one item is invalid, nothing from that file is imported. Items are imported in dependency order (environments, credentials, snippets, scenarios), and snippets and scenarios keep the version they were exported with.",
|
||||
"imported_count_one": "Imported {{count}} item",
|
||||
"imported_count_other": "Imported {{count}} items",
|
||||
"col_file": "File",
|
||||
"col_kind": "Kind",
|
||||
"col_name": "Name",
|
||||
"col_version": "Version",
|
||||
"kind_environment": "Environment",
|
||||
"kind_credential": "Credential",
|
||||
"kind_snippet": "Snippet",
|
||||
"kind_scenario": "Scenario"
|
||||
},
|
||||
"environments": {
|
||||
"title": "Environments",
|
||||
"created": "Environment created",
|
||||
"updated": "Environment updated",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_description": "Description",
|
||||
"col_data": "Data",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No environments yet.",
|
||||
@@ -41,16 +74,21 @@
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. staging, production",
|
||||
"form_name_required": "Name is required",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this environment",
|
||||
"form_data": "Data (JSON)",
|
||||
"form_data_invalid_json": "Must be a valid JSON object",
|
||||
"back": "Environments",
|
||||
"field_id": "ID",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_data": "Data"
|
||||
},
|
||||
"credentials": {
|
||||
"title": "Credentials",
|
||||
"created": "Credential created",
|
||||
"updated": "Credential updated",
|
||||
"empty": "No credentials yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Credential options",
|
||||
@@ -98,9 +136,16 @@
|
||||
"field_updated": "Updated",
|
||||
"field_lastUsed": "Last Used"
|
||||
},
|
||||
"scenarios": { "title": "Scenarios",
|
||||
"scenarios": {
|
||||
"title": "Scenarios",
|
||||
"created": "Scenario created",
|
||||
"updated": "Scenario updated",
|
||||
"run_started": "Scenario run started",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_version": "Version",
|
||||
"col_description": "Description",
|
||||
"col_last_run": "Last Run",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No scenarios yet.",
|
||||
"loading": "Loading…",
|
||||
@@ -108,6 +153,8 @@
|
||||
"action_delete": "Delete",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_version": "Version",
|
||||
"field_description": "Description",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
@@ -121,6 +168,7 @@
|
||||
"action_edit": "Edit",
|
||||
"action_runs": "Runs",
|
||||
"action_export": "Export",
|
||||
"action_export_e2e": "Export e2e test",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import scenario",
|
||||
"action_save": "Create",
|
||||
@@ -128,10 +176,18 @@
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Scenario",
|
||||
"edit_title": "Edit Scenario",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this scenario",
|
||||
"form_environment": "Default Environment",
|
||||
"form_environment_none": "None (no default environment)",
|
||||
"field_environment": "Default Environment",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. Login flow",
|
||||
"form_name_required": "Name is required",
|
||||
"credentials_heading": "Credentials",
|
||||
"used_snippets_heading": "Used Snippets",
|
||||
"used_snippet_pinned": "v{{version}} (pinned)",
|
||||
"used_snippet_latest": "Latest (v{{version}})",
|
||||
"cred_empty": "No credentials assigned.",
|
||||
"cred_col_alias": "Alias",
|
||||
"cred_col_name": "Credential",
|
||||
@@ -149,7 +205,23 @@
|
||||
"run_modal_title": "Select environment",
|
||||
"run_modal_env_label": "Environment",
|
||||
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
|
||||
"run_modal_env_required": "Please select an environment"
|
||||
"run_modal_env_required": "Please select an environment",
|
||||
"run_modal_version_label": "Version",
|
||||
"run_modal_version_latest": "Latest",
|
||||
"run_modal_version_latest_n": "Latest (v{{version}})",
|
||||
"run_modal_trace_label": "Playwright trace",
|
||||
"trace_mode_on": "Always keep",
|
||||
"trace_mode_retain_on_failure": "Keep on failure",
|
||||
"trace_mode_off": "Off",
|
||||
"trace_mode_default_suffix": "(default)",
|
||||
"export_modal_title": "Export Scenario",
|
||||
"export_include_environment": "Include Environment",
|
||||
"export_include_credentials": "Include Credentials",
|
||||
"form_timeout": "Scenario Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 600",
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
||||
"field_name": "Name",
|
||||
"field_id": "ID"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -165,6 +237,8 @@
|
||||
"page_size": "Items per page"
|
||||
},
|
||||
"steps": {
|
||||
"created": "Step created",
|
||||
"updated": "Step updated",
|
||||
"create_title": "Add Step",
|
||||
"edit_title": "Edit Step #{{order}}",
|
||||
"loading": "Loading…",
|
||||
@@ -183,7 +257,10 @@
|
||||
"form_session_placeholder": "e.g. my-session",
|
||||
"form_session_required": "Session name is required",
|
||||
"form_exec_code": "Exec code",
|
||||
"form_exec_code_placeholder": "return await page.title();"
|
||||
"form_exec_code_placeholder": "return await page.title();",
|
||||
"form_timeout": "Step Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 60",
|
||||
"form_timeout_hint": "Max seconds for this step (default: 60)"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Runs",
|
||||
@@ -194,12 +271,15 @@
|
||||
"col_scenario": "Scenario",
|
||||
"col_status": "Status",
|
||||
"col_steps": "Steps",
|
||||
"col_version": "Version",
|
||||
"col_created": "Started",
|
||||
"field_id": "ID",
|
||||
"field_status": "Status",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Started",
|
||||
"field_updated": "Updated",
|
||||
"field_trace": "Playwright trace",
|
||||
"field_scenario_version": "Scenario version",
|
||||
"steps_heading": "Step runs",
|
||||
"step_title": "Title",
|
||||
"logs_heading": "Logs",
|
||||
@@ -211,10 +291,20 @@
|
||||
"step_description": "Result",
|
||||
"log_level": "Level",
|
||||
"log_message": "Message",
|
||||
"log_time": "Time"
|
||||
"log_time": "Time",
|
||||
"action_download_logs": "Download logs",
|
||||
"action_repeat": "Repeat run",
|
||||
"repeat_no_environment": "The environment used by this run no longer exists",
|
||||
"export_logs_modal_title": "Export logs",
|
||||
"export_logs_format": "Format",
|
||||
"export_logs_format_md": "Markdown (.md)",
|
||||
"export_logs_format_csv": "CSV (.csv)",
|
||||
"action_export": "Export"
|
||||
},
|
||||
"snippets": {
|
||||
"title": "Snippets",
|
||||
"created": "Snippet created",
|
||||
"updated": "Snippet updated",
|
||||
"empty": "No snippets yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Snippet options",
|
||||
@@ -239,6 +329,7 @@
|
||||
"form_code_required": "Code is required",
|
||||
"field_id": "ID",
|
||||
"field_alias": "Alias",
|
||||
"field_version": "Version",
|
||||
"field_title": "Title",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
@@ -247,5 +338,26 @@
|
||||
"action_export": "Export",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import snippet"
|
||||
},
|
||||
"files": {
|
||||
"title": "Files",
|
||||
"upload": "Upload",
|
||||
"uploadTitle": "Upload File",
|
||||
"uploadSuccess": "File uploaded successfully",
|
||||
"name": "Name",
|
||||
"mimeType": "MIME Type",
|
||||
"size": "Size",
|
||||
"expiresAt": "Expires At",
|
||||
"expiresAtLabel": "Expires At (optional)",
|
||||
"createdAt": "Created",
|
||||
"download": "Download",
|
||||
"delete": "Delete",
|
||||
"deleteTitle": "Delete file",
|
||||
"confirmDelete": "Are you sure you want to delete \"{{name}}\" from this run?",
|
||||
"deleteSuccess": "File deleted",
|
||||
"expiredTooltip": "File is expired",
|
||||
"empty": "No files uploaded.",
|
||||
"totalCount": "Total: {{count}} file(s)",
|
||||
"artifactsTitle": "Artifacts"
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export interface ApiErrorToastDetail {
|
||||
|
||||
export function emitApiErrorToast(message: string): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
|
||||
detail: { message },
|
||||
@@ -13,17 +14,17 @@ export function emitApiErrorToast(message: string): void {
|
||||
);
|
||||
}
|
||||
|
||||
export function subscribeApiErrorToasts(
|
||||
handler: (message: string) => void,
|
||||
): () => void {
|
||||
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
|
||||
if (typeof window === 'undefined') return () => {};
|
||||
|
||||
const listener = (event: Event) => {
|
||||
const custom = event as CustomEvent<ApiErrorToastDetail>;
|
||||
const message = custom.detail?.message;
|
||||
if (message) handler(message);
|
||||
};
|
||||
window.addEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
|
||||
|
||||
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
|
||||
return () => {
|
||||
window.removeEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
|
||||
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
|
||||
};
|
||||
}
|
||||
+10
-5
@@ -1,17 +1,22 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import './i18n';
|
||||
import './ui/tokens.css';
|
||||
import App from './App';
|
||||
import { ToastProvider } from './ui';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,6 +9,7 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('credentials.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
@@ -16,9 +18,8 @@ export function CreateCredentialPage() {
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
@@ -35,14 +36,12 @@ export function CreateCredentialPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const credential = await credentials.create(name.trim(), data.trim() || undefined);
|
||||
toast.success('Credential created');
|
||||
toast.success(t('credentials.created'));
|
||||
navigate(`/credentials/${credential.id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -54,7 +53,11 @@ export function CreateCredentialPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{ label: t('credentials.create_title') },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CredentialDetailPage() {
|
||||
@@ -23,7 +17,7 @@ export function CredentialDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(credential?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
@@ -32,7 +26,6 @@ export function CredentialDetailPage() {
|
||||
credentials
|
||||
.get(id)
|
||||
.then(setCredential)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
@@ -65,7 +58,11 @@ export function CredentialDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{ label: credential?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
@@ -136,23 +133,14 @@ export function CredentialDetailPage() {
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('credentials.action_delete')}
|
||||
onClose={() => !deleting && setConfirmDeleteOpen(false)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('credentials.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this credential?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_credential')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import {
|
||||
@@ -11,10 +12,10 @@ import {
|
||||
Card,
|
||||
ContextMenu,
|
||||
DescriptionList,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function CredentialCard({
|
||||
@@ -100,10 +101,9 @@ function AddCredentialCard() {
|
||||
|
||||
export function CredentialsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
usePageTitle(t('credentials.title'));
|
||||
const [items, setItems] = useState<Credential[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -112,7 +112,6 @@ export function CredentialsPage() {
|
||||
credentials
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -136,19 +135,7 @@ export function CredentialsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await credentials.importCredential(payload);
|
||||
navigate(`/credentials/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
};
|
||||
const handleImport = useImportFile('credential');
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -179,23 +166,14 @@ export function CredentialsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('credentials.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('credentials.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this credential?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_credential')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
@@ -15,12 +16,16 @@ export function EditCredentialPage() {
|
||||
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
credential
|
||||
? `${t('credentials.edit_title')} — ${credential.name}`
|
||||
: t('credentials.edit_title'),
|
||||
);
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -31,11 +36,10 @@ export function EditCredentialPage() {
|
||||
setName(c.name);
|
||||
setData(c.data ?? '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
@@ -52,17 +56,15 @@ export function EditCredentialPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await credentials.update(id!, {
|
||||
name: name.trim(),
|
||||
data: data.trim() || null,
|
||||
});
|
||||
toast.success('Credential updated');
|
||||
toast.success(t('credentials.updated'));
|
||||
navigate(`/credentials/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -74,7 +76,11 @@ export function EditCredentialPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{
|
||||
label: credential?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/credentials/${id}`),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,17 +9,18 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateEnvironmentPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('environments.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('environments.form_name_required'));
|
||||
@@ -42,14 +44,16 @@ export function CreateEnvironmentPage() {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const env = await environments.create(name.trim(), parsedData);
|
||||
toast.success('Environment created');
|
||||
const env = await environments.create(
|
||||
name.trim(),
|
||||
parsedData,
|
||||
description.trim() || undefined,
|
||||
);
|
||||
toast.success(t('environments.created'));
|
||||
navigate(`/environments/${env.id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -61,7 +65,11 @@ export function CreateEnvironmentPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{ label: t('environments.create_title') },
|
||||
]}
|
||||
/>
|
||||
@@ -82,6 +90,15 @@ export function CreateEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
@@ -15,12 +16,15 @@ export function EditEnvironmentPage() {
|
||||
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
env ? `${t('environments.edit_title')} — ${env.name}` : t('environments.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -29,13 +33,13 @@ export function EditEnvironmentPage() {
|
||||
.then((data) => {
|
||||
setEnv(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('environments.form_name_required'));
|
||||
@@ -59,17 +63,16 @@ export function EditEnvironmentPage() {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await environments.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
data: parsedData,
|
||||
});
|
||||
toast.success('Environment updated');
|
||||
toast.success(t('environments.updated'));
|
||||
navigate(`/environments/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -81,7 +84,11 @@ export function EditEnvironmentPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{
|
||||
label: env?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/environments/${id}`),
|
||||
@@ -109,6 +116,15 @@ export function EditEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Upload, Pencil, Trash2, Globe } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Modal, Timestamp, UuidBadge } from '../../ui';
|
||||
import { environments } from '../../api';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EnvironmentDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(env?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
|
||||
@@ -24,9 +36,9 @@ export function EnvironmentDetailPage() {
|
||||
environments
|
||||
.get(id)
|
||||
.then(setEnv)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.catch((err: Error) => toast.error((err as Error).message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
}, [id, toast]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!env) return;
|
||||
@@ -57,7 +69,11 @@ export function EnvironmentDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{ label: env?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
@@ -104,15 +120,26 @@ export function EnvironmentDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{env.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={env.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
|
||||
<Card>
|
||||
{dataEntries.length === 0 ? (
|
||||
<p className={styles.muted}>{t('environments.no_data')}</p>
|
||||
) : (
|
||||
<DescriptionList
|
||||
layout="grid"
|
||||
items={dataEntries.map(([key, value]) => ({
|
||||
{dataEntries.length === 0 ? (
|
||||
<p className={styles.muted}>{t('environments.no_data')}</p>
|
||||
) : (
|
||||
<DescriptionList
|
||||
layout="grid"
|
||||
items={dataEntries.map(([key, value]) => ({
|
||||
term: key,
|
||||
detail: (
|
||||
<a href={value} target="_blank" rel="noopener noreferrer">
|
||||
@@ -120,30 +147,21 @@ export function EnvironmentDetailPage() {
|
||||
</a>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('environments.action_delete')}
|
||||
onClose={() => !deleting && setConfirmDeleteOpen(false)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('environments.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this environment?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_environment')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
@@ -12,10 +13,10 @@ import {
|
||||
Card,
|
||||
ContextMenu,
|
||||
DescriptionList,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
|
||||
@@ -117,10 +118,9 @@ function AddEnvironmentCard() {
|
||||
|
||||
export function EnvironmentsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
usePageTitle(t('environments.title'));
|
||||
const [items, setItems] = useState<Environment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -129,7 +129,6 @@ export function EnvironmentsPage() {
|
||||
environments
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -153,19 +152,7 @@ export function EnvironmentsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await environments.importEnvironment(payload);
|
||||
navigate(`/environments/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
};
|
||||
const handleImport = useImportFile('environment');
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -196,23 +183,14 @@ export function EnvironmentsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('environments.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('environments.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this environment?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_environment')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useRef, useState, type ChangeEvent } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Upload } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { importedItemPath } from '../../hooks/useImportFile';
|
||||
import { imports } from '../../api';
|
||||
import type { ImportedItem, ImportResult } from '../../api';
|
||||
import { Badge, Breadcrumbs, Button, Card, Table, type TableColumn } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
interface FileResult {
|
||||
fileName: string;
|
||||
result: ImportResult;
|
||||
}
|
||||
|
||||
type Row = ImportedItem & { fileName: string; rowKey: string };
|
||||
|
||||
export function ImportPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('import.title'));
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
// List pages hand over the result of an import they ran
|
||||
const [results, setResults] = useState<FileResult[]>(
|
||||
() => (location.state as { results?: FileResult[] } | null)?.results ?? [],
|
||||
);
|
||||
const [importing, setImporting] = useState(false);
|
||||
|
||||
const handleFiles = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
e.target.value = '';
|
||||
if (files.length === 0) return;
|
||||
setImporting(true);
|
||||
const next: FileResult[] = [];
|
||||
try {
|
||||
for (const file of files) {
|
||||
try {
|
||||
next.push({ fileName: file.name, result: await imports.yaml(await file.text()) });
|
||||
} catch {
|
||||
// error toast is already emitted by the API client; nothing from
|
||||
// this file was imported, continue with the next one
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setResults(next);
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const rows: Row[] = results.flatMap(({ fileName, result }) =>
|
||||
result.imported.map((item, i) => ({ ...item, fileName, rowKey: `${fileName}-${i}` })),
|
||||
);
|
||||
|
||||
const columns: TableColumn<Row>[] = [
|
||||
{ key: 'fileName', header: t('import.col_file'), render: (r) => r.fileName },
|
||||
{
|
||||
key: 'kind',
|
||||
header: t('import.col_kind'),
|
||||
width: 120,
|
||||
render: (r) => <Badge variant="neutral">{t(`import.kind_${r.kind}`)}</Badge>,
|
||||
},
|
||||
{ key: 'name', header: t('import.col_name'), render: (r) => r.name },
|
||||
{
|
||||
key: 'version',
|
||||
header: t('import.col_version'),
|
||||
width: 90,
|
||||
render: (r) =>
|
||||
r.version != null ? `v${r.version}` : <span className={styles.muted}>–</span>,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('import.title'), icon: <Upload size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".yaml,.yml,.json"
|
||||
multiple
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFiles}
|
||||
/>
|
||||
<Button size="sm" onClick={() => fileInputRef.current?.click()} disabled={importing}>
|
||||
<Upload size={14} />
|
||||
{t('import.action_choose')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<p>{t('import.description')}</p>
|
||||
<p className={styles.muted}>{t('import.description_validation')}</p>
|
||||
</Card>
|
||||
|
||||
{rows.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>
|
||||
{t('import.imported_count', { count: rows.length })}
|
||||
</h2>
|
||||
<Table<Row>
|
||||
columns={columns}
|
||||
data={rows}
|
||||
rowKey={(r) => r.rowKey}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
onRowClick={(r) => navigate(importedItemPath(r))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Activity } from 'lucide-react';
|
||||
import { runs } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
@@ -12,6 +14,7 @@ import {
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -31,49 +34,49 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
};
|
||||
|
||||
type AllRunRow = ScenarioRun & {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
scenario: { id: number; name: string };
|
||||
scenario: { id: string; name: string };
|
||||
};
|
||||
|
||||
export function AllRunsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('runs.title'));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [items, setItems] = useState<AllRunRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const hasDataRef = useRef(false);
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
runs
|
||||
.listAll()
|
||||
.then((res) => {
|
||||
setItems(res.data as AllRunRow[]);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['runs', sortBy, sortDir, page, pageSize],
|
||||
queryFn: () =>
|
||||
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, []);
|
||||
const items = (data?.data ?? []) as AllRunRow[];
|
||||
const total = data?.total ?? 0;
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => setPage(p);
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const columns: TableColumn<AllRunRow>[] = [
|
||||
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
|
||||
{
|
||||
key: 'scenario',
|
||||
key: 'scenario.name',
|
||||
header: t('runs.col_scenario'),
|
||||
sortable: true,
|
||||
render: (r) => (
|
||||
<span
|
||||
className={styles.linkCell}
|
||||
@@ -90,18 +93,25 @@ export function AllRunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 110,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -110,18 +120,30 @@ export function AllRunsPage() {
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
|
||||
<AutoRefreshIndicator
|
||||
active
|
||||
pulseKey={items.length}
|
||||
error={!!error}
|
||||
onClick={() => refetch()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
loading={isLoading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { runs } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { runs, runFiles } from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioRunDetail,
|
||||
@@ -10,24 +11,40 @@ import type {
|
||||
ScenarioRunStatus,
|
||||
RunStepStatus,
|
||||
LogLevel,
|
||||
FileMetadata,
|
||||
} from '../../api';
|
||||
import { scenarios } from '../../api';
|
||||
import {
|
||||
DeleteConfirmationModal,
|
||||
ExportLogsModal,
|
||||
type LogExportFormat,
|
||||
} from '../../components/modals';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Button,
|
||||
Breadcrumbs,
|
||||
Card,
|
||||
CodeBlock,
|
||||
DescriptionList,
|
||||
Notification,
|
||||
Pagination,
|
||||
Search,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import { ClipboardList, Activity } from 'lucide-react';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Activity,
|
||||
Download,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
} from 'lucide-react';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
@@ -62,19 +79,38 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
export function RunDetailPage() {
|
||||
const { runId } = useParams<{ runId: string }>();
|
||||
// Remount per run so "Repeat run" navigation starts from a clean state
|
||||
return <RunDetail key={runId} />;
|
||||
}
|
||||
|
||||
function RunDetail() {
|
||||
const { t } = useTranslation();
|
||||
const { id, runId } = useParams<{ id: string; runId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [polling, setPolling] = useState(false);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const [logPage, setLogPage] = useState(1);
|
||||
const [logSearch, setLogSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
const [expandedStepIds, setExpandedStepIds] = useState<Set<string>>(new Set());
|
||||
const [artifacts, setArtifacts] = useState<FileMetadata[]>([]);
|
||||
const [artifactsTotal, setArtifactsTotal] = useState(0);
|
||||
const [artifactsLoading, setArtifactsLoading] = useState(false);
|
||||
const [exportLogsOpen, setExportLogsOpen] = useState(false);
|
||||
const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md');
|
||||
const [exportingLogs, setExportingLogs] = useState(false);
|
||||
const [pendingDeleteFile, setPendingDeleteFile] = useState<FileMetadata | null>(null);
|
||||
const [deletingFile, setDeletingFile] = useState(false);
|
||||
const [repeating, setRepeating] = useState(false);
|
||||
const logSearchRef = useRef('');
|
||||
const LOG_PAGE_SIZE = 25;
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
@@ -87,6 +123,72 @@ export function RunDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
const handleExportLogs = async () => {
|
||||
if (!id || !runId) return;
|
||||
setExportingLogs(true);
|
||||
try {
|
||||
const content = await runs.exportLogs(id, runId, exportLogsFormat);
|
||||
const mimeType = exportLogsFormat === 'csv' ? 'text/csv' : 'text/markdown';
|
||||
const blob = new Blob([content], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `run-${runId}-logs.${exportLogsFormat}`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportLogsOpen(false);
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setExportingLogs(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepeatRun = async () => {
|
||||
if (!id || !run?.environmentId) return;
|
||||
setRepeating(true);
|
||||
try {
|
||||
const newRun = await scenarios.run(
|
||||
id,
|
||||
run.environmentId,
|
||||
run.saveSession,
|
||||
run.traceMode ?? undefined,
|
||||
run.scenarioVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${newRun.id}`);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRepeating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFile = async () => {
|
||||
if (!id || !runId || !pendingDeleteFile) return;
|
||||
setDeletingFile(true);
|
||||
try {
|
||||
await runFiles.remove(id, runId, pendingDeleteFile.id);
|
||||
toast.success(t('files.deleteSuccess'));
|
||||
setPendingDeleteFile(null);
|
||||
await loadArtifacts();
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setDeletingFile(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manualRefresh = () => {
|
||||
if (!id || !runId) return;
|
||||
runs
|
||||
@@ -99,6 +201,22 @@ export function RunDetailPage() {
|
||||
.catch((err: Error) => setError(err.message));
|
||||
};
|
||||
|
||||
const loadArtifacts = useCallback(async () => {
|
||||
if (!id || !runId) return;
|
||||
setArtifactsLoading(true);
|
||||
try {
|
||||
const result = await runFiles.list(id, runId);
|
||||
setArtifacts(result.items);
|
||||
setArtifactsTotal(result.total);
|
||||
} catch {
|
||||
// Silently fail - artifacts are not critical
|
||||
setArtifacts([]);
|
||||
setArtifactsTotal(0);
|
||||
} finally {
|
||||
setArtifactsLoading(false);
|
||||
}
|
||||
}, [id, runId]);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
setDebouncedSearch(logSearch);
|
||||
@@ -125,6 +243,7 @@ export function RunDetailPage() {
|
||||
if (cancelled) return;
|
||||
setScenario(sc);
|
||||
setRun(r);
|
||||
loadArtifacts();
|
||||
if (!FINAL.includes(r.status)) {
|
||||
setPolling(true);
|
||||
pollRef.current = setInterval(async () => {
|
||||
@@ -133,7 +252,10 @@ export function RunDetailPage() {
|
||||
if (cancelled) return;
|
||||
setRun(updated);
|
||||
setPulseKey((k) => k + 1);
|
||||
if (FINAL.includes(updated.status)) stopPolling();
|
||||
if (FINAL.includes(updated.status)) {
|
||||
stopPolling();
|
||||
await loadArtifacts();
|
||||
}
|
||||
} catch {
|
||||
stopPolling();
|
||||
}
|
||||
@@ -151,7 +273,7 @@ export function RunDetailPage() {
|
||||
cancelled = true;
|
||||
stopPolling();
|
||||
};
|
||||
}, [id, runId]);
|
||||
}, [id, runId, loadArtifacts]);
|
||||
|
||||
const stepColumns: TableColumn<ScenarioRunStep>[] = [
|
||||
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
|
||||
@@ -159,7 +281,7 @@ export function RunDetailPage() {
|
||||
key: 'title',
|
||||
header: t('runs.step_title'),
|
||||
width: 220,
|
||||
render: (s) => s.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
|
||||
render: (s) => s.title ?? <span className={styles.muted}>–</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
@@ -171,8 +293,110 @@ export function RunDetailPage() {
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: t('runs.step_description'),
|
||||
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
|
||||
header: (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '8px',
|
||||
}}
|
||||
>
|
||||
<span>{t('runs.step_description')}</span>
|
||||
{run?.stepRuns.some((s) => s.output) && (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (expandAll) {
|
||||
setExpandAll(false);
|
||||
setExpandedStepIds(new Set());
|
||||
} else {
|
||||
setExpandAll(true);
|
||||
setExpandedStepIds(
|
||||
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: '0 4px',
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
color: 'inherit',
|
||||
}}
|
||||
title={expandAll ? 'Collapse all' : 'Expand all'}
|
||||
>
|
||||
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
render: (s) => {
|
||||
const isExpanded = expandAll || expandedStepIds.has(s.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: '8px',
|
||||
marginBottom: isExpanded && s.output ? '8px' : 0,
|
||||
}}
|
||||
>
|
||||
{s.output && (
|
||||
<button
|
||||
onClick={() => {
|
||||
const newSet = new Set(expandedStepIds);
|
||||
if (newSet.has(s.id)) {
|
||||
newSet.delete(s.id);
|
||||
} else {
|
||||
newSet.add(s.id);
|
||||
}
|
||||
setExpandedStepIds(newSet);
|
||||
}}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: 0,
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
flexShrink: 0,
|
||||
marginTop: '2px',
|
||||
}}
|
||||
>
|
||||
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</button>
|
||||
)}
|
||||
<code style={{ wordBreak: 'break-word' }}>
|
||||
{s.description ? (
|
||||
s.description
|
||||
) : s.output ? (
|
||||
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
)}
|
||||
</code>
|
||||
</div>
|
||||
{isExpanded && s.output && (
|
||||
<div style={{ marginLeft: '24px' }}>
|
||||
<CodeBlock
|
||||
code={(() => {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(s.output), null, 2);
|
||||
} catch {
|
||||
return s.output;
|
||||
}
|
||||
})()}
|
||||
language="json"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -183,7 +407,11 @@ export function RunDetailPage() {
|
||||
width: 70,
|
||||
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
|
||||
},
|
||||
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
|
||||
{
|
||||
key: 'message',
|
||||
header: t('runs.log_message'),
|
||||
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
|
||||
},
|
||||
{
|
||||
key: 'time',
|
||||
header: t('runs.log_time'),
|
||||
@@ -197,9 +425,13 @@ export function RunDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{
|
||||
@@ -207,10 +439,30 @@ export function RunDetailPage() {
|
||||
icon: <Activity size={14} />,
|
||||
onClick: () => navigate(`/scenarios/${id}/runs`),
|
||||
},
|
||||
{ label: `#${runId}` },
|
||||
{ label: `${runId}` },
|
||||
]}
|
||||
/>
|
||||
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} error={!!error} onClick={manualRefresh} />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
{run && (
|
||||
<span title={run.environmentId ? undefined : t('runs.repeat_no_environment')}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={handleRepeatRun}
|
||||
disabled={!run.environmentId || repeating}
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
{t('runs.action_repeat')}
|
||||
</Button>
|
||||
</span>
|
||||
)}
|
||||
<AutoRefreshIndicator
|
||||
active={polling}
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={manualRefresh}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
|
||||
@@ -220,19 +472,62 @@ export function RunDetailPage() {
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
|
||||
{
|
||||
term: t('runs.field_status'),
|
||||
detail: (
|
||||
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
|
||||
{RUN_STATUS_LABEL[run.status]}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
|
||||
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
|
||||
]}
|
||||
items={(() => {
|
||||
const items = [
|
||||
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
|
||||
{
|
||||
term: t('runs.field_status'),
|
||||
detail: (
|
||||
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
|
||||
{RUN_STATUS_LABEL[run.status]}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
|
||||
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
|
||||
];
|
||||
if (run.scenarioVersion != null) {
|
||||
items.push({
|
||||
term: t('runs.field_scenario_version'),
|
||||
detail: <span>v{run.scenarioVersion}</span>,
|
||||
});
|
||||
}
|
||||
if (run.traceMode) {
|
||||
items.push({
|
||||
term: t('runs.field_trace'),
|
||||
detail: (
|
||||
<span>{t(`scenarios.trace_mode_${run.traceMode.replace(/-/g, '_')}`)}</span>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (run.environment) {
|
||||
items.push({
|
||||
term: 'Environment',
|
||||
detail: (
|
||||
<Link
|
||||
to={`/environments/${run.environment.id}`}
|
||||
style={{ color: 'var(--color-link)' }}
|
||||
>
|
||||
{run.environment.name}
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (run.session) {
|
||||
items.push({
|
||||
term: 'Session',
|
||||
detail: (
|
||||
<Link
|
||||
to={`/sessions/${run.session.id}`}
|
||||
style={{ color: 'var(--color-link)' }}
|
||||
>
|
||||
{run.session.sessionName}
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
})()}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
@@ -253,11 +548,17 @@ export function RunDetailPage() {
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => setExportLogsOpen(true)}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_download_logs')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={logColumns}
|
||||
@@ -276,8 +577,103 @@ export function RunDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(artifactsTotal > 0 || artifactsLoading) && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.artifactsTitle')}</h2>
|
||||
<Table<FileMetadata>
|
||||
loading={artifactsLoading}
|
||||
data={artifacts}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{ key: 'name', header: t('files.name'), render: (f) => f.name },
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(runFiles.contentUrl(id!, runId!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
header: '',
|
||||
render: (f) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={t('files.delete')}
|
||||
aria-label={t('files.delete')}
|
||||
onClick={() => setPendingDeleteFile(f)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ExportLogsModal
|
||||
open={exportLogsOpen}
|
||||
format={exportLogsFormat}
|
||||
onFormatChange={setExportLogsFormat}
|
||||
onClose={() => setExportLogsOpen(false)}
|
||||
onExport={handleExportLogs}
|
||||
isExporting={exportingLogs}
|
||||
/>
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={pendingDeleteFile != null}
|
||||
title={t('files.deleteTitle')}
|
||||
message={t('files.confirmDelete', { name: pendingDeleteFile?.name ?? '' })}
|
||||
onClose={() => setPendingDeleteFile(null)}
|
||||
onConfirm={handleDeleteFile}
|
||||
isDeleting={deletingFile}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Play, ClipboardList, Activity } from 'lucide-react';
|
||||
import { environments, scenarios, runs } from '../../api';
|
||||
import type {
|
||||
Environment,
|
||||
Scenario,
|
||||
ScenarioRun,
|
||||
ScenarioRunStep,
|
||||
ScenarioRunStatus,
|
||||
} from '../../api';
|
||||
import type { Environment, Scenario, ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
@@ -22,6 +17,7 @@ import {
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -40,7 +36,7 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
|
||||
type RunRow = ScenarioRun;
|
||||
|
||||
export function RunsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -50,6 +46,7 @@ export function RunsPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [items, setItems] = useState<RunRow[]>([]);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
@@ -60,30 +57,73 @@ export function RunsPage() {
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const hasDataRef = useRef(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([scenarios.get(id!), runs.list(id!)])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
// Keep refs so the poll interval always reads current values
|
||||
const sortByRef = useRef(sortBy);
|
||||
const sortDirRef = useRef(sortDir);
|
||||
const pageRef = useRef(page);
|
||||
const pageSizeRef = useRef(pageSize);
|
||||
sortByRef.current = sortBy;
|
||||
sortDirRef.current = sortDir;
|
||||
pageRef.current = page;
|
||||
pageSizeRef.current = pageSize;
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.get(id!),
|
||||
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
load('createdAt', 'desc', 1, 20);
|
||||
pollRef.current = setInterval(
|
||||
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
|
||||
10_000,
|
||||
);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
@@ -102,7 +142,7 @@ export function RunsPage() {
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(id!, selectedEnvId);
|
||||
toast.success('Scenario run started');
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
setRunModalOpen(false);
|
||||
} catch (err) {
|
||||
@@ -118,18 +158,25 @@ export function RunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -139,7 +186,11 @@ export function RunsPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
@@ -148,7 +199,12 @@ export function RunsPage() {
|
||||
]}
|
||||
/>
|
||||
<div className={styles.toolbarActions}>
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
|
||||
<AutoRefreshIndicator
|
||||
active
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={() => load(sortBy, sortDir, page, pageSize)}
|
||||
/>
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Play size={14} />
|
||||
{t('runs.action_run')}
|
||||
@@ -162,25 +218,32 @@ export function RunsPage() {
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={runModalOpen}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunModalOpen(false)}
|
||||
footer={(
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
|
||||
Cancel
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('runs.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
|
||||
@@ -1,36 +1,50 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateScenarioPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const scenario = await scenarios.create(name.trim());
|
||||
toast.success('Scenario created');
|
||||
const scenario = await scenarios.create(
|
||||
name.trim(),
|
||||
description.trim() || undefined,
|
||||
environmentId || undefined,
|
||||
);
|
||||
toast.success(t('scenarios.created'));
|
||||
navigate(`/scenarios/${scenario.id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -42,7 +56,11 @@ export function CreateScenarioPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{ label: t('scenarios.create_title') },
|
||||
]}
|
||||
/>
|
||||
@@ -63,6 +81,24 @@ export function CreateScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
@@ -14,10 +15,11 @@ export function CreateStepPage() {
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
usePageTitle(t('steps.create_title'));
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -27,20 +29,19 @@ export function CreateStepPage() {
|
||||
.catch(() => null);
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await steps.create(id!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
|
||||
});
|
||||
toast.success('Step created');
|
||||
toast.success(t('steps.created'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -52,7 +53,11 @@ export function CreateStepPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
@@ -75,6 +80,15 @@ export function CreateStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Scenario, Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditScenarioPage() {
|
||||
@@ -15,10 +16,16 @@ export function EditScenarioPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
scenario ? `${t('scenarios.edit_title')} — ${scenario.name}` : t('scenarios.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState<string>('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -27,26 +34,35 @@ export function EditScenarioPage() {
|
||||
.then((data) => {
|
||||
setScenario(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setEnvironmentId(data.environmentId ?? '');
|
||||
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await scenarios.update(id!, { name: name.trim() });
|
||||
toast.success('Scenario updated');
|
||||
await scenarios.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
environmentId: environmentId || null,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('scenarios.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -58,7 +74,11 @@ export function EditScenarioPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
@@ -86,6 +106,33 @@ export function EditScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.form_timeout')}
|
||||
placeholder={t('scenarios.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('scenarios.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
@@ -15,11 +16,14 @@ export function EditStepPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [step, setStep] = useState<ScenarioStep | null>(null);
|
||||
usePageTitle(
|
||||
step ? t('steps.edit_title', { order: step.order }) : t('steps.edit_title', { order: '' }),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !stepId) return;
|
||||
@@ -29,25 +33,24 @@ export function EditStepPage() {
|
||||
setStep(st);
|
||||
setTitle(st.title ?? '');
|
||||
setExecCode(st.execCode ?? '');
|
||||
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id, stepId]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await steps.update(id!, stepId!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success('Step updated');
|
||||
toast.success(t('steps.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -59,12 +62,16 @@ export function EditStepPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{ label: t('steps.edit_title', { order: step ? step.order + 1 : stepId }) },
|
||||
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -85,6 +92,15 @@ export function EditStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,10 +1,38 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, useCallback, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play, Pencil, Plus, History, Trash2, Upload, GripVertical, ClipboardList } from 'lucide-react';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { environments, scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
|
||||
import type { Scenario, ScenarioStep, ScenarioCredential, Credential, Environment } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import {
|
||||
Play,
|
||||
Pencil,
|
||||
Plus,
|
||||
History,
|
||||
Download,
|
||||
Trash2,
|
||||
Upload,
|
||||
GripVertical,
|
||||
ClipboardList,
|
||||
FileArchive,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
environments,
|
||||
scenarios,
|
||||
steps,
|
||||
scenarioCredentials,
|
||||
scenarioFiles,
|
||||
credentials as credentialsApi,
|
||||
} from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioStep,
|
||||
ScenarioCredential,
|
||||
Credential,
|
||||
Environment,
|
||||
FileMetadata,
|
||||
ScenarioVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from '../../api';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
@@ -16,9 +44,12 @@ import {
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import { ExportScenarioModal, RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function ScenarioDetailPage() {
|
||||
@@ -28,7 +59,7 @@ export function ScenarioDetailPage() {
|
||||
const toast = useToast();
|
||||
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(scenario?.name ?? null);
|
||||
|
||||
// Credentials state
|
||||
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
|
||||
@@ -44,6 +75,14 @@ export function ScenarioDetailPage() {
|
||||
const [reorderingSteps, setReorderingSteps] = useState(false);
|
||||
const [runModalOpen, setRunModalOpen] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
const [pendingDelete, setPendingDelete] = useState<
|
||||
@@ -51,6 +90,33 @@ export function ScenarioDetailPage() {
|
||||
>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
// Export modal state
|
||||
const [exportModalOpen, setExportModalOpen] = useState(false);
|
||||
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
||||
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
// Files state
|
||||
const [files, setFiles] = useState<FileMetadata[]>([]);
|
||||
const [filesLoading, setFilesLoading] = useState(false);
|
||||
const [uploadOpen, setUploadOpen] = useState(false);
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
|
||||
|
||||
const loadFiles = useCallback(async () => {
|
||||
if (!id) return;
|
||||
setFilesLoading(true);
|
||||
try {
|
||||
const result = await scenarioFiles.list(id);
|
||||
setFiles(result.items);
|
||||
} finally {
|
||||
setFilesLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
void scenarios
|
||||
@@ -59,8 +125,12 @@ export function ScenarioDetailPage() {
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
void loadFiles();
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
credentialsApi
|
||||
.list(1, 200)
|
||||
.then((r) => setAllCredentials(r.data))
|
||||
@@ -69,16 +139,37 @@ export function ScenarioDetailPage() {
|
||||
.list(1, 200)
|
||||
.then((r) => {
|
||||
setEnvs(r.data);
|
||||
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
}, [id, loadFiles]);
|
||||
|
||||
const openRunModal = () => {
|
||||
// Preselect the scenario's default environment (or the first one) when the
|
||||
// modal opens: by then both are loaded, and it follows default env edits
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : (envs[0]?.id ?? ''));
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
if (id) {
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
setRunModalOpen(true);
|
||||
};
|
||||
|
||||
const reloadScenario = async () => {
|
||||
if (!id) return;
|
||||
const s = await scenarios.get(id);
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
@@ -89,10 +180,17 @@ export function ScenarioDetailPage() {
|
||||
}
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(scenario.id, selectedEnvId);
|
||||
toast.success('Scenario run started');
|
||||
const run = await scenarios.run(
|
||||
scenario.id,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
setRunModalOpen(false);
|
||||
setSaveSessionFlag(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
@@ -106,19 +204,70 @@ export function ScenarioDetailPage() {
|
||||
navigate('/scenarios');
|
||||
};
|
||||
|
||||
const handleOpenExportModal = () => {
|
||||
if (!scenario) return;
|
||||
// Initialise all credential checkboxes to checked
|
||||
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
||||
setIncludeEnvironment(true);
|
||||
setExportModalOpen(true);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!scenario) return;
|
||||
const data = await scenarios.exportScenario(scenario.id);
|
||||
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const credIds = Array.from(includedCredentialIds);
|
||||
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
||||
includeEnvironment,
|
||||
credentialIds: credIds,
|
||||
});
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportModalOpen(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
async function handleUpload(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (!id || !uploadFile) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
await scenarioFiles.upload(
|
||||
id,
|
||||
uploadFile,
|
||||
uploadExpiresAt ? new Date(uploadExpiresAt) : undefined,
|
||||
);
|
||||
setUploadOpen(false);
|
||||
setUploadFile(null);
|
||||
setUploadExpiresAt('');
|
||||
await loadFiles();
|
||||
toast.success(t('files.uploadSuccess'));
|
||||
} catch {
|
||||
// error toast already emitted by API client
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteStep = async (stepId: string) => {
|
||||
await steps.remove(id!, stepId);
|
||||
await reloadScenario();
|
||||
@@ -138,7 +287,7 @@ export function ScenarioDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddCredential = async (e: React.FormEvent) => {
|
||||
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!addCredId) {
|
||||
@@ -231,7 +380,7 @@ export function ScenarioDetailPage() {
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order + 1, width: 60 },
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
@@ -319,13 +468,17 @@ export function ScenarioDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{ label: scenario?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{scenario && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Button size="sm" onClick={openRunModal}>
|
||||
<Play size={14} />
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
@@ -333,15 +486,29 @@ export function ScenarioDetailPage() {
|
||||
<History size={14} />
|
||||
{t('scenarios.action_runs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
|
||||
}
|
||||
>
|
||||
<FileArchive size={14} />
|
||||
{t('scenarios.action_export_e2e')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
|
||||
<Pencil size={14} />
|
||||
{t('scenarios.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={() => setPendingDelete({ type: 'scenario' })}>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => setPendingDelete({ type: 'scenario' })}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
{t('scenarios.action_delete')}
|
||||
</Button>
|
||||
@@ -359,6 +526,25 @@ export function ScenarioDetailPage() {
|
||||
items={[
|
||||
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
|
||||
{ term: t('scenarios.field_name'), detail: scenario.name },
|
||||
{ term: t('scenarios.field_version'), detail: `v${scenario.version}` },
|
||||
...(scenario.environment
|
||||
? [
|
||||
{
|
||||
term: t('scenarios.field_environment'),
|
||||
detail: (
|
||||
<a
|
||||
href={`/environments/${scenario.environment.id}`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
navigate(`/environments/${scenario.environment!.id}`);
|
||||
}}
|
||||
>
|
||||
{scenario.environment.name}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
term: t('scenarios.field_created'),
|
||||
detail: <Timestamp value={scenario.createdAt} />,
|
||||
@@ -371,6 +557,17 @@ export function ScenarioDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{scenario.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={scenario.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenario.steps.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
@@ -498,6 +695,139 @@ export function ScenarioDetailPage() {
|
||||
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Used snippets section ───────────────────────────────────────── */}
|
||||
{usedSnippets.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.used_snippets_heading')}</h2>
|
||||
</div>
|
||||
<Table<UsedSnippet>
|
||||
data={usedSnippets}
|
||||
rowKey={(s) => `${s.id}@${s.pinnedVersion ?? 'latest'}`}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
onRowClick={(s) => navigate(`/snippets/${s.id}`)}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'alias',
|
||||
header: t('snippets.field_alias'),
|
||||
render: (s) => s.alias,
|
||||
},
|
||||
{
|
||||
key: 'title',
|
||||
header: t('snippets.field_title'),
|
||||
render: (s) => s.title,
|
||||
},
|
||||
{
|
||||
key: 'version',
|
||||
header: t('snippets.field_version'),
|
||||
render: (s) =>
|
||||
s.pinnedVersion != null
|
||||
? t('scenarios.used_snippet_pinned', { version: s.pinnedVersion })
|
||||
: t('scenarios.used_snippet_latest', { version: s.version }),
|
||||
},
|
||||
] satisfies TableColumn<UsedSnippet>[]
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Files section ───────────────────────────────────────────────── */}
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.title')}</h2>
|
||||
<Button size="sm" onClick={() => setUploadOpen(true)}>
|
||||
<Upload size={14} /> {t('files.upload')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table<FileMetadata>
|
||||
loading={filesLoading}
|
||||
data={files}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'name',
|
||||
header: t('files.name'),
|
||||
render: (f) => f.name,
|
||||
},
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarioFiles.contentUrl(id!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Upload modal ─────────────────────────────────────────────── */}
|
||||
<Modal
|
||||
open={uploadOpen}
|
||||
title={t('files.uploadTitle')}
|
||||
onClose={() => setUploadOpen(false)}
|
||||
>
|
||||
<form onSubmit={handleUpload}>
|
||||
<input
|
||||
type="file"
|
||||
required
|
||||
onChange={(e) => setUploadFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
<Input
|
||||
label={t('files.expiresAtLabel')}
|
||||
type="datetime-local"
|
||||
value={uploadExpiresAt}
|
||||
onChange={(e) => setUploadExpiresAt(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" loading={uploading} disabled={!uploadFile}>
|
||||
{t('files.upload')}
|
||||
</Button>
|
||||
</form>
|
||||
</Modal>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -511,48 +841,62 @@ export function ScenarioDetailPage() {
|
||||
: t('scenarios.action_delete')
|
||||
}
|
||||
onClose={() => !deleting && setPendingDelete(null)}
|
||||
footer={(
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
|
||||
Cancel
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
|
||||
Confirm
|
||||
{t('common.button_confirm')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
>
|
||||
{pendingDelete?.type === 'step' && 'Are you sure you want to delete this step?'}
|
||||
{pendingDelete?.type === 'credential' && 'Are you sure you want to remove this credential from scenario?'}
|
||||
{pendingDelete?.type === 'scenario' && 'Are you sure you want to delete this scenario?'}
|
||||
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
|
||||
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
|
||||
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
<RunScenarioModal
|
||||
open={runModalOpen}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunModalOpen(false)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => setSelectedEnvId(e.target.value)}
|
||||
options={envs.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunModalOpen(false)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
|
||||
<ExportScenarioModal
|
||||
open={exportModalOpen}
|
||||
scenario={scenario}
|
||||
scenarioCredentials={scenarioCreds}
|
||||
environment={
|
||||
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
|
||||
}
|
||||
includeEnvironment={includeEnvironment}
|
||||
onIncludeEnvironmentChange={setIncludeEnvironment}
|
||||
includedCredentialIds={includedCredentialIds}
|
||||
onCredentialToggle={(credId, checked) => {
|
||||
setIncludedCredentialIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (checked) next.add(credId);
|
||||
else next.delete(credId);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
onClose={() => setExportModalOpen(false)}
|
||||
onExport={handleExport}
|
||||
isExporting={isExporting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,68 +1,145 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { environments, scenarios } from '../../api';
|
||||
import type { Environment, Scenario } from '../../api';
|
||||
import type { Environment, Scenario, ScenarioVersion, TraceMode } from '../../api';
|
||||
import { RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import type { ScenarioRunStatus } from '../../api';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const LAST_RUN_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
pending: 'neutral',
|
||||
in_progress: 'info',
|
||||
pass: 'success',
|
||||
fail: 'error',
|
||||
};
|
||||
|
||||
const LAST_RUN_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
pending: 'Pending',
|
||||
in_progress: 'Running',
|
||||
pass: 'Pass',
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
export function ScenariosPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const [items, setItems] = useState<Scenario[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
Promise.all([scenarios.list(), environments.list(1, 200)])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes.data);
|
||||
setEnvs(envRes.data);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
const [sortBy, setSortBy] = useState('updatedAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
environments.list(1, 200),
|
||||
])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setTotal(scenarioRes?.total ?? 0);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error((err as Error).message);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
load('updatedAt', 'desc', 1, 10);
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
const openRunModal = (id: string) => {
|
||||
setRunScenarioId(id);
|
||||
if (!selectedEnvId && envs.length > 0) {
|
||||
setSelectedEnvId(envs[0].id);
|
||||
}
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
const scenario = items.find((s) => s.id === id);
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!runScenarioId || !selectedEnvId) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(runScenarioId, selectedEnvId);
|
||||
toast.success('Scenario run started');
|
||||
const run = await scenarios.run(
|
||||
runScenarioId,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
|
||||
setRunScenarioId(null);
|
||||
setSaveSessionFlag(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
@@ -75,35 +152,47 @@ export function ScenariosPage() {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await scenarios.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await scenarios.importScenario(payload);
|
||||
navigate(`/scenarios/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
}
|
||||
};
|
||||
const handleImport = useImportFile('scenario');
|
||||
|
||||
const columns: TableColumn<Scenario>[] = [
|
||||
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
|
||||
{
|
||||
key: 'updated',
|
||||
key: 'version',
|
||||
header: t('scenarios.col_version'),
|
||||
width: 80,
|
||||
render: (s) => `v${s.version}`,
|
||||
},
|
||||
{
|
||||
key: 'lastRunStatus',
|
||||
header: t('scenarios.col_last_run'),
|
||||
width: 160,
|
||||
render: (s) =>
|
||||
s.lastRunStatus ? (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ display: 'inline-flex', minWidth: 62 }}>
|
||||
<Badge variant={LAST_RUN_VARIANT[s.lastRunStatus]}>
|
||||
{LAST_RUN_LABEL[s.lastRunStatus]}
|
||||
</Badge>
|
||||
</span>
|
||||
{s.lastRunAt && <Timestamp value={s.lastRunAt} />}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ color: 'var(--color-text-muted)', fontSize: '0.8em' }}>—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'updatedAt',
|
||||
header: t('scenarios.col_updated'),
|
||||
width: 140,
|
||||
sortable: true,
|
||||
render: (s) => <Timestamp value={s.updatedAt} />,
|
||||
},
|
||||
{
|
||||
@@ -167,55 +256,53 @@ export function ScenariosPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('scenarios.empty')}
|
||||
pageSize={10}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={deleteId != null}
|
||||
title={t('scenarios.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={(
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
Cancel
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('scenarios.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
>
|
||||
Are you sure you want to delete this scenario?
|
||||
{t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
<RunScenarioModal
|
||||
open={runScenarioId != null}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunScenarioId(null)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => setSelectedEnvId(e.target.value)}
|
||||
options={envs.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunScenarioId(null)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SessionDetailPage() {
|
||||
@@ -22,7 +15,7 @@ export function SessionDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(session?.sessionName ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
@@ -31,7 +24,6 @@ export function SessionDetailPage() {
|
||||
sessions
|
||||
.get(id)
|
||||
.then(setSession)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
@@ -52,7 +44,11 @@ export function SessionDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('sessions.title'), icon: <Monitor size={14} />, onClick: () => navigate('/sessions') },
|
||||
{
|
||||
label: t('sessions.title'),
|
||||
icon: <Monitor size={14} />,
|
||||
onClick: () => navigate('/sessions'),
|
||||
},
|
||||
{ label: session?.sessionName ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
@@ -102,23 +98,14 @@ export function SessionDetailPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('sessions.action_delete')}
|
||||
onClose={() => !deleting && setConfirmDeleteOpen(false)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('sessions.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this session?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_session')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
@@ -8,42 +9,56 @@ import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SessionsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('sessions.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Session[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [sortBy, setSortBy] = useState('id');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
sessions
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
||||
.then((res) => {
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
}, [load, sortBy, sortDir, page, pageSize]);
|
||||
|
||||
const handleSort = (col: string, dir: SortDirection) => {
|
||||
setSortBy(col);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
@@ -52,17 +67,24 @@ export function SessionsPage() {
|
||||
|
||||
const columns: TableColumn<Session>[] = [
|
||||
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
|
||||
{
|
||||
key: 'sessionName',
|
||||
header: t('sessions.col_name'),
|
||||
sortable: true,
|
||||
render: (s) => s.sessionName,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: t('sessions.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'lastUsed',
|
||||
key: 'lastUsedAt',
|
||||
header: t('sessions.col_lastUsed'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
@@ -97,28 +119,28 @@ export function SessionsPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('sessions.empty')}
|
||||
pageSize={10}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(s) => {
|
||||
setPageSize(s);
|
||||
setPage(1);
|
||||
}}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('sessions.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('sessions.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
Are you sure you want to delete this session?
|
||||
</Modal>
|
||||
message={t('common.confirm_delete_session')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,6 +9,7 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('snippets.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
@@ -19,9 +21,8 @@ export function CreateSnippetPage() {
|
||||
const [titleError, setTitleError] = useState('');
|
||||
const [codeError, setCodeError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!alias.trim()) {
|
||||
@@ -38,7 +39,6 @@ export function CreateSnippetPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const snippet = await snippets.create({
|
||||
alias: alias.trim(),
|
||||
@@ -46,11 +46,10 @@ export function CreateSnippetPage() {
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
toast.success('Snippet created');
|
||||
toast.success(t('snippets.created'));
|
||||
navigate(`/snippets/${snippet.id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -62,7 +61,11 @@ export function CreateSnippetPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{ label: t('snippets.create_title') },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
@@ -15,6 +16,9 @@ export function EditSnippetPage() {
|
||||
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [alias, setAlias] = useState('');
|
||||
usePageTitle(
|
||||
snippet ? `${t('snippets.edit_title')} — ${snippet.title}` : t('snippets.edit_title'),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
@@ -23,7 +27,6 @@ export function EditSnippetPage() {
|
||||
const [codeError, setCodeError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -36,11 +39,10 @@ export function EditSnippetPage() {
|
||||
setDescription(s.description ?? '');
|
||||
setCode(s.code);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!alias.trim()) {
|
||||
@@ -57,7 +59,6 @@ export function EditSnippetPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await snippets.update(id!, {
|
||||
alias: alias.trim(),
|
||||
@@ -65,11 +66,10 @@ export function EditSnippetPage() {
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
toast.success('Snippet updated');
|
||||
toast.success(t('snippets.updated'));
|
||||
navigate(`/snippets/${id}`);
|
||||
} catch (err) {
|
||||
const message = (err as Error).message;
|
||||
setError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -81,7 +81,11 @@ export function EditSnippetPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{
|
||||
label: snippet?.title ?? `#${id}`,
|
||||
onClick: () => navigate(`/snippets/${id}`),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, Braces } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
@@ -24,7 +25,7 @@ export function SnippetDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(snippet?.title ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
@@ -33,7 +34,6 @@ export function SnippetDetailPage() {
|
||||
snippets
|
||||
.get(id)
|
||||
.then(setSnippet)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
@@ -66,7 +66,11 @@ export function SnippetDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{ label: snippet?.title ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
@@ -103,6 +107,7 @@ export function SnippetDetailPage() {
|
||||
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
|
||||
{ term: t('snippets.field_alias'), detail: snippet.alias },
|
||||
{ term: t('snippets.field_title'), detail: snippet.title },
|
||||
{ term: t('snippets.field_version'), detail: `v${snippet.version}` },
|
||||
{
|
||||
term: t('snippets.field_created'),
|
||||
detail: <Timestamp value={snippet.createdAt} />,
|
||||
@@ -141,18 +146,22 @@ export function SnippetDetailPage() {
|
||||
open={confirmDeleteOpen}
|
||||
title={t('snippets.action_delete')}
|
||||
onClose={() => !deleting && setConfirmDeleteOpen(false)}
|
||||
footer={(
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
|
||||
Cancel
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setConfirmDeleteOpen(false)}
|
||||
disabled={deleting}
|
||||
>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('snippets.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
>
|
||||
Are you sure you want to delete this snippet?
|
||||
{t('common.confirm_delete_snippet')}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import {
|
||||
@@ -17,7 +18,10 @@ import {
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function firstParagraphBlocks(markdown: string, limit = 2): { preview: string; truncated: boolean } {
|
||||
function firstParagraphBlocks(
|
||||
markdown: string,
|
||||
limit = 2,
|
||||
): { preview: string; truncated: boolean } {
|
||||
const blocks = markdown
|
||||
.split(/\n\s*\n/g)
|
||||
.map((block) => block.trim())
|
||||
@@ -80,17 +84,19 @@ function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: s
|
||||
>
|
||||
<p className={styles.muted}>
|
||||
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
|
||||
{' · '}v{snippet.version}
|
||||
</p>
|
||||
{snippet.description && (() => {
|
||||
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
|
||||
if (!preview) return null;
|
||||
return (
|
||||
<>
|
||||
<MarkdownContent content={preview} />
|
||||
{truncated && <p className={styles.muted}>...</p>}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
{snippet.description &&
|
||||
(() => {
|
||||
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
|
||||
if (!preview) return null;
|
||||
return (
|
||||
<>
|
||||
<MarkdownContent content={preview} />
|
||||
{truncated && <p className={styles.muted}>...</p>}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -110,10 +116,9 @@ function AddSnippetCard() {
|
||||
|
||||
export function SnippetsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
usePageTitle(t('snippets.title'));
|
||||
const [items, setItems] = useState<Snippet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -122,7 +127,6 @@ export function SnippetsPage() {
|
||||
snippets
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -146,19 +150,7 @@ export function SnippetsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await snippets.importSnippet(payload);
|
||||
navigate(`/snippets/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
};
|
||||
const handleImport = useImportFile('snippet');
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -195,18 +187,18 @@ export function SnippetsPage() {
|
||||
open={deleteId != null}
|
||||
title={t('snippets.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={(
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
Cancel
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('snippets.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
}
|
||||
>
|
||||
Are you sure you want to delete this snippet?
|
||||
{t('common.confirm_delete_snippet')}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -36,15 +36,18 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
|
||||
<li key={i} className={styles.item}>
|
||||
{isLast ? (
|
||||
<span className={styles.current} aria-current="page">
|
||||
{item.icon}{item.label}
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</span>
|
||||
) : item.href ? (
|
||||
<a href={item.href} className={styles.link} onClick={item.onClick}>
|
||||
{item.icon}{item.label}
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</a>
|
||||
) : (
|
||||
<button type="button" className={styles.link} onClick={item.onClick}>
|
||||
{item.icon}{item.label}
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</button>
|
||||
)}
|
||||
{!isLast && <span className={styles.separator}>{sep}</span>}
|
||||
|
||||
@@ -27,11 +27,40 @@
|
||||
background: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.thContent {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.thSortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
.sortIcon {
|
||||
opacity: 0.4;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sortIconActive {
|
||||
opacity: 1;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .th {
|
||||
background: var(--color-secondary);
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
/* Rounded top corners on first/last header cells */
|
||||
.th:first-child { border-radius: var(--radius-lg) 0 0 0; }
|
||||
.th:last-child { border-radius: 0 var(--radius-lg) 0 0; }
|
||||
|
||||
+109
-24
@@ -1,13 +1,18 @@
|
||||
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
|
||||
import { Pagination } from '../Pagination/Pagination';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
export interface TableColumn<T> {
|
||||
key: string;
|
||||
header: ReactNode;
|
||||
render: (row: T) => ReactNode;
|
||||
width?: string | number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
/** If true, a sort icon is shown and clicking the header triggers onSort */
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface TableProps<T> {
|
||||
@@ -17,7 +22,10 @@ export interface TableProps<T> {
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
/** Enable built-in client-side pagination with this default page size */
|
||||
/**
|
||||
* Client-side pagination: pass a default page size to enable.
|
||||
* For server-side pagination use `total` + `page` + `onPageChange` instead.
|
||||
*/
|
||||
pageSize?: number;
|
||||
/** Offer a page-size selector when pagination is enabled */
|
||||
pageSizeOptions?: number[];
|
||||
@@ -25,6 +33,21 @@ export interface TableProps<T> {
|
||||
onRowClick?: (row: T) => void;
|
||||
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
|
||||
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
|
||||
/** Currently sorted column key (controlled) */
|
||||
sortBy?: string;
|
||||
/** Current sort direction (controlled) */
|
||||
sortDir?: SortDirection;
|
||||
/** Called when the user clicks a sortable column header */
|
||||
onSort?: (key: string, dir: SortDirection) => void;
|
||||
// ── Server-side pagination (controlled) ──────────────────────────────────
|
||||
/** Total record count from server. Presence switches to server-side pagination mode. */
|
||||
total?: number;
|
||||
/** Controlled current page (1-based). Required when `total` is set. */
|
||||
page?: number;
|
||||
/** Called when the user navigates to a new page. Required when `total` is set. */
|
||||
onPageChange?: (page: number) => void;
|
||||
/** Called when the user changes page size. Optional for server-side pagination. */
|
||||
onPageSizeChange?: (size: number) => void;
|
||||
}
|
||||
|
||||
export function Table<T>({
|
||||
@@ -38,34 +61,74 @@ export function Table<T>({
|
||||
pageSizeOptions,
|
||||
onRowClick,
|
||||
getRowProps,
|
||||
sortBy,
|
||||
sortDir,
|
||||
onSort,
|
||||
total,
|
||||
page: controlledPage,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
}: TableProps<T>) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
|
||||
const [internalPage, setInternalPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
|
||||
|
||||
const paginated = defaultPageSize !== undefined && !loading;
|
||||
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
|
||||
const serverMode = total !== undefined;
|
||||
|
||||
// Reset to page 1 when data changes and current page would be empty
|
||||
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safePage = Math.min(page, Math.max(1, lastPage));
|
||||
const handleSortClick = (key: string) => {
|
||||
if (!onSort) return;
|
||||
const nextDir: SortDirection = sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
|
||||
onSort(key, nextDir);
|
||||
};
|
||||
|
||||
// Client-side pagination
|
||||
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
|
||||
const visibleData = clientPaginated
|
||||
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
|
||||
: data;
|
||||
|
||||
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
|
||||
|
||||
// Server-side pagination display values
|
||||
const serverPage = controlledPage ?? 1;
|
||||
const serverTotal = total ?? 0;
|
||||
|
||||
return (
|
||||
<div className={`${styles.wrapper} ${className ?? ''}`}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={styles.th}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
>
|
||||
{col.header}
|
||||
</th>
|
||||
))}
|
||||
{columns.map((col) => {
|
||||
const isSorted = col.sortable && sortBy === col.key;
|
||||
const SortIcon = isSorted ? (sortDir === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown;
|
||||
|
||||
return (
|
||||
<th
|
||||
key={col.key}
|
||||
className={[styles.th, col.sortable ? styles.thSortable : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
|
||||
>
|
||||
<span className={styles.thContent}>
|
||||
{col.header}
|
||||
{col.sortable && (
|
||||
<SortIcon
|
||||
size={12}
|
||||
className={[styles.sortIcon, isSorted ? styles.sortIconActive : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -122,17 +185,39 @@ export function Table<T>({
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{paginated && data.length > 0 && (
|
||||
{serverMode && serverTotal > 0 && onPageChange && (
|
||||
<Pagination
|
||||
page={safePage}
|
||||
page={serverPage}
|
||||
pageSize={pageSize}
|
||||
total={serverTotal}
|
||||
onPageChange={onPageChange}
|
||||
onPageSizeChange={
|
||||
onPageSizeChange
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageSizeChange(size);
|
||||
}
|
||||
: pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageChange(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
/>
|
||||
)}
|
||||
{clientPaginated && data.length > 0 && (
|
||||
<Pagination
|
||||
page={safeInternalPage}
|
||||
pageSize={pageSize}
|
||||
total={data.length}
|
||||
onPageChange={setPage}
|
||||
onPageChange={setInternalPage}
|
||||
onPageSizeChange={
|
||||
pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
setInternalPage(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
|
||||
import styles from './ToastProvider.module.css';
|
||||
import { subscribeApiErrorToasts } from '../../lib/toast-events';
|
||||
|
||||
type ToastVariant = 'success' | 'error' | 'info';
|
||||
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
|
||||
|
||||
interface ToastItem {
|
||||
id: number;
|
||||
@@ -12,15 +11,6 @@ interface ToastItem {
|
||||
closing: boolean;
|
||||
}
|
||||
|
||||
interface ToastApi {
|
||||
show: (message: string, variant?: ToastVariant) => void;
|
||||
success: (message: string) => void;
|
||||
error: (message: string) => void;
|
||||
info: (message: string) => void;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastApi | null>(null);
|
||||
|
||||
const ICONS: Record<ToastVariant, React.ReactNode> = {
|
||||
success: <CheckCircle2 size={16} />,
|
||||
error: <AlertCircle size={16} />,
|
||||
@@ -41,33 +31,38 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
|
||||
setItems((prev) => prev.filter((item) => item.id !== id));
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback((id: number) => {
|
||||
setItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === id ? { ...item, closing: true } : item,
|
||||
),
|
||||
);
|
||||
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
|
||||
}, [remove]);
|
||||
const dismiss = useCallback(
|
||||
(id: number) => {
|
||||
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
|
||||
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
|
||||
},
|
||||
[remove],
|
||||
);
|
||||
|
||||
const show = useCallback((message: string, variant: ToastVariant = 'info') => {
|
||||
const now = Date.now();
|
||||
const dedupeKey = `${variant}:${message}`;
|
||||
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
|
||||
if (now - previousTs < 600) return;
|
||||
lastShownAtRef.current.set(dedupeKey, now);
|
||||
const show = useCallback(
|
||||
(message: string, variant: ToastVariant = 'info') => {
|
||||
const now = Date.now();
|
||||
const dedupeKey = `${variant}:${message}`;
|
||||
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
|
||||
if (now - previousTs < 600) return;
|
||||
lastShownAtRef.current.set(dedupeKey, now);
|
||||
|
||||
const id = Date.now() + Math.floor(Math.random() * 1000);
|
||||
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
|
||||
window.setTimeout(() => dismiss(id), durationMs);
|
||||
}, [dismiss, durationMs]);
|
||||
const id = Date.now() + Math.floor(Math.random() * 1000);
|
||||
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
|
||||
window.setTimeout(() => dismiss(id), durationMs);
|
||||
},
|
||||
[dismiss, durationMs],
|
||||
);
|
||||
|
||||
const api = useMemo<ToastApi>(() => ({
|
||||
show,
|
||||
success: (message: string) => show(message, 'success'),
|
||||
error: (message: string) => show(message, 'error'),
|
||||
info: (message: string) => show(message, 'info'),
|
||||
}), [show]);
|
||||
const api = useMemo<ToastApi>(
|
||||
() => ({
|
||||
show,
|
||||
success: (message: string) => show(message, 'success'),
|
||||
error: (message: string) => show(message, 'error'),
|
||||
info: (message: string) => show(message, 'info'),
|
||||
}),
|
||||
[show],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeApiErrorToasts((message) => api.error(message));
|
||||
@@ -86,7 +81,9 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
|
||||
role="status"
|
||||
>
|
||||
<div className={styles.content}>
|
||||
<span className={styles.icon} aria-hidden="true">{ICONS[item.variant]}</span>
|
||||
<span className={styles.icon} aria-hidden="true">
|
||||
{ICONS[item.variant]}
|
||||
</span>
|
||||
<p className={styles.message}>{item.message}</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -103,11 +100,3 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast(): ToastApi {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useToast must be used within ToastProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export type ToastVariant = 'success' | 'error' | 'info';
|
||||
|
||||
export interface ToastApi {
|
||||
show: (message: string, variant?: ToastVariant) => void;
|
||||
success: (message: string) => void;
|
||||
error: (message: string) => void;
|
||||
info: (message: string) => void;
|
||||
}
|
||||
|
||||
export const ToastContext = createContext<ToastApi | null>(null);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react';
|
||||
import { ToastContext, type ToastApi } from './toast-context';
|
||||
|
||||
export function useToast(): ToastApi {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useToast must be used within ToastProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -27,8 +27,9 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
|
||||
|
||||
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
|
||||
|
||||
export { ToastProvider, useToast } from './Toast/ToastProvider';
|
||||
export { ToastProvider } from './Toast/ToastProvider';
|
||||
export type { ToastProviderProps } from './Toast/ToastProvider';
|
||||
export { useToast } from './Toast/useToast';
|
||||
|
||||
export { Timestamp } from './Timestamp/Timestamp';
|
||||
export type { TimestampProps } from './Timestamp/Timestamp';
|
||||
@@ -61,7 +62,7 @@ export { Modal } from './Modal/Modal';
|
||||
export type { ModalProps } from './Modal/Modal';
|
||||
|
||||
export { Table } from './Table/Table';
|
||||
export type { TableProps, TableColumn } from './Table/Table';
|
||||
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
|
||||
|
||||
export { UuidBadge } from './UuidBadge/UuidBadge';
|
||||
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
|
||||
@@ -1 +0,0 @@
|
||||
{"root":["./src/App.tsx","./src/declarations.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/index.ts","./src/api/types.ts","./src/hooks/useTheme.ts","./src/i18n/index.ts","./src/lib/hljs.ts","./src/lib/toast-events.ts","./src/pages/credential/CreateCredentialPage.tsx","./src/pages/credential/CredentialDetailPage.tsx","./src/pages/credential/CredentialsPage.tsx","./src/pages/credential/EditCredentialPage.tsx","./src/pages/environment/CreateEnvironmentPage.tsx","./src/pages/environment/EditEnvironmentPage.tsx","./src/pages/environment/EnvironmentDetailPage.tsx","./src/pages/environment/EnvironmentsPage.tsx","./src/pages/run/AllRunsPage.tsx","./src/pages/run/RunDetailPage.tsx","./src/pages/run/RunsPage.tsx","./src/pages/scenario/CreateScenarioPage.tsx","./src/pages/scenario/CreateStepPage.tsx","./src/pages/scenario/EditScenarioPage.tsx","./src/pages/scenario/EditStepPage.tsx","./src/pages/scenario/ScenarioDetailPage.tsx","./src/pages/scenario/ScenariosPage.tsx","./src/pages/session/SessionDetailPage.tsx","./src/pages/session/SessionsPage.tsx","./src/pages/snippet/CreateSnippetPage.tsx","./src/pages/snippet/EditSnippetPage.tsx","./src/pages/snippet/SnippetDetailPage.tsx","./src/pages/snippet/SnippetsPage.tsx","./src/ui/index.ts","./src/ui/AutoRefreshIndicator/AutoRefreshIndicator.tsx","./src/ui/Badge/Badge.tsx","./src/ui/Breadcrumbs/Breadcrumbs.tsx","./src/ui/Button/Button.tsx","./src/ui/Card/Card.tsx","./src/ui/CodeBlock/CodeBlock.tsx","./src/ui/CodeEditor/CodeEditor.tsx","./src/ui/ContextMenu/ContextMenu.tsx","./src/ui/DescriptionList/DescriptionList.tsx","./src/ui/Input/Input.tsx","./src/ui/MarkdownContent/MarkdownContent.tsx","./src/ui/Modal/Modal.tsx","./src/ui/Notification/Notification.tsx","./src/ui/Pagination/Pagination.tsx","./src/ui/Search/Search.tsx","./src/ui/Select/Select.tsx","./src/ui/SidePanel/SidePanel.tsx","./src/ui/Table/Table.tsx","./src/ui/Textarea/Textarea.tsx","./src/ui/ThemeSwitcher/ThemeSwitcher.tsx","./src/ui/Timestamp/Timestamp.tsx","./src/ui/Toast/ToastProvider.tsx","./src/ui/UuidBadge/UuidBadge.tsx"],"version":"5.8.3"}
|
||||
@@ -0,0 +1,17 @@
|
||||
services:
|
||||
liqa:
|
||||
build:
|
||||
context: .
|
||||
ports:
|
||||
# UI, REST API (/api/v1), MCP (/mcp) and Swagger (/docs).
|
||||
# The production CORS origins (server/src/common/cors.ts) use this port;
|
||||
# set CORS_ORIGINS in .env when publishing it elsewhere.
|
||||
- "13000:3000"
|
||||
# Optional overrides (see .env.example); every setting has a default
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
volumes:
|
||||
# persist SQLite database across restarts
|
||||
- ./data:/app/data
|
||||
restart: unless-stopped
|
||||
@@ -1,23 +0,0 @@
|
||||
services:
|
||||
server:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: server/Dockerfile
|
||||
ports:
|
||||
- "13000:3000"
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
# persist SQLite database across restarts
|
||||
- ./data:/app/data
|
||||
# mount key files into the container
|
||||
- ./keys:/app/keys
|
||||
restart: unless-stopped
|
||||
|
||||
client:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: client/Dockerfile
|
||||
ports:
|
||||
- "13001:80"
|
||||
restart: unless-stopped
|
||||
+67
-38
@@ -1,50 +1,79 @@
|
||||
# Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Browser (React SPA - client/) │
|
||||
│ │
|
||||
│ Environments Credentials Snippets │
|
||||
│ Sessions Scenarios Runs │
|
||||
└─────────────────────────────┬────────────────────────┘
|
||||
│ HTTP REST (:13000)
|
||||
│
|
||||
MCP client (AI agent / VS Code Copilot)
|
||||
│ HTTP /mcp (Streamable MCP)
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ NestJS app (server/src/) │
|
||||
│ │
|
||||
│ McpService all MCP tools │
|
||||
│ SessionService session persistence │
|
||||
│ SessionContextService live browser contexts │
|
||||
│ EnvironmentService environment CRUD + import │
|
||||
│ CredentialService credential CRUD + import │
|
||||
│ SnippetService snippet CRUD + import │
|
||||
│ BrowserService ad-hoc open/exec │
|
||||
│ CodeExecutorService sandboxed JS runtime │
|
||||
│ ScenarioService scenarios/steps/runs CRUD │
|
||||
│ ScenarioSchedulerService @Interval(1 s) run worker │
|
||||
└───────────────────────┬──────────────────────────────┘
|
||||
│ better-sqlite3 (TypeORM)
|
||||
▼
|
||||
data/sessions.db
|
||||
Browser (React SPA) MCP client (AI agent, IDE)
|
||||
│ / and /api/v1 │ /mcp (Streamable HTTP)
|
||||
└──────────────┬──────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ liqa container (:13000 → 3000) NestJS app, server/src/ │
|
||||
│ │
|
||||
│ Routes / built client (ServeStaticModule) │
|
||||
│ /api/v1 REST API /docs Swagger UI │
|
||||
│ /mcp MCP tools /health health check │
|
||||
│ │
|
||||
│ McpService MCP tools → services below │
|
||||
│ ScenarioService scenarios, steps, versions, runs │
|
||||
│ ScenarioSchedulerService @Interval(1 s) run worker │
|
||||
│ E2eExportService standalone Playwright test zip │
|
||||
│ SnippetService snippets + versions │
|
||||
│ EnvironmentService environments │
|
||||
│ CredentialService credentials │
|
||||
│ ImportService central YAML import │
|
||||
│ FileStorageService scenario files + run artifacts │
|
||||
│ SessionService saved browser sessions │
|
||||
│ SessionContextService live Playwright contexts │
|
||||
│ SessionSchedulerService @Interval(60 s) session cleanup │
|
||||
│ BrowserService ad-hoc open / exec │
|
||||
│ CodeExecutorService runs step / snippet JS │
|
||||
└───────────────┬─────────────────────────────┬───────────────┘
|
||||
│ TypeORM (better-sqlite3) │ Playwright
|
||||
▼ ▼
|
||||
data/liqa.db, data/files/ chromium-headless-shell
|
||||
```
|
||||
|
||||
- **McpService** registers MCP tools and delegates to session, environment, browser, and scenario services.
|
||||
- **SessionService** persists session records in SQLite. **SessionContextService** manages live Playwright contexts for open sessions.
|
||||
- **EnvironmentService**, **CredentialService**, and **SnippetService** provide CRUD plus import/export upserts.
|
||||
- **BrowserService** handles stateless ad-hoc automation (`/open`, `/exec`) and session-aware browsing.
|
||||
- **CodeExecutorService** validates and executes user JS with `page`, `context`, and helper APIs.
|
||||
- **ScenarioService** manages scenarios, steps, credential aliases, runs, logs, and scenario import/export.
|
||||
- **ScenarioSchedulerService** polls pending runs every second and executes step runs to completion.
|
||||
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
|
||||
|
||||
## Server components (`server/src/`)
|
||||
|
||||
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
|
||||
- **ScenarioService** (`scenario/`) manages scenarios, steps, credential aliases, versions, runs, run logs, scenario/run files, and scenario export/import.
|
||||
- **ScenarioSchedulerService** picks up pending runs every second (up to 10 in parallel) and executes their steps in order in one Playwright browser per run. It handles step and scenario timeouts, failure page dumps (screenshot + HTML), Playwright traces, and saving the browser as a session (`saveSession`).
|
||||
- **E2eExportService** builds a standalone Playwright test project (zip) from a scenario, bundling the snippets, credentials and files it uses.
|
||||
- **SnippetService** (`snippet/`), **EnvironmentService** (`environment/`) and **CredentialService** (`credential/`) provide CRUD plus export/import.
|
||||
- **ImportService** (`import/`) implements `POST /import`: validates a YAML stream of mixed items, then imports them in dependency order (environments, credentials, snippets, scenarios).
|
||||
- **FileStorageService** (`file/`) stores uploaded scenario files and run artifacts under `FILES_DIR`, and deletes expired files on a cron schedule (`FILE_CLEANUP_CRON`).
|
||||
- **SessionService** (`session/`) persists saved sessions (cookies, localStorage); **SessionContextService** keeps their live Playwright contexts; **SessionSchedulerService** closes idle sessions and deletes old closed ones every minute.
|
||||
- **BrowserService** (`browser/`) handles ad-hoc automation (`POST /api/v1/open`, `POST /api/v1/exec`, and the `open_url` / `exec_code` MCP tools), optionally in a saved session.
|
||||
- **CodeExecutorService** (`code-executor/`) checks step and snippet code with acorn, then runs it with the `context` API (page, environment values, credentials, snippets, files, assertions, logs). It is not a security sandbox: step code is trusted.
|
||||
|
||||
Cross-cutting pieces:
|
||||
|
||||
- `config/app.config.ts` - all settings, validated at startup (see `.env.example`).
|
||||
- `database/` - the entity list, TypeORM data source options (shared by the app, the migration runner and the TypeORM CLI), the migration runner and the migrations.
|
||||
- `common/app-package.ts` - app name and version, read from the workspace root `package.json`.
|
||||
- `common/client-static.ts` - serving the built client, with the `index.html` fallback for client-side routes.
|
||||
- `common/body-parsers.ts` - YAML request bodies (`application/yaml`) for the import endpoint.
|
||||
- `interceptors/` - a trace id per request (kept in `AsyncLocalStorage` and added to log lines) and request/response logging; `filters/` - consistent error responses.
|
||||
|
||||
## Data
|
||||
|
||||
SQLite via TypeORM. The schema is managed by migrations (`server/src/database/migrations/`, registered in `migrations/index.ts`); `synchronize` is off. The Docker container applies pending migrations (`node dist/database/migrate`) before starting the server, and the server refuses to start while migrations are pending. See "Database migrations" in [development.md](development.md). The main tables:
|
||||
|
||||
- `scenarios` / `scenario_steps` hold the **latest** version of each scenario; `scenario_versions` holds a snapshot of every version (content + steps).
|
||||
- `snippets` holds the latest version of each snippet; `snippet_versions` holds every version. Step code pins a version with `runSnippet("alias@N")`.
|
||||
- `scenario_runs` record the scenario version, environment, trace mode and status; `scenario_run_steps` keep their own copy of each step's code, so a run always shows what it executed; `scenario_run_logs` hold ordered run logs.
|
||||
- `files` + `scenario_files` / `scenario_run_files` map stored files to scenarios and runs.
|
||||
- `environments`, `credentials`, `scenario_credentials` (alias → credential per scenario), `sessions`.
|
||||
|
||||
See [scenario.md](scenario.md) for versioning, runs and import/export rules.
|
||||
|
||||
## Client (`client/`)
|
||||
|
||||
A React 19 + TypeScript SPA served separately by Vite during development. In Docker Compose the same build artefacts are served statically alongside the API.
|
||||
A React 19 + TypeScript SPA. During development it's served by the Vite dev server; in the Docker image the server serves the built client from the same origin as the API.
|
||||
|
||||
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses HashRouter so the Vite proxy and server-side routes are never ambiguous.
|
||||
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses `BrowserRouter`; the server answers any GET outside `/api`, `/mcp`, `/docs` and `/health` with the client's `index.html`, so client-side routes survive a page refresh.
|
||||
|
||||
The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
|
||||
Pages: scenarios (with steps, versions, credentials, used snippets and files), runs, snippets, credentials, environments, sessions, and the central import page. The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
|
||||
|
||||
See [development.md](development.md) for the full client tech stack and directory layout.
|
||||
+79
-31
@@ -2,7 +2,7 @@
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 20+
|
||||
- Node.js 24+ (required by `engines` in `package.json`; the Docker image uses Node.js 24)
|
||||
- Docker + Docker Compose
|
||||
|
||||
The repository is a **npm workspace monorepo** with two packages:
|
||||
@@ -16,21 +16,29 @@ Install all dependencies from the repo root:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npx playwright install chromium # first time only (server)
|
||||
npx playwright install --only-shell chromium # first time only: headless Chromium for the server
|
||||
```
|
||||
|
||||
Copy `.env.example` to `.env` and fill in the required values before running.
|
||||
No `.env` is needed: every setting below has a default. To override settings, copy `.env.example` to `.env` and uncomment the ones you need. Docker Compose loads `.env` when it exists.
|
||||
|
||||
### Environment variables (server)
|
||||
|
||||
All settings are validated at startup by `server/src/config/app.config.ts`.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
|
||||
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
|
||||
| `PORT` | `3000` | HTTP port |
|
||||
| `KEYS_DIR` | `keys` | Directory for key material used by credential/snippet workflows |
|
||||
| `DB_PATH` | `data/sessions.db` | SQLite database file |
|
||||
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
||||
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
||||
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
|
||||
| `FILE_CLEANUP_CRON` | `0 3 * * *` | When expired files are deleted |
|
||||
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
|
||||
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to Chromium binary. Set automatically in Docker (`/usr/bin/chromium`). |
|
||||
| `PLAYWRIGHT_TRACE_MODE` | `off` | Default Playwright trace mode for runs: `on`, `retain-on-failure` or `off` (see [scenario.md](scenario.md)) |
|
||||
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
||||
|
||||
---
|
||||
|
||||
@@ -61,13 +69,12 @@ The server listens on port **3000** by default.
|
||||
npm -w client run dev
|
||||
```
|
||||
|
||||
The Vite dev server runs on **http://localhost:5173** and proxies these API prefixes to `localhost:13000` (or `localhost:3000` when running server locally):
|
||||
The Vite dev server runs on **http://localhost:5173**. It has no API proxy: the client calls `VITE_API_URL` (default `/api/v1` on its own origin), and the server allows CORS from `http://localhost:5173`. So point it at a running server:
|
||||
|
||||
- `/environments`
|
||||
- `/credentials`
|
||||
- `/snippets`
|
||||
- `/sessions`
|
||||
- `/scenarios`
|
||||
```bash
|
||||
npm -w client run dev:compose-api # API of the compose container (localhost:13000)
|
||||
VITE_API_URL=http://localhost:3000/api/v1 npm -w client run dev # API of a locally started server
|
||||
```
|
||||
|
||||
**Production build**:
|
||||
|
||||
@@ -79,6 +86,36 @@ The built files are emitted to `client/dist/`.
|
||||
|
||||
---
|
||||
|
||||
## Database migrations
|
||||
|
||||
The SQLite schema is managed by TypeORM migrations in `server/src/database/migrations/`; `synchronize` is off.
|
||||
|
||||
- **Docker:** the container applies pending migrations before starting the server.
|
||||
- **Locally:** build, then apply them before starting the server (it refuses to start while migrations are pending):
|
||||
|
||||
```bash
|
||||
npm -w server run build
|
||||
npm -w server run migration:run # apply pending migrations to DB_PATH
|
||||
npm -w server run migration:show # list migrations and whether they're applied
|
||||
```
|
||||
|
||||
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
|
||||
|
||||
**Changing the schema** (adding or changing an entity):
|
||||
|
||||
1. Change the entity and build (`npm -w server run build`).
|
||||
2. Make sure your local database is on the latest migration (`migration:run`).
|
||||
3. Generate a migration from the difference between the entities and that database:
|
||||
|
||||
```bash
|
||||
npm -w server run migration:generate -- src/database/migrations/AddSomething
|
||||
```
|
||||
|
||||
4. Review the generated file, then add its class to `MIGRATIONS` in `src/database/migrations/index.ts` (they're listed explicitly, oldest first).
|
||||
5. Run the tests: `test/migrations.spec.ts` checks that the migrations produce exactly the schema the entities describe, and fails if an entity change has no migration.
|
||||
|
||||
The initial migration (`Initial…`) adopts databases created before migrations existed (by `synchronize`): if the tables already exist, it's only recorded as applied.
|
||||
|
||||
## Running tests
|
||||
|
||||
### Server (Jest)
|
||||
@@ -99,7 +136,7 @@ Watch mode:
|
||||
npm -w server run test:watch
|
||||
```
|
||||
|
||||
Enable verbose NestJS log output during tests:
|
||||
Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`):
|
||||
|
||||
```bash
|
||||
npm -w server run test:debug
|
||||
@@ -163,6 +200,10 @@ Both workspaces target zero errors. Run lint before committing.
|
||||
|
||||
## Building the container
|
||||
|
||||
The root `Dockerfile` builds a single image with the whole application: it builds the client and the server in separate stages, and the runtime image runs the server, which also serves the built client (`CLIENT_DIR`).
|
||||
|
||||
The runtime image uses Playwright's headless-only Chromium build (`chromium-headless-shell`) with just the shared libraries it links against, plus DejaVu and Liberation fonts (Liberation is metric-compatible with Arial/Times, so pages lay out as they would with those fonts). All browser launches are headless, so the full desktop Chromium isn't installed. If a new Playwright version needs another library, `ldd` on the `chrome-headless-shell` binary in the image lists what's missing.
|
||||
|
||||
```bash
|
||||
docker compose build
|
||||
```
|
||||
@@ -189,9 +230,11 @@ Build and start in one step:
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
The server API is exposed at **http://localhost:13000**.
|
||||
Everything is served by the single `liqa` container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs` and health at `/health`. Unknown paths outside those routes get the client's `index.html`, so client-side routes survive a page refresh.
|
||||
|
||||
SQLite data is persisted in `./data/` and key files are mounted from `./keys/` — both directories are volume-mounted into the container.
|
||||
When switching from the old two-container setup (`server` + `client`), remove the old containers with `docker compose up -d --build --remove-orphans`.
|
||||
|
||||
The SQLite database and stored files are persisted in `./data/`, which is volume-mounted into the container.
|
||||
|
||||
Stop and remove containers:
|
||||
|
||||
@@ -209,7 +252,7 @@ docker compose logs -f
|
||||
|
||||
## Client overview
|
||||
|
||||
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, credentials, snippets, sessions, scenarios, and runs.
|
||||
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing scenarios, runs, snippets, credentials, environments and sessions, and for importing exported YAML.
|
||||
|
||||
### Tech stack
|
||||
|
||||
@@ -217,9 +260,13 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
|
||||
|---|---|
|
||||
| React 19 + TypeScript | UI framework |
|
||||
| Vite 6 | Dev server and bundler |
|
||||
| react-router-dom (HashRouter) | Client-side routing |
|
||||
| react-router-dom 7 (`BrowserRouter`) | Client-side routing |
|
||||
| @tanstack/react-query | Data fetching (cross-scenario runs list) |
|
||||
| i18next + react-i18next | Internationalisation |
|
||||
| lucide-react | Icon library |
|
||||
| @monaco-editor/react | Code editor for steps and snippets |
|
||||
| react-markdown + highlight.js | Markdown descriptions and code highlighting |
|
||||
| yaml | YAML export of entities |
|
||||
| moment | Relative timestamp formatting |
|
||||
| ESLint 10 + Prettier | Linting and formatting |
|
||||
| Storybook 10 + Vitest | Component development and testing |
|
||||
@@ -229,29 +276,30 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
|
||||
```
|
||||
client/
|
||||
src/
|
||||
api/ API client modules (environments, credentials, snippets, sessions, scenarios)
|
||||
hooks/ useTheme (light/dark persistence)
|
||||
api/ API client (client.ts) and types (types.ts)
|
||||
components/ modals/ - run, export, export logs and delete confirmation modals
|
||||
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile
|
||||
i18n/ i18next bootstrap + locales/en.json
|
||||
pages/ Environment/Credential/Snippet/Session/Scenario/Run pages
|
||||
ui/ Reusable component library
|
||||
Badge, Breadcrumbs, Button, Card, Input, Select,
|
||||
SidePanel, Table, ThemeSwitcher, Timestamp
|
||||
lib/ highlight.js setup, API error toast events
|
||||
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
|
||||
ui/ Reusable component library (Badge, Button, Card, CodeEditor, Modal,
|
||||
Select, SidePanel, Table, Toast, ... - see ui/index.ts)
|
||||
.storybook/
|
||||
stories/ *.stories.tsx for all ui/ components
|
||||
stories/ *.stories.tsx for ui/ components
|
||||
```
|
||||
|
||||
### Routing
|
||||
|
||||
Hash-based routing (`/#/path`) avoids conflicts with the Vite dev-server proxy. Default route redirects to `/#/scenarios`.
|
||||
`BrowserRouter` with plain paths. The root and unknown paths redirect to `/scenarios`. The server answers these paths with the client's `index.html` (see [architecture.md](architecture.md)), so they work on refresh.
|
||||
|
||||
| Route | Page |
|
||||
|---|---|
|
||||
| `/#/environments` | Environment list |
|
||||
| `/#/credentials` | Credential list |
|
||||
| `/#/snippets` | Snippet list |
|
||||
| `/#/sessions` | Session list |
|
||||
| `/#/scenarios` | Scenario list |
|
||||
| `/#/runs` | Cross-scenario runs list |
|
||||
| `/scenarios` | Scenario list |
|
||||
| `/scenarios/:id` | Scenario details (steps, versions, credentials, used snippets, files) |
|
||||
| `/scenarios/:id/runs`, `/scenarios/:id/runs/:runId` | Runs of a scenario, run details |
|
||||
| `/runs` | Cross-scenario runs list |
|
||||
| `/snippets`, `/credentials`, `/environments`, `/sessions` | Entity lists (plus `/:id`, `/new`, `/:id/edit` where applicable) |
|
||||
| `/import` | Central import |
|
||||
|
||||
### Theming
|
||||
|
||||
|
||||
+88
-28
@@ -1,56 +1,116 @@
|
||||
# MCP tools
|
||||
|
||||
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport).
|
||||
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls.
|
||||
|
||||
The server currently registers the following tools.
|
||||
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
|
||||
|
||||
## Sessions
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_sessions` | List stored sessions (paginated) |
|
||||
| `delete_session` | Delete a session by UUID |
|
||||
| `list_sessions` | List saved browser sessions (`orderBy`/`orderDir`) |
|
||||
| `delete_session` | Delete a session by `id` |
|
||||
|
||||
## Environments
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_environments` | List environments (paginated) |
|
||||
| `get_environment` | Get one environment by UUID |
|
||||
| `create_environment` | Create environment (`name`, `urls`) |
|
||||
| `update_environment` | Update environment (`id`, optional `name`/`urls`) |
|
||||
| `delete_environment` | Delete environment by UUID |
|
||||
| `list_environments` | List environments (`orderBy`/`orderDir`) |
|
||||
| `get_environment` | Get one environment by `id` |
|
||||
| `create_environment` | Create an environment: `name`, optional `description`, `data` |
|
||||
| `update_environment` | Update `name`, `description` and/or `data` of environment `id` |
|
||||
| `delete_environment` | Delete an environment by `id` |
|
||||
|
||||
`urls` is a free-form key/value map. Common keys: `id_url`, `cabinet_url`, `admin_url`.
|
||||
`data` is a free-form map of string keys to string values, read in step code with `context.getEnv(key)`.
|
||||
|
||||
## Credentials
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_credentials` | List credentials (`orderBy`/`orderDir`). Returns the full `data`, secrets included |
|
||||
| `get_credential` | Get one credential by `id` (full `data`) |
|
||||
| `create_credential` | Create a credential: `name`, optional `data` (JSON-encoded string) |
|
||||
| `update_credential` | Update `name` and/or `data`; omitted fields are left unchanged |
|
||||
| `delete_credential` | Delete a credential; also removes it from scenarios it's assigned to |
|
||||
|
||||
## Browser (ad-hoc)
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
|
||||
| `exec_code` | Execute Playwright JS with `page` and `context` in scope |
|
||||
| `open_url` | Open `url`, optionally in saved session `sessionName`; returns title and content (`readerMode` for readable text, `selector` to limit to one element) |
|
||||
| `exec_code` | Run Playwright JS that receives a single `context` argument (see [scenario.md](scenario.md)), optionally after opening `url` and/or in session `sessionName`. `environmentId` loads an environment for `context.getEnv()`; `credentials` (`{ alias: credentialId }`) loads credentials for `context.getCredential(alias)` |
|
||||
|
||||
## Scenarios
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_scenarios` | List scenarios (paginated) |
|
||||
| `get_scenario` | Get scenario with steps |
|
||||
| `create_scenario` | Create scenario by `name` |
|
||||
| `update_scenario` | Rename scenario |
|
||||
| `delete_scenario` | Delete scenario |
|
||||
| `create_scenario_step` | Add step to scenario |
|
||||
| `list_scenarios` | List scenarios (`orderBy`/`orderDir`) |
|
||||
| `get_scenario` | Get a scenario (latest version) with its steps |
|
||||
| `create_scenario` | Create a scenario: `name`, optional `description`, `environmentId` (default environment), `timeoutSeconds` |
|
||||
| `update_scenario` | Update scenario fields; bumps the version when content changes |
|
||||
| `delete_scenario` | Delete a scenario with its steps, versions and runs |
|
||||
| `create_scenario_step` | Append a step: `execCode`, optional `title` and `timeoutSeconds`. The schema also requires `order` and `type`, but both are ignored: new steps always go last (use `update_scenario_step` with `order` to move one) |
|
||||
| `get_scenario_step` | Get one step |
|
||||
| `update_scenario_step` | Update step fields |
|
||||
| `delete_scenario_step` | Delete step |
|
||||
| `list_scenario_runs` | List runs for a scenario |
|
||||
| `run_scenario` | Trigger run for scenario |
|
||||
| `get_scenario_run` | Get run with step runs and logs |
|
||||
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
|
||||
| `export_scenario` | Export scenario payload |
|
||||
| `import_scenario` | Import scenario payload |
|
||||
| `update_scenario_step` | Update step fields (including `order` to move it) |
|
||||
| `delete_scenario_step` | Delete a step |
|
||||
| `list_scenario_versions` | List a scenario's versions, newest first |
|
||||
| `get_scenario_version` | Get one scenario version with its steps |
|
||||
| `list_scenario_credentials` | List credentials assigned to a scenario (alias → credential) |
|
||||
| `add_scenario_credential` | Assign credential `credentialId` to a scenario under `alias` |
|
||||
| `remove_scenario_credential` | Remove an assignment by `scenarioCredentialId` (the assignment id, not the credential id) |
|
||||
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
|
||||
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
|
||||
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
|
||||
| `export_e2e_test` | Export a scenario as a standalone Playwright test project (zip, base64) |
|
||||
|
||||
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
|
||||
|
||||
## Runs
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `run_scenario` | Start a run of scenario `id` in `environmentId`; optional `version` (defaults to the latest), `saveSession`, `traceMode` (`on`, `retain-on-failure`, `off`; defaults to `PLAYWRIGHT_TRACE_MODE`) |
|
||||
| `list_scenario_runs` | List runs of a scenario, optionally filtered by `status` |
|
||||
| `list_all_runs` | List runs across all scenarios, optionally filtered by `status` |
|
||||
| `get_scenario_run` | Get a run with its step runs (outputs) and logs |
|
||||
| `wait_for_scenario_run` | Wait until a run is `pass` or `fail` (up to 5 minutes), then return it |
|
||||
|
||||
## Snippets
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_snippets` | List snippets (`orderBy`/`orderDir`) |
|
||||
| `get_snippet` | Get one snippet (latest version) |
|
||||
| `create_snippet` | Create a snippet: `alias`, `title`, `code`, optional `description` |
|
||||
| `update_snippet` | Update snippet fields; bumps its version when content changes |
|
||||
| `delete_snippet` | Delete a snippet and all its versions |
|
||||
| `list_snippet_versions` | List a snippet's versions, newest first |
|
||||
| `get_snippet_version` | Get one snippet version |
|
||||
|
||||
Step code runs a snippet with `context.runSnippet("alias", ...args)` (latest version) or `context.runSnippet("alias@3", ...args)` (version 3).
|
||||
|
||||
## Scenario files
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `upload_scenario_file` | Upload a file to a scenario: `name`, base64 `contentBase64`, optional `mimeType` and `expiresAt` (ISO 8601) |
|
||||
| `list_scenario_files` | List a scenario's files (`limit`, `offset`) |
|
||||
| `get_scenario_file_content` | Get a file's content as base64, with metadata |
|
||||
|
||||
## Run files
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_run_files` | List files created during a run (`limit`, `offset`): downloads, failure screenshots/HTML, `trace.zip` |
|
||||
| `get_run_file_content` | Get a run file's content as base64, with metadata |
|
||||
| `delete_run_file` | Delete a file from a run; the stored file is removed once no scenario or run references it (also `DELETE /api/v1/scenarios/:id/runs/:runId/files/:fileId` and the delete button on the run detail page) |
|
||||
|
||||
## Binary content handling
|
||||
|
||||
File tools carry binary content as base64 strings in a `contentBase64` field, with `encoding: "base64"` in the response. Decode it to get the original bytes.
|
||||
|
||||
Content for `upload_scenario_file` must be base64-encoded. Run files are only created by runs themselves (`context.downloadFile()`, failure page dumps, traces) and can't be uploaded.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tool IDs and entity IDs are UUIDs.
|
||||
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
|
||||
- The step `type` field (`login`, `exec`, `sign`) in `create_scenario_step`, `update_scenario_step` and `import_scenario` is a legacy field kept for compatibility; it's ignored, and every step runs its `execCode`.
|
||||
+101
-41
@@ -1,57 +1,117 @@
|
||||
# Scenario execution
|
||||
|
||||
When a scenario run is created, the server creates one `ScenarioRunStep` per scenario step.
|
||||
API paths below are relative to the REST prefix `/api/v1` (e.g. `POST /api/v1/scenarios/:id/run`).
|
||||
|
||||
- Step runs are ordered by `step.order`.
|
||||
- First step run starts as `pending`; the rest start as `waiting`.
|
||||
- Scheduler tick (`@Interval(1000)`) picks pending runs and processes steps in order.
|
||||
- Steps in the same run share one Playwright browser/context/page.
|
||||
## Runs
|
||||
|
||||
## Execution model
|
||||
Creating a run (`POST /scenarios/:id/run`, the Run button, or the `run_scenario` MCP tool) takes an environment, and optionally a scenario version (latest by default), `saveSession` and a trace mode.
|
||||
|
||||
Current scheduler behavior is exec-centric:
|
||||
|
||||
- `execCode` is required for a step to pass.
|
||||
- `validateCode` is optional and runs after `execCode`.
|
||||
- Legacy step type metadata may still appear in MCP payloads, but run execution is not branched by step type.
|
||||
- The run gets one step run per step of that scenario version, each with its own copy of the step's title, code and timeout. Editing or deleting steps later doesn't change existing runs.
|
||||
- The first step run starts as `pending`, the rest as `waiting`.
|
||||
- A scheduler tick (`@Interval(1000)`) picks up pending runs (up to 10 at a time) and executes their steps in order. All steps of a run share one Playwright browser, context and page.
|
||||
- A step passes when its code returns, and fails when it throws or times out. Its return value is stored as the step output (JSON) and is available to later steps via `context.getStepOutput()`.
|
||||
- When a step fails, the run is marked `fail`, the remaining steps are `cancelled`, and a screenshot and the page HTML are saved to the run's files (`step-<order>-failure.png` / `.html`).
|
||||
- Timeouts: each step gets its own `timeoutSeconds`, otherwise the scenario's `timeoutSeconds`, otherwise 60 s. The run as a whole fails once it has run longer than the scenario's `timeoutSeconds` (default 600 s); this is checked before each step.
|
||||
- With `saveSession`, the run's browser is kept after the run as a saved session named `run-<runId>` (see Sessions in the UI), instead of being closed.
|
||||
- Runs left `in_progress` when the server stops are marked `fail` on the next start.
|
||||
|
||||
## Script runtime
|
||||
|
||||
`execCode` and `validateCode` execute as async JavaScript with:
|
||||
|
||||
- `page`: Playwright `Page`
|
||||
- `context`: Playwright `BrowserContext`
|
||||
- `helpers`: utility object
|
||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||
|
||||
`validateCode` additionally receives `result`, which is the value returned by `execCode`.
|
||||
|
||||
## Available helpers
|
||||
|
||||
- `helpers.dumpDom(selector?)`: simplified DOM snapshot
|
||||
- `helpers.log(...args)`, `helpers.warn(...args)`, `helpers.error(...args)`: structured step logs
|
||||
- `helpers.getStepOutput(order)`: prior step output by absolute order (`0`, `1`, ...) or relative (`-1` previous step)
|
||||
- `helpers.getCredential(alias)`: credential payload assigned to the scenario alias
|
||||
- `helpers.env`: shallow copy of environment URL map
|
||||
- `helpers.getEnvUrl(key)`: required environment URL lookup (throws if missing)
|
||||
- `helpers.runSnippet(name, ...args)`: execute stored snippet code in the same page/context/helpers scope
|
||||
|
||||
## Validation contract
|
||||
|
||||
`validateCode` may return:
|
||||
Step code (`execCode`) and snippet code run as an async JavaScript function body with a single `context` argument:
|
||||
|
||||
```js
|
||||
return { success: true, description: 'ok' };
|
||||
// or
|
||||
return false;
|
||||
async (context) => {
|
||||
// your code here
|
||||
}
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
Available on `context`:
|
||||
|
||||
- Boolean: `true` = pass, `false` = fail
|
||||
- Object: `success` controls pass/fail; `description` is persisted as step description
|
||||
- `context.page`: Playwright `Page`
|
||||
- `context.browser`: Playwright `BrowserContext`
|
||||
- `context.env`: shallow copy of the environment's key/value map
|
||||
- `context.getEnv(key)`: environment value lookup (throws if missing)
|
||||
- `context.getCredential(alias)`: payload of the credential assigned to the scenario under `alias` (parsed JSON when the data is JSON; throws if missing)
|
||||
- `context.getStepOutput(order)`: output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||
- `context.dumpDom(selector?)`: simplified DOM snapshot of the page (or of one element)
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: run log entries
|
||||
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
||||
- `context.runSnippet(name, ...args)`: runs stored snippet code with the same context; the snippet receives the extra arguments as `...args`. `name` is the snippet alias for its latest version, or `alias@<version>` (e.g. `login@3`) to pin a specific version. Snippet start/finish/failure is logged
|
||||
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`), including their path on disk
|
||||
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run file (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
|
||||
|
||||
On validation failure, the step fails and the run is marked `fail`.
|
||||
Also in scope:
|
||||
|
||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||
- `expect`: Playwright's `expect` (e.g. `await expect(context.page.locator("h1")).toHaveText("Done")`)
|
||||
|
||||
Code is syntax-checked before it runs, and executes in the server process: it's trusted code, not sandboxed.
|
||||
|
||||
Step run logs also include automatic "Step N started / passed / failed" entries.
|
||||
|
||||
## Versioning
|
||||
|
||||
Scenarios and snippets are versioned, starting at version 1.
|
||||
|
||||
- A scenario's version goes up when its content changes: name, description, default environment, timeout, or any step change (add, edit, delete, reorder). Credential assignments and uploaded files are not versioned. Saving without changes does not create a new version.
|
||||
- A snippet's version goes up when its alias, title, description or code changes.
|
||||
- The scenario and snippet pages always show the latest version. Older versions are available via `GET /scenarios/:id/versions[/:version]` and `GET /snippets/:id/versions[/:version]`.
|
||||
- A run executes one scenario version, chosen in the run modal (latest by default) or via `version` in `POST /scenarios/:id/run`. The run keeps its own copy of that version's steps, so deleting or editing steps later doesn't change what the run shows. "Repeat run" reuses the run's version.
|
||||
- Step code uses the latest version of a snippet by default. `context.runSnippet("alias@3")` pins version 3 instead. The version is looked up through the snippet's current alias. Pinned versions are listed under "Used Snippets" on the scenario page.
|
||||
|
||||
### Export / import
|
||||
|
||||
Exports hold exactly one version and always include its `version` number (the latest by default, or `?version=N`). Imports require `version`, and restore that exact version by id + version:
|
||||
|
||||
- If that version already exists, it is left untouched.
|
||||
- Otherwise it is stored under that number, and becomes the latest if it is higher than the current latest version.
|
||||
- Without an `id`, a new scenario or snippet is created at the given version.
|
||||
|
||||
## Import
|
||||
|
||||
`POST /import` (the Import page in the UI, and the Import buttons on the list pages; the `import_yaml` MCP tool) imports any mix of environments, credentials, snippets and scenarios.
|
||||
|
||||
- Send YAML with `Content-Type: application/yaml`. A file is a stream of `---`-separated documents; each document holds one exported item or a list of items. JSON is valid YAML, and a JSON body (one item or an array) is accepted too.
|
||||
- Every item needs a `kind`: `environment`, `credential`, `snippet` or `scenario`. Snippets and scenarios also need `version` (see above).
|
||||
- All items are validated before anything is imported, so one invalid item means nothing from that request is imported. The error lists every invalid item by its position.
|
||||
- Items are imported in dependency order - environments, credentials, snippets, scenarios - regardless of their order in the file, so a scenario can reference an environment or credential from the same file.
|
||||
- The response lists what was imported: `{ imported: [{ kind, id, name, version? }] }`.
|
||||
|
||||
A scenario export (`GET /scenarios/:id/export`, optionally with its environment and credentials) is in this format, one document per entity, and can be imported back as is.
|
||||
|
||||
```yaml
|
||||
---
|
||||
# Environment: staging
|
||||
kind: environment
|
||||
id: 5b0c…
|
||||
name: staging
|
||||
data:
|
||||
base_url: https://staging.example
|
||||
---
|
||||
# Scenario: Login flow
|
||||
kind: scenario
|
||||
id: 9e1f…
|
||||
version: 3
|
||||
name: Login flow
|
||||
environmentId: 5b0c…
|
||||
steps:
|
||||
- title: Open login page
|
||||
execCode: await context.page.goto(context.getEnv("base_url"));
|
||||
```
|
||||
|
||||
## Playwright traces
|
||||
|
||||
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
|
||||
The trace mode is chosen per run: the run modal in the UI, the `traceMode` field of `POST /scenarios/:id/run`, and the `traceMode` argument of the `run_scenario` MCP tool all accept one of the values below. When it is omitted, the server's `PLAYWRIGHT_TRACE_MODE` setting is used (exposed via `GET /scenarios/run-defaults`). "Repeat run" reuses the original run's mode.
|
||||
|
||||
- `on`: keep the trace of every run
|
||||
- `retain-on-failure`: keep traces only for runs that failed
|
||||
- `off` (default): do not record traces
|
||||
|
||||
Traces are off by default because they often reach ~10 MB per run.
|
||||
|
||||
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
|
||||
|
||||
## Statuses
|
||||
|
||||
@@ -76,7 +136,7 @@ Run-step status:
|
||||
1. Create environment
|
||||
2. Create credentials and snippets (optional but common)
|
||||
3. Create scenario
|
||||
4. Add ordered steps (`execCode`, optional `validateCode`)
|
||||
4. Add ordered steps (`execCode`, optional `title` and `timeoutSeconds`)
|
||||
5. Assign credentials to scenario aliases when needed
|
||||
6. Run scenario
|
||||
7. Wait for run completion and inspect run logs/outputs
|
||||
Generated
+773
-9
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -1,7 +1,10 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.5.0",
|
||||
"version": "1.20.0",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
"workspaces": [
|
||||
"server",
|
||||
"client"
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
# ── Build stage ──────────────────────────────────────────────────────────────
|
||||
FROM node:22-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci -w server
|
||||
|
||||
COPY server/nest-cli.json ./server/
|
||||
COPY server/tsconfig*.json ./server/
|
||||
COPY server/src ./server/src
|
||||
RUN npm run -w server build
|
||||
|
||||
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
||||
FROM node:22-slim AS runtime
|
||||
|
||||
# Playwright / Chromium system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
chromium \
|
||||
fonts-noto \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Tell Playwright to use the system Chromium instead of downloading its own
|
||||
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci --omit=dev -w server
|
||||
|
||||
COPY --from=builder /app/server/dist ./dist
|
||||
|
||||
# Runtime directories (keys and SQLite DB mounted via volumes)
|
||||
RUN mkdir -p data keys
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "dist/main"]
|
||||
+8
-1
@@ -1,12 +1,15 @@
|
||||
{
|
||||
"name": "liqa-server",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"migration:run": "node dist/database/migrate",
|
||||
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
||||
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
@@ -25,13 +28,16 @@
|
||||
"@nestjs/core": "^11.1.18",
|
||||
"@nestjs/platform-express": "^11.1.18",
|
||||
"@nestjs/schedule": "^6.1.1",
|
||||
"@nestjs/serve-static": "^5.0.5",
|
||||
"@nestjs/swagger": "^11.2.6",
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"acorn": "^8.16.0",
|
||||
"archiver": "^7.0.1",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -45,6 +51,7 @@
|
||||
"@nestjs/cli": "^11.0.17",
|
||||
"@nestjs/testing": "^11.1.18",
|
||||
"@types/acorn": "^4.0.6",
|
||||
"@types/archiver": "^6.0.4",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/debug": "^4.1.13",
|
||||
"@types/express": "^5.0.6",
|
||||
|
||||
+18
-31
@@ -1,24 +1,19 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { ScheduleModule } from "@nestjs/schedule";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { BrowserModule } from "./browser/browser.module";
|
||||
import { SessionEntity } from "./session/session.entity";
|
||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { CredentialEntity } from "./credential/credential.entity";
|
||||
import { clientStaticOptions } from "./common/client-static";
|
||||
import { dataSourceOptions } from "./database/data-source";
|
||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||
import { CredentialModule } from "./credential/credential.module";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { FileModule } from "./file/file.module";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { ImportModule } from "./import/import.module";
|
||||
import { McpModule } from "./mcp/mcp.module";
|
||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
|
||||
import { ScenarioModule } from "./scenario/scenario.module";
|
||||
import { SnippetEntity } from "./snippet/snippet.entity";
|
||||
import { SnippetModule } from "./snippet/snippet.module";
|
||||
|
||||
@Module({
|
||||
@@ -29,31 +24,23 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
validate: validateAppConfig,
|
||||
}),
|
||||
ScheduleModule.forRoot(),
|
||||
ServeStaticModule.forRootAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService<AppConfig, true>) =>
|
||||
clientStaticOptions(config.get("CLIENT_DIR")),
|
||||
}),
|
||||
TypeOrmModule.forRootAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService<AppConfig, true>) => ({
|
||||
type: "better-sqlite3",
|
||||
database: config.get("DB_PATH"),
|
||||
entities: [
|
||||
SessionEntity,
|
||||
EnvironmentEntity,
|
||||
CredentialEntity,
|
||||
ScenarioEntity,
|
||||
ScenarioStepEntity,
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
SnippetEntity,
|
||||
],
|
||||
synchronize: true,
|
||||
}),
|
||||
useFactory: (config: ConfigService<AppConfig, true>) =>
|
||||
dataSourceOptions(config.get("DB_PATH")),
|
||||
}),
|
||||
BrowserModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
ScenarioModule,
|
||||
SnippetModule,
|
||||
FileModule,
|
||||
ImportModule,
|
||||
McpModule,
|
||||
HealthModule,
|
||||
],
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Body, Controller, Post } from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { OpenDto } from "./dto/open.dto";
|
||||
import { CredentialService } from "../credential/credential.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
|
||||
import { ExecDto } from "./dto/exec.dto";
|
||||
import { OpenDto } from "./dto/open.dto";
|
||||
|
||||
@ApiTags("browser")
|
||||
@Controller()
|
||||
@@ -11,6 +13,8 @@ export class BrowserController {
|
||||
constructor(
|
||||
private readonly browserService: BrowserService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly credentialService: CredentialService,
|
||||
) {}
|
||||
|
||||
@Post("open")
|
||||
@@ -54,8 +58,32 @@ export class BrowserController {
|
||||
@ApiResponse({ status: 400, description: "Invalid input" })
|
||||
@ApiResponse({ status: 404, description: "Session not found" })
|
||||
@ApiResponse({ status: 500, description: "Execution failed" })
|
||||
exec(@Body() dto: ExecDto): Promise<ExecResult> {
|
||||
async exec(@Body() dto: ExecDto): Promise<ExecResult> {
|
||||
this.codeExecutor.validate(dto.code);
|
||||
return this.browserService.exec(dto.sessionName, dto.code, dto.url);
|
||||
|
||||
// Resolve environment from DB
|
||||
let environment: Record<string, string | undefined> | undefined;
|
||||
if (dto.environmentId) {
|
||||
const env = await this.environmentService.findOne(dto.environmentId);
|
||||
environment = env.data;
|
||||
}
|
||||
|
||||
// Resolve credentials from DB (alias → payload)
|
||||
let credentials: Record<string, unknown> | undefined;
|
||||
if (dto.credentials && Object.keys(dto.credentials).length > 0) {
|
||||
credentials = {};
|
||||
for (const [alias, credId] of Object.entries(dto.credentials)) {
|
||||
const cred = await this.credentialService.findOne(credId);
|
||||
credentials[alias] = cred.data ? JSON.parse(cred.data) : {};
|
||||
}
|
||||
}
|
||||
|
||||
return this.browserService.exec(
|
||||
dto.sessionName,
|
||||
dto.code,
|
||||
dto.url,
|
||||
environment,
|
||||
credentials,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
import { CredentialModule } from "../credential/credential.module";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { SnippetModule } from "../snippet/snippet.module";
|
||||
import { BrowserController } from "./browser.controller";
|
||||
import { BrowserService } from "./browser.service";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
|
||||
@Module({
|
||||
imports: [SessionModule, CodeExecutorModule],
|
||||
imports: [
|
||||
SessionModule,
|
||||
CodeExecutorModule,
|
||||
SnippetModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
],
|
||||
controllers: [BrowserController],
|
||||
providers: [BrowserService],
|
||||
exports: [BrowserService],
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
} from "@nestjs/common";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { chromium } from "playwright";
|
||||
import type { BrowserContext } from "playwright";
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import { JSDOM } from "jsdom";
|
||||
import type { BrowserContext, Cookie } from "playwright";
|
||||
import { chromium } from "playwright";
|
||||
import type {
|
||||
ExecResult,
|
||||
ScriptLogger,
|
||||
} from "../code-executor/code-executor.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import { SessionContextService } from "../session/session-context.service";
|
||||
import { SessionService } from "../session/session.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import type { ExecResult } from "../code-executor/code-executor.service";
|
||||
import type { Cookie } from "playwright";
|
||||
import { SnippetService } from "../snippet/snippet.service";
|
||||
|
||||
export type { ExecResult } from "../code-executor/code-executor.service";
|
||||
|
||||
@@ -30,6 +34,7 @@ export class BrowserService {
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly snippetService: SnippetService,
|
||||
) {}
|
||||
|
||||
private parseCookies(raw: string | null | undefined): Cookie[] {
|
||||
@@ -164,20 +169,34 @@ export class BrowserService {
|
||||
sessionName: string | undefined,
|
||||
code: string,
|
||||
url?: string,
|
||||
environment?: EnvironmentData,
|
||||
credentials?: Record<string, unknown>,
|
||||
): Promise<ExecResult> {
|
||||
const label = sessionName ?? "anonymous";
|
||||
|
||||
if (sessionName) {
|
||||
const { page, context } =
|
||||
await this.getOrCreateNamedHandle(sessionName);
|
||||
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
|
||||
this.logger.log(`[${label}] exec: using persistent context`);
|
||||
const snippets = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
try {
|
||||
if (url) {
|
||||
this.logger.log(`[${label}] exec: navigating to ${url}`);
|
||||
await page.goto(url, { waitUntil: "networkidle" });
|
||||
}
|
||||
this.logger.log(`[${label}] exec: running user code`);
|
||||
const result = await this.codeExecutor.execute(page, context, code);
|
||||
const scriptLogger: ScriptLogger = (level, msg) =>
|
||||
this.logger[level](`[${label}] script: ${msg}`);
|
||||
const result = await this.codeExecutor.execute({
|
||||
page,
|
||||
browser: context,
|
||||
code,
|
||||
log: scriptLogger,
|
||||
credentials,
|
||||
environment,
|
||||
snippets,
|
||||
});
|
||||
this.logger.log(`[${label}] exec: done`);
|
||||
return result;
|
||||
} catch (err) {
|
||||
@@ -186,13 +205,20 @@ export class BrowserService {
|
||||
}
|
||||
|
||||
// Anonymous — ephemeral browser
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
|
||||
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
|
||||
// instead of launching a new browser for each request.
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const browserContext = await browser.newContext();
|
||||
const page = await browserContext.newPage();
|
||||
|
||||
if (url) {
|
||||
this.logger.log(`[${label}] exec: navigating to ${url}`);
|
||||
@@ -200,7 +226,17 @@ export class BrowserService {
|
||||
}
|
||||
|
||||
this.logger.log(`[${label}] exec: running user code`);
|
||||
const result = await this.codeExecutor.execute(page, context, code);
|
||||
const scriptLogger: ScriptLogger = (level, msg) =>
|
||||
this.logger[level](`[${label}] script: ${msg}`);
|
||||
const result = await this.codeExecutor.execute({
|
||||
page,
|
||||
browser: browserContext,
|
||||
code,
|
||||
log: scriptLogger,
|
||||
credentials,
|
||||
environment,
|
||||
snippets: snippetMap,
|
||||
});
|
||||
this.logger.log(`[${label}] exec: done`);
|
||||
return result;
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsString, IsUrl } from "class-validator";
|
||||
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
|
||||
|
||||
export class ExecDto {
|
||||
@ApiPropertyOptional({
|
||||
@@ -22,9 +22,27 @@ export class ExecDto {
|
||||
|
||||
@ApiProperty({
|
||||
description:
|
||||
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
|
||||
example: "return await page.title();",
|
||||
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
|
||||
example: "return await context.page.title();",
|
||||
})
|
||||
@IsString()
|
||||
code: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
|
||||
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
|
||||
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
|
||||
})
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
credentials?: Record<string, string>;
|
||||
}
|
||||
@@ -3,12 +3,16 @@ import {
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
} from "@nestjs/common";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { parse } from "acorn";
|
||||
import type { Page, BrowserContext } from "playwright";
|
||||
import { expect as playwrightExpect } from "@playwright/test";
|
||||
import { dumpDom } from "./dom-helpers";
|
||||
import { parse } from "acorn";
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import { URL } from "node:url";
|
||||
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { FileStorageService } from "../file/file-storage.service";
|
||||
import type { DomNode } from "./dom-helpers";
|
||||
import { dumpDom } from "./dom-helpers";
|
||||
|
||||
export interface ExecResult {
|
||||
result: unknown;
|
||||
@@ -19,6 +23,62 @@ export type ScriptLogger = (
|
||||
message: string,
|
||||
) => void;
|
||||
|
||||
/** The `context` object available inside user scripts as the sole argument. */
|
||||
export interface ScriptContext {
|
||||
/** Playwright Page for the current session. */
|
||||
page: Page;
|
||||
/** Playwright BrowserContext for the current session. */
|
||||
browser: BrowserContext;
|
||||
/** All environment values for the current run (empty object if none set). */
|
||||
env: Record<string, string | undefined>;
|
||||
/** Returns the environment value for `key`, or throws if not defined. */
|
||||
getEnv: (key: string) => string;
|
||||
/** Returns the credential value for `alias`, or throws if not found. */
|
||||
getCredential: (alias: string) => unknown;
|
||||
/** Returns the serialised output of a previous step by order index (negative = relative). */
|
||||
getStepOutput: (order: number) => Promise<unknown>;
|
||||
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
|
||||
dumpDom: (selector?: string) => Promise<DomNode>;
|
||||
log: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Runs `fn` and requires it to return `true`. Logs the outcome under
|
||||
* `description`, then throws if `fn` returned anything other than `true`
|
||||
* or threw an exception.
|
||||
*/
|
||||
assert: (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
) => Promise<void>;
|
||||
/** Runs a named snippet with the same context, plus any extra positional args. */
|
||||
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
|
||||
/** Returns metadata + absolute disk path for files attached to the current scenario. */
|
||||
getScenarioFiles: (opts?: { limit?: number; offset?: number }) => Promise<{
|
||||
items: Array<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
|
||||
total: number;
|
||||
}>;
|
||||
/** Downloads a file and creates a run artifact. */
|
||||
downloadFile: (
|
||||
url: string,
|
||||
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
|
||||
) => Promise<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
|
||||
}
|
||||
|
||||
export interface ExecContext {
|
||||
page: Page;
|
||||
browser: BrowserContext;
|
||||
code: string;
|
||||
log?: ScriptLogger;
|
||||
getStepOutput?: (order: number) => Promise<unknown>;
|
||||
credentials?: Record<string, unknown>;
|
||||
environment?: EnvironmentData | null;
|
||||
snippets?: Record<string, string> | null;
|
||||
scenarioId?: string;
|
||||
runId?: string;
|
||||
fileService?: FileStorageService;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CodeExecutorService {
|
||||
private readonly logger = new TraceLogger(CodeExecutorService.name);
|
||||
@@ -28,7 +88,7 @@ export class CodeExecutorService {
|
||||
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
|
||||
*/
|
||||
validate(code: string): void {
|
||||
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
|
||||
const wrapped = `async function __validate__(context) { ${code} }`;
|
||||
try {
|
||||
parse(wrapped, { ecmaVersion: 2022 });
|
||||
} catch (err) {
|
||||
@@ -40,20 +100,24 @@ export class CodeExecutorService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes `code` as an async function body with `page` and `context` in
|
||||
* scope. Always call `validate()` before this method.
|
||||
* Executes `code` as an async function body with a single `context` argument
|
||||
* that exposes page, browser, env helpers, credentials, snippets, and logging.
|
||||
* Always call `validate()` before this method.
|
||||
*/
|
||||
async execute(
|
||||
page: Page,
|
||||
context: BrowserContext,
|
||||
code: string,
|
||||
log?: ScriptLogger,
|
||||
getStepOutput?: (order: number) => Promise<unknown>,
|
||||
credentials?: Record<string, unknown>,
|
||||
environment?: EnvironmentData | null,
|
||||
snippets?: Record<string, string> | null,
|
||||
result?: unknown,
|
||||
): Promise<ExecResult> {
|
||||
async execute(ctx: ExecContext): Promise<ExecResult> {
|
||||
const {
|
||||
page,
|
||||
browser,
|
||||
code,
|
||||
log,
|
||||
getStepOutput,
|
||||
credentials,
|
||||
environment,
|
||||
snippets,
|
||||
scenarioId,
|
||||
runId,
|
||||
fileService,
|
||||
} = ctx;
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
const toStr = (args: unknown[]) =>
|
||||
@@ -65,9 +129,8 @@ export class CodeExecutorService {
|
||||
const envData: EnvironmentData = environment ?? {};
|
||||
const snippetMap: Record<string, string> = snippets ?? {};
|
||||
|
||||
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
|
||||
|
||||
let pageHelpers: Record<string, unknown>;
|
||||
// scriptContext is referenced by runSnippet, so we declare it first.
|
||||
let scriptContext: ScriptContext;
|
||||
|
||||
const fakeConsole = {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
@@ -78,11 +141,35 @@ export class CodeExecutorService {
|
||||
};
|
||||
|
||||
try {
|
||||
pageHelpers = {
|
||||
scriptContext = {
|
||||
page,
|
||||
browser,
|
||||
dumpDom: (selector?: string) => dumpDom(page, selector),
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
assert: async (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
): Promise<void> => {
|
||||
let passed: boolean;
|
||||
let failureReason: string | undefined;
|
||||
try {
|
||||
passed = (await fn()) === true;
|
||||
} catch (err) {
|
||||
passed = false;
|
||||
failureReason = (err as Error).message;
|
||||
}
|
||||
if (passed) {
|
||||
scriptLog("log", `Assertion passed: ${description}`);
|
||||
return;
|
||||
}
|
||||
const message = failureReason
|
||||
? `Assertion failed: ${description} (${failureReason})`
|
||||
: `Assertion failed: ${description}`;
|
||||
scriptLog("error", message);
|
||||
throw new Error(message);
|
||||
},
|
||||
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
|
||||
getCredential: (alias: string): unknown => {
|
||||
if (!(alias in credMap)) {
|
||||
@@ -92,10 +179,8 @@ export class CodeExecutorService {
|
||||
}
|
||||
return credMap[alias];
|
||||
},
|
||||
/** All values defined for the current environment (may be empty if no environment is set). */
|
||||
env: { ...envData },
|
||||
/** Returns the value for the given key, or throws if it is not defined. */
|
||||
getEnvUrl: (key: string): string => {
|
||||
getEnv: (key: string): string => {
|
||||
const value = envData[key];
|
||||
if (value == null) {
|
||||
throw new Error(
|
||||
@@ -104,12 +189,6 @@ export class CodeExecutorService {
|
||||
}
|
||||
return value;
|
||||
},
|
||||
/**
|
||||
* Runs a snippet by alias. Snippets receive the same page/context/helpers
|
||||
* as regular exec code, plus any positional args you pass.
|
||||
*
|
||||
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
|
||||
*/
|
||||
runSnippet: async (
|
||||
alias: string,
|
||||
...args: unknown[]
|
||||
@@ -118,43 +197,97 @@ export class CodeExecutorService {
|
||||
if (snippetCode == null) {
|
||||
throw new Error(`Snippet alias "${alias}" not found`);
|
||||
}
|
||||
scriptLog("log", `Snippet "${alias}" started`);
|
||||
const snippetFn = new Function(
|
||||
"page",
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"snippetArgs",
|
||||
"expect",
|
||||
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
|
||||
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
|
||||
);
|
||||
return snippetFn(
|
||||
page,
|
||||
context,
|
||||
pageHelpers,
|
||||
fakeConsole,
|
||||
args,
|
||||
playwrightExpect,
|
||||
try {
|
||||
const snippetResult = await snippetFn(
|
||||
scriptContext,
|
||||
fakeConsole,
|
||||
args,
|
||||
playwrightExpect,
|
||||
);
|
||||
scriptLog("log", `Snippet "${alias}" finished`);
|
||||
return snippetResult;
|
||||
} catch (err) {
|
||||
scriptLog(
|
||||
"error",
|
||||
`Snippet "${alias}" failed: ${(err as Error).message}`,
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
|
||||
if (!fileService || !scenarioId) {
|
||||
throw new Error("File service not available in this context");
|
||||
}
|
||||
const result = await fileService.listScenarioFiles(
|
||||
scenarioId,
|
||||
opts?.limit,
|
||||
opts?.offset,
|
||||
);
|
||||
return {
|
||||
items: result.items.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
mimeType: item.mimeType,
|
||||
size: item.size,
|
||||
sha256: item.sha256,
|
||||
path: item.path,
|
||||
})),
|
||||
total: result.total,
|
||||
};
|
||||
},
|
||||
downloadFile: async (
|
||||
url: string,
|
||||
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
|
||||
) => {
|
||||
if (!fileService || !scenarioId || !runId) {
|
||||
throw new Error("File service or run context not available");
|
||||
}
|
||||
// Download file
|
||||
const buffer = await downloadFileImpl(url, opts);
|
||||
|
||||
// Determine filename and mime type
|
||||
const filename = opts?.filename ?? new URL(url).pathname.split("/").pop() ?? "download";
|
||||
const mimeType = this.getMimeType(filename);
|
||||
|
||||
// Create run artifact with mapping
|
||||
const savedFile = await fileService.createAndSaveRunArtifact(
|
||||
runId,
|
||||
buffer,
|
||||
filename,
|
||||
mimeType,
|
||||
);
|
||||
|
||||
return {
|
||||
id: savedFile.id,
|
||||
name: savedFile.originalName,
|
||||
mimeType: savedFile.mimeType,
|
||||
size: savedFile.size,
|
||||
sha256: savedFile.sha256,
|
||||
path: fileService.getAbsolutePath(savedFile.filePath),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// Passing `console` and `expect` as named parameters exposes them in script scope.
|
||||
// `console` and `expect` are injected as named parameters so scripts
|
||||
// can reference them directly.
|
||||
const fn = new Function(
|
||||
"page",
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"result",
|
||||
"expect",
|
||||
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
|
||||
`return (async (context) => { ${code} })(context)`,
|
||||
);
|
||||
this.logger.debug("Executing user code");
|
||||
const execResult = await fn(
|
||||
page,
|
||||
context,
|
||||
pageHelpers,
|
||||
scriptContext,
|
||||
fakeConsole,
|
||||
result,
|
||||
playwrightExpect,
|
||||
);
|
||||
return { result: execResult };
|
||||
@@ -165,4 +298,26 @@ export class CodeExecutorService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infers MIME type from filename.
|
||||
*/
|
||||
private getMimeType(filename: string): string {
|
||||
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
|
||||
const mimeTypes: Record<string, string> = {
|
||||
pdf: "application/pdf",
|
||||
doc: "application/msword",
|
||||
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
xls: "application/vnd.ms-excel",
|
||||
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
jpg: "image/jpeg",
|
||||
jpeg: "image/jpeg",
|
||||
png: "image/png",
|
||||
gif: "image/gif",
|
||||
csv: "text/csv",
|
||||
txt: "text/plain",
|
||||
zip: "application/zip",
|
||||
};
|
||||
return mimeTypes[ext] ?? "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { FileStorageService } from "../file/file-storage.service";
|
||||
import type { ExecContext, ScriptLogger } from "./code-executor.service";
|
||||
|
||||
export class ExecContextBuilder {
|
||||
private readonly ctx: Partial<ExecContext> = {};
|
||||
|
||||
page(page: Page): this {
|
||||
this.ctx.page = page;
|
||||
return this;
|
||||
}
|
||||
|
||||
browser(browser: BrowserContext): this {
|
||||
this.ctx.browser = browser;
|
||||
return this;
|
||||
}
|
||||
|
||||
code(code: string): this {
|
||||
this.ctx.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
log(log: ScriptLogger): this {
|
||||
this.ctx.log = log;
|
||||
return this;
|
||||
}
|
||||
|
||||
getStepOutput(fn: (order: number) => Promise<unknown>): this {
|
||||
this.ctx.getStepOutput = fn;
|
||||
return this;
|
||||
}
|
||||
|
||||
credentials(credentials: Record<string, unknown>): this {
|
||||
this.ctx.credentials = credentials;
|
||||
return this;
|
||||
}
|
||||
|
||||
environment(environment: EnvironmentData | null): this {
|
||||
this.ctx.environment = environment;
|
||||
return this;
|
||||
}
|
||||
|
||||
snippets(snippets: Record<string, string> | null): this {
|
||||
this.ctx.snippets = snippets;
|
||||
return this;
|
||||
}
|
||||
|
||||
scenarioId(scenarioId: string): this {
|
||||
this.ctx.scenarioId = scenarioId;
|
||||
return this;
|
||||
}
|
||||
|
||||
runId(runId: string): this {
|
||||
this.ctx.runId = runId;
|
||||
return this;
|
||||
}
|
||||
|
||||
fileService(fileService: FileStorageService): this {
|
||||
this.ctx.fileService = fileService;
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): ExecContext {
|
||||
if (!this.ctx.page) throw new Error("ExecContextBuilder: page is required");
|
||||
if (!this.ctx.browser)
|
||||
throw new Error("ExecContextBuilder: browser is required");
|
||||
if (this.ctx.code === undefined)
|
||||
throw new Error("ExecContextBuilder: code is required");
|
||||
return this.ctx as ExecContext;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
export interface AppPackage {
|
||||
name: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
let cached: AppPackage | undefined;
|
||||
|
||||
/**
|
||||
* Name and version of the application, read from the workspace root
|
||||
* `package.json` (the one declaring `workspaces`) - the single source of the
|
||||
* app version. Found by walking up from this file, which covers both the repo
|
||||
* (`server/src/common` → repo root) and the Docker image
|
||||
* (`/app/dist/common` → `/app/package.json`).
|
||||
*/
|
||||
export function appPackage(): AppPackage {
|
||||
if (cached) return cached;
|
||||
let dir = __dirname;
|
||||
for (;;) {
|
||||
const file = path.join(dir, "package.json");
|
||||
if (fs.existsSync(file)) {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<
|
||||
AppPackage & { workspaces: unknown }
|
||||
>;
|
||||
if (pkg.workspaces && pkg.name && pkg.version) {
|
||||
cached = { name: pkg.name, version: pkg.version };
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) {
|
||||
throw new Error(
|
||||
`Workspace root package.json (with "workspaces", "name" and "version") not found above ${__dirname}`,
|
||||
);
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { NestExpressApplication } from "@nestjs/platform-express";
|
||||
|
||||
/** Content types accepted as raw YAML text (e.g. by `POST /import`). */
|
||||
export const YAML_CONTENT_TYPES = [
|
||||
"application/yaml",
|
||||
"application/x-yaml",
|
||||
"text/yaml",
|
||||
"text/x-yaml",
|
||||
];
|
||||
|
||||
/** Registers body parsers beyond Nest's default JSON/urlencoded ones. */
|
||||
export function configureBodyParsers(app: NestExpressApplication): void {
|
||||
app.useBodyParser("text", { type: YAML_CONTENT_TYPES, limit: "10mb" });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ServeStaticModuleOptions } from "@nestjs/serve-static";
|
||||
import type { ServerResponse } from "node:http";
|
||||
import * as path from "node:path";
|
||||
|
||||
/** Server routes that must never fall back to the client's index.html. */
|
||||
const SERVER_ROUTES = [
|
||||
"/api/{*path}",
|
||||
"/mcp{*path}",
|
||||
"/docs{*path}",
|
||||
"/health",
|
||||
"/healthz",
|
||||
];
|
||||
|
||||
/**
|
||||
* Serves the built client (SPA) from `clientDir`: static files as they are,
|
||||
* any other GET outside the server routes gets index.html so client-side
|
||||
* routes survive a page refresh. Returns no options (nothing served) when
|
||||
* `clientDir` is empty, e.g. in tests and local development.
|
||||
*/
|
||||
export function clientStaticOptions(
|
||||
clientDir: string,
|
||||
): ServeStaticModuleOptions[] {
|
||||
if (!clientDir) return [];
|
||||
return [
|
||||
{
|
||||
rootPath: path.resolve(clientDir),
|
||||
exclude: SERVER_ROUTES,
|
||||
serveStaticOptions: {
|
||||
setHeaders: (res: ServerResponse, filePath: string) => {
|
||||
// Vite emits content-hashed files under assets/; index.html must
|
||||
// always be revalidated so a new deploy is picked up immediately
|
||||
const cacheControl = filePath.includes(`${path.sep}assets${path.sep}`)
|
||||
? "public, max-age=31536000, immutable"
|
||||
: "no-cache";
|
||||
res.setHeader("Cache-Control", cacheControl);
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** Vite dev server (`npm -w client run dev`), calling the API cross-origin. */
|
||||
const DEV_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"];
|
||||
|
||||
/**
|
||||
* The port compose.yaml publishes. The UI is served from the same origin in
|
||||
* production, so these only matter for other tools calling the API from a
|
||||
* page on that origin; keep in sync with compose.yaml.
|
||||
*/
|
||||
const PRODUCTION_ORIGINS = ["http://localhost:13000", "http://127.0.0.1:13000"];
|
||||
|
||||
/**
|
||||
* Origins allowed to call the API cross-origin. `CORS_ORIGINS` (comma
|
||||
* separated) overrides the defaults, which depend on NODE_ENV: the compose
|
||||
* port in production, the Vite dev server otherwise.
|
||||
*/
|
||||
export function corsOrigins(nodeEnv: string, override: string): string[] {
|
||||
const configured = override
|
||||
.split(",")
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean);
|
||||
if (configured.length > 0) return configured;
|
||||
return nodeEnv === "production" ? PRODUCTION_ORIGINS : DEV_ORIGINS;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import * as https from "node:https";
|
||||
import * as http from "node:http";
|
||||
import { URL } from "node:url";
|
||||
|
||||
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
|
||||
const TIMEOUT_MS = 30000; // 30 seconds
|
||||
|
||||
function decodeDataUrl(urlStr: string): Buffer {
|
||||
const match = /^data:([^,]*),(.*)$/s.exec(urlStr);
|
||||
if (!match) {
|
||||
throw new Error("Malformed data: URL");
|
||||
}
|
||||
const [, meta, data] = match;
|
||||
if (meta.endsWith(";base64")) {
|
||||
return Buffer.from(data, "base64");
|
||||
}
|
||||
return Buffer.from(decodeURIComponent(data), "utf-8");
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
urlStr: string,
|
||||
options?: {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: string;
|
||||
},
|
||||
): Promise<Buffer> {
|
||||
if (urlStr.startsWith("data:")) {
|
||||
return decodeDataUrl(urlStr);
|
||||
}
|
||||
|
||||
const url = new URL(urlStr);
|
||||
const protocol = url.protocol === "https:" ? https : http;
|
||||
const method = options?.method ?? "GET";
|
||||
const headers = options?.headers ?? {};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
path: url.pathname + url.search,
|
||||
method,
|
||||
headers,
|
||||
timeout: TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
// Follow redirects
|
||||
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
downloadFile(res.headers.location, options).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.statusCode && res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let totalSize = 0;
|
||||
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
totalSize += chunk.length;
|
||||
if (totalSize > MAX_FILE_SIZE) {
|
||||
req.destroy();
|
||||
reject(new Error(`File exceeds maximum size of ${MAX_FILE_SIZE} bytes`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
|
||||
res.on("end", () => {
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
|
||||
res.on("error", reject);
|
||||
},
|
||||
);
|
||||
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
reject(new Error("Download timeout"));
|
||||
});
|
||||
|
||||
req.on("error", reject);
|
||||
|
||||
if (options?.body && (method === "POST" || method === "PUT")) {
|
||||
req.write(options.body);
|
||||
}
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/** Extracts the alias literals passed to `runSnippet("alias", ...)` calls in `code`. */
|
||||
export function extractRunSnippetAliases(code: string): string[] {
|
||||
const aliases: string[] = [];
|
||||
const regex = /runSnippet\s*\(\s*(['"`])((?:(?!\1).)*)\1/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = regex.exec(code)) !== null) {
|
||||
aliases.push(match[2]);
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the transitive closure of snippet aliases referenced (directly, or via
|
||||
* other snippets) by `stepCodes`, against the full alias -> code map. Aliases with
|
||||
* no matching entry in `snippetCodeByAlias` are dropped. Returned in discovery order.
|
||||
*/
|
||||
export function resolveUsedSnippetAliases(
|
||||
stepCodes: string[],
|
||||
snippetCodeByAlias: Record<string, string>,
|
||||
): string[] {
|
||||
const used: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const queue = stepCodes.flatMap((code) => extractRunSnippetAliases(code));
|
||||
while (queue.length > 0) {
|
||||
const alias = queue.shift()!;
|
||||
if (seen.has(alias)) continue;
|
||||
seen.add(alias);
|
||||
const code = snippetCodeByAlias[alias];
|
||||
if (code == null) continue;
|
||||
used.push(alias);
|
||||
queue.push(...extractRunSnippetAliases(code));
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a `runSnippet` reference into its alias and pinned version:
|
||||
* `"login@3"` → `{ alias: "login", version: 3 }`, `"login"` → `{ alias: "login", version: null }`.
|
||||
*/
|
||||
export function parseSnippetRef(ref: string): {
|
||||
alias: string;
|
||||
version: number | null;
|
||||
} {
|
||||
const match = /^(.+)@(\d+)$/.exec(ref);
|
||||
return match
|
||||
? { alias: match[1], version: Number(match[2]) }
|
||||
: { alias: ref, version: null };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AsyncLocalStorage } from "async_hooks";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
|
||||
export interface TraceStore {
|
||||
traceId: string;
|
||||
|
||||
@@ -1,26 +1,40 @@
|
||||
import { IsInt, IsString, Min, Max } from "class-validator";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
import {
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
validateSync,
|
||||
} from "class-validator";
|
||||
|
||||
import pkg from "../../package.json";
|
||||
import { appPackage } from "../common/app-package";
|
||||
|
||||
export enum TraceMode {
|
||||
On = "on",
|
||||
RetainOnFailure = "retain-on-failure",
|
||||
Off = "off",
|
||||
}
|
||||
|
||||
export class AppConfig {
|
||||
/** `production` in the Docker image; also selects the default CORS origins. */
|
||||
@IsString()
|
||||
NODE_ENV: string = "development";
|
||||
|
||||
/** Comma-separated origins allowed to call the API cross-origin; empty = default for NODE_ENV. */
|
||||
@IsString()
|
||||
CORS_ORIGINS: string = "";
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(65535)
|
||||
PORT: number = 3000;
|
||||
|
||||
@IsString()
|
||||
APP_NAME: string = pkg.name;
|
||||
APP_NAME: string = appPackage().name;
|
||||
|
||||
@IsString()
|
||||
APP_VERSION: string = pkg.version;
|
||||
|
||||
@IsString()
|
||||
KEYS_DIR: string = "keys";
|
||||
APP_VERSION: string = appPackage().version;
|
||||
|
||||
@IsString()
|
||||
DB_PATH: string = "data/liqa.db";
|
||||
@@ -32,6 +46,24 @@ export class AppConfig {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
SESSION_DELETE_CLOSED_DAYS: number = 7;
|
||||
|
||||
@IsString()
|
||||
FILES_DIR: string = "data/files";
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
FILE_RUN_EXPIRATION_DAYS: number = 7;
|
||||
|
||||
@IsString()
|
||||
FILE_CLEANUP_CRON: string = "0 3 * * *";
|
||||
|
||||
/** Directory with the built client to serve at `/`; empty to not serve it. */
|
||||
@IsString()
|
||||
CLIENT_DIR: string = "";
|
||||
|
||||
@IsEnum(TraceMode)
|
||||
// Off by default: traces with screenshots and snapshots easily reach ~10 MB per run
|
||||
PLAYWRIGHT_TRACE_MODE: TraceMode = TraceMode.Off;
|
||||
}
|
||||
|
||||
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
||||
|
||||
@@ -11,12 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { CredentialQueryDto } from "./dto/credential-query.dto";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
import { CredentialExportDto } from "./dto/credential-export.dto";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "./credential.service";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
|
||||
@ApiTags("credentials")
|
||||
@Controller("credentials")
|
||||
@@ -40,7 +39,7 @@ export class CredentialController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all credentials (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated credentials" })
|
||||
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
|
||||
findAll(@Query() query: CredentialQueryDto) {
|
||||
return this.credentialService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { CredentialController } from "./credential.controller";
|
||||
import { CredentialEntity } from "./credential.entity";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CredentialController } from "./credential.controller";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([CredentialEntity])],
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import {
|
||||
PaginatedResult,
|
||||
PaginationQueryDto,
|
||||
} from "../common/dto/pagination.dto";
|
||||
import { CredentialEntity } from "./credential.entity";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
import { CredentialExportDto } from "./dto/credential-export.dto";
|
||||
import {
|
||||
PaginationQueryDto,
|
||||
PaginatedResult,
|
||||
} from "../common/dto/pagination.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
|
||||
export type CredentialOrderBy =
|
||||
| "id"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "../credential.service";
|
||||
|
||||
const CREDENTIAL_ORDER_BY: CredentialOrderBy[] = ["id", "name", "lastUsedAt"];
|
||||
|
||||
export class CredentialQueryDto extends PaginationQueryDto<CredentialOrderBy> {
|
||||
@ApiPropertyOptional({ enum: CREDENTIAL_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(CREDENTIAL_ORDER_BY)
|
||||
declare orderBy?: CredentialOrderBy;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as fs from "node:fs";
|
||||
import { DataSource, type DataSourceOptions } from "typeorm";
|
||||
import { validateAppConfig } from "../config/app.config";
|
||||
import { ENTITIES } from "./entities";
|
||||
import { MIGRATIONS } from "./migrations";
|
||||
|
||||
/**
|
||||
* TypeORM options shared by the app, the migration runner and the TypeORM
|
||||
* CLI. The schema is managed by migrations only (`synchronize: false`).
|
||||
*/
|
||||
export function dataSourceOptions(database: string): DataSourceOptions {
|
||||
return {
|
||||
type: "better-sqlite3",
|
||||
database,
|
||||
entities: ENTITIES,
|
||||
migrations: MIGRATIONS,
|
||||
synchronize: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Outside Nest (migration runner, TypeORM CLI) nothing loads .env; load it
|
||||
// like ConfigModule does: optional, and without overriding set variables
|
||||
if (fs.existsSync(".env")) process.loadEnvFile(".env");
|
||||
|
||||
/**
|
||||
* Data source for the TypeORM CLI and `migrate.ts`, using DB_PATH from the
|
||||
* environment or .env (default `data/liqa.db`).
|
||||
*/
|
||||
export default new DataSource(
|
||||
dataSourceOptions(validateAppConfig(process.env).DB_PATH),
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
import { FileEntity } from "../file/file.entity";
|
||||
import { ScenarioFileEntity } from "../file/scenario-file.entity";
|
||||
import { ScenarioRunFileEntity } from "../file/scenario-run-file.entity";
|
||||
import { ScenarioCredentialEntity } from "../scenario/scenario-credential.entity";
|
||||
import { ScenarioRunLogEntity } from "../scenario/scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "../scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "../scenario/scenario-run.entity";
|
||||
import { ScenarioStepEntity } from "../scenario/scenario-step.entity";
|
||||
import { ScenarioVersionEntity } from "../scenario/scenario-version.entity";
|
||||
import { ScenarioEntity } from "../scenario/scenario.entity";
|
||||
import { SessionEntity } from "../session/session.entity";
|
||||
import { SnippetVersionEntity } from "../snippet/snippet-version.entity";
|
||||
import { SnippetEntity } from "../snippet/snippet.entity";
|
||||
|
||||
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
|
||||
export const ENTITIES = [
|
||||
SessionEntity,
|
||||
EnvironmentEntity,
|
||||
CredentialEntity,
|
||||
ScenarioEntity,
|
||||
ScenarioStepEntity,
|
||||
ScenarioVersionEntity,
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
SnippetEntity,
|
||||
SnippetVersionEntity,
|
||||
FileEntity,
|
||||
ScenarioFileEntity,
|
||||
ScenarioRunFileEntity,
|
||||
];
|
||||
@@ -0,0 +1,24 @@
|
||||
import dataSource from "./data-source";
|
||||
|
||||
/**
|
||||
* Applies pending migrations to the database at DB_PATH, then exits. Runs
|
||||
* before the server in the Docker image (`node dist/database/migrate`).
|
||||
*/
|
||||
async function migrate(): Promise<void> {
|
||||
await dataSource.initialize();
|
||||
try {
|
||||
const applied = await dataSource.runMigrations({ transaction: "each" });
|
||||
console.log(
|
||||
applied.length > 0
|
||||
? `Applied ${applied.length} migration(s): ${applied.map((m) => m.name).join(", ")}`
|
||||
: "Database schema is up to date",
|
||||
);
|
||||
} finally {
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
migrate().catch((err: unknown) => {
|
||||
console.error("Migration failed:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
/**
|
||||
* Initial schema. Databases created before migrations existed (by TypeORM
|
||||
* `synchronize`) already have this schema: for them this migration only gets
|
||||
* recorded as applied, and later migrations run from there.
|
||||
*/
|
||||
export class Initial1790793447827 implements MigrationInterface {
|
||||
name = "Initial1790793447827";
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
if (await queryRunner.hasTable("scenarios")) return;
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "credentials" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "data" text, "lastUsedAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "environments" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "data" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_9d00da4836959b86d7590f60c57" UNIQUE ("name"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "files" ("id" varchar PRIMARY KEY NOT NULL, "originalName" varchar NOT NULL, "mimeType" varchar NOT NULL, "size" integer NOT NULL, "sha256" varchar NOT NULL, "filePath" varchar NOT NULL, "expiresAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "sessions" ("id" varchar PRIMARY KEY NOT NULL, "sessionName" varchar NOT NULL, "token" text NOT NULL, "cookies" text NOT NULL, "localStorage" text NOT NULL DEFAULT ('{}'), "status" varchar NOT NULL DEFAULT ('closed'), "lastUsedAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_b8f17f1ce30f015f494188c50bb" UNIQUE ("sessionName"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "snippets" ("id" varchar PRIMARY KEY NOT NULL, "alias" varchar, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_bd062c68591ae917b720eb3427c" UNIQUE ("alias"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"), CONSTRAINT "FK_37f19dadd8e524b22a807ece1a9" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_96676b988693d5ca2923782530c" FOREIGN KEY ("credentialId") REFERENCES "credentials" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_credentials"("id", "scenarioId", "credentialId", "alias", "createdAt") SELECT "id", "scenarioId", "credentialId", "alias", "createdAt" FROM "scenario_credentials"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_credentials"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_credentials" RENAME TO "scenario_credentials"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_4bab3637cc3bf37677bb01c7446" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_steps"("id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt") SELECT "id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt" FROM "scenario_steps"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_steps"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_steps" RENAME TO "scenario_steps"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_ffdcf9186d95114f0dab068e20a" FOREIGN KEY ("environmentId") REFERENCES "environments" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenarios"("id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt") SELECT "id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt" FROM "scenarios"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenarios"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenarios" RENAME TO "scenarios"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_c41719984235f8984d1c6b92ef5" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_67013a49e7948fb530a7d956e2b" FOREIGN KEY ("fileId") REFERENCES "files" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_files"("id", "scenarioId", "fileId", "createdAt") SELECT "id", "scenarioId", "fileId", "createdAt" FROM "scenario_files"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_files"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_files" RENAME TO "scenario_files"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_213c27405af3433011121babb58" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_e84cd4c7725bdc5dfd09d18d92f" FOREIGN KEY ("scenarioStepId") REFERENCES "scenario_steps" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_run_steps"("id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt") SELECT "id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt" FROM "scenario_run_steps"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_steps"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_run_steps" RENAME TO "scenario_run_steps"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_1d2c2595dfff133de062f9c692a" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_5076ffbd1b4fa71f5de011eba1f" FOREIGN KEY ("environmentId") REFERENCES "environments" ("id") ON DELETE SET NULL ON UPDATE NO ACTION, CONSTRAINT "FK_068b01cdfa49095433f245d6708" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_runs"("id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt") SELECT "id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt" FROM "scenario_runs"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_runs"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_runs" RENAME TO "scenario_runs"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_5fc35a4bfc42d7566a0f7706902" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_637619025bdb0b6a89fae6e178d" FOREIGN KEY ("fileId") REFERENCES "files" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_run_files"("id", "runId", "fileId", "createdAt") SELECT "id", "runId", "fileId", "createdAt" FROM "scenario_run_files"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_files"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_run_files" RENAME TO "scenario_run_files"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_dde48478a42823e583a360dd468" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_62d82b9fce3a6a2947ed1136c67" FOREIGN KEY ("stepRunId") REFERENCES "scenario_run_steps" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_run_logs"("id", "runId", "stepRunId", "level", "message", "seq", "createdAt") SELECT "id", "runId", "stepRunId", "level", "message", "seq", "createdAt" FROM "scenario_run_logs"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_logs"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_run_logs" RENAME TO "scenario_run_logs"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"), CONSTRAINT "FK_f5ccfb45c7847cfab74cf4f17b6" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_scenario_versions"("id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt") SELECT "id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt" FROM "scenario_versions"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "scenario_versions"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_scenario_versions" RENAME TO "scenario_versions"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"), CONSTRAINT "FK_0d3a004957c9553619be11635fd" FOREIGN KEY ("snippetId") REFERENCES "snippets" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_snippet_versions"("id", "snippetId", "version", "alias", "title", "description", "code", "createdAt") SELECT "id", "snippetId", "version", "alias", "title", "description", "code", "createdAt" FROM "snippet_versions"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "snippet_versions"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_snippet_versions" RENAME TO "snippet_versions"`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "snippet_versions" RENAME TO "temporary_snippet_versions"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "snippet_versions"("id", "snippetId", "version", "alias", "title", "description", "code", "createdAt") SELECT "id", "snippetId", "version", "alias", "title", "description", "code", "createdAt" FROM "temporary_snippet_versions"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_snippet_versions"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_versions" RENAME TO "temporary_scenario_versions"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_versions"("id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt") SELECT "id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt" FROM "temporary_scenario_versions"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_versions"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_run_logs" RENAME TO "temporary_scenario_run_logs"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_run_logs"("id", "runId", "stepRunId", "level", "message", "seq", "createdAt") SELECT "id", "runId", "stepRunId", "level", "message", "seq", "createdAt" FROM "temporary_scenario_run_logs"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_run_logs"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_run_files" RENAME TO "temporary_scenario_run_files"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_run_files"("id", "runId", "fileId", "createdAt") SELECT "id", "runId", "fileId", "createdAt" FROM "temporary_scenario_run_files"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_run_files"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_runs" RENAME TO "temporary_scenario_runs"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_runs"("id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt") SELECT "id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt" FROM "temporary_scenario_runs"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_runs"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_run_steps" RENAME TO "temporary_scenario_run_steps"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_run_steps"("id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt") SELECT "id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt" FROM "temporary_scenario_run_steps"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_run_steps"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_files" RENAME TO "temporary_scenario_files"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_files"("id", "scenarioId", "fileId", "createdAt") SELECT "id", "scenarioId", "fileId", "createdAt" FROM "temporary_scenario_files"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_files"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenarios" RENAME TO "temporary_scenarios"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenarios"("id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt") SELECT "id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt" FROM "temporary_scenarios"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenarios"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_steps" RENAME TO "temporary_scenario_steps"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_steps"("id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt") SELECT "id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt" FROM "temporary_scenario_steps"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_steps"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "scenario_credentials" RENAME TO "temporary_scenario_credentials"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"))`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "scenario_credentials"("id", "scenarioId", "credentialId", "alias", "createdAt") SELECT "id", "scenarioId", "credentialId", "alias", "createdAt" FROM "temporary_scenario_credentials"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_scenario_credentials"`);
|
||||
await queryRunner.query(`DROP TABLE "snippet_versions"`);
|
||||
await queryRunner.query(`DROP TABLE "snippets"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_versions"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_logs"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_files"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_runs"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_run_steps"`);
|
||||
await queryRunner.query(`DROP TABLE "sessions"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_files"`);
|
||||
await queryRunner.query(`DROP TABLE "scenarios"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_steps"`);
|
||||
await queryRunner.query(`DROP TABLE "scenario_credentials"`);
|
||||
await queryRunner.query(`DROP TABLE "files"`);
|
||||
await queryRunner.query(`DROP TABLE "environments"`);
|
||||
await queryRunner.query(`DROP TABLE "credentials"`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Initial1790793447827 } from "./1790793447827-Initial";
|
||||
|
||||
/**
|
||||
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
||||
* same list works from compiled JS, ts-jest and the TypeORM CLI.
|
||||
*/
|
||||
export const MIGRATIONS = [Initial1790793447827];
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsString } from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsOptional, IsString } from "class-validator";
|
||||
import { EnvironmentData } from "../environment.entity";
|
||||
|
||||
export class CreateEnvironmentDto {
|
||||
@@ -8,6 +8,11 @@ export class CreateEnvironmentDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: "Generic key-value map for environment metadata",
|
||||
example: {
|
||||
|
||||
@@ -25,6 +25,11 @@ export class EnvironmentExportDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsObject()
|
||||
data: EnvironmentData;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { EnvironmentOrderBy } from "../environment.service";
|
||||
|
||||
const ENVIRONMENT_ORDER_BY: EnvironmentOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
|
||||
|
||||
export class EnvironmentQueryDto extends PaginationQueryDto<EnvironmentOrderBy> {
|
||||
@ApiPropertyOptional({ enum: ENVIRONMENT_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(ENVIRONMENT_ORDER_BY)
|
||||
declare orderBy?: EnvironmentOrderBy;
|
||||
}
|
||||
@@ -11,12 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { EnvironmentService } from "./environment.service";
|
||||
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { EnvironmentOrderBy } from "./environment.service";
|
||||
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
||||
import { EnvironmentService } from "./environment.service";
|
||||
|
||||
@ApiTags("environments")
|
||||
@Controller("environments")
|
||||
@@ -41,7 +40,7 @@ export class EnvironmentController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all environments (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated environments" })
|
||||
findAll(@Query() query: PaginationQueryDto<EnvironmentOrderBy>) {
|
||||
findAll(@Query() query: EnvironmentQueryDto) {
|
||||
return this.environmentService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
@@ -18,6 +18,9 @@ export class EnvironmentEntity {
|
||||
@Column({ unique: true })
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column("simple-json")
|
||||
data: EnvironmentData;
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { EnvironmentController } from "./environment.controller";
|
||||
import { EnvironmentEntity } from "./environment.entity";
|
||||
import { EnvironmentService } from "./environment.service";
|
||||
import { EnvironmentController } from "./environment.controller";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([EnvironmentEntity])],
|
||||
|
||||
@@ -5,14 +5,14 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { EnvironmentEntity } from "./environment.entity";
|
||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||
import {
|
||||
PaginationQueryDto,
|
||||
PaginatedResult,
|
||||
PaginationQueryDto,
|
||||
} from "../common/dto/pagination.dto";
|
||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
||||
import { EnvironmentEntity } from "./environment.entity";
|
||||
|
||||
export type EnvironmentOrderBy = "id" | "name" | "createdAt" | "updatedAt";
|
||||
|
||||
@@ -71,26 +71,47 @@ export class EnvironmentService {
|
||||
kind: "environment",
|
||||
id: env.id,
|
||||
name: env.name,
|
||||
description: env.description ?? undefined,
|
||||
data: env.data,
|
||||
};
|
||||
}
|
||||
|
||||
async importEnvironment(dto: EnvironmentExportDto): Promise<EnvironmentEntity> {
|
||||
async importEnvironment(
|
||||
dto: EnvironmentExportDto,
|
||||
): Promise<EnvironmentEntity> {
|
||||
if (dto.id) {
|
||||
const existing = await this.repo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
Object.assign(existing, { name: dto.name, data: dto.data });
|
||||
Object.assign(existing, {
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
return this.repo.save(
|
||||
this.repo.create({ id: dto.id, name: dto.name, data: dto.data }),
|
||||
this.repo.create({
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const byName = await this.repo.findOneBy({ name: dto.name });
|
||||
if (byName) {
|
||||
Object.assign(byName, { data: dto.data });
|
||||
Object.assign(byName, {
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(byName);
|
||||
}
|
||||
return this.repo.save(this.repo.create({ name: dto.name, data: dto.data }));
|
||||
return this.repo.save(
|
||||
this.repo.create({
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user