Compare commits

..
75 Commits
Author SHA1 Message Date
ars9 a328ef5ea7 feat(runs): record playwright traces with per-run trace mode, bump to 1.15.0
- record a trace for each scenario run and upload it as trace.zip
- add PLAYWRIGHT_TRACE_MODE (on, retain-on-failure, off) as the default
- add a trace mode option to the run modal, stored per run and reused
  by repeat run; expose the default via GET /scenarios/run-defaults
- accept traceMode in POST /scenarios/:id/run and run_scenario MCP tool
- share one run modal component between scenario list and detail pages
- git-ignore server/data
2026-09-30 14:58:07 +03:00
ars9 7d366e6368 feat(runs): add repeat run action to run detail page, bump to 1.14.0
- start a new run with the same environment and saveSession settings
  and navigate to it; disabled when the run's environment was deleted
- remount the run detail page per run id so per-run state resets
- type ScenarioRun.environmentId as nullable to match the backend
2026-09-30 14:35:31 +03:00
ars9 5ea1e38f25 feat(mcp): add credential CRUD tools, bump to 1.13.0
- add list/get/create/update/delete_credential MCP tools so credentials
  can be created and attached to scenarios entirely via MCP
- update_credential only changes the fields passed, keeping data intact
- add changelog entries for 1.13.0 and the missing 1.12.0 release
2026-09-30 14:26:15 +03:00
ars9andClaude Sonnet 5 d99bb75fc2 chore: sync package-lock.json version to 1.12.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 15:53:21 +03:00
ars9andClaude Sonnet 5 d79415cbb3 feat(scenario): dump page screenshot and HTML to run files on step failure
Captures a full-page screenshot and the current page HTML whenever a
scenario or snippet step fails, and uploads both as run artifacts so
failures can be diagnosed from the run's file list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 15:52:32 +03:00
ars9 1eea4eb8d8 feat(scenario): export scenarios as standalone playwright e2e test projects
- Added E2eExportService to package scenarios as plug-and-play zip archives
  containing package.json, playwright.config.ts, test.spec.ts, .env, credentials.json,
  snippets, and referenced scenario files
- Only bundles credentials, snippets, and files actually referenced (directly or
  transitively) by the scenario's steps, reducing archive size
- Exported test runs entirely offline using a context shim that mirrors liqa's API
  (page, getCredential, runSnippet, getScenarioFiles, downloadFile, assert, etc.)
- Added GET /scenarios/:id/export-e2e HTTP endpoint and export_e2e_test MCP tool
- Added getUsedSnippets() endpoint to list snippets referenced by a scenario
- Added "Used Snippets" section on scenario detail page
- Added archiver@^7.0.1 dependency for zip archive creation
- Bumped version to 1.11.0
2026-09-16 12:33:16 +03:00
ars9 385f51f3ba fix(scenario-logs): fix out-of-order run log persistence
- Add seq column assigned in call order to fix logs racing each other
  as fire-and-forget writes (e.g. a snippet's "started" entry could be
  saved after its "finished" entry)
- Log snippet start/finish/failure via context.runSnippet, matching
  existing step start/pass/fail logging
