Compare commits

...
55 Commits
Author SHA1 Message Date
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
174 changed files with 11027 additions and 13855 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
+10 -2
View File
@@ -1,5 +1,4 @@
# runtime / secrets
/keys
# runtime
/data
.env
*.log
@@ -13,3 +12,12 @@ server/dist
client/dist
*storybook.log
storybook-static
tsconfig.tsbuildinfo
# organization
TODO.md
# IDE/editor
.vscode/
.idea/
.github/
+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;
}
}
+7
View File
@@ -4,23 +4,30 @@
"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-markdown": "^10.1.0",
"react-router-dom": "^7.14.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.8.3"
},
"devDependencies": {
+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;
+146 -75
View File
@@ -1,43 +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, Activity, KeySquare, Braces } 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/environment/EnvironmentsPage';
import { EnvironmentDetailPage } from './pages/environment/EnvironmentDetailPage';
import { CreateEnvironmentPage } from './pages/environment/CreateEnvironmentPage';
import { EditEnvironmentPage } from './pages/environment/EditEnvironmentPage';
import { KeysPage } from './pages/KeysPage';
import { SessionsPage } from './pages/session/SessionsPage';
import { SessionDetailPage } from './pages/session/SessionDetailPage';
import { ScenariosPage } from './pages/scenario/ScenariosPage';
import { ScenarioDetailPage } from './pages/scenario/ScenarioDetailPage';
import { CreateScenarioPage } from './pages/scenario/CreateScenarioPage';
import { EditScenarioPage } from './pages/scenario/EditScenarioPage';
import { CreateStepPage } from './pages/scenario/CreateStepPage';
import { EditStepPage } from './pages/scenario/EditStepPage';
import { RunsPage } from './pages/run/RunsPage';
import { RunDetailPage } from './pages/run/RunDetailPage';
import { AllRunsPage } from './pages/run/AllRunsPage';
import { CredentialsPage } from './pages/credential/CredentialsPage';
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
import { SnippetsPage } from './pages/snippet/SnippetsPage';
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
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() {
@@ -49,56 +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/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 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>
);
+155 -45
View File
@@ -2,7 +2,8 @@ import type {
PaginatedResponse,
Credential,
Environment,
KeysResponse,
FileMetadata,
FileListResponse,
ScenarioCredential,
Session,
Scenario,
@@ -12,25 +13,47 @@ import type {
ScenarioStep,
Snippet,
} 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 ───────────────────────────────────────────────────────────────
@@ -77,13 +100,18 @@ export const snippets = {
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
create(
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(id: string, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
update(
id: string,
patch: Partial<Pick<Snippet, 'alias' | 'title' | 'description' | 'code'>>,
): Promise<Snippet> {
return request(`/snippets/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -112,13 +140,16 @@ export const environments = {
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: string, 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),
@@ -127,21 +158,27 @@ export const environments = {
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: string): Promise<Session> {
return request(`/sessions/${id}`);
@@ -154,19 +191,29 @@ 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: string): Promise<Scenario & { steps: ScenarioStep[] }> {
return request(`/scenarios/${id}`);
},
create(name: string): Promise<Scenario> {
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
return request('/scenarios', {
method: 'POST',
body: JSON.stringify({ name }),
body: JSON.stringify({ name, description, environmentId }),
});
},
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
update(
id: string,
patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>,
): Promise<Scenario> {
return request(`/scenarios/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -175,8 +222,11 @@ export const scenarios = {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: string): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, { method: 'POST' });
run(id: string, environmentId: string, saveSession?: boolean): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId, saveSession }),
});
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
@@ -184,11 +234,26 @@ export const scenarios = {
waitForRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}/wait`, { method: 'POST' });
},
listRuns(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
listRuns(
scenarioId: string,
page = 1,
limit = 20,
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
exportScenario(id: string): Promise<unknown> {
return request(`/scenarios/${id}/export`);
exportScenario(
id: string,
options: { includeEnvironment: boolean; credentialIds: string[] } = {
includeEnvironment: false,
credentialIds: [],
},
): Promise<string> {
const params = new URLSearchParams();
params.set('includeEnvironment', String(options.includeEnvironment));
for (const cid of options.credentialIds) {
params.append('credentialIds', cid);
}
return request(`/scenarios/${id}/export?${params.toString()}`);
},
importScenario(payload: unknown): Promise<Scenario> {
return request('/scenarios/import', {
@@ -201,16 +266,31 @@ export const scenarios = {
// ── Runs ─────────────────────────────────────────────────────────────────────
export const runs = {
listAll(page = 1, limit = 20, status?: string): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }>> {
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
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): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
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): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
},
};
@@ -236,18 +316,15 @@ export const scenarioCredentials = {
// ── Scenario Steps ────────────────────────────────────────────────────────────
export interface CreateStepPayload {
title?: string;
order: number;
type: 'login' | 'exec' | 'sign';
execCode?: string;
validateCode?: string;
timeoutSeconds?: number | null;
}
export interface UpdateStepPayload {
title?: string;
order?: number;
type?: 'login' | 'exec' | 'sign';
execCode?: string;
validateCode?: string;
timeoutSeconds?: number | null;
}
export const steps = {
@@ -270,3 +347,36 @@ export const steps = {
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
},
};
// ── Scenario Files ────────────────────────────────────────────────────────
export const scenarioFiles = {
upload(scenarioId: string, file: File, expiresAt?: Date): Promise<FileMetadata> {
const form = new FormData();
form.append('file', file);
if (expiresAt) form.append('expiresAt', expiresAt.toISOString());
return request(`/scenarios/${scenarioId}/files`, {
method: 'POST',
body: form,
});
},
list(scenarioId: string, limit = 20, offset = 0): Promise<FileListResponse> {
return request(`/scenarios/${scenarioId}/files?limit=${limit}&offset=${offset}`);
},
/** Returns a URL that can be used as an <a href> for direct download. */
contentUrl(scenarioId: string, fileId: string): string {
return `${BASE_URL}/scenarios/${scenarioId}/files/${fileId}/content`;
},
};
// ── Run Files ─────────────────────────────────────────────────────────────
export const runFiles = {
list(scenarioId: string, runId: string, limit = 20, offset = 0): Promise<FileListResponse> {
return request(`/scenarios/${scenarioId}/runs/${runId}/files?limit=${limit}&offset=${offset}`);
},
/** Returns a URL that can be used as an <a href> for direct download. */
contentUrl(scenarioId: string, runId: string, fileId: string): string {
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`;
},
};
+34 -17
View File
@@ -9,17 +9,15 @@ 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: string;
name: string;
urls: EnvironmentUrls;
description?: string;
data: EnvironmentData;
createdAt: string;
updatedAt: string;
}
@@ -39,19 +37,14 @@ export interface Credential {
export interface Snippet {
id: string;
name: string;
alias: string;
title: string;
description: string | null;
code: string;
createdAt: string;
updatedAt: string;
}
// ── Keys ──────────────────────────────────────────────────────────────────────
export interface KeysResponse {
keys: string[];
}
// ── Sessions ──────────────────────────────────────────────────────────────────
export type SessionStatus = 'open' | 'closed';
@@ -68,17 +61,13 @@ export interface Session {
// ── Scenarios ─────────────────────────────────────────────────────────────────
export type StepType = 'login' | 'exec' | 'sign';
export interface ScenarioStep {
id: string;
scenarioId: string;
order: number;
type: StepType;
title: string | null;
sessionName: string | null;
execCode: string | null;
validateCode: string | null;
timeoutSeconds: number | null;
createdAt: string;
updatedAt: string;
}
@@ -95,8 +84,14 @@ export interface ScenarioCredential {
export interface Scenario {
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;
}
@@ -110,7 +105,12 @@ export type LogLevel = 'log' | 'warn' | 'error';
export interface ScenarioRun {
id: string;
scenarioId: string;
environmentId: string;
sessionId?: string | null;
saveSession: boolean;
scenario?: Pick<Scenario, 'id' | 'name'>;
environment?: Pick<Environment, 'id' | 'name'>;
session?: { id: string; sessionName: string };
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
createdAt: string;
@@ -143,3 +143,20 @@ 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,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,80 @@
import { useTranslation } from 'react-i18next';
import { X, Play } from 'lucide-react';
import { Modal, Button, Select } from '../../ui';
import type { Environment } from '../../api';
export interface RunScenarioModalProps {
open: boolean;
environments: Environment[];
selectedEnvId: string;
onEnvSelect: (envId: string) => void;
saveSessionFlag: boolean;
onSaveSessionChange: (flag: boolean) => void;
onClose: () => void;
onRun: () => void;
isRunning: boolean;
actionLabel?: string;
}
export function RunScenarioModal({
open,
environments,
selectedEnvId,
onEnvSelect,
saveSessionFlag,
onSaveSessionChange,
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>
</>
)}
</Modal>
);
}
+6
View File
@@ -0,0 +1,6 @@
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';
+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]);
}
+93 -19
View File
@@ -1,4 +1,17 @@
{
"common": {
"button_cancel": "Cancel",
"button_confirm": "Confirm",
"button_delete": "Delete",
"confirm_delete_credential": "Are you sure you want to delete this credential?",
"confirm_delete_environment": "Are you sure you want to delete this environment?",
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
"confirm_delete_step": "Are you sure you want to delete this step?",
"confirm_delete_session": "Are you sure you want to delete this session?",
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
"save_session": "Save session"
},
"errors": {
"not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.",
@@ -19,37 +32,46 @@
},
"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",
@@ -57,7 +79,7 @@
"action_delete": "Delete",
"action_add": "Add credential",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Credential",
"edit_title": "Edit Credential",
@@ -97,9 +119,15 @@
"field_updated": "Updated",
"field_lastUsed": "Last Used"
},
"scenarios": { "title": "Scenarios",
"scenarios": {
"title": "Scenarios",
"created": "Scenario created",
"updated": "Scenario updated",
"run_started": "Scenario run started",
"col_id": "ID",
"col_name": "Name",
"col_description": "Description",
"col_last_run": "Last Run",
"col_updated": "Updated",
"empty": "No scenarios yet.",
"loading": "Loading…",
@@ -107,6 +135,7 @@
"action_delete": "Delete",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_steps": "Steps",
"field_created": "Created",
"field_updated": "Updated",
@@ -123,10 +152,15 @@
"action_import": "Import",
"import_error": "Failed to import scenario",
"action_save": "Create",
"action_update": "Save changes",
"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",
@@ -144,7 +178,19 @@
"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"
"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",
"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",
@@ -160,6 +206,8 @@
"page_size": "Items per page"
},
"steps": {
"created": "Step created",
"updated": "Step updated",
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
@@ -167,7 +215,7 @@
"action_edit": "Edit",
"action_delete": "Delete",
"action_save": "Add step",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"form_order": "Order",
"form_order_invalid": "Order must be a non-negative integer",
@@ -179,8 +227,9 @@
"form_session_required": "Session name is required",
"form_exec_code": "Exec code",
"form_exec_code_placeholder": "return await page.title();",
"form_validate_code": "Validate code",
"form_validate_code_placeholder": "return { success: result !== null, description: \"…\" };"
"form_timeout": "Step Timeout (seconds)",
"form_timeout_placeholder": "Default: 60",
"form_timeout_hint": "Max seconds for this step (default: 60)"
},
"runs": {
"title": "Runs",
@@ -198,7 +247,9 @@
"field_created": "Started",
"field_updated": "Updated",
"steps_heading": "Step runs",
"step_title": "Title",
"logs_heading": "Logs",
"logs_search_placeholder": "Filter logs…",
"step_order": "#",
"step_type": "Type",
"step_session": "Session",
@@ -210,6 +261,8 @@
},
"snippets": {
"title": "Snippets",
"created": "Snippet created",
"updated": "Snippet updated",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
@@ -217,20 +270,24 @@
"action_delete": "Delete",
"action_add": "Add snippet",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Snippet",
"edit_title": "Edit Snippet",
"form_name": "Name",
"form_name_placeholder": "e.g. clickLoginButton",
"form_name_required": "Name is required",
"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_name": "Name",
"field_alias": "Alias",
"field_title": "Title",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
@@ -238,5 +295,22 @@
"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>,
);
-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>
);
}
+43 -2
View File
@@ -6,7 +6,7 @@
}
.sectionHeading {
margin: 0;
margin: 0 0 var(--space-3);
line-height: 1;
font-size: var(--font-size-md);
font-weight: 600;
@@ -17,6 +17,13 @@
margin-top: var(--space-6);
}
.sectionHeadingRow {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-3);
}
.breadcrumbs {
margin-bottom: var(--space-4);
}
@@ -92,7 +99,8 @@
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
flex: 1;
min-width: 0;
}
.envCardId {
@@ -138,6 +146,35 @@
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;
}
@@ -189,6 +226,10 @@
max-width: 540px;
}
.formCardFull {
max-width: none;
}
.formFields {
display: flex;
flex-direction: column;
@@ -1,22 +1,25 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
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 [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -33,12 +36,13 @@ export function CreateCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success(t('credentials.created'));
navigate(`/credentials/${credential.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -49,16 +53,18 @@ export function CreateCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: t('credentials.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
@@ -72,24 +78,32 @@ export function CreateCredentialPage() {
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
<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>
@@ -1,11 +1,14 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Pencil, Trash2 } from 'lucide-react';
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, Notification, Timestamp, UuidBadge } from '../../ui';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
@@ -14,21 +17,28 @@ export function CredentialDetailPage() {
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(credential?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
credentials
.get(id)
.then(setCredential)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!credential) return;
await credentials.remove(credential.id);
navigate('/credentials');
setDeleting(true);
try {
await credentials.remove(credential.id);
navigate('/credentials');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
@@ -48,14 +58,18 @@ export function CredentialDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{
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}>
<Download size={14} />
<Upload size={14} />
{t('credentials.action_export')}
</Button>
<Button
@@ -66,7 +80,7 @@ export function CredentialDetailPage() {
<Pencil size={14} />
{t('credentials.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('credentials.action_delete')}
</Button>
@@ -74,31 +88,18 @@ export function CredentialDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_credential', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{credential && (
<>
<div className={styles.detailMeta}>
<Card>
<DescriptionList
layout="comfortable"
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} />
) : (
'—'
),
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
},
{
term: t('credentials.field_created'),
@@ -110,26 +111,36 @@ export function CredentialDetailPage() {
},
]}
/>
</div>
</Card>
{credential.data && (
<>
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
<Card>
<pre className={styles.codeBlock}>
{(() => {
<CodeBlock
language="json"
code={(() => {
try {
return JSON.stringify(JSON.parse(credential.data), null, 2);
} catch {
return credential.data;
}
})()}
</pre>
/>
</Card>
</>
</div>
)}
</>
)}
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
message={t('common.confirm_delete_credential')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+43 -13
View File
@@ -1,11 +1,21 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, Pencil, Trash2, Plus, Upload } from 'lucide-react';
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 {
Breadcrumbs,
Button,
Card,
ContextMenu,
DescriptionList,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function CredentialCard({
@@ -91,17 +101,18 @@ function AddCredentialCard() {
export function CredentialsPage() {
const { t } = useTranslation();
usePageTitle(t('credentials.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
credentials
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -109,9 +120,20 @@ export function CredentialsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await credentials.remove(id);
setItems((prev) => prev.filter((c) => c.id !== id));
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>) => {
@@ -123,15 +145,15 @@ export function CredentialsPage() {
const payload = yamlParse(text) as unknown;
const imported = await credentials.importCredential(payload);
navigate(`/credentials/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('credentials.title') }]} className={styles.breadcrumbs} />
<Breadcrumbs items={[{ label: t('credentials.title'), icon: <KeyRound size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -141,22 +163,30 @@ export function CredentialsPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('credentials.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading ? (
<p className={styles.muted}>{t('credentials.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((credential) => (
<CredentialCard key={credential.id} credential={credential} onDelete={handleDelete} />
<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>
);
}
@@ -1,24 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
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);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -29,11 +36,10 @@ export function EditCredentialPage() {
setName(c.name);
setData(c.data ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -50,15 +56,16 @@ export function EditCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
toast.success(t('credentials.updated'));
navigate(`/credentials/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -69,7 +76,11 @@ export function EditCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
@@ -79,12 +90,11 @@ export function EditCredentialPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{!loading && credential && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
@@ -98,17 +108,23 @@ export function EditCredentialPage() {
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
<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}>
@@ -117,9 +133,11 @@ export function EditCredentialPage() {
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>
@@ -1,39 +1,60 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
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 [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
return;
}
setSaving(true);
setError(null);
let parsedData: Record<string, string | undefined>;
try {
const env = await environments.create(name.trim(), {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
});
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) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -44,16 +65,18 @@ export function CreateEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: t('environments.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
@@ -67,34 +90,38 @@ export function CreateEnvironmentPage() {
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 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>
@@ -1,25 +1,30 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
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('');
const [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
usePageTitle(
env ? `${t('environments.edit_title')} — ${env.name}` : t('environments.edit_title'),
);
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -28,34 +33,47 @@ export function EditEnvironmentPage() {
.then((data) => {
setEnv(data);
setName(data.name);
setIdUrl(data.urls.id_url ?? '');
setCabinetUrl(data.urls.cabinet_url ?? '');
setAdminUrl(data.urls.admin_url ?? '');
setDescription(data.description || '');
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
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);
setError(null);
try {
await environments.update(id!, {
name: name.trim(),
urls: {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
},
description: description.trim() || undefined,
data: parsedData,
});
toast.success(t('environments.updated'));
navigate(`/environments/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -66,7 +84,11 @@ export function EditEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
@@ -76,12 +98,11 @@ export function EditEnvironmentPage() {
/>
</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}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
@@ -95,27 +116,29 @@ export function EditEnvironmentPage() {
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 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}>
@@ -124,9 +147,11 @@ export function EditEnvironmentPage() {
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>
@@ -1,33 +1,67 @@
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Pencil, Trash2 } from 'lucide-react';
import { environments } from '../../api';
import { usePageTitle } from '../../hooks/usePageTitle';
import { useNavigate, useParams } from 'react-router-dom';
import { stringify as yamlStringify } from 'yaml';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
import { environments } from '../../api';
import { DeleteConfirmationModal } from '../../components/modals';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const toast = useToast();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(env?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
useEffect(() => {
if (!id) return;
environments
.get(id)
.then(setEnv)
.catch((err: Error) => setError(err.message))
.catch((err: Error) => toast.error((err as Error).message))
.finally(() => setLoading(false));
}, [id]);
}, [id, toast]);
const handleDelete = async () => {
if (!env) return;
await environments.remove(env.id);
navigate('/environments');
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 (
@@ -35,12 +69,20 @@ export function EnvironmentDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{
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"
@@ -49,7 +91,7 @@ export function EnvironmentDetailPage() {
<Pencil size={14} />
{t('environments.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('environments.action_delete')}
</Button>
@@ -57,24 +99,15 @@ export function EnvironmentDetailPage() {
)}
</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}>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('environments.field_id'), detail: env.id },
{ term: t('environments.field_id'), detail: <UuidBadge id={env.id} /> },
{
term: t('environments.field_created'),
detail: <Timestamp value={env.createdAt} />,
@@ -85,18 +118,28 @@ export function EnvironmentDetailPage() {
},
]}
/>
</div>
</Card>
<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]) => ({
{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">
@@ -104,11 +147,21 @@ export function EnvironmentDetailPage() {
</a>
),
}))}
/>
)}
</Card>
/>
)}
</Card>
</div>
</>
)}
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
message={t('common.confirm_delete_environment')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,16 +1,39 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, ExternalLink, Pencil, Trash2, Plus } from 'lucide-react';
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 {
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 urlEntries = Object.entries(env.urls).filter(([, v]) => v);
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}>
@@ -34,6 +57,11 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
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} />,
@@ -61,15 +89,15 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
footer={footer}
onClick={() => navigate(`/environments/${env.id}`)}
>
{urlEntries.length > 0 && (
{dataEntries.length > 0 && (
<DescriptionList
layout="compact"
truncate
items={urlEntries.map(([key, value]) => ({ term: key, detail: value }))}
items={dataEntries.map(([key, value]) => ({ term: key, detail: value }))}
/>
)}
{urlEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_urls')}</p>
{dataEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_data')}</p>
)}
</Card>
);
@@ -90,15 +118,18 @@ function AddEnvironmentCard() {
export function EnvironmentsPage() {
const { t } = useTranslation();
usePageTitle(t('environments.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
environments
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -106,25 +137,73 @@ export function EnvironmentsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await environments.remove(id);
setItems((prev) => prev.filter((e) => e.id !== id));
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>
<Breadcrumbs items={[{ label: t('environments.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<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={handleDelete} />
<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>
);
}
+64 -43
View File
@@ -1,9 +1,21 @@
import { useEffect, useRef, useState } from 'react';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Activity } from 'lucide-react';
import { runs } from '../../api';
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import { AutoRefreshIndicator, Badge, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
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';
@@ -22,45 +34,49 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
};
type AllRunRow = ScenarioRun & {
stepRuns: ScenarioRunStep[];
scenario: { id: number; name: string };
scenario: { id: string; name: string };
};
export function AllRunsPage() {
const { t } = useTranslation();
usePageTitle(t('runs.title'));
const navigate = useNavigate();
const [items, setItems] = useState<AllRunRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const load = () => {
runs
.listAll()
.then((res) => {
setItems(res.data as AllRunRow[]);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['runs', sortBy, sortDir, page, pageSize],
queryFn: () =>
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
refetchInterval: 10_000,
staleTime: 0,
});
const items = (data?.data ?? []) as AllRunRow[];
const total = data?.total ?? 0;
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
};
useEffect(() => {
setLoading(true);
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
const handlePageChange = (p: number) => setPage(p);
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
};
const columns: TableColumn<AllRunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'scenario',
key: 'scenario.name',
header: t('runs.col_scenario'),
sortable: true,
render: (r) => (
<span
className={styles.linkCell}
@@ -77,20 +93,14 @@ export function AllRunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 110,
render: (r) => (
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
),
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
header: t('runs.col_steps'),
width: 80,
render: (r) => r.stepRuns.length,
},
{
key: 'created',
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
@@ -98,20 +108,31 @@ export function AllRunsPage() {
return (
<div>
<div className={styles.pageToolbar}>
<h1 className={styles.pageTitle}>{t('runs.title')}</h1>
<AutoRefreshIndicator active pulseKey={pulseKey} />
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator
active
pulseKey={items.length}
error={!!error}
onClick={() => refetch()}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
loading={isLoading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
</div>
);
+340 -44
View File
@@ -1,7 +1,8 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect, useRef, useState, useCallback } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { runs } from '../../api';
import { usePageTitle } from '../../hooks/usePageTitle';
import { runs, runFiles } from '../../api';
import type {
Scenario,
ScenarioRunDetail,
@@ -10,21 +11,26 @@ import type {
ScenarioRunStatus,
RunStepStatus,
LogLevel,
FileMetadata,
} from '../../api';
import { scenarios } from '../../api';
import {
AutoRefreshIndicator,
Badge,
Button,
Breadcrumbs,
Card,
CodeBlock,
DescriptionList,
Notification,
Pagination,
Search,
Table,
Timestamp,
UuidBadge,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import { ChevronDown, ChevronRight, ClipboardList, Activity, Download } from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
@@ -56,6 +62,8 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
error: 'error',
};
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
export function RunDetailPage() {
const { t } = useTranslation();
const { id, runId } = useParams<{ id: string; runId: string }>();
@@ -64,13 +72,22 @@ export function RunDetailPage() {
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 logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
const stopPolling = () => {
if (pollRef.current) {
clearInterval(pollRef.current);
@@ -79,6 +96,61 @@ export function RunDetailPage() {
}
};
const handleFileDownload = (url: string, filename: string) => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
};
const isFileExpired = (file: FileMetadata) =>
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
const 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;
@@ -88,37 +160,45 @@ export function RunDetailPage() {
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);
const updated = await runs.get(id, runId, logSearchRef.current);
if (cancelled) return;
setRun(updated);
setPulseKey((k) => k + 1);
if (FINAL.includes(updated.status)) stopPolling();
if (FINAL.includes(updated.status)) {
stopPolling();
await loadArtifacts();
}
} catch {
stopPolling();
}
}, 1000);
}
})
.catch((err: Error) => { if (!cancelled) setError(err.message); })
.finally(() => { if (!cancelled) setLoading(false); });
.catch((err: Error) => {
if (!cancelled) setError(err.message);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
stopPolling();
};
}, [id, runId]);
}, [id, runId, loadArtifacts]);
const stepColumns: TableColumn<ScenarioRunStep>[] = [
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
{
key: 'type',
header: t('runs.step_type'),
width: 80,
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? '–'}</Badge>,
key: 'title',
header: t('runs.step_title'),
width: 220,
render: (s) => s.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
},
{
key: 'status',
@@ -130,8 +210,110 @@ export function RunDetailPage() {
},
{
key: 'description',
header: t('runs.step_description'),
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
header: (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<span>{t('runs.step_description')}</span>
{run?.stepRuns.some((s) => s.output) && (
<button
onClick={() => {
if (expandAll) {
setExpandAll(false);
setExpandedStepIds(new Set());
} else {
setExpandAll(true);
setExpandedStepIds(
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
);
}
}}
style={{
background: 'none',
border: 'none',
padding: '0 4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
color: 'inherit',
}}
title={expandAll ? 'Collapse all' : 'Expand all'}
>
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
</div>
),
render: (s) => {
const isExpanded = expandAll || expandedStepIds.has(s.id);
return (
<div>
<div
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
marginBottom: isExpanded && s.output ? '8px' : 0,
}}
>
{s.output && (
<button
onClick={() => {
const newSet = new Set(expandedStepIds);
if (newSet.has(s.id)) {
newSet.delete(s.id);
} else {
newSet.add(s.id);
}
setExpandedStepIds(newSet);
}}
style={{
background: 'none',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
flexShrink: 0,
marginTop: '2px',
}}
>
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
<code style={{ wordBreak: 'break-word' }}>
{s.description ? (
s.description
) : s.output ? (
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
) : (
<span className={styles.muted}>–</span>
)}
</code>
</div>
{isExpanded && s.output && (
<div style={{ marginLeft: '24px' }}>
<CodeBlock
code={(() => {
try {
return JSON.stringify(JSON.parse(s.output), null, 2);
} catch {
return s.output;
}
})()}
language="json"
/>
</div>
)}
</div>
);
},
},
];
@@ -142,7 +324,11 @@ export function RunDetailPage() {
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
{
key: 'message',
header: t('runs.log_message'),
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
},
{
key: 'time',
header: t('runs.log_time'),
@@ -156,47 +342,80 @@ export function RunDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
label: t('runs.title'),
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
{ label: `${runId}` },
]}
/>
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} />
<AutoRefreshIndicator
active={polling}
pulseKey={pulseKey}
error={!!error}
onClick={manualRefresh}
/>
</div>
{error && (
<Notification variant="error">
{error.startsWith('404') ? t('errors.not_found') : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
{run && (
<>
<Card>
<DescriptionList
layout="comfortable"
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_steps'), detail: run.stepRuns.length },
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
]}
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.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>
@@ -215,14 +434,91 @@ export function RunDetailPage() {
{run.logs.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<Search
value={logSearch}
onChange={setLogSearch}
placeholder={t('runs.logs_search_placeholder')}
/>
</div>
<Table
columns={logColumns}
data={run.logs}
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>
)}
</>
+163 -37
View File
@@ -1,10 +1,24 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play } from 'lucide-react';
import { scenarios, runs } from '../../api';
import type { Scenario, ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import { AutoRefreshIndicator, Badge, Breadcrumbs, Button, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
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';
@@ -22,44 +36,120 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
fail: 'Fail',
};
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
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 load = useCallback(() => {
if (!id) return;
setLoading(true);
Promise.all([scenarios.get(id!), runs.list(id!)])
.then(([sc, res]) => {
setScenario(sc);
setItems(res.data);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [total, setTotal] = useState(0);
// Keep refs so the poll interval always reads current values
const sortByRef = useRef(sortBy);
const sortDirRef = useRef(sortDir);
const pageRef = useRef(page);
const pageSizeRef = useRef(pageSize);
sortByRef.current = sortBy;
sortDirRef.current = sortDir;
pageRef.current = page;
pageSizeRef.current = pageSize;
const load = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
if (!id) return;
if (!hasDataRef.current) setLoading(true);
Promise.all([
scenarios.get(id!),
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
])
.then(([sc, res]) => {
setScenario(sc);
setItems(res.data);
setTotal(res.total);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
},
[id],
);
useEffect(() => {
load();
pollRef.current = setInterval(load, 10_000);
load('createdAt', 'desc', 1, 20);
pollRef.current = setInterval(
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
10_000,
);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [load]);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handlePageChange = (p: number) => {
setPage(p);
load(sortBy, sortDir, p, pageSize);
};
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
load(sortBy, sortDir, 1, size);
};
useEffect(() => {
environments
.list(1, 200)
.then((res) => {
setEnvs(res.data);
setSelectedEnvId((prev) => prev || res.data[0]?.id || '');
})
.catch(() => {});
}, []);
const handleRun = async () => {
const run = await scenarios.run(id!);
navigate(`/scenarios/${id}/runs/${run.id}`);
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>[] = [
@@ -68,20 +158,14 @@ export function RunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 100,
render: (r) => (
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
),
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
header: t('runs.col_steps'),
width: 80,
render: (r) => r.stepRuns.length,
},
{
key: 'created',
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
@@ -91,34 +175,76 @@ export function RunsPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('runs.title') },
{ label: t('runs.title'), icon: <Activity size={14} /> },
]}
/>
<div className={styles.toolbarActions}>
<AutoRefreshIndicator active pulseKey={pulseKey} />
<Button size="sm" onClick={handleRun}>
<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>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={
<>
<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>
);
}
@@ -1,32 +1,51 @@
import { useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
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);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
useEffect(() => {
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, []);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const scenario = await scenarios.create(name.trim());
const scenario = await scenarios.create(
name.trim(),
description.trim() || undefined,
environmentId || undefined,
);
toast.success(t('scenarios.created'));
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -37,14 +56,16 @@ export function CreateScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: t('scenarios.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
@@ -60,13 +81,33 @@ export function CreateScenarioPage() {
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={8}
/>
</div>
<Select
label={t('scenarios.form_environment')}
value={environmentId}
onChange={(e) => setEnvironmentId(e.target.value)}
options={[
{ value: '', label: t('scenarios.form_environment_none') },
...envs.map((env) => ({ value: env.id, label: env.name })),
]}
/>
</div>
<div className={styles.formActions}>
<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>
+35 -63
View File
@@ -1,57 +1,48 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario, StepType } from '../../api';
import type { CreateStepPayload } from '../../api/client';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
export function CreateStepPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [order, setOrder] = useState('0');
usePageTitle(t('steps.create_title'));
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [errors, setErrors] = useState<Partial<Record<keyof CreateStepPayload, string>>>({});
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
scenarios.get(id).then(setScenario).catch(() => null);
scenarios
.get(id)
.then(setScenario)
.catch(() => null);
}, [id]);
const validate = (): boolean => {
const next: typeof errors = {};
if (isNaN(Number(order)) || Number(order) < 0) next.order = t('steps.form_order_invalid');
setErrors(next);
return Object.keys(next).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validate()) return;
setSaving(true);
setError(null);
try {
await steps.create(id!, {
order: Number(order),
title: title.trim() || undefined,
type,
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
});
toast.success(t('steps.created'));
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -62,7 +53,11 @@ export function CreateStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -72,60 +67,37 @@ export function CreateStepPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => setOrder(e.target.value)}
error={errors.order}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
<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>
+65 -12
View File
@@ -1,22 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
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);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -25,24 +34,36 @@ export function EditScenarioPage() {
.then((data) => {
setScenario(data);
setName(data.name);
setDescription(data.description || '');
setEnvironmentId(data.environmentId ?? '');
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
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) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -53,7 +74,11 @@ export function EditScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -63,7 +88,6 @@ export function EditScenarioPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{!loading && scenario && (
@@ -82,6 +106,33 @@ export function EditScenarioPage() {
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={8}
/>
</div>
<Select
label={t('scenarios.form_environment')}
value={environmentId}
onChange={(e) => setEnvironmentId(e.target.value)}
options={[
{ value: '', label: t('scenarios.form_environment_none') },
...envs.map((env) => ({ value: env.id, label: env.name })),
]}
/>
<Input
label={t('scenarios.form_timeout')}
placeholder={t('scenarios.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('scenarios.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
@@ -90,9 +141,11 @@ export function EditScenarioPage() {
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>
+35 -70
View File
@@ -1,29 +1,29 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario, ScenarioStep, StepType } from '../../api';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import type { Scenario, ScenarioStep } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
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);
const [order, setOrder] = useState('');
usePageTitle(
step ? t('steps.edit_title', { order: step.order }) : t('steps.edit_title', { order: '' }),
);
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [orderError, setOrderError] = useState('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id || !stepId) return;
@@ -31,41 +31,27 @@ export function EditStepPage() {
.then(([sc, st]) => {
setScenario(sc);
setStep(st);
setOrder(String(st.order));
setTitle(st.title ?? '');
setType(st.type);
setExecCode(st.execCode ?? '');
setValidateCode(st.validateCode ?? '');
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id, stepId]);
const validate = (): boolean => {
let valid = true;
if (isNaN(Number(order)) || Number(order) < 0) {
setOrderError(t('steps.form_order_invalid'));
valid = false;
}
return valid;
};
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validate()) return;
setSaving(true);
setError(null);
try {
await steps.update(id!, stepId!, {
order: Number(order),
title: title.trim() || undefined,
type,
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success(t('steps.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -76,68 +62,45 @@ export function EditStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.edit_title', { order: step?.order ?? stepId }) },
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('steps.loading')}</p>}
{!loading && step && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => {
setOrder(e.target.value);
setOrderError('');
}}
error={orderError || undefined}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
<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}>
@@ -146,9 +109,11 @@ export function EditStepPage() {
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>
+559 -92
View File
@@ -1,39 +1,60 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState, useCallback, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Pencil, Plus, History, Trash2, Download } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential } from '../../api';
import { usePageTitle } from '../../hooks/usePageTitle';
import {
Play,
Pencil,
Plus,
History,
Download,
Trash2,
Upload,
GripVertical,
ClipboardList,
} from 'lucide-react';
import {
environments,
scenarios,
steps,
scenarioCredentials,
scenarioFiles,
credentials as credentialsApi,
} from '../../api';
import type {
Scenario,
ScenarioStep,
ScenarioCredential,
Credential,
Environment,
FileMetadata,
} from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Input,
Notification,
Modal,
Select,
Table,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
type TableColumn,
} from '../../ui';
import { ExportScenarioModal } from '../../components/modals';
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 toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(scenario?.name ?? null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
@@ -44,27 +65,103 @@ export function ScenarioDetailPage() {
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);
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 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;
scenarios
void scenarios
.get(id)
.then((s) => {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
void loadFiles();
credentialsApi
.list(1, 200)
.then((r) => setAllCredentials(r.data))
.catch(() => {});
}, [id]);
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 ?? []);
};
const handleRun = async () => {
if (!scenario) return;
const run = await scenarios.run(scenario.id);
navigate(`/scenarios/${id}/runs/${run.id}`);
if (!selectedEnvId) {
toast.error(t('scenarios.run_modal_env_required'));
return;
}
setRunning(true);
try {
const run = await scenarios.run(scenario.id, selectedEnvId, saveSessionFlag);
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 () => {
@@ -73,30 +170,100 @@ export function ScenarioDetailPage() {
navigate('/scenarios');
};
const handleOpenExportModal = () => {
if (!scenario) return;
// Initialise all credential checkboxes to checked
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
setIncludeEnvironment(true);
setExportModalOpen(true);
};
const handleExport = async () => {
if (!scenario) return;
const data = await scenarios.exportScenario(scenario.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
setIsExporting(true);
try {
const credIds = Array.from(includedCredentialIds);
const yamlContent = await scenarios.exportScenario(scenario.id, {
includeEnvironment,
credentialIds: credIds,
});
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
setExportModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setIsExporting(false);
}
};
const handleFileDownload = (url: string, filename: string) => {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
};
const isFileExpired = (file: FileMetadata) =>
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
async function handleUpload(e: SubmitEvent) {
e.preventDefault();
if (!id || !uploadFile) return;
setUploading(true);
try {
await scenarioFiles.upload(
id,
uploadFile,
uploadExpiresAt ? new Date(uploadExpiresAt) : undefined,
);
setUploadOpen(false);
setUploadFile(null);
setUploadExpiresAt('');
await loadFiles();
toast.success(t('files.uploadSuccess'));
} catch {
// error toast already emitted by API client
} finally {
setUploading(false);
}
}
const handleDeleteStep = async (stepId: string) => {
await steps.remove(id!, stepId);
setScenario((prev) =>
prev ? { ...prev, steps: prev.steps.filter((s) => s.id !== stepId) } : prev,
);
await reloadScenario();
};
const handleAddCredential = async (e: React.FormEvent) => {
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 (!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 {
@@ -120,18 +287,73 @@ export function ScenarioDetailPage() {
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: '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: '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>,
render: (s) =>
s.title ?? (
<span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>
),
},
{
key: 'updated',
@@ -163,7 +385,7 @@ export function ScenarioDetailPage() {
title={t('steps.action_delete')}
onClick={(e) => {
e.stopPropagation();
handleDeleteStep(s.id);
setPendingDelete({ type: 'step', id: s.id });
}}
>
<Trash2 size={14} />
@@ -198,7 +420,7 @@ export function ScenarioDetailPage() {
title={t('scenarios.cred_action_remove')}
onClick={(e) => {
e.stopPropagation();
handleRemoveCredential(sc.id);
setPendingDelete({ type: 'credential', id: sc.id });
}}
>
<Trash2 size={14} />
@@ -212,13 +434,17 @@ export function ScenarioDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button size="sm" onClick={handleRun}>
<Button size="sm" onClick={() => setRunModalOpen(true)}>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
@@ -226,15 +452,19 @@ export function ScenarioDetailPage() {
<History size={14} />
{t('scenarios.action_runs')}
</Button>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
<Upload size={14} />
{t('scenarios.action_export')}
</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={handleDelete}>
<Button
variant="danger"
size="sm"
onClick={() => setPendingDelete({ type: 'scenario' })}
>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
@@ -242,25 +472,34 @@ export function ScenarioDetailPage() {
)}
</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"
layout="grid"
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
...(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} />,
@@ -273,6 +512,17 @@ export function ScenarioDetailPage() {
/>
</Card>
{scenario.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={scenario.description} />
</Card>
</div>
)}
{scenario.steps.length > 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
@@ -288,6 +538,30 @@ export function ScenarioDetailPage() {
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>
)}
@@ -315,42 +589,52 @@ export function ScenarioDetailPage() {
{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>
<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>
)}
@@ -366,8 +650,191 @@ export function ScenarioDetailPage() {
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
)}
</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>
<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('scenarios.action_run')}
</Button>
</>
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => setSaveSessionFlag(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
<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>
);
}
+220 -30
View File
@@ -1,43 +1,141 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Plus, Trash2, Upload } from 'lucide-react';
import { usePageTitle } from '../../hooks/usePageTitle';
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
import { environments, scenarios } from '../../api';
import type { Environment, Scenario } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Modal,
Select,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
useToast,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import type { ScenarioRunStatus } from '../../api';
import styles from '../Page.module.css';
const LAST_RUN_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const LAST_RUN_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
export function ScenariosPage() {
const { t } = useTranslation();
usePageTitle(t('scenarios.title'));
const navigate = useNavigate();
const toast = useToast();
const [items, setItems] = useState<Scenario[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const fileInputRef = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
scenarios
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
const [sortBy, setSortBy] = useState('updatedAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const load = useCallback(
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
Promise.all([
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
environments.list(1, 200),
])
.then(([scenarioRes, envRes]) => {
setItems(scenarioRes?.data ?? []);
setTotal(scenarioRes?.total ?? 0);
setEnvs(envRes?.data ?? []);
})
.catch((err) => {
toast.error((err as Error).message);
})
.finally(() => setLoading(false));
},
[toast],
);
useEffect(() => {
load();
load('updatedAt', 'desc', 1, 10);
}, [load]);
const handleRun = async (id: string) => {
const run = await scenarios.run(id);
navigate(`/scenarios/${id}/runs/${run.id}`);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handleDelete = async (id: string) => {
await scenarios.remove(id);
setLoading(true);
load();
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);
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);
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>) => {
@@ -49,18 +147,37 @@ export function ScenariosPage() {
const payload = yamlParse(text) as unknown;
const imported = await scenarios.importScenario(payload);
navigate(`/scenarios/${imported.id}`);
} catch (err) {
setError((err as Error).message);
} 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 },
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
{
key: 'updated',
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} />,
},
{
@@ -70,14 +187,24 @@ export function ScenariosPage() {
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button size="sm" title={t('scenarios.action_run')} onClick={() => handleRun(s.id)}>
<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={() => handleDelete(s.id)}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
@@ -89,7 +216,7 @@ export function ScenariosPage() {
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
<Breadcrumbs items={[{ label: t('scenarios.title'), icon: <ClipboardList size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -99,7 +226,7 @@ export function ScenariosPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('scenarios.action_import')}
</Button>
<Button size="sm" onClick={() => navigate('/scenarios/new')}>
@@ -108,17 +235,80 @@ export function ScenariosPage() {
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('scenarios.empty')}
pageSize={10}
pageSize={pageSize}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={
<>
<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>
<Modal
open={runScenarioId != null}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunScenarioId(null)}
footer={
<>
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
Cancel
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('scenarios.action_run')}
</Button>
</>
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => setSaveSessionFlag(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
</div>
);
}
+31 -17
View File
@@ -1,10 +1,12 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
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, Notification, Timestamp, UuidBadge } from '../../ui';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionDetailPage() {
@@ -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(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,32 +44,28 @@ 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: <UuidBadge id={session.id} /> },
{ term: t('sessions.field_name'), detail: session.sessionName },
@@ -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>
);
}
+81 -19
View File
@@ -1,50 +1,90 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
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, Timestamp, UuidBadge } from '../../ui';
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 [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [sortBy, setSortBy] = useState('id');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const load = useCallback(() => {
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
sessions
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
.then((res) => {
setItems(res.data);
setTotal(res.total);
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load();
}, [load]);
load(sortBy, sortDir, page, pageSize);
}, [load, sortBy, sortDir, page, pageSize]);
const handleDelete = async (id: string) => {
await sessions.remove(id);
setLoading(true);
load();
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: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
{
key: 'sessionName',
header: t('sessions.col_name'),
sortable: true,
render: (s) => s.sessionName,
},
{
key: 'status',
header: t('sessions.col_status'),
width: 100,
sortable: true,
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
},
{
key: 'lastUsed',
key: 'lastUsedAt',
header: t('sessions.col_lastUsed'),
width: 160,
sortable: true,
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
},
{
@@ -57,7 +97,10 @@ export function SessionsPage() {
variant="danger"
size="sm"
title={t('sessions.action_delete')}
onClick={() => handleDelete(s.id)}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
@@ -67,18 +110,37 @@ export function SessionsPage() {
return (
<div>
<Breadcrumbs items={[{ label: t('sessions.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<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')}
pageSize={10}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={setPage}
onPageSizeChange={(s) => {
setPageSize(s);
setPage(1);
}}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
<DeleteConfirmationModal
open={deleteId != null}
title={t('sessions.action_delete')}
message={t('common.confirm_delete_session')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+59 -32
View File
@@ -1,27 +1,36 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
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 [name, setName] = useState('');
const [alias, setAlias] = useState('');
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
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()) {
@@ -30,16 +39,18 @@ export function CreateSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
name: name.trim(),
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success(t('snippets.created'));
navigate(`/snippets/${snippet.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -50,59 +61,75 @@ export function CreateSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: t('snippets.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setName(e.target.value);
setNameError('');
setAlias(e.target.value);
setAliasError('');
}}
error={nameError || undefined}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
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>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
<CodeEditor
value={code}
onChange={(e) => {
setCode(e.target.value);
onChange={(v) => {
setCode(v);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
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>
+65 -39
View File
@@ -1,25 +1,32 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePageTitle } from '../../hooks/usePageTitle';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
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 [name, setName] = useState('');
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 [nameError, setNameError] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,19 +34,23 @@ export function EditSnippetPage() {
.get(id)
.then((s) => {
setSnippet(s);
setName(s.name);
setAlias(s.alias);
setTitle(s.title);
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
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()) {
@@ -48,16 +59,18 @@ export function EditSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(id!, {
name: name.trim(),
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success(t('snippets.updated'));
navigate(`/snippets/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
toast.error(message);
} finally {
setSaving(false);
}
@@ -68,9 +81,13 @@ export function EditSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{
label: snippet?.name ?? `#${id}`,
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
},
{ label: t('snippets.edit_title') },
@@ -78,59 +95,68 @@ export function EditSnippetPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && snippet && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setName(e.target.value);
setNameError('');
setAlias(e.target.value);
setAliasError('');
}}
error={nameError || undefined}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
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>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
<CodeEditor
value={code}
onChange={(e) => {
setCode(e.target.value);
onChange={(v) => {
setCode(v);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
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}`)}
>
<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>
+73 -30
View File
@@ -1,11 +1,22 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Pencil, Trash2 } from 'lucide-react';
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, Notification, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function SnippetDetailPage() {
@@ -14,21 +25,28 @@ export function SnippetDetailPage() {
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(snippet?.title ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
snippets
.get(id)
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!snippet) return;
await snippets.remove(snippet.id);
navigate('/snippets');
setDeleting(true);
try {
await snippets.remove(snippet.id);
navigate('/snippets');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
@@ -38,7 +56,7 @@ export function SnippetDetailPage() {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snippet-${snippet.name}.yaml`;
a.download = `snippet-${snippet.alias}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
@@ -48,14 +66,18 @@ export function SnippetDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: snippet?.name ?? `#${id}` },
{
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}>
<Download size={14} />
<Upload size={14} />
{t('snippets.action_export')}
</Button>
<Button
@@ -66,7 +88,7 @@ export function SnippetDetailPage() {
<Pencil size={14} />
{t('snippets.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('snippets.action_delete')}
</Button>
@@ -74,29 +96,17 @@ export function SnippetDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_snippet', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{snippet && (
<>
<div className={styles.detailMeta}>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
{ term: t('snippets.field_name'), detail: snippet.name },
{
term: t('snippets.field_description'),
detail: snippet.description ?? '—',
},
{ 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} />,
@@ -107,18 +117,51 @@ export function SnippetDetailPage() {
},
]}
/>
</div>
</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.sectionHeader}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
</div>
<Card>
<pre className={styles.codeBlock}>{snippet.code}</pre>
<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>
);
}
+86 -28
View File
@@ -1,32 +1,52 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Code, Pencil, Trash2, Plus, Upload } from 'lucide-react';
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, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
function SnippetCard({
snippet,
onDelete,
}: {
snippet: Snippet;
onDelete: (id: string) => void;
}) {
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.name}</span>
<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')}>
<Code size={14} />
<Settings size={14} />
</Button>
}
items={[
@@ -62,9 +82,20 @@ function SnippetCard({
footer={footer}
onClick={() => navigate(`/snippets/${snippet.id}`)}
>
{snippet.description && (
<p className={styles.muted}>{snippet.description}</p>
)}
<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>
);
}
@@ -84,17 +115,18 @@ function AddSnippetCard() {
export function SnippetsPage() {
const { t } = useTranslation();
usePageTitle(t('snippets.title'));
const navigate = useNavigate();
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -102,9 +134,20 @@ export function SnippetsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await snippets.remove(id);
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>) => {
@@ -116,15 +159,15 @@ export function SnippetsPage() {
const payload = yamlParse(text) as unknown;
const imported = await snippets.importSnippet(payload);
navigate(`/snippets/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
<Breadcrumbs items={[{ label: t('snippets.title'), icon: <Braces size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -134,26 +177,41 @@ export function SnippetsPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('snippets.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && (
<div className={styles.envGrid}>
{items.map((s) => (
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
<SnippetCard key={s.id} snippet={s} onDelete={requestDelete} />
))}
{items.length === 0 && (
<p className={styles.muted}>{t('snippets.empty')}</p>
)}
{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>
);
}
@@ -45,6 +45,25 @@
}
}
/* ── 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 {
@@ -67,3 +86,18 @@
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;
}
@@ -4,22 +4,39 @@ export interface AutoRefreshIndicatorProps {
active: boolean;
pulseKey?: number;
label?: string;
error?: boolean;
onClick?: () => void;
}
export function AutoRefreshIndicator({ active, pulseKey, label = 'Live' }: AutoRefreshIndicatorProps) {
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, active ? styles.active : styles.inactive].join(' ')}
title={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
aria-label={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
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} />
)}
{pulseKey !== undefined && pulseKey > 0 && <span key={pulseKey} className={styles.ring} />}
</span>
<span className={styles.label}>{label}</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 */
}
+29
View File
@@ -27,11 +27,40 @@
background: var(--color-secondary-fg);
}
.thContent {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
.thSortable {
cursor: pointer;
user-select: none;
}
.thSortable:hover {
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
}
.sortIcon {
opacity: 0.4;
flex-shrink: 0;
}
.sortIconActive {
opacity: 1;
color: var(--color-primary);
}
[data-theme="dark"] .th {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
[data-theme="dark"] .thSortable:hover {
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
}
/* Rounded top corners on first/last header cells */
.th:first-child { border-radius: var(--radius-lg) 0 0 0; }
.th:last-child { border-radius: 0 var(--radius-lg) 0 0; }
+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
}
+4 -2
View File
@@ -1,8 +1,10 @@
import React, { useId } from 'react';
import styles from './Textarea.module.css';
export interface TextareaProps
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'id'> {
export interface TextareaProps extends Omit<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
'id'
> {
label?: string;
hint?: string;
error?: string;
@@ -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;
}
+20 -1
View File
@@ -27,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';
@@ -42,8 +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 -8
View File
@@ -1,23 +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',
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': '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"
}
```
+35 -28
View File
@@ -1,49 +1,56 @@
# 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 |
## 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.
+60 -54
View File
@@ -1,80 +1,86 @@
# 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.runSnippet(name, ...args)`: execute stored snippet code with the same context
- `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
## Validation contract
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:
`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
+1614 -10
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.4.0",
"version": "1.7.0",
"private": true,
"workspaces": [
"server",
+10 -7
View File
@@ -4,11 +4,13 @@ FROM node:22-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY server/package.json ./server/
RUN npm ci -w server
COPY nest-cli.json tsconfig*.json ./
COPY src ./src
RUN npm run build
COPY server/nest-cli.json ./server/
COPY server/tsconfig*.json ./server/
COPY server/src ./server/src
RUN npm run -w server build
# ── Runtime stage ─────────────────────────────────────────────────────────────
FROM node:22-slim AS runtime
@@ -27,12 +29,13 @@ ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server/package.json ./server/
RUN npm ci --omit=dev -w server
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/server/dist ./dist
# Runtime directories (keys and SQLite DB mounted via volumes)
RUN mkdir -p data keys
RUN mkdir -p data
EXPOSE 3000
-11239
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -27,16 +27,19 @@
"@nestjs/schedule": "^6.1.1",
"@nestjs/swagger": "^11.2.6",
"@nestjs/typeorm": "^11.0.1",
"@playwright/test": "^1.59.1",
"acorn": "^8.16.0",
"better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.4",
"effect": "^3.21.0",
"jsdom": "^29.0.2",
"playwright": "^1.59.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"swagger-ui-express": "^5.0.1",
"typeorm": "^0.3.28",
"yaml": "^2.8.3",
"zod": "^4.3.6"
},
"devDependencies": {
+19 -13
View File
@@ -1,24 +1,27 @@
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { AppConfig, validateAppConfig } from "./config/app.config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScheduleModule } from "@nestjs/schedule";
import { HealthModule } from "./health/health.module";
import { AuthModule } from "./auth/auth.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module";
import { SessionEntity } from "./session/session.entity";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { AppConfig, validateAppConfig } from "./config/app.config";
import { CredentialEntity } from "./credential/credential.entity";
import { CredentialModule } from "./credential/credential.module";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { FileEntity } from "./file/file.entity";
import { FileModule } from "./file/file.module";
import { ScenarioFileEntity } from "./file/scenario-file.entity";
import { ScenarioRunFileEntity } from "./file/scenario-run-file.entity";
import { HealthModule } from "./health/health.module";
import { McpModule } from "./mcp/mcp.module";
import { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioModule } from "./scenario/scenario.module";
import { SessionEntity } from "./session/session.entity";
import { SnippetEntity } from "./snippet/snippet.entity";
import { SnippetModule } from "./snippet/snippet.module";
@@ -46,16 +49,19 @@ import { SnippetModule } from "./snippet/snippet.module";
ScenarioRunLogEntity,
ScenarioCredentialEntity,
SnippetEntity,
FileEntity,
ScenarioFileEntity,
ScenarioRunFileEntity,
],
synchronize: true,
}),
}),
AuthModule,
BrowserModule,
EnvironmentModule,
CredentialModule,
ScenarioModule,
SnippetModule,
FileModule,
McpModule,
HealthModule,
],
-51
View File
@@ -1,51 +0,0 @@
import { Body, Controller, Get, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { AuthService } from "./auth.service";
import { LoginDto } from "./dto/login.dto";
@ApiTags("auth")
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get("keys")
@ApiOperation({
summary: "List available key identifiers from the keys directory",
})
@ApiResponse({
status: 200,
description: "List of key names",
schema: {
properties: { keys: { type: "array", items: { type: "string" } } },
},
})
listKeys(): { keys: string[] } {
return { keys: this.authService.listKeys() };
}
@Post("login")
@ApiOperation({
summary: "Log in using a file key and return the session token",
})
@ApiResponse({
status: 201,
description: "Login successful",
schema: {
properties: {
token: { type: "string" },
sessionName: { type: "string" },
},
},
})
@ApiResponse({ status: 400, description: "Key not found or invalid" })
@ApiResponse({ status: 500, description: "Automation failed" })
login(
@Body() dto: LoginDto,
): Promise<{ token: string; sessionName: string }> {
return this.authService.login(
dto.key,
dto.environmentName,
dto.sessionName,
);
}
}
-13
View File
@@ -1,13 +0,0 @@
import { Module } from "@nestjs/common";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
@Module({
imports: [SessionModule, EnvironmentModule],
controllers: [AuthController],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}
-265
View File
@@ -1,265 +0,0 @@
import {
Injectable,
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "../config/app.config";
import { chromium } from "playwright";
import type { Page } from "playwright";
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import { SessionService } from "../session/session.service";
import { SessionContextService } from "../session/session-context.service";
import { EnvironmentService } from "../environment/environment.service";
interface KeyDescriptor {
keyFile?: string;
login?: string;
password: string;
}
@Injectable()
export class AuthService {
private readonly logger = new TraceLogger(AuthService.name);
private readonly keysDir: string;
constructor(
private readonly config: ConfigService<AppConfig, true>,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly environmentService: EnvironmentService,
) {
this.keysDir = path.resolve(this.config.get("KEYS_DIR"));
}
listKeys(): string[] {
if (!fs.existsSync(this.keysDir)) return [];
return fs
.readdirSync(this.keysDir)
.filter((f) => f.endsWith(".json"))
.map((f) => path.basename(f, ".json"));
}
private loadKeyDescriptor(keyId: string): KeyDescriptor {
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
if (!fs.existsSync(keyJsonPath)) {
throw new BadRequestException(`Key not found: ${keyId}`);
}
try {
return JSON.parse(fs.readFileSync(keyJsonPath, "utf-8")) as KeyDescriptor;
} catch (err) {
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, {
cause: err,
});
}
}
async login(
keyId: string,
environmentName: string,
sessionName?: string,
): Promise<{ token: string; sessionName: string }> {
const resolvedSession = sessionName ?? crypto.randomUUID();
const env = await this.environmentService
.findAll()
.then(({ data }) => data.find((e) => e.name === environmentName));
if (!env)
throw new NotFoundException(`Environment "${environmentName}" not found`);
const loginUrl = env.urls.id_url;
const cabinetUrl = env.urls.cabinet_url;
if (!loginUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing id_url`,
);
if (!cabinetUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing cabinet_url`,
);
const descriptor = this.loadKeyDescriptor(keyId);
const useLoginPassword = !!descriptor.login;
if (!useLoginPassword) {
if (!descriptor.keyFile) {
throw new BadRequestException(
`Key descriptor for "${keyId}" must have either "login" or "keyFile"`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
}
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
this.logger.log(`Navigating to ${loginUrl}`);
await page.goto(loginUrl, { waitUntil: "networkidle" });
if (useLoginPassword) {
// Click "Логін і пароль" auth method
await page.locator('p[aria-label="Логін і пароль"]').click();
// Fill login and password
await page.getByLabel("Електронна пошта").fill(descriptor.login!);
await page.getByLabel("Пароль").fill(descriptor.password);
// Click "Увійти"
await page.locator('button:has-text("Увійти")').click();
} else {
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile!);
// Click "Файловий ключ" button
await page.getByText("Файловий ключ").click();
// Upload key file via hidden file input
const fileInput = page.locator(
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
);
await fileInput.setInputFiles(keyFilePath);
// Enter password
await page
.locator("#id-app-login-file-key-password")
.fill(descriptor.password);
// Click "Продовжити"
await page.locator("#id-app-login-file-key-sign-button").click();
}
// Wait until redirected to cabinet
this.logger.log(`Waiting for redirect to ${cabinetUrl}`);
await page.waitForURL(cabinetUrl, { timeout: 30000 });
// Extract token from localStorage
const token = await page.evaluate(() => localStorage.getItem("token"));
if (!token) {
throw new InternalServerErrorException(
"Login succeeded but token was not found in localStorage",
);
}
// Capture all cookies and localStorage from the browser context
const cookies = await context.cookies();
const localStorageData = await page.evaluate(() => {
const entries: Record<string, string> = {};
for (let i = 0; i < window.localStorage.length; i++) {
const k = window.localStorage.key(i);
if (k !== null) entries[k] = window.localStorage.getItem(k) ?? "";
}
return entries;
});
await this.sessionService.upsert(
resolvedSession,
token,
cookies,
localStorageData,
);
// Register the live Playwright context — browser stays open for reuse
this.sessionContextService.register(
resolvedSession,
browser,
context,
page,
);
this.logger.log(
`Login successful for key ${keyId}, session: ${resolvedSession}`,
);
return { token, sessionName: resolvedSession };
} catch (err) {
// Close browser only on failure — on success it is kept alive in SessionContextService
await browser.close().catch(() => {});
if (
err instanceof BadRequestException ||
err instanceof InternalServerErrorException
) {
throw err;
}
this.logger.error(`Login failed: ${(err as Error).message}`);
throw new InternalServerErrorException(
`Login automation failed: ${(err as Error).message}`,
{ cause: err },
);
}
}
async signWithKey(keyId: string, page: Page): Promise<void> {
const descriptor = this.loadKeyDescriptor(keyId);
if (!descriptor.keyFile) {
throw new BadRequestException(
`Key descriptor for "${keyId}" must have "keyFile" to sign`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
this.logger.log(`Signing with key ${keyId} on page: ${page.url()}`);
// Open the EDS sign widget (skip if it's already open)
const isSignDialogOpen = await page
.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]')
.isVisible()
.catch(() => false);
if (!isSignDialogOpen) {
await page
.locator("button")
.filter({ hasText: /підпис|sign/i })
.first()
.click();
await page.waitForTimeout(500);
}
// Select the file key tab inside the widget
await page
.locator('button, [role="tab"], li')
.filter({ hasText: /файлов|file key/i })
.first()
.click();
await page.waitForTimeout(300);
// Upload the key file
const fileInput = page.locator(
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
);
await fileInput.setInputFiles(keyFilePath);
await page.waitForTimeout(300);
// Enter password
await page.locator('input[type="password"]').fill(descriptor.password);
await page.waitForTimeout(200);
// Submit
await page
.locator("button")
.filter({ hasText: /підпис|sign|підтвер/i })
.last()
.click();
await page.waitForLoadState("networkidle");
this.logger.log(`Sign completed for key ${keyId}`);
}
}
-30
View File
@@ -1,30 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class LoginDto {
@ApiProperty({
description:
"Key identifier — filename (without extension) from the keys/ directory",
example: "3273334361",
})
@IsString()
@IsNotEmpty()
key: string;
@ApiProperty({
description: "Environment name to resolve login/cabinet URLs from",
example: "liquio-diia-stg",
})
@IsString()
@IsNotEmpty()
environmentName: string;
@ApiPropertyOptional({
description:
"Session name to store credentials under. Auto-generated UUID if omitted.",
example: "my-test-session",
})
@IsOptional()
@IsString()
sessionName?: string;
}
+32 -4
View File
@@ -1,9 +1,11 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { OpenDto } from "./dto/open.dto";
import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto";
@ApiTags("browser")
@Controller()
@@ -11,6 +13,8 @@ export class BrowserController {
constructor(
private readonly browserService: BrowserService,
private readonly codeExecutor: CodeExecutorService,
private readonly environmentService: EnvironmentService,
private readonly credentialService: CredentialService,
) {}
@Post("open")
@@ -54,8 +58,32 @@ export class BrowserController {
@ApiResponse({ status: 400, description: "Invalid input" })
@ApiResponse({ status: 404, description: "Session not found" })
@ApiResponse({ status: 500, description: "Execution failed" })
exec(@Body() dto: ExecDto): Promise<ExecResult> {
async exec(@Body() dto: ExecDto): Promise<ExecResult> {
this.codeExecutor.validate(dto.code);
return this.browserService.exec(dto.sessionName, dto.code, dto.url);
// Resolve environment from DB
let environment: Record<string, string | undefined> | undefined;
if (dto.environmentId) {
const env = await this.environmentService.findOne(dto.environmentId);
environment = env.data;
}
// Resolve credentials from DB (alias → payload)
let credentials: Record<string, unknown> | undefined;
if (dto.credentials && Object.keys(dto.credentials).length > 0) {
credentials = {};
for (const [alias, credId] of Object.entries(dto.credentials)) {
const cred = await this.credentialService.findOne(credId);
credentials[alias] = cred.data ? JSON.parse(cred.data) : {};
}
}
return this.browserService.exec(
dto.sessionName,
dto.code,
dto.url,
environment,
credentials,
);
}
}
+12 -3
View File
@@ -1,11 +1,20 @@
import { Module } from "@nestjs/common";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialModule } from "../credential/credential.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { BrowserController } from "./browser.controller";
import { BrowserService } from "./browser.service";
import { SessionModule } from "../session/session.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
@Module({
imports: [SessionModule, CodeExecutorModule],
imports: [
SessionModule,
CodeExecutorModule,
SnippetModule,
EnvironmentModule,
CredentialModule,
],
controllers: [BrowserController],
providers: [BrowserService],
exports: [BrowserService],
+97 -15
View File
@@ -1,16 +1,22 @@
import { Readability } from "@mozilla/readability";
import {
Injectable,
HttpException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { chromium } from "playwright";
import type { BrowserContext } from "playwright";
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { SessionContextService } from "../session/session-context.service";
import type { BrowserContext, Cookie } from "playwright";
import { chromium } from "playwright";
import type {
ExecResult,
ScriptLogger,
} from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import type { ExecResult } from "../code-executor/code-executor.service";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { SnippetService } from "../snippet/snippet.service";
export type { ExecResult } from "../code-executor/code-executor.service";
@@ -26,9 +32,55 @@ export class BrowserService {
constructor(
private readonly sessionContextService: SessionContextService,
private readonly sessionService: SessionService,
private readonly codeExecutor: CodeExecutorService,
private readonly snippetService: SnippetService,
) {}
private parseCookies(raw: string | null | undefined): Cookie[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as unknown;
return Array.isArray(parsed) ? (parsed as Cookie[]) : [];
} catch {
return [];
}
}
private async getOrCreateNamedHandle(sessionName: string) {
try {
return await this.sessionContextService.getHandle(sessionName);
} catch {
this.logger.log(
`[${sessionName}] creating session context automatically`,
);
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext();
const page = await context.newPage();
const existing = await this.sessionService.findBySessionName(sessionName);
const cookies = this.parseCookies(existing?.cookies);
if (cookies.length > 0) {
await context.addCookies(cookies);
}
this.sessionContextService.register(sessionName, browser, context, page);
await this.sessionService.upsert(
sessionName,
existing?.token ?? `auto:${sessionName}`,
await context.cookies(),
{},
);
return { browser, context, page };
}
}
private rethrow(err: unknown, label: string, operation: string): never {
if (err instanceof HttpException) {
throw err;
@@ -90,8 +142,7 @@ export class BrowserService {
this.logger.log(`[${label}] open: ${url}`);
if (sessionName) {
const { context } =
await this.sessionContextService.getHandle(sessionName);
const { context } = await this.getOrCreateNamedHandle(sessionName);
try {
return await this.extractContent(context, url, readerMode, selector);
} catch (err) {
@@ -118,20 +169,34 @@ export class BrowserService {
sessionName: string | undefined,
code: string,
url?: string,
environment?: EnvironmentData,
credentials?: Record<string, unknown>,
): Promise<ExecResult> {
const label = sessionName ?? "anonymous";
if (sessionName) {
const { page, context } =
await this.sessionContextService.getHandle(sessionName);
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
this.logger.log(`[${label}] exec: using persistent context`);
const snippets = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
try {
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
await page.goto(url, { waitUntil: "networkidle" });
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: context,
code,
log: scriptLogger,
credentials,
environment,
snippets,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
@@ -140,13 +205,20 @@ export class BrowserService {
}
// Anonymous — ephemeral browser
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
// instead of launching a new browser for each request.
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
@@ -154,7 +226,17 @@ export class BrowserService {
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: browserContext,
code,
log: scriptLogger,
credentials,
environment,
snippets: snippetMap,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
+22 -4
View File
@@ -1,10 +1,10 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsUrl } from "class-validator";
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
export class ExecDto {
@ApiPropertyOptional({
description:
"Session name previously created by POST /login. If omitted, executes without a stored session.",
"Optional named browser session. If it does not exist yet, it is created automatically.",
example: "test-session-1",
})
@IsOptional()
@@ -22,9 +22,27 @@ export class ExecDto {
@ApiProperty({
description:
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
example: "return await page.title();",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
example: "return await context.page.title();",
})
@IsString()
code: string;
@ApiPropertyOptional({
description:
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
})
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({
description:
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
})
@IsOptional()
@IsObject()
credentials?: Record<string, string>;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { IsBoolean, IsOptional, IsString, IsUrl } from "class-validator";
export class OpenDto {
@ApiPropertyOptional({
description:
"Session name previously created by POST /login. If omitted, opens the URL without a stored session.",
"Optional named browser session. If it does not exist yet, it is created automatically.",
example: "test-session-1",
})
@IsOptional()
+178 -46
View File
@@ -3,11 +3,16 @@ import {
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { expect as playwrightExpect } from "@playwright/test";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import type { BrowserContext, Page } from "playwright";
import { URL } from "url";
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import type { FileStorageService } from "../file/file-storage.service";
import type { DomNode } from "./dom-helpers";
import { dumpDom } from "./dom-helpers";
import type { EnvironmentUrls } from "../environment/environment.entity";
export interface ExecResult {
result: unknown;
@@ -18,6 +23,54 @@ export type ScriptLogger = (
message: string,
) => void;
/** The `context` object available inside user scripts as the sole argument. */
export interface ScriptContext {
/** Playwright Page for the current session. */
page: Page;
/** Playwright BrowserContext for the current session. */
browser: BrowserContext;
/** All environment values for the current run (empty object if none set). */
env: Record<string, string | undefined>;
/** Returns the environment value for `key`, or throws if not defined. */
getEnv: (key: string) => string;
/** Returns the credential value for `alias`, or throws if not found. */
getCredential: (alias: string) => unknown;
/** Returns the serialised output of a previous step by order index (negative = relative). */
getStepOutput: (order: number) => Promise<unknown>;
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
dumpDom: (selector?: string) => Promise<DomNode>;
log: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
/** Runs a named snippet with the same context, plus any extra positional args. */
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
/** Returns metadata + absolute disk path for files attached to the current scenario. */
getScenarioFiles: (opts?: { limit?: number; offset?: number }) => Promise<{
items: Array<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
total: number;
}>;
/** Downloads a file and creates a run artifact. */
downloadFile: (
url: string,
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
) => Promise<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
}
export interface ExecContext {
page: Page;
browser: BrowserContext;
code: string;
log?: ScriptLogger;
getStepOutput?: (order: number) => Promise<unknown>;
credentials?: Record<string, unknown>;
environment?: EnvironmentData | null;
snippets?: Record<string, string> | null;
result?: unknown;
scenarioId?: string;
runId?: string;
fileService?: FileStorageService;
}
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
@@ -27,7 +80,7 @@ export class CodeExecutorService {
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
const wrapped = `async function __validate__(context) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
@@ -39,20 +92,25 @@ export class CodeExecutorService {
}
/**
* Executes `code` as an async function body with `page` and `context` in
* scope. Always call `validate()` before this method.
* Executes `code` as an async function body with a single `context` argument
* that exposes page, browser, env helpers, credentials, snippets, and logging.
* Always call `validate()` before this method.
*/
async execute(
page: Page,
context: BrowserContext,
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentUrls | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
async execute(ctx: ExecContext): Promise<ExecResult> {
const {
page,
browser,
code,
log,
getStepOutput,
credentials,
environment,
snippets,
result,
scenarioId,
runId,
fileService,
} = ctx;
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
const toStr = (args: unknown[]) =>
@@ -61,12 +119,11 @@ export class CodeExecutorService {
.join(" ");
const credMap: Record<string, unknown> = credentials ?? {};
const envUrls: EnvironmentUrls = environment ?? {};
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
// eslint-disable-next-line prefer-const
let pageHelpers: Record<string, unknown>;
// scriptContext is referenced by runSnippet, so we declare it first.
let scriptContext: ScriptContext;
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
@@ -77,7 +134,9 @@ export class CodeExecutorService {
};
try {
pageHelpers = {
scriptContext = {
page,
browser,
dumpDom: (selector?: string) => dumpDom(page, selector),
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
@@ -91,52 +150,103 @@ export class CodeExecutorService {
}
return credMap[alias];
},
/** All URLs defined for the current environment (may be empty if no environment is set). */
env: { ...envUrls },
/** Returns the URL for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
const value = envUrls[key];
env: { ...envData },
getEnv: (key: string): string => {
const value = envData[key];
if (value == null) {
throw new Error(
`Environment URL "${key}" is not defined for this environment`,
`Environment value "${key}" is not defined for this environment`,
);
}
return value;
},
/**
* Runs a named snippet by name. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (name: string, ...args: unknown[]): Promise<unknown> => {
const snippetCode = snippetMap[name];
runSnippet: async (
alias: string,
...args: unknown[]
): Promise<unknown> => {
const snippetCode = snippetMap[alias];
if (snippetCode == null) {
throw new Error(`Snippet "${name}" not found`);
throw new Error(`Snippet alias "${alias}" not found`);
}
const snippetFn = new Function(
"page",
"context",
"helpers",
"console",
"snippetArgs",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
"expect",
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
);
return snippetFn(page, context, pageHelpers, fakeConsole, args);
return snippetFn(scriptContext, fakeConsole, args, playwrightExpect);
},
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
if (!fileService || !scenarioId) {
throw new Error("File service not available in this context");
}
const result = await fileService.listScenarioFiles(
scenarioId,
opts?.limit,
opts?.offset,
);
return {
items: result.items.map((item) => ({
id: item.id,
name: item.name,
mimeType: item.mimeType,
size: item.size,
sha256: item.sha256,
path: item.path,
})),
total: result.total,
};
},
downloadFile: async (
url: string,
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
) => {
if (!fileService || !scenarioId || !runId) {
throw new Error("File service or run context not available");
}
// Download file
const buffer = await downloadFileImpl(url, opts);
// Determine filename and mime type
const filename = opts?.filename ?? new URL(url).pathname.split("/").pop() ?? "download";
const mimeType = this.getMimeType(filename);
// Create run artifact with mapping
const savedFile = await fileService.createAndSaveRunArtifact(
runId,
buffer,
filename,
mimeType,
);
return {
id: savedFile.id,
name: savedFile.originalName,
mimeType: savedFile.mimeType,
size: savedFile.size,
sha256: savedFile.sha256,
path: fileService.getAbsolutePath(savedFile.filePath),
};
},
};
// Passing `console` as a named parameter shadows the global in the script scope.
// `console`, `result`, and `expect` are injected as named parameters so
// existing scripts that reference them directly still work.
const fn = new Function(
"page",
"context",
"helpers",
"console",
"result",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
"expect",
`return (async (context) => { ${code} })(context)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(page, context, pageHelpers, fakeConsole, result);
const execResult = await fn(
scriptContext,
fakeConsole,
result,
playwrightExpect,
);
return { result: execResult };
} catch (err) {
throw new InternalServerErrorException(
@@ -145,4 +255,26 @@ export class CodeExecutorService {
);
}
}
/**
* Infers MIME type from filename.
*/
private getMimeType(filename: string): string {
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
const mimeTypes: Record<string, string> = {
pdf: "application/pdf",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
csv: "text/csv",
txt: "text/plain",
zip: "application/zip",
};
return mimeTypes[ext] ?? "application/octet-stream";
}
}
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more