Compare commits

...
77 Commits
Author SHA1 Message Date
c0fe15dc01 Keep test output quiet with opt-in diagnostic logs (#25)
CI / changes (push) Successful in 4s
CI / server (push) Failing after 1h44m8s
CI / client (push) Successful in 1m52s
CI / image (push) Skipped
Test runs stay quiet by default. Diagnostic logs can be enabled explicitly when troubleshooting, while normal application logging and saved scenario output remain available.

Resolves #22.

---------

Co-authored-by: ars9 <ars9@pm.me>
Co-authored-by: agent <agent@halstation.halstation.local>
Reviewed-on: #25
Co-authored-by: agent-codex <agent-codex@ars9.space>
2026-11-11 22:23:44 +02:00
ars9 8b48d4812d Merge pull request 'feat(auth): deliver optional authentication across Liqa' (#24) from agent-codex/liqa:master into master
CI / changes (push) Successful in 31s
CI / server (push) Failing after 1h42m43s
CI / client (push) Successful in 2m55s
CI / image (push) Skipped
Reviewed-on: #24
2026-11-11 19:35:12 +02:00
ars9 ff9a700c86 Merge pull request 'test(auth): cover integrated account journey' (#6) from feat/task-57-auth-integration into master
CI / changes (pull_request) Canceled after 0s
CI / server (pull_request) Canceled after 0s
CI / client (pull_request) Canceled after 0s
CI / image (pull_request) Canceled after 0s
Reviewed-on: agent-codex/liqa#6
2026-11-09 23:25:48 +02:00
ars9 ea4f72c236 Merge pull request 'docs(auth): document optional authentication setup' (#5) from feat/task-56-auth-documentation into master
Reviewed-on: agent-codex/liqa#5
2026-11-09 23:24:38 +02:00
agent 9ff9579a7b test(auth): cover integrated account journey
- Exercise CLI provisioning through browser/API/MCP auth, run events, logout, and deletion.
- Allow integration coverage to reopen the same file-backed test database.
2026-11-09 15:58:49 -05:00
agent 9bdba32a34 docs(auth): document optional authentication setup
- Explain opt-in configuration, protected surfaces, migrations and cookie behavior.
- Document operator CLI, MCP bearer use, cleanup, and supported local origins.
2026-11-09 15:50:12 -05:00
ars9 d4d9bceb98 Merge pull request 'feat(auth): add operator account CLI' (#4) from feat/task-53-operator-cli-refresh into master
Reviewed-on: agent-codex/liqa#4
2026-11-09 22:35:48 +02:00
agent 768a799db0 feat(auth): add operator account CLI
- Add local and container-ready user management and token commands.
- Document setup and verify commands against an isolated database.
2026-11-09 14:31:29 -05:00
ars9 fe19fb9d56 Merge pull request 'feat(client): add cookie-backed browser authentication' (#3) from fix/task-55-authenticated-eventsource-repair-2 into master
Reviewed-on: agent-codex/liqa#3
2026-11-09 21:21:20 +02:00
agent f2bcbe07b6 fix(client): clarify login form styling
- Add spacing for the session-expired notice and distinguish login inputs.
- Assert those surfaces in expired-session light and dark stories.
2026-11-09 14:07:59 -05:00
agent 8676d6281c fix(client): focus password after invalid login
- Defer focus until submission finishes and the password field is cleared.
2026-11-05 04:32:25 -05:00
agent 92141a25fb feat(client): add cookie-backed authentication UI
- Add session-aware login, logout and protected navigation.
- Send cookie credentials for API and run-event requests with localized UI stories.
2026-11-05 04:18:11 -05:00
ars9 9e4b692444 Merge pull request 'feat(auth): clean expired revoked tokens' (#2) from feat/task-54-revocation-cleanup into master
Reviewed-on: agent-codex/liqa#2
2026-11-05 11:12:51 +02:00
agent 2976a08aef feat(auth): clean expired revoked tokens
- Remove expired token revocations at startup and on the configured cron.
- Verify expiry boundaries and disabled-auth behavior.
2026-11-05 02:48:53 -05:00
ars9 c3e8670515 Merge pull request 'feat(auth): add optional authentication' (#1) from feat/task-52-optional-auth-server into master
Reviewed-on: agent-codex/liqa#1
2026-11-05 00:31:56 +02:00
agent 1830feb71b refactor(auth): address server review feedback
- Extract auth DTOs, cookie/JWT helpers and the generic duration parser.
- Configure the session cookie and map domain auth failures to HTTP responses.
- Add typed Swagger responses and focused regression coverage.
2026-11-04 17:15:00 -05:00
agent 72e127888c fix(auth): redact passwords on normalized login paths
CI / changes (pull_request) Canceled after 0s
CI / server (pull_request) Canceled after 0s
CI / client (pull_request) Canceled after 0s
CI / image (pull_request) Canceled after 0s
- Normalize login paths before applying request-body redaction.
- Cover trailing-slash paths and assert the password never reaches logs.
2026-11-04 15:59:49 -05:00
agent de41571b5c feat(auth): add optional authentication boundary
- Add account, JWT session, revocation, cookie and bearer handling.
- Protect server surfaces while preserving public health, manifest and disabled mode.
- Add SQLite migration and focused server regression coverage.
2026-11-04 15:43:33 -05:00
ars9 d4bb274982 chore(release): cut minor release
CI / changes (push) Skipped
CI / server (push) Failing after 34m15s
CI / client (push) Successful in 2m43s
CI / image (push) Skipped
- bump version to 1.26.0
- add versioned e2e test export to the changelog
2026-10-08 18:54:34 +03:00
ars9 969f24ea73 Merge pull request 'feat: export e2e tests for a chosen scenario version' (#21) from feat/e2e-export-version into master
CI / changes (push) Successful in 16s
CI / server (push) Successful in 1m32s
CI / client (push) Successful in 1m32s
CI / image (push) Skipped
Reviewed-on: #21
2026-10-08 18:53:26 +03:00
ars9 81164f8494 feat: export e2e tests for a chosen scenario version
CI / changes (pull_request) Successful in 14s
CI / server (pull_request) Successful in 2m25s
CI / client (pull_request) Successful in 1m35s
CI / image (pull_request) Skipped
- GET /scenarios/:id/export-e2e and the export_e2e_test MCP tool take
  an optional version, defaulting to the latest
- build the test project from that version's steps, name and timeout
- put the version in the zip name (<scenario>-vN-e2e-test.zip), the
  generated package name and the README heading
- the Export e2e test button exports the version being viewed
- document the e2e export in scenario.md and mcp.md
2026-10-08 18:37:33 +03:00
ars9 14763103cf chore(release): cut minor release
CI / server (push) Successful in 1m7s
CI / changes (push) Skipped
CI / client (push) Successful in 1m23s
CI / image (push) Successful in 1m59s
- bump version to 1.25.0
- add browser notifications for scenario runs to the changelog
2026-10-07 19:23:01 +03:00
ars9 78f4c35d56 docs(claude): forbid co-author trailers and issue refs in commits
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Skipped
CI / image (push) Skipped
- keep issue references like Closes #12 for pull request descriptions
2026-10-07 19:22:02 +03:00
ars9 4b050fbdc4 Merge pull request 'Browser notifications' (#14) from feat/browser-notifications into master
CI / changes (push) Successful in 6s
CI / server (push) Successful in 3m4s
CI / client (push) Successful in 1m33s
CI / image (push) Skipped
Reviewed-on: #14
2026-10-07 19:20:59 +03:00
ars9 a93b3ef835 fix(client): keep run notifications connected in Firefox
CI / changes (pull_request) Successful in 6s
CI / server (pull_request) Successful in 1m16s
CI / client (pull_request) Successful in 1m28s
CI / image (pull_request) Skipped
- reopen the run events stream with backoff when the browser closes it for good (Firefox drops quiet connections after a network change)
- enable notifications when the permission is granted outside the bell, unless turned off explicitly
- follow permission changes made in the browser's site settings
- highlight the bell while notifications are on
2026-10-07 19:04:59 +03:00
ars9 d7eb018245 feat: browser notifications for scenario runs
- add RunEventsService and emit run.started / run.finished from the scheduler
- stream run events over SSE at GET /api/v1/scenarios/runs/events with a heartbeat
- add useRunNotifications hook and NotificationToggle (opt-in bell in the side panel footer)
- refresh runs lists when a run finishes
- document the events stream and notifications

Closes #12
2026-10-07 18:20:30 +03:00
ars9 968a8e470b chore(release): cut patch release
CI / server (push) Successful in 1m14s
CI / changes (push) Skipped
CI / client (push) Successful in 1m23s
CI / image (push) Successful in 1m52s
- bump version to 1.24.4
- add changelog entry for versioned export filenames and the
  install script terminal fix
2026-10-07 17:38:11 +03:00
ars9 3c8def3814 Merge pull request 'feat(client): include version in exported scenario and snippet filenames' (#13) from feat/export-version-filename into master
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Successful in 1m15s
CI / image (push) Skipped
Reviewed-on: #13
2026-10-07 17:36:55 +03:00
ars9 6e5da08719 feat(client): include version in exported scenario and snippet filenames
CI / changes (pull_request) Successful in 10s
CI / server (pull_request) Skipped
CI / client (pull_request) Successful in 1m21s
CI / image (pull_request) Skipped
- request the exact version being exported via ?version=N so file
  content always matches the filename
- name downloads <scenario>-v<N>.yaml and snippet-<alias>-v<N>.yaml
2026-10-07 17:34:21 +03:00
ars9 1abd95f9e1 Merge pull request 'fix(install): read prompts from the terminal and start liqa' (#11) from fix/install-tty into master
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Skipped
CI / image (push) Skipped
Reviewed-on: #11
2026-10-02 15:53:43 +03:00
ars9 d7476f0fe8 fix(install): read prompts from the terminal and start liqa
CI / changes (pull_request) Successful in 7s
CI / server (pull_request) Skipped
CI / client (pull_request) Skipped
CI / image (pull_request) Skipped
- read answers from /dev/tty: under `curl ... | bash` stdin is the
  script itself, so `read` consumed the script's own lines; fall back
  to defaults when there is no terminal
- check that docker, the compose plugin and the daemon work and that
  compose accepts the generated compose.yaml
- start liqa with `docker compose up -d` in the install directory,
  printing the manual start command if a check or the start fails
2026-10-02 15:53:16 +03:00
ars9 75bb0af9fd chore: self-test example and tag-only image builds
CI / server (push) Successful in 1m7s
CI / changes (push) Skipped
CI / client (push) Successful in 1m15s
CI / image (push) Successful in 1m58s
- examples/self-test: importable scenario, snippets, credential and
  environment that test the liqa instance they run on
- CI builds the Docker image only for vX.Y.Z release tags
- bump version to 1.24.3
2026-10-02 15:43:31 +03:00
ars9 0c11e11c27 Merge pull request 'feat(examples): add self-test example' (#10) from feat/examples into master
CI / changes (push) Successful in 6s
CI / client (push) Skipped
CI / server (push) Successful in 1m6s
CI / image (push) Skipped
Reviewed-on: #10
2026-10-02 15:42:19 +03:00
ars9 c1924060eb feat(examples): add self-test example
CI / changes (pull_request) Successful in 7s
CI / client (pull_request) Skipped
CI / server (pull_request) Successful in 1m7s
CI / image (pull_request) Skipped
- add examples/ with a ready-to-import self-test: environment, credential,
  snippets and a scenario that creates, runs and checks another scenario
  through the liqa REST API and UI, then cleans up
- add test/examples.spec.ts: imports every example and parses its code
- link the examples from README, docs/scenario.md and CLAUDE.md

Closes #6
2026-10-02 15:39:02 +03:00
ars9 28dfce246a Merge pull request 'ci: build docker images only on release tags' (#9) from chore/release-on-tags into master
CI / changes (push) Successful in 7s
CI / server (push) Successful in 1m12s
CI / client (push) Successful in 1m21s
CI / image (push) Skipped
Reviewed-on: #9
2026-10-02 14:37:34 +03:00
ars9 a0624789ce ci: build docker images only on release tags
CI / changes (pull_request) Successful in 6s
CI / server (pull_request) Successful in 1m19s
CI / client (pull_request) Successful in 1m26s
CI / image (pull_request) Skipped
- trigger the image job on vX.Y.Z tag pushes instead of master pushes
- run server and client checks unconditionally on tags before the build
- fail the build when the tag doesn't match the package.json version
- document the release routine: version bump, changelog and tag are
  done on master after work branches are merged
2026-10-02 14:36:59 +03:00
ars9 a8d00056ff chore: run log data collapsing and client manifest
CI / changes (push) Successful in 6s
CI / version (push) Successful in 7s
CI / server (push) Successful in 1m17s
CI / client (push) Successful in 1m14s
CI / image (push) Successful in 1m58s
- large run log data blocks start collapsed, with per-block and
  expand/collapse-all toggles; limits set by RUN_LOG_DATA_COLLAPSE_BYTES
  and RUN_LOG_DATA_COLLAPSE_LINES
- copy logs button copies the filtered logs as plain text
- GET /manifest.json serves the app version and public client settings,
  cached by the UI in localStorage
- bump version to 1.24.2
2026-10-02 14:16:02 +03:00
ars9 639b80f468 Merge pull request 'feat(logs): collapse large run log data and serve client manifest' (#8) from feat/log-data-collapse into master
CI / changes (push) Successful in 7s
CI / version (push) Successful in 7s
CI / server (push) Successful in 1m13s
CI / client (push) Successful in 1m28s
CI / image (push) Skipped
Reviewed-on: #8
2026-10-02 14:12:54 +03:00
ars9 718a12c2f4 feat(logs): collapse large run log data and serve client manifest
CI / changes (pull_request) Successful in 6s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m30s
CI / client (pull_request) Successful in 1m31s
CI / image (pull_request) Skipped
- collapse run log data blocks whose pretty-printed JSON exceeds a byte
  or line limit, with a per-block toggle and an expand/collapse-all
  button next to the Logs heading
- align data blocks and toggles with the context/message column
- add a "Copy logs" button that copies the filtered logs as plain text
  with every data block expanded
- add GET /manifest.json with the app name, version and run log data
  limits (RUN_LOG_DATA_COLLAPSE_BYTES / RUN_LOG_DATA_COLLAPSE_LINES)
- load the manifest in the client stale-while-revalidate: localStorage
  copy first, refetched per page load and on tab focus after a while
- show the server version in the sidebar footer, with a reload hint
  when it differs from the client build

Closes #3
2026-10-02 14:05:49 +03:00
ars9 4e55d14599 chore: step output and assertion log data
CI / changes (push) Successful in 14s
CI / version (push) Successful in 12s
CI / server (push) Successful in 1m17s
CI / client (push) Successful in 1m18s
CI / image (push) Successful in 1m49s
- "Step N passed" log entries carry the step's return value as data
- context.assert takes an optional details argument stored as log data
  on failure; step and snippet failure entries name only the assertion
- log output shows elapsed time in whole seconds
- run artifact and scenario file names open the file in a new tab
- bump version to 1.24.1
2026-10-02 11:12:12 +03:00
ars9 0f84db57f1 Merge pull request 'feat(scenario): attach step output and assertion details to run log' (#7) from feat/step-assert-log-data into master
CI / changes (push) Successful in 6s
CI / version (push) Successful in 8s
CI / server (push) Successful in 1m25s
CI / client (push) Successful in 1m16s
CI / image (push) Skipped
Reviewed-on: #7
2026-10-02 11:09:52 +03:00
ars9 959b3b70c9 feat(scenario): attach step output and assertion details to run log
CI / changes (pull_request) Successful in 9s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m44s
CI / client (pull_request) Successful in 1m36s
CI / image (pull_request) Skipped
- "Step N passed" log entry carries the step's return value as data
- context.assert accepts an optional details argument; on failure the
  assertion:fail entry stores { details, error } as data
- assertion failures throw AssertionFailedError so "Step N failed" and
  "Snippet X failed" entries name only the assertion, without repeating
  the details; the step run description keeps the full message
- exported e2e runtime accepts and prints assert details
- log output shows elapsed time in whole seconds, matching the stored
  timestamp resolution
- run artifact and scenario file names link to the inline file content
  in a new tab
2026-10-02 11:05:29 +03:00
ars9 2281a8729b chore: code reference modal
CI / changes (push) Successful in 6s
CI / version (push) Successful in 6s
CI / server (push) Successful in 1m24s
CI / client (push) Successful in 1m34s
CI / image (push) Successful in 1m57s
- step and snippet editors open a reference of the script runtime and
  its context API from a (?) button next to the Code label
- bump version to 1.24.0
2026-10-01 14:50:23 +03:00
ars9 e3c2c0cebb Merge pull request 'feat(client): add code reference modal to step and snippet editors' (#4) from feat/code-context-help into master
CI / changes (push) Successful in 5s
CI / server (push) Skipped
CI / version (push) Successful in 5s
CI / client (push) Successful in 1m18s
CI / image (push) Skipped
Reviewed-on: #4
2026-10-01 14:48:35 +03:00
ars9 daecf3d539 feat(client): add code reference modal to step and snippet editors
CI / changes (pull_request) Successful in 7s
CI / version (pull_request) Skipped
CI / server (pull_request) Skipped
CI / client (pull_request) Successful in 1m13s
CI / image (pull_request) Skipped
- a (?) button next to the Code label on the step and snippet
  create/edit pages opens a reference of the script runtime: globals,
  every context member with examples, and pitfalls such as awaiting
  getStepOutput and assert
- the reference lives in components/modals/code-help.md and is
  rendered as markdown
- Modal takes size="lg" for document-like content; the dialog is
  capped to the viewport and its body scrolls, focusable when lg so
  the keyboard can scroll it
- docs/scenario.md notes that getStepOutput is async and points to
  the in-app reference to keep in sync
2026-10-01 14:45:03 +03:00
ars9 71259bc11d chore: run log context, data and debug level
CI / changes (push) Successful in 6s
CI / version (push) Successful in 6s
CI / server (push) Successful in 1m9s
CI / client (push) Successful in 1m17s
CI / image (push) Successful in 1m48s
- scenario run log entries carry a context (step/snippet/assertion/run)
  and a data payload split out from the message, plus a new debug level
- run detail page shows the full log list in a terminal-style viewer
  instead of a paginated table
- bump version to 1.23.0
2026-10-01 14:24:01 +03:00
ars9 d085ea3ded Merge pull request 'Add log context and data' (#2) from feat/run-log-context into master
CI / changes (push) Successful in 6s
CI / version (push) Successful in 7s
CI / server (push) Successful in 1m4s
CI / client (push) Successful in 1m22s
CI / image (push) Skipped
Reviewed-on: #2
2026-10-01 14:19:39 +03:00
ars9 1273491eee feat(scenario): split log args into message/data and add debug level
CI / changes (pull_request) Successful in 12s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m4s
CI / client (pull_request) Successful in 1m33s
CI / image (pull_request) Skipped
- context.log/warn/error and console.* split arguments: strings join
  into message, object/array args are kept out of it and stored as
  the log entry's new data column (JSON), so message stays a stable
  string regardless of an object's shape
- added a debug log level alongside log/warn/error, including
  context.debug() and console.debug() (previously folded into log)
- CSV/Markdown run log export include the data column/block
- LogOutput renders data pretty-printed in a separate block below
  the message, and dims debug entries with a dedicated grey token
  calibrated to the WCAG AA contrast floor
2026-10-01 14:09:45 +03:00
ars9 6cba785e2f feat(scenario): tag run log entries with their context
- scenario_run_logs gains a context column (step:N, snippet:alias,
  assertion:pass/fail, run), tracked through a call stack in
  CodeExecutorService so nested runSnippet calls tag their own and
  inner log lines
- automatic step started/passed/failed entries and the Playwright
  trace upload notice are tagged accordingly
- run log export (CSV/Markdown) and the logs search match context
  as well as message
- add a LogOutput UI component: a terminal-style log viewer with
  level color coding, elapsed-time-since-start timestamps and a
  context tag, replacing the generic Table on the run detail page
- show the full log list instead of paginating it, capped to a
  scrollable block
- fix migrations.spec.ts's revert test, which only undid the last
  migration instead of all of them
2026-10-01 13:26:07 +03:00
ars9 5152fffe82 Merge pull request 'Chore/ci path filters and registry version check' (#1) from chore/ci-path-filters-and-registry-version-check into master
CI / changes (push) Successful in 6s
CI / version (push) Successful in 6s
CI / server (push) Successful in 1m24s
CI / client (push) Successful in 1m15s
CI / image (push) Skipped
Reviewed-on: #1
2026-10-01 12:30:58 +03:00
ars9 9df8a652dc ci: guard image job with an explicit push-event check
CI / changes (pull_request) Successful in 7s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m6s
CI / client (pull_request) Successful in 1m20s
CI / image (pull_request) Skipped
- defense in depth alongside the version job's existing push-only
  condition, so the image job can't run on pull requests
2026-10-01 12:29:08 +03:00
ars9 e577ee8683 ci: skip unaffected jobs and rebuilt image versions
CI / changes (pull_request) Successful in 11s
CI / version (pull_request) Skipped
CI / server (pull_request) Successful in 1m10s
CI / client (pull_request) Successful in 1m23s
CI / image (pull_request) Skipped
- server and client jobs only run when their directory (or shared
  root files) changed, via a new changes job using dorny/paths-filter
- the version job now checks the registry for an existing image tag
  of the current package.json version instead of diffing against the
  previous commit's package.json, so the image job is skipped once
  that version has already been pushed
- the image job tolerates server/client being skipped rather than
  requiring both to succeed
2026-10-01 12:26:57 +03:00
ars9 0e998333e0 docs(claude): require a branch for features, chores and fixes
- master is reserved for version-bump release commits
2026-10-01 12:23:09 +03:00
ars9 2840df68b2 docs: add quick install script and README section
CI / server (push) Successful in 1m39s
CI / client (push) Successful in 1m23s
CI / version (push) Successful in 7s
CI / image (push) Skipped
- scripts/install.sh prompts for install directory, port and version,
  then writes a compose.yaml using the published registry image and
  creates a data/ directory for the SQLite volume
- README documents a one-line curl | bash install using the script's
  raw URL on the Gitea instance
2026-10-01 12:20:20 +03:00
ars9 0341fc2201 docs(claude): tag version commits with their changelog entry
CI / server (push) Successful in 1m24s
CI / client (push) Successful in 1m43s
CI / version (push) Successful in 6s
CI / image (push) Skipped
- add a step to tag each version-bump commit as v<version>, annotated
  with that version's changelog entry verbatim
- push tags with git push --follow-tags
2026-10-01 12:04:43 +03:00
ars9 bba6eb2f94 chore: license the project under mit
CI / server (push) Successful in 1m9s
CI / client (push) Successful in 1m23s
CI / version (push) Successful in 6s
CI / image (push) Successful in 2m7s
- add the mit LICENSE and set license and author in all package.json
  files, plus a license section in the readme
- generate the license notices of all shipped production dependencies
  and node.js in a dockerfile stage and serve them at /licenses.txt,
  linked from the sidebar footer
- keep license files when slimming node_modules in the image
- add oci labels, with the version passed in by ci
- document licensing in the development docs
- bump version to 1.22.2
2026-10-01 11:44:51 +03:00
ars9 531754c3fa test(server): stop timing-dependent failures on busy ci runners
- raise the jest test timeout to 30s: building the nest app in
  beforeAll can exceed the 5s default when all suites start at once
- accept any run status when reading back a just-created run, since
  the scheduler may already have picked it up
2026-10-01 11:44:51 +03:00
ars9 cafc126d1b ci: set the image registry explicitly
- use REGISTRY (git.hq.ars9.space) for login and image tags instead of
  deriving it from the server url, which is the runner's registration
  address and may be internal-only
- document how jobs reach gitea when the runner uses an internal address
2026-10-01 11:11:39 +03:00
ars9 f24a1b7dd5 ci: add gitea actions for quality checks and versioned images
- run server lint, type-check, tests and build, and client lint, build
  and storybook tests on master and pull requests
- when a push to master changes the package.json version, build the
  docker image and push it to the gitea registry tagged with the
  version and latest
- document the workflow and the REGISTRY_TOKEN secret
2026-10-01 11:07:42 +03:00
ars9 63c2df96f1 build(docker): slim down the runtime image
- install production dependencies and chromium in a separate stage
- drop source maps, typescript sources and declarations, docs,
  typeorm's browser build, better-sqlite3's c sources and ffmpeg
- base the runtime on debian:bookworm-slim with only the node binary
- document the image layout
- bump version to 1.22.1
2026-10-01 10:52:47 +03:00
ars9 23fa302b25 feat(scenarios): export used snippets with a scenario
- list the snippets a scenario uses in the export dialog, checked by
  default, with the versions the scenario uses
- export each selected snippet once per used version (latest and
  pinned) via the new snippetIds query parameter
- resolve used snippets from the exported version's steps
- show the scenario version in the export dialog
- document the export query parameters
- bump version to 1.22.0
2026-10-01 10:45:39 +03:00
ars9 f43d902297 feat(credentials): hide credential data until revealed
- add a RevealableCodeBlock ui component that renders its code only
  after the user clicks Reveal, with a storybook story
- use it for the data section of the credential page
- bump version to 1.21.1
2026-10-01 10:36:37 +03:00
ars9 2129708819 feat(ui): color-code uuid badges and highlight them on hover
- show a circle colored by the first 6 hex digits of the uuid,
  bordered with the badge text color for contrast in both themes
- lighten the uuid badge background on hover
- let Badge accept a className
- add a storybook story with six sample uuids and a randomize button
- bump version to 1.21.0
2026-10-01 10:23:50 +03:00
ars9 6e9b99e415 fix(ui): meet wcag aa text contrast in both themes
- add --color-primary-text for lime used as text or icon color
- stop dimming the idle refresh label with opacity
- darken the light danger button and lighten the dark danger hover
- define syntax highlighting colors per theme as --hl-* tokens
- darken light muted text slightly
- add a storybook contrast page, fail storybook tests on a11y violations
  and show live token values in the colors story
- bump version to 1.20.2
2026-09-30 22:27:06 +03:00
ars9 8aadbd25fb chore(deps): update dependencies and bring storybook up to date
- update client and server dependencies within their ranges, keeping
  all playwright packages aligned at 1.63
- fix code flagged by react-hooks 7.1: refs written during render and
  synchronous setState in effects
- add stories for the ui components that had none, with interaction
  tests, and cover all DescriptionList layouts
- drop the unused mdx stories pattern
- run the storybook tests as part of the pre-commit checks
- bump version to 1.20.1
2026-09-30 22:05:21 +03:00
ars9 9f341719ef feat(database): manage the schema with typeorm migrations
- replace synchronize with migrations, starting with a generated initial
  migration that adopts databases created by synchronize
- apply pending migrations in the docker container before the server,
  and refuse to start the server while migrations are pending
- share one entity list and data source between app, migration runner,
  typeorm cli and tests; tests run the real migrations
- add migration:run, migration:show and migration:generate scripts and
  a test that fails when entities and migrations differ
- exit with code 1 when startup fails
- bump version to 1.20.0
2026-09-30 21:45:42 +03:00
ars9 5de9272281 feat(server): choose cors origins by NODE_ENV and run docker in production
- allow the vite dev server origins in development and the compose port
  origins in production; CORS_ORIGINS overrides both
- set NODE_ENV=production in the runtime docker image
- document both settings in .env.example and the development docs
- bump version to 1.19.3
2026-09-30 21:31:48 +03:00
ars9 a6d468bd2c chore: make .env optional and comment out all example settings
- load .env in compose only when it exists; every setting has a default
- comment out every setting in .env.example, with ## for descriptions
  and # VAR=default for settings to uncomment
- update README, development docs and CLAUDE.md accordingly
2026-09-30 21:23:18 +03:00
ars9 b0f2c72b5f docs: bring docs up to date and drop unused keys setting
- rewrite architecture, development, mcp and scenario docs to match the
  current code: single container, all mcp tools, runs, versioning,
  timeouts, settings, client routing and dev setup
- rewrite README as a general overview without liquio-specific wording
- remove the unused KEYS_DIR setting and ./keys compose mount
- remove the unused result parameter from step code execution
- complete .env.example with the file storage settings and fix the
  DB_PATH default
2026-09-30 21:18:41 +03:00
ars9 e586ab9bd9 fix(scenarios): preselect default environment when opening run modal
- choose the scenario's default environment when the run modal opens on
  the scenario detail page, instead of in a load effect that raced with
  loading the scenario and could fall back to the first environment
- set the run to a final status directly in the status filter test so
  the scheduler can't change it mid-test
- bump version to 1.19.2
2026-09-30 21:07:15 +03:00
ars9 68415f805b chore: upgrade to node 24 and read app version from workspace root
- base the docker image on node:24-slim and require node >=24 via
  engines in the root package.json
- read app name and version from the workspace root package.json for
  config, swagger, startup log and mcp server info; drop the server
  workspace version
- bind test http servers to 127.0.0.1 so tests pass in containers
  without ipv6 loopback
- bump version to 1.19.1
2026-09-30 20:57:33 +03:00
ars9 a4bfa3117f feat(docker): serve the whole app from a single container
- serve the built client from the server via serve-static (CLIENT_DIR),
  falling back to index.html outside /api, /mcp, /docs and /health
- replace server and client Dockerfiles and nginx with one root
  Dockerfile and a single liqa compose service on port 13000
- use Playwright's chromium-headless-shell with only its required libs
  and DejaVu/Liberation fonts instead of Debian chromium and Noto
- clear the npm cache in the runtime image
- bump version to 1.19.0
2026-09-30 20:28:10 +03:00
ars9 8935783371 feat(import): add central yaml import for all exportable kinds
- add POST /import, an import page and the import_yaml mcp tool; items
  are validated up front and imported in dependency order
- switch list page import buttons to the central import
- write scenario exports as separate --- yaml documents per entity
- give each test app its own files dir to avoid cross-suite races
- use node: prefix for node built-in imports
- bump version to 1.18.0
2026-09-30 19:25:03 +03:00
ars9 cf56840df9 refactor: fix lint errors across server and client
- replace any types with explicit types in scenario file listing,
  import/export and mcp upload code
- type test server addresses and list callbacks, drop unused vars
- document why e2e export keeps the archiver import-require form
- remove unused scenario files total state in the client
- require clean lint in both packages in CLAUDE.md
2026-09-30 18:55:17 +03:00
ars9 1c5c906cbb feat(runs): add deleting files from a run
- add 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
- add a delete button with confirmation to the run detail files table
- bump version to 1.17.0
2026-09-30 18:51:25 +03:00
ars9 ac12301818 docs: add CLAUDE.md and rename compose file to compose.yaml
- add CLAUDE.md with app overview, compose deployment details, doc
  references, code quality checks and the release/commit workflow
- rename docker-compose.yaml to compose.yaml, the preferred compose
  spec file name
2026-09-30 18:45:59 +03:00
ars9 84dba6d670 fix(runs): disable playwright traces by default, bump to 1.16.1
- default PLAYWRIGHT_TRACE_MODE to off since traces often reach ~10 MB
  per run; traces can still be enabled per run or via the setting
2026-09-30 18:35:26 +03:00
213 changed files with 15124 additions and 4338 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ node_modules
**/*.log **/*.log
data data
keys keys
**/*.tsbuildinfo
+54 -15
View File
@@ -1,20 +1,59 @@
NODE_ENV=development ## Optional overrides: copy to .env and uncomment the settings you need.
PORT=3000 ## 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 ## production in the Docker image; also selects the default CORS origins
KEYS_DIR=keys # NODE_ENV=development
# PORT=3000
# SQLite database path ## Application log output: console (default) or debug (controlled by DEBUG namespaces)
DB_PATH=data/sessions.db # LOG_MODE=console
# Playwright executable (set in Docker; leave empty to use system default) ## Optional account authentication (disabled unless explicitly enabled)
# AUTH_ENABLED=true
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
# AUTH_JWT_SECRET=replace-with-a-private-random-secret
## Browser cookie name and default JWT lifetime
# AUTH_COOKIE_NAME=liqa_auth
# AUTH_JWT_EXPIRES_IN=24h
## Expired logout revocations are cleaned at startup and on this cron schedule.
# AUTH_REVOKED_TOKEN_CLEANUP_CRON=0 3 * * *
## 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
## 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
## Run log data blocks whose pretty-printed JSON exceeds either limit start
## collapsed in the UI (bytes, lines); served to the client via /manifest.json
# RUN_LOG_DATA_COLLAPSE_BYTES=256
# RUN_LOG_DATA_COLLAPSE_LINES=5
## 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 # PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
# Session lifecycle ## Directory with the built client to serve at / (the Docker image sets it to
# Close open sessions that have been idle for longer than this many minutes ## "client"; leave unset to not serve the UI, e.g. when using the Vite dev server)
SESSION_IDLE_TIMEOUT_MINUTES=30 # CLIENT_DIR=client
# 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
PLAYWRIGHT_TRACE_MODE=on
+120
View File
@@ -0,0 +1,120 @@
# Code quality checks on master and pull requests. The server and client jobs
# only run when their directory (or shared root files) changed. On a release
# tag push (vX.Y.Z), runs both jobs unconditionally and then builds the Docker
# image and pushes it to this Gitea instance's container registry, tagged with
# the version and `latest`. The tag must match the root package.json version.
#
# Needs a repository (or owner) secret REGISTRY_TOKEN: a Gitea access token
# with package write access for the repository owner. The registry host is
# set explicitly below rather than taken from the server URL, which is the
# address the runner was registered with and may be internal-only.
name: CI
on:
push:
branches: [master]
tags: ['v[0-9]+.[0-9]+.[0-9]+']
pull_request:
env:
REGISTRY: git.hq.ars9.space
jobs:
# Not needed on tag pushes: server and client always run there
changes:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
outputs:
server: ${{ steps.filter.outputs.server }}
client: ${{ steps.filter.outputs.client }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
server:
- 'server/**'
- 'package.json'
- 'package-lock.json'
- '.gitea/workflows/ci.yml'
client:
- 'client/**'
- 'package.json'
- 'package-lock.json'
- '.gitea/workflows/ci.yml'
server:
needs: changes
# changes is skipped on tag pushes, hence !cancelled()
if: |
!cancelled() &&
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.server == 'true')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci -w server
- name: Lint
run: npm run -w server lint -- --max-warnings=0
- name: Type-check
run: npx tsc --noEmit -p server/tsconfig.json
- name: Test
run: npm test -w server
- name: Build
run: npm run -w server build
client:
needs: changes
# changes is skipped on tag pushes, hence !cancelled()
if: |
!cancelled() &&
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.client == 'true')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci -w client
- name: Lint
run: npm run -w client lint -- --max-warnings=0
- name: Build
run: npm run -w client build
- name: Install headless Chromium for Storybook tests
run: npx playwright install --with-deps --only-shell chromium
- name: Storybook tests
run: npm run -w client test:storybook
image:
needs: [server, client]
if: ${{ !failure() && !cancelled() && startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check the tag matches package.json
run: |
version=$(node -p "require('./package.json').version")
if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
echo "tag ${GITHUB_REF_NAME} does not match package.json version ${version}"
exit 1
fi
echo "VERSION=${version}" >> "$GITHUB_ENV"
- name: Log in to the registry
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
OWNER: ${{ github.repository_owner }}
run: |
echo "IMAGE=${REGISTRY}/$(echo "${GITHUB_REPOSITORY}" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$OWNER" --password-stdin
- name: Build
run: docker build --build-arg VERSION="${VERSION}" -t "${IMAGE}:${VERSION}" -t "${IMAGE}:latest" .
- name: Push
run: |
docker push "${IMAGE}:${VERSION}"
docker push "${IMAGE}:latest"
+287
View File
@@ -2,6 +2,293 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## 1.26.0 - 2026-10-08
Changes since 1.25.0:
### Added
- e2e test export for a chosen scenario version: `GET /api/v1/scenarios/:id/export-e2e` and the `export_e2e_test` MCP tool take an optional `version` (defaults to the latest), and the test project is built from that version's steps, name and timeout. The Export e2e test button in the UI exports the version being viewed.
### Changed
- Exported e2e test archives include the version in their filename (`<scenario name>-v<N>-e2e-test.zip`), and the version also appears in the generated package name and README heading.
## 1.25.0 - 2026-10-07
Changes since 1.24.4:
### Added
- Browser notifications for scenario runs: the UI shows "Run started / passed / failed: <scenario>" notifications for runs started from the UI, the REST API, MCP or the scheduler; clicking one opens the run. Turn them on with the bell button in the side panel footer (granting the permission from the browser's prompt or site settings works too). Notifications need a secure context (HTTPS or `localhost`).
- `GET /api/v1/scenarios/runs/events`: a server-sent events stream of run lifecycle events (`run.started`, `run.finished`) with a periodic `ping` heartbeat.
### Changed
- Runs lists refresh as soon as a run finishes while notifications are on.
## 1.24.4 - 2026-10-07
Changes since 1.24.3:
### Changed
- Exported scenario and snippet files include the exported version in their filename: `<scenario name>-v<N>.yaml` and `snippet-<alias>-v<N>.yaml`.
### Fixed
- `scripts/install.sh` reads prompts from the terminal, so `curl ... | bash` installs no longer consume the script's own lines as answers (it falls back to defaults when there is no terminal). It also checks that Docker, the compose plugin and the daemon work, and starts liqa with `docker compose up -d`, printing the manual start command if a check or the start fails.
## 1.24.3 - 2026-10-02
Changes since 1.24.2:
### Added
- `examples/` directory with ready-to-import example resources. The first one, `examples/self-test`, is a scenario that tests the liqa instance it runs on: it creates a temporary scenario through the REST API, runs it, checks the run and its page in the UI, and cleans up. It uses an environment, a credential, snippets and assertions.
### Changed
- CI builds and pushes the Docker image only when a `vX.Y.Z` release tag is pushed, not on every merge to `master`.
## 1.24.2 - 2026-10-02
Changes since 1.24.1:
### Added
- Large run log data blocks start collapsed behind a "Show data (size, lines)" toggle: data whose pretty-printed JSON is over `RUN_LOG_DATA_COLLAPSE_BYTES` (default 256) bytes or `RUN_LOG_DATA_COLLAPSE_LINES` (default 5) lines. An "Expand data" / "Collapse data" button next to the Logs heading opens or closes all of them.
- "Copy logs" button on the run page: copies the currently filtered logs to the clipboard as plain text, with every data block expanded.
- `GET /manifest.json`: public client configuration served by the server - the app name and version, and the run log data limits. The UI caches it in `localStorage` and revalidates it on page load and when the tab is refocused after a while.
### Changed
- The sidebar footer shows the server's version (from `/manifest.json`); its tooltip suggests reloading the page when it differs from the version the UI was built with.
- Run log data blocks are aligned with the context/message column instead of the level column.
## 1.24.1 - 2026-10-02
Changes since 1.24.0:
### Added
- `context.assert(fn, description, details?)`: optional `details` argument. On failure, the `assertion:fail` log entry stores `{ details, error }` as data (`error` is the exception message when `fn` threw), so large diagnostics such as a response body can stay out of the message. The exported e2e runtime accepts and prints it too.
- The "Step N passed" log entry carries the step's return value as data.
- File names in the run Artifacts and scenario Files tables link to the file content, opening it in a new tab (shown inline when the browser can display it).
### Changed
- For assertion failures, the "Step N failed" and "Snippet X failed" log entries name only the assertion (`Assertion failed: <description>`) instead of repeating the failure details. The step run's description keeps the full message.
- Log output shows elapsed time in whole seconds (`+14s`), matching the stored timestamp resolution.
## 1.24.0 - 2026-10-01
Changes since 1.23.0:
### Added
- Code reference in the UI: a (?) button next to the Code label on the step and snippet create/edit pages opens a modal documenting the script runtime - the globals (`context`, `expect`, `console`, and `args` in snippets) and every `context` member with examples, including pitfalls such as awaiting `getStepOutput()` and `assert()`, and `downloadFile()` not sending the browser's cookies.
### Changed
- `Modal` UI component: new `size="lg"` for long, document-like content. Dialogs are now capped to the viewport height and their body scrolls, instead of overflowing the screen.
## 1.23.0 - 2026-10-01
Changes since 1.22.2:
### Added
- Run log entries now carry a `context` (where the message was generated: `step:<N>`, `snippet:<alias>`, `assertion:pass`/`fail`, or `run`) and a `data` field: `context.log`/`warn`/`error` and `console.*` split their arguments so strings join into `message` while object/array arguments are kept separate as `data` (JSON), instead of being `JSON.stringify`'d into the message text.
- Added a `debug` log level (`context.debug()`, `console.debug()`), alongside `log`/`warn`/`error`.
- New `LogOutput` UI component: a terminal-style log viewer on the run detail page, color-coded by level, with an elapsed-time-since-start column, a context tag, and `data` rendered pretty-printed in a separate block below the message. The full log list is shown (no more pagination), capped to a scrollable block.
- Run log CSV/Markdown export (`GET /scenarios/:id/runs/:runId/export`) include the new `context` and `data` columns/blocks; the logs search (`?q=`) also matches `context`.
## 1.22.2 - 2026-10-01
Changes since 1.22.1:
### Added
- MIT license (`LICENSE`), declared in all `package.json` files and the README.
- The Docker image includes the license notices of everything it ships: `scripts/third-party-licenses.mjs` collects the license of every production dependency of the client and server, the Node.js license is added, and the result is served at `/licenses.txt`, linked as "Licenses" in the sidebar footer.
- OCI image labels for title, version, license and source; CI passes the version as the `VERSION` build arg.
### Fixed
- The Docker image keeps packages' `LICENSE.md`/`NOTICE.md` files, which the 1.22.1 slimming step deleted along with other Markdown files.
## 1.22.1 - 2026-10-01
Changes since 1.22.0:
### Changed
- The Docker image is about 20% smaller (1.09 GB → 876 MB on disk, 251 MB → 220 MB compressed). Production dependencies and Chromium are installed in a separate stage that drops files nothing loads at runtime (source maps, TypeScript sources and declarations, docs, TypeORM's browser build, better-sqlite3's C sources, Playwright's ffmpeg). The runtime image is `debian:bookworm-slim` with only the `node` binary, so it no longer contains `npm`, `npx`, `yarn` or `corepack`.
## 1.22.0 - 2026-10-01
Changes since 1.21.1:
### Added
- The Export Scenario dialog lists the snippets the scenario uses (including ones used only through other snippets), all checked by default. A selected snippet is exported once per version the scenario uses: the latest for `runSnippet("alias")`, plus each version pinned with `alias@N`. `GET /scenarios/:id/export` takes the new `snippetIds` query parameter for this.
- The Export Scenario dialog shows the scenario version next to its name and id.
## 1.21.1 - 2026-10-01
Changes since 1.21.0:
### Changed
- The credential page hides the credential data when it opens; a Reveal button shows it and Hide hides it again. The data is not rendered on the page until revealed.
### Added
- A `RevealableCodeBlock` UI component (a CodeBlock that starts hidden behind a Reveal/Hide button), with a Storybook story.
## 1.21.0 - 2026-10-01
Changes since 1.20.2:
### Added
- UUID badges show a small colored circle in front of the short id. Its color comes from the first 6 hex digits of the UUID, so the same id always gets the same color, and its border uses the badge text color to stay visible in both themes.
- UUID badges get lighter on hover to show they can be clicked.
- `Badge` accepts an optional `className`.
- A Storybook "Colors" story for UuidBadge with six sample ids and a button to randomize them.
## 1.20.2 - 2026-09-30
Changes since 1.20.1:
### Fixed
- Text contrast now meets WCAG AA (4.5:1) in both themes:
- the "Live" refresh label and the table sort icon use a new `--color-primary-text` token (dark lime in the light theme) instead of the light lime brand color;
- the idle refresh label is no longer dimmed with opacity;
- the light theme's danger button is a little darker, and the dark theme's danger hover is lighter so its dark text stays readable;
- syntax highlighting colors are defined per theme (`--hl-*` tokens), darker in the light theme;
- muted text is slightly darker in the light theme.
### Added
- A Storybook "Accessibility / Contrast" page that measures the contrast of the most contrast-prone components in both themes.
- Storybook accessibility checks now fail the tests on violations (`a11y.test: 'error'`). The Colors story shows each token's current value per theme and includes the syntax colors.
## 1.20.1 - 2026-09-30
Changes since 1.20.0:
### Added
- Storybook stories for AutoRefreshIndicator, CodeBlock, CodeEditor, MarkdownContent, Modal, Notification, Search, Textarea, Toast and UuidBadge, with interaction tests where the component has behavior. The DescriptionList story covers all four layouts.
### Changed
- Updated all client and server dependencies to the latest versions within their ranges, including React 19.3, Storybook 10.6, NestJS 11.2, TypeORM 0.3.31 and Playwright 1.63 (the Docker image now ships HeadlessChrome 153).
- The Storybook tests are part of the pre-commit checks.
### Fixed
- Code flagged by the stricter React hooks lint rules: the runs list no longer writes refs during render, and the scenario list, scenario files and sessions list no longer set state synchronously inside effects.
## 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 ## 1.16.0 - 2026-09-30
Changes since 1.15.0: Changes since 1.15.0:
+75
View File
@@ -0,0 +1,75 @@
# 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`, public client configuration at `/manifest.json`.
- `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
- [examples/](examples/README.md) - ready-to-import example resources (YAML); `server/test/examples.spec.ts` imports each file, so keep them in sync with the import format
- [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.
## Branching
Never commit directly to `master` when implementing a feature, chore or bug fix: create a separate branch for the work first, forked from `master`. These commits don't change the version or `CHANGELOG.md`; the branch is merged back to `master` through a pull request. Only release commits (see "Releasing a new version") are made on `master`.
Never add a `Co-Authored-By` trailer to commit messages. Don't put issue references like `Closes #12` in commit messages either; they belong only in the pull request description.
When committing on a work branch, also update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions) in the same branch.
## 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 && npm run test:storybook
```
- Lint must stay clean in both packages (no errors, no warnings).
- `test:storybook` runs every story in `client/.storybook/stories/` in headless Chromium (needs `npx playwright install --only-shell chromium` once, and again after Playwright updates). Add or update a story when adding or changing a `client/src/ui/` component.
- 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`, ...).
## Releasing a new version
A release is cut on `master` after one or more work branches have been merged (their pull request checks are already green). CI builds and pushes the Docker image only when a `vX.Y.Z` tag is pushed, not on merges.
When asked to release:
1. Make sure you're on an up-to-date, clean `master` (`git switch master && git pull`), and collect the changes since the last release: `git log --oneline "$(git describe --tags --abbrev=0)"..HEAD`.
2. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on those 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).
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. Commit only these release changes on `master`. 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.
6. **Tag the release commit** with an annotated tag `v<version>` whose message is that version's `CHANGELOG.md` entry, verbatim (from its `## <version>` heading up to the next version's heading). `--cleanup=whitespace` is required: the default cleanup strips lines starting with `#`, which would drop the entry's headings:
```bash
v=<version>
awk -v v="$v" 'index($0, "## " v " ") == 1 {p = 1; print; next} p && /^## / {exit} p' CHANGELOG.md \
| git tag -a "v$v" --cleanup=whitespace -F -
```
7. **Ask the user before pushing**, then push the commit and the tag together with `git push --follow-tags` (it also pushes annotated tags). The tag push triggers the image build; it fails if the tag doesn't match the `package.json` version.
8. **Ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
+157
View File
@@ -0,0 +1,157 @@
# 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 dependencies ──────────────────────────────────────────────────────
FROM node:24-slim AS runtime-deps
WORKDIR /app
COPY package*.json ./
COPY server/package.json ./server/
# Production dependencies and 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, and neither is ffmpeg (only used for video recording).
#
# Then drop what nothing loads at runtime: source maps, TypeScript sources and
# declarations, docs (but not license files), TypeORM's browser build and
# better-sqlite3's C sources (the addon is already compiled).
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
RUN npm ci --omit=dev -w server \
&& npx playwright install --only-shell chromium \
&& rm -rf /ms-playwright/ffmpeg-* \
&& find node_modules -type f \( \
-name '*.map' -o -name '*.ts' -o -name '*.mts' -o -name '*.cts' \
-o \( \( -iname '*.md' -o -iname '*.markdown' \) \
! -iname 'licen[cs]e*' ! -iname 'notice*' ! -iname 'copying*' \) \
\) -delete \
&& rm -rf node_modules/typeorm/browser \
node_modules/better-sqlite3/deps \
node_modules/better-sqlite3/src
# ── License notices ───────────────────────────────────────────────────────────
# One file with the project's LICENSE and the license of everything the image
# ships: the production dependencies of both workspaces (the client's are
# bundled into its build, so their license files aren't in the image
# otherwise) and the Node.js binary, whose LICENSE the node image doesn't
# include.
FROM node:24-slim AS licenses
WORKDIR /app
COPY package*.json LICENSE ./
COPY client/package.json ./client/
COPY server/package.json ./server/
COPY scripts/third-party-licenses.mjs ./scripts/
RUN npm ci --omit=dev --ignore-scripts \
&& node scripts/third-party-licenses.mjs > licenses.txt \
&& node -e ' \
const url = `https://raw.githubusercontent.com/nodejs/node/v${process.versions.node}/LICENSE`; \
fetch(url).then(async (r) => { \
if (!r.ok) throw new Error(`${url}: ${r.status}`); \
const rule = "-".repeat(79); \
process.stdout.write(`\n${rule}\n\nnode@${process.versions.node}\nLicense: MIT\n\n${(await r.text()).trim()}\n`); \
}).catch((e) => { console.error(e.message); process.exit(1); });' >> licenses.txt
# ── Runtime ───────────────────────────────────────────────────────────────────
# Plain Debian with just the node binary: npm, yarn, corepack and the C
# headers that come with the node image aren't needed to run the app.
FROM debian:bookworm-slim AS runtime
# Set by CI from the root package.json version
ARG VERSION=dev
LABEL org.opencontainers.image.title="liqa" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.licenses="MIT" \
org.opencontainers.image.source="https://git.hq.ars9.space/ars9/liqa"
# 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/*
COPY --from=runtime-deps /usr/local/bin/node /usr/local/bin/node
WORKDIR /app
COPY package*.json ./
COPY server/package.json ./server/
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
COPY --from=runtime-deps /ms-playwright /ms-playwright
COPY --from=runtime-deps /app/node_modules ./node_modules
COPY --from=server-build /app/server/dist ./dist
COPY --from=client-build /app/client/dist ./client
# The project's license, and every shipped component's license notices (also
# served by the app at /licenses.txt)
COPY LICENSE ./
COPY --from=licenses /app/licenses.txt ./client/licenses.txt
# 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"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Andrii Arsenin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+48 -29
View File
@@ -1,46 +1,65 @@
# 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.
Authentication is **disabled by default**. To enable operator-managed accounts, set `AUTH_ENABLED=true` and provide a private `AUTH_JWT_SECRET`; then rebuild/restart the service and provision an account with the CLI. See [operator authentication](docs/development.md#operator-account-commands) for setup and browser/API usage. Existing deployments remain unauthenticated until explicitly enabled.
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/`.
To see it work, import and run the [self-test example](examples/self-test/): a scenario that tests liqa itself using an environment, a credential and snippets.
---
## Installation
To install liqa from the published image, without cloning this repo:
```bash
curl -fsSL https://git.hq.ars9.space/ars9/liqa/raw/branch/master/scripts/install.sh | bash
```
This asks for an install directory, a port and a version (latest by default), then writes a `compose.yaml` and a `data/` directory there. Start it with `docker compose up -d` in that directory.
--- ---
## Overview ## Overview
The bot manages four core concepts:
| Concept | Description | | Concept | Description |
|---|---| |---|---|
| **Environment** | A named set of URLs for a deployment target (e.g. `liquio-diia-stg`) | | **Scenario** | An ordered list of steps (async Playwright JS) that run in sequence in one browser. Versioned: every content change creates a new version |
| **Key** | A JSON descriptor in `keys/` that points to an EDS key file + password | | **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) |
| **Session** | Saved browser state (cookies + localStorage) produced by a login | | **Snippet** | Reusable, versioned code called from steps with `context.runSnippet("alias")` (or `"alias@N"` for a specific version) |
| **Scenario** | An ordered list of steps that run in sequence against a shared browser instance | | **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). - [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
- [examples/](examples/) - ready-to-import example scenarios
- [CHANGELOG.md](CHANGELOG.md) - release notes
--- ---
## Key descriptors ## License
See [docs/key-descriptors.md](docs/key-descriptors.md). [MIT](LICENSE) © 2026 Andrii Arsenin
--- Third-party packages keep their own licenses. The Docker image includes all their notices, and the app serves them at `/licenses.txt` (linked as "Licenses" in the sidebar footer). See [docs/development.md](docs/development.md#licenses).
## 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.
+1 -1
View File
@@ -12,7 +12,7 @@ function getAbsolutePath(value: string) {
return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`))); return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`)));
} }
const config: StorybookConfig = { const config: StorybookConfig = {
stories: ['./stories/**/*.mdx', './stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'], stories: ['./stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [ addons: [
getAbsolutePath('@storybook/addon-vitest'), getAbsolutePath('@storybook/addon-vitest'),
getAbsolutePath('@storybook/addon-a11y'), getAbsolutePath('@storybook/addon-a11y'),
+2 -1
View File
@@ -37,7 +37,8 @@ const preview: Preview = {
}, },
}, },
a11y: { a11y: {
test: 'todo', // Accessibility violations (e.g. color contrast) fail the story's test
test: 'error',
}, },
}, },
}; };
@@ -0,0 +1,28 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { AuthStatusPage } from '../../src/pages/auth/AuthStatusPage';
const meta: Meta<typeof AuthStatusPage> = {
title: 'Authentication/Session status',
component: AuthStatusPage,
parameters: { layout: 'fullscreen' },
tags: ['autodocs'],
args: { onRetry: fn() },
};
export default meta;
type Story = StoryObj<typeof AuthStatusPage>;
export const Checking: Story = {};
export const SessionCheckFailure: Story = {
args: { failed: true },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('alert')).toHaveTextContent(
"Couldn't check your session. Try again.",
);
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
await expect(args.onRetry).toHaveBeenCalledTimes(1);
},
};
@@ -0,0 +1,71 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect } from 'storybook/test';
import { auth } from '../../src/api/client';
import { createRunEventSource } from '../../src/hooks/useRunNotifications';
function TransportExample() {
return <p>Browser auth uses HttpOnly cookies for API and run-event requests.</p>;
}
const meta: Meta<typeof TransportExample> = {
title: 'Authentication/Cookie transport',
component: TransportExample,
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof TransportExample>;
export const CookieCredentials: Story = {
play: async () => {
const originalFetch = globalThis.fetch;
const localStorageLength = localStorage.length;
let requestInit: RequestInit | undefined;
globalThis.fetch = async (_input, init) => {
requestInit = init;
return new Response(
JSON.stringify({
user: {
id: 'synthetic-user-id',
username: 'synthetic-operator',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
);
};
try {
const user = await auth.login('synthetic-operator', 'synthetic-password');
await expect(requestInit?.credentials).toBe('include');
await expect(user.username).toBe('synthetic-operator');
await expect(new Headers(requestInit?.headers).has('Authorization')).toBe(false);
await expect(localStorage.length).toBe(localStorageLength);
} finally {
globalThis.fetch = originalFetch;
}
},
};
export const EventStreamIncludesCookieCredentials: Story = {
play: async () => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'EventSource');
let options: EventSourceInit | undefined;
class StubEventSource {
constructor(_url: string | URL, init?: EventSourceInit) {
options = init;
}
close() {}
}
Object.defineProperty(globalThis, 'EventSource', {
configurable: true,
value: StubEventSource,
});
try {
createRunEventSource().close();
await expect(options?.withCredentials).toBe(true);
} finally {
if (previous) Object.defineProperty(globalThis, 'EventSource', previous);
else Reflect.deleteProperty(globalThis, 'EventSource');
}
},
};
@@ -0,0 +1,25 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
const meta: Meta<typeof AutoRefreshIndicator> = {
title: 'UI/AutoRefreshIndicator',
component: AutoRefreshIndicator,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onClick: fn() },
};
export default meta;
type Story = StoryObj<typeof AutoRefreshIndicator>;
export const Active: Story = { args: { active: true, pulseKey: 1 } };
export const Idle: Story = { args: { active: false } };
export const Errored: Story = { args: { active: false, error: true } };
export const ClickToRefresh: Story = {
args: { active: false },
play: async ({ args, canvasElement }) => {
await userEvent.click(within(canvasElement).getByRole('button'));
await expect(args.onClick).toHaveBeenCalled();
},
};
@@ -0,0 +1,33 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect } from 'storybook/test';
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
const meta: Meta<typeof CodeBlock> = {
title: 'UI/CodeBlock',
component: CodeBlock,
parameters: { layout: 'padded' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof CodeBlock>;
export const JavaScript: Story = {
args: {
language: 'javascript',
code: "const url = context.getEnv('BASE_URL');\nawait context.page.goto(url);\nreturn await context.page.title();",
},
play: async ({ canvasElement }) => {
// Highlighting splits the code into many spans: check the whole text and
// that highlighting actually happened
const code = canvasElement.querySelector('code');
await expect(code).toHaveTextContent('await context.page.goto(url);');
await expect(code?.querySelector('.hljs-keyword')).not.toBeNull();
},
};
export const Json: Story = {
args: {
language: 'json',
code: JSON.stringify({ status: 'pass', output: { title: 'Dashboard' } }, null, 2),
},
};
@@ -0,0 +1,35 @@
import React, { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { CodeEditor, type CodeEditorProps } from '../../src/ui/CodeEditor/CodeEditor';
// Monaco is loaded from a CDN at runtime, so these stories only check that the
// editor mounts; they have no interaction tests.
function ControlledEditor(
props: Omit<CodeEditorProps, 'value' | 'onChange'> & { initial: string },
) {
const { initial, ...rest } = props;
const [value, setValue] = useState(initial);
return <CodeEditor {...rest} value={value} onChange={setValue} />;
}
const meta: Meta<typeof ControlledEditor> = {
title: 'UI/CodeEditor',
component: ControlledEditor,
parameters: { layout: 'padded' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof ControlledEditor>;
export const JavaScript: Story = {
args: {
language: 'javascript',
rows: 8,
initial:
"await context.page.goto(context.getEnv('BASE_URL'));\nreturn await context.page.title();",
},
};
export const WithError: Story = {
args: { language: 'javascript', rows: 4, error: true, initial: 'await context.page.goto(' },
};
+45 -4
View File
@@ -1,10 +1,16 @@
import React from 'react'; import React, { useLayoutEffect, useRef, useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite'; import type { Meta, StoryObj } from '@storybook/react-vite';
const palette = [ const palette = [
{ name: 'Atlantis', token: '--color-primary', hex: '#9DD341', role: 'Primary / Action' }, { name: 'Atlantis', token: '--color-primary', hex: '#9DD341', role: 'Primary / Action' },
{
name: 'Atlantis text',
token: '--color-primary-text',
hex: '#496904',
role: 'Primary as text / icon',
},
{ name: 'Outer Space', token: '--color-text', hex: '#2D3339', role: 'Text / Surface' }, { name: 'Outer Space', token: '--color-text', hex: '#2D3339', role: 'Text / Surface' },
{ name: 'Kimberly', token: '--color-text-muted', hex: '#6650C0', role: 'Muted text / Info' }, { name: 'Kimberly', token: '--color-text-muted', hex: '#634DBD', role: 'Muted text / Info' },
{ name: 'Powder Ash', token: '--color-border', hex: '#AFBFB9', role: 'Border / Neutral' }, { name: 'Powder Ash', token: '--color-border', hex: '#AFBFB9', role: 'Border / Neutral' },
]; ];
@@ -23,12 +29,23 @@ const semanticColors = [
{ name: 'Running fg', token: '--color-running-fg', hex: '#6B4A00' }, { name: 'Running fg', token: '--color-running-fg', hex: '#6B4A00' },
]; ];
const syntaxColors = [
{ name: 'Comment', token: '--hl-comment', hex: '#4F6557' },
{ name: 'Keyword', token: '--hl-keyword', hex: '#764E99' },
{ name: 'String / title', token: '--hl-string', hex: '#4F6821' },
{ name: 'Number', token: '--hl-number', hex: '#895403' },
{ name: 'Function', token: '--hl-function', hex: '#056980' },
{ name: 'Variable / params', token: '--hl-variable', hex: '#815354' },
{ name: 'Property', token: '--hl-property', hex: '#1D6971' },
{ name: 'Meta', token: '--hl-meta', hex: '#615B7E' },
];
const surfaceColors = [ const surfaceColors = [
{ name: 'Background', token: '--color-bg', hex: '#E6EDEA' }, { name: 'Background', token: '--color-bg', hex: '#E6EDEA' },
{ name: 'Background subtle', token: '--color-bg-subtle', hex: '#D8E2DE' }, { name: 'Background subtle', token: '--color-bg-subtle', hex: '#D8E2DE' },
{ name: 'Secondary', token: '--color-secondary', hex: '#EDF1EF' }, { name: 'Secondary', token: '--color-secondary', hex: '#EDF1EF' },
{ name: 'Secondary hover', token: '--color-secondary-hover', hex: '#DFE6E3' }, { name: 'Secondary hover', token: '--color-secondary-hover', hex: '#DFE6E3' },
{ name: 'Danger', token: '--color-danger', hex: '#D94F4F' }, { name: 'Danger', token: '--color-danger', hex: '#CE4546' },
{ name: 'Primary fg', token: '--color-primary-fg', hex: '#2D3339' }, { name: 'Primary fg', token: '--color-primary-fg', hex: '#2D3339' },
]; ];
@@ -43,8 +60,27 @@ function Swatch({
hex: string; hex: string;
role?: string; role?: string;
}) { }) {
// Show the token's current value (per theme) rather than a hard-coded copy
const ref = useRef<HTMLDivElement>(null);
const [value, setValue] = useState(hex);
useLayoutEffect(() => {
const read = () => {
if (!ref.current) return;
const resolved = getComputedStyle(ref.current).getPropertyValue(token).trim();
if (resolved) setValue(resolved.toUpperCase());
};
read();
// Re-read when the theme toolbar switches data-theme on <html>
const observer = new MutationObserver(read);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});
return () => observer.disconnect();
}, [token]);
return ( return (
<div <div
ref={ref}
style={{ style={{
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
@@ -72,7 +108,7 @@ function Swatch({
</div> </div>
)} )}
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}> <div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
{hex} {value}
</div> </div>
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}> <div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
{token} {token}
@@ -128,6 +164,11 @@ function ColorPalette() {
<Swatch key={c.token} {...c} /> <Swatch key={c.token} {...c} />
))} ))}
</Section> </Section>
<Section title="Syntax highlighting">
{syntaxColors.map((c) => (
<Swatch key={c.token} {...c} />
))}
</Section>
</div> </div>
); );
} }
@@ -13,7 +13,7 @@ export default meta;
type Story = StoryObj<typeof ContextMenu>; type Story = StoryObj<typeof ContextMenu>;
const trigger = ( const trigger = (
<Button variant="ghost" size="sm"> <Button variant="ghost" size="sm" aria-label="Actions">
<Settings size={16} /> <Settings size={16} />
</Button> </Button>
); );
@@ -0,0 +1,330 @@
import React, { useLayoutEffect, useRef, useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
import { Button } from '../../src/ui/Button/Button';
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
/*
* Text contrast review page (WCAG AA: 4.5:1 for normal text, 3:1 for large
* text) for the components where contrast is easiest to get wrong: light
* brand colors used as text, dimmed labels, colored buttons and syntax
* highlighting. Every sample is the real component, shown in both themes, and
* the contrast of each piece of text is measured live from the rendered
* colors - so this page stays accurate as the design tokens change.
*/
// ── Contrast measurement ─────────────────────────────────────────────────────
type Rgba = [number, number, number, number];
function parseColor(value: string): Rgba {
const parts = value.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0];
return [parts[0], parts[1], parts[2], parts[3] ?? 1];
}
function luminance([r, g, b]: Rgba): number {
const channel = (c: number) => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}
function contrast(a: Rgba, b: Rgba): number {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
/** Blends `top` over an opaque `bottom`. */
function blend(top: Rgba, bottom: Rgba): Rgba {
const a = top[3];
return [0, 1, 2].map((i) => top[i] * a + bottom[i] * (1 - a)).concat(1) as Rgba;
}
/** Product of the `opacity` of `el` and its ancestors (e.g. a dimmed idle label). */
function opacityChain(el: Element): number {
let opacity = 1;
for (let node: Element | null = el; node; node = node.parentElement) {
opacity *= parseFloat(getComputedStyle(node).opacity);
}
return opacity;
}
/** The opaque color behind `el`, from its own and its ancestors' backgrounds. */
function effectiveBackground(el: Element): Rgba {
const layers: Rgba[] = [];
for (let node: Element | null = el; node; node = node.parentElement) {
const bg = parseColor(getComputedStyle(node).backgroundColor);
bg[3] *= opacityChain(node);
if (bg[3] > 0) layers.push(bg);
if (bg[3] >= 1) break;
}
return layers.reduceRight<Rgba>((under, layer) => blend(layer, under), [255, 255, 255, 1]);
}
const hex = ([r, g, b]: Rgba) =>
'#' + [r, g, b].map((c) => Math.round(c).toString(16).padStart(2, '0')).join('');
interface Measurement {
text: string;
fg: string;
bg: string;
ratio: number;
required: number;
}
/** Measures every element that directly contains visible text. */
function measure(root: HTMLElement): Measurement[] {
const seen = new Set<string>();
const results: Measurement[] = [];
for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {
const text = Array.from(el.childNodes)
.filter((n) => n.nodeType === Node.TEXT_NODE)
.map((n) => n.textContent ?? '')
.join('')
.trim();
if (!text || el.closest('[aria-hidden="true"]')) continue;
const style = getComputedStyle(el);
const fontSize = parseFloat(style.fontSize);
const bold = Number(style.fontWeight) >= 700;
// WCAG "large text": at least 24px, or 18.66px bold
const required = fontSize >= 24 || (bold && fontSize >= 18.66) ? 3 : 4.5;
const bgColor = effectiveBackground(el);
const fg = parseColor(style.color);
fg[3] *= opacityChain(el);
const fgColor = blend(fg, bgColor);
const key = `${hex(fgColor)}|${hex(bgColor)}|${required}`;
if (seen.has(key)) continue;
seen.add(key);
results.push({
text: text.length > 28 ? `${text.slice(0, 28)}…` : text,
fg: hex(fgColor),
bg: hex(bgColor),
ratio: contrast(fgColor, bgColor),
required,
});
}
return results.sort((a, b) => a.ratio / a.required - b.ratio / b.required);
}
function Readout({ items }: { items: Measurement[] }) {
return (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 8 }}>
<tbody>
{items.map((m) => {
const pass = m.ratio >= m.required;
return (
<tr
key={`${m.fg}${m.bg}${m.required}`}
style={{ borderTop: '1px solid var(--color-border)' }}
>
<td style={{ padding: '4px 6px' }}>
<span
style={{
display: 'inline-block',
padding: '1px 6px',
borderRadius: 3,
background: m.bg,
color: m.fg,
fontFamily: 'monospace',
}}
>
{m.text}
</span>
</td>
<td
style={{
padding: '4px 6px',
fontFamily: 'monospace',
color: 'var(--color-text-muted)',
}}
>
{m.fg} on {m.bg}
</td>
<td
style={{
padding: '4px 6px',
textAlign: 'right',
fontWeight: 700,
whiteSpace: 'nowrap',
color: pass ? 'var(--color-text)' : 'var(--color-danger)',
}}
>
{m.ratio.toFixed(2)}:1 {pass ? '✓' : `✗ needs ${m.required}:1`}
</td>
</tr>
);
})}
</tbody>
</table>
);
}
/** Renders a sample and measures its text contrast after layout. */
function Sample({ children }: { children: React.ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
const [items, setItems] = useState<Measurement[]>([]);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
// Measure after the theme/styles have applied
const frame = requestAnimationFrame(() => setItems(measure(el)));
return () => cancelAnimationFrame(frame);
}, []);
return (
<div>
<div ref={ref}>{children}</div>
<Readout items={items} />
</div>
);
}
// ── Page ─────────────────────────────────────────────────────────────────────
// Covers every syntax color: comment, keyword, string, number, function
// (title), params, property
const JS_CODE = [
'// Open the app and wait for the dashboard',
'async function openDashboard(context, timeoutMs) {',
" const url = context.getEnv('BASE_URL');",
' await context.page.goto(url, { timeout: timeoutMs ?? 30000 });',
' return context.page.title();',
'}',
].join('\n');
const JSON_CODE = JSON.stringify(
{ status: 'pass', attempts: 2, cached: false, output: { title: 'Dashboard' } },
null,
2,
);
interface Issue {
title: string;
note: string;
render: () => React.ReactNode;
}
const ISSUES: Issue[] = [
{
title: 'AutoRefreshIndicator label',
note: 'Active ("Live", --color-primary-text), idle and error labels (runs pages).',
render: () => (
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
<AutoRefreshIndicator active pulseKey={1} />
<AutoRefreshIndicator active={false} />
<AutoRefreshIndicator active={false} error />
</div>
),
},
{
title: 'Danger button',
note: 'Danger, primary and secondary buttons (text on colored backgrounds).',
render: () => (
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<Button variant="danger">Delete</Button>
<Button variant="danger" size="sm">
Delete
</Button>
<Button variant="primary">Run</Button>
<Button variant="secondary">Cancel</Button>
</div>
),
},
{
title: 'Code highlighting - JavaScript',
note: 'All --hl-* syntax colors on the page background (step code, snippets).',
render: () => <CodeBlock language="javascript" code={JS_CODE} />,
},
{
title: 'Code highlighting - JSON',
note: 'Keys, strings, numbers and literals in JSON step outputs.',
render: () => <CodeBlock language="json" code={JSON_CODE} />,
},
{
title: 'Muted text',
note: '--color-text-muted on both background shades (hints, table headers, descriptions).',
render: () => (
<div style={{ display: 'flex', gap: 8 }}>
{['var(--color-bg)', 'var(--color-bg-subtle)'].map((bg) => (
<span
key={bg}
style={{
background: bg,
color: 'var(--color-text-muted)',
padding: '4px 8px',
fontSize: 13,
}}
>
Last run 2 minutes ago
</span>
))}
</div>
),
},
];
function Panel({ theme }: { theme: 'light' | 'dark' }) {
return (
<section
// The dark tokens apply under [data-theme="dark"]; light is the page default
data-theme={theme === 'dark' ? 'dark' : undefined}
style={{
flex: '1 1 420px',
minWidth: 0,
padding: 16,
borderRadius: 8,
background: 'var(--color-bg)',
color: 'var(--color-text)',
border: '1px solid var(--color-border)',
}}
>
<h2 style={{ margin: '0 0 12px', fontSize: 16 }}>
{theme === 'dark' ? 'Dark theme' : 'Light theme'}
</h2>
{ISSUES.map((issue) => (
<div key={issue.title} style={{ marginBottom: 24 }}>
<h3 style={{ margin: '0 0 2px', fontSize: 14 }}>{issue.title}</h3>
<p style={{ margin: '0 0 8px', fontSize: 12, color: 'var(--color-text-muted)' }}>
{issue.note}
</p>
<Sample>{issue.render()}</Sample>
</div>
))}
</section>
);
}
function ContrastPage() {
return (
<div style={{ padding: 16 }}>
<p
style={{
margin: '0 0 16px',
fontSize: 13,
color: 'var(--color-text-muted)',
maxWidth: 820,
}}
>
Text contrast of the components where it's easiest to get wrong (WCAG AA: 4.5:1 for normal
text, 3:1 for large text). Each row is a piece of text in the sample, measured from its
rendered colors, worst first.
</p>
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
<Panel theme="light" />
<Panel theme="dark" />
</div>
</div>
);
}
const meta: Meta<typeof ContrastPage> = {
title: 'Accessibility/Contrast',
component: ContrastPage,
// a11y checks use the project default ('error' in preview.tsx)
parameters: { layout: 'fullscreen' },
// The light panel relies on the page default (light) theme
globals: { theme: 'light' },
};
export default meta;
type Story = StoryObj<typeof ContrastPage>;
export const Overview: Story = {};
@@ -15,7 +15,7 @@ const meta: Meta<typeof DescriptionList> = {
), ),
], ],
argTypes: { argTypes: {
layout: { control: 'select', options: ['inline', 'compact'] }, layout: { control: 'select', options: ['inline', 'compact', 'comfortable', 'grid'] },
}, },
}; };
export default meta; export default meta;
@@ -35,6 +35,14 @@ export const Compact: Story = {
args: { items: urlItems, layout: 'compact' }, args: { items: urlItems, layout: 'compact' },
}; };
export const Comfortable: Story = {
args: { items: urlItems, layout: 'comfortable' },
};
export const Grid: Story = {
args: { items: urlItems, layout: 'grid' },
};
export const WithLinks: Story = { export const WithLinks: Story = {
args: { args: {
layout: 'inline', layout: 'inline',
@@ -0,0 +1,197 @@
import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { LogOutput, type LogOutputEntry } from '../../src/ui/LogOutput/LogOutput';
import { formatLogText } from '../../src/ui/LogOutput/logText';
const meta: Meta<typeof LogOutput> = {
title: 'UI/LogOutput',
component: LogOutput,
tags: ['autodocs'],
parameters: { layout: 'padded' },
};
export default meta;
type Story = StoryObj<typeof LogOutput>;
const secondsAgo = (n: number) => new Date(Date.now() - n * 1000).toISOString();
export const Default: Story = {
args: {
startTime: secondsAgo(60),
entries: [
{
id: 0,
level: 'debug',
context: 'step:1',
message: 'Resolved credential alias "sdJwtKey" to a file credential',
createdAt: secondsAgo(61),
},
{
id: 1,
level: 'log',
context: 'step:1',
message: 'Step 1 started: Login with PKCS',
createdAt: secondsAgo(60),
},
{
id: 2,
level: 'log',
context: 'snippet:loginWithPkcs',
message: 'Snippet "loginWithPkcs" started',
createdAt: secondsAgo(58),
},
{
id: 3,
level: 'log',
context: 'snippet:loginWithPkcs',
message: 'Saved credential as run file:',
data: JSON.stringify({
id: '181d8ae2-4aee-4f33-a657-210efe7fe668',
name: 'credential.sd-jwt',
mimeType: 'application/octet-stream',
size: 1657,
sha256: '9c4226999c700a39bda30279907e4479a5b3920ccde5c75771ea0e264c638c0',
path: 'data/files/18/181d/181d8ae2-4aee-4f33-a657-210efe7fe668',
}),
createdAt: secondsAgo(57),
},
{
id: 4,
level: 'log',
context: 'snippet:loginWithPkcs',
message: 'Navigating to ID login: https://id.example.com',
createdAt: secondsAgo(57),
},
{
id: 5,
level: 'log',
context: 'assertion:pass',
message: 'Assertion passed: page must have redirected to cabinet URL',
createdAt: secondsAgo(40),
},
{
id: 6,
level: 'warn',
context: 'snippet:loginWithPkcs',
message: 'Retrying file upload after a transient error',
createdAt: secondsAgo(39),
},
{
id: 7,
level: 'log',
context: 'step:1',
message: 'Step 1 passed',
createdAt: secondsAgo(30),
},
{
id: 8,
level: 'error',
context: 'assertion:fail',
message: 'Assertion failed: Document validation must pass (got 422)',
createdAt: secondsAgo(10),
},
{
id: 9,
level: 'error',
context: 'step:2',
message: 'Step 2 failed: Document validation must pass (got 422)',
createdAt: secondsAgo(9),
},
],
},
};
export const Scrollable: Story = {
args: {
maxHeight: 160,
startTime: secondsAgo(60),
entries: Array.from({ length: 30 }, (_, i) => ({
id: i,
level: (['log', 'log', 'log', 'warn', 'error'] as const)[i % 5],
context: `step:${Math.floor(i / 6) + 1}`,
message: `Log entry ${i + 1}`,
createdAt: secondsAgo(60 - i * 2),
})),
},
};
const largeDataEntries: LogOutputEntry[] = [
{
id: 0,
level: 'log',
context: 'step:1',
message: 'Small payload:',
data: JSON.stringify({ status: 200 }),
createdAt: secondsAgo(20),
},
{
id: 1,
level: 'log',
context: 'step:1',
message: 'Large payload:',
data: JSON.stringify({
user: { id: 42, name: 'Jane Doe', roles: ['admin', 'qa'] },
token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9',
}),
createdAt: secondsAgo(18),
},
{
id: 2,
level: 'warn',
context: 'step:2',
message: 'Another large payload:',
data: JSON.stringify(Array.from({ length: 8 }, (_, i) => ({ row: i }))),
createdAt: secondsAgo(10),
},
];
function LargeDataLog() {
const [expanded, setExpanded] = useState(false);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
<button type="button" onClick={() => setExpanded((v) => !v)}>
{expanded ? 'Collapse all' : 'Expand all'}
</button>
<LogOutput startTime={secondsAgo(20)} entries={largeDataEntries} dataExpanded={expanded} />
</div>
);
}
/** Data blocks over the default limits (256 bytes, 5 lines) start collapsed. */
export const LargeData: Story = {
render: () => <LargeDataLog />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// Data blocks are syntax-highlighted into separate tokens, so check the log's text
const log = canvas.getByRole('log');
// Only the small payload is visible initially
await expect(log).toHaveTextContent('"status": 200');
await expect(log).not.toHaveTextContent('Jane Doe');
const toggles = canvas.getAllByRole('button', { name: /^Show data/ });
await expect(toggles).toHaveLength(2);
await userEvent.click(toggles[0]);
await expect(log).toHaveTextContent('Jane Doe');
await userEvent.click(canvas.getByRole('button', { name: 'Hide data' }));
await expect(log).not.toHaveTextContent('Jane Doe');
await userEvent.click(canvas.getByRole('button', { name: 'Expand all' }));
await expect(log).toHaveTextContent('Jane Doe');
await expect(canvas.getAllByRole('button', { name: 'Hide data' })).toHaveLength(2);
await userEvent.click(canvas.getByRole('button', { name: 'Collapse all' }));
await expect(log).not.toHaveTextContent('Jane Doe');
// The plain-text form always includes every data block
const text = formatLogText(largeDataEntries, largeDataEntries[0].createdAt);
await expect(text).toContain('[step:1] Large payload:\n {');
await expect(text).toContain('"name": "Jane Doe"');
},
};
export const Empty: Story = {
args: {
entries: [],
emptyMessage: 'No logs yet.',
},
};
@@ -0,0 +1,132 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { ApiError } from '../../src/api/client';
import { LoginForm } from '../../src/pages/auth/LoginForm';
const meta: Meta<typeof LoginForm> = {
title: 'Authentication/Login form',
component: LoginForm,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onSubmit: async () => undefined },
decorators: [
(Story) => (
<div style={{ width: 'min(calc(100vw - 32px), 440px)' }}>
<Story />
</div>
),
],
};
export default meta;
type Story = StoryObj<typeof LoginForm>;
async function expectLoginSurfaces(canvasElement: HTMLElement) {
const canvas = within(canvasElement);
const card = canvasElement.querySelector('section');
const notice = canvas.getByText('Your session has expired. Sign in again to continue.');
const username = canvas.getByRole('textbox', { name: 'Username' });
if (!card) throw new Error('Login card was not rendered.');
await expect(window.getComputedStyle(notice).marginBottom).not.toBe('0px');
await expect(window.getComputedStyle(username).backgroundColor).not.toBe(
window.getComputedStyle(card).backgroundColor,
);
}
export const Initial: Story = {};
export const ExpiredSession: Story = {
args: { expired: true },
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
};
export const SignedOut: Story = { args: { signedOut: true } };
export const DarkTheme: Story = {
args: { expired: true },
decorators: [
(Story) => (
<div data-theme="dark" style={{ width: 440, padding: 24, background: 'var(--color-bg)' }}>
<Story />
</div>
),
],
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
};
export const NarrowViewport: Story = {
decorators: [
(Story) => (
<div style={{ width: 320, padding: 16, background: 'var(--color-bg)' }}>
<Story />
</div>
),
],
};
export const EmptyFieldValidation: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.getByText('Enter your username.')).toBeVisible();
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveFocus();
await expect(canvas.getByLabelText('Password')).toHaveAttribute('aria-invalid', 'true');
},
};
export const InvalidCredentials: Story = {
args: {
onSubmit: async () => {
throw new ApiError(401, 'Unauthorized');
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'wrong-password');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(await canvas.findByRole('alert')).toHaveTextContent(
'Username or password is incorrect.',
);
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveValue('operator');
await expect(canvas.getByLabelText('Password')).toHaveValue('');
await expect(canvas.getByLabelText('Password')).toHaveFocus();
},
};
export const RequestFailureAndRetry: Story = {
args: {
onSubmit: (() => {
let attempts = 0;
return async () => {
attempts += 1;
if (attempts === 1) throw new ApiError(503, 'Unavailable');
};
})(),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'temporary');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(await canvas.findByRole('alert')).toHaveTextContent(
"Couldn't sign in. Check your connection and try again.",
);
await expect(canvas.getByLabelText('Password')).toHaveValue('temporary');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.queryByRole('alert')).not.toBeInTheDocument();
},
};
export const Submitting: Story = {
args: { onSubmit: () => new Promise(() => undefined) },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'secret');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.getByRole('status')).toHaveTextContent('Signing in…');
await expect(canvas.getByRole('button', { name: 'Signing in…' })).toBeDisabled();
},
};
@@ -0,0 +1,35 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import { MarkdownContent } from '../../src/ui/MarkdownContent/MarkdownContent';
const meta: Meta<typeof MarkdownContent> = {
title: 'UI/MarkdownContent',
component: MarkdownContent,
parameters: { layout: 'padded' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof MarkdownContent>;
export const Description: Story = {
args: {
content: [
'## Login flow',
'',
'Logs in with the **test user** and checks the dashboard.',
'',
'- Uses the `BASE_URL` environment value',
'- Needs the `user` credential alias',
'',
'```js',
"await context.page.goto(context.getEnv('BASE_URL'));",
'```',
].join('\n'),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('heading', { name: 'Login flow' })).toBeInTheDocument();
await expect(canvas.getByText('test user').tagName).toBe('STRONG');
await expect(canvas.getAllByRole('listitem')).toHaveLength(2);
},
};
@@ -0,0 +1,98 @@
import React, { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { Modal } from '../../src/ui/Modal/Modal';
import { Button } from '../../src/ui/Button/Button';
function ModalDemo({
title,
body,
size,
}: {
title: string;
body: React.ReactNode;
size?: 'md' | 'lg';
}) {
const [open, setOpen] = useState(false);
return (
<>
<Button onClick={() => setOpen(true)}>Open modal</Button>
<Modal
open={open}
size={size}
title={title}
onClose={() => setOpen(false)}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={() => setOpen(false)}>Confirm</Button>
</>
}
>
{body}
</Modal>
</>
);
}
const meta: Meta<typeof ModalDemo> = {
title: 'UI/Modal',
component: ModalDemo,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { title: 'Delete scenario', body: 'This deletes the scenario, its versions and its runs.' },
};
export default meta;
type Story = StoryObj<typeof ModalDemo>;
export const Default: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
const dialog = canvas.getByRole('dialog', { name: 'Delete scenario' });
await expect(dialog).toHaveTextContent('its versions and its runs');
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
},
};
export const ClosesOnEscapeAndBackdrop: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
await userEvent.keyboard('{Escape}');
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
await userEvent.click(canvas.getByRole('presentation'));
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
},
};
export const Large: Story = {
args: {
title: 'Code reference',
size: 'lg',
body: (
<>
{Array.from({ length: 60 }, (_, i) => (
<p key={i}>Paragraph {i + 1} of a long, document-like modal body.</p>
))}
</>
),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
const dialog = canvas.getByRole('dialog', { name: 'Code reference' });
// The dialog stays within the viewport; its body scrolls instead.
await expect(dialog.getBoundingClientRect().height).toBeLessThanOrEqual(window.innerHeight);
const body = within(dialog).getByText(
'Paragraph 1 of a long, document-like modal body.',
).parentElement!;
await expect(body.scrollHeight).toBeGreaterThan(body.clientHeight);
await expect(within(dialog).getByRole('button', { name: 'Confirm' })).toBeVisible();
},
};
@@ -0,0 +1,30 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Notification } from '../../src/ui/Notification/Notification';
const meta: Meta<typeof Notification> = {
title: 'UI/Notification',
component: Notification,
parameters: { layout: 'padded' },
tags: ['autodocs'],
argTypes: {
variant: { control: 'select', options: ['info', 'success', 'error', 'warning', 'note'] },
},
};
export default meta;
type Story = StoryObj<typeof Notification>;
export const Info: Story = {
args: {
variant: 'info',
title: 'Traces are off',
children: 'Enable them per run in the run modal.',
},
};
export const Success: Story = { args: { variant: 'success', children: 'Scenario imported.' } };
export const Error: Story = {
args: { variant: 'error', title: 'Run failed', children: 'Step 2 timed out after 60s.' },
};
export const Warning: Story = {
args: { variant: 'warning', children: 'The environment of this run no longer exists.' },
};
export const Note: Story = { args: { variant: 'note', children: 'Pinned snippet version: v3.' } };
@@ -0,0 +1,17 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import { NotificationToggle } from '../../src/ui/NotificationToggle/NotificationToggle';
const meta: Meta<typeof NotificationToggle> = {
title: 'UI/NotificationToggle',
component: NotificationToggle,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onToggle: fn() },
};
export default meta;
type Story = StoryObj<typeof NotificationToggle>;
export const Off: Story = { args: { state: 'off' } };
export const On: Story = { args: { state: 'on' } };
export const Blocked: Story = { args: { state: 'blocked' } };
@@ -0,0 +1,31 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect } from 'storybook/test';
import { safeReturnTo } from '../../src/auth/returnTo';
function ReturnToSafetyExample() {
return <p>Local return destinations are checked before use.</p>;
}
const meta: Meta<typeof ReturnToSafetyExample> = {
title: 'Authentication/Return destination safety',
component: ReturnToSafetyExample,
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof ReturnToSafetyExample>;
export const Validation: Story = {
play: async () => {
await expect(safeReturnTo('/scenarios/123/runs/456?example=1#details')).toBe(
'/scenarios/123/runs/456?example=1#details',
);
await expect(safeReturnTo('/scenarios')).toBe('/scenarios');
await expect(safeReturnTo('//external.example/path')).toBeNull();
await expect(safeReturnTo('https://external.example/path')).toBeNull();
await expect(safeReturnTo('/%2f%2fexternal.example')).toBeNull();
await expect(safeReturnTo('/%5c%5cexternal.example')).toBeNull();
await expect(safeReturnTo('/login?returnTo=/scenarios')).toBeNull();
await expect(safeReturnTo('/auth/me')).toBeNull();
await expect(safeReturnTo('/%')).toBeNull();
},
};
@@ -0,0 +1,33 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { RevealableCodeBlock } from '../../src/ui/RevealableCodeBlock/RevealableCodeBlock';
const meta: Meta<typeof RevealableCodeBlock> = {
title: 'UI/RevealableCodeBlock',
component: RevealableCodeBlock,
parameters: { layout: 'padded' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof RevealableCodeBlock>;
export const Default: Story = {
args: {
language: 'json',
code: JSON.stringify({ username: 'admin', password: 's3cr3t-p4ss' }, null, 2),
},
play: async ({ canvasElement }) => {
// The code is not rendered until revealed, and hidden again on the second click
const canvas = within(canvasElement);
const toggle = canvas.getByRole('button');
await expect(canvasElement).not.toHaveTextContent('s3cr3t-p4ss');
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await userEvent.click(toggle);
await expect(canvasElement.querySelector('code')).toHaveTextContent('s3cr3t-p4ss');
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await userEvent.click(toggle);
await expect(canvasElement).not.toHaveTextContent('s3cr3t-p4ss');
},
};
@@ -0,0 +1,34 @@
import React, { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { Search } from '../../src/ui/Search/Search';
function ControlledSearch({ placeholder }: { placeholder?: string }) {
const [value, setValue] = useState('');
return (
<div>
<Search value={value} onChange={setValue} placeholder={placeholder} />
<p data-testid="query">{value}</p>
</div>
);
}
const meta: Meta<typeof ControlledSearch> = {
title: 'UI/Search',
component: ControlledSearch,
parameters: { layout: 'centered' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof ControlledSearch>;
export const Default: Story = {};
export const Typing: Story = {
args: { placeholder: 'Filter logs…' },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByPlaceholderText('Filter logs…'), 'timeout');
await expect(canvas.getByTestId('query')).toHaveTextContent('timeout');
},
};
@@ -0,0 +1,34 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { SignOutControl } from '../../src/pages/auth/SignOutControl';
const meta: Meta<typeof SignOutControl> = {
title: 'Authentication/Sign out',
component: SignOutControl,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onSignOut: fn() },
};
export default meta;
type Story = StoryObj<typeof SignOutControl>;
export const Ready: Story = {};
export const Pending: Story = {
args: { pending: true },
play: async ({ canvasElement }) => {
const button = within(canvasElement).getByRole('button', { name: 'Signing out…' });
await expect(button).toBeDisabled();
},
};
export const FailureAndRetry: Story = {
args: { failed: true },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('alert')).toHaveTextContent("Couldn't sign out. Try again.");
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
await expect(args.onSignOut).toHaveBeenCalledTimes(1);
},
};
@@ -0,0 +1,37 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import { Textarea } from '../../src/ui/Textarea/Textarea';
const meta: Meta<typeof Textarea> = {
title: 'UI/Textarea',
component: Textarea,
parameters: { layout: 'centered' },
tags: ['autodocs'],
decorators: [
(Story) => (
<div style={{ width: 360 }}>
<Story />
</div>
),
],
};
export default meta;
type Story = StoryObj<typeof Textarea>;
export const Default: Story = {
args: { label: 'Description', placeholder: 'Describe this scenario', rows: 4 },
};
export const WithHint: Story = {
args: { label: 'Description', hint: 'Markdown is supported.', rows: 4 },
};
export const WithError: Story = {
args: { label: 'Description', error: 'Description is too long.', rows: 4 },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const textarea = canvas.getByLabelText('Description');
await expect(textarea).toHaveAttribute('aria-invalid', 'true');
await expect(canvas.getByRole('alert')).toHaveTextContent('Description is too long.');
},
};
@@ -0,0 +1,41 @@
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { ToastProvider } from '../../src/ui/Toast/ToastProvider';
import { useToast } from '../../src/ui/Toast/useToast';
import { Button } from '../../src/ui/Button/Button';
function ToastButtons() {
const toast = useToast();
return (
<div style={{ display: 'flex', gap: 8 }}>
<Button onClick={() => toast.success('Scenario run started')}>Success</Button>
<Button variant="danger" onClick={() => toast.error('Environment not found')}>
Error
</Button>
<Button variant="secondary" onClick={() => toast.info('Traces are off')}>
Info
</Button>
</div>
);
}
const meta: Meta<typeof ToastProvider> = {
title: 'UI/Toast',
component: ToastProvider,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { durationMs: 3500, children: <ToastButtons /> },
};
export default meta;
type Story = StoryObj<typeof ToastProvider>;
export const Default: Story = {};
export const ShowsToast: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Success' }));
await expect(await within(document.body).findByText('Scenario run started')).toBeVisible();
},
};
@@ -0,0 +1,63 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { useState } from 'react';
import { expect, within } from 'storybook/test';
import { Button } from '../../src/ui/Button/Button';
import { UuidBadge } from '../../src/ui/UuidBadge/UuidBadge';
const meta: Meta<typeof UuidBadge> = {
title: 'UI/UuidBadge',
component: UuidBadge,
parameters: { layout: 'centered' },
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof UuidBadge>;
export const Default: Story = {
args: { id: '61d2b1c2-7664-4dca-974f-436c2ee90b2e' },
play: async ({ canvasElement }) => {
// Shows a shortened id and keeps the full one in the tooltip
const badge = within(canvasElement).getByTitle('61d2b1c2-7664-4dca-974f-436c2ee90b2e');
await expect(badge).toHaveTextContent('61d2…0b2e');
},
};
const SAMPLE_IDS = [
'61d2b1c2-7664-4dca-974f-436c2ee90b2e',
'e83f0a5d-1b9c-4f27-8d6e-2a4c9b7f1e03',
'0c7a94f1-3e52-4b8d-a1f6-9d2e5c8b4a70',
'f4b21e8c-9a07-4c63-b5d2-7e1f0a3c6d98',
'8d5e3a10-c4f7-4e29-9b81-5f6a2d0c7e14',
'2a9fc067-58d3-4a1e-86b4-c3e7f19d5b2a',
];
function Gallery() {
const [ids, setIds] = useState(SAMPLE_IDS);
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 12 }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
{ids.map((id) => (
<UuidBadge key={id} id={id} />
))}
</div>
<Button
size="sm"
variant="secondary"
onClick={() => setIds(ids.map(() => crypto.randomUUID()))}
>
Randomize
</Button>
</div>
);
}
export const Colors: Story = {
render: () => <Gallery />,
play: async ({ canvasElement }) => {
// Each sample id gets its own badge
const canvas = within(canvasElement);
for (const id of SAMPLE_IDS) {
await expect(canvas.getByTitle(id)).toBeInTheDocument();
}
},
};
-20
View File
@@ -1,20 +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
COPY client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
-17
View File
@@ -1,17 +0,0 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://server:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+2
View File
@@ -1,6 +1,8 @@
{ {
"name": "liqa-client", "name": "liqa-client",
"private": true, "private": true,
"license": "MIT",
"author": "Andrii Arsenin",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+80
View File
@@ -36,11 +36,19 @@
min-height: 100%; min-height: 100%;
} }
.footerButtons {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
}
.sideFooter { .sideFooter {
margin-top: auto; margin-top: auto;
padding: var(--space-3) var(--space-2) var(--space-2); padding: var(--space-3) var(--space-2) var(--space-2);
border-top: var(--border-width) solid var(--color-border); border-top: var(--border-width) solid var(--color-border);
display: flex; display: flex;
flex-wrap: wrap;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: var(--space-2); gap: var(--space-2);
@@ -52,6 +60,78 @@
white-space: nowrap; white-space: nowrap;
} }
.versionLink {
color: inherit;
text-decoration: none;
}
.versionLink:hover,
.versionLink:focus-visible {
text-decoration: underline;
}
.signOut,
.expandForSignOut {
display: inline-flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
padding: 0;
color: var(--color-text-muted);
background: transparent;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
cursor: pointer;
}
.signOut:hover,
.expandForSignOut:hover {
color: var(--color-text);
background: var(--color-secondary);
}
.signOut:focus-visible,
.expandForSignOut:focus-visible,
.logoutFailure button:focus-visible {
outline: 2px solid var(--color-primary-text);
outline-offset: 2px;
}
.signOut:disabled {
opacity: 0.55;
cursor: wait;
}
.logoutFailure {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
}
.logoutFailure button {
min-height: 32px;
color: inherit;
background: transparent;
border: var(--border-width) solid currentColor;
border-radius: var(--radius-sm);
cursor: pointer;
}
.expandForSignOut {
position: fixed;
left: 8px;
bottom: 12px;
z-index: 20;
background: var(--color-bg-subtle);
box-shadow: var(--shadow-sm);
}
.navItem { .navItem {
display: flex; display: flex;
align-items: center; align-items: center;
+115 -6
View File
@@ -1,11 +1,19 @@
import { lazy, Suspense } from 'react'; import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { NavLink, Navigate, Route, Routes } from 'react-router-dom'; import { LogOut } from 'lucide-react';
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; 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 type { LucideIcon } from 'lucide-react';
import styles from './App.module.css'; import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui'; import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg'; import liqaLogo from './assets/liqa.svg';
import { useManifest } from './hooks/useManifest';
import { useRunNotifications } from './hooks/useRunNotifications';
import { useAuth } from './auth/useAuth';
import { safeReturnTo } from './auth/returnTo';
import { AuthStatusPage } from './pages/auth/AuthStatusPage';
import { LoginPage } from './pages/auth/LoginPage';
import { SignOutControl } from './pages/auth/SignOutControl';
const EnvironmentsPage = lazy(() => const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })), import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
@@ -89,6 +97,9 @@ const EditSnippetPage = lazy(() =>
const SnippetDetailPage = lazy(() => const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })), 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 } | { separator: true })[] = [ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: true })[] = [
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity }, { path: '/runs', labelKey: 'nav.runs', Icon: Activity },
@@ -98,14 +109,65 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces }, { path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound }, { path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe }, { path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ separator: true },
{ path: '/import', labelKey: 'nav.import', Icon: Upload },
]; ];
export default function App() { export default function App() {
const { t } = useTranslation(); const { t } = useTranslation();
const auth = useAuth();
const location = useLocation();
const [search] = useSearchParams();
const [collapsed, setCollapsed] = useState(false);
const [loggingOut, setLoggingOut] = useState(false);
const [logoutFailed, setLogoutFailed] = useState(false);
const focusSignOut = useRef(false);
const { version } = useManifest();
const notifications = useRunNotifications();
useEffect(() => {
if (!collapsed && focusSignOut.current) {
focusSignOut.current = false;
document.querySelector<HTMLButtonElement>('[data-sign-out="true"]')?.focus();
}
}, [collapsed]);
async function signOut() {
if (loggingOut) return;
setLoggingOut(true);
setLogoutFailed(false);
try {
await auth.logout();
} catch {
setLogoutFailed(true);
} finally {
setLoggingOut(false);
}
}
const onLogin = location.pathname === '/login';
if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) {
return <AuthStatusPage />;
}
if (auth.enabled && auth.status === 'error') {
return <AuthStatusPage failed onRetry={() => void auth.checkSession()} />;
}
if (!auth.enabled && onLogin) return <Navigate to="/scenarios" replace />;
if (auth.enabled && auth.status === 'authenticated' && onLogin) {
return <Navigate to={safeReturnTo(search.get('returnTo')) ?? '/scenarios'} replace />;
}
if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) {
const returnTo =
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
return <Navigate to={`/login?returnTo=${encodeURIComponent(returnTo)}`} replace />;
}
if (onLogin) return <LoginPage />;
return ( return (
<div className={styles.shell}> <div className={styles.shell}>
<SidePanel <SidePanel
collapsed={collapsed}
onCollapsedChange={setCollapsed}
header={ header={
<div className={styles.header}> <div className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.brand} /> <img src={liqaLogo} alt="Liqa" className={styles.brand} />
@@ -134,12 +196,58 @@ export default function App() {
</nav> </nav>
<div className={styles.sideFooter}> <div className={styles.sideFooter}>
<ThemeSwitcher /> <div className={styles.footerButtons}>
<div className={styles.version}>v{__APP_VERSION__}</div> <ThemeSwitcher />
{notifications && (
<NotificationToggle state={notifications.state} onToggle={notifications.toggle} />
)}
{auth.enabled && auth.status === 'authenticated' && (
<SignOutControl
pending={loggingOut}
failed={logoutFailed}
onSignOut={() => void signOut()}
/>
)}
</div>
<div className={styles.version}>
<span
title={
version !== __APP_VERSION__
? t('nav.version_mismatch', { client: __APP_VERSION__ })
: undefined
}
>
v{version}
</span>{' '}
·{' '}
<a
className={styles.versionLink}
href="/licenses.txt"
target="_blank"
rel="noopener noreferrer"
>
{t('nav.licenses')}
</a>
</div>
</div> </div>
</div> </div>
</SidePanel> </SidePanel>
{collapsed && auth.enabled && auth.status === 'authenticated' && (
<button
type="button"
className={styles.expandForSignOut}
aria-label={t('auth.show_sign_out')}
title={t('auth.show_sign_out')}
onClick={() => {
focusSignOut.current = true;
setCollapsed(false);
}}
>
<LogOut size={18} aria-hidden="true" />
</button>
)}
<main className={styles.main}> <main className={styles.main}>
<Suspense fallback={<p>Loading…</p>}> <Suspense fallback={<p>Loading…</p>}>
<Routes> <Routes>
@@ -163,6 +271,7 @@ export default function App() {
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} /> <Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} /> <Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} /> <Route path="/snippets" element={<SnippetsPage />} />
<Route path="/import" element={<ImportPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} /> <Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} /> <Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} /> <Route path="/snippets/:id" element={<SnippetDetailPage />} />
+98 -33
View File
@@ -4,6 +4,7 @@ import type {
Environment, Environment,
FileMetadata, FileMetadata,
FileListResponse, FileListResponse,
ImportResult,
RunDefaults, RunDefaults,
ScenarioCredential, ScenarioCredential,
Session, Session,
@@ -27,7 +28,28 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
'', '',
); );
async function request<T>(path: string, init?: RequestInit): Promise<T> { /** URL of the server-sent events stream of run lifecycle events. */
export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`;
export class ApiError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = 'ApiError';
}
}
interface RequestOptions {
quietErrors?: boolean;
}
async function request<T>(
path: string,
init?: RequestInit,
options: RequestOptions = {},
): Promise<T> {
let res: Response; let res: Response;
try { try {
const headers = new Headers(init?.headers); const headers = new Headers(init?.headers);
@@ -37,18 +59,26 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
res = await fetch(`${BASE_URL}${path}`, { res = await fetch(`${BASE_URL}${path}`, {
...init, ...init,
credentials: init?.credentials ?? 'include',
headers, headers,
}); });
} catch (err) { } catch (err) {
const message = (err as Error).message || 'Network request failed'; const message = (err as Error).message || 'Network request failed';
emitApiErrorToast(message); if (!options.quietErrors) emitApiErrorToast(message);
throw new Error(message); throw new Error(message);
} }
if (!res.ok) { if (!res.ok) {
const text = await res.text().catch(() => res.statusText); const text = await res.text().catch(() => res.statusText);
const message = `${res.status} ${text}`; const message = `${res.status} ${text}`;
emitApiErrorToast(message); const error = new ApiError(res.status, message);
throw new Error(message); if (res.status === 401 && !path.startsWith('/auth/')) {
const event = new CustomEvent('liqa:unauthorized', { cancelable: true });
const handled = !window.dispatchEvent(event);
if (!handled && !options.quietErrors) emitApiErrorToast(message);
} else if (!options.quietErrors && !path.startsWith('/auth/')) {
emitApiErrorToast(message);
}
throw error;
} }
const contentLength = res.headers.get('content-length'); const contentLength = res.headers.get('content-length');
if (res.status === 204 || contentLength === '0') return undefined as T; if (res.status === 204 || contentLength === '0') return undefined as T;
@@ -61,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
return text as T; return text as T;
} }
export interface AuthUser {
id: string;
username: string;
createdAt: string;
updatedAt: string;
}
export const auth = {
async login(username: string, password: string): Promise<AuthUser> {
const response = await request<{ user: AuthUser }>(
'/auth/login',
{ method: 'POST', body: JSON.stringify({ username, password }) },
{ quietErrors: true },
);
return response.user;
},
me(): Promise<AuthUser> {
return request('/auth/me', undefined, { quietErrors: true });
},
logout(): Promise<void> {
return request('/auth/logout', { method: 'POST' }, { quietErrors: true });
},
};
// ── Credentials ─────────────────────────────────────────────────────────────── // ── Credentials ───────────────────────────────────────────────────────────────
export const credentials = { export const credentials = {
@@ -88,12 +142,6 @@ export const credentials = {
exportCredential(id: string): Promise<unknown> { exportCredential(id: string): Promise<unknown> {
return request(`/credentials/${id}/export`); return request(`/credentials/${id}/export`);
}, },
importCredential(payload: unknown): Promise<Credential> {
return request('/credentials/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
}; };
// ── Snippets ────────────────────────────────────────────────────────────────── // ── Snippets ──────────────────────────────────────────────────────────────────
@@ -128,14 +176,9 @@ export const snippets = {
versions(id: string): Promise<SnippetVersion[]> { versions(id: string): Promise<SnippetVersion[]> {
return request(`/snippets/${id}/versions`); return request(`/snippets/${id}/versions`);
}, },
exportSnippet(id: string): Promise<unknown> { exportSnippet(id: string, version?: number): Promise<unknown> {
return request(`/snippets/${id}/export`); const query = version === undefined ? '' : `?version=${version}`;
}, return request(`/snippets/${id}/export${query}`);
importSnippet(payload: unknown): Promise<Snippet> {
return request('/snippets/import', {
method: 'POST',
body: JSON.stringify(payload),
});
}, },
}; };
@@ -169,12 +212,6 @@ export const environments = {
exportEnvironment(id: string): Promise<unknown> { exportEnvironment(id: string): Promise<unknown> {
return request(`/environments/${id}/export`); return request(`/environments/${id}/export`);
}, },
importEnvironment(payload: unknown): Promise<Environment> {
return request('/environments/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
}; };
// ── Sessions ────────────────────────────────────────────────────────────────── // ── Sessions ──────────────────────────────────────────────────────────────────
@@ -264,26 +301,33 @@ export const scenarios = {
}, },
exportScenario( exportScenario(
id: string, id: string,
options: { includeEnvironment: boolean; credentialIds: string[] } = { options: {
includeEnvironment: boolean;
credentialIds: string[];
snippetIds: string[];
version?: number;
} = {
includeEnvironment: false, includeEnvironment: false,
credentialIds: [], credentialIds: [],
snippetIds: [],
}, },
): Promise<string> { ): Promise<string> {
const params = new URLSearchParams(); const params = new URLSearchParams();
params.set('includeEnvironment', String(options.includeEnvironment)); params.set('includeEnvironment', String(options.includeEnvironment));
if (options.version !== undefined) {
params.set('version', String(options.version));
}
for (const cid of options.credentialIds) { for (const cid of options.credentialIds) {
params.append('credentialIds', cid); params.append('credentialIds', cid);
} }
for (const sid of options.snippetIds) {
params.append('snippetIds', sid);
}
return request(`/scenarios/${id}/export?${params.toString()}`); return request(`/scenarios/${id}/export?${params.toString()}`);
}, },
importScenario(payload: unknown): Promise<Scenario> { exportE2eTestUrl(id: string, version?: number): string {
return request('/scenarios/import', { const query = version === undefined ? '' : `?version=${version}`;
method: 'POST', return `${BASE_URL}/scenarios/${id}/export-e2e${query}`;
body: JSON.stringify(payload),
});
},
exportE2eTestUrl(id: string): string {
return `${BASE_URL}/scenarios/${id}/export-e2e`;
}, },
usedSnippets(id: string): Promise<UsedSnippet[]> { usedSnippets(id: string): Promise<UsedSnippet[]> {
return request(`/scenarios/${id}/used-snippets`); return request(`/scenarios/${id}/used-snippets`);
@@ -409,4 +453,25 @@ export const runFiles = {
contentUrl(scenarioId: string, runId: string, fileId: string): string { contentUrl(scenarioId: string, runId: string, fileId: string): string {
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`; 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,
});
},
}; };
+31 -1
View File
@@ -147,7 +147,7 @@ export interface RunDefaults {
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled'; export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
export type LogLevel = 'log' | 'warn' | 'error'; export type LogLevel = 'debug' | 'log' | 'warn' | 'error';
export interface ScenarioRun { export interface ScenarioRun {
id: string; id: string;
@@ -189,7 +189,11 @@ export interface ScenarioRunLog {
runId: string; runId: string;
stepRunId: string | null; stepRunId: string | null;
level: LogLevel; level: LogLevel;
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
context: string | null;
message: string; message: string;
/** JSON payload attached to the message (e.g. a created file's metadata), as a raw string. */
data: string | null;
createdAt: string; createdAt: string;
} }
@@ -214,3 +218,29 @@ export interface FileListResponse {
items: FileMetadata[]; items: FileMetadata[];
total: number; 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[];
}
/** Run lifecycle event pushed by the server on `GET /scenarios/runs/events`. */
export interface RunEvent {
type: 'run.started' | 'run.finished';
runId: string;
scenarioId: string;
scenarioName: string;
status: ScenarioRunStatus;
at: string;
}
+133
View File
@@ -0,0 +1,133 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { ApiError, auth as authApi, type AuthUser } from '../api/client';
import { refreshManifest } from '../lib/manifest';
import { useManifest } from '../hooks/useManifest';
import { loginPath, safeReturnTo } from './returnTo';
import { AuthContext } from './context';
import type { AuthStatus } from './context';
export function AuthProvider({ children }: { children: ReactNode }) {
const { auth: manifestAuth } = useManifest();
const enabled = manifestAuth.enabled;
const location = useLocation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [status, setStatus] = useState<AuthStatus>('checking');
const [user, setUser] = useState<AuthUser | null>(null);
const statusRef = useRef(status);
const enabledRef = useRef(enabled);
const handledUnauthorized = useRef(false);
const checkInFlight = useRef<Promise<void> | null>(null);
useEffect(() => {
enabledRef.current = enabled;
statusRef.current = status;
}, [enabled, status]);
const updateStatus = useCallback((next: AuthStatus) => {
statusRef.current = next;
setStatus(next);
}, []);
const checkSession = useCallback(async () => {
if (!enabledRef.current) {
setUser(null);
updateStatus('disabled');
return;
}
if (checkInFlight.current) return checkInFlight.current;
updateStatus('checking');
const check = authApi
.me()
.then((account) => {
setUser(account);
handledUnauthorized.current = false;
updateStatus('authenticated');
})
.catch((error: unknown) => {
setUser(null);
updateStatus(
error instanceof ApiError && error.status === 401 ? 'unauthenticated' : 'error',
);
})
.finally(() => {
checkInFlight.current = null;
});
checkInFlight.current = check;
return check;
}, [updateStatus]);
useEffect(() => {
if (!enabled) {
// This synchronizes the session state with the server's feature flag.
// eslint-disable-next-line react-hooks/set-state-in-effect
setUser(null);
updateStatus('disabled');
queryClient.clear();
return;
}
void checkSession();
}, [enabled, checkSession, queryClient, updateStatus]);
useEffect(() => {
const onUnauthorized = (event: Event) => {
if (!enabledRef.current) return;
if (handledUnauthorized.current) {
event.preventDefault();
return;
}
if (statusRef.current !== 'authenticated') return;
event.preventDefault();
handledUnauthorized.current = true;
queryClient.clear();
setUser(null);
updateStatus('unauthenticated');
const target =
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
navigate(loginPath(target, true), { replace: true });
};
window.addEventListener('liqa:unauthorized', onUnauthorized);
return () => window.removeEventListener('liqa:unauthorized', onUnauthorized);
}, [location.hash, location.pathname, location.search, navigate, queryClient, updateStatus]);
const login = useCallback(
async (username: string, password: string) => {
let account: AuthUser;
try {
account = await authApi.login(username, password);
} catch (error) {
if (error instanceof ApiError && error.status === 404) await refreshManifest();
throw error;
}
queryClient.clear();
handledUnauthorized.current = false;
setUser(account);
updateStatus('authenticated');
},
[queryClient, updateStatus],
);
const logout = useCallback(async () => {
try {
await authApi.logout();
} catch (error) {
if (!(error instanceof ApiError && error.status === 401)) {
await checkSession();
throw error;
}
}
queryClient.clear();
setUser(null);
updateStatus('unauthenticated');
handledUnauthorized.current = false;
navigate('/login?notice=signedOut', { replace: true });
}, [checkSession, navigate, queryClient, updateStatus]);
return (
<AuthContext.Provider value={{ enabled, status, user, login, logout, checkSession }}>
{children}
</AuthContext.Provider>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { createContext } from 'react';
import type { AuthUser } from '../api/client';
export type AuthStatus = 'disabled' | 'checking' | 'authenticated' | 'unauthenticated' | 'error';
export interface AuthContextValue {
enabled: boolean;
status: AuthStatus;
user: AuthUser | null;
login: (username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkSession: () => Promise<void>;
}
export const AuthContext = createContext<AuthContextValue | null>(null);
+45
View File
@@ -0,0 +1,45 @@
/** Return only a well-formed route on this app's origin. */
export function safeReturnTo(value: string | null | undefined): string | null {
if (
!value ||
!value.startsWith('/') ||
value.startsWith('//') ||
value.includes('\\') ||
/%(?:2f|5c)/i.test(value)
)
return null;
let decoded = value;
try {
for (let pass = 0; pass < 3; pass += 1) {
const next = decodeURIComponent(decoded);
if (next === decoded) break;
decoded = next;
}
} catch {
return null;
}
const containsControl = [...decoded].some((character) => {
const code = character.charCodeAt(0);
return code < 32 || code === 127;
});
if (decoded.startsWith('//') || decoded.includes('\\') || containsControl) {
return null;
}
try {
const target = new URL(value, window.location.origin);
if (target.origin !== window.location.origin) return null;
if (/^\/(?:login|auth)(?:\/|$)/i.test(target.pathname)) return null;
return `${target.pathname}${target.search}${target.hash}`;
} catch {
return null;
}
}
export function loginPath(returnTo: string, expired = false): string {
const query = new URLSearchParams();
query.set('returnTo', safeReturnTo(returnTo) ?? '/scenarios');
if (expired) query.set('expired', '1');
return `/login?${query.toString()}`;
}
+8
View File
@@ -0,0 +1,8 @@
import { useContext } from 'react';
import { AuthContext } from './context';
export function useAuth() {
const value = useContext(AuthContext);
if (!value) throw new Error('useAuth must be used inside AuthProvider');
return value;
}
@@ -0,0 +1,20 @@
.helpButton {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 2px;
border: none;
border-radius: var(--radius-sm);
background: none;
color: var(--color-text-muted);
cursor: pointer;
}
.helpButton:hover {
color: var(--color-primary);
}
.helpButton:focus-visible {
outline: none;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.35);
}
@@ -0,0 +1,54 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleHelp, X } from 'lucide-react';
import { Modal, Button, MarkdownContent } from '../../ui';
import content from './code-help.md?raw';
import styles from './CodeHelpModal.module.css';
export interface CodeHelpModalProps {
open: boolean;
onClose: () => void;
}
/** Reference for the script runtime (`context`, `expect`, ...) available to step and snippet code. */
export function CodeHelpModal({ open, onClose }: CodeHelpModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
size="lg"
title={t('code_help.title')}
onClose={onClose}
footer={
<Button variant="secondary" onClick={onClose}>
<X size={14} />
{t('code_help.close')}
</Button>
}
>
<MarkdownContent content={content} />
</Modal>
);
}
/** A (?) button that opens the {@link CodeHelpModal}; place it next to a code field label. */
export function CodeHelpButton() {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<>
<button
type="button"
className={styles.helpButton}
onClick={() => setOpen(true)}
aria-label={t('code_help.open')}
title={t('code_help.open')}
>
<CircleHelp size={16} />
</button>
<CodeHelpModal open={open} onClose={() => setOpen(false)} />
</>
);
}
@@ -61,3 +61,8 @@
cursor: pointer; cursor: pointer;
accent-color: var(--color-primary); accent-color: var(--color-primary);
} }
.versions {
color: var(--color-text-muted);
font-size: var(--font-size-xs);
}
@@ -1,7 +1,7 @@
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { X, Upload } from 'lucide-react'; import { X, Upload } from 'lucide-react';
import { Modal, Button, UuidBadge } from '../../ui'; import { Modal, Button, UuidBadge } from '../../ui';
import type { Scenario, ScenarioCredential } from '../../api'; import type { Scenario, ScenarioCredential, UsedSnippet } from '../../api';
import styles from './ExportScenarioModal.module.css'; import styles from './ExportScenarioModal.module.css';
export interface ExportScenarioModalProps { export interface ExportScenarioModalProps {
@@ -13,6 +13,9 @@ export interface ExportScenarioModalProps {
onIncludeEnvironmentChange: (v: boolean) => void; onIncludeEnvironmentChange: (v: boolean) => void;
includedCredentialIds: Set<string>; includedCredentialIds: Set<string>;
onCredentialToggle: (id: string, checked: boolean) => void; onCredentialToggle: (id: string, checked: boolean) => void;
usedSnippets: UsedSnippet[];
includedSnippetIds: Set<string>;
onSnippetToggle: (id: string, checked: boolean) => void;
onClose: () => void; onClose: () => void;
onExport: () => void; onExport: () => void;
isExporting: boolean; isExporting: boolean;
@@ -27,12 +30,24 @@ export function ExportScenarioModal({
onIncludeEnvironmentChange, onIncludeEnvironmentChange,
includedCredentialIds, includedCredentialIds,
onCredentialToggle, onCredentialToggle,
usedSnippets,
includedSnippetIds,
onSnippetToggle,
onClose, onClose,
onExport, onExport,
isExporting, isExporting,
}: ExportScenarioModalProps) { }: ExportScenarioModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
// One row per snippet, listing every version the scenario uses (latest or pinned)
const snippetRows = new Map<string, { alias: string; versions: number[] }>();
for (const s of usedSnippets) {
const row = snippetRows.get(s.id) ?? { alias: s.alias, versions: [] };
const version = s.pinnedVersion ?? s.version;
if (!row.versions.includes(version)) row.versions.push(version);
snippetRows.set(s.id, row);
}
return ( return (
<Modal <Modal
open={open} open={open}
@@ -64,6 +79,10 @@ export function ExportScenarioModal({
<UuidBadge id={scenario.id} /> <UuidBadge id={scenario.id} />
</span> </span>
</div> </div>
<div className={styles.metaRow}>
<span className={styles.metaLabel}>{t('scenarios.field_version')}</span>
<span className={styles.metaValue}>v{scenario.version}</span>
</div>
</div> </div>
{environment && ( {environment && (
@@ -95,6 +114,25 @@ export function ExportScenarioModal({
))} ))}
</div> </div>
)} )}
{snippetRows.size > 0 && (
<div className={styles.section}>
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_snippets')}</h4>
{[...snippetRows].map(([snippetId, row]) => (
<label key={snippetId} className={styles.checkboxRow}>
<input
type="checkbox"
checked={includedSnippetIds.has(snippetId)}
onChange={(e) => onSnippetToggle(snippetId, e.target.checked)}
/>
<span>{row.alias}</span>
<span className={styles.versions}>
{row.versions.map((v) => `v${v}`).join(', ')}
</span>
</label>
))}
</div>
)}
</div> </div>
)} )}
</Modal> </Modal>
+195
View File
@@ -0,0 +1,195 @@
Step code and snippet code are the **body of an async function**. Use `await` freely; whatever you `return` becomes the step (or snippet) output.
```js
async (context) => {
// your code here
}
```
All steps of a run share one browser, one browser context and one page, so state carries over from step to step: the current URL, cookies, local storage, open dialogs.
A step **passes** when its code returns, and **fails** when it throws or exceeds its timeout. When a step fails, the remaining steps are cancelled, and a screenshot and the page HTML are saved to the run's files.
## Globals
| Name | Description |
| --- | --- |
| `context` | The run context, described below. |
| `expect` | Playwright's [`expect`](https://playwright.dev/docs/test-assertions), with auto-retrying web assertions. |
| `console` | Writes to the run log: `log`/`info` → `log`, plus `warn`, `error` and `debug`. |
| `args` | **Snippets only.** The extra arguments passed to `context.runSnippet(name, ...args)`. |
Code runs in the server process with Node.js. It is trusted code, not sandboxed.
## Browser
### `context.page`
The Playwright [`Page`](https://playwright.dev/docs/api/class-page) of the run.
```js
await context.page.goto(context.getEnv("base_url"));
await context.page.getByRole("button", { name: "Sign in" }).click();
await expect(context.page.locator("h1")).toHaveText("Dashboard");
```
### `context.browser`
The Playwright [`BrowserContext`](https://playwright.dev/docs/api/class-browsercontext) the page belongs to. Use it for cookies, storage state, extra pages and HTTP requests that share the browser's cookies.
```js
const cookies = await context.browser.cookies();
const res = await context.browser.request.get(context.getEnv("api_url") + "/me");
```
### `context.dumpDom(selector?)` → `Promise<DomNode>`
Returns a simplified tree of the live DOM, starting at `selector` (default `"body"`). Decorative and layout elements are filtered out. The tree keeps landmarks, interactive elements, and elements with `role`, `data-testid`, `data-qa`, `data-action` or `data-element-id`. Each node has `tag` and `children`, plus `role`, `testid`, `id`, `name`, `type`, `text`, `href`, `checked`, `disabled`, etc. when they are present. This is useful for finding selectors without a screenshot.
If nothing matches `selector`, it returns a node with `tag: "ERROR"` instead of throwing.
```js
context.log("Login form:", await context.dumpDom("form"));
```
## Environment
### `context.env`
A copy of the selected environment's key/value map, `{}` when there is none. A missing key reads as `undefined`.
### `context.getEnv(key)` → `string`
Returns the environment value for `key`, and **throws** if it is not defined. Prefer it over `context.env[key]` for required settings: the step then fails with a clear message.
```js
const baseUrl = context.getEnv("base_url");
const locale = context.env.locale ?? "en";
```
## Credentials
### `context.getCredential(alias)` → `unknown`
Returns the payload of the credential assigned to this scenario under `alias` (see **Credentials** on the scenario page). JSON data is returned parsed, anything else as a string. **Throws** if no credential has that alias.
```js
const { username, password } = context.getCredential("admin");
await context.page.getByLabel("Username").fill(username);
await context.page.getByLabel("Password").fill(password);
```
## Step outputs
### `context.getStepOutput(order)` → `Promise<unknown>`
Returns the output (the return value) of another step in the same run. **It is async, so `await` it.**
- A positive `order` is absolute: `1` is the first step.
- A negative `order` is relative: `-1` is the previous step.
Returns `null` if that step does not exist, has not run, or returned nothing. A step's output is stored as JSON, so only JSON-serializable values come back as they were returned (no functions, `Date` becomes a string, Playwright objects are not usable).
```js
// step 2
return { orderId: await context.page.locator("#order-id").textContent() };
// step 3
const { orderId } = await context.getStepOutput(-1);
```
## Logging
### `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`
Write an entry with that level to the run log. `console.*` does the same. Strings, numbers and booleans are joined with spaces into the message. Objects and arrays are kept separate as structured **data**, shown pretty-printed under the message: one object is stored as is, several are stored as an array.
```js
context.log("Created user", user.id, user); // message "Created user 42", data = user
```
Every entry is tagged with where it came from: `step:<N>`, or `snippet:<alias>` while a snippet runs.
## Assertions
### `context.assert(fn, description, details?)` → `Promise<void>`
Runs `fn` (sync or async) and requires it to return exactly `true`.
- On success, it logs `description` (tagged `assertion:pass`).
- If `fn` returns anything else or throws, it logs `Assertion failed: <description>` as an error (tagged `assertion:fail`) and throws, which fails the step. The entry's data holds `details` (if given) and the exception message as `error` (if `fn` threw).
Await it, or a failure will not stop the step.
```js
await context.assert(
async () => (await context.page.locator(".cart-item").count()) === 3,
"Cart contains 3 items",
);
```
Pass large diagnostics (e.g. a response body) as `details` rather than in `description`, so the message stays short:
```js
await context.assert(() => response.ok(), "Validation must pass", {
status: response.status(),
body: await response.json(),
});
```
Use `expect` instead for assertions that wait and retry until the page matches, e.g. `await expect(locator).toBeVisible()`.
## Snippets
### `context.runSnippet(name, ...args)` → `Promise<unknown>`
Runs a stored snippet with the same `context` (same page, environment and credentials) and returns the snippet's return value. Extra arguments are available inside the snippet as `args`.
- `name` is the snippet alias, which runs its latest version.
- `alias@<version>` (e.g. `login@3`) pins a specific version.
Start, finish and failure are logged. If the snippet throws, the error propagates and fails the calling step unless you catch it. Snippets can call other snippets.
```js
// step code
const user = await context.runSnippet("login", "admin", { remember: true });
// snippet "login"
const [alias, opts] = args;
const { username, password } = context.getCredential(alias);
// ...
return { username };
```
## Files
### `context.getScenarioFiles(opts?)` → `Promise<{ items, total }>`
Lists the files uploaded to this scenario (see **Files** on the scenario page). `opts` takes `limit` and `offset` for paging. Each item has `id`, `name`, `mimeType`, `size`, `sha256` and `path`, the absolute path on the server's disk, which you can pass to Playwright:
```js
const { items } = await context.getScenarioFiles();
const doc = items.find((f) => f.name === "contract.pdf");
await context.page.locator("input[type=file]").setInputFiles(doc.path);
```
### `context.downloadFile(url, opts?)` → `Promise<FileInfo>`
Fetches `url` on the server and saves the response as a file of the current run. It returns the same fields as a scenario file (`id`, `name`, `mimeType`, `size`, `sha256`, `path`).
- `opts`: `method`, `headers`, `body` (a string) and `filename`. Without `filename`, the last segment of the URL path is used, and the MIME type is derived from the file extension.
- Redirects are followed. Any final status other than 200 throws. The limits are 100 MB and a 30 s timeout.
- `url` may be a `data:` URI (`data:<type>;base64,<data>` or `data:<type>,<percent-encoded>`), which saves content generated in the script without a network request. Pass `filename` in this case.
- Only works during a real scenario run. It throws in ad-hoc execution such as the `exec_code` MCP tool.
- This is a server-side request: it does **not** send the browser's cookies. Pass them in `headers` if the URL needs a session.
```js
await context.downloadFile(
"data:application/json;base64," + btoa(JSON.stringify(report)),
{ filename: "report.json" },
);
```
## Timeouts
Each step has its own timeout, or else the scenario's timeout, or else 60 s. The whole run fails once it exceeds the scenario's timeout (600 s by default). That check happens between steps.
+2
View File
@@ -6,3 +6,5 @@ export { RunScenarioModal } from './RunScenarioModal';
export type { RunScenarioModalProps } from './RunScenarioModal'; export type { RunScenarioModalProps } from './RunScenarioModal';
export { ExportLogsModal } from './ExportLogsModal'; export { ExportLogsModal } from './ExportLogsModal';
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal'; export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
export { CodeHelpModal, CodeHelpButton } from './CodeHelpModal';
export type { CodeHelpModalProps } from './CodeHelpModal';
+43
View File
@@ -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
}
};
}
+10
View File
@@ -0,0 +1,10 @@
import { useSyncExternalStore } from 'react';
import { getManifest, subscribeManifest, type Manifest } from '../lib/manifest';
/**
* Public client configuration from the server's /manifest.json: the cached
* copy (or defaults) at first, updated once the fresh one arrives.
*/
export function useManifest(): Manifest {
return useSyncExternalStore(subscribeManifest, getManifest);
}
+184
View File
@@ -0,0 +1,184 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { RUN_EVENTS_URL } from '../api/client';
import type { RunEvent } from '../api/types';
import type { NotificationToggleState } from '../ui';
import { useAuth } from '../auth/useAuth';
const STORAGE_KEY = 'liqa-run-notifications';
const RETRY_MIN_MS = 1_000;
const RETRY_MAX_MS = 30_000;
export function createRunEventSource(): EventSource {
return new EventSource(RUN_EVENTS_URL, { withCredentials: true });
}
function supported(): boolean {
return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window;
}
/** The stored choice: `null` until the user toggles notifications explicitly. */
function readEnabled(): boolean | null {
try {
const value = localStorage.getItem(STORAGE_KEY);
return value === null ? null : value === '1';
} catch {
return null;
}
}
function writeEnabled(enabled: boolean): void {
try {
localStorage.setItem(STORAGE_KEY, enabled ? '1' : '0');
} catch {
// storage unavailable: the choice just doesn't persist
}
}
/**
* Opt-in browser notifications for run start/finish, driven by the server's
* run events stream (so runs started from the API, MCP or the scheduler are
* covered too). Returns `null` when the browser lacks Notification/EventSource.
*/
export function useRunNotifications(): {
state: NotificationToggleState;
toggle: () => void;
} | null {
const auth = useAuth();
const isSupported = supported();
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [stored, setStored] = useState(readEnabled);
const [permission, setPermission] = useState<NotificationPermission>(() =>
isSupported ? Notification.permission : 'denied',
);
// Permission granted outside the toggle (browser prompt or site settings)
// enables notifications unless the user turned them off explicitly
const enabled = stored ?? permission === 'granted';
// Follow permission changes made in the browser's site settings
useEffect(() => {
if (!isSupported) return;
const sync = () => setPermission(Notification.permission);
let status: PermissionStatus | undefined;
let cancelled = false;
navigator.permissions
?.query({ name: 'notifications' })
.then((s) => {
if (cancelled) return;
status = s;
status.addEventListener('change', sync);
})
.catch(() => {});
window.addEventListener('focus', sync);
return () => {
cancelled = true;
status?.removeEventListener('change', sync);
window.removeEventListener('focus', sync);
};
}, [isSupported]);
// Latest callbacks without reopening the stream when they change
const handlers = useRef({ t, navigate });
useEffect(() => {
handlers.current = { t, navigate };
});
const active =
isSupported &&
enabled &&
permission === 'granted' &&
(!auth.enabled || auth.status === 'authenticated');
useEffect(() => {
if (!active) return;
let source: EventSource;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let retryDelay = RETRY_MIN_MS;
const onEvent = (message: MessageEvent<string>) => {
let event: RunEvent;
try {
event = JSON.parse(message.data) as RunEvent;
} catch {
return;
}
if (event.type === 'run.finished') {
void queryClient.invalidateQueries({ queryKey: ['runs'] });
}
const { t: translate, navigate: go } = handlers.current;
const key =
event.type === 'run.started'
? 'run_started'
: event.status === 'pass'
? 'run_pass'
: 'run_fail';
const notification = new Notification(
translate(`notifications.${key}_title`, { scenario: event.scenarioName }),
{
body: translate(`notifications.${key}_body`),
// finished replaces started for the same run
tag: event.runId,
},
);
notification.onclick = () => {
window.focus();
go(`/scenarios/${event.scenarioId}/runs/${event.runId}`);
notification.close();
};
};
const connect = () => {
source = createRunEventSource();
source.addEventListener('open', () => {
retryDelay = RETRY_MIN_MS;
});
// The browser retries transient errors itself, but some failures close
// the stream for good (e.g. Firefox drops quiet connections after a
// network change), so reopen it with backoff
source.addEventListener('error', () => {
if (source.readyState !== EventSource.CLOSED) return;
retryTimer = setTimeout(connect, retryDelay);
retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS);
});
source.addEventListener('run.started', onEvent as EventListener);
source.addEventListener('run.finished', onEvent as EventListener);
};
connect();
return () => {
clearTimeout(retryTimer);
source.close();
};
}, [active, queryClient]);
const toggle = useCallback(() => {
if (!isSupported) return;
if (Notification.permission === 'default') {
void Notification.requestPermission().then((result) => {
setPermission(result);
if (result === 'granted') {
setStored(true);
writeEnabled(true);
}
});
return;
}
if (Notification.permission !== 'granted') {
setPermission(Notification.permission);
return;
}
const next = !enabled;
setStored(next);
writeEnabled(next);
}, [isSupported, enabled]);
if (!isSupported) return null;
return {
state: permission === 'denied' ? 'blocked' : active ? 'on' : 'off',
toggle,
};
}
+75 -4
View File
@@ -1,4 +1,24 @@
{ {
"auth": {
"page_title": "Sign in",
"sign_in": "Sign in",
"signing_in": "Signing in…",
"username": "Username",
"password": "Password",
"username_required": "Enter your username.",
"password_required": "Enter your password.",
"invalid_credentials": "Username or password is incorrect.",
"sign_in_failed": "Couldn't sign in. Check your connection and try again.",
"checking_session": "Checking your session…",
"session_check_failed": "Couldn't check your session. Try again.",
"retry": "Retry",
"session_expired": "Your session has expired. Sign in again to continue.",
"sign_out": "Sign out",
"signing_out": "Signing out…",
"signed_out": "You have signed out.",
"sign_out_failed": "Couldn't sign out. Try again.",
"show_sign_out": "Expand the menu to sign out"
},
"common": { "common": {
"button_cancel": "Cancel", "button_cancel": "Cancel",
"button_confirm": "Confirm", "button_confirm": "Confirm",
@@ -12,6 +32,11 @@
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?", "confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
"save_session": "Save session" "save_session": "Save session"
}, },
"code_help": {
"open": "Code reference",
"title": "Code reference",
"close": "Close"
},
"errors": { "errors": {
"not_found": "Not found", "not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.", "not_found_session": "Session {{id}} does not exist or has been deleted.",
@@ -22,13 +47,32 @@
"generic": "Something went wrong. Please try again." "generic": "Something went wrong. Please try again."
}, },
"nav": { "nav": {
"licenses": "Licenses",
"version_mismatch": "Server version; this page was built for v{{client}}. Reload to update.",
"environments": "Environments", "environments": "Environments",
"credentials": "Credentials", "credentials": "Credentials",
"snippets": "Snippets", "snippets": "Snippets",
"keys": "Keys", "keys": "Keys",
"sessions": "Sessions", "sessions": "Sessions",
"scenarios": "Scenarios", "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": { "environments": {
"title": "Environments", "title": "Environments",
@@ -200,11 +244,10 @@
"export_modal_title": "Export Scenario", "export_modal_title": "Export Scenario",
"export_include_environment": "Include Environment", "export_include_environment": "Include Environment",
"export_include_credentials": "Include Credentials", "export_include_credentials": "Include Credentials",
"export_include_snippets": "Include Snippets",
"form_timeout": "Scenario Timeout (seconds)", "form_timeout": "Scenario Timeout (seconds)",
"form_timeout_placeholder": "Default: 600", "form_timeout_placeholder": "Default: 600",
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)", "form_timeout_hint": "Max seconds for the entire scenario run (default: 600)"
"field_name": "Name",
"field_id": "ID"
}, },
"theme": { "theme": {
"switch_to_light": "Switch to light theme", "switch_to_light": "Switch to light theme",
@@ -212,6 +255,22 @@
"light_mode": "Light mode", "light_mode": "Light mode",
"dark_mode": "Dark mode" "dark_mode": "Dark mode"
}, },
"notifications": {
"enable": "Enable browser notifications for runs",
"disable": "Disable browser notifications for runs",
"blocked": "Notifications are blocked in your browser settings",
"run_started_title": "Run started: {{scenario}}",
"run_started_body": "The scenario run is in progress.",
"run_pass_title": "Run passed: {{scenario}}",
"run_pass_body": "All steps passed.",
"run_fail_title": "Run failed: {{scenario}}",
"run_fail_body": "The scenario run failed."
},
"revealable": {
"hidden": "Hidden so secrets aren't exposed on screen.",
"reveal": "Reveal",
"hide": "Hide"
},
"pagination": { "pagination": {
"prev": "Previous page", "prev": "Previous page",
"next": "Next page", "next": "Next page",
@@ -276,6 +335,14 @@
"log_message": "Message", "log_message": "Message",
"log_time": "Time", "log_time": "Time",
"action_download_logs": "Download logs", "action_download_logs": "Download logs",
"action_copy_logs": "Copy logs",
"logs_copied": "Logs copied to clipboard",
"logs_copy_failed": "Could not copy logs to clipboard",
"logs_expand_data": "Expand data",
"logs_collapse_data": "Collapse data",
"logs_show_data_one": "Show data ({{size}}, {{count}} line)",
"logs_show_data_other": "Show data ({{size}}, {{count}} lines)",
"logs_hide_data": "Hide data",
"action_repeat": "Repeat run", "action_repeat": "Repeat run",
"repeat_no_environment": "The environment used by this run no longer exists", "repeat_no_environment": "The environment used by this run no longer exists",
"export_logs_modal_title": "Export logs", "export_logs_modal_title": "Export logs",
@@ -334,6 +401,10 @@
"expiresAtLabel": "Expires At (optional)", "expiresAtLabel": "Expires At (optional)",
"createdAt": "Created", "createdAt": "Created",
"download": "Download", "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", "expiredTooltip": "File is expired",
"empty": "No files uploaded.", "empty": "No files uploaded.",
"totalCount": "Total: {{count}} file(s)", "totalCount": "Total: {{count}} file(s)",
+130
View File
@@ -0,0 +1,130 @@
import { DEFAULT_LOG_DATA_LIMITS, type LogDataLimits } from '../ui/LogOutput/logText';
/** Public client configuration served by the server at /manifest.json. */
export interface Manifest {
name: string;
/** Server version; can differ from the client build's __APP_VERSION__ until the page is reloaded. */
version: string;
runLogs: {
dataLimits: LogDataLimits;
};
auth: {
enabled: boolean;
};
}
export const DEFAULT_MANIFEST: Manifest = {
name: 'liqa',
version: __APP_VERSION__,
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
auth: { enabled: false },
};
const STORAGE_KEY = 'liqa-manifest';
/** A tab coming back into view refetches the manifest if it is older than this. */
const REFRESH_AFTER_MS = 5 * 60 * 1000;
// Served next to the API's /api/v1 (so "/manifest.json" by default, or on
// VITE_API_URL's origin when the client talks to another server)
const MANIFEST_URL = new URL(
'../../manifest.json',
new URL(
`${(import.meta.env.VITE_API_URL ?? '/api/v1').replace(/\/$/, '')}/`,
window.location.href,
),
).toString();
/** Fills fields missing from `raw` (e.g. a manifest cached by an older version) with defaults. */
function normalize(raw: unknown): Manifest | null {
if (typeof raw !== 'object' || raw === null) return null;
const m = raw as Partial<Manifest>;
const limits: Partial<LogDataLimits> = m.runLogs?.dataLimits ?? {};
const num = (v: unknown, fallback: number) => (typeof v === 'number' && v >= 0 ? v : fallback);
return {
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
auth: { enabled: m.auth?.enabled === true },
runLogs: {
dataLimits: {
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
lines: num(limits.lines, DEFAULT_LOG_DATA_LIMITS.lines),
},
},
};
}
// Storage can be unavailable (private mode, blocked site data): the manifest
// then just comes from the network on every page load
function readCache(): Manifest | null {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? normalize(JSON.parse(stored)) : null;
} catch {
return null;
}
}
function writeCache(manifest: Manifest) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(manifest));
} catch {
// ignore, see readCache
}
}
let current: Manifest = readCache() ?? DEFAULT_MANIFEST;
let fetchedAt = 0;
let inFlight: Promise<void> | null = null;
const listeners = new Set<() => void>();
/**
* Fetches the manifest and notifies subscribers if it changed. Failures are
* silent: the cached (or default) manifest stays in use.
*/
export function refreshManifest(): Promise<void> {
inFlight ??= fetch(MANIFEST_URL, {
headers: { Accept: 'application/json' },
credentials: 'include',
})
.then((res) => (res.ok ? res.json() : null))
.then((raw: unknown) => {
const next = normalize(raw);
if (!next) return;
fetchedAt = Date.now();
writeCache(next);
if (JSON.stringify(next) !== JSON.stringify(current)) {
current = next;
listeners.forEach((l) => l());
}
})
.catch(() => undefined)
.finally(() => {
inFlight = null;
});
return inFlight;
}
function onVisibilityChange() {
if (document.visibilityState === 'visible' && Date.now() - fetchedAt > REFRESH_AFTER_MS) {
void refreshManifest();
}
}
/**
* Stale-while-revalidate: subscribers get the localStorage copy right away,
* and the manifest is refetched once per page load (the server answers 304
* while it is unchanged) and when the tab becomes visible again after a while.
*/
export function subscribeManifest(listener: () => void): () => void {
if (listeners.size === 0) document.addEventListener('visibilitychange', onVisibilityChange);
listeners.add(listener);
if (fetchedAt === 0) void refreshManifest();
return () => {
listeners.delete(listener);
if (listeners.size === 0) document.removeEventListener('visibilitychange', onVisibilityChange);
};
}
export function getManifest(): Manifest {
return current;
}
+13 -2
View File
@@ -6,15 +6,26 @@ import './i18n';
import './ui/tokens.css'; import './ui/tokens.css';
import App from './App'; import App from './App';
import { ToastProvider } from './ui'; import { ToastProvider } from './ui';
import { AuthProvider } from './auth/AuthContext';
import { ApiError } from './api/client';
const queryClient = new QueryClient(); const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: (failureCount, error) =>
error instanceof ApiError && error.status === 401 ? false : failureCount < 3,
},
},
});
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<ToastProvider> <ToastProvider>
<BrowserRouter> <BrowserRouter>
<App /> <AuthProvider>
<App />
</AuthProvider>
</BrowserRouter> </BrowserRouter>
</ToastProvider> </ToastProvider>
</QueryClientProvider> </QueryClientProvider>
+6
View File
@@ -255,6 +255,12 @@
color: var(--color-text); color: var(--color-text);
} }
.labelRow {
display: flex;
align-items: center;
gap: var(--space-1);
}
.textarea { .textarea {
width: 100%; width: 100%;
padding: var(--space-2) var(--space-3); padding: var(--space-2) var(--space-3);
@@ -0,0 +1,57 @@
.page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
color: var(--color-text);
background: var(--color-bg);
font-family: var(--font-family);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
}
.logo {
display: block;
width: auto;
height: 32px;
padding: 3px 6px;
background: #e6edea;
border-radius: var(--radius-md);
}
.main {
flex: 1;
display: grid;
place-items: center;
padding: var(--space-6) 0;
}
.message {
width: min(100%, 440px);
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-4);
margin: 0;
padding: var(--space-6);
text-align: center;
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
}
.message p {
margin: 0;
color: var(--color-error-fg);
}
@media (max-width: 480px) {
.page {
padding: 16px;
}
}
+38
View File
@@ -0,0 +1,38 @@
import { useTranslation } from 'react-i18next';
import { Button, ThemeSwitcher } from '../../ui';
import { usePageTitle } from '../../hooks/usePageTitle';
import liqaLogo from '../../assets/liqa.svg';
import styles from './AuthStatusPage.module.css';
export function AuthStatusPage({
failed = false,
onRetry,
}: {
failed?: boolean;
onRetry?: () => void;
}) {
const { t } = useTranslation();
usePageTitle(t('auth.page_title'));
return (
<div className={styles.page}>
<header className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
<ThemeSwitcher />
</header>
<main className={styles.main} aria-live="polite">
{failed ? (
<section className={styles.message}>
<p role="alert">{t('auth.session_check_failed')}</p>
<Button type="button" size="lg" onClick={onRetry}>
{t('auth.retry')}
</Button>
</section>
) : (
<p className={styles.message} role="status">
{t('auth.checking_session')}
</p>
)}
</main>
</div>
);
}
@@ -0,0 +1,65 @@
.card {
width: min(100%, 400px);
padding: 24px;
color: var(--color-text);
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
}
.title {
margin: 0 0 var(--space-5);
font-size: var(--font-size-lg);
line-height: 1.3;
text-align: center;
}
.title:focus {
outline: 2px solid var(--color-primary-text);
outline-offset: 4px;
border-radius: var(--radius-sm);
}
.notice,
.formError {
margin: 0;
padding: var(--space-3) var(--space-4);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-md);
font-size: var(--font-size-sm);
}
.notice {
margin-bottom: var(--space-4);
}
.form .loginInput {
background: var(--color-bg-subtle);
}
.form {
display: flex;
flex-direction: column;
gap: var(--space-4);
}
.submit {
width: 100%;
}
.status {
margin: 0;
color: var(--color-text-muted);
font-size: var(--font-size-sm);
}
@media (max-width: 480px) {
.card {
padding: var(--space-4);
border: 0;
border-radius: 0;
box-shadow: none;
}
}
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { ApiError } from '../../api/client';
import { Button, Input } from '../../ui';
import styles from './LoginForm.module.css';
export interface LoginFormProps {
expired?: boolean;
signedOut?: boolean;
onSubmit: (username: string, password: string) => Promise<void>;
}
export function LoginForm({ expired = false, signedOut = false, onSubmit }: LoginFormProps) {
const { t } = useTranslation();
const titleRef = useRef<HTMLHeadingElement>(null);
const formRef = useRef<HTMLFormElement>(null);
const focusPasswordAfterInvalidCredentialsRef = useRef(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [usernameError, setUsernameError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [formError, setFormError] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
titleRef.current?.focus();
}, []);
useEffect(() => {
if (!submitting && focusPasswordAfterInvalidCredentialsRef.current) {
focusPasswordAfterInvalidCredentialsRef.current = false;
formRef.current?.querySelector<HTMLInputElement>('input[name="password"]')?.focus();
}
}, [submitting]);
function focusInput(name: string) {
formRef.current?.querySelector<HTMLInputElement>(`input[name="${name}"]`)?.focus();
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (submitting) return;
setFormError('');
const missingUsername = username.trim().length === 0;
const missingPassword = password.length === 0;
setUsernameError(missingUsername ? t('auth.username_required') : '');
setPasswordError(missingPassword ? t('auth.password_required') : '');
if (missingUsername || missingPassword) {
focusInput(missingUsername ? 'username' : 'password');
return;
}
setSubmitting(true);
try {
await onSubmit(username, password);
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
setFormError(t('auth.invalid_credentials'));
setPassword('');
focusPasswordAfterInvalidCredentialsRef.current = true;
} else {
setFormError(t('auth.sign_in_failed'));
}
} finally {
setSubmitting(false);
}
}
return (
<section className={styles.card} aria-labelledby="login-title">
<h1 id="login-title" ref={titleRef} tabIndex={-1} className={styles.title}>
{t('auth.sign_in')}
</h1>
{expired && <p className={styles.notice}>{t('auth.session_expired')}</p>}
{signedOut && <p className={styles.notice}>{t('auth.signed_out')}</p>}
<form
ref={formRef}
className={styles.form}
onSubmit={(event) => void handleSubmit(event)}
noValidate
>
<Input
name="username"
className={styles.loginInput}
label={t('auth.username')}
autoComplete="username"
autoCapitalize="none"
autoCorrect="off"
value={username}
onChange={(event) => {
setUsername(event.target.value);
if (usernameError) setUsernameError('');
}}
error={usernameError || undefined}
disabled={submitting}
/>
<Input
name="password"
className={styles.loginInput}
type="password"
label={t('auth.password')}
autoComplete="current-password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
if (passwordError) setPasswordError('');
}}
error={passwordError || undefined}
disabled={submitting}
/>
{formError && (
<p className={styles.formError} role="alert">
{formError}
</p>
)}
{submitting && (
<p className={styles.status} role="status" aria-live="polite">
{t('auth.signing_in')}
</p>
)}
<Button
type="submit"
size="lg"
loading={submitting}
disabled={submitting}
className={styles.submit}
>
{t(submitting ? 'auth.signing_in' : 'auth.sign_in')}
</Button>
</form>
</section>
);
}
@@ -0,0 +1,44 @@
.page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
color: var(--color-text);
background: var(--color-bg);
font-family: var(--font-family);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
}
.logo {
display: block;
width: auto;
height: 32px;
padding: 3px 6px;
background: #e6edea;
border-radius: var(--radius-md);
}
.main {
flex: 1;
min-height: 0;
display: grid;
place-items: center;
padding: var(--space-6) 0;
}
@media (max-width: 480px) {
.page {
padding: 16px;
}
.main {
align-items: start;
padding-top: clamp(40px, 12vh, 96px);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { useCallback } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../../auth/useAuth';
import { safeReturnTo } from '../../auth/returnTo';
import { usePageTitle } from '../../hooks/usePageTitle';
import { ThemeSwitcher } from '../../ui';
import liqaLogo from '../../assets/liqa.svg';
import { LoginForm } from './LoginForm';
import styles from './LoginPage.module.css';
export function LoginPage() {
const auth = useAuth();
const navigate = useNavigate();
const [search] = useSearchParams();
const { t } = useTranslation();
const returnTo = safeReturnTo(search.get('returnTo')) ?? '/scenarios';
const expired = search.get('expired') === '1';
const signedOut = search.get('notice') === 'signedOut';
usePageTitle(t('auth.page_title'));
const handleSubmit = useCallback(
async (username: string, password: string) => {
await auth.login(username, password);
navigate(returnTo, { replace: true });
},
[auth, navigate, returnTo],
);
return (
<div className={styles.page}>
<header className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
<ThemeSwitcher />
</header>
<main className={styles.main}>
<LoginForm expired={expired} signedOut={signedOut} onSubmit={handleSubmit} />
</main>
</div>
);
}
@@ -0,0 +1,57 @@
.root {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.button {
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
color: var(--color-text);
background: transparent;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
font: inherit;
font-size: var(--font-size-xs);
cursor: pointer;
}
.button:hover:not(:disabled) {
background: var(--color-secondary);
}
.button:focus-visible,
.failure button:focus-visible {
outline: 2px solid var(--color-primary-text);
outline-offset: 2px;
}
.button:disabled {
opacity: 0.55;
cursor: wait;
}
.failure {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
}
.failure button {
min-height: 32px;
color: inherit;
background: transparent;
border: var(--border-width) solid currentColor;
border-radius: var(--radius-sm);
cursor: pointer;
}
+39
View File
@@ -0,0 +1,39 @@
import { LogOut } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import styles from './SignOutControl.module.css';
export function SignOutControl({
pending = false,
failed = false,
onSignOut,
}: {
pending?: boolean;
failed?: boolean;
onSignOut: () => void;
}) {
const { t } = useTranslation();
return (
<div className={styles.root}>
<button
type="button"
className={styles.button}
onClick={onSignOut}
disabled={pending}
data-sign-out="true"
aria-label={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
title={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
>
<LogOut size={16} aria-hidden="true" />
<span>{t(pending ? 'auth.signing_out' : 'auth.sign_out')}</span>
</button>
{failed && (
<div className={styles.failure} role="alert">
<span>{t('auth.sign_out_failed')}</span>
<button type="button" onClick={onSignOut} disabled={pending}>
{t('auth.retry')}
</button>
</div>
)}
</div>
);
}
@@ -3,11 +3,18 @@ import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react'; import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml'; import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api'; import { credentials } from '../../api';
import type { Credential } from '../../api'; import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui'; import {
Breadcrumbs,
Button,
Card,
DescriptionList,
RevealableCodeBlock,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals'; import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
@@ -117,7 +124,8 @@ export function CredentialDetailPage() {
<div className={styles.stepsSection}> <div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2> <h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
<Card> <Card>
<CodeBlock <RevealableCodeBlock
key={credential.id}
language="json" language="json"
code={(() => { code={(() => {
try { try {
@@ -2,8 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { useImportFile } from '../../hooks/useImportFile';
import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react'; import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { credentials } from '../../api'; import { credentials } from '../../api';
import type { Credential } from '../../api'; import type { Credential } from '../../api';
import { import {
@@ -102,7 +102,6 @@ function AddCredentialCard() {
export function CredentialsPage() { export function CredentialsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
usePageTitle(t('credentials.title')); usePageTitle(t('credentials.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Credential[]>([]); const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
@@ -136,19 +135,7 @@ export function CredentialsPage() {
} }
}; };
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleImport = useImportFile('credential');
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 {
// Import errors are silently ignored
}
};
return ( return (
<div> <div>
@@ -2,8 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { useImportFile } from '../../hooks/useImportFile';
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react'; import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { stringify as yamlStringify } from 'yaml'; import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api'; import { environments } from '../../api';
import type { Environment } from '../../api'; import type { Environment } from '../../api';
@@ -119,7 +119,6 @@ function AddEnvironmentCard() {
export function EnvironmentsPage() { export function EnvironmentsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
usePageTitle(t('environments.title')); usePageTitle(t('environments.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Environment[]>([]); const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
@@ -153,19 +152,7 @@ export function EnvironmentsPage() {
} }
}; };
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleImport = useImportFile('environment');
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 {
// Import errors are silently ignored
}
};
return ( return (
<div> <div>
+116
View File
@@ -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>
);
}
+132 -49
View File
@@ -1,20 +1,23 @@
import { useEffect, useRef, useState, useCallback } from 'react'; import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom'; import { useNavigate, useParams, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useManifest } from '../../hooks/useManifest';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { runs, runFiles } from '../../api'; import { runs, runFiles } from '../../api';
import type { import type {
Scenario, Scenario,
ScenarioRunDetail, ScenarioRunDetail,
ScenarioRunStep, ScenarioRunStep,
ScenarioRunLog,
ScenarioRunStatus, ScenarioRunStatus,
RunStepStatus, RunStepStatus,
LogLevel,
FileMetadata, FileMetadata,
} from '../../api'; } from '../../api';
import { scenarios } from '../../api'; import { scenarios } from '../../api';
import { ExportLogsModal, type LogExportFormat } from '../../components/modals'; import {
DeleteConfirmationModal,
ExportLogsModal,
type LogExportFormat,
} from '../../components/modals';
import { import {
AutoRefreshIndicator, AutoRefreshIndicator,
Badge, Badge,
@@ -23,7 +26,9 @@ import {
Card, Card,
CodeBlock, CodeBlock,
DescriptionList, DescriptionList,
Pagination, formatLogText,
hasLargeData,
LogOutput,
Search, Search,
Table, Table,
Timestamp, Timestamp,
@@ -36,8 +41,10 @@ import {
ChevronDown, ChevronDown,
ChevronRight, ChevronRight,
ClipboardList, ClipboardList,
Copy,
Activity, Activity,
Download, Download,
Trash2,
RotateCcw, RotateCcw,
} from 'lucide-react'; } from 'lucide-react';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
@@ -65,12 +72,6 @@ const STEP_STATUS_VARIANT: Record<RunStepStatus, BadgeVariant> = {
cancelled: 'warning', cancelled: 'warning',
}; };
const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
log: 'neutral',
warn: 'warning',
error: 'error',
};
const FINAL: ScenarioRunStatus[] = ['pass', 'fail']; const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
export function RunDetailPage() { export function RunDetailPage() {
@@ -84,6 +85,7 @@ function RunDetail() {
const { id, runId } = useParams<{ id: string; runId: string }>(); const { id, runId } = useParams<{ id: string; runId: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const toast = useToast(); const toast = useToast();
const logDataLimits = useManifest().runLogs.dataLimits;
const [scenario, setScenario] = useState<Scenario | null>(null); const [scenario, setScenario] = useState<Scenario | null>(null);
const [run, setRun] = useState<ScenarioRunDetail | null>(null); const [run, setRun] = useState<ScenarioRunDetail | null>(null);
@@ -92,7 +94,6 @@ function RunDetail() {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [polling, setPolling] = useState(false); const [polling, setPolling] = useState(false);
const [pulseKey, setPulseKey] = useState(0); const [pulseKey, setPulseKey] = useState(0);
const [logPage, setLogPage] = useState(1);
const [logSearch, setLogSearch] = useState(''); const [logSearch, setLogSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState(''); const [debouncedSearch, setDebouncedSearch] = useState('');
const [expandAll, setExpandAll] = useState(false); const [expandAll, setExpandAll] = useState(false);
@@ -103,9 +104,11 @@ function RunDetail() {
const [exportLogsOpen, setExportLogsOpen] = useState(false); const [exportLogsOpen, setExportLogsOpen] = useState(false);
const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md'); const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md');
const [exportingLogs, setExportingLogs] = useState(false); const [exportingLogs, setExportingLogs] = useState(false);
const [pendingDeleteFile, setPendingDeleteFile] = useState<FileMetadata | null>(null);
const [deletingFile, setDeletingFile] = useState(false);
const [repeating, setRepeating] = useState(false); const [repeating, setRepeating] = useState(false);
const [logDataExpanded, setLogDataExpanded] = useState(false);
const logSearchRef = useRef(''); const logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null); const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const stopPolling = () => { const stopPolling = () => {
@@ -147,6 +150,33 @@ function RunDetail() {
} }
}; };
const logEntries = useMemo(
() =>
(run?.logs ?? []).map((l) => ({
id: l.id,
level: l.level,
context: l.context,
message: l.message,
data: l.data,
createdAt: l.createdAt,
})),
[run?.logs],
);
const logsHaveLargeData = useMemo(
() => hasLargeData(logEntries, logDataLimits),
[logEntries, logDataLimits],
);
// Copies the (filtered) logs as plain text with every data block expanded
const handleCopyLogs = async () => {
try {
await navigator.clipboard.writeText(formatLogText(logEntries, run?.createdAt));
toast.success(t('runs.logs_copied'));
} catch {
toast.error(t('runs.logs_copy_failed'));
}
};
const handleRepeatRun = async () => { const handleRepeatRun = async () => {
if (!id || !run?.environmentId) return; if (!id || !run?.environmentId) return;
setRepeating(true); setRepeating(true);
@@ -167,6 +197,21 @@ function RunDetail() {
} }
}; };
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 = () => { const manualRefresh = () => {
if (!id || !runId) return; if (!id || !runId) return;
runs runs
@@ -199,7 +244,6 @@ function RunDetail() {
const t = setTimeout(() => { const t = setTimeout(() => {
setDebouncedSearch(logSearch); setDebouncedSearch(logSearch);
logSearchRef.current = logSearch; logSearchRef.current = logSearch;
setLogPage(1);
}, 300); }, 300);
return () => clearTimeout(t); return () => clearTimeout(t);
}, [logSearch]); }, [logSearch]);
@@ -378,26 +422,6 @@ function RunDetail() {
}, },
]; ];
const logColumns: TableColumn<ScenarioRunLog>[] = [
{
key: 'level',
header: t('runs.log_level'),
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{
key: 'message',
header: t('runs.log_message'),
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
},
{
key: 'time',
header: t('runs.log_time'),
width: 160,
render: (l) => <Timestamp value={l.createdAt} />,
},
];
return ( return (
<div> <div>
<div className={styles.pageToolbar}> <div className={styles.pageToolbar}>
@@ -525,7 +549,22 @@ function RunDetail() {
{run.logs.length > 0 && ( {run.logs.length > 0 && (
<div className={styles.stepsSection}> <div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}> <div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2> <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<h2 className={styles.sectionHeading} style={{ margin: 0 }}>
{t('runs.logs_heading')}
</h2>
{logsHaveLargeData && (
<Button
variant="ghost"
size="sm"
aria-expanded={logDataExpanded}
onClick={() => setLogDataExpanded((v) => !v)}
>
{logDataExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
{logDataExpanded ? t('runs.logs_collapse_data') : t('runs.logs_expand_data')}
</Button>
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Search <Search
value={logSearch} value={logSearch}
@@ -536,23 +575,27 @@ function RunDetail() {
<Download size={14} /> <Download size={14} />
{t('runs.action_download_logs')} {t('runs.action_download_logs')}
</Button> </Button>
<Button variant="secondary" size="sm" onClick={handleCopyLogs}>
<Copy size={14} />
{t('runs.action_copy_logs')}
</Button>
</div> </div>
</div> </div>
<Table <LogOutput
columns={logColumns} startTime={run.createdAt}
data={run.logs.slice((logPage - 1) * LOG_PAGE_SIZE, logPage * LOG_PAGE_SIZE)} maxHeight={480}
rowKey={(l) => l.id} entries={logEntries}
loading={false} dataLimits={logDataLimits}
dataExpanded={logDataExpanded}
showDataLabel={({ bytes, lines }) =>
t('runs.logs_show_data', {
size: bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`,
count: lines,
})
}
hideDataLabel={t('runs.logs_hide_data')}
emptyMessage="" emptyMessage=""
/> />
{run.logs.length > LOG_PAGE_SIZE && (
<Pagination
page={logPage}
pageSize={LOG_PAGE_SIZE}
total={run.logs.length}
onPageChange={setLogPage}
/>
)}
</div> </div>
)} )}
@@ -565,7 +608,23 @@ function RunDetail() {
rowKey={(f) => f.id} rowKey={(f) => f.id}
columns={ columns={
[ [
{ key: 'name', header: t('files.name'), render: (f) => f.name }, {
key: 'name',
header: t('files.name'),
// Served inline, so the browser shows what it can (images, text, PDF).
render: (f) =>
isFileExpired(f) ? (
f.name
) : (
<a
href={runFiles.contentUrl(id!, runId!, f.id)}
target="_blank"
rel="noopener noreferrer"
>
{f.name}
</a>
),
},
{ {
key: 'mimeType', key: 'mimeType',
header: t('files.mimeType'), header: t('files.mimeType'),
@@ -611,6 +670,21 @@ function RunDetail() {
); );
}, },
}, },
{
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>[] ] satisfies TableColumn<FileMetadata>[]
} }
emptyMessage={t('files.empty')} emptyMessage={t('files.empty')}
@@ -628,6 +702,15 @@ function RunDetail() {
onExport={handleExportLogs} onExport={handleExportLogs}
isExporting={exportingLogs} 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> </div>
); );
} }
+6 -4
View File
@@ -68,10 +68,12 @@ export function RunsPage() {
const sortDirRef = useRef(sortDir); const sortDirRef = useRef(sortDir);
const pageRef = useRef(page); const pageRef = useRef(page);
const pageSizeRef = useRef(pageSize); const pageSizeRef = useRef(pageSize);
sortByRef.current = sortBy; useEffect(() => {
sortDirRef.current = sortDir; sortByRef.current = sortBy;
pageRef.current = page; sortDirRef.current = sortDir;
pageSizeRef.current = pageSize; pageRef.current = page;
pageSizeRef.current = pageSize;
}, [sortBy, sortDir, page, pageSize]);
const load = useCallback( const load = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => { (orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
+5 -1
View File
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api'; import { scenarios, steps } from '../../api';
import type { Scenario } from '../../api'; import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import { CodeHelpButton } from '../../components/modals';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
export function CreateStepPage() { export function CreateStepPage() {
@@ -77,7 +78,10 @@ export function CreateStepPage() {
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
/> />
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label> <div className={styles.labelRow}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeHelpButton />
</div>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} /> <CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div> </div>
<Input <Input
+5 -1
View File
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api'; import { scenarios, steps } from '../../api';
import type { Scenario, ScenarioStep } from '../../api'; import type { Scenario, ScenarioStep } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import { CodeHelpButton } from '../../components/modals';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
export function EditStepPage() { export function EditStepPage() {
@@ -89,7 +90,10 @@ export function EditStepPage() {
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
/> />
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label> <div className={styles.labelRow}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeHelpButton />
</div>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} /> <CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div> </div>
<Input <Input
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, useCallback, SubmitEvent } from 'react'; import { useEffect, useState, useCallback, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
@@ -82,10 +82,9 @@ export function ScenarioDetailPage() {
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]); const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
// null = latest // null = latest
const [runVersion, setRunVersion] = useState<number | null>(null); const [runVersion, setRunVersion] = useState<number | null>(null);
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'on'; const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
const [envs, setEnvs] = useState<Environment[]>([]); const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState(''); const [selectedEnvId, setSelectedEnvId] = useState('');
const envInitRef = useRef(false);
const [pendingDelete, setPendingDelete] = useState< const [pendingDelete, setPendingDelete] = useState<
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null { type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
>(null); >(null);
@@ -95,12 +94,12 @@ export function ScenarioDetailPage() {
const [exportModalOpen, setExportModalOpen] = useState(false); const [exportModalOpen, setExportModalOpen] = useState(false);
const [includeEnvironment, setIncludeEnvironment] = useState(true); const [includeEnvironment, setIncludeEnvironment] = useState(true);
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set()); const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
const [includedSnippetIds, setIncludedSnippetIds] = useState<Set<string>>(new Set());
const [isExporting, setIsExporting] = useState(false); const [isExporting, setIsExporting] = useState(false);
// Files state // Files state
const [files, setFiles] = useState<FileMetadata[]>([]); const [files, setFiles] = useState<FileMetadata[]>([]);
const [filesTotal, setFilesTotal] = useState(0); const [filesLoading, setFilesLoading] = useState(true);
const [filesLoading, setFilesLoading] = useState(false);
const [uploadOpen, setUploadOpen] = useState(false); const [uploadOpen, setUploadOpen] = useState(false);
const [uploadFile, setUploadFile] = useState<File | null>(null); const [uploadFile, setUploadFile] = useState<File | null>(null);
const [uploadExpiresAt, setUploadExpiresAt] = useState(''); const [uploadExpiresAt, setUploadExpiresAt] = useState('');
@@ -108,18 +107,23 @@ export function ScenarioDetailPage() {
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]); const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
const loadFiles = useCallback(async () => { // Fetches the files; `filesLoading` starts as true for the fetch from the
// load effect, and `loadFiles` sets it for reloads (e.g. after an upload)
const fetchFiles = useCallback(async () => {
if (!id) return; if (!id) return;
setFilesLoading(true);
try { try {
const result = await scenarioFiles.list(id); const result = await scenarioFiles.list(id);
setFiles(result.items); setFiles(result.items);
setFilesTotal(result.total);
} finally { } finally {
setFilesLoading(false); setFilesLoading(false);
} }
}, [id]); }, [id]);
const loadFiles = async () => {
setFilesLoading(true);
await fetchFiles();
};
useEffect(() => { useEffect(() => {
if (!id) return; if (!id) return;
void scenarios void scenarios
@@ -129,7 +133,7 @@ export function ScenarioDetailPage() {
setScenarioCreds(s.scenarioCredentials ?? []); setScenarioCreds(s.scenarioCredentials ?? []);
}) })
.finally(() => setLoading(false)); .finally(() => setLoading(false));
void loadFiles(); void fetchFiles();
scenarios scenarios
.usedSnippets(id) .usedSnippets(id)
.then(setUsedSnippets) .then(setUsedSnippets)
@@ -144,16 +148,25 @@ export function ScenarioDetailPage() {
setEnvs(r.data); setEnvs(r.data);
}) })
.catch(() => {}); .catch(() => {});
}, [id, loadFiles]); }, [id, fetchFiles]);
// Default selected env to scenario's linked environment (or first env) once both are loaded const openRunModal = () => {
useEffect(() => { // Preselect the scenario's default environment (or the first one) when the
if (envInitRef.current || envs.length === 0) return; // modal opens: by then both are loaded, and it follows default env edits
envInitRef.current = true;
const preferred = scenario?.environmentId ?? null; const preferred = scenario?.environmentId ?? null;
const exists = preferred ? envs.some((e) => e.id === preferred) : false; const exists = preferred ? envs.some((e) => e.id === preferred) : false;
setSelectedEnvId(exists ? preferred! : envs[0].id); setSelectedEnvId(exists ? preferred! : (envs[0]?.id ?? ''));
}, [scenario, envs]); setTraceModeOverride(null);
setRunVersion(null);
setRunVersions([]);
if (id) {
scenarios
.versions(id)
.then(setRunVersions)
.catch(() => undefined);
}
setRunModalOpen(true);
};
const reloadScenario = async () => { const reloadScenario = async () => {
if (!id) return; if (!id) return;
@@ -200,8 +213,9 @@ export function ScenarioDetailPage() {
const handleOpenExportModal = () => { const handleOpenExportModal = () => {
if (!scenario) return; if (!scenario) return;
// Initialise all credential checkboxes to checked // Initialise all credential and snippet checkboxes to checked
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId))); setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
setIncludedSnippetIds(new Set(usedSnippets.map((s) => s.id)));
setIncludeEnvironment(true); setIncludeEnvironment(true);
setExportModalOpen(true); setExportModalOpen(true);
}; };
@@ -214,12 +228,14 @@ export function ScenarioDetailPage() {
const yamlContent = await scenarios.exportScenario(scenario.id, { const yamlContent = await scenarios.exportScenario(scenario.id, {
includeEnvironment, includeEnvironment,
credentialIds: credIds, credentialIds: credIds,
snippetIds: Array.from(includedSnippetIds),
version: scenario.version,
}); });
const blob = new Blob([yamlContent], { type: 'application/yaml' }); const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; a.href = url;
a.download = `${scenario.name}.yaml`; a.download = `${scenario.name}-v${scenario.version}.yaml`;
a.click(); a.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
setExportModalOpen(false); setExportModalOpen(false);
@@ -472,21 +488,7 @@ export function ScenarioDetailPage() {
/> />
{scenario && ( {scenario && (
<div className={styles.toolbarActions}> <div className={styles.toolbarActions}>
<Button <Button size="sm" onClick={openRunModal}>
size="sm"
onClick={() => {
setTraceModeOverride(null);
setRunVersion(null);
setRunVersions([]);
if (id) {
scenarios
.versions(id)
.then(setRunVersions)
.catch(() => undefined);
}
setRunModalOpen(true);
}}
>
<Play size={14} /> <Play size={14} />
{t('scenarios.action_run')} {t('scenarios.action_run')}
</Button> </Button>
@@ -502,7 +504,10 @@ export function ScenarioDetailPage() {
variant="secondary" variant="secondary"
size="sm" size="sm"
onClick={() => onClick={() =>
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`) handleFileDownload(
scenarios.exportE2eTestUrl(id!, scenario.version),
`${scenario.name}-v${scenario.version}-e2e-test.zip`,
)
} }
> >
<FileArchive size={14} /> <FileArchive size={14} />
@@ -760,7 +765,19 @@ export function ScenarioDetailPage() {
{ {
key: 'name', key: 'name',
header: t('files.name'), header: t('files.name'),
render: (f) => f.name, // Served inline, so the browser shows what it can (images, text, PDF).
render: (f) =>
isFileExpired(f) ? (
f.name
) : (
<a
href={scenarioFiles.contentUrl(id!, f.id)}
target="_blank"
rel="noopener noreferrer"
>
{f.name}
</a>
),
}, },
{ {
key: 'mimeType', key: 'mimeType',
@@ -901,6 +918,16 @@ export function ScenarioDetailPage() {
return next; return next;
}); });
}} }}
usedSnippets={usedSnippets}
includedSnippetIds={includedSnippetIds}
onSnippetToggle={(snippetId, checked) => {
setIncludedSnippetIds((prev) => {
const next = new Set(prev);
if (checked) next.add(snippetId);
else next.delete(snippetId);
return next;
});
}}
onClose={() => setExportModalOpen(false)} onClose={() => setExportModalOpen(false)}
onExport={handleExport} onExport={handleExport}
isExporting={isExporting} isExporting={isExporting}
+13 -19
View File
@@ -2,8 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { useImportFile } from '../../hooks/useImportFile';
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react'; import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { environments, scenarios } from '../../api'; import { environments, scenarios } from '../../api';
import type { Environment, Scenario, ScenarioVersion, TraceMode } from '../../api'; import type { Environment, Scenario, ScenarioVersion, TraceMode } from '../../api';
import { RunScenarioModal } from '../../components/modals'; import { RunScenarioModal } from '../../components/modals';
@@ -56,7 +56,7 @@ export function ScenariosPage() {
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]); const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
// null = latest // null = latest
const [runVersion, setRunVersion] = useState<number | null>(null); const [runVersion, setRunVersion] = useState<number | null>(null);
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'on'; const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
const [envs, setEnvs] = useState<Environment[]>([]); const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState(''); const [selectedEnvId, setSelectedEnvId] = useState('');
@@ -68,9 +68,10 @@ export function ScenariosPage() {
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const load = useCallback( // Fetches a page; `loading` starts as true for the initial fetch from the
// effect, and `load` sets it for later ones (no setState inside the effect)
const fetchPage = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => { (orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
Promise.all([ Promise.all([
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'), scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
environments.list(1, 200), environments.list(1, 200),
@@ -88,9 +89,14 @@ export function ScenariosPage() {
[toast], [toast],
); );
const load = (orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
fetchPage(orderBy, orderDir, p, limit);
};
useEffect(() => { useEffect(() => {
load('updatedAt', 'desc', 1, 10); fetchPage('updatedAt', 'desc', 1, 10);
}, [load]); }, [fetchPage]);
const handleSort = (key: string, dir: SortDirection) => { const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key); setSortBy(key);
@@ -159,19 +165,7 @@ export function ScenariosPage() {
} }
}; };
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleImport = useImportFile('scenario');
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 {
// Import errors are silently ignored
}
};
const columns: TableColumn<Scenario>[] = [ const columns: TableColumn<Scenario>[] = [
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 }, { key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
+8 -3
View File
@@ -23,7 +23,9 @@ export function SessionsPage() {
usePageTitle(t('sessions.title')); usePageTitle(t('sessions.title'));
const navigate = useNavigate(); const navigate = useNavigate();
const [items, setItems] = useState<Session[]>([]); const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true); // Loading until the current query's result has arrived (derived, so the
// loading effect doesn't have to set state synchronously)
const [loadedQuery, setLoadedQuery] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const [sortBy, setSortBy] = useState('id'); const [sortBy, setSortBy] = useState('id');
@@ -32,15 +34,18 @@ export function SessionsPage() {
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const query = `${sortBy}|${sortDir}|${page}|${pageSize}`;
const loading = loadedQuery !== query;
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => { const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true); const key = `${orderBy}|${orderDir}|${p}|${limit}`;
sessions sessions
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC') .list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
.then((res) => { .then((res) => {
setItems(res.data); setItems(res.data);
setTotal(res.total); setTotal(res.total);
}) })
.finally(() => setLoading(false)); .finally(() => setLoadedQuery(key));
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -5,6 +5,7 @@ import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, Braces } from 'lucide-react'; import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api'; import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import { CodeHelpButton } from '../../components/modals';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
export function CreateSnippetPage() { export function CreateSnippetPage() {
@@ -107,10 +108,13 @@ export function CreateSnippetPage() {
/> />
</div> </div>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.fieldLabel}> <div className={styles.labelRow}>
{t('snippets.form_code')} <label className={styles.fieldLabel}>
<span className={styles.requiredMark}> *</span> {t('snippets.form_code')}
</label> <span className={styles.requiredMark}> *</span>
</label>
<CodeHelpButton />
</div>
<CodeEditor <CodeEditor
value={code} value={code}
onChange={(v) => { onChange={(v) => {
+8 -4
View File
@@ -6,6 +6,7 @@ import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api'; import { snippets } from '../../api';
import type { Snippet } from '../../api'; import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import { CodeHelpButton } from '../../components/modals';
import styles from '../Page.module.css'; import styles from '../Page.module.css';
export function EditSnippetPage() { export function EditSnippetPage() {
@@ -134,10 +135,13 @@ export function EditSnippetPage() {
/> />
</div> </div>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.fieldLabel}> <div className={styles.labelRow}>
{t('snippets.form_code')} <label className={styles.fieldLabel}>
<span className={styles.requiredMark}> *</span> {t('snippets.form_code')}
</label> <span className={styles.requiredMark}> *</span>
</label>
<CodeHelpButton />
</div>
<CodeEditor <CodeEditor
value={code} value={code}
onChange={(v) => { onChange={(v) => {
@@ -51,12 +51,12 @@ export function SnippetDetailPage() {
const handleExport = async () => { const handleExport = async () => {
if (!snippet) return; if (!snippet) return;
const data = await snippets.exportSnippet(snippet.id); const data = await snippets.exportSnippet(snippet.id, snippet.version);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' }); const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; a.href = url;
a.download = `snippet-${snippet.alias}.yaml`; a.download = `snippet-${snippet.alias}-v${snippet.version}.yaml`;
a.click(); a.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
}; };
+2 -15
View File
@@ -2,8 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle'; import { usePageTitle } from '../../hooks/usePageTitle';
import { useImportFile } from '../../hooks/useImportFile';
import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react'; import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { snippets } from '../../api'; import { snippets } from '../../api';
import type { Snippet } from '../../api'; import type { Snippet } from '../../api';
import { import {
@@ -117,7 +117,6 @@ function AddSnippetCard() {
export function SnippetsPage() { export function SnippetsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
usePageTitle(t('snippets.title')); usePageTitle(t('snippets.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Snippet[]>([]); const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
@@ -151,19 +150,7 @@ export function SnippetsPage() {
} }
}; };
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleImport = useImportFile('snippet');
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 {
// Import errors are silently ignored
}
};
return ( return (
<div> <div>
@@ -71,7 +71,7 @@
} }
.active .label { .active .label {
color: var(--color-primary); color: var(--color-primary-text);
font-weight: 600; font-weight: 600;
} }
@@ -83,8 +83,8 @@
} }
.inactive .label { .inactive .label {
/* Not dimmed with opacity: muted text already reads as inactive and keeps 4.5:1 */
color: var(--color-text-muted); color: var(--color-text-muted);
opacity: 0.5;
} }
/* ── Error state ──────────────────────────────────────────── */ /* ── Error state ──────────────────────────────────────────── */
+3 -2
View File
@@ -6,12 +6,13 @@ export type BadgeVariant = 'success' | 'error' | 'warning' | 'info' | 'neutral'
export interface BadgeProps { export interface BadgeProps {
variant?: BadgeVariant; variant?: BadgeVariant;
dot?: boolean; dot?: boolean;
className?: string;
children: React.ReactNode; children: React.ReactNode;
} }
export function Badge({ variant = 'neutral', dot = false, children }: BadgeProps) { export function Badge({ variant = 'neutral', dot = false, className, children }: BadgeProps) {
return ( return (
<span className={[styles.badge, styles[variant]].join(' ')}> <span className={[styles.badge, styles[variant], className].filter(Boolean).join(' ')}>
{dot && <span className={styles.dot} aria-hidden="true" />} {dot && <span className={styles.dot} aria-hidden="true" />}
{children} {children}
</span> </span>
+6
View File
@@ -88,3 +88,9 @@
@keyframes spin { @keyframes spin {
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
} }
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
+8 -8
View File
@@ -18,7 +18,7 @@
.code :global(.hljs-comment), .code :global(.hljs-comment),
.code :global(.hljs-quote) { .code :global(.hljs-quote) {
color: var(--hl-comment, #6A8072); color: var(--hl-comment);
font-style: italic; font-style: italic;
} }
@@ -27,7 +27,7 @@
.code :global(.hljs-built_in), .code :global(.hljs-built_in),
.code :global(.hljs-name), .code :global(.hljs-name),
.code :global(.hljs-tag) { .code :global(.hljs-tag) {
color: var(--hl-keyword, #A67DCC); color: var(--hl-keyword);
} }
.code :global(.hljs-string), .code :global(.hljs-string),
@@ -39,32 +39,32 @@
.code :global(.hljs-template-variable), .code :global(.hljs-template-variable),
.code :global(.hljs-type), .code :global(.hljs-type),
.code :global(.hljs-addition) { .code :global(.hljs-addition) {
color: var(--hl-string, #9BB870); color: var(--hl-string);
} }
.code :global(.hljs-number), .code :global(.hljs-number),
.code :global(.hljs-regexp), .code :global(.hljs-regexp),
.code :global(.hljs-link) { .code :global(.hljs-link) {
color: var(--hl-number, #E8A85F); color: var(--hl-number);
} }
.code :global(.hljs-function), .code :global(.hljs-function),
.code :global(.hljs-title.hljs-function_) { .code :global(.hljs-title.hljs-function_) {
color: var(--hl-function, #5BB8D4); color: var(--hl-function);
} }
.code :global(.hljs-variable), .code :global(.hljs-variable),
.code :global(.hljs-params) { .code :global(.hljs-params) {
color: var(--hl-variable, #D4A0A0); color: var(--hl-variable);
} }
.code :global(.hljs-property) { .code :global(.hljs-property) {
color: var(--hl-property, #79C0C8); color: var(--hl-property);
} }
.code :global(.hljs-deletion), .code :global(.hljs-deletion),
.code :global(.hljs-meta) { .code :global(.hljs-meta) {
color: var(--hl-meta, #A9A3C9); color: var(--hl-meta);
} }
.code :global(.hljs-emphasis) { .code :global(.hljs-emphasis) {
@@ -0,0 +1,147 @@
.root {
display: flex;
flex-direction: column;
background: var(--color-bg-subtle);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
overflow: auto;
font-family: var(--font-mono, ui-monospace, 'Cascadia Code', 'Fira Code', monospace);
font-size: var(--font-size-xs);
/* Where the context/message column starts: timestamp + level + their gaps */
--log-body-offset: calc(7em + 4.5em + 2 * var(--space-2));
}
.empty {
padding: var(--space-4);
color: var(--color-text-muted);
font-size: var(--font-size-sm);
}
.line {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: var(--space-1) var(--space-3);
border-left: 3px solid transparent;
border-bottom: 1px solid var(--color-border);
}
.line:last-child {
border-bottom: none;
}
.lineHeader {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: var(--space-2);
}
.data {
margin: 0 0 var(--space-1) var(--log-body-offset);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-sm);
background: var(--color-bg);
max-width: 100%;
overflow-x: auto;
}
.data > * {
margin: 0;
padding: var(--space-2) var(--space-3);
}
.timestamp {
flex: 0 0 auto;
min-width: 7em;
text-align: right;
color: var(--color-text-muted);
white-space: nowrap;
}
.level {
flex: 0 0 auto;
width: 4.5em;
text-transform: uppercase;
font-weight: 700;
}
.context {
flex: 0 0 auto;
color: var(--color-secondary-fg);
}
.context::before {
content: '[';
}
.context::after {
content: ']';
}
.message {
flex: 1 1 320px;
color: var(--color-text);
white-space: pre-wrap;
word-break: break-word;
}
.debug {
border-left-color: var(--color-border);
}
.debug .level,
.debug .message,
.debug .timestamp,
.debug .context {
color: var(--color-text-faint);
}
.log {
border-left-color: var(--color-border);
}
.log .level {
color: var(--color-text-muted);
}
.warn {
border-left-color: var(--color-warning-fg);
background: var(--color-warning-bg);
}
.warn .level {
color: var(--color-warning-fg);
}
.error {
border-left-color: var(--color-error-fg);
background: var(--color-error-bg);
}
.error .level {
color: var(--color-error-fg);
}
.dataToggle {
display: inline-flex;
align-items: center;
gap: var(--space-1);
align-self: flex-start;
margin-left: var(--log-body-offset);
padding: 0;
border: none;
background: none;
font: inherit;
color: var(--color-text);
cursor: pointer;
}
.dataToggle svg {
flex: 0 0 auto;
color: var(--color-primary-text);
}
.dataToggle:hover {
text-decoration: underline;
}
+147
View File
@@ -0,0 +1,147 @@
import { useMemo, useState } from 'react';
import { ChevronDown, ChevronRight } from 'lucide-react';
import { CodeBlock } from '../CodeBlock/CodeBlock';
import {
DEFAULT_LOG_DATA_LIMITS,
exceedsLimits,
formatElapsed,
measureData,
prettyData,
type LogDataLimits,
} from './logText';
import styles from './LogOutput.module.css';
export type LogOutputLevel = 'debug' | 'log' | 'warn' | 'error';
export interface LogOutputEntry {
id: string | number;
level: LogOutputLevel;
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
context?: string | null;
message: string;
/** JSON payload attached to the message, as a raw string; rendered pretty-printed, separately from the message. */
data?: string | null;
createdAt: string | number | Date;
}
export interface LogOutputProps {
entries: LogOutputEntry[];
/** Reference point for the elapsed-time column; defaults to the first entry's timestamp. */
startTime?: string | number | Date;
/** Caps the block's height (e.g. "400px"), scrolling once entries overflow it. */
maxHeight?: string | number;
emptyMessage?: string;
className?: string;
/** Data blocks whose pretty-printed JSON exceeds either limit start collapsed behind a toggle. */
dataLimits?: LogDataLimits;
/**
* Expands (true) or collapses (false) every large data block. Changing it
* discards the per-entry toggles made since the last change.
*/
dataExpanded?: boolean;
/** Label of a collapsed data block's toggle, e.g. "Show data (1.2 KB, 40 lines)". */
showDataLabel?: (size: { bytes: number; lines: number }) => string;
hideDataLabel?: string;
}
function formatBytes(bytes: number): string {
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
}
const defaultShowDataLabel = ({ bytes, lines }: { bytes: number; lines: number }) =>
`Show data (${formatBytes(bytes)}, ${lines} ${lines === 1 ? 'line' : 'lines'})`;
/** Terminal-style log viewer: one line per entry, color-coded by level. */
export function LogOutput({
entries,
startTime,
maxHeight,
emptyMessage = 'No logs.',
className,
dataLimits = DEFAULT_LOG_DATA_LIMITS,
dataExpanded = false,
showDataLabel = defaultShowDataLabel,
hideDataLabel = 'Hide data',
}: LogOutputProps) {
// Per-entry toggles, reset whenever dataExpanded changes
const [toggled, setToggled] = useState<Set<LogOutputEntry['id']>>(() => new Set());
const [prevDataExpanded, setPrevDataExpanded] = useState(dataExpanded);
if (prevDataExpanded !== dataExpanded) {
setPrevDataExpanded(dataExpanded);
setToggled(new Set());
}
const dataBlocks = useMemo(() => {
const blocks = new Map<
LogOutputEntry['id'],
{ pretty: string; bytes: number; lines: number }
>();
for (const entry of entries) {
if (!entry.data) continue;
const pretty = prettyData(entry.data);
blocks.set(entry.id, { pretty, ...measureData(pretty) });
}
return blocks;
}, [entries]);
const toggle = (id: LogOutputEntry['id']) =>
setToggled((prev) => {
const next = new Set(prev);
if (!next.delete(id)) next.add(id);
return next;
});
if (entries.length === 0) {
return <div className={styles.empty}>{emptyMessage}</div>;
}
const startMs = new Date(startTime ?? entries[0].createdAt).getTime();
return (
<div
className={[styles.root, className].filter(Boolean).join(' ')}
style={maxHeight !== undefined ? { maxHeight } : undefined}
role="log"
tabIndex={0}
>
{entries.map((entry) => {
const entryMs = new Date(entry.createdAt).getTime();
const block = dataBlocks.get(entry.id);
const large = block != null && exceedsLimits(block, dataLimits);
const open = !large || dataExpanded !== toggled.has(entry.id);
return (
<div key={entry.id} className={[styles.line, styles[entry.level]].join(' ')}>
<div className={styles.lineHeader}>
<span className={styles.timestamp} title={new Date(entryMs).toISOString()}>
{formatElapsed(entryMs - startMs)}
</span>
<span className={styles.level}>{entry.level}</span>
{entry.context && <span className={styles.context}>{entry.context}</span>}
<span className={styles.message}>{entry.message}</span>
</div>
{block && large && (
<button
type="button"
className={styles.dataToggle}
aria-expanded={open}
onClick={() => toggle(entry.id)}
>
{open ? (
<ChevronDown size={14} strokeWidth={3} aria-hidden="true" />
) : (
<ChevronRight size={14} strokeWidth={3} aria-hidden="true" />
)}
{open ? hideDataLabel : showDataLabel(block)}
</button>
)}
{block && open && (
<div className={styles.data}>
<CodeBlock code={block.pretty} language="json" />
</div>
)}
</div>
);
})}
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
import type { LogOutputEntry } from './LogOutput';
/** Data blocks above either limit start collapsed. */
export interface LogDataLimits {
/** UTF-8 byte size of the pretty-printed data. */
bytes: number;
/** Line count of the pretty-printed data. */
lines: number;
}
export const DEFAULT_LOG_DATA_LIMITS: LogDataLimits = { bytes: 256, lines: 5 };
const encoder = new TextEncoder();
/**
* "+12s" (or "-" if before startTime, e.g. clock skew). Log timestamps are
* stored with second resolution, so fractions would be noise.
*/
export function formatElapsed(deltaMs: number): string {
const sign = deltaMs < 0 ? '-' : '+';
return `${sign}${Math.round(Math.abs(deltaMs) / 1000)}s`;
}
/** Pretty-prints `data` if it's valid JSON, otherwise returns it as-is. */
export function prettyData(data: string): string {
try {
return JSON.stringify(JSON.parse(data), null, 2);
} catch {
return data;
}
}
/** Byte size and line count of an already pretty-printed data block. */
export function measureData(pretty: string): { bytes: number; lines: number } {
return { bytes: encoder.encode(pretty).length, lines: pretty.split('\n').length };
}
export function exceedsLimits(size: { bytes: number; lines: number }, limits: LogDataLimits) {
return size.bytes > limits.bytes || size.lines > limits.lines;
}
/** True if any entry's data block exceeds the limits (i.e. renders collapsed by default). */
export function hasLargeData(
entries: Pick<LogOutputEntry, 'data'>[],
limits: LogDataLimits = DEFAULT_LOG_DATA_LIMITS,
): boolean {
return entries.some((e) => e.data && exceedsLimits(measureData(prettyData(e.data)), limits));
}
/**
* Plain-text rendering of the log, one entry per line with every data block
* pretty-printed and indented below its line (e.g. for copying to the clipboard).
*/
export function formatLogText(
entries: LogOutputEntry[],
startTime?: string | number | Date,
): string {
if (entries.length === 0) return '';
const startMs = new Date(startTime ?? entries[0].createdAt).getTime();
return entries
.map((entry) => {
const elapsed = formatElapsed(new Date(entry.createdAt).getTime() - startMs);
const context = entry.context ? ` [${entry.context}]` : '';
const header = `${elapsed.padStart(6)} ${entry.level.toUpperCase().padEnd(5)}${context} ${entry.message}`;
if (!entry.data) return header;
const data = prettyData(entry.data)
.split('\n')
.map((line) => ` ${line}`)
.join('\n');
return `${header}\n${data}`;
})
.join('\n');
}
+8
View File
@@ -16,6 +16,13 @@
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent); box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
overflow: hidden; overflow: hidden;
display: flex;
flex-direction: column;
max-height: 100%;
}
.lg {
width: min(880px, 100%);
} }
.header { .header {
@@ -31,6 +38,7 @@
.body { .body {
padding: var(--space-2) var(--space-5) var(--space-4); padding: var(--space-2) var(--space-5) var(--space-4);
color: var(--color-text-muted); color: var(--color-text-muted);
overflow-y: auto;
} }
.footer { .footer {
+8 -3
View File
@@ -7,9 +7,11 @@ export interface ModalProps {
children?: React.ReactNode; children?: React.ReactNode;
onClose: () => void; onClose: () => void;
footer?: React.ReactNode; footer?: React.ReactNode;
/** `lg` widens the dialog for long, document-like content. */
size?: 'md' | 'lg';
} }
export function Modal({ open, title, children, onClose, footer }: ModalProps) { export function Modal({ open, title, children, onClose, footer, size = 'md' }: ModalProps) {
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
const onKeyDown = (event: KeyboardEvent) => { const onKeyDown = (event: KeyboardEvent) => {
@@ -24,7 +26,7 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
return ( return (
<div className={styles.overlay} role="presentation" onClick={onClose}> <div className={styles.overlay} role="presentation" onClick={onClose}>
<div <div
className={styles.dialog} className={size === 'lg' ? `${styles.dialog} ${styles.lg}` : styles.dialog}
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
aria-label={title} aria-label={title}
@@ -33,7 +35,10 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
<div className={styles.header}> <div className={styles.header}>
<h3 className={styles.title}>{title}</h3> <h3 className={styles.title}>{title}</h3>
</div> </div>
<div className={styles.body}>{children}</div> {/* Long (lg) content scrolls; make it focusable so the keyboard can scroll it. */}
<div className={styles.body} tabIndex={size === 'lg' ? 0 : undefined}>
{children}
</div>
{footer && <div className={styles.footer}>{footer}</div>} {footer && <div className={styles.footer}>{footer}</div>}
</div> </div>
</div> </div>
@@ -0,0 +1,48 @@
.btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
background: none;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
color: var(--color-text-muted);
cursor: pointer;
flex-shrink: 0;
transition: background var(--transition), color var(--transition), border-color var(--transition);
}
.btn:hover {
background: var(--color-bg-subtle);
color: var(--color-text);
border-color: var(--color-text-muted);
}
.btn:active {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn:disabled:hover {
background: none;
color: var(--color-text-muted);
border-color: var(--color-border);
}
.btn[aria-pressed='true'] {
background: var(--color-primary);
border-color: var(--color-primary);
color: var(--color-primary-fg);
}
.btn[aria-pressed='true']:hover {
background: var(--color-primary-hover);
border-color: var(--color-primary-hover);
}
@@ -0,0 +1,39 @@
import { Bell, BellOff } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import styles from './NotificationToggle.module.css';
/**
* - `on`: notifications are enabled
* - `off`: available, but not enabled (or permission not asked yet)
* - `blocked`: the browser denied the permission
*/
export type NotificationToggleState = 'on' | 'off' | 'blocked';
export interface NotificationToggleProps {
state: NotificationToggleState;
onToggle: () => void;
}
export function NotificationToggle({ state, onToggle }: NotificationToggleProps) {
const { t } = useTranslation();
const label =
state === 'on'
? t('notifications.disable')
: state === 'blocked'
? t('notifications.blocked')
: t('notifications.enable');
return (
<button
type="button"
className={styles.btn}
onClick={onToggle}
disabled={state === 'blocked'}
aria-label={label}
aria-pressed={state === 'on'}
title={label}
>
{state === 'on' ? <Bell size={16} /> : <BellOff size={16} />}
</button>
);
}
@@ -0,0 +1,17 @@
.wrapper {
display: flex;
align-items: flex-start;
gap: var(--space-3);
}
.content {
flex: 1;
min-width: 0;
}
.placeholder {
margin: 0;
color: var(--color-text-muted);
font-size: var(--font-size-sm);
line-height: 1.6;
}
@@ -0,0 +1,38 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Eye, EyeOff } from 'lucide-react';
import { Button } from '../Button/Button';
import { CodeBlock } from '../CodeBlock/CodeBlock';
import styles from './RevealableCodeBlock.module.css';
export interface RevealableCodeBlockProps {
code: string;
language?: string;
}
/** A CodeBlock that starts hidden; the code is only rendered after the user reveals it. */
export function RevealableCodeBlock({ code, language }: RevealableCodeBlockProps) {
const { t } = useTranslation();
const [revealed, setRevealed] = useState(false);
return (
<div className={styles.wrapper}>
<div className={styles.content}>
{revealed ? (
<CodeBlock code={code} language={language} />
) : (
<p className={styles.placeholder}>{t('revealable.hidden')}</p>
)}
</div>
<Button
variant="secondary"
size="sm"
aria-expanded={revealed}
onClick={() => setRevealed((r) => !r)}
>
{revealed ? <EyeOff size={14} /> : <Eye size={14} />}
{revealed ? t('revealable.hide') : t('revealable.reveal')}
</Button>
</div>
);
}
+1 -1
View File
@@ -38,7 +38,7 @@ export function SidePanel({
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties} style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
aria-expanded={!collapsed} aria-expanded={!collapsed}
> >
<div className={styles.inner}> <div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
{header && <div className={styles.header}>{header}</div>} {header && <div className={styles.header}>{header}</div>}
<div className={styles.content}>{children}</div> <div className={styles.content}>{children}</div>
</div> </div>
+1 -1
View File
@@ -49,7 +49,7 @@
.sortIconActive { .sortIconActive {
opacity: 1; opacity: 1;
color: var(--color-primary); color: var(--color-primary-text);
} }
[data-theme="dark"] .th { [data-theme="dark"] .th {
@@ -4,6 +4,23 @@
position: relative; position: relative;
} }
.badge {
transition: background var(--transition);
}
.badge:hover {
background: color-mix(in srgb, var(--color-neutral-bg) 85%, white);
}
.swatch {
width: 8px;
height: 8px;
border-radius: 50%;
border: 1px solid currentColor;
box-sizing: border-box;
flex-shrink: 0;
}
.button { .button {
all: unset; all: unset;
cursor: pointer; cursor: pointer;
+10 -1
View File
@@ -7,9 +7,15 @@ export interface UuidBadgeProps {
id: string; id: string;
} }
function uuidColor(id: string): string | null {
const hex = id.replace(/-/g, '').slice(0, 6);
return /^[0-9a-f]{6}$/i.test(hex) ? `#${hex}` : null;
}
export function UuidBadge({ id }: UuidBadgeProps) { export function UuidBadge({ id }: UuidBadgeProps) {
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const short = `${id.slice(0, 4)}…${id.slice(-4)}`; const short = `${id.slice(0, 4)}…${id.slice(-4)}`;
const color = uuidColor(id);
const handleClick = (e: React.MouseEvent) => { const handleClick = (e: React.MouseEvent) => {
e.stopPropagation(); e.stopPropagation();
@@ -21,7 +27,10 @@ export function UuidBadge({ id }: UuidBadgeProps) {
return ( return (
<span className={styles.wrapper} title={copied ? 'Copied!' : id}> <span className={styles.wrapper} title={copied ? 'Copied!' : id}>
<Badge variant="neutral"> <Badge variant="neutral" className={styles.badge}>
{color && (
<span className={styles.swatch} style={{ background: color }} aria-hidden="true" />
)}
<button type="button" className={styles.button} onClick={handleClick}> <button type="button" className={styles.button} onClick={handleClick}>
{short} {short}
</button> </button>
+10
View File
@@ -26,6 +26,8 @@ export { Breadcrumbs } from './Breadcrumbs/Breadcrumbs';
export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs'; export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs';
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher'; export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { NotificationToggle } from './NotificationToggle/NotificationToggle';
export type { NotificationToggleState } from './NotificationToggle/NotificationToggle';
export { ToastProvider } from './Toast/ToastProvider'; export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider'; export type { ToastProviderProps } from './Toast/ToastProvider';
@@ -43,6 +45,9 @@ export type { SearchProps } from './Search/Search';
export { CodeBlock } from './CodeBlock/CodeBlock'; export { CodeBlock } from './CodeBlock/CodeBlock';
export type { CodeBlockProps } from './CodeBlock/CodeBlock'; export type { CodeBlockProps } from './CodeBlock/CodeBlock';
export { RevealableCodeBlock } from './RevealableCodeBlock/RevealableCodeBlock';
export type { RevealableCodeBlockProps } from './RevealableCodeBlock/RevealableCodeBlock';
export { CodeEditor } from './CodeEditor/CodeEditor'; export { CodeEditor } from './CodeEditor/CodeEditor';
export type { CodeEditorProps } from './CodeEditor/CodeEditor'; export type { CodeEditorProps } from './CodeEditor/CodeEditor';
@@ -66,3 +71,8 @@ export type { TableProps, TableColumn, SortDirection } from './Table/Table';
export { UuidBadge } from './UuidBadge/UuidBadge'; export { UuidBadge } from './UuidBadge/UuidBadge';
export type { UuidBadgeProps } from './UuidBadge/UuidBadge'; export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
export { LogOutput } from './LogOutput/LogOutput';
export type { LogOutputProps, LogOutputEntry, LogOutputLevel } from './LogOutput/LogOutput';
export { DEFAULT_LOG_DATA_LIMITS, formatLogText, hasLargeData } from './LogOutput/logText';
export type { LogDataLimits } from './LogOutput/logText';
+29 -4
View File
@@ -11,6 +11,8 @@
--color-primary-hover: #8ABD2E; --color-primary-hover: #8ABD2E;
--color-primary-active: #77A320; --color-primary-active: #77A320;
--color-primary-fg: #2D3339; /* Outer Space on bright green */ --color-primary-fg: #2D3339; /* Outer Space on bright green */
/* Primary as text/icon color on light surfaces (Atlantis is too light for text) */
--color-primary-text: #496904;
/* Secondary — Kimberly tint */ /* Secondary — Kimberly tint */
--color-secondary: #EDEAF8; --color-secondary: #EDEAF8;
@@ -19,8 +21,8 @@
--color-secondary-fg: #6650C0; /* Kimberly */ --color-secondary-fg: #6650C0; /* Kimberly */
--color-secondary-border: #B8B0E0; --color-secondary-border: #B8B0E0;
/* Danger */ /* Danger (white text needs >= 4.5:1) */
--color-danger: #D94F4F; --color-danger: #CE4546;
--color-danger-hover: #C03A3A; --color-danger-hover: #C03A3A;
--color-danger-fg: #ffffff; --color-danger-fg: #ffffff;
@@ -43,11 +45,22 @@
--color-link-hover: #3D2F80; --color-link-hover: #3D2F80;
--color-text: #2D3339; --color-text: #2D3339;
--color-text-muted: #6650C0; /* Kimberly */ --color-text-muted: #634DBD; /* Kimberly, a touch darker for 4.5:1 on bg-subtle */
--color-text-faint: #5C6063; /* desaturated grey, ~4.5:1 on bg-subtle - as washed out as WCAG AA allows */
--color-border: #AFBFB9; /* Powder Ash */ --color-border: #AFBFB9; /* Powder Ash */
--color-bg: #E6EDEA; /* Powder Ash tint */ --color-bg: #E6EDEA; /* Powder Ash tint */
--color-bg-subtle: #D8E2DE; /* Powder Ash tint, 1 step darker */ --color-bg-subtle: #D8E2DE; /* Powder Ash tint, 1 step darker */
/* Syntax highlighting (CodeBlock); each >= 4.5:1 on bg and bg-subtle */
--hl-comment: #4F6557;
--hl-keyword: #764E99;
--hl-string: #4F6821;
--hl-number: #895403;
--hl-function: #056980;
--hl-variable: #815354;
--hl-property: #1D6971;
--hl-meta: #615B7E;
/* Spacing */ /* Spacing */
--space-1: 4px; --space-1: 4px;
--space-2: 8px; --space-2: 8px;
@@ -112,6 +125,7 @@ a:hover {
--color-primary-hover: #AEDE55; --color-primary-hover: #AEDE55;
--color-primary-active: #8ABD2E; --color-primary-active: #8ABD2E;
--color-primary-fg: #1A1F24; --color-primary-fg: #1A1F24;
--color-primary-text: #9DD341;
/* Secondary — dark Kimberly tint */ /* Secondary — dark Kimberly tint */
--color-secondary: #2A2548; --color-secondary: #2A2548;
@@ -122,7 +136,7 @@ a:hover {
/* Danger */ /* Danger */
--color-danger: #E06060; --color-danger: #E06060;
--color-danger-hover: #CC4A4A; --color-danger-hover: #F06E6D; /* lighter, so the dark text keeps >= 4.5:1 */
--color-danger-fg: #1A1F24; --color-danger-fg: #1A1F24;
/* Semantic */ /* Semantic */
@@ -145,7 +159,18 @@ a:hover {
--color-text: #E2EAE6; --color-text: #E2EAE6;
--color-text-muted: #A9A3C9; /* lightened Kimberly */ --color-text-muted: #A9A3C9; /* lightened Kimberly */
--color-text-faint: #9A9A9A; /* desaturated grey, ~4.5:1 on dark bg-subtle - as washed out as WCAG AA allows */
--color-border: #3D4850; --color-border: #3D4850;
--color-bg: #1A1F24; /* deeper than Outer Space */ --color-bg: #1A1F24; /* deeper than Outer Space */
--color-bg-subtle: #2D3339; /* Outer Space */ --color-bg-subtle: #2D3339; /* Outer Space */
/* Syntax highlighting (CodeBlock); each >= 4.5:1 on bg and bg-subtle */
--hl-comment: #8AA192;
--hl-keyword: #B38ADA;
--hl-string: #9BB870;
--hl-number: #E8A85F;
--hl-function: #5BB8D4;
--hl-variable: #D4A0A0;
--hl-property: #79C0C8;
--hl-meta: #A9A3C9;
} }
+17
View File
@@ -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
-23
View File
@@ -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
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff. Show more