- Rework Markdown log export to per-entry sections instead of a table
- Version bump: 1.10.0 -> 1.10.1
2026-09-15 13:17:29 +03:00
ars9 540a7ec96b feat(logs): add scenario run logs export
- Backend: logs export endpoint for CSV and Markdown formats
- Frontend: ExportLogsModal with download button on run detail page
- Updated i18n and CHANGELOG
- Version bump: 1.9.1 -> 1.10.0
2026-09-15 13:04:59 +03:00
ars9 4e79d3cd81 feat(scenario): add automatic step boundary logging to run logs
- step start, pass, and fail events logged automatically
- step boundaries visible in run logs without explicit context.log calls
- version bumped from 1.9.0 to 1.9.1
2026-09-15 12:53:33 +03:00
ars9 cbfd4404c1 feat(scenario): add context.assert() API for script assertions
- Add context.assert(fn, description) for function assertions
- Logs outcome on success/failure, throws on assertion failure
- Bump package version from 1.8.0 to 1.9.0
2026-09-15 12:35:17 +03:00
ars9andClaude Sonnet 5 50820b8b40 feat(scenario): let context.downloadFile save data: URLs as run artifacts
Scenario steps can now persist in-script generated content (e.g. an
obtained VC's JWT) as a run file via context.downloadFile('data:...'),
without needing a network fetch. Bumps to 1.8.0.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 10:37:22 +03:00
ars9 502a3e4f2c 1.7.1 2026-04-21 18:09:49 +03:00
ars9 b57b55f3e1 feat(mcp): add file tools for scenarios and runs
- expose scenario file upload, listing, and content retrieval over MCP\n- expose run artifact listing and content retrieval with end-to-end coverage
2026-04-21 18:00:41 +03:00
ars9 06c662042b doc(changelog): add changelog 2026-04-21 17:09:05 +03:00
ars9 461669b3fb 1.7.0 2026-04-21 16:49:46 +03:00
ars9 9580a7b2df fix(files): expose expiry and disable expired downloads
- return expiresAt and createdAt for scenario and run file metadata\n- keep download actions visible while preventing expired file access
2026-04-21 16:46:33 +03:00
ars9 86f9ac5603 feat(files): add file management UI for scenarios and runs
- add scenario upload and download UI with typed file API helpers
- show run artifacts on run detail pages after polling completes
- handle multipart uploads and absolute file paths for downloads
2026-04-21 15:58:04 +03:00
ars9 6a91ce30e3 feat(files): add file storage subsystem with scenario and run artifact support
- add FileEntity, ScenarioFileEntity, ScenarioRunFileEntity with UUID-sharded disk tree
- FileStorageService: write/sha256/expiry, paginated listing, dynamic cleanup cron via SchedulerRegistry
- expose getScenarioFiles() and downloadFile() on ScriptContext for use in exec code
- wire scenarioId, runId, fileService into ExecContextBuilder and scenario scheduler
- add file upload and listing endpoints to ScenarioController
- add FILES_DIR, FILE_RUN_EXPIRATION_DAYS, FILE_CLEANUP_CRON to AppConfig
2026-04-21 13:01:09 +03:00
ars9 aa3bae9020 feat(client): set dynamic page title based on content
- add usePageTitle hook that writes '<title> | Liqa' to document.title
- list pages use section name; detail pages use entity name once loaded
- create/edit pages use static action title, edit includes entity name
2026-04-20 16:32:16 +03:00
ars9 ba46789226 feat(mcp): add snippet CRUD tools to MCP server
- register list_snippets, get_snippet, create_snippet, update_snippet, delete_snippet
- inject SnippetService into McpService and import SnippetModule into McpModule
- cover all five tools with integration tests including error cases
2026-04-20 16:21:52 +03:00
ars9 4e494ce4fd feat(scenarios): show last run status and timestamp on scenarios list
- extend findAll to join latest run per scenario via correlated subquery
- return lastRunStatus and lastRunAt fields in GET /scenarios response
- add Last Run column with badge and timestamp to ScenariosPage
- add integration tests for null and populated lastRunStatus
2026-04-17 15:13:28 +03:00
ars9 8c6158e8e3 1.6.1 2026-04-17 14:49:03 +03:00
ars9 b4cfe050fa perf(scenario-scheduler): parallelize run pickup with effect, add cache cleanup
- replace sequential for-loop in pickUpPendingRuns with Effect.forEach concurrency:10
- extract CONCURRENCY_LIMIT constant shared by both startup and pickup paths
- clear all run caches (creds, snippets, env, timeouts, activeRuns) on setup failure
- call failRun on setup error to leave the db run in a consistent failed state
2026-04-17 14:48:55 +03:00
ars9 a199700878 perf(scenario-scheduler): parallelize stale-run cleanup on startup with effect
- use Effect.forEach with concurrency:10 to fail up to 10 runs in parallel
- isolate each failRun with catchAll so one failure doesn't abort the rest
- log unexpected failRun errors per run without halting the batch
2026-04-17 14:32:25 +03:00
ars9 2a46b355db fix(scenario-runner): harden run failure handling across all paths
- add onModuleInit to fail in_progress runs on server restart
  (playwright sessions cannot be recovered after restart)
- extract failRun() shared method used by restart cleanup, timeout,
  and unexpected error paths for consistent step run status updates
- fix catch path to also fail/cancel step runs (previously left orphaned)
- accept plain {name, steps} payload in importScenario alongside
  full export format; throw BadRequestException for invalid input
- include stepRuns relation in findRuns paginated response
- add scenario-scheduler.spec.ts integration tests for onModuleInit
2026-04-17 14:11:43 +03:00
ars9 a50dce2755 feat(scenarios): add timeoutSeconds to scenarios and steps
- add timeoutSeconds field to scenario and step entities
- add timeoutSeconds to create/update DTOs for scenario and step
- enforce timeout via scheduler: abort run if step exceeds limit
- expose timeoutSeconds in MCP create/update scenario and step tools
- add client-side type, API, i18n, and form support for timeoutSeconds
- add integration tests for timeout persistence via REST and MCP
2026-04-17 13:46:30 +03:00
ars9 8dbd319bba fix(scenario-runner): preserve session on failed runs
- failStepRun was calling closeBrowserHandle immediately, removing the
  handle before maybePreserveSession could read it in the finally block
- delegate browser lifecycle to maybePreserveSession for both pass and
  fail paths so saveSession=true is honoured regardless of run outcome
2026-04-15 18:49:31 +03:00
ars9 67e230a647 fix(credential): stamp lastUsedAt via db CURRENT_TIMESTAMP when run consumes credentials 2026-04-15 12:26:09 +03:00
ars9 ad155e269c feat(table,runs,sessions): add server-side sorting and pagination
- add sortable column support to Table with asc/desc/unsorted icons
- active sort icon uses --color-primary; no header background change
- Table supports server-side mode via total/page/onPageChange props
- wire server-side sort+pagination in ScenariosPage, AllRunsPage, RunsPage, SessionsPage
- remove steps count column from run tables
- fix server: RunsQueryDto now extends PaginationQueryDto with orderBy/orderDir
- fix findAllRuns to use QueryBuilder; sort by scenario.name via JOIN
- add per-resource typed query DTOs with @IsIn allowlist on orderBy
- prevents SQL injection and returns 400 for unknown orderBy values
2026-04-15 12:18:47 +03:00
ars9 f268d0e3eb feat(scenarios): overhaul export/import with multi-entity YAML format
- export now accepts includeEnvironment and credentialIds query params
- output is a YAML stream with comment-delimited environment, credential, and scenario sections
- scenario entity includes credentials array with alias mappings
- import accepts both old single-object and new array format, upserts envs/creds before linking
- new ExportScenarioModal with env and per-credential checkboxes replaces direct download
2026-04-15 00:35:14 +03:00
ars9 a779ab4667 feat(scenarios): link scenarios to a default environment
- add optional ManyToOne relation from scenario to environment entity
- expose environmentId in create/update DTOs, service, and MCP tools
- pre-select linked environment in run modals on detail and list pages
- add environment selector to create/edit scenario forms
- show linked environment as a navigable link on scenario detail page
2026-04-15 00:05:55 +03:00
ars9 e6aacc899d feat(scenarios,environments): add markdown description field
- add optional description to scenario and environment entities
- expose description in create/update DTOs, MCP tools, and export DTOs
- render description as markdown on detail pages
- add description editor (CodeEditor) to create/edit forms for both resources
2026-04-14 23:53:45 +03:00
ars9 4dab218b75 1.6.0 2026-04-14 23:16:44 +03:00
ars9 622924ed53 refactor(nav): reorganize sidebar with dynamic sections at top
- move runs and sessions to top of navigation (most dynamic)
- add visual separator between dynamic and configuration sections
- reorder remaining items: scenarios, snippets, credentials, environments
- implement separator component in nav rendering logic
2026-04-14 23:15:49 +03:00
ars9 6c43b53590 fix(scenarios): add error handling for API calls and dev script with local API
- add catch handler to promises for better error visibility
- use null coalescing operators to prevent undefined accessing
- add dev:compose-api npm script pointing to localhost:13000 API
- include toast dependency in useCallback to avoid stale closures
2026-04-14 23:09:38 +03:00
ars9 e66e53c817 chore: apply code formatting and linting
- format long import statements with consistent line wrapping
- apply consistent indentation across client and server modules
- remove generated tsconfig.tsbuildinfo file
2026-04-14 22:54:03 +03:00
ars9 a71be39076 fix: fix links in scenario service 2026-04-14 21:11:35 +03:00
ars9 5ec9fd0bc3 refactor: add session and environment relationships to scenario run
- add sessionId optional column to ScenarioRunEntity
- add ManyToOne relationship to EnvironmentEntity (with eager loading)
- add ManyToOne relationship to SessionEntity (optional)
- update ScenarioRun client types to include session and environment data
- add environment name and session link to RunDetailPage
- update UI to display save session, environment, and session info
2026-04-14 19:29:48 +03:00
ars9 80d9af42b5 fix: add save session checkbox to run modal on scenarios list page
- add saveSessionFlag state to ScenariosPage
- pass saveSessionFlag to scenarios.run() call
- render save session checkbox in run modal when envs are available
- reset saveSessionFlag after scenario run completes
2026-04-14 19:24:13 +03:00
ars9 dcb002304b feat(run-detail): add expandable step output blocks with json pretty-printing
- add collapsible code blocks for step output with JSON syntax highlighting
- display byte count when output exists but no description available
- support both individual row expansion and header-level expand all toggle
- pretty-print JSON output for improved readability
- wrap log messages in code tags for monospace display
- fix step order numbering to start from 1 instead of 2
2026-04-14 19:19:39 +03:00
ars9 196bf4c2e8 feat: add saveSession flag to create scenario runs
- Add optional `saveSession` boolean parameter to CreateScenarioRunDto
- Add `saveSession` column to ScenarioRunEntity
- When saveSession=true and run completes, preserve the browser context as a named explore session instead of closing it
- Session name follows pattern: run-{runId}
- Automatically extracts token and localStorage for session persistence
- Injected SessionService and SessionContextService into ScenarioSchedulerService
- Updated MCP run_scenario tool to accept saveSession parameter
- Updated UI run dialog with checkbox to enable session preservation
- Client API updated to pass saveSession flag
2026-04-14 18:54:45 +03:00
ars9 0e47623a6b feat(browser,mcp): resolve environment and credentials from DB in exec
- POST /exec now accepts environmentId (UUID) and credentials (alias → UUID)
  instead of raw payloads; resolves entities via EnvironmentService and
  CredentialService before passing data to browserService.exec
- exec_code MCP tool updated with same schema: environmentId + credentials map
- CredentialModule imported into BrowserModule and McpModule
- docs(scenario): rewrite script runtime section for single context argument
- docs(mcp): update exec_code description to reflect new parameter shapes
- style: reorder imports across server source (formatter)
2026-04-14 18:09:28 +03:00
ars9 90be5a5490 refactor(code-executor): migrate user scripts to single context argument
- replace (page, context, helpers) signature with async (context) => {}
- add ScriptContext interface exposing page, browser, env, getEnv,
  getCredential, getStepOutput, runSnippet, dumpDom, log/warn/error
- rename getEnvUrl to getEnv throughout service and docs
- fix step ordering: normalizeStepOrder and run step rows are now 1-based
- migrate existing DB rows (scenario_steps, scenario_run_steps) +1
- update all tests and stored snippet/step code in DB to new API
2026-04-14 17:44:59 +03:00
ars9 1a2e786ca8 feat(browser): add environment, credentials, and script logger to POST /exec
- ExecDto gains optional `environment` and `credentials` fields
- BrowserService.exec forwards both to CodeExecutorService.execute so
  helpers.env, helpers.getEnvUrl(), and helpers.getCredential() work
  identically to scenario-scheduler steps
- script console.log/warn/error now routed through TraceLogger with
  session label prefix
- integration tests cover env/creds injection and missing-alias error
2026-04-14 16:57:06 +03:00
ars9 d34ea9e943 fix(browser): inject snippets into exec_code context; fix(ui): step order starts at 1 in run detail
- BrowserService.exec() now builds snippet map via SnippetService and passes
  it to CodeExecutorService.execute() for both named-session and anonymous paths
- SnippetModule added to BrowserModule imports to wire the dependency
- RunDetailPage step order column renders s.order + 1 (was 0-based)
2026-04-14 16:28:31 +03:00
ars9 310997c3ae feat(mcp): add credential and all-runs tools; replace deprecated z.string().uuid()
- add list_scenario_credentials, add_scenario_credential, remove_scenario_credential tools
- add list_all_runs tool (global across all scenarios)
- replace all deprecated z.string().uuid() with z.uuid() throughout mcp.service
2026-04-14 14:45:55 +03:00
ars9 7acd1bc5a1 feat(client): add nginx config for SPA routing and API proxy
- add try_files fallback to serve index.html for all non-asset paths
- proxy /api/ requests to the server container to avoid HTML being
  returned by nginx for API calls when using full route paths
2026-04-14 13:05:55 +03:00
ars9 5ba327b745 1.5.0 2026-04-11 00:53:44 +03:00
ars9 238c52610a refactor(scenario): remove validateCode — assertions live in execCode
- drop validateCode column, DTOs, service mappings, and scheduler branch
- remove parseValidateResult helper and ValidateResult interface
- inject playwright expect into code executor for direct use in execCode
- strip validateCode from MCP tool schemas, client types, and UI forms
2026-04-11 00:52:50 +03:00
ars9 29e91b0078 test(server): align specs with run environment and step schema
- update scenario tests to create runs with required environmentId
- adjust browser controller expectations to session auto-create behavior
- sync playwright/context mocks with current browser service usage
2026-04-11 00:22:58 +03:00
ars9 56d23f913d feat(scenarios): require environment for scenario runs
- require environmentId when creating runs in API and MCP tools

- pass selected environment data into step execution helpers

- prompt for environment selection before running scenarios in UI
2026-04-11 00:12:21 +03:00
ars9 d8ea2d0126 feat(ui): require confirmation before delete actions
- add a reusable modal component and export it from the shared ui barrel

- gate all delete and remove flows behind explicit confirmation dialogs

- use a solid modal surface color token with fallback to avoid transparent body
2026-04-10 23:46:20 +03:00
ars9 7223371fae refactor(snippets): adopt alias/title model and markdown UX
- rename snippet identity from name to alias and add required title fields

- migrate snippet API, forms, cards, and detail views to alias/title semantics

- render markdown descriptions with short card previews and split vendor chunks
2026-04-10 23:26:36 +03:00
ars9 11db983ea6 refactor(api): version routes and externalize client base url
- serve REST endpoints under /api/v1 with root exceptions for health and mcp

- move swagger UI to /docs and allow direct frontend calls via CORS

- remove Vite proxy/hash routing and rely on env-driven VITE_API_URL
2026-04-10 22:53:32 +03:00
ars9 ccce3381c1 refactor(client): centralize error feedback with toast events
- emit API/network failures through a shared toast event bridge

- remove per-page inline error notifications to avoid duplicate error UI

- dedupe repeated toast messages to keep feedback readable
2026-04-10 22:24:30 +03:00
ars9 7444082b65 feat(ui): add toasts for create edit and run flows
- add global ToastProvider and useToast hook mounted at app root

- show success/error toasts for environment, credential, snippet, and scenario create/edit actions

- show run-started/error toasts on scenario run actions with 100ms exit animation
2026-04-10 21:44:04 +03:00
ars9 d511c85891 refactor(client): split feature chunks and polish environment ui
- lazy-load route pages and add entity-based manual chunking in Vite

- prevent environment pages from crashing when legacy records miss data

- fix sidebar toggle chevron direction and make env forms full width
2026-04-10 21:32:07 +03:00
ars9 fd515ee459 refactor(environment): rename urls payload to data
- replace hardcoded URL keys with a generic key-value data map

- align backend DTOs, MCP schemas, and service import/export mapping

- update environment UI forms to edit JSON data instead of fixed fields
2026-04-10 21:22:46 +03:00
ars9 b45f95d8cf refactor(session): auto-create named browser sessions
- create and register named browser sessions on open/exec when missing

- align scenario step DTO/entity/service by removing sessionName usage

- update MCP scenario-step schemas to use optional title fields
2026-04-10 21:06:00 +03:00
ars9 1627733701 docs: refresh architecture and runtime documentation
- align architecture, development, MCP, and scenario docs with current code

- remove obsolete key descriptor document and stale keys/auth references
2026-04-10 20:40:20 +03:00
ars9 0e4a2e1819 feat(app): add environment import/export and sidebar footer info
- add environment import/export API endpoints and client integration

- add environment export actions and toolbar import/export buttons in UI

- move theme switcher to sidebar bottom and show root package version

- switch snippet card menu icon to cog for consistent options affordance
2026-04-10 20:29:40 +03:00
ars9 99da7ac891 feat(ui): add breadcrumb icons, fix alignment, and remove duplicate form headers
- add section icons to all breadcrumbs across every page
- fix breadcrumb nav display:flex so icons align vertically with buttons
- wrap all page breadcrumbs in pageToolbar div for consistent layout
- add Breadcrumbs to AllRunsPage which previously used a plain h1
- fix envCardHeader flex:1 so settings button hugs the right edge
- remove card header from environment create/edit forms (duplicated breadcrumb)
2026-04-10 19:58:33 +03:00
ars9 de0cbeef7c refactor(workspace): restore yaml exports and align docker builds
- return scenario export payloads as yaml to match existing workflows

- harden step reordering flow for drag-and-drop and one-based ui labels

- switch server container to workspace-lockfile installs and root ignore rules
2026-04-10 18:19:38 +03:00
ars9 259dac806e refactor(auth): remove keys auth module and align tests
- remove server auth module and client keys page/routes/api to simplify flow

- update mcp and scenario tests to match uuid routes and step schema
2026-04-10 16:42:43 +03:00
ars9 673aa0f458 refactor(scenario): remove step type and simplify scheduler to exec-only
- remove StepType, type column, and type field from step entity and DTOs
- remove executeLoginStep, executeSignStep, executeExecStep from scheduler
- inline exec logic directly in executeStepRun; all steps run execCode
- remove AuthService, EnvironmentService, runEnvironments from scheduler
- remove type selector from CreateStepPage and EditStepPage
- remove type badge column from ScenarioDetailPage
- fix useEffect dependency arrays in RunDetailPage (FINAL, id, runId, polling)
- fix duplicate /snippets proxy key in vite.config.ts
- remove unused escapeHtml export from hljs.ts
2026-04-10 16:14:17 +03:00
ars9 1c13e068ad feat(ui): add CodeBlock and CodeEditor components with Monaco and hljs
- add CodeBlock for read-only syntax-highlighted display (hljs, js/json)
- add CodeEditor wrapping Monaco editor with theme sync, focus state, and error state
- replace code textareas in snippet, credential, and step pages with CodeEditor
- replace code <pre> blocks in snippet and credential detail pages with CodeBlock
- make form cards full-width on pages with code editors
- add resize:vertical support to CodeEditor wrapper with automaticLayout
2026-04-10 15:53:26 +03:00
ars9 2046e64428 feat(runs): add log search with backend LIKE filter and pagination
- add Search pill component with lucide icon and focus highlight
- wire debounced search input to GET /run/:id?q= backend filter
- backend filters run logs with LIKE %q% via TypeORM
- add sectionHeadingRow layout for heading + search alignment
- add i18n keys: runs.step_title, logs_search_placeholder
2026-04-10 15:09:05 +03:00
ars9 fd655c3253 feat(runs): add step title column, step descriptions, and snippet logging 2026-04-10 14:56:15 +03:00
ars9 607abcafc5 fix(scenarios): order runs by createdAt desc, scenarios list by updatedAt desc 2026-04-10 13:57:34 +03:00
ars9 b26eb10b3d 1.4.0 2026-04-10 13:09:25 +03:00
ars9 32be7c0a59 feat(export-import): add yaml export/import with id upsert for credentials, snippets, and scenarios
- all entities export a kind field (credential/snippet/scenario) for safe type checking on import
- import upserts by id: overwrites if id exists, creates with explicit id otherwise
- scenario export now includes id and step ids; import deletes old steps before recreating
- add GET /:id/export and POST /import endpoints to credential and snippet controllers
- add UuidBadge ui component: shortens uuid to first+last 4 hex chars, tooltip, clipboard copy with animated ClipboardCheck icon pop
- apply UuidBadge across all entity id display sites (detail pages, card footers, table columns)
- add export/import buttons to CredentialsPage, SnippetsPage, CredentialDetailPage, SnippetDetailPage
2026-04-10 13:09:09 +03:00
ars9 1164289173 feat(snippets): add snippets entity, crud, and auto-browser-per-run
- add Snippet entity with name, description, code; full CRUD backend
- add snippets pages (list, create, edit, detail) and nav entry
- add runSnippet helper in code-executor using new Function with args array
- add result param to execute() so validateCode can access exec output
- remove sessionName from steps; each run now spawns its own fresh browser
- fix waitForURL race by polling localStorage for token instead
2026-04-10 00:22:51 +03:00
ars9 1efbbb38a3 feat(scenarios): add step title, scenario credentials, and environment context in executor
- add nullable title column to scenario steps; exposed in create/edit forms and step table
- add scenario-credential join (many-to-many with CredentialEntity) with CRUD endpoints
- expose environment URLs in code executor helpers via helpers.env and helpers.getEnvUrl()
- resolve and cache environment per run from the login step's environmentName in scheduler
- add section spacing and step table title column to ScenarioDetailPage
2026-04-09 23:37:21 +03:00
ars9 1f3a604940 feat(runs): add runs pages, polling, autorefresh indicator, and scheduler fix
- add global runs page and per-scenario runs/run-detail pages
- run detail page polls every 1s until pass/fail, cleans up on unmount
- runs list pages poll every 10s with AutoRefreshIndicator (pulse on data load)
- fix scheduler: set run to pass after empty step loop to prevent stuck in_progress
- fix table header colors and link cell color for readability
- fix play button to navigate to the new run after creation
- fix package.json import paths in server for Docker build context
2026-04-09 21:58:27 +03:00
ars9 ebcb8b8ff4 refactor(client): group pages by entity and add scenario/step crud
- move environment, scenario, session pages into entity subdirs
- add CreateScenarioPage and EditScenarioPage
- add CreateStepPage and EditStepPage with order/type/session/code fields
- add per-step edit and delete row actions on ScenarioDetailPage
- add step api methods (get, create, update, remove) to api client
- add sectionToolbar, formField, fieldLabel, textarea css utilities
2026-04-09 20:45:34 +03:00
194 changed files with 18285 additions and 13786 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
.git
.gitignore
node_modules
**/node_modules
**/dist
**/.DS_Store
**/*.log
data
keys
+4 -1
View File
@@ -14,4 +14,7 @@ DB_PATH=data/sessions.db
# 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
SESSION_DELETE_CLOSED_DAYS=7
# Playwright trace recording for scenario runs: on | retain-on-failure | off
PLAYWRIGHT_TRACE_MODE=on
+11 -2
View File
@@ -1,6 +1,6 @@
# runtime / secrets
/keys
# runtime
/data
server/data/
.env
*.log
@@ -13,3 +13,12 @@ server/dist
client/dist
*storybook.log
storybook-static
tsconfig.tsbuildinfo
# organization
TODO.md
# IDE/editor
.vscode/
.idea/
.github/
+143
View File
@@ -0,0 +1,143 @@
# Changelog
All notable changes to this project will be documented in this file.
## 1.15.0 - 2026-09-30
Changes since 1.14.0:
### Added
- Scenario runs now record a Playwright trace (screenshots and DOM snapshots) and upload it to the run's files as `trace.zip` when the run finishes. Open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
- Added the `PLAYWRIGHT_TRACE_MODE` setting (`on` (default), `retain-on-failure`, or `off`) that controls which traces are kept.
- Added a "Playwright trace" option to the run modal to override the trace mode for a single run. It defaults to the server's `PLAYWRIGHT_TRACE_MODE`, served by the new `GET /scenarios/run-defaults` endpoint.
- `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `traceMode`. The trace mode is stored on the run, shown on the run detail page, and reused by "Repeat run".
### Changed
- The run modals on the scenario list and scenario detail pages now share one component.
- `server/data/` is now git-ignored.
## 1.14.0 - 2026-09-30
Changes since 1.13.0:
### Added
- Added a "Repeat run" button on the scenario run detail page that starts a new run of the same scenario with the same environment and "save session" setting, then navigates to it. The button is disabled when the run's environment has since been deleted.
## 1.13.0 - 2026-09-30
Changes since 1.12.0:
### Added
- Added credential CRUD tools to the MCP server: `list_credentials`, `get_credential`, `create_credential`, `update_credential`, and `delete_credential`. Combined with the existing `add_scenario_credential` tool, credentials can now be created and attached to scenarios entirely via MCP.
## 1.12.0 - 2026-09-16
Changes since 1.11.0:
### Added
- When a scenario or snippet step fails, a full-page screenshot and the current page HTML are captured and uploaded as run artifacts, so failures can be diagnosed from the run's file list.
## 1.11.0 - 2026-09-15
Changes since 1.10.1:
### Added
- Added export of a scenario as a standalone, plug-and-play Playwright e2e test project (zip archive with `package.json`, `playwright.config.ts`, `test.spec.ts`, `README.md`, `.env`, `credentials.json`, `snippets/*.js`, and any attached scenario files) that runs entirely independently of the liqa backend. Available as a "Export e2e test" button on the scenario detail page, `GET /scenarios/:id/export-e2e`, and the `export_e2e_test` MCP tool.
- The exported test only bundles the credentials, snippets, and attached files actually referenced (directly or transitively) by the scenario's steps.
- Added a "Used Snippets" section on the scenario detail page listing the snippets referenced by the scenario's steps, linking to each snippet's detail page. Backed by `GET /scenarios/:id/used-snippets`.
## 1.10.1 - 2026-09-15
Changes since 1.10.0:
### Added
- `context.runSnippet()` now logs "Snippet started"/"finished"/"failed" entries, matching the automatic step start/pass/fail logging.
### Changed
- Reworked the Markdown log export format: each log entry is now its own `## [level] timestamp` section with the message as its body, instead of a single large table.
### Fixed
- Run logs could persist out of call order (e.g. a snippet's "started" log appearing after its "finished" log) because writes were fire-and-forget and raced against each other. Log entries now carry a per-run sequence number assigned in call order, and queries/exports sort by it.
## 1.10.0 - 2026-09-15
Changes since 1.9.1:
### Added
- Added a "Download logs" button on the scenario run detail page: opens a modal to choose Markdown (default) or CSV, then downloads the run's logs in that format.
- Added `GET /scenarios/:id/run/:runId/logs/export?format=csv|md` backend endpoint to export a run's logs.
## 1.9.1 - 2026-09-15
Changes since 1.9.0:
### Added
- Scenario run logs now include an automatic entry when a step starts and when it finishes (pass or fail), so step boundaries are visible in run logs even for steps that don't call `context.log`/`context.assert` themselves.
## 1.9.0 - 2026-09-15
Changes since 1.8.0:
### Added
- Added `context.assert(fn, description)` for scenario/snippet script steps: runs the given function, requires it to return `true`, logs the outcome (`log` on success, `error` on failure or exception), and throws to stop the step on failure.
### Changed
- Documented `context.assert` in `docs/scenario.md`.
## 1.8.0 - 2026-09-15
Changes since 1.7.1:
### Added
- `context.downloadFile()` now accepts `data:` URIs, so scenario steps can save in-script generated content (e.g. a credential JWT) as a run artifact without a network fetch.
### Changed
- Documented the full scenario step `context` file API (`getScenarioFiles`, `downloadFile`) in `docs/scenario.md`.
## 1.7.1 - 2026-04-21
Changes since 1.7.0:
### Added
- Added MCP tools to upload, list, and fetch scenario files using base64 content payloads.
- Added MCP tools to list run artifacts and fetch run artifact content with metadata.
### Changed
- Documented MCP binary content handling for scenario files and run artifacts.
## 1.7.0 - 2026-04-21
Changes since 1.6.1:
### Added
- Added scenario file storage and run artifact support on the backend.
- Added file management UI for scenarios and run details, including artifact lists.
- Added snippet CRUD tools to the MCP server.
### Changed
- Added dynamic page titles based on the active client content.
- Extended the scenarios list to show the latest run status and timestamp.
### Fixed
- Exposed file expiry metadata in scenario and run file responses.
- Disabled expired download actions in the UI while keeping the action visible.
+3
View File
@@ -0,0 +1,3 @@
# Frontend API base URL.
# Example for local Docker server: backend container is exposed on localhost:13000.
VITE_API_URL=http://localhost:13000/api/v1
+1
View File
@@ -15,5 +15,6 @@ RUN npm run -w client build
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
@@ -0,0 +1,17 @@
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;
}
}
+9 -1
View File
@@ -4,23 +4,31 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"test:compile": "tsc --noEmit",
"test:storybook": "vitest run --project storybook",
"lint": "eslint src .storybook",
"lint:fix": "eslint src .storybook --fix",
"format": "prettier --write \"src/**/*.{ts,tsx}\" \".storybook/**/*.{ts,tsx}\""
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
"moment": "^2.30.1",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-i18next": "^17.0.2",
"react-router-dom": "^7.14.0"
"react-markdown": "^10.1.0",
"react-router-dom": "^7.14.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.8.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
+28
View File
@@ -30,6 +30,28 @@
padding: var(--space-2) 0;
}
.sideContent {
display: flex;
flex-direction: column;
min-height: 100%;
}
.sideFooter {
margin-top: auto;
padding: var(--space-3) var(--space-2) var(--space-2);
border-top: var(--border-width) solid var(--color-border);
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
}
.version {
color: var(--color-text-muted);
font-size: var(--font-size-xs);
white-space: nowrap;
}
.navItem {
display: flex;
align-items: center;
@@ -73,6 +95,12 @@
background: var(--color-secondary-hover);
}
.navSeparator {
height: var(--border-width);
background: var(--color-border);
margin: var(--space-2) var(--space-2);
}
.main {
flex: 1;
overflow-y: auto;
+145 -41
View File
@@ -1,25 +1,103 @@
import { lazy, Suspense } from 'react';
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Globe, KeyRound, Monitor, ClipboardList } from 'lucide-react';
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg';
import { EnvironmentsPage } from './pages/EnvironmentsPage';
import { EnvironmentDetailPage } from './pages/EnvironmentDetailPage';
import { CreateEnvironmentPage } from './pages/CreateEnvironmentPage';
import { EditEnvironmentPage } from './pages/EditEnvironmentPage';
import { KeysPage } from './pages/KeysPage';
import { SessionsPage } from './pages/SessionsPage';
import { SessionDetailPage } from './pages/SessionDetailPage';
import { ScenariosPage } from './pages/ScenariosPage';
import { ScenarioDetailPage } from './pages/ScenarioDetailPage';
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
);
const EnvironmentDetailPage = lazy(() =>
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
default: m.EnvironmentDetailPage,
})),
);
const CreateEnvironmentPage = lazy(() =>
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
default: m.CreateEnvironmentPage,
})),
);
const EditEnvironmentPage = lazy(() =>
import('./pages/environment/EditEnvironmentPage').then((m) => ({
default: m.EditEnvironmentPage,
})),
);
const SessionsPage = lazy(() =>
import('./pages/session/SessionsPage').then((m) => ({ default: m.SessionsPage })),
);
const SessionDetailPage = lazy(() =>
import('./pages/session/SessionDetailPage').then((m) => ({ default: m.SessionDetailPage })),
);
const ScenariosPage = lazy(() =>
import('./pages/scenario/ScenariosPage').then((m) => ({ default: m.ScenariosPage })),
);
const ScenarioDetailPage = lazy(() =>
import('./pages/scenario/ScenarioDetailPage').then((m) => ({ default: m.ScenarioDetailPage })),
);
const CreateScenarioPage = lazy(() =>
import('./pages/scenario/CreateScenarioPage').then((m) => ({ default: m.CreateScenarioPage })),
);
const EditScenarioPage = lazy(() =>
import('./pages/scenario/EditScenarioPage').then((m) => ({ default: m.EditScenarioPage })),
);
const CreateStepPage = lazy(() =>
import('./pages/scenario/CreateStepPage').then((m) => ({ default: m.CreateStepPage })),
);
const EditStepPage = lazy(() =>
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
);
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
const RunDetailPage = lazy(() =>
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
);
const AllRunsPage = lazy(() =>
import('./pages/run/AllRunsPage').then((m) => ({ default: m.AllRunsPage })),
);
const CredentialsPage = lazy(() =>
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
);
const CreateCredentialPage = lazy(() =>
import('./pages/credential/CreateCredentialPage').then((m) => ({
default: m.CreateCredentialPage,
})),
);
const EditCredentialPage = lazy(() =>
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
);
const CredentialDetailPage = lazy(() =>
import('./pages/credential/CredentialDetailPage').then((m) => ({
default: m.CredentialDetailPage,
})),
);
const SnippetsPage = lazy(() =>
import('./pages/snippet/SnippetsPage').then((m) => ({ default: m.SnippetsPage })),
);
const CreateSnippetPage = lazy(() =>
import('./pages/snippet/CreateSnippetPage').then((m) => ({ default: m.CreateSnippetPage })),
);
const EditSnippetPage = lazy(() =>
import('./pages/snippet/EditSnippetPage').then((m) => ({ default: m.EditSnippetPage })),
);
const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
);
const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: true })[] = [
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ separator: true },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
];
export default function App() {
@@ -31,41 +109,67 @@ export default function App() {
header={
<div className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
<ThemeSwitcher />
</div>
}
width={220}
>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
</nav>
<div className={styles.sideContent}>
<nav className={styles.nav}>
{NAV.map((item, index) =>
'separator' in item ? (
<div key={`separator-${index}`} className={styles.navSeparator} />
) : (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(item.labelKey)}
</NavLink>
),
)}
</nav>
<div className={styles.sideFooter}>
<ThemeSwitcher />
<div className={styles.version}>v{__APP_VERSION__}</div>
</div>
</div>
</SidePanel>
<main className={styles.main}>
<Routes>
<Route index element={<Navigate to="/scenarios" replace />} />
<Route path="/environments" element={<EnvironmentsPage />} />
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
<Route path="/keys" element={<KeysPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/sessions/:id" element={<SessionDetailPage />} />
<Route path="/scenarios" element={<ScenariosPage />} />
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
<Suspense fallback={<p>Loading…</p>}>
<Routes>
<Route index element={<Navigate to="/scenarios" replace />} />
<Route path="/environments" element={<EnvironmentsPage />} />
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/sessions/:id" element={<SessionDetailPage />} />
<Route path="/scenarios" element={<ScenariosPage />} />
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
<Route path="/credentials" element={<CredentialsPage />} />
<Route path="/credentials/new" element={<CreateCredentialPage />} />
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
<Route path="/runs" element={<AllRunsPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
</Suspense>
</main>
</div>
);
+324 -38
View File
@@ -1,77 +1,191 @@
import type {
PaginatedResponse,
Credential,
Environment,
KeysResponse,
FileMetadata,
FileListResponse,
RunDefaults,
ScenarioCredential,
Session,
Scenario,
ScenarioRun,
ScenarioRunDetail,
ScenarioRunStep,
ScenarioStep,
Snippet,
TraceMode,
} from './types';
import { emitApiErrorToast } from '../lib/toast-events';
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
// In production (or when VITE_API_URL is set) we hit the configured origin directly.
const BASE_URL: string = (import.meta.env.VITE_API_URL as string | undefined) ?? '';
// API calls are versioned under /api/v1 by default.
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
/\/$/,
'',
);
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE_URL}${path}`, {
headers: { 'Content-Type': 'application/json', ...init?.headers },
...init,
});
let res: Response;
try {
const headers = new Headers(init?.headers);
if (!(init?.body instanceof FormData) && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
res = await fetch(`${BASE_URL}${path}`, {
...init,
headers,
});
} catch (err) {
const message = (err as Error).message || 'Network request failed';
emitApiErrorToast(message);
throw new Error(message);
}
if (!res.ok) {
const text = await res.text().catch(() => res.statusText);
throw new Error(`${res.status} ${text}`);
const message = `${res.status} ${text}`;
emitApiErrorToast(message);
throw new Error(message);
}
const contentLength = res.headers.get('content-length');
if (res.status === 204 || contentLength === '0') return undefined as T;
const contentType = res.headers.get('content-type')?.toLowerCase() ?? '';
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
if (contentType.includes('application/json')) {
return JSON.parse(text) as T;
}
return text as T;
}
// ── Credentials ───────────────────────────────────────────────────────────────
export const credentials = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Credential>> {
return request(`/credentials?page=${page}&limit=${limit}`);
},
get(id: string): Promise<Credential> {
return request(`/credentials/${id}`);
},
create(name: string, data?: string): Promise<Credential> {
return request('/credentials', {
method: 'POST',
body: JSON.stringify({ name, data }),
});
},
update(id: string, patch: Partial<Pick<Credential, 'name' | 'data'>>): Promise<Credential> {
return request(`/credentials/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: string): Promise<void> {
return request(`/credentials/${id}`, { method: 'DELETE' });
},
exportCredential(id: string): Promise<unknown> {
return request(`/credentials/${id}/export`);
},
importCredential(payload: unknown): Promise<Credential> {
return request('/credentials/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Snippets ──────────────────────────────────────────────────────────────────
export const snippets = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Snippet>> {
return request(`/snippets?page=${page}&limit=${limit}`);
},
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(
id: string,
patch: Partial<Pick<Snippet, 'alias' | 'title' | 'description' | 'code'>>,
): Promise<Snippet> {
return request(`/snippets/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: string): Promise<void> {
return request(`/snippets/${id}`, { method: 'DELETE' });
},
exportSnippet(id: string): Promise<unknown> {
return request(`/snippets/${id}/export`);
},
importSnippet(payload: unknown): Promise<Snippet> {
return request('/snippets/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Environments ──────────────────────────────────────────────────────────────
export const environments = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Environment>> {
return request(`/environments?page=${page}&limit=${limit}`);
},
get(id: number): Promise<Environment> {
get(id: string): Promise<Environment> {
return request(`/environments/${id}`);
},
create(name: string, urls: Environment['urls']): Promise<Environment> {
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
return request('/environments', {
method: 'POST',
body: JSON.stringify({ name, urls }),
body: JSON.stringify({ name, description, data }),
});
},
update(id: number, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
update(
id: string,
patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>,
): Promise<Environment> {
return request(`/environments/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/environments/${id}`, { method: 'DELETE' });
},
};
// ── Keys ──────────────────────────────────────────────────────────────────────
export const keys = {
list(): Promise<KeysResponse> {
return request('/keys');
exportEnvironment(id: string): Promise<unknown> {
return request(`/environments/${id}/export`);
},
importEnvironment(payload: unknown): Promise<Environment> {
return request('/environments/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Sessions ──────────────────────────────────────────────────────────────────
export const sessions = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
return request(`/sessions?page=${page}&limit=${limit}`);
list(
page = 1,
limit = 50,
orderBy = 'id',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<Session>> {
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
},
get(id: number): Promise<Session> {
get(id: string): Promise<Session> {
return request(`/sessions/${id}`);
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/sessions/${id}`, { method: 'DELETE' });
},
};
@@ -79,37 +193,209 @@ export const sessions = {
// ── Scenarios ─────────────────────────────────────────────────────────────────
export const scenarios = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
return request(`/scenarios?page=${page}&limit=${limit}`);
list(
page = 1,
limit = 50,
orderBy = 'updatedAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<Scenario>> {
return request(
`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
);
},
get(id: number): Promise<Scenario & { steps: ScenarioStep[] }> {
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
return request(`/scenarios/${id}`);
},
create(name: string): Promise<Scenario> {
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
return request('/scenarios', {
method: 'POST',
body: JSON.stringify({ name }),
body: JSON.stringify({ name, description, environmentId }),
});
},
update(id: number, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
update(
id: string,
patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>,
): Promise<Scenario> {
return request(`/scenarios/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: number): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, { method: 'POST' });
run(
id: string,
environmentId: string,
saveSession?: boolean,
traceMode?: TraceMode,
): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId, saveSession, traceMode }),
});
},
getRun(scenarioId: number, runId: number): Promise<ScenarioRun> {
runDefaults(): Promise<RunDefaults> {
return request('/scenarios/run-defaults');
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
},
waitForRun(scenarioId: number, runId: number): Promise<ScenarioRun> {
waitForRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}/wait`, { method: 'POST' });
},
listRuns(scenarioId: number, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun>> {
listRuns(
scenarioId: string,
page = 1,
limit = 20,
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
exportScenario(
id: string,
options: { includeEnvironment: boolean; credentialIds: string[] } = {
includeEnvironment: false,
credentialIds: [],
},
): Promise<string> {
const params = new URLSearchParams();
params.set('includeEnvironment', String(options.includeEnvironment));
for (const cid of options.credentialIds) {
params.append('credentialIds', cid);
}
return request(`/scenarios/${id}/export?${params.toString()}`);
},
importScenario(payload: unknown): Promise<Scenario> {
return request('/scenarios/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
exportE2eTestUrl(id: string): string {
return `${BASE_URL}/scenarios/${id}/export-e2e`;
},
usedSnippets(id: string): Promise<Snippet[]> {
return request(`/scenarios/${id}/used-snippets`);
},
};
// ── Runs ─────────────────────────────────────────────────────────────────────
export const runs = {
listAll(
page = 1,
limit = 20,
status?: string,
orderBy = 'createdAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<ScenarioRun & { scenario: { id: string; name: string } }>> {
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
if (status) q.set('status', status);
return request(`/scenarios/runs?${q}`);
},
list(
scenarioId: string,
page = 1,
limit = 20,
orderBy = 'createdAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(
`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
);
},
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
},
exportLogs(scenarioId: string, runId: string, format: 'csv' | 'md'): Promise<string> {
return request(`/scenarios/${scenarioId}/run/${runId}/logs/export?format=${format}`);
},
};
// ── Scenario Credentials ──────────────────────────────────────────────────────
export const scenarioCredentials = {
list(scenarioId: string): Promise<ScenarioCredential[]> {
return request(`/scenarios/${scenarioId}/credentials`);
},
add(scenarioId: string, credentialId: string, alias: string): Promise<ScenarioCredential> {
return request(`/scenarios/${scenarioId}/credentials`, {
method: 'POST',
body: JSON.stringify({ credentialId, alias }),
});
},
remove(scenarioId: string, scCredId: string): Promise<void> {
return request(`/scenarios/${scenarioId}/credentials/${scCredId}`, {
method: 'DELETE',
});
},
};
// ── Scenario Steps ────────────────────────────────────────────────────────────
export interface CreateStepPayload {
title?: string;
execCode?: string;
timeoutSeconds?: number | null;
}
export interface UpdateStepPayload {
title?: string;
order?: number;
execCode?: string;
timeoutSeconds?: number | null;
}
export const steps = {
get(scenarioId: string, stepId: string): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`);
},
create(scenarioId: string, payload: CreateStepPayload): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps`, {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(scenarioId: string, stepId: string, payload: UpdateStepPayload): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`, {
method: 'PATCH',
body: JSON.stringify(payload),
});
},
remove(scenarioId: string, stepId: string): Promise<void> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
},
};
// ── Scenario Files ────────────────────────────────────────────────────────
export const scenarioFiles = {
upload(scenarioId: string, file: File, expiresAt?: Date): Promise<FileMetadata> {
const form = new FormData();
form.append('file', file);
if (expiresAt) form.append('expiresAt', expiresAt.toISOString());
return request(`/scenarios/${scenarioId}/files`, {
method: 'POST',
body: form,
});
},
list(scenarioId: string, limit = 20, offset = 0): Promise<FileListResponse> {
return request(`/scenarios/${scenarioId}/files?limit=${limit}&offset=${offset}`);
},
/** Returns a URL that can be used as an <a href> for direct download. */
contentUrl(scenarioId: string, fileId: string): string {
return `${BASE_URL}/scenarios/${scenarioId}/files/${fileId}/content`;
},
};
// ── Run Files ─────────────────────────────────────────────────────────────
export const runFiles = {
list(scenarioId: string, runId: string, limit = 20, offset = 0): Promise<FileListResponse> {
return request(`/scenarios/${scenarioId}/runs/${runId}/files?limit=${limit}&offset=${offset}`);
},
/** Returns a URL that can be used as an <a href> for direct download. */
contentUrl(scenarioId: string, runId: string, fileId: string): string {
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`;
},
};
+111 -21
View File
@@ -9,25 +9,40 @@ export interface PaginatedResponse<T> {
// ── Environments ──────────────────────────────────────────────────────────────
export interface EnvironmentUrls {
id_url?: string;
cabinet_url?: string;
admin_url?: string;
export interface EnvironmentData {
[key: string]: string | undefined;
}
export interface Environment {
id: number;
id: string;
name: string;
urls: EnvironmentUrls;
description?: string;
data: EnvironmentData;
createdAt: string;
updatedAt: string;
}
// ── Keys ──────────────────────────────────────────────────────────────────────
// ── Credentials ───────────────────────────────────────────────────────────────
export interface KeysResponse {
keys: string[];
export interface Credential {
id: string;
name: string;
data: string | null;
lastUsedAt: string | null;
createdAt: string;
updatedAt: string;
}
// ── Snippets ──────────────────────────────────────────────────────────────────
export interface Snippet {
id: string;
alias: string;
title: string;
description: string | null;
code: string;
createdAt: string;
updatedAt: string;
}
// ── Sessions ──────────────────────────────────────────────────────────────────
@@ -35,7 +50,7 @@ export interface KeysResponse {
export type SessionStatus = 'open' | 'closed';
export interface Session {
id: number;
id: string;
sessionName: string;
token: string;
status: SessionStatus;
@@ -46,34 +61,109 @@ export interface Session {
// ── Scenarios ─────────────────────────────────────────────────────────────────
export type StepType = 'login' | 'exec' | 'sign';
export interface ScenarioStep {
id: number;
scenarioId: number;
id: string;
scenarioId: string;
order: number;
type: StepType;
sessionName: string;
title: string | null;
execCode: string | null;
validateCode: string | null;
timeoutSeconds: number | null;
createdAt: string;
updatedAt: string;
}
export interface ScenarioCredential {
id: string;
scenarioId: string;
credentialId: string;
alias: string;
credential: Credential;
createdAt: string;
}
export interface Scenario {
id: number;
id: string;
name: string;
description?: string;
environmentId?: string | null;
timeoutSeconds?: number | null;
environment?: Pick<Environment, 'id' | 'name'>;
steps?: ScenarioStep[];
scenarioCredentials?: ScenarioCredential[];
lastRunStatus?: ScenarioRunStatus | null;
lastRunAt?: string | null;
createdAt: string;
updatedAt: string;
}
export type ScenarioRunStatus = 'pending' | 'running' | 'pass' | 'fail';
export type ScenarioRunStatus = 'pending' | 'in_progress' | 'pass' | 'fail';
export type TraceMode = 'on' | 'retain-on-failure' | 'off';
export interface RunDefaults {
traceMode: TraceMode;
}
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
export type LogLevel = 'log' | 'warn' | 'error';
export interface ScenarioRun {
id: number;
scenarioId: number;
id: string;
scenarioId: string;
environmentId: string | null;
sessionId?: string | null;
saveSession: boolean;
traceMode: TraceMode | null;
scenario?: Pick<Scenario, 'id' | 'name'>;
environment?: Pick<Environment, 'id' | 'name'>;
session?: { id: string; sessionName: string };
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
createdAt: string;
updatedAt: string;
}
export interface ScenarioRunStep {
id: string;
runId: string;
scenarioStepId: string;
scenarioStep: ScenarioStep;
status: RunStepStatus;
order: number;
description: string | null;
output: string | null;
createdAt: string;
updatedAt: string;
}
export interface ScenarioRunLog {
id: string;
runId: string;
stepRunId: string | null;
level: LogLevel;
message: string;
createdAt: string;
}
export interface ScenarioRunDetail extends ScenarioRun {
stepRuns: ScenarioRunStep[];
logs: ScenarioRunLog[];
}
// ── Files ─────────────────────────────────────────────────────────────────
export interface FileMetadata {
id: string;
name: string;
mimeType: string;
size: number;
sha256: string;
expiresAt: string | null;
createdAt: string;
}
export interface FileListResponse {
items: FileMetadata[];
total: number;
}
@@ -0,0 +1,45 @@
import { useTranslation } from 'react-i18next';
import { X, Trash2 } from 'lucide-react';
import { Modal, Button } from '../../ui';
export interface DeleteConfirmationModalProps {
open: boolean;
title: string;
message: string;
onClose: () => void;
onConfirm: () => void;
isDeleting: boolean;
}
export function DeleteConfirmationModal({
open,
title,
message,
onClose,
onConfirm,
isDeleting,
}: DeleteConfirmationModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={title}
onClose={() => !isDeleting && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isDeleting}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={onConfirm} disabled={isDeleting}>
<Trash2 size={14} />
{t('common.button_delete')}
</Button>
</>
}
>
{message}
</Modal>
);
}
@@ -0,0 +1,27 @@
.section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sectionTitle {
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-muted, #888);
margin: 0;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.radioRow {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
cursor: pointer;
}
.radioRow input[type='radio'] {
cursor: pointer;
accent-color: var(--color-primary);
}
@@ -0,0 +1,68 @@
import { useTranslation } from 'react-i18next';
import { X, Download } from 'lucide-react';
import { Modal, Button } from '../../ui';
import styles from './ExportLogsModal.module.css';
export type LogExportFormat = 'md' | 'csv';
export interface ExportLogsModalProps {
open: boolean;
format: LogExportFormat;
onFormatChange: (format: LogExportFormat) => void;
onClose: () => void;
onExport: () => void;
isExporting: boolean;
}
export function ExportLogsModal({
open,
format,
onFormatChange,
onClose,
onExport,
isExporting,
}: ExportLogsModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={t('runs.export_logs_modal_title')}
onClose={() => !isExporting && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={onExport} disabled={isExporting}>
<Download size={14} />
{t('runs.action_export')}
</Button>
</>
}
>
<div className={styles.section}>
<h4 className={styles.sectionTitle}>{t('runs.export_logs_format')}</h4>
<label className={styles.radioRow}>
<input
type="radio"
name="log-export-format"
checked={format === 'md'}
onChange={() => onFormatChange('md')}
/>
<span>{t('runs.export_logs_format_md')}</span>
</label>
<label className={styles.radioRow}>
<input
type="radio"
name="log-export-format"
checked={format === 'csv'}
onChange={() => onFormatChange('csv')}
/>
<span>{t('runs.export_logs_format_csv')}</span>
</label>
</div>
</Modal>
);
}
@@ -0,0 +1,63 @@
.exportModal {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.scenarioMeta {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: var(--color-primary);
border-radius: 6px;
}
.metaRow {
display: flex;
align-items: center;
gap: 0.75rem;
}
.metaLabel {
font-size: 0.75rem;
font-weight: 600;
color: var(--color-primary-fg);
opacity: 0.7;
min-width: 4rem;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.metaValue {
font-size: 0.875rem;
color: var(--color-primary-fg);
}
.section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sectionTitle {
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-muted, #888);
margin: 0;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.checkboxRow {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
cursor: pointer;
}
.checkboxRow input[type='checkbox'] {
cursor: pointer;
accent-color: var(--color-primary);
}
@@ -0,0 +1,102 @@
import { useTranslation } from 'react-i18next';
import { X, Upload } from 'lucide-react';
import { Modal, Button, UuidBadge } from '../../ui';
import type { Scenario, ScenarioCredential } from '../../api';
import styles from './ExportScenarioModal.module.css';
export interface ExportScenarioModalProps {
open: boolean;
scenario: Scenario | null;
scenarioCredentials: ScenarioCredential[];
environment: Pick<{ id: string; name: string }, 'id' | 'name'> | null;
includeEnvironment: boolean;
onIncludeEnvironmentChange: (v: boolean) => void;
includedCredentialIds: Set<string>;
onCredentialToggle: (id: string, checked: boolean) => void;
onClose: () => void;
onExport: () => void;
isExporting: boolean;
}
export function ExportScenarioModal({
open,
scenario,
scenarioCredentials,
environment,
includeEnvironment,
onIncludeEnvironmentChange,
includedCredentialIds,
onCredentialToggle,
onClose,
onExport,
isExporting,
}: ExportScenarioModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={t('scenarios.export_modal_title')}
onClose={() => !isExporting && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={onExport} disabled={isExporting}>
<Upload size={14} />
{t('scenarios.action_export')}
</Button>
</>
}
>
{scenario && (
<div className={styles.exportModal}>
<div className={styles.scenarioMeta}>
<div className={styles.metaRow}>
<span className={styles.metaLabel}>{t('scenarios.field_name')}</span>
<span className={styles.metaValue}>{scenario.name}</span>
</div>
<div className={styles.metaRow}>
<span className={styles.metaLabel}>{t('scenarios.field_id')}</span>
<span className={styles.metaValue}>
<UuidBadge id={scenario.id} />
</span>
</div>
</div>
{environment && (
<div className={styles.section}>
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_environment')}</h4>
<label className={styles.checkboxRow}>
<input
type="checkbox"
checked={includeEnvironment}
onChange={(e) => onIncludeEnvironmentChange(e.target.checked)}
/>
<span>{environment.name}</span>
</label>
</div>
)}
{scenarioCredentials.length > 0 && (
<div className={styles.section}>
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_credentials')}</h4>
{scenarioCredentials.map((sc) => (
<label key={sc.credentialId} className={styles.checkboxRow}>
<input
type="checkbox"
checked={includedCredentialIds.has(sc.credentialId)}
onChange={(e) => onCredentialToggle(sc.credentialId, e.target.checked)}
/>
<span>{sc.credential?.name ?? sc.alias}</span>
</label>
))}
</div>
)}
</div>
)}
</Modal>
);
}
@@ -0,0 +1,101 @@
import { useTranslation } from 'react-i18next';
import { X, Play } from 'lucide-react';
import { Modal, Button, Select } from '../../ui';
import type { Environment, TraceMode } from '../../api';
const TRACE_MODES: TraceMode[] = ['on', 'retain-on-failure', 'off'];
export interface RunScenarioModalProps {
open: boolean;
environments: Environment[];
selectedEnvId: string;
onEnvSelect: (envId: string) => void;
saveSessionFlag: boolean;
onSaveSessionChange: (flag: boolean) => void;
traceMode: TraceMode;
defaultTraceMode: TraceMode | null;
onTraceModeChange: (mode: TraceMode) => void;
onClose: () => void;
onRun: () => void;
isRunning: boolean;
actionLabel?: string;
}
export function RunScenarioModal({
open,
environments,
selectedEnvId,
onEnvSelect,
saveSessionFlag,
onSaveSessionChange,
traceMode,
defaultTraceMode,
onTraceModeChange,
onClose,
onRun,
isRunning,
actionLabel,
}: RunScenarioModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={t('scenarios.run_modal_title')}
onClose={() => !isRunning && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isRunning}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={onRun} disabled={isRunning || !selectedEnvId}>
<Play size={14} />
{actionLabel || t('scenarios.action_run')}
</Button>
</>
}
>
{environments.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => onEnvSelect(e.target.value)}
options={environments.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{
display: 'flex',
alignItems: 'center',
marginTop: '1rem',
gap: '0.5rem',
}}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => onSaveSessionChange(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
<div style={{ marginTop: '1rem' }}>
<Select
label={t('scenarios.run_modal_trace_label')}
value={traceMode}
onChange={(e) => onTraceModeChange(e.target.value as TraceMode)}
options={TRACE_MODES.map((mode) => ({
value: mode,
label:
t(`scenarios.trace_mode_${mode.replace(/-/g, '_')}`) +
(mode === defaultTraceMode ? ` ${t('scenarios.trace_mode_default_suffix')}` : ''),
}))}
/>
</div>
</>
)}
</Modal>
);
}
+8
View File
@@ -0,0 +1,8 @@
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
export { ExportScenarioModal } from './ExportScenarioModal';
export type { ExportScenarioModalProps } from './ExportScenarioModal';
export { RunScenarioModal } from './RunScenarioModal';
export type { RunScenarioModalProps } from './RunScenarioModal';
export { ExportLogsModal } from './ExportLogsModal';
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
+2
View File
@@ -6,3 +6,5 @@ declare module '*.css' {
interface ImportMetaEnv {
readonly VITE_API_URL?: string;
}
declare const __APP_VERSION__: string;
+17
View File
@@ -0,0 +1,17 @@
import { useEffect } from 'react';
const APP_NAME = 'Liqa';
/**
* Sets document.title to "<title> | Liqa" for the current page.
* Pass undefined or empty string to fall back to just "Liqa".
*/
export function usePageTitle(title: string | null | undefined): void {
useEffect(() => {
const prev = document.title;
document.title = title ? `${title} | ${APP_NAME}` : APP_NAME;
return () => {
document.title = prev;
};
}, [title]);
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
import { scenarios } from '../api';
import type { RunDefaults } from '../api';
// Server run defaults don't change while the app is open; fetch them once
let cached: Promise<RunDefaults> | null = null;
/**
* Returns the server-configured defaults for new scenario runs, or null
* while they are loading (or if the request failed).
*/
export function useRunDefaults(): RunDefaults | null {
const [defaults, setDefaults] = useState<RunDefaults | null>(null);
useEffect(() => {
let cancelled = false;
cached ??= scenarios.runDefaults().catch((err: unknown) => {
cached = null;
throw err;
});
cached.then((d) => !cancelled && setDefaults(d)).catch(() => undefined);
return () => {
cancelled = true;
};
}, []);
return defaults;
}
+241 -10
View File
@@ -1,50 +1,104 @@
{
"common": {
"button_cancel": "Cancel",
"button_confirm": "Confirm",
"button_delete": "Delete",
"confirm_delete_credential": "Are you sure you want to delete this credential?",
"confirm_delete_environment": "Are you sure you want to delete this environment?",
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
"confirm_delete_step": "Are you sure you want to delete this step?",
"confirm_delete_session": "Are you sure you want to delete this session?",
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
"save_session": "Save session"
},
"errors": {
"not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.",
"not_found_environment": "Environment {{id}} does not exist or has been deleted.",
"not_found_credential": "Credential {{id}} does not exist or has been deleted.",
"not_found_scenario": "Scenario {{id}} does not exist or has been deleted.",
"not_found_snippet": "Snippet {{id}} does not exist or has been deleted.",
"generic": "Something went wrong. Please try again."
},
"nav": {
"environments": "Environments",
"credentials": "Credentials",
"snippets": "Snippets",
"keys": "Keys",
"sessions": "Sessions",
"scenarios": "Scenarios"
"scenarios": "Scenarios",
"runs": "Runs"
},
"environments": {
"title": "Environments",
"created": "Environment created",
"updated": "Environment updated",
"col_id": "ID",
"col_name": "Name",
"col_urls": "URLs",
"col_description": "Description",
"col_data": "Data",
"col_updated": "Updated",
"empty": "No environments yet.",
"loading": "Loading…",
"no_urls": "No URLs configured.",
"no_data": "No data configured.",
"menu_label": "Environment options",
"action_view": "View details",
"action_delete": "Delete",
"action_add": "Add environment",
"action_edit": "Edit",
"action_export": "Export",
"action_import": "Import",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Environment",
"edit_title": "Edit Environment",
"form_name": "Name",
"form_name_placeholder": "e.g. staging, production",
"form_name_required": "Name is required",
"form_id_url": "ID URL",
"form_cabinet_url": "Cabinet URL",
"form_admin_url": "Admin URL",
"form_description": "Description",
"form_description_placeholder": "Describe this environment",
"form_data": "Data (JSON)",
"form_data_invalid_json": "Must be a valid JSON object",
"back": "Environments",
"field_id": "ID",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
"section_urls": "URLs"
"section_data": "Data"
},
"credentials": {
"title": "Credentials",
"created": "Credential created",
"updated": "Credential updated",
"empty": "No credentials yet.",
"loading": "Loading…",
"menu_label": "Credential options",
"action_edit": "Edit",
"action_delete": "Delete",
"action_add": "Add credential",
"action_save": "Create",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Credential",
"edit_title": "Edit Credential",
"form_name": "Name",
"form_name_placeholder": "e.g. staging-api-key",
"form_name_required": "Name is required",
"form_data": "Data (JSON)",
"form_data_placeholder": "{\"token\": \"…\"}",
"form_data_invalid_json": "Must be valid JSON",
"field_id": "ID",
"field_last_used": "Last Used",
"field_created": "Created",
"field_updated": "Updated",
"section_data": "Data",
"action_export": "Export",
"action_import": "Import",
"import_error": "Failed to import credential"
},
"keys": {
"title": "Keys",
"col_name": "Key name",
"empty": "No key files found."
},
@@ -67,8 +121,13 @@
},
"scenarios": {
"title": "Scenarios",
"created": "Scenario created",
"updated": "Scenario updated",
"run_started": "Scenario run started",
"col_id": "ID",
"col_name": "Name",
"col_description": "Description",
"col_last_run": "Last Run",
"col_updated": "Updated",
"empty": "No scenarios yet.",
"loading": "Loading…",
@@ -76,14 +135,69 @@
"action_delete": "Delete",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_steps": "Steps",
"field_created": "Created",
"field_updated": "Updated",
"steps_heading": "Steps",
"step_order": "#",
"step_title": "Title",
"step_type": "Type",
"step_session": "Session",
"step_updated": "Updated"
"step_updated": "Updated",
"action_add": "New scenario",
"action_edit": "Edit",
"action_runs": "Runs",
"action_export": "Export",
"action_export_e2e": "Export e2e test",
"action_import": "Import",
"import_error": "Failed to import scenario",
"action_save": "Create",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Scenario",
"edit_title": "Edit Scenario",
"form_description": "Description",
"form_description_placeholder": "Describe this scenario",
"form_environment": "Default Environment",
"form_environment_none": "None (no default environment)",
"field_environment": "Default Environment",
"form_name": "Name",
"form_name_placeholder": "e.g. Login flow",
"form_name_required": "Name is required",
"credentials_heading": "Credentials",
"used_snippets_heading": "Used Snippets",
"cred_empty": "No credentials assigned.",
"cred_col_alias": "Alias",
"cred_col_name": "Credential",
"cred_col_added": "Added",
"cred_action_add": "Add credential",
"cred_action_remove": "Remove",
"cred_action_save": "Add",
"cred_action_cancel": "Cancel",
"cred_form_cred": "Credential",
"cred_form_cred_placeholder": "Select credential…",
"cred_form_cred_required": "Select a credential",
"cred_form_alias": "Alias",
"cred_form_alias_placeholder": "e.g. api_key",
"cred_form_alias_required": "Alias is required",
"run_modal_title": "Select environment",
"run_modal_env_label": "Environment",
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
"run_modal_env_required": "Please select an environment",
"run_modal_trace_label": "Playwright trace",
"trace_mode_on": "Always keep",
"trace_mode_retain_on_failure": "Keep on failure",
"trace_mode_off": "Off",
"trace_mode_default_suffix": "(default)",
"export_modal_title": "Export Scenario",
"export_include_environment": "Include Environment",
"export_include_credentials": "Include Credentials",
"form_timeout": "Scenario Timeout (seconds)",
"form_timeout_placeholder": "Default: 600",
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
"field_name": "Name",
"field_id": "ID"
},
"theme": {
"switch_to_light": "Switch to light theme",
@@ -97,5 +211,122 @@
"range": "{{from}}–{{to}} of {{total}}",
"per_page": "{{count}} per page",
"page_size": "Items per page"
},
"steps": {
"created": "Step created",
"updated": "Step updated",
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
"action_add": "Add step",
"action_edit": "Edit",
"action_delete": "Delete",
"action_save": "Add step",
"action_update": "Save",
"action_cancel": "Cancel",
"form_order": "Order",
"form_order_invalid": "Order must be a non-negative integer",
"form_title": "Title",
"form_title_placeholder": "e.g. Check login page",
"form_type": "Type",
"form_session": "Session name",
"form_session_placeholder": "e.g. my-session",
"form_session_required": "Session name is required",
"form_exec_code": "Exec code",
"form_exec_code_placeholder": "return await page.title();",
"form_timeout": "Step Timeout (seconds)",
"form_timeout_placeholder": "Default: 60",
"form_timeout_hint": "Max seconds for this step (default: 60)"
},
"runs": {
"title": "Runs",
"loading": "Loading…",
"empty": "No runs yet.",
"action_run": "Run scenario",
"col_id": "ID",
"col_scenario": "Scenario",
"col_status": "Status",
"col_steps": "Steps",
"col_created": "Started",
"field_id": "ID",
"field_status": "Status",
"field_steps": "Steps",
"field_created": "Started",
"field_updated": "Updated",
"field_trace": "Playwright trace",
"steps_heading": "Step runs",
"step_title": "Title",
"logs_heading": "Logs",
"logs_search_placeholder": "Filter logs…",
"step_order": "#",
"step_type": "Type",
"step_session": "Session",
"step_status": "Status",
"step_description": "Result",
"log_level": "Level",
"log_message": "Message",
"log_time": "Time",
"action_download_logs": "Download logs",
"action_repeat": "Repeat run",
"repeat_no_environment": "The environment used by this run no longer exists",
"export_logs_modal_title": "Export logs",
"export_logs_format": "Format",
"export_logs_format_md": "Markdown (.md)",
"export_logs_format_csv": "CSV (.csv)",
"action_export": "Export"
},
"snippets": {
"title": "Snippets",
"created": "Snippet created",
"updated": "Snippet updated",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
"action_edit": "Edit",
"action_delete": "Delete",
"action_add": "Add snippet",
"action_save": "Create",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Snippet",
"edit_title": "Edit Snippet",
"form_alias": "Alias",
"form_alias_placeholder": "e.g. clickLoginButton",
"form_alias_required": "Alias is required",
"form_title": "Title",
"form_title_placeholder": "e.g. Click Login Button",
"form_title_required": "Title is required",
"form_description": "Description",
"form_description_placeholder": "What does this snippet do?",
"form_code": "Code",
"form_code_placeholder": "await page.click('#login-btn');",
"form_code_required": "Code is required",
"field_id": "ID",
"field_alias": "Alias",
"field_title": "Title",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
"section_code": "Code",
"action_export": "Export",
"action_import": "Import",
"import_error": "Failed to import snippet"
},
"files": {
"title": "Files",
"upload": "Upload",
"uploadTitle": "Upload File",
"uploadSuccess": "File uploaded successfully",
"name": "Name",
"mimeType": "MIME Type",
"size": "Size",
"expiresAt": "Expires At",
"expiresAtLabel": "Expires At (optional)",
"createdAt": "Created",
"download": "Download",
"expiredTooltip": "File is expired",
"empty": "No files uploaded.",
"totalCount": "Total: {{count}} file(s)",
"artifactsTitle": "Artifacts"
}
}
+8
View File
@@ -0,0 +1,8 @@
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('json', json);
export default hljs;
+30
View File
@@ -0,0 +1,30 @@
export const API_ERROR_TOAST_EVENT = 'liqa:api-error-toast';
export interface ApiErrorToastDetail {
message: string;
}
export function emitApiErrorToast(message: string): void {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
detail: { message },
}),
);
}
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
if (typeof window === 'undefined') return () => {};
const listener = (event: Event) => {
const custom = event as CustomEvent<ApiErrorToastDetail>;
const message = custom.detail?.message;
if (message) handler(message);
};
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
return () => {
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
};
}
+12 -4
View File
@@ -1,14 +1,22 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './i18n';
import './ui/tokens.css';
import App from './App';
import { ToastProvider } from './ui';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')!).render(
<StrictMode>
<HashRouter>
<App />
</HashRouter>
<QueryClientProvider client={queryClient}>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</QueryClientProvider>
</StrictMode>,
);
-105
View File
@@ -1,105 +0,0 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { environments } from '../api';
import { Breadcrumbs, Button, Card, Input } from '../ui';
import styles from './Page.module.css';
export function CreateEnvironmentPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [name, setName] = useState('');
const [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
const [nameError, setNameError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const env = await environments.create(name.trim(), {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
});
navigate(`/environments/${env.id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{ label: t('environments.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
placeholder={t('environments.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('environments.form_id_url')}
type="url"
placeholder="https://…"
value={idUrl}
onChange={(e) => setIdUrl(e.target.value)}
/>
<Input
label={t('environments.form_cabinet_url')}
type="url"
placeholder="https://…"
value={cabinetUrl}
onChange={(e) => setCabinetUrl(e.target.value)}
/>
<Input
label={t('environments.form_admin_url')}
type="url"
placeholder="https://…"
value={adminUrl}
onChange={(e) => setAdminUrl(e.target.value)}
/>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/environments')}>
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('environments.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
-138
View File
@@ -1,138 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, Input } from '../ui';
import styles from './Page.module.css';
export function EditEnvironmentPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [name, setName] = useState('');
const [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
const [nameError, setNameError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
environments
.get(Number(id))
.then((data) => {
setEnv(data);
setName(data.name);
setIdUrl(data.urls.id_url ?? '');
setCabinetUrl(data.urls.cabinet_url ?? '');
setAdminUrl(data.urls.admin_url ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await environments.update(Number(id), {
name: name.trim(),
urls: {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
},
});
navigate(`/environments/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
},
{ label: t('environments.edit_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{!loading && env && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
placeholder={t('environments.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('environments.form_id_url')}
type="url"
placeholder="https://…"
value={idUrl}
onChange={(e) => setIdUrl(e.target.value)}
/>
<Input
label={t('environments.form_cabinet_url')}
type="url"
placeholder="https://…"
value={cabinetUrl}
onChange={(e) => setCabinetUrl(e.target.value)}
/>
<Input
label={t('environments.form_admin_url')}
type="url"
placeholder="https://…"
value={adminUrl}
onChange={(e) => setAdminUrl(e.target.value)}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/environments/${id}`)}
>
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('environments.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
-114
View File
@@ -1,114 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Pencil, Trash2 } from 'lucide-react';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../ui';
import styles from './Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
environments
.get(Number(id))
.then(setEnv)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!env) return;
await environments.remove(env.id);
navigate('/environments');
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{ label: env?.name ?? `#${id}` },
]}
/>
{env && (
<div className={styles.toolbarActions}>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/environments/${env.id}/edit`)}
>
<Pencil size={14} />
{t('environments.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('environments.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_environment', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{env && (
<>
<div className={styles.detailMeta}>
<DescriptionList
layout="comfortable"
items={[
{ term: t('environments.field_id'), detail: env.id },
{
term: t('environments.field_created'),
detail: <Timestamp value={env.createdAt} />,
},
{
term: t('environments.field_updated'),
detail: <Timestamp value={env.updatedAt} />,
},
]}
/>
</div>
<h2 className={styles.sectionHeading}>{t('environments.section_urls')}</h2>
<Card>
{Object.entries(env.urls).filter(([, v]) => v).length === 0 ? (
<p className={styles.muted}>{t('environments.no_urls')}</p>
) : (
<DescriptionList
layout="comfortable"
items={Object.entries(env.urls)
.filter(([, v]) => v)
.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
{value}
</a>
),
}))}
/>
)}
</Card>
</>
)}
</div>
);
}
-130
View File
@@ -1,130 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, ExternalLink, Pencil, Trash2, Plus } from 'lucide-react';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp } from '../ui';
import styles from './Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: number) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const urlEntries = Object.entries(env.urls).filter(([, v]) => v);
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{env.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('environments.menu_label')}>
<Settings size={14} />
</Button>
}
items={[
{
label: t('environments.action_view'),
icon: <ExternalLink size={14} />,
onClick: () => navigate(`/environments/${env.id}`),
},
{
label: t('environments.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/environments/${env.id}/edit`),
},
{
label: t('environments.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(env.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<span className={styles.envCardId}>#{env.id}</span>
<Timestamp value={env.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/environments/${env.id}`)}
>
{urlEntries.length > 0 && (
<DescriptionList
layout="compact"
truncate
items={urlEntries.map(([key, value]) => ({ term: key, detail: value }))}
/>
)}
{urlEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_urls')}</p>
)}
</Card>
);
}
function AddEnvironmentCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/environments/new')}>
<Plus size={16} />
{t('environments.action_add')}
</Button>
</div>
);
}
export function EnvironmentsPage() {
const { t } = useTranslation();
const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = () => {
environments
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const handleDelete = async (id: number) => {
await environments.remove(id);
setItems((prev) => prev.filter((e) => e.id !== id));
};
return (
<div>
<Breadcrumbs items={[{ label: t('environments.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
{loading ? (
<p className={styles.muted}>{t('environments.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((env) => (
<EnvironmentCard key={env.id} env={env} onDelete={handleDelete} />
))}
<AddEnvironmentCard />
</div>
)}
</div>
);
}
-44
View File
@@ -1,44 +0,0 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { keys } from '../api';
import { Breadcrumbs, Table, type TableColumn } from '../ui';
import styles from './Page.module.css';
interface KeyRow {
name: string;
}
export function KeysPage() {
const { t } = useTranslation();
const [items, setItems] = useState<KeyRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const columns: TableColumn<KeyRow>[] = [
{ key: 'name', header: t('keys.col_name'), render: (k) => k.name },
];
useEffect(() => {
keys
.list()
.then((res) => setItems(res.keys.map((name) => ({ name }))))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
return (
<div>
<Breadcrumbs items={[{ label: t('keys.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(k) => k.name}
loading={loading}
emptyMessage={t('keys.empty')}
pageSize={10}
pageSizeOptions={[10, 25, 50]}
/>
</div>
);
}
+116 -3
View File
@@ -6,14 +6,22 @@
}
.sectionHeading {
margin: var(--space-6) 0 var(--space-3);
margin: 0 0 var(--space-3);
line-height: 1;
font-size: var(--font-size-md);
font-weight: 600;
color: var(--color-text);
}
.stepsSection {
margin-top: var(--space-2);
margin-top: var(--space-6);
}
.sectionHeadingRow {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-3);
}
.breadcrumbs {
@@ -91,7 +99,8 @@
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
flex: 1;
min-width: 0;
}
.envCardId {
@@ -119,6 +128,53 @@
margin-right: calc(-1 * var(--space-1));
}
.pageTitle {
margin: 0;
font-size: var(--font-size-lg);
font-weight: 700;
color: var(--color-text);
}
.linkCell {
color: var(--color-link);
cursor: pointer;
text-decoration: underline;
text-underline-offset: 2px;
}
.linkCell:hover {
color: var(--color-link-hover);
}
.dragHandle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: var(--radius-sm);
cursor: grab;
color: var(--color-text-muted);
}
.dragHandle:hover {
background: color-mix(in srgb, var(--color-secondary) 18%, transparent);
color: var(--color-text);
}
.dragHandle:active {
cursor: grabbing;
}
.dragHandleDisabled {
opacity: 0.45;
cursor: not-allowed;
}
.dragOverRow {
background: color-mix(in srgb, var(--color-primary) 16%, transparent) !important;
}
.envCardHeader button:hover {
background: color-mix(in srgb, currentColor 15%, transparent) !important;
}
@@ -170,6 +226,10 @@
max-width: 540px;
}
.formCardFull {
max-width: none;
}
.formFields {
display: flex;
flex-direction: column;
@@ -183,6 +243,47 @@
justify-content: flex-end;
}
.formField {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.fieldLabel {
font-size: var(--font-size-sm);
font-weight: 500;
color: var(--color-text);
}
.textarea {
width: 100%;
padding: var(--space-2) var(--space-3);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
background: var(--color-bg-input, var(--color-bg-raised));
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
resize: vertical;
transition: border-color var(--transition), box-shadow var(--transition);
box-sizing: border-box;
}
.textarea:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent);
}
/* ── Section toolbar ─────────────────────────────────────────────────────── */
.sectionToolbar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-3);
}
/* ── Environment detail page ────────────────────────────────────────────── */
.detailToolbar {
@@ -252,3 +353,15 @@
.envDetailUrlVal a:hover {
text-decoration: underline;
}
/* ── Code block ────────────────────────────────────────────────────────── */
.codeBlock {
margin: 0;
font-family: var(--font-mono, ui-monospace, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
white-space: pre-wrap;
word-break: break-all;
overflow-x: auto;
}
-141
View File
@@ -1,141 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Trash2 } from 'lucide-react';
import { scenarios } from '../api';
import type { Scenario, ScenarioStep } from '../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Notification,
Table,
Timestamp,
type TableColumn,
} from '../ui';
import styles from './Page.module.css';
const STEP_TYPE_VARIANT: Record<string, 'info' | 'warning' | 'success'> = {
login: 'success',
exec: 'info',
sign: 'warning',
};
export function ScenarioDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
scenarios
.get(Number(id))
.then(setScenario)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleRun = async () => {
if (!scenario) return;
await scenarios.run(scenario.id);
};
const handleDelete = async () => {
if (!scenario) return;
await scenarios.remove(scenario.id);
navigate('/scenarios');
};
const stepColumns: TableColumn<ScenarioStep>[] = [
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'type',
header: t('scenarios.step_type'),
width: 90,
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
},
{ key: 'session', header: t('scenarios.step_session'), render: (s) => s.sessionName },
{
key: 'updated',
header: t('scenarios.step_updated'),
width: 140,
render: (s) => <Timestamp value={s.updatedAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button size="sm" onClick={handleRun}>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_scenario', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{scenario && (
<>
<Card>
<DescriptionList
layout="comfortable"
items={[
{ term: t('scenarios.field_id'), detail: scenario.id },
{ term: t('scenarios.field_name'), detail: scenario.name },
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
},
{
term: t('scenarios.field_updated'),
detail: <Timestamp value={scenario.updatedAt} />,
},
]}
/>
</Card>
{scenario.steps.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Table
columns={stepColumns}
data={scenario.steps}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
/>
</div>
)}
</>
)}
</div>
);
}
-87
View File
@@ -1,87 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Trash2 } from 'lucide-react';
import { scenarios } from '../api';
import type { Scenario } from '../api';
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp } from '../ui';
import styles from './Page.module.css';
export function ScenariosPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<Scenario[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
scenarios
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load();
}, [load]);
const handleRun = async (id: number) => {
await scenarios.run(id);
};
const handleDelete = async (id: number) => {
await scenarios.remove(id);
setLoading(true);
load();
};
const columns: TableColumn<Scenario>[] = [
{ key: 'id', header: t('scenarios.col_id'), render: (s) => s.id, width: 60 },
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name },
{
key: 'updated',
header: t('scenarios.col_updated'),
width: 140,
render: (s) => <Timestamp value={s.updatedAt} />,
},
{
key: 'actions',
header: '',
width: 100,
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button size="sm" title={t('scenarios.action_run')} onClick={() => handleRun(s.id)}>
<Play size={14} />
</Button>
<Button
variant="danger"
size="sm"
title={t('scenarios.action_delete')}
onClick={() => handleDelete(s.id)}
>
<Trash2 size={14} />
</Button>
</span>
),
},
];
return (
<div>
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('scenarios.empty')}
pageSize={10}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
/>
</div>
);
}
-84
View File
@@ -1,84 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { sessions } from '../api';
import type { Session } from '../api';
import { Badge, Breadcrumbs, Button, Table, type TableColumn, Timestamp } from '../ui';
import styles from './Page.module.css';
export function SessionsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
sessions
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load();
}, [load]);
const handleDelete = async (id: number) => {
await sessions.remove(id);
setLoading(true);
load();
};
const columns: TableColumn<Session>[] = [
{ key: 'id', header: t('sessions.col_id'), render: (s) => s.id, width: 60 },
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
{
key: 'status',
header: t('sessions.col_status'),
width: 100,
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
},
{
key: 'lastUsed',
header: t('sessions.col_lastUsed'),
width: 160,
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
},
{
key: 'actions',
header: '',
width: 48,
align: 'right',
render: (s) => (
<Button
variant="danger"
size="sm"
title={t('sessions.action_delete')}
onClick={() => handleDelete(s.id)}
>
<Trash2 size={14} />
</Button>
),
},
];
return (
<div>
<Breadcrumbs items={[{ label: t('sessions.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('sessions.empty')}
pageSize={10}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
</div>
);
}
@@ -0,0 +1,114 @@
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateCredentialPage() {
const { t } = useTranslation();
usePageTitle(t('credentials.create_title'));
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [data, setData] = useState('');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('credentials.form_name_required'));
valid = false;
}
if (data.trim()) {
try {
JSON.parse(data.trim());
} catch {
setDataError(t('credentials.form_data_invalid_json'));
valid = false;
}
}
if (!valid) return;
setSaving(true);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success(t('credentials.created'));
navigate(`/credentials/${credential.id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: t('credentials.create_title') },
]}
/>
</div>
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
placeholder={t('credentials.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('credentials.form_data')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
language="json"
value={data}
onChange={(v) => {
setData(v);
setDataError('');
}}
rows={6}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/credentials')}>
<X size={14} />
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('credentials.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,146 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
usePageTitle(credential?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
credentials
.get(id)
.then(setCredential)
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!credential) return;
setDeleting(true);
try {
await credentials.remove(credential.id);
navigate('/credentials');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
if (!credential) return;
const data = await credentials.exportCredential(credential.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `credential-${credential.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: credential?.name ?? `#${id}` },
]}
/>
{credential && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Upload size={14} />
{t('credentials.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/credentials/${credential.id}/edit`)}
>
<Pencil size={14} />
{t('credentials.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('credentials.action_delete')}
</Button>
</div>
)}
</div>
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{credential && (
<>
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('credentials.field_id'), detail: <UuidBadge id={credential.id} /> },
{
term: t('credentials.field_last_used'),
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
},
{
term: t('credentials.field_created'),
detail: <Timestamp value={credential.createdAt} />,
},
{
term: t('credentials.field_updated'),
detail: <Timestamp value={credential.updatedAt} />,
},
]}
/>
</Card>
{credential.data && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
<Card>
<CodeBlock
language="json"
code={(() => {
try {
return JSON.stringify(JSON.parse(credential.data), null, 2);
} catch {
return credential.data;
}
})()}
/>
</Card>
</div>
)}
</>
)}
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
message={t('common.confirm_delete_credential')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -0,0 +1,192 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
DescriptionList,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function CredentialCard({
credential,
onDelete,
}: {
credential: Credential;
onDelete: (id: string) => void;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{credential.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('credentials.menu_label')}>
<Settings size={14} />
</Button>
}
items={[
{
label: t('credentials.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/credentials/${credential.id}/edit`),
},
{
label: t('credentials.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(credential.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<UuidBadge id={credential.id} />
<Timestamp value={credential.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/credentials/${credential.id}`)}
>
<DescriptionList
layout="compact"
truncate
items={[
{
term: t('credentials.field_last_used'),
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
},
]}
/>
</Card>
);
}
function AddCredentialCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/credentials/new')}>
<Plus size={16} />
{t('credentials.action_add')}
</Button>
</div>
);
}
export function CredentialsPage() {
const { t } = useTranslation();
usePageTitle(t('credentials.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
credentials
.list()
.then((res) => setItems(res.data))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await credentials.remove(deleteId);
setItems((prev) => prev.filter((c) => c.id !== deleteId));
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await credentials.importCredential(payload);
navigate(`/credentials/${imported.id}`);
} catch {
// Import errors are silently ignored
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('credentials.title'), icon: <KeyRound size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Download size={14} />
{t('credentials.action_import')}
</Button>
</div>
</div>
{loading ? (
<p className={styles.muted}>{t('credentials.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((credential) => (
<CredentialCard key={credential.id} credential={credential} onDelete={requestDelete} />
))}
<AddCredentialCard />
</div>
)}
<DeleteConfirmationModal
open={deleteId != null}
title={t('credentials.action_delete')}
message={t('common.confirm_delete_credential')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -0,0 +1,149 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditCredentialPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [credential, setCredential] = useState<Credential | null>(null);
const [name, setName] = useState('');
usePageTitle(
credential
? `${t('credentials.edit_title')} — ${credential.name}`
: t('credentials.edit_title'),
);
const [data, setData] = useState('');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
credentials
.get(id)
.then((c) => {
setCredential(c);
setName(c.name);
setData(c.data ?? '');
})
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('credentials.form_name_required'));
valid = false;
}
if (data.trim()) {
try {
JSON.parse(data.trim());
} catch {
setDataError(t('credentials.form_data_invalid_json'));
valid = false;
}
}
if (!valid) return;
setSaving(true);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
toast.success(t('credentials.updated'));
navigate(`/credentials/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
},
{ label: t('credentials.edit_title') },
]}
/>
</div>
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{!loading && credential && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
placeholder={t('credentials.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('credentials.form_data')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
language="json"
value={data}
onChange={(v) => {
setData(v);
setDataError('');
}}
rows={6}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/credentials/${id}`)}
>
<X size={14} />
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('credentials.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,132 @@
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateEnvironmentPage() {
const { t } = useTranslation();
usePageTitle(t('environments.create_title'));
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
return;
}
let parsedData: Record<string, string | undefined>;
try {
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
throw new Error('invalid');
}
parsedData = Object.fromEntries(
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
k,
v == null ? undefined : String(v),
]),
);
setDataError('');
} catch {
setDataError(t('environments.form_data_invalid_json'));
return;
}
setSaving(true);
try {
const env = await environments.create(
name.trim(),
parsedData,
description.trim() || undefined,
);
toast.success(t('environments.created'));
navigate(`/environments/${env.id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: t('environments.create_title') },
]}
/>
</div>
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
placeholder={t('environments.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={6}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
language="json"
value={dataJson}
onChange={(v) => {
setDataJson(v);
setDataError('');
}}
rows={8}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/environments')}>
<X size={14} />
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('environments.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,163 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditEnvironmentPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [env, setEnv] = useState<Environment | null>(null);
const [name, setName] = useState('');
usePageTitle(
env ? `${t('environments.edit_title')} — ${env.name}` : t('environments.edit_title'),
);
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
environments
.get(id)
.then((data) => {
setEnv(data);
setName(data.name);
setDescription(data.description || '');
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
return;
}
let parsedData: Record<string, string | undefined>;
try {
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
throw new Error('invalid');
}
parsedData = Object.fromEntries(
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
k,
v == null ? undefined : String(v),
]),
);
setDataError('');
} catch {
setDataError(t('environments.form_data_invalid_json'));
return;
}
setSaving(true);
try {
await environments.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
data: parsedData,
});
toast.success(t('environments.updated'));
navigate(`/environments/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
},
{ label: t('environments.edit_title') },
]}
/>
</div>
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{!loading && env && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
placeholder={t('environments.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={6}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
language="json"
value={dataJson}
onChange={(v) => {
setDataJson(v);
setDataError('');
}}
rows={8}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/environments/${id}`)}
>
<X size={14} />
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('environments.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,167 @@
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { useNavigate, useParams } from 'react-router-dom';
import { stringify as yamlStringify } from 'yaml';
import type { Environment } from '../../api';
import { environments } from '../../api';
import { DeleteConfirmationModal } from '../../components/modals';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const toast = useToast();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
usePageTitle(env?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
useEffect(() => {
if (!id) return;
environments
.get(id)
.then(setEnv)
.catch((err: Error) => toast.error((err as Error).message))
.finally(() => setLoading(false));
}, [id, toast]);
const handleDelete = async () => {
if (!env) return;
setDeleting(true);
try {
await environments.remove(env.id);
navigate('/environments');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
if (!env) return;
const data = await environments.exportEnvironment(env.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `environment-${env.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: env?.name ?? `#${id}` },
]}
/>
{env && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Upload size={14} />
{t('environments.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/environments/${env.id}/edit`)}
>
<Pencil size={14} />
{t('environments.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('environments.action_delete')}
</Button>
</div>
)}
</div>
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{env && (
<>
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('environments.field_id'), detail: <UuidBadge id={env.id} /> },
{
term: t('environments.field_created'),
detail: <Timestamp value={env.createdAt} />,
},
{
term: t('environments.field_updated'),
detail: <Timestamp value={env.updatedAt} />,
},
]}
/>
</Card>
{env.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={env.description} />
</Card>
</div>
)}
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
<Card>
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
{value}
</a>
),
}))}
/>
)}
</Card>
</div>
</>
)}
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
message={t('common.confirm_delete_environment')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -0,0 +1,209 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
DescriptionList,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const dataEntries = Object.entries(env.data ?? {}).filter(([, v]) => v);
const handleExport = async () => {
const data = await environments.exportEnvironment(env.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `environment-${env.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{env.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('environments.menu_label')}>
<Settings size={14} />
</Button>
}
items={[
{
label: t('environments.action_view'),
icon: <ExternalLink size={14} />,
onClick: () => navigate(`/environments/${env.id}`),
},
{
label: t('environments.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/environments/${env.id}/edit`),
},
{
label: t('environments.action_export'),
icon: <Download size={14} />,
onClick: () => void handleExport(),
},
{
label: t('environments.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(env.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<UuidBadge id={env.id} />
<Timestamp value={env.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/environments/${env.id}`)}
>
{dataEntries.length > 0 && (
<DescriptionList
layout="compact"
truncate
items={dataEntries.map(([key, value]) => ({ term: key, detail: value }))}
/>
)}
{dataEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_data')}</p>
)}
</Card>
);
}
function AddEnvironmentCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/environments/new')}>
<Plus size={16} />
{t('environments.action_add')}
</Button>
</div>
);
}
export function EnvironmentsPage() {
const { t } = useTranslation();
usePageTitle(t('environments.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
environments
.list()
.then((res) => setItems(res.data))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await environments.remove(deleteId);
setItems((prev) => prev.filter((e) => e.id !== deleteId));
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await environments.importEnvironment(payload);
navigate(`/environments/${imported.id}`);
} catch {
// Import errors are silently ignored
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('environments.title'), icon: <Globe size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Download size={14} />
{t('environments.action_import')}
</Button>
</div>
</div>
{loading ? (
<p className={styles.muted}>{t('environments.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((env) => (
<EnvironmentCard key={env.id} env={env} onDelete={requestDelete} />
))}
<AddEnvironmentCard />
</div>
)}
<DeleteConfirmationModal
open={deleteId != null}
title={t('environments.action_delete')}
message={t('common.confirm_delete_environment')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+139
View File
@@ -0,0 +1,139 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Activity } from 'lucide-react';
import { runs } from '../../api';
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
import {
AutoRefreshIndicator,
Badge,
Breadcrumbs,
Table,
Timestamp,
UuidBadge,
type TableColumn,
type SortDirection,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
const STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
type AllRunRow = ScenarioRun & {
scenario: { id: string; name: string };
};
export function AllRunsPage() {
const { t } = useTranslation();
usePageTitle(t('runs.title'));
const navigate = useNavigate();
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['runs', sortBy, sortDir, page, pageSize],
queryFn: () =>
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
refetchInterval: 10_000,
staleTime: 0,
});
const items = (data?.data ?? []) as AllRunRow[];
const total = data?.total ?? 0;
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
};
const handlePageChange = (p: number) => setPage(p);
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
};
const columns: TableColumn<AllRunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'scenario.name',
header: t('runs.col_scenario'),
sortable: true,
render: (r) => (
<span
className={styles.linkCell}
onClick={(e) => {
e.stopPropagation();
navigate(`/scenarios/${r.scenario.id}`);
}}
>
{r.scenario.name}
</span>
),
},
{
key: 'status',
header: t('runs.col_status'),
width: 110,
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator
active
pulseKey={items.length}
error={!!error}
onClick={() => refetch()}
/>
</div>
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={isLoading}
emptyMessage={t('runs.empty')}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
</div>
);
}
+626
View File
@@ -0,0 +1,626 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { runs, runFiles } from '../../api';
import type {
Scenario,
ScenarioRunDetail,
ScenarioRunStep,
ScenarioRunLog,
ScenarioRunStatus,
RunStepStatus,
LogLevel,
FileMetadata,
} from '../../api';
import { scenarios } from '../../api';
import { ExportLogsModal, type LogExportFormat } from '../../components/modals';
import {
AutoRefreshIndicator,
Badge,
Button,
Breadcrumbs,
Card,
CodeBlock,
DescriptionList,
Pagination,
Search,
Table,
Timestamp,
UuidBadge,
useToast,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import {
ChevronDown,
ChevronRight,
ClipboardList,
Activity,
Download,
RotateCcw,
} from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const RUN_STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
const STEP_STATUS_VARIANT: Record<RunStepStatus, BadgeVariant> = {
waiting: 'neutral',
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
cancelled: 'warning',
};
const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
log: 'neutral',
warn: 'warning',
error: 'error',
};
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
export function RunDetailPage() {
const { runId } = useParams<{ runId: string }>();
// Remount per run so "Repeat run" navigation starts from a clean state
return <RunDetail key={runId} />;
}
function RunDetail() {
const { t } = useTranslation();
const { id, runId } = useParams<{ id: string; runId: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
const [loading, setLoading] = useState(true);
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
const [error, setError] = useState<string | null>(null);
const [polling, setPolling] = useState(false);
const [pulseKey, setPulseKey] = useState(0);
const [logPage, setLogPage] = useState(1);
const [logSearch, setLogSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [expandAll, setExpandAll] = useState(false);
const [expandedStepIds, setExpandedStepIds] = useState<Set<string>>(new Set());
const [artifacts, setArtifacts] = useState<FileMetadata[]>([]);
const [artifactsTotal, setArtifactsTotal] = useState(0);
const [artifactsLoading, setArtifactsLoading] = useState(false);
const [exportLogsOpen, setExportLogsOpen] = useState(false);
const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md');
const [exportingLogs, setExportingLogs] = useState(false);
const [repeating, setRepeating] = useState(false);
const logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const stopPolling = () => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
setPolling(false);
}
};
const handleFileDownload = (url: string, filename: string) => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
};
const isFileExpired = (file: FileMetadata) =>
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
const handleExportLogs = async () => {
if (!id || !runId) return;
setExportingLogs(true);
try {
const content = await runs.exportLogs(id, runId, exportLogsFormat);
const mimeType = exportLogsFormat === 'csv' ? 'text/csv' : 'text/markdown';
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `run-${runId}-logs.${exportLogsFormat}`;
a.click();
URL.revokeObjectURL(url);
setExportLogsOpen(false);
} catch {
// error toast is already emitted by the API client
} finally {
setExportingLogs(false);
}
};
const handleRepeatRun = async () => {
if (!id || !run?.environmentId) return;
setRepeating(true);
try {
const newRun = await scenarios.run(
id,
run.environmentId,
run.saveSession,
run.traceMode ?? undefined,
);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${newRun.id}`);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRepeating(false);
}
};
const manualRefresh = () => {
if (!id || !runId) return;
runs
.get(id, runId, logSearchRef.current)
.then((r) => {
setRun(r);
setError(null);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message));
};
const loadArtifacts = useCallback(async () => {
if (!id || !runId) return;
setArtifactsLoading(true);
try {
const result = await runFiles.list(id, runId);
setArtifacts(result.items);
setArtifactsTotal(result.total);
} catch {
// Silently fail - artifacts are not critical
setArtifacts([]);
setArtifactsTotal(0);
} finally {
setArtifactsLoading(false);
}
}, [id, runId]);
useEffect(() => {
const t = setTimeout(() => {
setDebouncedSearch(logSearch);
logSearchRef.current = logSearch;
setLogPage(1);
}, 300);
return () => clearTimeout(t);
}, [logSearch]);
useEffect(() => {
if (!id || !runId || polling) return;
runs
.get(id, runId, debouncedSearch)
.then(setRun)
.catch(() => undefined);
}, [id, runId, polling, debouncedSearch]);
useEffect(() => {
if (!id || !runId) return;
let cancelled = false;
Promise.all([scenarios.get(id), runs.get(id, runId)])
.then(([sc, r]) => {
if (cancelled) return;
setScenario(sc);
setRun(r);
loadArtifacts();
if (!FINAL.includes(r.status)) {
setPolling(true);
pollRef.current = setInterval(async () => {
try {
const updated = await runs.get(id, runId, logSearchRef.current);
if (cancelled) return;
setRun(updated);
setPulseKey((k) => k + 1);
if (FINAL.includes(updated.status)) {
stopPolling();
await loadArtifacts();
}
} catch {
stopPolling();
}
}, 1000);
}
})
.catch((err: Error) => {
if (!cancelled) setError(err.message);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
stopPolling();
};
}, [id, runId, loadArtifacts]);
const stepColumns: TableColumn<ScenarioRunStep>[] = [
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
{
key: 'title',
header: t('runs.step_title'),
width: 220,
render: (s) => s.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
},
{
key: 'status',
header: t('runs.step_status'),
width: 110,
render: (s) => (
<Badge variant={STEP_STATUS_VARIANT[s.status]}>{s.status.replace('_', ' ')}</Badge>
),
},
{
key: 'description',
header: (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<span>{t('runs.step_description')}</span>
{run?.stepRuns.some((s) => s.output) && (
<button
onClick={() => {
if (expandAll) {
setExpandAll(false);
setExpandedStepIds(new Set());
} else {
setExpandAll(true);
setExpandedStepIds(
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
);
}
}}
style={{
background: 'none',
border: 'none',
padding: '0 4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
color: 'inherit',
}}
title={expandAll ? 'Collapse all' : 'Expand all'}
>
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
</div>
),
render: (s) => {
const isExpanded = expandAll || expandedStepIds.has(s.id);
return (
<div>
<div
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
marginBottom: isExpanded && s.output ? '8px' : 0,
}}
>
{s.output && (
<button
onClick={() => {
const newSet = new Set(expandedStepIds);
if (newSet.has(s.id)) {
newSet.delete(s.id);
} else {
newSet.add(s.id);
}
setExpandedStepIds(newSet);
}}
style={{
background: 'none',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
flexShrink: 0,
marginTop: '2px',
}}
>
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
<code style={{ wordBreak: 'break-word' }}>
{s.description ? (
s.description
) : s.output ? (
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
) : (
<span className={styles.muted}>–</span>
)}
</code>
</div>
{isExpanded && s.output && (
<div style={{ marginLeft: '24px' }}>
<CodeBlock
code={(() => {
try {
return JSON.stringify(JSON.parse(s.output), null, 2);
} catch {
return s.output;
}
})()}
language="json"
/>
</div>
)}
</div>
);
},
},
];
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 (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
label: t('runs.title'),
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `${runId}` },
]}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
{run && (
<span title={run.environmentId ? undefined : t('runs.repeat_no_environment')}>
<Button
variant="secondary"
size="sm"
onClick={handleRepeatRun}
disabled={!run.environmentId || repeating}
>
<RotateCcw size={14} />
{t('runs.action_repeat')}
</Button>
</span>
)}
<AutoRefreshIndicator
active={polling}
pulseKey={pulseKey}
error={!!error}
onClick={manualRefresh}
/>
</div>
</div>
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
{run && (
<>
<Card>
<DescriptionList
layout="grid"
items={(() => {
const items = [
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
];
if (run.traceMode) {
items.push({
term: t('runs.field_trace'),
detail: (
<span>{t(`scenarios.trace_mode_${run.traceMode.replace(/-/g, '_')}`)}</span>
),
});
}
if (run.environment) {
items.push({
term: 'Environment',
detail: (
<Link
to={`/environments/${run.environment.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.environment.name}
</Link>
),
});
}
if (run.session) {
items.push({
term: 'Session',
detail: (
<Link
to={`/sessions/${run.session.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.session.sessionName}
</Link>
),
});
}
return items;
})()}
/>
</Card>
{run.stepRuns.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('runs.steps_heading')}</h2>
<Table
columns={stepColumns}
data={run.stepRuns}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
/>
</div>
)}
{run.logs.length > 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Search
value={logSearch}
onChange={setLogSearch}
placeholder={t('runs.logs_search_placeholder')}
/>
<Button variant="secondary" size="sm" onClick={() => setExportLogsOpen(true)}>
<Download size={14} />
{t('runs.action_download_logs')}
</Button>
</div>
</div>
<Table
columns={logColumns}
data={run.logs.slice((logPage - 1) * LOG_PAGE_SIZE, logPage * LOG_PAGE_SIZE)}
rowKey={(l) => l.id}
loading={false}
emptyMessage=""
/>
{run.logs.length > LOG_PAGE_SIZE && (
<Pagination
page={logPage}
pageSize={LOG_PAGE_SIZE}
total={run.logs.length}
onPageChange={setLogPage}
/>
)}
</div>
)}
{(artifactsTotal > 0 || artifactsLoading) && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('files.artifactsTitle')}</h2>
<Table<FileMetadata>
loading={artifactsLoading}
data={artifacts}
rowKey={(f) => f.id}
columns={
[
{ key: 'name', header: t('files.name'), render: (f) => f.name },
{
key: 'mimeType',
header: t('files.mimeType'),
render: (f) => f.mimeType,
},
{
key: 'size',
header: t('files.size'),
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
},
{
key: 'expiresAt',
header: t('files.expiresAt'),
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
},
{
key: 'createdAt',
header: t('files.createdAt'),
render: (f) => <Timestamp value={f.createdAt} />,
},
{
key: 'download',
header: '',
render: (f) => {
const expired = isFileExpired(f);
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
return (
<span title={tooltip}>
<Button
variant="secondary"
size="sm"
title={tooltip}
aria-label={tooltip}
disabled={expired}
onClick={() =>
handleFileDownload(runFiles.contentUrl(id!, runId!, f.id), f.name)
}
>
<Download size={14} />
</Button>
</span>
);
},
},
] satisfies TableColumn<FileMetadata>[]
}
emptyMessage={t('files.empty')}
/>
</div>
)}
</>
)}
<ExportLogsModal
open={exportLogsOpen}
format={exportLogsFormat}
onFormatChange={setExportLogsFormat}
onClose={() => setExportLogsOpen(false)}
onExport={handleExportLogs}
isExporting={exportingLogs}
/>
</div>
);
}
+250
View File
@@ -0,0 +1,250 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Play, ClipboardList, Activity } from 'lucide-react';
import { environments, scenarios, runs } from '../../api';
import type { Environment, Scenario, ScenarioRun, ScenarioRunStatus } from '../../api';
import {
AutoRefreshIndicator,
Badge,
Breadcrumbs,
Button,
Modal,
Select,
Table,
Timestamp,
UuidBadge,
useToast,
type TableColumn,
type SortDirection,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
const STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
type RunRow = ScenarioRun;
export function RunsPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [items, setItems] = useState<RunRow[]>([]);
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [total, setTotal] = useState(0);
// Keep refs so the poll interval always reads current values
const sortByRef = useRef(sortBy);
const sortDirRef = useRef(sortDir);
const pageRef = useRef(page);
const pageSizeRef = useRef(pageSize);
sortByRef.current = sortBy;
sortDirRef.current = sortDir;
pageRef.current = page;
pageSizeRef.current = pageSize;
const load = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
if (!id) return;
if (!hasDataRef.current) setLoading(true);
Promise.all([
scenarios.get(id!),
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
])
.then(([sc, res]) => {
setScenario(sc);
setItems(res.data);
setTotal(res.total);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
},
[id],
);
useEffect(() => {
load('createdAt', 'desc', 1, 20);
pollRef.current = setInterval(
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
10_000,
);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [load]);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handlePageChange = (p: number) => {
setPage(p);
load(sortBy, sortDir, p, pageSize);
};
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
load(sortBy, sortDir, 1, size);
};
useEffect(() => {
environments
.list(1, 200)
.then((res) => {
setEnvs(res.data);
setSelectedEnvId((prev) => prev || res.data[0]?.id || '');
})
.catch(() => {});
}, []);
const handleRun = async () => {
if (!selectedEnvId) {
toast.error(t('scenarios.run_modal_env_required'));
return;
}
setRunning(true);
try {
const run = await scenarios.run(id!, selectedEnvId);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const columns: TableColumn<RunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'status',
header: t('runs.col_status'),
width: 100,
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('runs.title'), icon: <Activity size={14} /> },
]}
/>
<div className={styles.toolbarActions}>
<AutoRefreshIndicator
active
pulseKey={pulseKey}
error={!!error}
onClick={() => load(sortBy, sortDir, page, pageSize)}
/>
<Button size="sm" onClick={() => setRunModalOpen(true)}>
<Play size={14} />
{t('runs.action_run')}
</Button>
</div>
</div>
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
emptyMessage={t('runs.empty')}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('runs.action_run')}
</Button>
</>
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
)}
</Modal>
</div>
);
}
@@ -0,0 +1,118 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateScenarioPage() {
const { t } = useTranslation();
usePageTitle(t('scenarios.create_title'));
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [environmentId, setEnvironmentId] = useState('');
const [envs, setEnvs] = useState<Environment[]>([]);
const [nameError, setNameError] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, []);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
try {
const scenario = await scenarios.create(
name.trim(),
description.trim() || undefined,
environmentId || undefined,
);
toast.success(t('scenarios.created'));
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: t('scenarios.create_title') },
]}
/>
</div>
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('scenarios.form_name')}
placeholder={t('scenarios.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={8}
/>
</div>
<Select
label={t('scenarios.form_environment')}
value={environmentId}
onChange={(e) => setEnvironmentId(e.target.value)}
options={[
{ value: '', label: t('scenarios.form_environment_none') },
...envs.map((env) => ({ value: env.id, label: env.name })),
]}
/>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/scenarios')}>
<X size={14} />
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('scenarios.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,108 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateStepPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
usePageTitle(t('steps.create_title'));
const [title, setTitle] = useState('');
const [execCode, setExecCode] = useState('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
scenarios
.get(id)
.then(setScenario)
.catch(() => null);
}, [id]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
try {
await steps.create(id!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
});
toast.success(t('steps.created'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.create_title') },
]}
/>
</div>
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
<Input
label={t('steps.form_timeout')}
placeholder={t('steps.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('steps.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate(`/scenarios/${id}`)}>
<X size={14} />
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('steps.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,157 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, environments } from '../../api';
import type { Scenario, Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditScenarioPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [name, setName] = useState('');
usePageTitle(
scenario ? `${t('scenarios.edit_title')} — ${scenario.name}` : t('scenarios.edit_title'),
);
const [description, setDescription] = useState('');
const [environmentId, setEnvironmentId] = useState<string>('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [envs, setEnvs] = useState<Environment[]>([]);
const [nameError, setNameError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
scenarios
.get(id)
.then((data) => {
setScenario(data);
setName(data.name);
setDescription(data.description || '');
setEnvironmentId(data.environmentId ?? '');
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
})
.finally(() => setLoading(false));
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, [id]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
try {
await scenarios.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
environmentId: environmentId || null,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success(t('scenarios.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('scenarios.edit_title') },
]}
/>
</div>
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{!loading && scenario && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('scenarios.form_name')}
placeholder={t('scenarios.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={8}
/>
</div>
<Select
label={t('scenarios.form_environment')}
value={environmentId}
onChange={(e) => setEnvironmentId(e.target.value)}
options={[
{ value: '', label: t('scenarios.form_environment_none') },
...envs.map((env) => ({ value: env.id, label: env.name })),
]}
/>
<Input
label={t('scenarios.form_timeout')}
placeholder={t('scenarios.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('scenarios.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
<X size={14} />
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('scenarios.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
+125
View File
@@ -0,0 +1,125 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario, ScenarioStep } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditStepPage() {
const { t } = useTranslation();
const { id, stepId } = useParams<{ id: string; stepId: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [step, setStep] = useState<ScenarioStep | null>(null);
usePageTitle(
step ? t('steps.edit_title', { order: step.order }) : t('steps.edit_title', { order: '' }),
);
const [title, setTitle] = useState('');
const [execCode, setExecCode] = useState('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id || !stepId) return;
Promise.all([scenarios.get(id), steps.get(id, stepId)])
.then(([sc, st]) => {
setScenario(sc);
setStep(st);
setTitle(st.title ?? '');
setExecCode(st.execCode ?? '');
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
})
.finally(() => setLoading(false));
}, [id, stepId]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
try {
await steps.update(id!, stepId!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success(t('steps.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
]}
/>
</div>
{loading && <p className={styles.muted}>{t('steps.loading')}</p>}
{!loading && step && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
<Input
label={t('steps.form_timeout')}
placeholder={t('steps.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('steps.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
<X size={14} />
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('steps.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,885 @@
import { useEffect, useRef, useState, useCallback, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import {
Play,
Pencil,
Plus,
History,
Download,
Trash2,
Upload,
GripVertical,
ClipboardList,
FileArchive,
} from 'lucide-react';
import {
environments,
scenarios,
steps,
scenarioCredentials,
scenarioFiles,
credentials as credentialsApi,
} from '../../api';
import type {
Scenario,
ScenarioStep,
ScenarioCredential,
Credential,
Environment,
FileMetadata,
Snippet,
TraceMode,
} from '../../api';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Input,
Modal,
Select,
Table,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
type TableColumn,
} from '../../ui';
import { ExportScenarioModal, RunScenarioModal } from '../../components/modals';
import { useRunDefaults } from '../../hooks/useRunDefaults';
import styles from '../Page.module.css';
export function ScenarioDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
usePageTitle(scenario?.name ?? null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
const [allCredentials, setAllCredentials] = useState<Credential[]>([]);
const [addCredOpen, setAddCredOpen] = useState(false);
const [addCredId, setAddCredId] = useState('');
const [addAlias, setAddAlias] = useState('');
const [addCredError, setAddCredError] = useState('');
const [addAliasError, setAddAliasError] = useState('');
const [addCredSaving, setAddCredSaving] = useState(false);
const [draggedStepId, setDraggedStepId] = useState<string | null>(null);
const [dragOverStepId, setDragOverStepId] = useState<string | null>(null);
const [reorderingSteps, setReorderingSteps] = useState(false);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
// null = use the server's configured default
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
const runDefaults = useRunDefaults();
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'on';
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const envInitRef = useRef(false);
const [pendingDelete, setPendingDelete] = useState<
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
>(null);
const [deleting, setDeleting] = useState(false);
// Export modal state
const [exportModalOpen, setExportModalOpen] = useState(false);
const [includeEnvironment, setIncludeEnvironment] = useState(true);
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
const [isExporting, setIsExporting] = useState(false);
// Files state
const [files, setFiles] = useState<FileMetadata[]>([]);
const [filesTotal, setFilesTotal] = useState(0);
const [filesLoading, setFilesLoading] = useState(false);
const [uploadOpen, setUploadOpen] = useState(false);
const [uploadFile, setUploadFile] = useState<File | null>(null);
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
const [uploading, setUploading] = useState(false);
const [usedSnippets, setUsedSnippets] = useState<Snippet[]>([]);
const loadFiles = useCallback(async () => {
if (!id) return;
setFilesLoading(true);
try {
const result = await scenarioFiles.list(id);
setFiles(result.items);
setFilesTotal(result.total);
} finally {
setFilesLoading(false);
}
}, [id]);
useEffect(() => {
if (!id) return;
void scenarios
.get(id)
.then((s) => {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.finally(() => setLoading(false));
void loadFiles();
scenarios
.usedSnippets(id)
.then(setUsedSnippets)
.catch(() => {});
credentialsApi
.list(1, 200)
.then((r) => setAllCredentials(r.data))
.catch(() => {});
environments
.list(1, 200)
.then((r) => {
setEnvs(r.data);
})
.catch(() => {});
}, [id, loadFiles]);
// Default selected env to scenario's linked environment (or first env) once both are loaded
useEffect(() => {
if (envInitRef.current || envs.length === 0) return;
envInitRef.current = true;
const preferred = scenario?.environmentId ?? null;
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
setSelectedEnvId(exists ? preferred! : envs[0].id);
}, [scenario, envs]);
const reloadScenario = async () => {
if (!id) return;
const s = await scenarios.get(id);
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
scenarios
.usedSnippets(id)
.then(setUsedSnippets)
.catch(() => {});
};
const handleRun = async () => {
if (!scenario) return;
if (!selectedEnvId) {
toast.error(t('scenarios.run_modal_env_required'));
return;
}
setRunning(true);
try {
const run = await scenarios.run(
scenario.id,
selectedEnvId,
saveSessionFlag,
traceModeOverride ?? undefined,
);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const handleDelete = async () => {
if (!scenario) return;
await scenarios.remove(scenario.id);
navigate('/scenarios');
};
const handleOpenExportModal = () => {
if (!scenario) return;
// Initialise all credential checkboxes to checked
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
setIncludeEnvironment(true);
setExportModalOpen(true);
};
const handleExport = async () => {
if (!scenario) return;
setIsExporting(true);
try {
const credIds = Array.from(includedCredentialIds);
const yamlContent = await scenarios.exportScenario(scenario.id, {
includeEnvironment,
credentialIds: credIds,
});
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
setExportModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setIsExporting(false);
}
};
const handleFileDownload = (url: string, filename: string) => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
};
const isFileExpired = (file: FileMetadata) =>
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
async function handleUpload(e: SubmitEvent) {
e.preventDefault();
if (!id || !uploadFile) return;
setUploading(true);
try {
await scenarioFiles.upload(
id,
uploadFile,
uploadExpiresAt ? new Date(uploadExpiresAt) : undefined,
);
setUploadOpen(false);
setUploadFile(null);
setUploadExpiresAt('');
await loadFiles();
toast.success(t('files.uploadSuccess'));
} catch {
// error toast already emitted by API client
} finally {
setUploading(false);
}
}
const handleDeleteStep = async (stepId: string) => {
await steps.remove(id!, stepId);
await reloadScenario();
};
const handleMoveStep = async (fromStepId: string, toStepId: string) => {
if (!scenario || reorderingSteps) return;
setReorderingSteps(true);
try {
const orderedSteps = [...scenario.steps].sort((a, b) => a.order - b.order);
const toIndex = orderedSteps.findIndex((step) => step.id === toStepId);
if (toIndex < 0) return;
await steps.update(id!, fromStepId, { order: toIndex });
await reloadScenario();
} finally {
setReorderingSteps(false);
}
};
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!addCredId) {
setAddCredError(t('scenarios.cred_form_cred_required'));
valid = false;
}
if (!addAlias.trim()) {
setAddAliasError(t('scenarios.cred_form_alias_required'));
valid = false;
}
if (!valid) return;
setAddCredSaving(true);
try {
const sc = await scenarioCredentials.add(id!, addCredId, addAlias.trim());
// Re-fetch the credential object since the response may not include it
const full = await scenarioCredentials.list(id!);
setScenarioCreds(full);
void sc;
setAddCredOpen(false);
setAddCredId('');
setAddAlias('');
} catch (err) {
setAddCredError((err as Error).message);
} finally {
setAddCredSaving(false);
}
};
const handleRemoveCredential = async (scCredId: string) => {
await scenarioCredentials.remove(id!, scCredId);
setScenarioCreds((prev) => prev.filter((sc) => sc.id !== scCredId));
};
const confirmDelete = async () => {
if (!pendingDelete) return;
setDeleting(true);
try {
if (pendingDelete.type === 'scenario') {
await handleDelete();
return;
}
if (pendingDelete.type === 'step') {
await handleDeleteStep(pendingDelete.id);
}
if (pendingDelete.type === 'credential') {
await handleRemoveCredential(pendingDelete.id);
}
setPendingDelete(null);
} finally {
setDeleting(false);
}
};
const stepColumns: TableColumn<ScenarioStep>[] = [
{
key: 'drag',
header: '',
width: 44,
align: 'center',
render: (s) => (
<span
role="button"
tabIndex={0}
aria-label="Drag to reorder step"
className={[styles.dragHandle, reorderingSteps ? styles.dragHandleDisabled : '']
.filter(Boolean)
.join(' ')}
draggable={!reorderingSteps}
onClick={(e) => e.stopPropagation()}
onDragStart={(e) => {
if (reorderingSteps) {
e.preventDefault();
return;
}
setDraggedStepId(s.id);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', s.id);
}}
onDragEnd={() => {
setDraggedStepId(null);
setDragOverStepId(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
}
}}
>
<GripVertical size={14} />
</span>
),
},
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'title',
header: t('scenarios.step_title'),
render: (s) =>
s.title ?? (
<span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>
),
},
{
key: 'updated',
header: t('scenarios.step_updated'),
width: 140,
render: (s) => <Timestamp value={s.updatedAt} />,
},
{
key: 'actions',
header: '',
width: 80,
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button
size="sm"
variant="secondary"
title={t('steps.action_edit')}
onClick={(e) => {
e.stopPropagation();
navigate(`/scenarios/${id}/steps/${s.id}/edit`);
}}
>
<Pencil size={14} />
</Button>
<Button
size="sm"
variant="danger"
title={t('steps.action_delete')}
onClick={(e) => {
e.stopPropagation();
setPendingDelete({ type: 'step', id: s.id });
}}
>
<Trash2 size={14} />
</Button>
</span>
),
},
];
const credColumns: TableColumn<ScenarioCredential>[] = [
{ key: 'alias', header: t('scenarios.cred_col_alias'), render: (sc) => sc.alias },
{
key: 'name',
header: t('scenarios.cred_col_name'),
render: (sc) => sc.credential?.name ?? `#${sc.credentialId}`,
},
{
key: 'added',
header: t('scenarios.cred_col_added'),
width: 140,
render: (sc) => <Timestamp value={sc.createdAt} />,
},
{
key: 'actions',
header: '',
width: 60,
align: 'right',
render: (sc) => (
<Button
size="sm"
variant="danger"
title={t('scenarios.cred_action_remove')}
onClick={(e) => {
e.stopPropagation();
setPendingDelete({ type: 'credential', id: sc.id });
}}
>
<Trash2 size={14} />
</Button>
),
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button
size="sm"
onClick={() => {
setTraceModeOverride(null);
setRunModalOpen(true);
}}
>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/runs`)}>
<History size={14} />
{t('scenarios.action_runs')}
</Button>
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
<Upload size={14} />
{t('scenarios.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() =>
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
}
>
<FileArchive size={14} />
{t('scenarios.action_export_e2e')}
</Button>
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
<Pencil size={14} />
{t('scenarios.action_edit')}
</Button>
<Button
variant="danger"
size="sm"
onClick={() => setPendingDelete({ type: 'scenario' })}
>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
</div>
)}
</div>
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{scenario && (
<>
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
...(scenario.environment
? [
{
term: t('scenarios.field_environment'),
detail: (
<a
href={`/environments/${scenario.environment.id}`}
onClick={(e) => {
e.preventDefault();
navigate(`/environments/${scenario.environment!.id}`);
}}
>
{scenario.environment.name}
</a>
),
},
]
: []),
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
},
{
term: t('scenarios.field_updated'),
detail: <Timestamp value={scenario.updatedAt} />,
},
]}
/>
</Card>
{scenario.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={scenario.description} />
</Card>
</div>
)}
{scenario.steps.length > 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Button size="sm" onClick={() => navigate(`/scenarios/${id}/steps/new`)}>
<Plus size={14} />
{t('steps.action_add')}
</Button>
</div>
<Table
columns={stepColumns}
data={scenario.steps}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
getRowProps={(s) => ({
className: dragOverStepId === s.id ? styles.dragOverRow : undefined,
onDragOver: (e) => {
if (reorderingSteps) return;
e.preventDefault();
if (draggedStepId && draggedStepId !== s.id) {
setDragOverStepId(s.id);
}
},
onDragLeave: () => {
if (dragOverStepId === s.id) {
setDragOverStepId(null);
}
},
onDrop: async (e) => {
if (reorderingSteps) return;
e.preventDefault();
const fromId = draggedStepId ?? e.dataTransfer.getData('text/plain');
setDragOverStepId(null);
setDraggedStepId(null);
if (!fromId || fromId === s.id) return;
await handleMoveStep(fromId, s.id);
},
})}
/>
</div>
)}
{scenario.steps.length === 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Button size="sm" onClick={() => navigate(`/scenarios/${id}/steps/new`)}>
<Plus size={14} />
{t('steps.action_add')}
</Button>
</div>
</div>
)}
{/* ── Credentials section ──────────────────────────────────── */}
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.credentials_heading')}</h2>
<Button size="sm" onClick={() => setAddCredOpen((v) => !v)}>
<Plus size={14} />
{t('scenarios.cred_action_add')}
</Button>
</div>
{addCredOpen && (
<div style={{ marginBottom: 'var(--space-4)' }}>
<Card className={styles.formCard}>
<form onSubmit={handleAddCredential} noValidate>
<div className={styles.formFields}>
<Select
label={t('scenarios.cred_form_cred')}
value={addCredId}
onChange={(e) => {
setAddCredId(e.target.value);
setAddCredError('');
}}
error={addCredError || undefined}
options={[
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
]}
/>
<Input
label={t('scenarios.cred_form_alias')}
placeholder={t('scenarios.cred_form_alias_placeholder')}
value={addAlias}
onChange={(e) => {
setAddAlias(e.target.value);
setAddAliasError('');
}}
error={addAliasError || undefined}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => {
setAddCredOpen(false);
setAddCredId('');
setAddAlias('');
}}
>
{t('scenarios.cred_action_cancel')}
</Button>
<Button type="submit" size="sm" loading={addCredSaving}>
{t('scenarios.cred_action_save')}
</Button>
</div>
</form>
</Card>
</div>
)}
{scenarioCreds.length > 0 ? (
<Table
columns={credColumns}
data={scenarioCreds}
rowKey={(sc) => sc.id}
loading={false}
emptyMessage=""
/>
) : (
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
)}
</div>
{/* ── Used snippets section ───────────────────────────────────────── */}
{usedSnippets.length > 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.used_snippets_heading')}</h2>
</div>
<Table<Snippet>
data={usedSnippets}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
onRowClick={(s) => navigate(`/snippets/${s.id}`)}
columns={
[
{
key: 'alias',
header: t('snippets.field_alias'),
render: (s) => s.alias,
},
{
key: 'title',
header: t('snippets.field_title'),
render: (s) => s.title,
},
] satisfies TableColumn<Snippet>[]
}
/>
</div>
)}
{/* ── Files section ───────────────────────────────────────────────── */}
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('files.title')}</h2>
<Button size="sm" onClick={() => setUploadOpen(true)}>
<Upload size={14} /> {t('files.upload')}
</Button>
</div>
<Table<FileMetadata>
loading={filesLoading}
data={files}
rowKey={(f) => f.id}
columns={
[
{
key: 'name',
header: t('files.name'),
render: (f) => f.name,
},
{
key: 'mimeType',
header: t('files.mimeType'),
render: (f) => f.mimeType,
},
{
key: 'size',
header: t('files.size'),
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
},
{
key: 'expiresAt',
header: t('files.expiresAt'),
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
},
{
key: 'createdAt',
header: t('files.createdAt'),
render: (f) => <Timestamp value={f.createdAt} />,
},
{
key: 'download',
header: '',
render: (f) => {
const expired = isFileExpired(f);
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
return (
<span title={tooltip}>
<Button
variant="secondary"
size="sm"
title={tooltip}
aria-label={tooltip}
disabled={expired}
onClick={() =>
handleFileDownload(scenarioFiles.contentUrl(id!, f.id), f.name)
}
>
<Download size={14} />
</Button>
</span>
);
},
},
] satisfies TableColumn<FileMetadata>[]
}
emptyMessage={t('files.empty')}
/>
</div>
{/* ── Upload modal ─────────────────────────────────────────────── */}
<Modal
open={uploadOpen}
title={t('files.uploadTitle')}
onClose={() => setUploadOpen(false)}
>
<form onSubmit={handleUpload}>
<input
type="file"
required
onChange={(e) => setUploadFile(e.target.files?.[0] ?? null)}
/>
<Input
label={t('files.expiresAtLabel')}
type="datetime-local"
value={uploadExpiresAt}
onChange={(e) => setUploadExpiresAt(e.target.value)}
/>
<Button type="submit" loading={uploading} disabled={!uploadFile}>
{t('files.upload')}
</Button>
</form>
</Modal>
</>
)}
<Modal
open={pendingDelete != null}
title={
pendingDelete?.type === 'step'
? t('steps.action_delete')
: pendingDelete?.type === 'credential'
? t('scenarios.cred_action_remove')
: t('scenarios.action_delete')
}
onClose={() => !deleting && setPendingDelete(null)}
footer={
<>
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
{t('common.button_confirm')}
</Button>
</>
}
>
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
</Modal>
<RunScenarioModal
open={runModalOpen}
environments={envs}
selectedEnvId={selectedEnvId}
onEnvSelect={setSelectedEnvId}
saveSessionFlag={saveSessionFlag}
onSaveSessionChange={setSaveSessionFlag}
traceMode={traceMode}
defaultTraceMode={runDefaults?.traceMode ?? null}
onTraceModeChange={setTraceModeOverride}
onClose={() => setRunModalOpen(false)}
onRun={handleRun}
isRunning={running}
/>
<ExportScenarioModal
open={exportModalOpen}
scenario={scenario}
scenarioCredentials={scenarioCreds}
environment={
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
}
includeEnvironment={includeEnvironment}
onIncludeEnvironmentChange={setIncludeEnvironment}
includedCredentialIds={includedCredentialIds}
onCredentialToggle={(credId, checked) => {
setIncludedCredentialIds((prev) => {
const next = new Set(prev);
if (checked) next.add(credId);
else next.delete(credId);
return next;
});
}}
onClose={() => setExportModalOpen(false)}
onExport={handleExport}
isExporting={isExporting}
/>
</div>
);
}
+301
View File
@@ -0,0 +1,301 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { environments, scenarios } from '../../api';
import type { Environment, Scenario, TraceMode } from '../../api';
import { RunScenarioModal } from '../../components/modals';
import { useRunDefaults } from '../../hooks/useRunDefaults';
import {
Badge,
Breadcrumbs,
Button,
Modal,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
useToast,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import type { ScenarioRunStatus } from '../../api';
import styles from '../Page.module.css';
const LAST_RUN_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const LAST_RUN_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
export function ScenariosPage() {
const { t } = useTranslation();
usePageTitle(t('scenarios.title'));
const navigate = useNavigate();
const toast = useToast();
const [items, setItems] = useState<Scenario[]>([]);
const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
// null = use the server's configured default
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
const runDefaults = useRunDefaults();
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'on';
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const fileInputRef = useRef<HTMLInputElement>(null);
const [sortBy, setSortBy] = useState('updatedAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const load = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
Promise.all([
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
environments.list(1, 200),
])
.then(([scenarioRes, envRes]) => {
setItems(scenarioRes?.data ?? []);
setTotal(scenarioRes?.total ?? 0);
setEnvs(envRes?.data ?? []);
})
.catch((err) => {
toast.error((err as Error).message);
})
.finally(() => setLoading(false));
},
[toast],
);
useEffect(() => {
load('updatedAt', 'desc', 1, 10);
}, [load]);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handlePageChange = (p: number) => {
setPage(p);
load(sortBy, sortDir, p, pageSize);
};
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
load(sortBy, sortDir, 1, size);
};
const openRunModal = (id: string) => {
setRunScenarioId(id);
setTraceModeOverride(null);
const scenario = items.find((s) => s.id === id);
const preferred = scenario?.environmentId ?? null;
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
};
const handleRun = async () => {
if (!runScenarioId || !selectedEnvId) return;
setRunning(true);
try {
const run = await scenarios.run(
runScenarioId,
selectedEnvId,
saveSessionFlag,
traceModeOverride ?? undefined,
);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
setRunScenarioId(null);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await scenarios.remove(deleteId);
load(sortBy, sortDir, page, pageSize);
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await scenarios.importScenario(payload);
navigate(`/scenarios/${imported.id}`);
} catch {
// Import errors are silently ignored
}
};
const columns: TableColumn<Scenario>[] = [
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
{
key: 'lastRunStatus',
header: t('scenarios.col_last_run'),
width: 160,
render: (s) =>
s.lastRunStatus ? (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
<span style={{ display: 'inline-flex', minWidth: 62 }}>
<Badge variant={LAST_RUN_VARIANT[s.lastRunStatus]}>
{LAST_RUN_LABEL[s.lastRunStatus]}
</Badge>
</span>
{s.lastRunAt && <Timestamp value={s.lastRunAt} />}
</span>
) : (
<span style={{ color: 'var(--color-text-muted)', fontSize: '0.8em' }}>—</span>
),
},
{
key: 'updatedAt',
header: t('scenarios.col_updated'),
width: 140,
sortable: true,
render: (s) => <Timestamp value={s.updatedAt} />,
},
{
key: 'actions',
header: '',
width: 100,
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button
size="sm"
title={t('scenarios.action_run')}
onClick={(e) => {
e.stopPropagation();
openRunModal(s.id);
}}
>
<Play size={14} />
</Button>
<Button
variant="danger"
size="sm"
title={t('scenarios.action_delete')}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
</span>
),
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('scenarios.title'), icon: <ClipboardList size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Download size={14} />
{t('scenarios.action_import')}
</Button>
<Button size="sm" onClick={() => navigate('/scenarios/new')}>
<Plus size={14} />
{t('scenarios.action_add')}
</Button>
</div>
</div>
<Table
columns={columns}
data={items}
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('scenarios.empty')}
pageSize={pageSize}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('scenarios.action_delete')}
</Button>
</>
}
>
{t('common.confirm_delete_scenario')}
</Modal>
<RunScenarioModal
open={runScenarioId != null}
environments={envs}
selectedEnvId={selectedEnvId}
onEnvSelect={setSelectedEnvId}
saveSessionFlag={saveSessionFlag}
onSaveSessionChange={setSaveSessionFlag}
traceMode={traceMode}
defaultTraceMode={runDefaults?.traceMode ?? null}
onTraceModeChange={setTraceModeOverride}
onClose={() => setRunScenarioId(null)}
onRun={handleRun}
isRunning={running}
/>
</div>
);
}
@@ -1,11 +1,13 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { sessions } from '../api';
import type { Session } from '../api';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../ui';
import styles from './Page.module.css';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionDetailPage() {
const { t } = useTranslation();
@@ -13,21 +15,28 @@ export function SessionDetailPage() {
const navigate = useNavigate();
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(session?.sessionName ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
sessions
.get(Number(id))
.get(id)
.then(setSession)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!session) return;
await sessions.remove(session.id);
navigate('/sessions');
setDeleting(true);
try {
await sessions.remove(session.id);
navigate('/sessions');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
return (
@@ -35,34 +44,30 @@ export function SessionDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('sessions.title'), onClick: () => navigate('/sessions') },
{
label: t('sessions.title'),
icon: <Monitor size={14} />,
onClick: () => navigate('/sessions'),
},
{ label: session?.sessionName ?? `#${id}` },
]}
/>
{session && (
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('sessions.action_delete')}
</Button>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_session', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('sessions.loading')}</p>}
{session && (
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('sessions.field_id'), detail: session.id },
{ term: t('sessions.field_id'), detail: <UuidBadge id={session.id} /> },
{ term: t('sessions.field_name'), detail: session.sessionName },
{
term: t('sessions.field_status'),
@@ -92,6 +97,15 @@ export function SessionDetailPage() {
/>
</Card>
)}
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('sessions.action_delete')}
message={t('common.confirm_delete_session')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+146
View File
@@ -0,0 +1,146 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionsPage() {
const { t } = useTranslation();
usePageTitle(t('sessions.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [sortBy, setSortBy] = useState('id');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
sessions
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
.then((res) => {
setItems(res.data);
setTotal(res.total);
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load(sortBy, sortDir, page, pageSize);
}, [load, sortBy, sortDir, page, pageSize]);
const handleSort = (col: string, dir: SortDirection) => {
setSortBy(col);
setSortDir(dir);
setPage(1);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await sessions.remove(deleteId);
load(sortBy, sortDir, page, pageSize);
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const columns: TableColumn<Session>[] = [
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
{
key: 'sessionName',
header: t('sessions.col_name'),
sortable: true,
render: (s) => s.sessionName,
},
{
key: 'status',
header: t('sessions.col_status'),
width: 100,
sortable: true,
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
},
{
key: 'lastUsedAt',
header: t('sessions.col_lastUsed'),
width: 160,
sortable: true,
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
},
{
key: 'actions',
header: '',
width: 48,
align: 'right',
render: (s) => (
<Button
variant="danger"
size="sm"
title={t('sessions.action_delete')}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
),
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('sessions.title'), icon: <Monitor size={14} /> }]} />
</div>
<Table
columns={columns}
data={items}
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('sessions.empty')}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={setPage}
onPageSizeChange={(s) => {
setPageSize(s);
setPage(1);
}}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
<DeleteConfirmationModal
open={deleteId != null}
title={t('sessions.action_delete')}
message={t('common.confirm_delete_session')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -0,0 +1,140 @@
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateSnippetPage() {
const { t } = useTranslation();
usePageTitle(t('snippets.create_title'));
const navigate = useNavigate();
const toast = useToast();
const [alias, setAlias] = useState('');
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
setAliasError(t('snippets.form_alias_required'));
valid = false;
}
if (!title.trim()) {
setTitleError(t('snippets.form_title_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
try {
const snippet = await snippets.create({
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success(t('snippets.created'));
navigate(`/snippets/${snippet.id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: t('snippets.create_title') },
]}
/>
</div>
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setAlias(e.target.value);
setAliasError('');
}}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_title')}
placeholder={t('snippets.form_title_placeholder')}
value={title}
onChange={(e) => {
setTitle(e.target.value);
setTitleError('');
}}
error={titleError || undefined}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
<CodeEditor
value={description}
onChange={setDescription}
language="markdown"
rows={10}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
value={code}
onChange={(v) => {
setCode(v);
setCodeError('');
}}
rows={14}
error={!!codeError}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
<X size={14} />
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
<Save size={14} />
{t('snippets.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,168 @@
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditSnippetPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [alias, setAlias] = useState('');
usePageTitle(
snippet ? `${t('snippets.edit_title')} — ${snippet.title}` : t('snippets.edit_title'),
);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!id) return;
snippets
.get(id)
.then((s) => {
setSnippet(s);
setAlias(s.alias);
setTitle(s.title);
setDescription(s.description ?? '');
setCode(s.code);
})
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
setAliasError(t('snippets.form_alias_required'));
valid = false;
}
if (!title.trim()) {
setTitleError(t('snippets.form_title_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
try {
await snippets.update(id!, {
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success(t('snippets.updated'));
navigate(`/snippets/${id}`);
} catch (err) {
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
},
{ label: t('snippets.edit_title') },
]}
/>
</div>
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && snippet && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setAlias(e.target.value);
setAliasError('');
}}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_title')}
placeholder={t('snippets.form_title_placeholder')}
value={title}
onChange={(e) => {
setTitle(e.target.value);
setTitleError('');
}}
error={titleError || undefined}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
<CodeEditor
value={description}
onChange={setDescription}
language="markdown"
rows={10}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
value={code}
onChange={(v) => {
setCode(v);
setCodeError('');
}}
rows={14}
error={!!codeError}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate(`/snippets/${id}`)}>
<X size={14} />
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
<Save size={14} />
{t('snippets.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,167 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Upload, Pencil, Trash2, Braces } from 'lucide-react';
import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function SnippetDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
usePageTitle(snippet?.title ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
snippets
.get(id)
.then(setSnippet)
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!snippet) return;
setDeleting(true);
try {
await snippets.remove(snippet.id);
navigate('/snippets');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
if (!snippet) return;
const data = await snippets.exportSnippet(snippet.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snippet-${snippet.alias}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: snippet?.title ?? `#${id}` },
]}
/>
{snippet && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Upload size={14} />
{t('snippets.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/snippets/${snippet.id}/edit`)}
>
<Pencil size={14} />
{t('snippets.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('snippets.action_delete')}
</Button>
</div>
)}
</div>
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{snippet && (
<>
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
{ term: t('snippets.field_alias'), detail: snippet.alias },
{ term: t('snippets.field_title'), detail: snippet.title },
{
term: t('snippets.field_created'),
detail: <Timestamp value={snippet.createdAt} />,
},
{
term: t('snippets.field_updated'),
detail: <Timestamp value={snippet.updatedAt} />,
},
]}
/>
</Card>
{snippet.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('snippets.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={snippet.description} />
</Card>
</div>
)}
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
</div>
<Card>
<CodeBlock code={snippet.code} />
</Card>
</div>
</>
)}
<Modal
open={confirmDeleteOpen}
title={t('snippets.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={
<>
<Button
variant="secondary"
onClick={() => setConfirmDeleteOpen(false)}
disabled={deleting}
>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
}
>
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
}
+217
View File
@@ -0,0 +1,217 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
function firstParagraphBlocks(
markdown: string,
limit = 2,
): { preview: string; truncated: boolean } {
const blocks = markdown
.split(/\n\s*\n/g)
.map((block) => block.trim())
.filter(Boolean);
const sliced = blocks.slice(0, limit);
return {
preview: sliced.join('\n\n'),
truncated: blocks.length > limit,
};
}
function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: string) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{snippet.title}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
<Settings size={14} />
</Button>
}
items={[
{
label: t('snippets.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/snippets/${snippet.id}/edit`),
},
{
label: t('snippets.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(snippet.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<UuidBadge id={snippet.id} />
<Timestamp value={snippet.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/snippets/${snippet.id}`)}
>
<p className={styles.muted}>
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
</p>
{snippet.description &&
(() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
</Card>
);
}
function AddSnippetCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/snippets/new')}>
<Plus size={16} />
{t('snippets.action_add')}
</Button>
</div>
);
}
export function SnippetsPage() {
const { t } = useTranslation();
usePageTitle(t('snippets.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
snippets
.list()
.then((res) => setItems(res.data))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await snippets.remove(deleteId);
load();
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await snippets.importSnippet(payload);
navigate(`/snippets/${imported.id}`);
} catch {
// Import errors are silently ignored
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('snippets.title'), icon: <Braces size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Download size={14} />
{t('snippets.action_import')}
</Button>
</div>
</div>
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && (
<div className={styles.envGrid}>
{items.map((s) => (
<SnippetCard key={s.id} snippet={s} onDelete={requestDelete} />
))}
{items.length === 0 && <p className={styles.muted}>{t('snippets.empty')}</p>}
<AddSnippetCard />
</div>
)}
<Modal
open={deleteId != null}
title={t('snippets.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
}
>
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
}
@@ -0,0 +1,103 @@
.root {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--font-size-xs);
font-family: var(--font-family);
user-select: none;
}
/* ── Dot ──────────────────────────────────────────────────── */
.dot {
position: relative;
width: 10px;
height: 10px;
flex-shrink: 0;
}
.dot::before {
content: '';
position: absolute;
inset: 0;
border-radius: 50%;
transition: background var(--transition);
}
/* ── Pulse ring ───────────────────────────────────────────── */
.ring {
position: absolute;
inset: 0;
border-radius: 50%;
animation: pulse 0.8s ease-out 1;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent);
}
70% {
box-shadow: 0 0 0 7px color-mix(in srgb, var(--color-primary) 0%, transparent);
}
100% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent);
}
}
/* ── Clickable / hover ────────────────────────────────────── */
.clickable {
cursor: pointer;
border-radius: 99px;
padding: 2px 6px;
margin: -2px -6px;
transition: background var(--transition);
}
.clickable:hover {
background: color-mix(in srgb, var(--color-text) 8%, transparent);
}
.clickable:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
/* ── Active state ─────────────────────────────────────────── */
.active .dot::before {
background: var(--color-primary);
}
.active .label {
color: var(--color-primary);
font-weight: 600;
}
/* ── Inactive / disabled state ────────────────────────────── */
.inactive .dot::before {
background: var(--color-text-muted);
opacity: 0.4;
}
.inactive .label {
color: var(--color-text-muted);
opacity: 0.5;
}
/* ── Error state ──────────────────────────────────────────── */
.error .dot::before {
background: var(--color-error-fg);
}
.error .ring {
animation: none;
}
.error .label {
color: var(--color-error-fg);
font-weight: 600;
}
@@ -0,0 +1,42 @@
import styles from './AutoRefreshIndicator.module.css';
export interface AutoRefreshIndicatorProps {
active: boolean;
pulseKey?: number;
label?: string;
error?: boolean;
onClick?: () => void;
}
export function AutoRefreshIndicator({
active,
pulseKey,
label = 'Live',
error = false,
onClick,
}: AutoRefreshIndicatorProps) {
const stateClass = error ? styles.error : active ? styles.active : styles.inactive;
const titleText = error
? 'Refresh failed — click to retry'
: active
? 'Auto-refreshing'
: 'Auto-refresh stopped';
return (
<div
className={[styles.root, stateClass, onClick ? styles.clickable : ''].join(' ')}
title={titleText}
aria-label={titleText}
aria-live="polite"
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
onClick={onClick}
onKeyDown={onClick ? (e) => (e.key === 'Enter' || e.key === ' ') && onClick() : undefined}
>
<span className={styles.dot}>
{pulseKey !== undefined && pulseKey > 0 && <span key={pulseKey} className={styles.ring} />}
</span>
<span className={styles.label}>{error ? 'Error' : label}</span>
</div>
);
}
+1
View File
@@ -9,6 +9,7 @@
border-radius: var(--radius-full);
white-space: nowrap;
line-height: 1.6;
box-shadow: var(--shadow-xs);
}
.dot {
@@ -1,4 +1,6 @@
.nav {
display: flex;
align-items: center;
font-family: var(--font-family);
}
@@ -19,6 +21,9 @@
}
.link {
display: inline-flex;
align-items: center;
gap: var(--space-1);
font-size: var(--font-size-sm);
color: var(--color-text-muted);
text-decoration: none;
@@ -42,6 +47,9 @@
}
.current {
display: inline-flex;
align-items: center;
gap: var(--space-1);
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--color-text);
@@ -3,6 +3,7 @@ import styles from './Breadcrumbs.module.css';
export interface BreadcrumbItem {
label: string;
icon?: React.ReactNode;
href?: string;
onClick?: (e: React.MouseEvent) => void;
}
@@ -35,14 +36,17 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
<li key={i} className={styles.item}>
{isLast ? (
<span className={styles.current} aria-current="page">
{item.icon}
{item.label}
</span>
) : item.href ? (
<a href={item.href} className={styles.link} onClick={item.onClick}>
{item.icon}
{item.label}
</a>
) : (
<button type="button" className={styles.link} onClick={item.onClick}>
{item.icon}
{item.label}
</button>
)}
+1
View File
@@ -11,6 +11,7 @@
white-space: nowrap;
outline: none;
text-decoration: none;
box-shadow: var(--shadow-xs);
transition:
background var(--transition),
border-color var(--transition),
+3
View File
@@ -7,6 +7,9 @@
}
.header {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-3) var(--space-6);
font-weight: 600;
font-size: var(--font-size-sm);
@@ -0,0 +1,76 @@
.pre {
margin: 0;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
}
.code {
font-family: var(--font-mono, ui-monospace, 'Cascadia Code', 'Fira Code', monospace);
font-size: var(--font-size-sm);
line-height: 1.6;
display: block;
background: transparent !important;
color: var(--color-text);
}
/* ── highlight.js token overrides (theme-aware) ─────────────────────── */
.code :global(.hljs-comment),
.code :global(.hljs-quote) {
color: var(--hl-comment, #6A8072);
font-style: italic;
}
.code :global(.hljs-keyword),
.code :global(.hljs-selector-tag),
.code :global(.hljs-built_in),
.code :global(.hljs-name),
.code :global(.hljs-tag) {
color: var(--hl-keyword, #A67DCC);
}
.code :global(.hljs-string),
.code :global(.hljs-title),
.code :global(.hljs-section),
.code :global(.hljs-attribute),
.code :global(.hljs-literal),
.code :global(.hljs-template-tag),
.code :global(.hljs-template-variable),
.code :global(.hljs-type),
.code :global(.hljs-addition) {
color: var(--hl-string, #9BB870);
}
.code :global(.hljs-number),
.code :global(.hljs-regexp),
.code :global(.hljs-link) {
color: var(--hl-number, #E8A85F);
}
.code :global(.hljs-function),
.code :global(.hljs-title.hljs-function_) {
color: var(--hl-function, #5BB8D4);
}
.code :global(.hljs-variable),
.code :global(.hljs-params) {
color: var(--hl-variable, #D4A0A0);
}
.code :global(.hljs-property) {
color: var(--hl-property, #79C0C8);
}
.code :global(.hljs-deletion),
.code :global(.hljs-meta) {
color: var(--hl-meta, #A9A3C9);
}
.code :global(.hljs-emphasis) {
font-style: italic;
}
.code :global(.hljs-strong) {
font-weight: 700;
}
+27
View File
@@ -0,0 +1,27 @@
import { useMemo } from 'react';
import hljs from '../../lib/hljs';
import styles from './CodeBlock.module.css';
export interface CodeBlockProps {
code: string;
language?: string;
}
export function CodeBlock({ code, language = 'javascript' }: CodeBlockProps) {
const highlighted = useMemo(() => {
try {
return hljs.highlight(code, { language }).value;
} catch {
return code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
}, [code, language]);
return (
<pre className={styles.pre}>
<code
className={`${styles.code} hljs language-${language}`}
dangerouslySetInnerHTML={{ __html: highlighted }}
/>
</pre>
);
}
@@ -0,0 +1,18 @@
.wrapper {
width: 100%;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
overflow: hidden;
resize: vertical;
min-height: 80px;
transition: border-color var(--transition), box-shadow var(--transition);
}
.focused {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent);
}
.hasError {
border-color: var(--color-danger);
}
+79
View File
@@ -0,0 +1,79 @@
import { useState, useEffect } from 'react';
import Editor, { OnMount } from '@monaco-editor/react';
import styles from './CodeEditor.module.css';
export interface CodeEditorProps {
value: string;
onChange: (value: string) => void;
language?: string;
rows?: number;
error?: boolean;
}
function useMonacoTheme() {
const [theme, setTheme] = useState(() =>
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
);
useEffect(() => {
const observer = new MutationObserver(() => {
setTheme(
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
);
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});
return () => observer.disconnect();
}, []);
return theme;
}
export function CodeEditor({
value,
onChange,
language = 'javascript',
rows = 6,
error = false,
}: CodeEditorProps) {
const theme = useMonacoTheme();
const [focused, setFocused] = useState(false);
const height = rows * 20 + 16;
const handleMount: OnMount = (editor) => {
editor.onDidFocusEditorWidget(() => setFocused(true));
editor.onDidBlurEditorWidget(() => setFocused(false));
};
return (
<div
className={[styles.wrapper, focused ? styles.focused : '', error ? styles.hasError : '']
.filter(Boolean)
.join(' ')}
style={{ height }}
>
<Editor
height="100%"
theme={theme}
language={language}
value={value}
onChange={(v) => onChange(v ?? '')}
onMount={handleMount}
options={{
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 14,
lineHeight: 20,
wordWrap: 'on',
padding: { top: 8, bottom: 8 },
folding: false,
renderLineHighlight: 'line',
scrollbar: { vertical: 'auto', horizontal: 'hidden' },
automaticLayout: true,
}}
/>
</div>
);
}
@@ -45,7 +45,26 @@
max-width: 100%;
}
/* ── Layout modifiers ───────────────────────────────────────── */
/* ── Grid layout ───────────────────────────────────────────── */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: var(--space-4) var(--space-6);
}
.grid .row {
flex-direction: column;
gap: var(--space-1);
}
.grid .term {
margin-bottom: 0;
}
.grid .detail {
font-size: var(--font-size-sm);
}
.inline .row {
flex-direction: row;
@@ -16,8 +16,8 @@ export interface DescriptionListItem {
export interface DescriptionListProps {
items: DescriptionListItem[];
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default) */
layout?: 'inline' | 'compact' | 'comfortable';
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default); 'grid' flows items into a responsive multi-column grid */
layout?: 'inline' | 'compact' | 'comfortable' | 'grid';
/** Truncate detail values with ellipsis; full value shown in a tooltip on hover */
truncate?: boolean;
className?: string;
+1
View File
@@ -23,6 +23,7 @@
height: 36px;
width: 100%;
outline: none;
box-shadow: var(--shadow-xs);
transition: border-color var(--transition), box-shadow var(--transition);
}
@@ -0,0 +1,113 @@
.markdown {
color: var(--color-text);
line-height: 1.65;
font-size: var(--font-size-sm);
}
.markdown > :first-child {
margin-top: 0;
}
.markdown > :last-child {
margin-bottom: 0;
}
.markdown h1,
.markdown h2,
.markdown h3,
.markdown h4,
.markdown h5,
.markdown h6 {
line-height: 1.25;
margin: var(--space-5) 0 var(--space-3);
}
.markdown h1 {
font-size: var(--font-size-lg);
}
.markdown h2 {
font-size: var(--font-size-md);
}
.markdown h3,
.markdown h4,
.markdown h5,
.markdown h6 {
font-size: var(--font-size-sm);
}
.markdown p {
margin: 0 0 var(--space-3);
}
.markdown ul,
.markdown ol {
margin: 0 0 var(--space-3);
padding-left: 1.35rem;
}
.markdown li + li {
margin-top: var(--space-1);
}
.markdown blockquote {
margin: 0 0 var(--space-3);
padding: var(--space-2) var(--space-3);
border-left: 3px solid var(--color-primary);
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
border-radius: var(--radius-sm);
}
.markdown pre {
margin: 0 0 var(--space-3);
padding: var(--space-3);
border-radius: var(--radius-md);
background: var(--color-code-bg, var(--color-bg-raised));
border: var(--border-width) solid var(--color-border);
overflow-x: auto;
}
.markdown code {
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.92em;
}
.markdown :not(pre) > code {
padding: 0.12em 0.4em;
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--color-bg-raised) 60%, var(--color-secondary) 40%);
border: 1px solid var(--color-border);
}
.markdown table {
width: 100%;
border-collapse: collapse;
margin: 0 0 var(--space-3);
}
.markdown th,
.markdown td {
border: var(--border-width) solid var(--color-border);
padding: var(--space-2) var(--space-3);
text-align: left;
vertical-align: top;
}
.markdown th {
background: color-mix(in srgb, var(--color-bg-raised) 85%, var(--color-secondary) 15%);
}
.markdown a {
color: var(--color-link);
}
.markdown a:hover {
color: var(--color-link-hover);
}
.markdown hr {
border: 0;
border-top: var(--border-width) solid var(--color-border);
margin: var(--space-4) 0;
}
@@ -0,0 +1,16 @@
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import styles from './MarkdownContent.module.css';
export interface MarkdownContentProps {
content: string;
className?: string;
}
export function MarkdownContent({ content, className }: MarkdownContentProps) {
return (
<div className={`${styles.markdown}${className ? ` ${className}` : ''}`}>
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
.overlay {
position: fixed;
inset: 0;
z-index: 2000;
background: color-mix(in srgb, #000 45%, transparent);
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4);
}
.dialog {
width: min(520px, 100%);
background-color: var(--color-bg-subtle, #ffffff);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
overflow: hidden;
}
.header {
padding: var(--space-4) var(--space-5) var(--space-2);
}
.title {
margin: 0;
font-size: var(--font-size-md);
color: var(--color-text);
}
.body {
padding: var(--space-2) var(--space-5) var(--space-4);
color: var(--color-text-muted);
}
.footer {
padding: var(--space-3) var(--space-5) var(--space-4);
display: flex;
justify-content: flex-end;
gap: var(--space-2);
}
+41
View File
@@ -0,0 +1,41 @@
import { useEffect } from 'react';
import styles from './Modal.module.css';
export interface ModalProps {
open: boolean;
title: string;
children?: React.ReactNode;
onClose: () => void;
footer?: React.ReactNode;
}
export function Modal({ open, title, children, onClose, footer }: ModalProps) {
useEffect(() => {
if (!open) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [open, onClose]);
if (!open) return null;
return (
<div className={styles.overlay} role="presentation" onClick={onClose}>
<div
className={styles.dialog}
role="dialog"
aria-modal="true"
aria-label={title}
onClick={(event) => event.stopPropagation()}
>
<div className={styles.header}>
<h3 className={styles.title}>{title}</h3>
</div>
<div className={styles.body}>{children}</div>
{footer && <div className={styles.footer}>{footer}</div>}
</div>
</div>
);
}
+36
View File
@@ -0,0 +1,36 @@
.root {
display: inline-flex;
align-items: center;
gap: var(--space-2);
padding: 5px var(--space-3);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-full);
background: var(--color-bg-subtle);
transition: border-color var(--transition), background var(--transition);
}
.root:focus-within {
border-color: var(--color-primary);
background: var(--color-bg);
}
.icon {
color: var(--color-text-muted);
flex-shrink: 0;
display: block;
}
.input {
border: none;
background: transparent;
color: var(--color-text);
font-family: var(--font-family);
font-size: var(--font-size-xs);
outline: none;
width: 180px;
min-width: 0;
}
.input::placeholder {
color: var(--color-text-muted);
}
+23
View File
@@ -0,0 +1,23 @@
import { Search as SearchIcon } from 'lucide-react';
import styles from './Search.module.css';
export interface SearchProps {
value: string;
onChange: (value: string) => void;
placeholder?: string;
}
export function Search({ value, onChange, placeholder = 'Search…' }: SearchProps) {
return (
<div className={styles.root}>
<SearchIcon size={13} className={styles.icon} />
<input
className={styles.input}
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
/>
</div>
);
}
+4 -3
View File
@@ -79,10 +79,11 @@
/* ── Chevron rotation ────────────────────────────────────── */
.chevron {
transition: transform 220ms ease;
/* Points right (→) by default = collapse direction */
transform: rotate(180deg);
/* Points left (←) by default = collapse direction */
}
.collapsed .chevron {
transform: rotate(180deg);
/* Points left (←) = expand direction */
transform: rotate(0deg);
/* Points right (→) = expand direction */
}
+35 -1
View File
@@ -19,12 +19,46 @@
padding: var(--space-3) var(--space-4);
font-weight: 700;
font-size: var(--font-size-xs);
color: var(--color-secondary-fg);
color: #ffffff;
text-transform: uppercase;
letter-spacing: 0.06em;
border-bottom: var(--border-width) solid var(--color-secondary-border);
white-space: nowrap;
background: var(--color-secondary-fg);
}
.thContent {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
.thSortable {
cursor: pointer;
user-select: none;
}
.thSortable:hover {
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
}
.sortIcon {
opacity: 0.4;
flex-shrink: 0;
}
.sortIconActive {
opacity: 1;
color: var(--color-primary);
}
[data-theme="dark"] .th {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
[data-theme="dark"] .thSortable:hover {
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
}
/* Rounded top corners on first/last header cells */
+150 -45
View File
@@ -1,13 +1,18 @@
import { useState, type ReactNode } from 'react';
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
import { Pagination } from '../Pagination/Pagination';
import styles from './Table.module.css';
export type SortDirection = 'asc' | 'desc';
export interface TableColumn<T> {
key: string;
header: ReactNode;
render: (row: T) => ReactNode;
width?: string | number;
align?: 'left' | 'center' | 'right';
/** If true, a sort icon is shown and clicking the header triggers onSort */
sortable?: boolean;
}
export interface TableProps<T> {
@@ -17,12 +22,32 @@ export interface TableProps<T> {
loading?: boolean;
emptyMessage?: string;
className?: string;
/** Enable built-in client-side pagination with this default page size */
/**
* Client-side pagination: pass a default page size to enable.
* For server-side pagination use `total` + `page` + `onPageChange` instead.
*/
pageSize?: number;
/** Offer a page-size selector when pagination is enabled */
pageSizeOptions?: number[];
/** Called when a row is clicked */
onRowClick?: (row: T) => void;
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
/** Currently sorted column key (controlled) */
sortBy?: string;
/** Current sort direction (controlled) */
sortDir?: SortDirection;
/** Called when the user clicks a sortable column header */
onSort?: (key: string, dir: SortDirection) => void;
// ── Server-side pagination (controlled) ──────────────────────────────────
/** Total record count from server. Presence switches to server-side pagination mode. */
total?: number;
/** Controlled current page (1-based). Required when `total` is set. */
page?: number;
/** Called when the user navigates to a new page. Required when `total` is set. */
onPageChange?: (page: number) => void;
/** Called when the user changes page size. Optional for server-side pagination. */
onPageSizeChange?: (size: number) => void;
}
export function Table<T>({
@@ -35,34 +60,75 @@ export function Table<T>({
pageSize: defaultPageSize,
pageSizeOptions,
onRowClick,
getRowProps,
sortBy,
sortDir,
onSort,
total,
page: controlledPage,
onPageChange,
onPageSizeChange,
}: TableProps<T>) {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
const [internalPage, setInternalPage] = useState(1);
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
const paginated = defaultPageSize !== undefined && !loading;
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
const serverMode = total !== undefined;
// Reset to page 1 when data changes and current page would be empty
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
const safePage = Math.min(page, Math.max(1, lastPage));
const handleSortClick = (key: string) => {
if (!onSort) return;
const nextDir: SortDirection = sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
onSort(key, nextDir);
};
// Client-side pagination
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
const visibleData = clientPaginated
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
: data;
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
// Server-side pagination display values
const serverPage = controlledPage ?? 1;
const serverTotal = total ?? 0;
return (
<div className={`${styles.wrapper} ${className ?? ''}`}>
<table className={styles.table}>
<thead>
<tr>
{columns.map((col) => (
<th
key={col.key}
className={styles.th}
style={{
width: col.width,
textAlign: col.align ?? 'left',
}}
>
{col.header}
</th>
))}
{columns.map((col) => {
const isSorted = col.sortable && sortBy === col.key;
const SortIcon = isSorted ? (sortDir === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown;
return (
<th
key={col.key}
className={[styles.th, col.sortable ? styles.thSortable : '']
.filter(Boolean)
.join(' ')}
style={{
width: col.width,
textAlign: col.align ?? 'left',
}}
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
>
<span className={styles.thContent}>
{col.header}
{col.sortable && (
<SortIcon
size={12}
className={[styles.sortIcon, isSorted ? styles.sortIconActive : '']
.filter(Boolean)
.join(' ')}
aria-hidden="true"
/>
)}
</span>
</th>
);
})}
</tr>
</thead>
<tbody>
@@ -79,40 +145,79 @@ export function Table<T>({
</td>
</tr>
) : (
visibleData.map((row) => (
<tr
key={rowKey(row)}
className={[styles.tr, onRowClick ? styles.clickable : '']
.filter(Boolean)
.join(' ')}
onClick={onRowClick ? () => onRowClick(row) : undefined}
>
{columns.map((col) => (
<td
key={col.key}
className={styles.td}
style={{ textAlign: col.align ?? 'left' }}
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
>
{col.render(row)}
</td>
))}
</tr>
))
visibleData.map((row) => {
const rowProps = getRowProps?.(row);
const mergedClassName = [
styles.tr,
onRowClick ? styles.clickable : '',
rowProps?.className ?? '',
]
.filter(Boolean)
.join(' ');
const handleClick = (event: MouseEvent<HTMLTableRowElement>) => {
rowProps?.onClick?.(event);
if (!event.defaultPrevented) {
onRowClick?.(row);
}
};
return (
<tr
key={rowKey(row)}
{...rowProps}
className={mergedClassName}
onClick={onRowClick || rowProps?.onClick ? handleClick : undefined}
>
{columns.map((col) => (
<td
key={col.key}
className={styles.td}
style={{ textAlign: col.align ?? 'left' }}
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
>
{col.render(row)}
</td>
))}
</tr>
);
})
)}
</tbody>
</table>
{paginated && data.length > 0 && (
{serverMode && serverTotal > 0 && onPageChange && (
<Pagination
page={safePage}
page={serverPage}
pageSize={pageSize}
total={serverTotal}
onPageChange={onPageChange}
onPageSizeChange={
onPageSizeChange
? (size) => {
setPageSize(size);
onPageSizeChange(size);
}
: pageSizeOptions
? (size) => {
setPageSize(size);
onPageChange(1);
}
: undefined
}
pageSizeOptions={pageSizeOptions}
/>
)}
{clientPaginated && data.length > 0 && (
<Pagination
page={safeInternalPage}
pageSize={pageSize}
total={data.length}
onPageChange={setPage}
onPageChange={setInternalPage}
onPageSizeChange={
pageSizeOptions
? (size) => {
setPageSize(size);
setPage(1);
setInternalPage(1);
}
: undefined
}
@@ -0,0 +1,60 @@
.wrapper {
display: flex;
flex-direction: column;
gap: var(--space-1);
font-family: var(--font-family);
width: 100%;
}
.label {
font-size: var(--font-size-sm);
font-weight: 500;
color: var(--color-text);
}
.textarea {
font-family: var(--font-family-mono, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
padding: var(--space-2) var(--space-3);
width: 100%;
outline: none;
resize: vertical;
transition: border-color var(--transition), box-shadow var(--transition);
}
.textarea::placeholder {
color: var(--color-text-muted);
}
.textarea:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}
.textarea:disabled {
opacity: 0.5;
cursor: not-allowed;
background: var(--color-bg-subtle);
}
.hasError {
border-color: var(--color-error-fg);
}
.hasError:focus {
border-color: var(--color-error-fg);
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
}
.hint {
font-size: var(--font-size-xs);
color: var(--color-text-muted);
}
.error {
font-size: var(--font-size-xs);
color: var(--color-error-fg);
}
+42
View File
@@ -0,0 +1,42 @@
import React, { useId } from 'react';
import styles from './Textarea.module.css';
export interface TextareaProps extends Omit<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
'id'
> {
label?: string;
hint?: string;
error?: string;
}
export function Textarea({ label, hint, error, className, ...props }: TextareaProps) {
const id = useId();
return (
<div className={styles.wrapper}>
{label && (
<label htmlFor={id} className={styles.label}>
{label}
</label>
)}
<textarea
id={id}
className={[styles.textarea, error ? styles.hasError : '', className]
.filter(Boolean)
.join(' ')}
aria-describedby={error ? `${id}-error` : hint ? `${id}-hint` : undefined}
aria-invalid={error ? true : undefined}
{...props}
/>
{error ? (
<span id={`${id}-error`} className={styles.error} role="alert">
{error}
</span>
) : hint ? (
<span id={`${id}-hint`} className={styles.hint}>
{hint}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,87 @@
.viewport {
position: fixed;
top: var(--space-4);
right: var(--space-4);
z-index: 2000;
display: flex;
flex-direction: column;
gap: var(--space-2);
width: min(380px, calc(100vw - (var(--space-4) * 2)));
pointer-events: none;
}
.toast {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-3);
border-radius: var(--radius-md);
border: var(--border-width) solid var(--color-border);
background: var(--color-bg-subtle);
box-shadow: var(--shadow-md);
pointer-events: auto;
opacity: 1;
transform: translateX(0) scale(1);
transition: opacity 100ms ease, transform 100ms ease;
}
.leaving {
opacity: 0;
transform: translateX(8px) scale(0.98);
pointer-events: none;
}
.content {
display: flex;
align-items: flex-start;
gap: var(--space-2);
min-width: 0;
}
.icon {
margin-top: 1px;
flex-shrink: 0;
}
.message {
margin: 0;
font-size: var(--font-size-sm);
line-height: 1.4;
color: var(--color-text);
overflow-wrap: anywhere;
}
.close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: none;
background: transparent;
border-radius: var(--radius-sm);
color: var(--color-text-muted);
cursor: pointer;
flex-shrink: 0;
}
.close:hover {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
.success {
border-color: color-mix(in srgb, var(--color-primary) 50%, var(--color-border));
background: var(--color-success-bg);
}
.error {
border-color: color-mix(in srgb, var(--color-danger) 50%, var(--color-border));
background: var(--color-error-bg);
}
.info {
border-color: color-mix(in srgb, var(--color-secondary-fg) 35%, var(--color-border));
background: var(--color-info-bg);
}
+102
View File
@@ -0,0 +1,102 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import styles from './ToastProvider.module.css';
import { subscribeApiErrorToasts } from '../../lib/toast-events';
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
interface ToastItem {
id: number;
message: string;
variant: ToastVariant;
closing: boolean;
}
const ICONS: Record<ToastVariant, React.ReactNode> = {
success: <CheckCircle2 size={16} />,
error: <AlertCircle size={16} />,
info: <Info size={16} />,
};
export interface ToastProviderProps {
children: React.ReactNode;
durationMs?: number;
}
export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProps) {
const EXIT_ANIMATION_MS = 100;
const [items, setItems] = useState<ToastItem[]>([]);
const lastShownAtRef = useRef<Map<string, number>>(new Map());
const remove = useCallback((id: number) => {
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
const dismiss = useCallback(
(id: number) => {
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
},
[remove],
);
const show = useCallback(
(message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
},
[dismiss, durationMs],
);
const api = useMemo<ToastApi>(
() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}),
[show],
);
useEffect(() => {
return subscribeApiErrorToasts((message) => api.error(message));
}, [api]);
return (
<ToastContext.Provider value={api}>
{children}
<div className={styles.viewport} aria-live="polite" aria-atomic="true">
{items.map((item) => (
<div
key={item.id}
className={[styles.toast, styles[item.variant], item.closing ? styles.leaving : '']
.filter(Boolean)
.join(' ')}
role="status"
>
<div className={styles.content}>
<span className={styles.icon} aria-hidden="true">
{ICONS[item.variant]}
</span>
<p className={styles.message}>{item.message}</p>
</div>
<button
type="button"
className={styles.close}
aria-label="Dismiss notification"
onClick={() => dismiss(item.id)}
>
<X size={14} />
</button>
</div>
))}
</div>
</ToastContext.Provider>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { createContext } from 'react';
export type ToastVariant = 'success' | 'error' | 'info';
export interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
export const ToastContext = createContext<ToastApi | null>(null);
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { ToastContext, type ToastApi } from './toast-context';
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
@@ -0,0 +1,38 @@
.wrapper {
display: inline-flex;
align-items: center;
position: relative;
}
.button {
all: unset;
cursor: pointer;
font: inherit;
color: inherit;
letter-spacing: 0.02em;
}
.button:focus-visible {
outline: 2px solid var(--color-focus-ring);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
.pop {
position: absolute;
left: calc(100% + 4px);
top: 50%;
transform: translateY(-50%);
display: inline-flex;
align-items: center;
color: var(--color-success-fg);
animation: popFade 1s ease forwards;
pointer-events: none;
}
@keyframes popFade {
0% { opacity: 0; transform: translateY(calc(-50% - 4px)); }
20% { opacity: 1; transform: translateY(-50%); }
70% { opacity: 1; transform: translateY(-50%); }
100% { opacity: 0; transform: translateY(calc(-50% - 4px)); }
}
+36
View File
@@ -0,0 +1,36 @@
import { useState } from 'react';
import { ClipboardCheck } from 'lucide-react';
import { Badge } from '../Badge/Badge';
import styles from './UuidBadge.module.css';
export interface UuidBadgeProps {
id: string;
}
export function UuidBadge({ id }: UuidBadgeProps) {
const [copied, setCopied] = useState(false);
const short = `${id.slice(0, 4)}…${id.slice(-4)}`;
const handleClick = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(id).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1000);
});
};
return (
<span className={styles.wrapper} title={copied ? 'Copied!' : id}>
<Badge variant="neutral">
<button type="button" className={styles.button} onClick={handleClick}>
{short}
</button>
</Badge>
{copied && (
<span className={styles.pop} aria-hidden="true">
<ClipboardCheck size={13} />
</span>
)}
</span>
);
}
+29 -1
View File
@@ -1,3 +1,6 @@
export { AutoRefreshIndicator } from './AutoRefreshIndicator/AutoRefreshIndicator';
export type { AutoRefreshIndicatorProps } from './AutoRefreshIndicator/AutoRefreshIndicator';
export { Button } from './Button/Button';
export type { ButtonProps } from './Button/Button';
@@ -7,6 +10,9 @@ export type { BadgeProps, BadgeVariant } from './Badge/Badge';
export { Input } from './Input/Input';
export type { InputProps } from './Input/Input';
export { Textarea } from './Textarea/Textarea';
export type { TextareaProps } from './Textarea/Textarea';
export { Select } from './Select/Select';
export type { SelectProps, SelectOption } from './Select/Select';
@@ -21,12 +27,28 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
export { useToast } from './Toast/useToast';
export { Timestamp } from './Timestamp/Timestamp';
export type { TimestampProps } from './Timestamp/Timestamp';
export { Pagination } from './Pagination/Pagination';
export type { PaginationProps } from './Pagination/Pagination';
export { Search } from './Search/Search';
export type { SearchProps } from './Search/Search';
export { CodeBlock } from './CodeBlock/CodeBlock';
export type { CodeBlockProps } from './CodeBlock/CodeBlock';
export { CodeEditor } from './CodeEditor/CodeEditor';
export type { CodeEditorProps } from './CodeEditor/CodeEditor';
export { MarkdownContent } from './MarkdownContent/MarkdownContent';
export type { MarkdownContentProps } from './MarkdownContent/MarkdownContent';
export { ContextMenu } from './ContextMenu/ContextMenu';
export type { ContextMenuProps, ContextMenuItem } from './ContextMenu/ContextMenu';
@@ -36,5 +58,11 @@ export type { DescriptionListProps, DescriptionListItem } from './DescriptionLis
export { Notification } from './Notification/Notification';
export type { NotificationProps, NotificationVariant } from './Notification/Notification';
export { Modal } from './Modal/Modal';
export type { ModalProps } from './Modal/Modal';
export { Table } from './Table/Table';
export type { TableProps, TableColumn } from './Table/Table';
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
export { UuidBadge } from './UuidBadge/UuidBadge';
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
+2 -1
View File
@@ -74,7 +74,8 @@
--border-width: 1.5px;
/* Shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.06);
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.08), 0 0px 1px rgba(0, 0, 0, 0.04);
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.06);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -1px rgba(0, 0, 0, 0.04);
/* Transitions */
-1
View File
@@ -1 +0,0 @@
{"root":["./src/App.tsx","./src/main.tsx"],"version":"5.8.3"}
+81 -7
View File
@@ -1,22 +1,96 @@
/// <reference types="vitest/config" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import { playwright } from '@vitest/browser-playwright';
const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
const rootPackageJsonPath = path.resolve(dirname, '../package.json');
const APP_VERSION = (() => {
try {
const json = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf8')) as {
version?: string;
};
return json.version ?? 'dev';
} catch {
return 'dev';
}
})();
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify(APP_VERSION),
},
plugins: [react()],
server: {
proxy: {
'/environments': 'http://localhost:13000',
'/sessions': 'http://localhost:13000',
'/scenarios': 'http://localhost:13000',
'/keys': 'http://localhost:13000',
'/login': 'http://localhost:13000',
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (!id.includes('/client/src/') && !id.includes('/node_modules/')) {
return;
}
if (id.includes('/node_modules/lucide-react')) {
return 'icons';
}
if (id.includes('/node_modules/monaco-editor') || id.includes('/node_modules/@monaco-editor')) {
return 'editor';
}
if (
id.includes('/node_modules/react-markdown')
|| id.includes('/node_modules/remark-')
|| id.includes('/node_modules/rehype-')
|| id.includes('/node_modules/unified')
|| id.includes('/node_modules/micromark')
|| id.includes('/node_modules/mdast-')
|| id.includes('/node_modules/hast-')
|| id.includes('/node_modules/unist-')
|| id.includes('/node_modules/vfile')
) {
return 'markdown';
}
if (
id.includes('/node_modules/i18next')
|| id.includes('/node_modules/react-i18next')
) {
return 'i18n';
}
if (id.includes('/node_modules/moment')) {
return 'datetime';
}
if (id.includes('/node_modules/yaml')) {
return 'yaml';
}
if (id.includes('/node_modules/')) {
return 'vendor';
}
if (id.includes('/src/pages/environment/')) {
return 'environments';
}
if (id.includes('/src/pages/scenario/')) {
return 'scenarios';
}
if (id.includes('/src/pages/run/')) {
return 'runs';
}
if (id.includes('/src/pages/snippet/')) {
return 'snippets';
}
if (id.includes('/src/pages/credential/')) {
return 'credentials';
}
if (id.includes('/src/pages/session/')) {
return 'sessions';
}
if (id.includes('/src/api/')) {
return 'api';
}
},
},
},
},
test: {
+2 -2
View File
@@ -1,8 +1,8 @@
services:
server:
build:
context: ./server
dockerfile: Dockerfile
context: .
dockerfile: server/Dockerfile
ports:
- "13000:3000"
env_file:
+35 -35
View File
@@ -1,45 +1,43 @@
# Architecture
```
┌─────────────────────────────────────────┐
│ Browser (React SPA — client/) │
│ │
│ EnvironmentsPage KeysPage │
│ SessionsPage ScenariosPage │
└───────────────────┬─────────────────────┘
│ HTTP REST (:13000)
│
┌──────────────────────────────────────────────────────┐
│ Browser (React SPA - client/) │
│ │
│ Environments Credentials Snippets │
│ Sessions Scenarios Runs │
└─────────────────────────────┬────────────────────────┘
│ HTTP REST (:13000)
│
MCP client (AI agent / VS Code Copilot)
│ HTTP /mcp (Streamable MCP)
│ HTTP /mcp (Streamable MCP)
▼
┌──────────────────────────────────────┐
│ NestJS app (server/src/) │
│ │
│ McpService ← all MCP tools │
│ │
│ AuthService login + sessions │
│ SessionService session CRUD │
│ EnvironmentService environment CRUD │
│ BrowserService ad-hoc browsing │
│ CodeExecutorService sandboxed JS │
│ │
│ ScenarioService scenario CRUD │
│ ScenarioSchedulerService │
│ └─ @Interval(1 s) tick loop │
└──────────────────┬───────────────────┘
│ better-sqlite3 (TypeORM)
▼
data/sessions.db
┌──────────────────────────────────────────────────────┐
│ NestJS app (server/src/) │
│ │
│ McpService all MCP tools │
│ SessionService session persistence │
│ SessionContextService live browser contexts │
│ EnvironmentService environment CRUD + import │
│ CredentialService credential CRUD + import │
│ SnippetService snippet CRUD + import │
│ BrowserService ad-hoc open/exec │
│ CodeExecutorService sandboxed JS runtime │
│ ScenarioService scenarios/steps/runs CRUD │
│ ScenarioSchedulerService @Interval(1 s) run worker │
└───────────────────────┬──────────────────────────────┘
│ better-sqlite3 (TypeORM)
▼
data/sessions.db
```
- **McpService** — registers every MCP tool and delegates to domain services.
- **AuthService** — drives a Playwright browser to log in via a key descriptor; saves cookies + localStorage as a `Session`.
- **SessionService** — stores and retrieves saved browser sessions.
- **EnvironmentService** — stores named environments (URL maps) used by auth and scenarios.
- **BrowserService** — ad-hoc, stateless `open_url` / `exec_code` operations outside the scenario scheduler.
- **CodeExecutorService** — compiles and runs user-supplied Playwright JS inside a sandboxed `async` function with `page`, `context`, and `helpers` in scope.
- **ScenarioService** — CRUD for scenarios, steps, runs, and run logs; import/export.
- **ScenarioSchedulerService** — polls for pending step runs every second and executes them. All steps in the same run share **one browser instance** (see [scenario.md](scenario.md)).
- **McpService** registers MCP tools and delegates to session, environment, browser, and scenario services.
- **SessionService** persists session records in SQLite. **SessionContextService** manages live Playwright contexts for open sessions.
- **EnvironmentService**, **CredentialService**, and **SnippetService** provide CRUD plus import/export upserts.
- **BrowserService** handles stateless ad-hoc automation (`/open`, `/exec`) and session-aware browsing.
- **CodeExecutorService** validates and executes user JS with `page`, `context`, and helper APIs.
- **ScenarioService** manages scenarios, steps, credential aliases, runs, logs, and scenario import/export.
- **ScenarioSchedulerService** polls pending runs every second and executes step runs to completion.
## Client (`client/`)
@@ -47,4 +45,6 @@ A React 19 + TypeScript SPA served separately by Vite during development. In Doc
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses HashRouter so the Vite proxy and server-side routes are never ambiguous.
The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
See [development.md](development.md) for the full client tech stack and directory layout.
+20 -8
View File
@@ -26,8 +26,10 @@ Copy `.env.example` to `.env` and fill in the required values before running.
| Variable | Default | Description |
|---|---|---|
| `PORT` | `3000` | HTTP port |
| `KEYS_DIR` | `keys` | Directory containing `*.json` key descriptors |
| `KEYS_DIR` | `keys` | Directory for key material used by credential/snippet workflows |
| `DB_PATH` | `data/sessions.db` | SQLite database file |
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to Chromium binary. Set automatically in Docker (`/usr/bin/chromium`). |
---
@@ -59,7 +61,13 @@ The server listens on port **3000** by default.
npm -w client run dev
```
The Vite dev server runs on **http://localhost:5173** and proxies all API paths (`/environments`, `/sessions`, `/scenarios`, `/keys`, `/login`, `/mcp`) to the server at `localhost:3000`.
The Vite dev server runs on **http://localhost:5173** and proxies these API prefixes to `localhost:13000` (or `localhost:3000` when running server locally):
- `/environments`
- `/credentials`
- `/snippets`
- `/sessions`
- `/scenarios`
**Production build**:
@@ -201,7 +209,7 @@ docker compose logs -f
## Client overview
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, sessions, keys, and scenarios.
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, credentials, snippets, sessions, scenarios, and runs.
### Tech stack
@@ -221,11 +229,11 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
```
client/
src/
api/ API client modules (environments, keys, sessions, scenarios)
api/ API client modules (environments, credentials, snippets, sessions, scenarios)
hooks/ useTheme (light/dark persistence)
i18n/ i18next bootstrap + locales/en.json
pages/ EnvironmentsPage, KeysPage, SessionsPage, ScenariosPage
ui/ Reusable component library
pages/ Environment/Credential/Snippet/Session/Scenario/Run pages
ui/ Reusable component library
Badge, Breadcrumbs, Button, Card, Input, Select,
SidePanel, Table, ThemeSwitcher, Timestamp
.storybook/
@@ -239,10 +247,14 @@ Hash-based routing (`/#/path`) avoids conflicts with the Vite dev-server proxy.
| Route | Page |
|---|---|
| `/#/environments` | Environment list |
| `/#/keys` | Key list |
| `/#/credentials` | Credential list |
| `/#/snippets` | Snippet list |
| `/#/sessions` | Session list |
| `/#/scenarios` | Scenario list |
| `/#/runs` | Cross-scenario runs list |
### Theming
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar header. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar footer. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
The sidebar footer also shows the app version read from the workspace root `package.json` and injected via Vite `define`.
-20
View File
@@ -1,20 +0,0 @@
# Key descriptors
Each file in `KEYS_DIR` is named `<keyId>.json` and takes one of two forms:
**File key (EDS):**
```json
{
"keyFile": "path/to/key.dat",
"password": "secret"
}
```
`keyFile` is resolved relative to `KEYS_DIR`.
**Login + password:**
```json
{
"login": "user@example.com",
"password": "secret"
}
```
+57 -28
View File
@@ -1,49 +1,78 @@
# MCP tools
## Auth / session
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport).
The server currently registers the following tools.
## Sessions
| Tool | Description |
|---|---|
| `list_keys` | List available key IDs from `KEYS_DIR` |
| `login` | Log in with a key against an environment; stores resulting session |
| `list_sessions` | Paginated list of saved sessions |
| `delete_session` | Delete a session by ID |
| `list_sessions` | List stored sessions (paginated) |
| `delete_session` | Delete a session by UUID |
## Environments
| Tool | Description |
|---|---|
| `list_environments` | Paginated list of environments |
| `get_environment` | Get one environment by ID |
| `create_environment` | Create an environment (`name` + `urls` map) |
| `update_environment` | Update name / urls |
| `delete_environment` | Delete by ID |
| `list_environments` | List environments (paginated) |
| `get_environment` | Get one environment by UUID |
| `create_environment` | Create environment (`name`, `urls`) |
| `update_environment` | Update environment (`id`, optional `name`/`urls`) |
| `delete_environment` | Delete environment by UUID |
`urls` is a free-form map. Recognised keys: `id_url` (auth server), `cabinet_url` (cabinet redirect target), `admin_url`.
`urls` is a free-form key/value map. Common keys: `id_url`, `cabinet_url`, `admin_url`.
## Browser (ad-hoc, stateless)
## Browser (ad-hoc)
| Tool | Description |
|---|---|
| `open_url` | Navigate to a URL and return page content / reader-mode text |
| `exec_code` | Run Playwright JS in a session's browser context |
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
| `exec_code` | Execute Playwright JS — script receives a single `context` argument (see `scenario.md`). Optional `environmentId` (UUID) resolves environment from DB for `context.getEnv()`. Optional `credentials` (`{ alias: credentialUUID }`) resolves credentials from DB for `context.getCredential(alias)`. |
## Scenarios
| Tool | Description |
|---|---|
| `list_scenarios` | Paginated list |
| `get_scenario` | Fetch scenario with all steps |
| `create_scenario` | Create a new scenario by name |
| `update_scenario` | Rename |
| `delete_scenario` | Delete (cascades to steps and runs) |
| `create_scenario_step` | Add a step |
| `get_scenario_step` | Fetch one step |
| `list_scenarios` | List scenarios (paginated) |
| `get_scenario` | Get scenario with steps |
| `create_scenario` | Create scenario by `name` |
| `update_scenario` | Rename scenario |
| `delete_scenario` | Delete scenario |
| `create_scenario_step` | Add step to scenario |
| `get_scenario_step` | Get one step |
| `update_scenario_step` | Update step fields |
| `delete_scenario_step` | Remove a step |
| `list_scenario_runs` | Paginated run history (with optional status filter) |
| `run_scenario` | Trigger an immediate run |
| `get_scenario_run` | Get a run with all step runs and their outputs |
| `wait_for_scenario_run` | Block until run reaches `pass`/`fail`, return full run |
| `export_scenario` | Export scenario as a portable JSON payload |
| `import_scenario` | Import a scenario from an export payload |
| `delete_scenario_step` | Delete step |
| `list_scenario_runs` | List runs for a scenario |
| `run_scenario` | Trigger run for scenario |
| `get_scenario_run` | Get run with step runs and logs |
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
| `export_scenario` | Export scenario payload |
| `import_scenario` | Import scenario payload |
## Scenario Files
| Tool | Description |
|---|---|
| `upload_scenario_file` | Upload a file to a scenario; accepts optional `expiresAt` (ISO 8601 date string) |
| `list_scenario_files` | List scenario files (paginated) |
| `get_scenario_file_content` | Retrieve file content as base64 with metadata |
## Run Artifact Files
| Tool | Description |
|---|---|
| `list_run_files` | List files (artifacts) created during a scenario run (paginated) |
| `get_run_file_content` | Retrieve run artifact content as base64 with metadata; run artifacts are read-only and inherit expiry from the run artifact subsystem |
## Binary Content Handling
File tools transport binary payloads as base64-encoded strings in a `contentBase64` field with an accompanying `encoding: "base64"` marker in the response. When retrieving file content via `get_scenario_file_content` or `get_run_file_content`, decode the base64 to recover the original bytes.
Scenario files uploaded via `upload_scenario_file` must have their content pre-encoded as base64. Run artifacts are created implicitly through scenario execution (via `context.downloadFile()` during step execution) and cannot be uploaded via MCP.
## Notes
- Tool IDs and entity IDs are UUIDs.
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
+75 -54
View File
@@ -1,80 +1,101 @@
# Scenario execution
When a scenario is run, the scheduler creates a `ScenarioRun` with one `ScenarioRunStep` per step. Steps are executed **in order** (by `step.order`), one per scheduler tick.
When a scenario run is created, the server creates one `ScenarioRunStep` per scenario step.
**All steps in the same run share a single Playwright browser instance.** The browser is created on the first `exec` or `sign` step (using session cookies + localStorage), reused for every subsequent step, and closed when the run finishes (pass or fail).
- Step runs are ordered by `step.order`.
- First step run starts as `pending`; the rest start as `waiting`.
- Scheduler tick (`@Interval(1000)`) picks pending runs and processes steps in order.
- Steps in the same run share one Playwright browser/context/page.
## Step types
## Execution model
### `login`
Current scheduler behavior is exec-centric:
Authenticates in a **separate, ephemeral browser** and saves the resulting session to the database. Subsequent exec/sign steps load that session into the shared browser.
- `execCode` is required for a step to pass.
- `validateCode` is optional and runs after `execCode`.
- Legacy step type metadata may still appear in MCP payloads, but run execution is not branched by step type.
`execCode` must be a JSON object:
```json
{ "keyId": "3137411915", "environmentName": "liquio-diia-stg" }
```
## Script runtime
### `exec`
Runs arbitrary Playwright JS on the **shared page**. The page carries over state from the previous step (URL, form inputs, cookies, etc.).
`execCode` is executed as the body of an `async` function with these variables in scope:
- `page` — current Playwright `Page`
- `context` — current Playwright `BrowserContext`
- `helpers.dumpDom(selector?)` — returns a simplified DOM string
- `helpers.getStepOutput(order)` — returns the JSON-parsed `output` of a previous step. Positive values are absolute step orders; negative values are relative to the current step (`-1` = previous step).
Any value returned from `execCode` is JSON-serialised and stored as the `output` field on the `ScenarioRunStep` record. Subsequent steps can read it via `helpers.getStepOutput()`.
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
```js
// example execCode
await page.goto('https://cabinet.example.com/tasks/create/987825');
await page.locator('input[name="institution"]').fill('caltech');
await page.locator('button:has-text("Далі")').click();
await page.waitForLoadState('networkidle');
return page.url(); // stored in ScenarioRunStep.output
async (context) => {
// your code here
}
```
### `sign`
Available in scope:
Performs EDS signing on the **current shared page** using a key from `KEYS_DIR`. The step clicks the sign widget, selects the file key method, uploads the key file, enters the password, and submits — all without requiring the step author to handle key material in their code.
- `context.page`: Playwright `Page`
- `context.browser`: Playwright `BrowserContext`
- `context.env`: shallow copy of environment key/value map
- `context.getEnv(key)`: required environment value lookup (throws if missing)
- `context.getCredential(alias)`: credential payload assigned to the scenario alias
- `context.getStepOutput(order)`: prior step output by absolute order (`1`, `2`, ...) or relative (`-1` = previous step)
- `context.dumpDom(selector?)`: simplified DOM snapshot
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: structured step logs
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`)
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run artifact (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
`execCode` must be a JSON object:
```json
{ "keyId": "3137411915" }
```
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
## Validation code
## Playwright traces
Any step type optionally accepts `validateCode` — Playwright JS that runs on the shared page **after** the main action and must return a result evaluated as:
Each run records a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
The trace mode is chosen per run: the run modal in the UI, the `traceMode` field of `POST /scenarios/:id/run`, and the `traceMode` argument of the `run_scenario` MCP tool all accept one of the values below. When it is omitted, the server's `PLAYWRIGHT_TRACE_MODE` setting is used (exposed via `GET /scenarios/run-defaults`). "Repeat run" reuses the original run's mode.
- `on` (default): keep the trace of every run
- `retain-on-failure`: keep traces only for runs that failed
- `off`: do not record traces
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
## Validation contract
`validateCode` may return:
```js
return { success: true, description: 'Application created' };
return { success: true, description: 'ok' };
// or
return { success: false, description: 'Expected success banner not found' };
// or simply
return someBoolean;
return false;
```
If `success` is false the step (and the whole run) fails with the provided `description`.
Interpretation:
## Run statuses
- Boolean: `true` = pass, `false` = fail
- Object: `success` controls pass/fail; `description` is persisted as step description
`pending` → `in_progress` → `pass` | `fail`
On validation failure, the step fails and the run is marked `fail`.
Individual step runs also expose `waiting` (not yet reached) and `cancelled` (run failed before this step).
## Statuses
## Adding a new scenario (example workflow)
Run status:
```
1. create_environment (if not already present)
2. create_scenario → get scenarioId
3. create_scenario_step type=login, order=0
4. create_scenario_step type=exec, order=1 (navigate + fill form)
5. create_scenario_step type=sign, order=2
6. create_scenario_step type=exec, order=3 (validateCode checks success banner)
7. run_scenario → get runId
8. wait_for_scenario_run (blocks until pass/fail, returns full run with outputs)
```
- `pending`
- `in_progress`
- `pass`
- `fail`
Run-step status:
- `waiting`
- `pending`
- `in_progress`
- `pass`
- `fail`
- `cancelled`
## Example workflow
1. Create environment
2. Create credentials and snippets (optional but common)
3. Create scenario
4. Add ordered steps (`execCode`, optional `validateCode`)
5. Assign credentials to scenario aliases when needed
6. Run scenario
7. Wait for run completion and inspect run logs/outputs
+2305 -25
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more