Compare commits

..
26 Commits
Author SHA1 Message Date
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
116 changed files with 3792 additions and 999 deletions

No files matched your search

+9
View File
@@ -12,3 +12,12 @@ server/dist
client/dist
*storybook.log
storybook-static
tsconfig.tsbuildinfo
# organization
TODO.md
# IDE/editor
.vscode/
.idea/
.github/
+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;
}
}
+3
View File
@@ -4,10 +4,12 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"test:compile": "tsc --noEmit",
"test:storybook": "vitest run --project storybook",
"lint": "eslint src .storybook",
"lint:fix": "eslint src .storybook --fix",
@@ -15,6 +17,7 @@
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
+6
View File
@@ -95,6 +95,12 @@
background: var(--color-secondary-hover);
}
.navSeparator {
height: var(--border-width);
background: var(--color-border);
margin: var(--space-2) var(--space-2);
}
.main {
flex: 1;
overflow-y: auto;
+42 -26
View File
@@ -11,13 +11,19 @@ const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
);
const EnvironmentDetailPage = lazy(() =>
import('./pages/environment/EnvironmentDetailPage').then((m) => ({ default: m.EnvironmentDetailPage })),
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
default: m.EnvironmentDetailPage,
})),
);
const CreateEnvironmentPage = lazy(() =>
import('./pages/environment/CreateEnvironmentPage').then((m) => ({ default: m.CreateEnvironmentPage })),
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
default: m.CreateEnvironmentPage,
})),
);
const EditEnvironmentPage = lazy(() =>
import('./pages/environment/EditEnvironmentPage').then((m) => ({ default: m.EditEnvironmentPage })),
import('./pages/environment/EditEnvironmentPage').then((m) => ({
default: m.EditEnvironmentPage,
})),
);
const SessionsPage = lazy(() =>
@@ -46,9 +52,7 @@ const EditStepPage = lazy(() =>
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
);
const RunsPage = lazy(() =>
import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })),
);
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
const RunDetailPage = lazy(() =>
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
);
@@ -60,13 +64,17 @@ const CredentialsPage = lazy(() =>
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
);
const CreateCredentialPage = lazy(() =>
import('./pages/credential/CreateCredentialPage').then((m) => ({ default: m.CreateCredentialPage })),
import('./pages/credential/CreateCredentialPage').then((m) => ({
default: m.CreateCredentialPage,
})),
);
const EditCredentialPage = lazy(() =>
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
);
const CredentialDetailPage = lazy(() =>
import('./pages/credential/CredentialDetailPage').then((m) => ({ default: m.CredentialDetailPage })),
import('./pages/credential/CredentialDetailPage').then((m) => ({
default: m.CredentialDetailPage,
})),
);
const SnippetsPage = lazy(() =>
@@ -82,13 +90,17 @@ const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
);
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
const NAV: (
| { path: string; labelKey: string; Icon: LucideIcon }
| { separator: true }
)[] = [
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ separator: true },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
];
export default function App() {
@@ -106,18 +118,22 @@ export default function App() {
>
<div className={styles.sideContent}>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
{NAV.map((item, index) =>
'separator' in item ? (
<div key={`separator-${index}`} className={styles.navSeparator} />
) : (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(item.labelKey)}
</NavLink>
),
)}
</nav>
<div className={styles.sideFooter}>
+46 -19
View File
@@ -15,7 +15,10 @@ import { emitApiErrorToast } from '../lib/toast-events';
// API calls are versioned under /api/v1 by default.
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(/\/$/, '');
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
/\/$/,
'',
);
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
@@ -90,7 +93,9 @@ export const snippets = {
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string }): Promise<Snippet> {
create(
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
@@ -128,13 +133,13 @@ export const environments = {
get(id: string): Promise<Environment> {
return request(`/environments/${id}`);
},
create(name: string, data: Environment['data']): Promise<Environment> {
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
return request('/environments', {
method: 'POST',
body: JSON.stringify({ name, data }),
body: JSON.stringify({ name, description, data }),
});
},
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
update(id: string, patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>): Promise<Environment> {
return request(`/environments/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -157,8 +162,8 @@ export const environments = {
// ── Sessions ──────────────────────────────────────────────────────────────────
export const sessions = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
return request(`/sessions?page=${page}&limit=${limit}`);
list(page = 1, limit = 50, orderBy = 'id', orderDir: 'ASC' | 'DESC' = 'DESC'): Promise<PaginatedResponse<Session>> {
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
},
get(id: string): Promise<Session> {
return request(`/sessions/${id}`);
@@ -171,19 +176,24 @@ export const sessions = {
// ── Scenarios ─────────────────────────────────────────────────────────────────
export const scenarios = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
list(
page = 1,
limit = 50,
orderBy = 'updatedAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<Scenario>> {
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
},
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
return request(`/scenarios/${id}`);
},
create(name: string): Promise<Scenario> {
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
return request('/scenarios', {
method: 'POST',
body: JSON.stringify({ name }),
body: JSON.stringify({ name, description, environmentId }),
});
},
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
update(id: string, patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>): Promise<Scenario> {
return request(`/scenarios/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -192,10 +202,10 @@ export const scenarios = {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: string, environmentId: string): Promise<ScenarioRun> {
run(id: string, environmentId: string, saveSession?: boolean): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId }),
body: JSON.stringify({ environmentId, saveSession }),
});
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
@@ -211,8 +221,19 @@ export const scenarios = {
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
exportScenario(id: string): Promise<string> {
return request(`/scenarios/${id}/export`);
exportScenario(
id: string,
options: { includeEnvironment: boolean; credentialIds: string[] } = {
includeEnvironment: false,
credentialIds: [],
},
): Promise<string> {
const params = new URLSearchParams();
params.set('includeEnvironment', String(options.includeEnvironment));
for (const cid of options.credentialIds) {
params.append('credentialIds', cid);
}
return request(`/scenarios/${id}/export?${params.toString()}`);
},
importScenario(payload: unknown): Promise<Scenario> {
return request('/scenarios/import', {
@@ -229,12 +250,14 @@ export const runs = {
page = 1,
limit = 20,
status?: string,
orderBy = 'createdAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<
PaginatedResponse<
ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }
ScenarioRun & { scenario: { id: string; name: string } }
>
> {
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
if (status) q.set('status', status);
return request(`/scenarios/runs?${q}`);
},
@@ -242,8 +265,10 @@ export const runs = {
scenarioId: string,
page = 1,
limit = 20,
orderBy = 'createdAt',
orderDir: 'ASC' | 'DESC' = 'DESC',
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
},
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
@@ -274,12 +299,14 @@ export const scenarioCredentials = {
export interface CreateStepPayload {
title?: string;
execCode?: string;
timeoutSeconds?: number | null;
}
export interface UpdateStepPayload {
title?: string;
order?: number;
execCode?: string;
timeoutSeconds?: number | null;
}
export const steps = {
+10
View File
@@ -16,6 +16,7 @@ export interface EnvironmentData {
export interface Environment {
id: string;
name: string;
description?: string;
data: EnvironmentData;
createdAt: string;
updatedAt: string;
@@ -66,6 +67,7 @@ export interface ScenarioStep {
order: number;
title: string | null;
execCode: string | null;
timeoutSeconds: number | null;
createdAt: string;
updatedAt: string;
}
@@ -82,6 +84,10 @@ 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[];
createdAt: string;
@@ -98,7 +104,11 @@ 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;
@@ -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';
+50 -3
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,8 +32,11 @@
},
"environments": {
"title": "Environments",
"created": "Environment created",
"updated": "Environment updated",
"col_id": "ID",
"col_name": "Name",
"col_description": "Description",
"col_data": "Data",
"col_updated": "Updated",
"empty": "No environments yet.",
@@ -41,16 +57,21 @@
"form_name": "Name",
"form_name_placeholder": "e.g. staging, production",
"form_name_required": "Name is required",
"form_description": "Description",
"form_description_placeholder": "Describe this environment",
"form_data": "Data (JSON)",
"form_data_invalid_json": "Must be a valid JSON object",
"back": "Environments",
"field_id": "ID",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
"section_data": "Data"
},
"credentials": {
"title": "Credentials",
"created": "Credential created",
"updated": "Credential updated",
"empty": "No credentials yet.",
"loading": "Loading…",
"menu_label": "Credential options",
@@ -98,9 +119,14 @@
"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_updated": "Updated",
"empty": "No scenarios yet.",
"loading": "Loading…",
@@ -108,6 +134,7 @@
"action_delete": "Delete",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_steps": "Steps",
"field_created": "Created",
"field_updated": "Updated",
@@ -128,6 +155,11 @@
"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",
@@ -149,7 +181,15 @@
"run_modal_title": "Select environment",
"run_modal_env_label": "Environment",
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
"run_modal_env_required": "Please select an environment"
"run_modal_env_required": "Please select an environment",
"export_modal_title": "Export Scenario",
"export_include_environment": "Include Environment",
"export_include_credentials": "Include Credentials",
"form_timeout": "Scenario Timeout (seconds)",
"form_timeout_placeholder": "Default: 600",
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
"field_name": "Name",
"field_id": "ID"
},
"theme": {
"switch_to_light": "Switch to light theme",
@@ -165,6 +205,8 @@
"page_size": "Items per page"
},
"steps": {
"created": "Step created",
"updated": "Step updated",
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
@@ -183,7 +225,10 @@
"form_session_placeholder": "e.g. my-session",
"form_session_required": "Session name is required",
"form_exec_code": "Exec code",
"form_exec_code_placeholder": "return await page.title();"
"form_exec_code_placeholder": "return await page.title();",
"form_timeout": "Step Timeout (seconds)",
"form_timeout_placeholder": "Default: 60",
"form_timeout_hint": "Max seconds for this step (default: 60)"
},
"runs": {
"title": "Runs",
@@ -215,6 +260,8 @@
},
"snippets": {
"title": "Snippets",
"created": "Snippet created",
"updated": "Snippet updated",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
+6 -5
View File
@@ -6,6 +6,7 @@ export interface ApiErrorToastDetail {
export function emitApiErrorToast(message: string): void {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
detail: { message },
@@ -13,17 +14,17 @@ export function emitApiErrorToast(message: string): void {
);
}
export function subscribeApiErrorToasts(
handler: (message: string) => void,
): () => void {
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
if (typeof window === 'undefined') return () => {};
const listener = (event: Event) => {
const custom = event as CustomEvent<ApiErrorToastDetail>;
const message = custom.detail?.message;
if (message) handler(message);
};
window.addEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
return () => {
window.removeEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
};
}
+10 -5
View File
@@ -1,17 +1,22 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './i18n';
import './ui/tokens.css';
import App from './App';
import { ToastProvider } from './ui';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
<QueryClientProvider client={queryClient}>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</QueryClientProvider>
</StrictMode>,
);
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
@@ -16,9 +16,8 @@ export function CreateCredentialPage() {
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -35,14 +34,12 @@ export function CreateCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success('Credential created');
toast.success(t('credentials.created'));
navigate(`/credentials/${credential.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -54,7 +51,11 @@ export function CreateCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: t('credentials.create_title') },
]}
/>
@@ -6,15 +6,8 @@ import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
@@ -23,7 +16,6 @@ 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);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -32,7 +24,6 @@ export function CredentialDetailPage() {
credentials
.get(id)
.then(setCredential)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -65,7 +56,11 @@ export function CredentialDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: credential?.name ?? `#${id}` },
]}
/>
@@ -136,23 +131,14 @@ export function CredentialDetailPage() {
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -11,10 +11,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function CredentialCard({
@@ -103,7 +103,6 @@ export function CredentialsPage() {
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);
@@ -112,7 +111,6 @@ export function CredentialsPage() {
credentials
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -145,8 +143,8 @@ 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
}
};
@@ -179,23 +177,14 @@ export function CredentialsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('credentials.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
@@ -20,7 +20,6 @@ export function EditCredentialPage() {
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -31,11 +30,10 @@ export function EditCredentialPage() {
setName(c.name);
setData(c.data ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -52,17 +50,15 @@ export function EditCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
toast.success('Credential updated');
toast.success(t('credentials.updated'));
navigate(`/credentials/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -74,7 +70,11 @@ export function EditCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
@@ -12,13 +12,13 @@ export function CreateEnvironmentPage() {
const toast = useToast();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -42,14 +42,16 @@ export function CreateEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
const env = await environments.create(name.trim(), parsedData);
toast.success('Environment created');
const env = await environments.create(
name.trim(),
parsedData,
description.trim() || undefined,
);
toast.success(t('environments.created'));
navigate(`/environments/${env.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -61,7 +63,11 @@ export function CreateEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: t('environments.create_title') },
]}
/>
@@ -82,6 +88,15 @@ export function CreateEnvironmentPage() {
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={6}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
@@ -15,12 +15,12 @@ export function EditEnvironmentPage() {
const [env, setEnv] = useState<Environment | null>(null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [dataJson, setDataJson] = useState('{}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -29,13 +29,13 @@ export function EditEnvironmentPage() {
.then((data) => {
setEnv(data);
setName(data.name);
setDescription(data.description || '');
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -59,17 +59,16 @@ export function EditEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
await environments.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
data: parsedData,
});
toast.success('Environment updated');
toast.success(t('environments.updated'));
navigate(`/environments/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +80,11 @@ export function EditEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
@@ -109,6 +112,15 @@ export function EditEnvironmentPage() {
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={6}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
@@ -1,20 +1,30 @@
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Upload, Pencil, Trash2, Globe } from 'lucide-react';
import { useNavigate, useParams } from 'react-router-dom';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Modal, Timestamp, UuidBadge } from '../../ui';
import { environments } from '../../api';
import { DeleteConfirmationModal } from '../../components/modals';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const toast = useToast();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
@@ -24,9 +34,9 @@ export function EnvironmentDetailPage() {
environments
.get(id)
.then(setEnv)
.catch((err: Error) => setError(err.message))
.catch((err: Error) => toast.error((err as Error).message))
.finally(() => setLoading(false));
}, [id]);
}, [id, toast]);
const handleDelete = async () => {
if (!env) return;
@@ -57,7 +67,11 @@ export function EnvironmentDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: env?.name ?? `#${id}` },
]}
/>
@@ -104,15 +118,26 @@ export function EnvironmentDetailPage() {
/>
</Card>
{env.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={env.description} />
</Card>
</div>
)}
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
<Card>
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
@@ -120,30 +145,21 @@ export function EnvironmentDetailPage() {
</a>
),
}))}
/>
)}
</Card>
/>
)}
</Card>
</div>
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -12,10 +12,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
@@ -120,7 +120,6 @@ export function EnvironmentsPage() {
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);
@@ -129,7 +128,6 @@ export function EnvironmentsPage() {
environments
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -162,8 +160,8 @@ export function EnvironmentsPage() {
const payload = yamlParse(text) as unknown;
const imported = await environments.importEnvironment(payload);
navigate(`/environments/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -196,23 +194,14 @@ export function EnvironmentsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('environments.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+56 -42
View File
@@ -1,9 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Activity } from 'lucide-react';
import { runs } from '../../api';
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
import {
AutoRefreshIndicator,
Badge,
@@ -12,6 +13,7 @@ import {
Timestamp,
UuidBadge,
type TableColumn,
type SortDirection,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
@@ -31,49 +33,53 @@ 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();
const navigate = useNavigate();
const [items, setItems] = useState<AllRunRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const load = useCallback(() => {
if (!hasDataRef.current) setLoading(true);
runs
.listAll()
.then((res) => {
setItems(res.data as AllRunRow[]);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
const {
data,
isLoading,
error,
refetch,
} = useQuery({
queryKey: ['runs', sortBy, sortDir, page, pageSize],
queryFn: () =>
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
refetchInterval: 10_000,
staleTime: 0,
});
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
const items = (data?.data ?? []) as AllRunRow[];
const total = data?.total ?? 0;
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
};
const handlePageChange = (p: number) => setPage(p);
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
};
const columns: TableColumn<AllRunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'scenario',
key: 'scenario.name',
header: t('runs.col_scenario'),
sortable: true,
render: (r) => (
<span
className={styles.linkCell}
@@ -90,18 +96,14 @@ export function AllRunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 110,
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
header: t('runs.col_steps'),
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} />,
},
];
@@ -110,18 +112,30 @@ export function AllRunsPage() {
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
<AutoRefreshIndicator
active
pulseKey={items.length}
error={!!error}
onClick={() => refetch()}
/>
</div>
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
loading={isLoading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
</div>
);
+168 -23
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { runs } from '../../api';
import type {
@@ -17,8 +17,8 @@ import {
Badge,
Breadcrumbs,
Card,
CodeBlock,
DescriptionList,
Notification,
Pagination,
Search,
Table,
@@ -27,7 +27,7 @@ import {
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import { ClipboardList, Activity } from 'lucide-react';
import { ChevronDown, ChevronRight, ClipboardList, Activity } from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
@@ -75,6 +75,8 @@ export function RunDetailPage() {
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 logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -171,8 +173,109 @@ export function RunDetailPage() {
},
{
key: 'description',
header: t('runs.step_description'),
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
header: (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<span>{t('runs.step_description')}</span>
{run?.stepRuns.some((s) => s.output) && (
<button
onClick={() => {
if (expandAll) {
setExpandAll(false);
setExpandedStepIds(new Set());
} else {
setExpandAll(true);
setExpandedStepIds(
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
);
}
}}
style={{
background: 'none',
border: 'none',
padding: '0 4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
color: 'inherit',
}}
title={expandAll ? 'Collapse all' : 'Expand all'}
>
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
</div>
),
render: (s) => {
const isExpanded = expandAll || expandedStepIds.has(s.id);
return (
<div>
<div
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
marginBottom: isExpanded && s.output ? '8px' : 0,
}}
>
{s.output && (
<button
onClick={() => {
const newSet = new Set(expandedStepIds);
if (newSet.has(s.id)) {
newSet.delete(s.id);
} else {
newSet.add(s.id);
}
setExpandedStepIds(newSet);
}}
style={{
background: 'none',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
flexShrink: 0,
marginTop: '2px',
}}
>
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
<code style={{ wordBreak: 'break-word' }}>
{s.description ? (
s.description
) : s.output ? (
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
) : (
<span className={styles.muted}>–</span>
)}
</code>
</div>
{isExpanded && s.output && (
<div style={{ marginLeft: '24px' }}>
<CodeBlock
code={(() => {
try {
return JSON.stringify(JSON.parse(s.output), null, 2);
} catch {
return s.output;
}
})()}
language="json"
/>
</div>
)}
</div>
);
},
},
];
@@ -183,7 +286,11 @@ export function RunDetailPage() {
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
{
key: 'message',
header: t('runs.log_message'),
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
},
{
key: 'time',
header: t('runs.log_time'),
@@ -197,9 +304,13 @@ export function RunDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
@@ -207,10 +318,15 @@ export function RunDetailPage() {
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
{ label: `${runId}` },
]}
/>
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} error={!!error} onClick={manualRefresh} />
<AutoRefreshIndicator
active={polling}
pulseKey={pulseKey}
error={!!error}
onClick={manualRefresh}
/>
</div>
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
@@ -220,19 +336,48 @@ export function RunDetailPage() {
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
]}
items={(() => {
const items = [
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
];
if (run.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>
+75 -24
View File
@@ -7,7 +7,6 @@ import type {
Environment,
Scenario,
ScenarioRun,
ScenarioRunStep,
ScenarioRunStatus,
} from '../../api';
import {
@@ -22,6 +21,7 @@ import {
UuidBadge,
useToast,
type TableColumn,
type SortDirection,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
@@ -40,7 +40,7 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
fail: 'Fail',
};
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
type RunRow = ScenarioRun;
export function RunsPage() {
const { t } = useTranslation();
@@ -60,30 +60,74 @@ export function RunsPage() {
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const load = useCallback(() => {
if (!id) return;
if (!hasDataRef.current) setLoading(true);
Promise.all([scenarios.get(id!), runs.list(id!)])
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]);
},
[id],
);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
load('createdAt', 'desc', 1, 20);
pollRef.current = setInterval(
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
10_000,
);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [load]);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handlePageChange = (p: number) => {
setPage(p);
load(sortBy, sortDir, p, pageSize);
};
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
load(sortBy, sortDir, 1, size);
};
useEffect(() => {
environments
.list(1, 200)
@@ -102,7 +146,7 @@ export function RunsPage() {
setRunning(true);
try {
const run = await scenarios.run(id!, selectedEnvId);
toast.success('Scenario run started');
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
@@ -118,18 +162,14 @@ export function RunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 100,
sortable: true,
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
header: t('runs.col_steps'),
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} />,
},
];
@@ -139,7 +179,11 @@ export function RunsPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -148,7 +192,7 @@ export function RunsPage() {
]}
/>
<div className={styles.toolbarActions}>
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={() => load(sortBy, sortDir, page, pageSize)} />
<Button size="sm" onClick={() => setRunModalOpen(true)}>
<Play size={14} />
{t('runs.action_run')}
@@ -162,25 +206,32 @@ export function RunsPage() {
rowKey={(r) => r.id}
loading={loading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSize={pageSize}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('runs.action_run')}
</Button>
</>
)}
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
@@ -1,9 +1,10 @@
import { useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios } from '../../api';
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
import { scenarios, environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateScenarioPage() {
@@ -12,25 +13,29 @@ export function CreateScenarioPage() {
const toast = useToast();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [environmentId, setEnvironmentId] = useState('');
const [envs, setEnvs] = useState<Environment[]>([]);
const [nameError, setNameError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
useEffect(() => {
environments.list(1, 200).then((r) => setEnvs(r?.data ?? [])).catch(() => {});
}, []);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const scenario = await scenarios.create(name.trim());
toast.success('Scenario created');
const scenario = await scenarios.create(name.trim(), description.trim() || undefined, environmentId || undefined);
toast.success(t('scenarios.created'));
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -42,7 +47,11 @@ export function CreateScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: t('scenarios.create_title') },
]}
/>
@@ -63,6 +72,24 @@ export function CreateScenarioPage() {
required
autoFocus
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
<CodeEditor
language="markdown"
value={description}
onChange={setDescription}
rows={8}
/>
</div>
<Select
label={t('scenarios.form_environment')}
value={environmentId}
onChange={(e) => setEnvironmentId(e.target.value)}
options={[
{ value: '', label: t('scenarios.form_environment_none') },
...envs.map((env) => ({ value: env.id, label: env.name })),
]}
/>
</div>
<div className={styles.formActions}>
+19 -7
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -16,8 +16,8 @@ export function CreateStepPage() {
const [scenario, setScenario] = useState<Scenario | null>(null);
const [title, setTitle] = useState('');
const [execCode, setExecCode] = useState('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,20 +27,19 @@ export function CreateStepPage() {
.catch(() => null);
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.create(id!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
});
toast.success('Step created');
toast.success(t('steps.created'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -52,7 +51,11 @@ export function CreateStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -75,6 +78,15 @@ export function CreateStepPage() {
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
<Input
label={t('steps.form_timeout')}
placeholder={t('steps.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('steps.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
+52 -12
View File
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
import { scenarios, environments } from '../../api';
import type { Scenario, Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditScenarioPage() {
@@ -15,10 +15,13 @@ export function EditScenarioPage() {
const [scenario, setScenario] = useState<Scenario | null>(null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [environmentId, setEnvironmentId] = useState<string>('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [envs, setEnvs] = useState<Environment[]>([]);
const [nameError, setNameError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,26 +30,32 @@ export function EditScenarioPage() {
.then((data) => {
setScenario(data);
setName(data.name);
setDescription(data.description || '');
setEnvironmentId(data.environmentId ?? '');
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
environments.list(1, 200).then((r) => setEnvs(r?.data ?? [])).catch(() => {});
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
toast.success('Scenario updated');
await scenarios.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
environmentId: environmentId || null,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success(t('scenarios.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -58,7 +67,11 @@ export function EditScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -86,6 +99,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}>
+21 -9
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -17,9 +17,9 @@ export function EditStepPage() {
const [step, setStep] = useState<ScenarioStep | null>(null);
const [title, setTitle] = useState('');
const [execCode, setExecCode] = useState('');
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id || !stepId) return;
@@ -29,25 +29,24 @@ export function EditStepPage() {
setStep(st);
setTitle(st.title ?? '');
setExecCode(st.execCode ?? '');
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id, stepId]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.update(id!, stepId!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success('Step updated');
toast.success(t('steps.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -59,12 +58,16 @@ export function EditStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.edit_title', { order: step ? step.order + 1 : stepId }) },
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
]}
/>
</div>
@@ -85,6 +88,15 @@ export function EditStepPage() {
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
<Input
label={t('steps.form_timeout')}
placeholder={t('steps.form_timeout_placeholder')}
type="number"
min={1}
value={timeoutSeconds}
onChange={(e) => setTimeoutSeconds(e.target.value)}
hint={t('steps.form_timeout_hint')}
/>
</div>
<div className={styles.formActions}>
+163 -39
View File
@@ -1,10 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Pencil, Plus, History, Trash2, Upload, GripVertical, ClipboardList } from 'lucide-react';
import {
Play,
Pencil,
Plus,
History,
Trash2,
Upload,
GripVertical,
ClipboardList,
} from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { environments, scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential, Environment } from '../../api';
import {
environments,
scenarios,
steps,
scenarioCredentials,
credentials as credentialsApi,
} from '../../api';
import type {
Scenario,
ScenarioStep,
ScenarioCredential,
Credential,
Environment,
} from '../../api';
import {
Breadcrumbs,
Button,
@@ -16,9 +37,11 @@ import {
Table,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
type TableColumn,
} from '../../ui';
import { ExportScenarioModal } from '../../components/modals';
import styles from '../Page.module.css';
export function ScenarioDetailPage() {
@@ -28,7 +51,6 @@ export function ScenarioDetailPage() {
const toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
@@ -44,13 +66,21 @@ export function ScenarioDetailPage() {
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);
useEffect(() => {
if (!id) return;
void scenarios
@@ -59,7 +89,6 @@ export function ScenarioDetailPage() {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
credentialsApi
.list(1, 200)
@@ -69,11 +98,19 @@ export function ScenarioDetailPage() {
.list(1, 200)
.then((r) => {
setEnvs(r.data);
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
})
.catch(() => {});
}, [id]);
// 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);
@@ -89,10 +126,11 @@ export function ScenarioDetailPage() {
}
setRunning(true);
try {
const run = await scenarios.run(scenario.id, selectedEnvId);
toast.success('Scenario run started');
const run = await scenarios.run(scenario.id, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -106,17 +144,36 @@ export function ScenarioDetailPage() {
navigate('/scenarios');
};
const handleOpenExportModal = () => {
if (!scenario) return;
// Initialise all credential checkboxes to checked
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
setIncludeEnvironment(true);
setExportModalOpen(true);
};
const handleExport = async () => {
if (!scenario) return;
const data = await scenarios.exportScenario(scenario.id);
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
setIsExporting(true);
try {
const credIds = Array.from(includedCredentialIds);
const yamlContent = await scenarios.exportScenario(scenario.id, {
includeEnvironment,
credentialIds: credIds,
});
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
setExportModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setIsExporting(false);
}
};
const handleDeleteStep = async (stepId: string) => {
@@ -138,7 +195,7 @@ export function ScenarioDetailPage() {
}
};
const handleAddCredential = async (e: React.FormEvent) => {
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!addCredId) {
@@ -231,7 +288,7 @@ export function ScenarioDetailPage() {
</span>
),
},
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order + 1, width: 60 },
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'title',
header: t('scenarios.step_title'),
@@ -319,7 +376,11 @@ export function ScenarioDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: scenario?.name ?? `#${id}` },
]}
/>
@@ -333,7 +394,7 @@ export function ScenarioDetailPage() {
<History size={14} />
{t('scenarios.action_runs')}
</Button>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
<Upload size={14} />
{t('scenarios.action_export')}
</Button>
@@ -341,7 +402,11 @@ export function ScenarioDetailPage() {
<Pencil size={14} />
{t('scenarios.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={() => setPendingDelete({ type: 'scenario' })}>
<Button
variant="danger"
size="sm"
onClick={() => setPendingDelete({ type: 'scenario' })}
>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
@@ -359,6 +424,19 @@ export function ScenarioDetailPage() {
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
...(scenario.environment
? [{
term: t('scenarios.field_environment'),
detail: (
<a
href={`/environments/${scenario.environment.id}`}
onClick={(e) => { e.preventDefault(); navigate(`/environments/${scenario.environment!.id}`); }}
>
{scenario.environment.name}
</a>
),
}]
: []),
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
@@ -371,6 +449,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}>
@@ -511,48 +600,83 @@ export function ScenarioDetailPage() {
: t('scenarios.action_delete')
}
onClose={() => !deleting && setPendingDelete(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
Confirm
{t('common.button_confirm')}
</Button>
</>
)}
}
>
{pendingDelete?.type === 'step' && 'Are you sure you want to delete this step?'}
{pendingDelete?.type === 'credential' && 'Are you sure you want to remove this credential from scenario?'}
{pendingDelete?.type === 'scenario' && 'Are you sure you want to delete this scenario?'}
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('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 }))}
/>
<>
<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>
);
}
+87 -32
View File
@@ -12,6 +12,7 @@ import {
Select,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
useToast,
@@ -24,45 +25,80 @@ export function ScenariosPage() {
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(() => {
Promise.all([scenarios.list(), environments.list(1, 200)])
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);
setEnvs(envRes.data);
setItems(scenarioRes?.data ?? []);
setTotal(scenarioRes?.total ?? 0);
setEnvs(envRes?.data ?? []);
})
.catch((err) => {
toast.error((err as Error).message);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
}, [toast]);
useEffect(() => {
load();
load('updatedAt', 'desc', 1, 10);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [load]);
const handleSort = (key: string, dir: SortDirection) => {
setSortBy(key);
setSortDir(dir);
setPage(1);
load(key, dir, 1, pageSize);
};
const handlePageChange = (p: number) => {
setPage(p);
load(sortBy, sortDir, p, pageSize);
};
const handlePageSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
load(sortBy, sortDir, 1, size);
};
const openRunModal = (id: string) => {
setRunScenarioId(id);
if (!selectedEnvId && envs.length > 0) {
setSelectedEnvId(envs[0].id);
}
const scenario = items.find((s) => s.id === id);
const preferred = scenario?.environmentId ?? null;
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
};
const handleRun = async () => {
if (!runScenarioId || !selectedEnvId) return;
setRunning(true);
try {
const run = await scenarios.run(runScenarioId, selectedEnvId);
toast.success('Scenario run started');
const run = await scenarios.run(runScenarioId, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
setRunScenarioId(null);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -75,8 +111,7 @@ export function ScenariosPage() {
setDeleting(true);
try {
await scenarios.remove(deleteId);
setLoading(true);
load();
load(sortBy, sortDir, page, pageSize);
setDeleteId(null);
} finally {
setDeleting(false);
@@ -92,18 +127,19 @@ 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: 'updatedAt',
header: t('scenarios.col_updated'),
width: 140,
sortable: true,
render: (s) => <Timestamp value={s.updatedAt} />,
},
{
@@ -167,34 +203,41 @@ export function ScenariosPage() {
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('scenarios.empty')}
pageSize={10}
pageSize={pageSize}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
/>
<Modal
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('scenarios.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this scenario?
{t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runScenarioId != null}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunScenarioId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
Cancel
@@ -203,17 +246,29 @@ export function ScenariosPage() {
{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 }))}
/>
<>
<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>
+13 -28
View File
@@ -4,16 +4,8 @@ import { useTranslation } from 'react-i18next';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionDetailPage() {
@@ -22,7 +14,6 @@ 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);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -31,7 +22,6 @@ export function SessionDetailPage() {
sessions
.get(id)
.then(setSession)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -52,7 +42,11 @@ export function SessionDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('sessions.title'), icon: <Monitor size={14} />, onClick: () => navigate('/sessions') },
{
label: t('sessions.title'),
icon: <Monitor size={14} />,
onClick: () => navigate('/sessions'),
},
{ label: session?.sessionName ?? `#${id}` },
]}
/>
@@ -102,23 +96,14 @@ export function SessionDetailPage() {
</Card>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('sessions.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+37 -28
View File
@@ -8,12 +8,13 @@ import {
Badge,
Breadcrumbs,
Button,
Modal,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionsPage() {
@@ -21,29 +22,38 @@ export function SessionsPage() {
const navigate = useNavigate();
const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [sortBy, setSortBy] = useState('id');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const load = useCallback(() => {
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
setLoading(true);
sessions
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
.then((res) => { setItems(res.data); setTotal(res.total); })
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load();
}, [load]);
load(sortBy, sortDir, page, pageSize);
}, [load, sortBy, sortDir, page, pageSize]);
const handleSort = (col: string, dir: SortDirection) => {
setSortBy(col);
setSortDir(dir);
setPage(1);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await sessions.remove(deleteId);
setLoading(true);
load();
load(sortBy, sortDir, page, pageSize);
setDeleteId(null);
} finally {
setDeleting(false);
@@ -52,17 +62,19 @@ export function SessionsPage() {
const columns: TableColumn<Session>[] = [
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
{ key: 'sessionName', header: t('sessions.col_name'), sortable: true, render: (s) => s.sessionName },
{
key: 'status',
header: t('sessions.col_status'),
width: 100,
sortable: true,
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
},
{
key: 'lastUsed',
key: 'lastUsedAt',
header: t('sessions.col_lastUsed'),
width: 160,
sortable: true,
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
},
{
@@ -97,28 +109,25 @@ export function SessionsPage() {
rowKey={(s) => s.id}
loading={loading}
emptyMessage={t('sessions.empty')}
pageSize={10}
sortBy={sortBy}
sortDir={sortDir}
onSort={handleSort}
total={total}
page={page}
onPageChange={setPage}
onPageSizeChange={(s) => { setPageSize(s); setPage(1); }}
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('sessions.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
@@ -19,9 +19,8 @@ export function CreateSnippetPage() {
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -38,7 +37,6 @@ export function CreateSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
alias: alias.trim(),
@@ -46,11 +44,10 @@ export function CreateSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet created');
toast.success(t('snippets.created'));
navigate(`/snippets/${snippet.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -62,7 +59,11 @@ export function CreateSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: t('snippets.create_title') },
]}
/>
+8 -8
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
@@ -23,7 +23,6 @@ export function EditSnippetPage() {
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -36,11 +35,10 @@ export function EditSnippetPage() {
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -57,7 +55,6 @@ export function EditSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(id!, {
alias: alias.trim(),
@@ -65,11 +62,10 @@ export function EditSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet updated');
toast.success(t('snippets.updated'));
navigate(`/snippets/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +77,11 @@ export function EditSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
+14 -8
View File
@@ -24,7 +24,6 @@ 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);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -33,7 +32,6 @@ export function SnippetDetailPage() {
snippets
.get(id)
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -66,7 +64,11 @@ export function SnippetDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: snippet?.title ?? `#${id}` },
]}
/>
@@ -141,18 +143,22 @@ export function SnippetDetailPage() {
open={confirmDeleteOpen}
title={t('snippets.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
<Button
variant="secondary"
onClick={() => setConfirmDeleteOpen(false)}
disabled={deleting}
>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+21 -19
View File
@@ -17,7 +17,10 @@ import {
} from '../../ui';
import styles from '../Page.module.css';
function firstParagraphBlocks(markdown: string, limit = 2): { preview: string; truncated: boolean } {
function firstParagraphBlocks(
markdown: string,
limit = 2,
): { preview: string; truncated: boolean } {
const blocks = markdown
.split(/\n\s*\n/g)
.map((block) => block.trim())
@@ -81,16 +84,17 @@ function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: s
<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>}
</>
);
})()}
{snippet.description &&
(() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
</Card>
);
}
@@ -113,7 +117,6 @@ export function SnippetsPage() {
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);
@@ -122,7 +125,6 @@ export function SnippetsPage() {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -155,8 +157,8 @@ 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
}
};
@@ -195,18 +197,18 @@ export function SnippetsPage() {
open={deleteId != null}
title={t('snippets.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+6 -3
View File
@@ -36,15 +36,18 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
<li key={i} className={styles.item}>
{isLast ? (
<span className={styles.current} aria-current="page">
{item.icon}{item.label}
{item.icon}
{item.label}
</span>
) : item.href ? (
<a href={item.href} className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</a>
) : (
<button type="button" className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</button>
)}
{!isLast && <span className={styles.separator}>{sep}</span>}
+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; }
+120 -24
View File
@@ -1,13 +1,18 @@
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
import { Pagination } from '../Pagination/Pagination';
import styles from './Table.module.css';
export type SortDirection = 'asc' | 'desc';
export interface TableColumn<T> {
key: string;
header: ReactNode;
render: (row: T) => ReactNode;
width?: string | number;
align?: 'left' | 'center' | 'right';
/** If true, a sort icon is shown and clicking the header triggers onSort */
sortable?: boolean;
}
export interface TableProps<T> {
@@ -17,7 +22,10 @@ export interface TableProps<T> {
loading?: boolean;
emptyMessage?: string;
className?: string;
/** Enable built-in client-side pagination with this default page size */
/**
* Client-side pagination: pass a default page size to enable.
* For server-side pagination use `total` + `page` + `onPageChange` instead.
*/
pageSize?: number;
/** Offer a page-size selector when pagination is enabled */
pageSizeOptions?: number[];
@@ -25,6 +33,21 @@ export interface TableProps<T> {
onRowClick?: (row: T) => void;
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
/** Currently sorted column key (controlled) */
sortBy?: string;
/** Current sort direction (controlled) */
sortDir?: SortDirection;
/** Called when the user clicks a sortable column header */
onSort?: (key: string, dir: SortDirection) => void;
// ── Server-side pagination (controlled) ──────────────────────────────────
/** Total record count from server. Presence switches to server-side pagination mode. */
total?: number;
/** Controlled current page (1-based). Required when `total` is set. */
page?: number;
/** Called when the user navigates to a new page. Required when `total` is set. */
onPageChange?: (page: number) => void;
/** Called when the user changes page size. Optional for server-side pagination. */
onPageSizeChange?: (size: number) => void;
}
export function Table<T>({
@@ -38,34 +61,85 @@ export function Table<T>({
pageSizeOptions,
onRowClick,
getRowProps,
sortBy,
sortDir,
onSort,
total,
page: controlledPage,
onPageChange,
onPageSizeChange,
}: TableProps<T>) {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
const [internalPage, setInternalPage] = useState(1);
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
const paginated = defaultPageSize !== undefined && !loading;
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
const serverMode = total !== undefined;
// Reset to page 1 when data changes and current page would be empty
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
const safePage = Math.min(page, Math.max(1, lastPage));
const handleSortClick = (key: string) => {
if (!onSort) return;
const nextDir: SortDirection =
sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
onSort(key, nextDir);
};
// Client-side pagination
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
const visibleData = clientPaginated
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
: data;
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
// Server-side pagination display values
const serverPage = controlledPage ?? 1;
const serverTotal = total ?? 0;
return (
<div className={`${styles.wrapper} ${className ?? ''}`}>
<table className={styles.table}>
<thead>
<tr>
{columns.map((col) => (
<th
key={col.key}
className={styles.th}
style={{
width: col.width,
textAlign: col.align ?? 'left',
}}
>
{col.header}
</th>
))}
{columns.map((col) => {
const isSorted = col.sortable && sortBy === col.key;
const SortIcon = isSorted
? sortDir === 'asc'
? ArrowUp
: ArrowDown
: ArrowUpDown;
return (
<th
key={col.key}
className={[
styles.th,
col.sortable ? styles.thSortable : '',
]
.filter(Boolean)
.join(' ')}
style={{
width: col.width,
textAlign: col.align ?? 'left',
}}
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
>
<span className={styles.thContent}>
{col.header}
{col.sortable && (
<SortIcon
size={12}
className={[
styles.sortIcon,
isSorted ? styles.sortIconActive : '',
]
.filter(Boolean)
.join(' ')}
aria-hidden="true"
/>
)}
</span>
</th>
);
})}
</tr>
</thead>
<tbody>
@@ -122,17 +196,39 @@ export function Table<T>({
)}
</tbody>
</table>
{paginated && data.length > 0 && (
{serverMode && serverTotal > 0 && onPageChange && (
<Pagination
page={safePage}
page={serverPage}
pageSize={pageSize}
total={serverTotal}
onPageChange={onPageChange}
onPageSizeChange={
onPageSizeChange
? (size) => {
setPageSize(size);
onPageSizeChange(size);
}
: pageSizeOptions
? (size) => {
setPageSize(size);
onPageChange(1);
}
: undefined
}
pageSizeOptions={pageSizeOptions}
/>
)}
{clientPaginated && data.length > 0 && (
<Pagination
page={safeInternalPage}
pageSize={pageSize}
total={data.length}
onPageChange={setPage}
onPageChange={setInternalPage}
onPageSizeChange={
pageSizeOptions
? (size) => {
setPageSize(size);
setPage(1);
setInternalPage(1);
}
: undefined
}
+34 -45
View File
@@ -1,9 +1,8 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import styles from './ToastProvider.module.css';
import { subscribeApiErrorToasts } from '../../lib/toast-events';
type ToastVariant = 'success' | 'error' | 'info';
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
interface ToastItem {
id: number;
@@ -12,15 +11,6 @@ interface ToastItem {
closing: boolean;
}
interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
const ToastContext = createContext<ToastApi | null>(null);
const ICONS: Record<ToastVariant, React.ReactNode> = {
success: <CheckCircle2 size={16} />,
error: <AlertCircle size={16} />,
@@ -41,33 +31,38 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
const dismiss = useCallback((id: number) => {
setItems((prev) =>
prev.map((item) =>
item.id === id ? { ...item, closing: true } : item,
),
);
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
}, [remove]);
const dismiss = useCallback(
(id: number) => {
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
},
[remove],
);
const show = useCallback((message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const show = useCallback(
(message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
}, [dismiss, durationMs]);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
},
[dismiss, durationMs],
);
const api = useMemo<ToastApi>(() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}), [show]);
const api = useMemo<ToastApi>(
() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}),
[show],
);
useEffect(() => {
return subscribeApiErrorToasts((message) => api.error(message));
@@ -86,7 +81,9 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
role="status"
>
<div className={styles.content}>
<span className={styles.icon} aria-hidden="true">{ICONS[item.variant]}</span>
<span className={styles.icon} aria-hidden="true">
{ICONS[item.variant]}
</span>
<p className={styles.message}>{item.message}</p>
</div>
<button
@@ -103,11 +100,3 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
</ToastContext.Provider>
);
}
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+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;
}
+3 -2
View File
@@ -27,8 +27,9 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { ToastProvider, useToast } from './Toast/ToastProvider';
export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
export { useToast } from './Toast/useToast';
export { Timestamp } from './Timestamp/Timestamp';
export type { TimestampProps } from './Timestamp/Timestamp';
@@ -61,7 +62,7 @@ export { Modal } from './Modal/Modal';
export type { ModalProps } from './Modal/Modal';
export { Table } from './Table/Table';
export type { TableProps, TableColumn } from './Table/Table';
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
export { UuidBadge } from './UuidBadge/UuidBadge';
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
-1
View File
@@ -1 +0,0 @@
{"root":["./src/App.tsx","./src/declarations.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/index.ts","./src/api/types.ts","./src/hooks/useTheme.ts","./src/i18n/index.ts","./src/lib/hljs.ts","./src/lib/toast-events.ts","./src/pages/credential/CreateCredentialPage.tsx","./src/pages/credential/CredentialDetailPage.tsx","./src/pages/credential/CredentialsPage.tsx","./src/pages/credential/EditCredentialPage.tsx","./src/pages/environment/CreateEnvironmentPage.tsx","./src/pages/environment/EditEnvironmentPage.tsx","./src/pages/environment/EnvironmentDetailPage.tsx","./src/pages/environment/EnvironmentsPage.tsx","./src/pages/run/AllRunsPage.tsx","./src/pages/run/RunDetailPage.tsx","./src/pages/run/RunsPage.tsx","./src/pages/scenario/CreateScenarioPage.tsx","./src/pages/scenario/CreateStepPage.tsx","./src/pages/scenario/EditScenarioPage.tsx","./src/pages/scenario/EditStepPage.tsx","./src/pages/scenario/ScenarioDetailPage.tsx","./src/pages/scenario/ScenariosPage.tsx","./src/pages/session/SessionDetailPage.tsx","./src/pages/session/SessionsPage.tsx","./src/pages/snippet/CreateSnippetPage.tsx","./src/pages/snippet/EditSnippetPage.tsx","./src/pages/snippet/SnippetDetailPage.tsx","./src/pages/snippet/SnippetsPage.tsx","./src/ui/index.ts","./src/ui/AutoRefreshIndicator/AutoRefreshIndicator.tsx","./src/ui/Badge/Badge.tsx","./src/ui/Breadcrumbs/Breadcrumbs.tsx","./src/ui/Button/Button.tsx","./src/ui/Card/Card.tsx","./src/ui/CodeBlock/CodeBlock.tsx","./src/ui/CodeEditor/CodeEditor.tsx","./src/ui/ContextMenu/ContextMenu.tsx","./src/ui/DescriptionList/DescriptionList.tsx","./src/ui/Input/Input.tsx","./src/ui/MarkdownContent/MarkdownContent.tsx","./src/ui/Modal/Modal.tsx","./src/ui/Notification/Notification.tsx","./src/ui/Pagination/Pagination.tsx","./src/ui/Search/Search.tsx","./src/ui/Select/Select.tsx","./src/ui/SidePanel/SidePanel.tsx","./src/ui/Table/Table.tsx","./src/ui/Textarea/Textarea.tsx","./src/ui/ThemeSwitcher/ThemeSwitcher.tsx","./src/ui/Timestamp/Timestamp.tsx","./src/ui/Toast/ToastProvider.tsx","./src/ui/UuidBadge/UuidBadge.tsx"],"version":"5.8.3"}
+1 -1
View File
@@ -28,7 +28,7 @@ The server currently registers the following tools.
| Tool | Description |
|---|---|
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
| `exec_code` | Execute Playwright JS with `page` and `context` in scope |
| `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
+19 -15
View File
@@ -17,24 +17,28 @@ Current scheduler behavior is exec-centric:
## Script runtime
`execCode` and `validateCode` execute as async JavaScript with:
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
- `page`: Playwright `Page`
- `context`: Playwright `BrowserContext`
- `helpers`: utility object
```js
async (context) => {
// your code here
}
```
Available in scope:
- `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.)
`validateCode` additionally receives `result`, which is the value returned by `execCode`.
## Available helpers
- `helpers.dumpDom(selector?)`: simplified DOM snapshot
- `helpers.log(...args)`, `helpers.warn(...args)`, `helpers.error(...args)`: structured step logs
- `helpers.getStepOutput(order)`: prior step output by absolute order (`0`, `1`, ...) or relative (`-1` previous step)
- `helpers.getCredential(alias)`: credential payload assigned to the scenario alias
- `helpers.env`: shallow copy of environment URL map
- `helpers.getEnvUrl(key)`: required environment URL lookup (throws if missing)
- `helpers.runSnippet(name, ...args)`: execute stored snippet code in the same page/context/helpers scope
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
## Validation contract
+76 -3
View File
@@ -1,12 +1,12 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "liqa",
"version": "1.5.0",
"version": "1.6.1",
"workspaces": [
"server",
"client"
@@ -16,6 +16,7 @@
"name": "liqa-client",
"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",
@@ -3978,7 +3979,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true,
"license": "MIT"
},
"node_modules/@storybook/addon-a11y": {
@@ -4202,6 +4202,30 @@
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.99.0.tgz",
"integrity": "sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.99.0.tgz",
"integrity": "sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==",
"dependencies": {
"@tanstack/query-core": "5.99.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
@@ -7194,6 +7218,16 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/effect": {
"version": "3.21.0",
"resolved": "https://registry.npmjs.org/effect/-/effect-3.21.0.tgz",
"integrity": "sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"fast-check": "^3.23.1"
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.332",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.332.tgz",
@@ -8093,6 +8127,44 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
"node_modules/fast-check": {
"version": "3.23.2",
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",
"integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/dubzzz"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fast-check"
}
],
"license": "MIT",
"dependencies": {
"pure-rand": "^6.1.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/fast-check/node_modules/pure-rand": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
"integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/dubzzz"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fast-check"
}
],
"license": "MIT"
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -15962,6 +16034,7 @@
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.6.1",
"private": true,
"workspaces": [
"server",
+1 -1
View File
@@ -35,7 +35,7 @@ RUN npm ci --omit=dev -w server
COPY --from=builder /app/server/dist ./dist
# Runtime directories (keys and SQLite DB mounted via volumes)
RUN mkdir -p data keys
RUN mkdir -p data
EXPOSE 3000
+1
View File
@@ -32,6 +32,7 @@
"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",
+11 -11
View File
@@ -1,23 +1,23 @@
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 { 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 { 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";
+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],
+50 -14
View File
@@ -1,18 +1,22 @@
import { Readability } from "@mozilla/readability";
import {
Injectable,
HttpException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { chromium } from "playwright";
import type { BrowserContext } from "playwright";
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import type { BrowserContext, Cookie } from "playwright";
import { chromium } from "playwright";
import type {
ExecResult,
ScriptLogger,
} from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import type { ExecResult } from "../code-executor/code-executor.service";
import type { Cookie } from "playwright";
import { SnippetService } from "../snippet/snippet.service";
export type { ExecResult } from "../code-executor/code-executor.service";
@@ -30,6 +34,7 @@ export class BrowserService {
private readonly sessionContextService: SessionContextService,
private readonly sessionService: SessionService,
private readonly codeExecutor: CodeExecutorService,
private readonly snippetService: SnippetService,
) {}
private parseCookies(raw: string | null | undefined): Cookie[] {
@@ -164,20 +169,34 @@ export class BrowserService {
sessionName: string | undefined,
code: string,
url?: string,
environment?: EnvironmentData,
credentials?: Record<string, unknown>,
): Promise<ExecResult> {
const label = sessionName ?? "anonymous";
if (sessionName) {
const { page, context } =
await this.getOrCreateNamedHandle(sessionName);
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
this.logger.log(`[${label}] exec: using persistent context`);
const snippets = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
try {
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
await page.goto(url, { waitUntil: "networkidle" });
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: context,
code,
log: scriptLogger,
credentials,
environment,
snippets,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
@@ -186,13 +205,20 @@ export class BrowserService {
}
// Anonymous — ephemeral browser
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
// instead of launching a new browser for each request.
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
@@ -200,7 +226,17 @@ export class BrowserService {
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: browserContext,
code,
log: scriptLogger,
credentials,
environment,
snippets: snippetMap,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
+21 -3
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsUrl } from "class-validator";
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
export class ExecDto {
@ApiPropertyOptional({
@@ -22,9 +22,27 @@ export class ExecDto {
@ApiProperty({
description:
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
example: "return await page.title();",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
example: "return await context.page.title();",
})
@IsString()
code: string;
@ApiPropertyOptional({
description:
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
})
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({
description:
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
})
@IsOptional()
@IsObject()
credentials?: Record<string, string>;
}
@@ -3,12 +3,13 @@ import {
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { expect as playwrightExpect } from "@playwright/test";
import { dumpDom } from "./dom-helpers";
import { parse } from "acorn";
import type { BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import type { DomNode } from "./dom-helpers";
import { dumpDom } from "./dom-helpers";
export interface ExecResult {
result: unknown;
@@ -19,6 +20,41 @@ 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>;
}
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;
}
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
@@ -28,7 +64,7 @@ export class CodeExecutorService {
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
const wrapped = `async function __validate__(context) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
@@ -40,20 +76,22 @@ export class CodeExecutorService {
}
/**
* Executes `code` as an async function body with `page` and `context` in
* scope. Always call `validate()` before this method.
* Executes `code` as an async function body with a single `context` argument
* that exposes page, browser, env helpers, credentials, snippets, and logging.
* Always call `validate()` before this method.
*/
async execute(
page: Page,
context: BrowserContext,
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentData | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
async execute(ctx: ExecContext): Promise<ExecResult> {
const {
page,
browser,
code,
log,
getStepOutput,
credentials,
environment,
snippets,
result,
} = ctx;
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
const toStr = (args: unknown[]) =>
@@ -65,9 +103,8 @@ export class CodeExecutorService {
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
let pageHelpers: Record<string, unknown>;
// scriptContext is referenced by runSnippet, so we declare it first.
let scriptContext: ScriptContext;
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
@@ -78,7 +115,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)),
@@ -92,10 +131,8 @@ export class CodeExecutorService {
}
return credMap[alias];
},
/** All values defined for the current environment (may be empty if no environment is set). */
env: { ...envData },
/** Returns the value for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
getEnv: (key: string): string => {
const value = envData[key];
if (value == null) {
throw new Error(
@@ -104,12 +141,6 @@ export class CodeExecutorService {
}
return value;
},
/**
* Runs a snippet by alias. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (
alias: string,
...args: unknown[]
@@ -119,40 +150,28 @@ export class CodeExecutorService {
throw new Error(`Snippet alias "${alias}" not found`);
}
const snippetFn = new Function(
"page",
"context",
"helpers",
"console",
"snippetArgs",
"expect",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
);
return snippetFn(
page,
context,
pageHelpers,
fakeConsole,
args,
playwrightExpect,
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
);
return snippetFn(scriptContext, fakeConsole, args, playwrightExpect);
},
};
// Passing `console` and `expect` as named parameters exposes them in 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",
"expect",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
`return (async (context) => { ${code} })(context)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(
page,
context,
pageHelpers,
scriptContext,
fakeConsole,
result,
playwrightExpect,
@@ -0,0 +1,61 @@
import type { BrowserContext, Page } from "playwright";
import type { EnvironmentData } from "../environment/environment.entity";
import type { ExecContext, ScriptLogger } from "./code-executor.service";
export class ExecContextBuilder {
private readonly ctx: Partial<ExecContext> = {};
page(page: Page): this {
this.ctx.page = page;
return this;
}
browser(browser: BrowserContext): this {
this.ctx.browser = browser;
return this;
}
code(code: string): this {
this.ctx.code = code;
return this;
}
log(log: ScriptLogger): this {
this.ctx.log = log;
return this;
}
getStepOutput(fn: (order: number) => Promise<unknown>): this {
this.ctx.getStepOutput = fn;
return this;
}
credentials(credentials: Record<string, unknown>): this {
this.ctx.credentials = credentials;
return this;
}
environment(environment: EnvironmentData | null): this {
this.ctx.environment = environment;
return this;
}
snippets(snippets: Record<string, string> | null): this {
this.ctx.snippets = snippets;
return this;
}
result(result: unknown): this {
this.ctx.result = result;
return this;
}
build(): ExecContext {
if (!this.ctx.page) throw new Error("ExecContextBuilder: page is required");
if (!this.ctx.browser)
throw new Error("ExecContextBuilder: browser is required");
if (this.ctx.code === undefined)
throw new Error("ExecContextBuilder: code is required");
return this.ctx as ExecContext;
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
import { IsInt, IsString, Min, Max } from "class-validator";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import { IsInt, IsString, Max, Min, validateSync } from "class-validator";
import pkg from "../../package.json";
@@ -11,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { CredentialQueryDto } from "./dto/credential-query.dto";
import { CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { CredentialOrderBy } from "./credential.service";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
@ApiTags("credentials")
@Controller("credentials")
@@ -40,7 +39,7 @@ export class CredentialController {
@Get()
@ApiOperation({ summary: "List all credentials (paginated)" })
@ApiResponse({ status: 200, description: "Paginated credentials" })
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
findAll(@Query() query: CredentialQueryDto) {
return this.credentialService.findAll(query);
}
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { CredentialController } from "./credential.controller";
import { CredentialEntity } from "./credential.entity";
import { CredentialService } from "./credential.service";
import { CredentialController } from "./credential.controller";
@Module({
imports: [TypeOrmModule.forFeature([CredentialEntity])],
+5 -5
View File
@@ -1,14 +1,14 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "./credential.entity";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
export type CredentialOrderBy =
| "id"
@@ -0,0 +1,13 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsOptional } from "class-validator";
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
import { CredentialOrderBy } from "../credential.service";
const CREDENTIAL_ORDER_BY: CredentialOrderBy[] = ["id", "name", "lastUsedAt"];
export class CredentialQueryDto extends PaginationQueryDto<CredentialOrderBy> {
@ApiPropertyOptional({ enum: CREDENTIAL_ORDER_BY })
@IsOptional()
@IsIn(CREDENTIAL_ORDER_BY)
declare orderBy?: CredentialOrderBy;
}
@@ -1,5 +1,5 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsObject, IsString } from "class-validator";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsObject, IsOptional, IsString } from "class-validator";
import { EnvironmentData } from "../environment.entity";
export class CreateEnvironmentDto {
@@ -8,6 +8,11 @@ export class CreateEnvironmentDto {
@IsNotEmpty()
name: string;
@ApiPropertyOptional({ description: "Optional markdown description" })
@IsOptional()
@IsString()
description?: string;
@ApiProperty({
description: "Generic key-value map for environment metadata",
example: {
@@ -25,6 +25,11 @@ export class EnvironmentExportDto {
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiProperty()
@IsObject()
data: EnvironmentData;
@@ -0,0 +1,13 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsOptional } from "class-validator";
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
import { EnvironmentOrderBy } from "../environment.service";
const ENVIRONMENT_ORDER_BY: EnvironmentOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
export class EnvironmentQueryDto extends PaginationQueryDto<EnvironmentOrderBy> {
@ApiPropertyOptional({ enum: ENVIRONMENT_ORDER_BY })
@IsOptional()
@IsIn(ENVIRONMENT_ORDER_BY)
declare orderBy?: EnvironmentOrderBy;
}
@@ -11,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { EnvironmentService } from "./environment.service";
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { EnvironmentOrderBy } from "./environment.service";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentService } from "./environment.service";
@ApiTags("environments")
@Controller("environments")
@@ -41,7 +40,7 @@ export class EnvironmentController {
@Get()
@ApiOperation({ summary: "List all environments (paginated)" })
@ApiResponse({ status: 200, description: "Paginated environments" })
findAll(@Query() query: PaginationQueryDto<EnvironmentOrderBy>) {
findAll(@Query() query: EnvironmentQueryDto) {
return this.environmentService.findAll(query);
}
+5 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
@@ -18,6 +18,9 @@ export class EnvironmentEntity {
@Column({ unique: true })
name: string;
@Column("text", { nullable: true })
description: string | null;
@Column("simple-json")
data: EnvironmentData;
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { EnvironmentController } from "./environment.controller";
import { EnvironmentEntity } from "./environment.entity";
import { EnvironmentService } from "./environment.service";
import { EnvironmentController } from "./environment.controller";
@Module({
imports: [TypeOrmModule.forFeature([EnvironmentEntity])],
+31 -10
View File
@@ -5,14 +5,14 @@ import {
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { EnvironmentEntity } from "./environment.entity";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentEntity } from "./environment.entity";
export type EnvironmentOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -71,26 +71,47 @@ export class EnvironmentService {
kind: "environment",
id: env.id,
name: env.name,
description: env.description ?? undefined,
data: env.data,
};
}
async importEnvironment(dto: EnvironmentExportDto): Promise<EnvironmentEntity> {
async importEnvironment(
dto: EnvironmentExportDto,
): Promise<EnvironmentEntity> {
if (dto.id) {
const existing = await this.repo.findOneBy({ id: dto.id });
if (existing) {
Object.assign(existing, { name: dto.name, data: dto.data });
Object.assign(existing, {
name: dto.name,
description: dto.description ?? null,
data: dto.data,
});
return this.repo.save(existing);
}
return this.repo.save(
this.repo.create({ id: dto.id, name: dto.name, data: dto.data }),
this.repo.create({
id: dto.id,
name: dto.name,
description: dto.description ?? null,
data: dto.data,
}),
);
}
const byName = await this.repo.findOneBy({ name: dto.name });
if (byName) {
Object.assign(byName, { data: dto.data });
Object.assign(byName, {
description: dto.description ?? null,
data: dto.data,
});
return this.repo.save(byName);
}
return this.repo.save(this.repo.create({ name: dto.name, data: dto.data }));
return this.repo.save(
this.repo.create({
name: dto.name,
description: dto.description ?? null,
data: dto.data,
}),
);
}
}
+1 -1
View File
@@ -6,8 +6,8 @@ import {
HttpException,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { TraceLogger } from "../common/trace-logger";
@Catch(BadRequestException, InternalServerErrorException)
export class HttpExceptionFilter implements ExceptionFilter {
@@ -4,9 +4,9 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger";
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
+1 -1
View File
@@ -4,8 +4,8 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import type { Request } from "express";
import * as crypto from "crypto";
import type { Request } from "express";
import { Observable } from "rxjs";
import { traceStorage } from "../common/trace-context";
+9 -12
View File
@@ -1,14 +1,14 @@
import { NestFactory } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "./config/app.config";
import { RequestMethod, ValidationPipe } from "@nestjs/common";
import { TraceLogger } from "./common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { TraceInterceptor } from "./interceptors/trace.interceptor";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { name as pkgName, version as pkgVersion } from "../package.json";
import { AppModule } from "./app.module";
import { TraceLogger } from "./common/trace-logger";
import { AppConfig } from "./config/app.config";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { TraceInterceptor } from "./interceptors/trace.interceptor";
async function bootstrap() {
const API_PREFIX = "api/v1";
@@ -34,10 +34,7 @@ async function bootstrap() {
const nodeEnv = config.get("NODE_ENV");
app.enableCors({
origin: [
"http://localhost:5173",
"http://127.0.0.1:5173",
],
origin: ["http://localhost:5173", "http://127.0.0.1:5173"],
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
credentials: true,
});
+6 -4
View File
@@ -1,16 +1,18 @@
import { Module } from "@nestjs/common";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { BrowserModule } from "../browser/browser.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialModule } from "../credential/credential.module";
import { EnvironmentModule } from "../environment/environment.module";
import { ScenarioModule } from "../scenario/scenario.module";
import { SessionModule } from "../session/session.module";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
@Module({
imports: [
SessionModule,
EnvironmentModule,
CredentialModule,
BrowserModule,
CodeExecutorModule,
ScenarioModule,
+294 -41
View File
@@ -7,6 +7,7 @@ import { SessionService } from "../session/session.service";
import { SessionContextService } from "../session/session-context.service";
import { EnvironmentService } from "../environment/environment.service";
import type { EnvironmentData } from "../environment/environment.entity";
import { CredentialService } from "../credential/credential.service";
import { BrowserService } from "../browser/browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "../scenario/scenario.service";
@@ -19,6 +20,7 @@ export class McpService {
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly environmentService: EnvironmentService,
private readonly credentialService: CredentialService,
private readonly browserService: BrowserService,
private readonly codeExecutor: CodeExecutorService,
private readonly scenarioService: ScenarioService,
@@ -86,7 +88,7 @@ export class McpService {
{
description: "Delete a session by numeric ID (closes it first if open)",
inputSchema: {
id: z.string().uuid().describe("Session ID to delete"),
id: z.uuid().describe("Session ID to delete"),
},
},
async ({ id }) => {
@@ -151,7 +153,7 @@ export class McpService {
{
description: "Get an environment record by ID",
inputSchema: {
id: z.string().uuid().describe("Environment ID"),
id: z.uuid().describe("Environment ID"),
},
},
async ({ id }) => {
@@ -179,15 +181,20 @@ export class McpService {
name: z
.string()
.describe("Unique environment name, e.g. liquio-diia-stg"),
description: z
.string()
.optional()
.describe("Optional markdown description"),
data: z
.record(z.string(), z.string())
.describe("Map of string keys to string values"),
},
},
async ({ name, data }) => {
async ({ name, description, data }) => {
try {
const env = await this.environmentService.create({
name,
description,
data: data as EnvironmentData,
});
return {
@@ -205,20 +212,26 @@ export class McpService {
server.registerTool(
"update_environment",
{
description: "Update an existing environment (name and/or data)",
description:
"Update an existing environment (name, description, and/or data)",
inputSchema: {
id: z.string().uuid().describe("Environment ID to update"),
id: z.uuid().describe("Environment ID to update"),
name: z.string().optional().describe("New name"),
description: z
.string()
.optional()
.describe("New markdown description"),
data: z
.record(z.string(), z.string())
.optional()
.describe("New data map"),
},
},
async ({ id, name, data }) => {
async ({ id, name, description, data }) => {
try {
const env = await this.environmentService.update(id, {
name,
description,
data: data as EnvironmentData | undefined,
});
return {
@@ -238,7 +251,7 @@ export class McpService {
{
description: "Delete an environment by ID",
inputSchema: {
id: z.string().uuid().describe("Environment ID to delete"),
id: z.uuid().describe("Environment ID to delete"),
},
},
async ({ id }) => {
@@ -309,7 +322,7 @@ export class McpService {
"exec_code",
{
description:
"Execute arbitrary Playwright JavaScript with `page` and `context` in scope",
"Execute Playwright JS — script receives a single `context` argument (see scenario.md). Use `environmentId` (UUID) and `credentials` (alias → credential UUID) to resolve data from the DB and enable context.getEnv() / context.getCredential() / context.runSnippet().",
inputSchema: {
sessionName: z
.string()
@@ -320,19 +333,56 @@ export class McpService {
code: z
.string()
.describe(
"JavaScript code body to execute (async-safe, may use `page` and `context`)",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
),
url: z
.string()
.url()
.optional()
.describe("Optional URL to navigate to before running code"),
environmentId: z
.string()
.uuid()
.optional()
.describe(
"UUID of an existing environment entity. Its key/value data is available via context.env and context.getEnv().",
),
credentials: z
.record(z.string(), z.string())
.optional()
.describe(
"Map of alias → credential UUID. Each credential is loaded from the DB and available via context.getCredential(alias).",
),
},
},
async ({ sessionName, code, url }) => {
async ({ sessionName, code, url, environmentId, credentials }) => {
try {
this.codeExecutor.validate(code);
const result = await this.browserService.exec(sessionName, code, url);
let environment: EnvironmentData | undefined;
if (environmentId) {
const env = await this.environmentService.findOne(environmentId);
environment = env.data;
}
let resolvedCredentials: Record<string, unknown> | undefined;
if (credentials && Object.keys(credentials).length > 0) {
resolvedCredentials = {};
for (const [alias, credId] of Object.entries(credentials)) {
const cred = await this.credentialService.findOne(credId);
resolvedCredentials[alias] = cred.data
? JSON.parse(cred.data)
: {};
}
}
const result = await this.browserService.exec(
sessionName,
code,
url,
environment,
resolvedCredentials,
);
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
@@ -392,7 +442,7 @@ export class McpService {
{
description: "Get a scenario with its steps by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -418,11 +468,30 @@ export class McpService {
description: "Create a new scenario",
inputSchema: {
name: z.string().describe("Scenario name"),
description: z
.string()
.optional()
.describe("Optional markdown description"),
environmentId: z
.uuid()
.optional()
.describe("Optional linked environment ID"),
timeoutSeconds: z
.number()
.int()
.min(1)
.optional()
.describe("Scenario-level timeout in seconds (default 600)"),
},
},
async ({ name }) => {
async ({ name, description, environmentId, timeoutSeconds }) => {
try {
const scenario = await this.scenarioService.create({ name });
const scenario = await this.scenarioService.create({
name,
description,
environmentId,
timeoutSeconds,
});
return {
content: [
{ type: "text" as const, text: JSON.stringify(scenario) },
@@ -440,15 +509,36 @@ export class McpService {
server.registerTool(
"update_scenario",
{
description: "Update a scenario name",
description: "Update a scenario name and/or description",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
name: z.string().optional().describe("New name"),
description: z
.string()
.optional()
.describe("New markdown description"),
environmentId: z
.uuid()
.nullable()
.optional()
.describe("Linked environment ID (null to unlink)"),
timeoutSeconds: z
.number()
.int()
.min(1)
.nullable()
.optional()
.describe("Scenario-level timeout in seconds (null to reset to default 600)"),
},
},
async ({ id, name }) => {
async ({ id, name, description, environmentId, timeoutSeconds }) => {
try {
const scenario = await this.scenarioService.update(id, { name });
const scenario = await this.scenarioService.update(id, {
name,
description,
environmentId,
timeoutSeconds,
});
return {
content: [
{ type: "text" as const, text: JSON.stringify(scenario) },
@@ -468,7 +558,7 @@ export class McpService {
{
description: "Delete a scenario by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -493,7 +583,7 @@ export class McpService {
{
description: "Add a step to a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Parent scenario ID"),
scenarioId: z.uuid().describe("Parent scenario ID"),
order: z
.number()
.int()
@@ -505,6 +595,12 @@ export class McpService {
.string()
.optional()
.describe("Playwright JS code to execute (exec steps)"),
timeoutSeconds: z
.number()
.int()
.min(1)
.optional()
.describe("Step-level timeout in seconds (default 60, falls back to scenario timeout)"),
},
},
async ({ scenarioId, ...dto }) => {
@@ -527,8 +623,8 @@ export class McpService {
{
description: "Get a single step of a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -551,8 +647,8 @@ export class McpService {
{
description: "Update a step within a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
order: z
.number()
.int()
@@ -565,6 +661,13 @@ export class McpService {
.describe("New step type"),
title: z.string().optional().describe("New step title"),
execCode: z.string().optional().describe("New exec code"),
timeoutSeconds: z
.number()
.int()
.min(1)
.nullable()
.optional()
.describe("Step-level timeout in seconds (null to reset to default)"),
},
},
async ({ scenarioId, stepId, ...dto }) => {
@@ -591,8 +694,8 @@ export class McpService {
{
description: "Delete a step from a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -621,7 +724,7 @@ export class McpService {
description:
"List runs for a scenario (paginated, optionally filtered by status)",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
scenarioId: z.uuid().describe("Scenario ID"),
status: z
.enum(["pending", "in_progress", "pass", "fail"])
.optional()
@@ -664,16 +767,23 @@ export class McpService {
{
description: "Trigger an immediate run of a scenario by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID to run"),
id: z.uuid().describe("Scenario ID to run"),
environmentId: z
.string()
.uuid()
.describe("Environment ID to run the scenario in"),
saveSession: z
.boolean()
.optional()
.describe("Save session after run completes"),
},
},
async ({ id, environmentId }) => {
async ({ id, environmentId, saveSession }) => {
try {
const run = await this.scenarioService.createRun(id, environmentId);
const run = await this.scenarioService.createRun(
id,
environmentId,
saveSession,
);
return {
content: [{ type: "text" as const, text: JSON.stringify(run) }],
};
@@ -692,8 +802,8 @@ export class McpService {
description:
"Get a specific scenario run with all step runs and their outputs",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
scenarioId: z.uuid().describe("Scenario ID"),
runId: z.uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -717,8 +827,8 @@ export class McpService {
description:
"Block until a scenario run reaches pass or fail (max 5 min), then return the full run with step outputs",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
scenarioId: z.uuid().describe("Scenario ID"),
runId: z.uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -736,18 +846,157 @@ export class McpService {
},
);
server.registerTool(
"list_scenario_credentials",
{
description: "List credentials assigned to a scenario",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
},
},
async ({ scenarioId }) => {
try {
const creds =
await this.scenarioService.findScenarioCredentials(scenarioId);
return {
content: [{ type: "text" as const, text: JSON.stringify(creds) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"add_scenario_credential",
{
description:
"Add a credential to a scenario with an alias (used in snippets)",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
credentialId: z.uuid().describe("Credential ID to associate"),
alias: z
.string()
.describe(
"Alias used to reference this credential in step code, e.g. pkcs_key",
),
},
},
async ({ scenarioId, credentialId, alias }) => {
try {
const result = await this.scenarioService.addScenarioCredential(
scenarioId,
{ credentialId, alias },
);
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"remove_scenario_credential",
{
description: "Remove a credential assignment from a scenario",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
scenarioCredentialId: z
.uuid()
.describe(
"Scenario-credential assignment ID (not the credential ID)",
),
},
},
async ({ scenarioId, scenarioCredentialId }) => {
try {
await this.scenarioService.removeScenarioCredential(
scenarioId,
scenarioCredentialId,
);
return {
content: [
{
type: "text" as const,
text: `Credential assignment ${scenarioCredentialId} removed from scenario ${scenarioId}`,
},
],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"list_all_runs",
{
description:
"List runs across all scenarios (paginated, filterable by status)",
inputSchema: {
status: z
.enum(["pending", "in_progress", "pass", "fail"])
.optional()
.describe("Filter by run status"),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number (default 1)"),
limit: z
.number()
.int()
.min(1)
.optional()
.describe("Items per page (default 20)"),
},
},
async ({ status, page, limit }) => {
try {
const result = await this.scenarioService.findAllRuns({
status,
page,
limit,
});
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"export_scenario",
{
description:
"Export a scenario as a portable JSON payload (name + steps)",
inputSchema: {
id: z.string().uuid().describe("Scenario ID to export"),
id: z.uuid().describe("Scenario ID to export"),
},
},
async ({ id }) => {
try {
const exported = await this.scenarioService.exportScenario(id);
const exported = await this.scenarioService.exportScenario(id, {
includeEnvironment: false,
credentialIds: [],
});
return {
content: [
{ type: "text" as const, text: JSON.stringify(exported) },
@@ -769,6 +1018,10 @@ export class McpService {
"Import a scenario from an export payload, creating a new scenario with all its steps",
inputSchema: {
name: z.string().describe("Scenario name"),
description: z
.string()
.optional()
.describe("Optional markdown description"),
steps: z
.array(
z.object({
@@ -785,13 +1038,13 @@ export class McpService {
.describe("Ordered list of steps"),
},
},
async ({ name, steps }) => {
async ({ name, description, steps }) => {
try {
const scenario = await this.scenarioService.importScenario({
kind: "scenario",
name,
steps: steps as Parameters<
typeof this.scenarioService.importScenario
>[0]["steps"],
description,
steps: steps as { title: string | null; execCode: string | null }[],
});
return {
content: [
@@ -1,7 +1,11 @@
import { IsNotEmpty, IsUUID } from "class-validator";
import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from "class-validator";
export class CreateScenarioRunDto {
@IsUUID()
@IsNotEmpty()
environmentId: string;
@IsBoolean()
@IsOptional()
saveSession?: boolean;
}
@@ -1,5 +1,5 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
import { IsInt, IsNotEmpty, IsOptional, IsString, Min } from "class-validator";
export class CreateScenarioStepDto {
@ApiPropertyOptional({ example: "Check login page title" })
@@ -13,4 +13,9 @@ export class CreateScenarioStepDto {
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional({ description: "Step timeout in seconds (default: 60)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number;
}
+18 -2
View File
@@ -1,9 +1,25 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString } from "class-validator";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
export class CreateScenarioDto {
@ApiProperty({ example: "Login and verify cabinet" })
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional({ description: "Optional markdown description" })
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional({ description: "Optional linked environment ID" })
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({ description: "Scenario timeout in seconds (default: 600)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number;
}
@@ -1 +1,15 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsOptional } from "class-validator";
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
import { ScenarioOrderBy } from "../scenario.service";
export { PaginationQueryDto } from "../../common/dto/pagination.dto";
const SCENARIO_ORDER_BY: ScenarioOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
export class ScenarioQueryDto extends PaginationQueryDto<ScenarioOrderBy> {
@ApiPropertyOptional({ enum: SCENARIO_ORDER_BY })
@IsOptional()
@IsIn(SCENARIO_ORDER_BY)
declare orderBy?: ScenarioOrderBy;
}
+9 -14
View File
@@ -1,22 +1,17 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsIn, IsInt, IsOptional, Min } from "class-validator";
import { IsIn, IsOptional } from "class-validator";
import { RunStatus } from "../scenario-run.entity";
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
export class RunsQueryDto {
@ApiPropertyOptional({ example: 1, default: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number = 1;
export type RunOrderBy = "createdAt" | "status" | "scenario.name";
@ApiPropertyOptional({ example: 20, default: 20 })
const RUN_ORDER_BY: RunOrderBy[] = ["createdAt", "status", "scenario.name"];
export class RunsQueryDto extends PaginationQueryDto<RunOrderBy> {
@ApiPropertyOptional({ enum: RUN_ORDER_BY })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
limit?: number = 20;
@IsIn(RUN_ORDER_BY)
declare orderBy?: RunOrderBy;
@ApiPropertyOptional({
enum: ["pending", "in_progress", "pass", "fail"],
@@ -4,11 +4,13 @@ import {
IsArray,
IsIn,
IsNotEmpty,
IsObject,
IsOptional,
IsString,
IsUUID,
ValidateNested,
} from "class-validator";
import { EnvironmentData } from "../../environment/environment.entity";
export class ScenarioStepExportDto {
@ApiPropertyOptional()
@@ -22,7 +24,65 @@ export class ScenarioStepExportDto {
@IsString()
@IsNotEmpty()
execCode: string | null;
}
export class CredentialExportDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(["credential"])
kind?: "credential";
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
id?: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
data?: string | null;
}
export class EnvironmentExportInlineDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(["environment"])
kind?: "environment";
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
id?: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiProperty()
@IsObject()
data: EnvironmentData;
}
export class ScenarioCredentialMappingDto {
@ApiProperty()
@IsUUID()
credentialId: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
alias: string;
}
export class ScenarioExportDto {
@@ -47,9 +107,32 @@ export class ScenarioExportDto {
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({ type: [ScenarioCredentialMappingDto] })
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ScenarioCredentialMappingDto)
credentials?: ScenarioCredentialMappingDto[];
@ApiProperty({ type: [ScenarioStepExportDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => ScenarioStepExportDto)
steps: ScenarioStepExportDto[];
}
/** Union type for multi-entity export array items */
export type ExportEntity =
| EnvironmentExportInlineDto
| CredentialExportDto
| ScenarioExportDto;
@@ -19,4 +19,9 @@ export class UpdateScenarioStepDto {
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional({ description: "Step timeout in seconds (null to use default of 60)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number | null;
}
+17 -1
View File
@@ -1,5 +1,5 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsNotEmpty } from "class-validator";
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
export class UpdateScenarioDto {
@ApiPropertyOptional({ example: "Updated scenario name" })
@@ -7,4 +7,20 @@ export class UpdateScenarioDto {
@IsString()
@IsNotEmpty()
name?: string;
@ApiPropertyOptional({ description: "Optional markdown description" })
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional({ description: "Linked environment ID (null to unlink)" })
@IsOptional()
@IsUUID()
environmentId?: string | null;
@ApiPropertyOptional({ description: "Scenario timeout in seconds (null to use default of 600)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number | null;
}
@@ -1,14 +1,14 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
Unique,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { CredentialEntity } from "../credential/credential.entity";
import { ScenarioEntity } from "./scenario.entity";
@Entity("scenario_credentials")
@Unique(["scenarioId", "alias"])
@@ -1,13 +1,13 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
export type LogLevel = "log" | "warn" | "error";
@@ -1,11 +1,11 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
+23 -7
View File
@@ -1,15 +1,17 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
JoinColumn,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { SessionEntity } from "../session/session.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioEntity } from "./scenario.entity";
export type RunStatus = "pending" | "in_progress" | "pass" | "fail";
@@ -21,16 +23,30 @@ export class ScenarioRunEntity {
@Column("text")
scenarioId: string;
@Column("text", { default: "" })
environmentId: string;
@Column("text", { nullable: true, default: null })
environmentId: string | null;
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioId" })
scenario: ScenarioEntity;
@ManyToOne(() => EnvironmentEntity, { onDelete: "SET NULL", nullable: true })
@JoinColumn({ name: "environmentId" })
environment: EnvironmentEntity;
@Column("text", { nullable: true, default: null })
sessionId: string | null;
@ManyToOne(() => SessionEntity, { onDelete: "SET NULL", nullable: true })
@JoinColumn({ name: "sessionId" })
session: SessionEntity | null;
@Column({ type: "text", default: "pending" })
status: RunStatus;
@Column({ type: "boolean", default: false })
saveSession: boolean;
@OneToMany(() => ScenarioRunStepEntity, (rs) => rs.run, {
cascade: true,
eager: false,
+250 -52
View File
@@ -1,21 +1,28 @@
import { Injectable } from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { traceStorage } from "../common/trace-context";
import { Injectable, OnModuleInit } from "@nestjs/common";
import { Interval } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import * as crypto from "crypto";
import { chromium } from "playwright";
import { Effect } from "effect";
import type { Browser, BrowserContext, Page } from "playwright";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { chromium } from "playwright";
import { Repository } from "typeorm";
import type { ScriptLogger } from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "./scenario.service";
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
import { traceStorage } from "../common/trace-context";
import { TraceLogger } from "../common/trace-logger";
import {
EnvironmentData,
EnvironmentEntity,
} from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { SnippetService } from "../snippet/snippet.service";
import { EnvironmentEntity, EnvironmentData } from "../environment/environment.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioService } from "./scenario.service";
interface BrowserHandle {
browser: Browser;
@@ -24,7 +31,7 @@ interface BrowserHandle {
}
@Injectable()
export class ScenarioSchedulerService {
export class ScenarioSchedulerService implements OnModuleInit {
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
private readonly activeRuns = new Set<string>();
private readonly runBrowsers = new Map<string, BrowserHandle>();
@@ -34,6 +41,12 @@ export class ScenarioSchedulerService {
private readonly runSnippets = new Map<string, Record<string, string>>();
// Cache environment values per run (built once when a run starts)
private readonly runEnvironments = new Map<string, EnvironmentData>();
// Cache scenario-level timeout (seconds) per run
private readonly runScenarioTimeouts = new Map<string, number | null>();
private static readonly DEFAULT_SCENARIO_TIMEOUT_SEC = 600;
private static readonly DEFAULT_STEP_TIMEOUT_SEC = 60;
private static readonly CONCURRENCY_LIMIT = 10;
constructor(
@InjectRepository(ScenarioRunEntity)
@@ -47,8 +60,74 @@ export class ScenarioSchedulerService {
private readonly codeExecutor: CodeExecutorService,
private readonly scenarioService: ScenarioService,
private readonly snippetService: SnippetService,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
) {}
async onModuleInit(): Promise<void> {
const staleRuns = await this.runRepo.find({
where: { status: "in_progress" },
});
if (staleRuns.length === 0) return;
this.logger.error(
`Server restart detected ${staleRuns.length} in-progress run(s) that cannot be recovered — marking as failed`,
);
for (const run of staleRuns) {
this.logger.error(
`Run #${run.id}: marked fail due to server restart (playwright session lost)`,
);
}
await Effect.runPromise(
Effect.forEach(
staleRuns,
(run) =>
Effect.tryPromise(() =>
this.failRun(
run.id,
"Run aborted: server restarted and playwright session could not be recovered",
),
).pipe(
Effect.catchAll((err) =>
Effect.sync(() =>
this.logger.error(
`Run #${run.id}: failRun threw unexpectedly — ${String(err)}`,
),
),
),
),
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
),
);
}
/**
* Marks a run as failed, fails its active step run, cancels any queued
* step runs, and persists an error log entry. Use this for all failure paths.
*/
private async failRun(runId: string, reason: string): Promise<void> {
await this.runRepo.update(runId, { status: "fail" });
// Fail the actively-running step; cancel anything still queued
await this.runStepRepo
.createQueryBuilder()
.update()
.set({ status: "fail" })
.where("runId = :runId AND status = 'in_progress'", { runId })
.execute();
await this.runStepRepo
.createQueryBuilder()
.update()
.set({ status: "cancelled" })
.where("runId = :runId AND status IN (:...statuses)", {
runId,
statuses: ["pending", "waiting"],
})
.execute();
this.persistLog(runId, null, "error", reason);
}
private persistLog(
runId: string,
stepRunId: string | null,
@@ -72,7 +151,7 @@ export class ScenarioSchedulerService {
): (order: number) => Promise<unknown> {
return async (order: number) => {
const targetOrder = order < 0 ? stepRun.order + order : order;
if (targetOrder < 0) return null;
if (targetOrder < 1) return null;
const sr = await this.runStepRepo.findOne({
where: { runId: stepRun.runId, order: targetOrder },
});
@@ -90,36 +169,68 @@ export class ScenarioSchedulerService {
@Interval(1000)
async pickUpPendingRuns(): Promise<void> {
const pending = await this.runRepo.find({ where: { status: "pending" } });
for (const run of pending) {
if (this.activeRuns.has(run.id)) continue;
this.activeRuns.add(run.id);
run.status = "in_progress";
await this.runRepo.save(run);
this.logger.log(`Run #${run.id} → in_progress`);
// Pre-load credential map for the scenario
const credMap = await this.scenarioService
.buildCredentialMap(run.scenarioId)
.catch(() => ({}) as Record<string, unknown>);
this.runCredentials.set(run.id, credMap);
// Pre-load snippet map
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
this.runSnippets.set(run.id, snippetMap);
// Pre-load selected environment data
const environmentData = await this.environmentRepo
.findOneBy({ id: run.environmentId })
.then((env) => env?.data ?? {})
.catch(() => ({} as EnvironmentData));
this.runEnvironments.set(run.id, environmentData);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
this.processRunToCompletion(run.id),
);
}
const newRuns = pending.filter((run) => !this.activeRuns.has(run.id));
if (newRuns.length === 0) return;
await Effect.runPromise(
Effect.forEach(
newRuns,
(run) => {
this.activeRuns.add(run.id);
return Effect.tryPromise(async () => {
run.status = "in_progress";
await this.runRepo.save(run);
this.logger.log(`Run #${run.id} → in_progress`);
const credMap = await this.scenarioService
.buildCredentialMap(run.scenarioId)
.catch(() => ({}) as Record<string, unknown>);
this.runCredentials.set(run.id, credMap);
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
this.runSnippets.set(run.id, snippetMap);
const environmentData = await this.environmentRepo
.findOneBy({ id: run.environmentId })
.then((env) => env?.data ?? {})
.catch(() => ({}) as EnvironmentData);
this.runEnvironments.set(run.id, environmentData);
const scenario = await this.scenarioService
.findOne(run.scenarioId)
.catch(() => null);
this.runScenarioTimeouts.set(run.id, scenario?.timeoutSeconds ?? null);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
this.processRunToCompletion(run.id),
);
}).pipe(
Effect.catchAll((err) =>
Effect.promise(async () => {
this.activeRuns.delete(run.id);
this.runCredentials.delete(run.id);
this.runSnippets.delete(run.id);
this.runEnvironments.delete(run.id);
this.runScenarioTimeouts.delete(run.id);
this.logger.error(
`Run #${run.id}: setup failed — ${String(err)}`,
);
await this.failRun(
run.id,
`Run setup failed: ${String(err)}`,
).catch(() => {});
}),
),
);
},
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
),
);
}
private async processRunToCompletion(runId: string): Promise<void> {
const scenarioTimeoutSec =
this.runScenarioTimeouts.get(runId) ??
ScenarioSchedulerService.DEFAULT_SCENARIO_TIMEOUT_SEC;
const scenarioDeadline = Date.now() + scenarioTimeoutSec * 1000;
try {
let stepRun = await this.runStepRepo.findOne({
where: { runId, status: "pending" },
@@ -127,6 +238,16 @@ export class ScenarioSchedulerService {
order: { order: "ASC" },
});
while (stepRun) {
if (Date.now() >= scenarioDeadline) {
this.logger.error(
`Run #${runId}: exceeded scenario timeout of ${scenarioTimeoutSec}s`,
);
await this.failRun(
runId,
`Scenario timed out after ${scenarioTimeoutSec}s`,
);
return;
}
await this.executeStepRun(stepRun);
stepRun = await this.runStepRepo.findOne({
where: { runId, status: "pending" },
@@ -144,12 +265,68 @@ export class ScenarioSchedulerService {
this.logger.error(
`Run #${runId}: unexpected error: ${(err as Error).message}`,
);
await this.runRepo.update(runId, { status: "fail" });
await this.failRun(runId, `Unexpected error: ${(err as Error).message}`);
} finally {
this.activeRuns.delete(runId);
this.runCredentials.delete(runId);
this.runSnippets.delete(runId);
this.runEnvironments.delete(runId);
this.runScenarioTimeouts.delete(runId);
await this.maybePreserveSession(runId);
}
}
/**
* If the run was created with saveSession=true, promote the run's browser
* context to a named explore session instead of closing it.
*/
private async maybePreserveSession(runId: string): Promise<void> {
const run = await this.runRepo.findOneBy({ id: runId });
if (!run?.saveSession) {
await this.closeBrowserHandle(runId);
return;
}
const handle = this.runBrowsers.get(runId);
if (!handle) {
return;
}
const sessionName = `run-${runId}`;
try {
const cookies = await handle.context.cookies();
const localStorage = await handle.page
.evaluate(() => ({ ...window.localStorage }))
.catch((): Record<string, string> => ({}));
const token =
(localStorage["accessToken"] as string | undefined) ??
(localStorage["token"] as string | undefined) ??
cookies.find((c) => c.name === "token")?.value ??
"";
const session = await this.sessionService.upsert(
sessionName,
token,
cookies,
localStorage,
);
await this.runRepo.update(runId, { sessionId: session.id });
this.sessionContextService.register(
sessionName,
handle.browser,
handle.context,
handle.page,
);
// Remove from runBrowsers so closeBrowserHandle won't close it
this.runBrowsers.delete(runId);
this.logger.log(
`Run #${runId}: browser preserved as session "${sessionName}" (${session.id})`,
);
} catch (err) {
this.logger.warn(
`Run #${runId}: failed to preserve session — ${(err as Error).message}`,
);
await this.closeBrowserHandle(runId);
}
}
@@ -172,16 +349,34 @@ export class ScenarioSchedulerService {
const creds = this.runCredentials.get(stepRun.runId);
const snips = this.runSnippets.get(stepRun.runId);
const env = this.runEnvironments.get(stepRun.runId);
const { result: execOutput } = await this.codeExecutor.execute(
page,
context,
step.execCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
creds,
env,
snips,
const execCtx = new ExecContextBuilder()
.page(page)
.browser(context)
.code(step.execCode)
.log(this.stepLogger(stepRun.id, stepRun.runId))
.getStepOutput(getStepOutput)
.credentials(creds)
.environment(env)
.snippets(snips)
.build();
const scenarioTimeoutSec = this.runScenarioTimeouts.get(stepRun.runId) ?? null;
const stepTimeoutSec =
step.timeoutSeconds ??
scenarioTimeoutSec ??
ScenarioSchedulerService.DEFAULT_STEP_TIMEOUT_SEC;
const stepTimeoutMs = stepTimeoutSec * 1000;
const timeoutPromise = new Promise<never>((_, reject) =>
setTimeout(
() => reject(new Error(`Step timed out after ${stepTimeoutSec}s`)),
stepTimeoutMs,
),
);
const { result: execOutput } = await Promise.race([
this.codeExecutor.execute(execCtx),
timeoutPromise,
]);
await this.passStepRun(stepRun, null, execOutput);
} catch (err) {
@@ -259,7 +454,8 @@ export class ScenarioSchedulerService {
],
});
if (remaining === 0) {
await this.closeBrowserHandle(stepRun.runId);
// Don't close the browser here — maybePreserveSession will handle it
// (either preserving it if saveSession=true, or closing if false)
await this.runRepo.update(stepRun.runId, { status: "pass" });
this.logger.log(`Run #${stepRun.runId} → pass (all steps passed)`);
}
@@ -288,7 +484,9 @@ export class ScenarioSchedulerService {
this.logger.log(`Run #${stepRun.runId}: remaining steps cancelled`);
await this.closeBrowserHandle(stepRun.runId);
// Don't close the browser here — maybePreserveSession (called from
// processRunToCompletion's finally block) will either preserve it as a
// session (saveSession=true) or close it (saveSession=false).
await this.runRepo.update(stepRun.runId, { status: "fail" });
this.logger.log(`Run #${stepRun.runId} → fail`);
}
+7 -4
View File
@@ -1,11 +1,11 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
@@ -32,6 +32,9 @@ export class ScenarioStepEntity {
@Column({ type: "text", nullable: true })
execCode: string | null;
@Column({ type: "int", nullable: true })
timeoutSeconds: number | null;
@CreateDateColumn()
createdAt: Date;
+42 -16
View File
@@ -14,17 +14,16 @@ import {
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Response } from "express";
import { stringify as yamlStringify } from "yaml";
import { ScenarioService } from "./scenario.service";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import { PaginationQueryDto } from "./dto/pagination-query.dto";
import { ScenarioOrderBy } from "./scenario.service";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { CreateScenarioRunDto } from "./dto/create-scenario-run.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { ScenarioQueryDto } from "./dto/pagination-query.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ExportEntity } from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { ScenarioService } from "./scenario.service";
@ApiTags("scenarios")
@Controller("scenarios")
@@ -41,16 +40,16 @@ export class ScenarioController {
}
@Post("import")
@ApiOperation({ summary: "Import a scenario from an export payload" })
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
@ApiResponse({ status: 201, description: "Scenario imported" })
importScenario(@Body() dto: ScenarioExportDto) {
return this.scenarioService.importScenario(dto);
importScenario(@Body() payload: unknown) {
return this.scenarioService.importScenario(payload as any);
}
@Get()
@ApiOperation({ summary: "List all scenarios (paginated)" })
@ApiResponse({ status: 200 })
findAll(@Query() query: PaginationQueryDto<ScenarioOrderBy>) {
findAll(@Query() query: ScenarioQueryDto) {
return this.scenarioService.findAll(query);
}
@@ -97,11 +96,34 @@ export class ScenarioController {
@ApiResponse({ status: 404, description: "Scenario not found" })
async exportScenario(
@Param("id", ParseUUIDPipe) id: string,
@Query("includeEnvironment") includeEnvironment: string,
@Query("credentialIds") credentialIds: string | string[] | undefined,
@Res({ passthrough: true }) res: Response,
) {
const payload = await this.scenarioService.exportScenario(id);
const credIds: string[] = credentialIds
? Array.isArray(credentialIds)
? credentialIds
: credentialIds.split(",").filter(Boolean)
: [];
const entities = await this.scenarioService.exportScenario(id, {
includeEnvironment: includeEnvironment === "true",
credentialIds: credIds,
});
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
return yamlStringify(payload);
// Serialize as YAML stream: each entity separated by a comment header
const kindLabels: Record<string, string> = {
environment: "Environment",
credential: "Credential",
scenario: "Scenario",
};
const parts = (entities as ExportEntity[]).map((entity) => {
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
const comment = `# --- ${label}: ${
(entity as any).name ?? (entity as any).id ?? ""
} ---`;
return `${comment}\n${yamlStringify(entity)}`;
});
return parts.join("\n");
}
// ── Steps ─────────────────────────────────────────────────────────────────
@@ -215,7 +237,11 @@ export class ScenarioController {
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: CreateScenarioRunDto,
) {
return this.scenarioService.createRun(id, dto.environmentId);
return this.scenarioService.createRun(
id,
dto.environmentId,
dto.saveSession,
);
}
@Get(":id/run/:runId")
+20 -4
View File
@@ -1,13 +1,16 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
@Entity("scenarios")
export class ScenarioEntity {
@@ -17,6 +20,19 @@ export class ScenarioEntity {
@Column()
name: string;
@Column("text", { nullable: true })
description: string | null;
@Column({ nullable: true, type: "text" })
environmentId: string | null;
@Column({ type: "int", nullable: true })
timeoutSeconds: number | null;
@ManyToOne(() => EnvironmentEntity, { nullable: true, onDelete: "SET NULL", eager: false })
@JoinColumn({ name: "environmentId" })
environment: EnvironmentEntity | null;
@OneToMany(() => ScenarioStepEntity, (step) => step.scenario, {
cascade: true,
eager: false,
+11 -11
View File
@@ -1,20 +1,20 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { ScenarioService } from "./scenario.service";
import { ScenarioController } from "./scenario.controller";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioController } from "./scenario.controller";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioService } from "./scenario.service";
@Module({
imports: [
+217 -38
View File
@@ -1,29 +1,35 @@
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Like, Repository } from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
import {
CredentialExportDto,
EnvironmentExportInlineDto,
ExportEntity,
ScenarioExportDto,
} from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioEntity } from "./scenario.entity";
export { PaginatedResult } from "../common/dto/pagination.dto";
export type ScenarioOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -77,6 +83,7 @@ export class ScenarioService {
"steps",
"scenarioCredentials",
"scenarioCredentials.credential",
"environment",
],
order: { steps: { order: "ASC" } },
});
@@ -104,8 +111,8 @@ export class ScenarioService {
});
for (let i = 0; i < ordered.length; i += 1) {
const step = ordered[i];
if (step.order !== i) {
step.order = i;
if (step.order !== i + 1) {
step.order = i + 1;
await this.stepRepo.save(step);
}
}
@@ -120,7 +127,7 @@ export class ScenarioService {
const created = await this.stepRepo.save(
this.stepRepo.create({
...dto,
order: currentCount,
order: currentCount + 1,
scenarioId,
title: dto.title ?? null,
execCode: dto.execCode ?? null,
@@ -269,6 +276,15 @@ export class ScenarioService {
}
map[sc.alias] = parsed;
}
if (scs.length > 0) {
const ids = scs.map((sc) => sc.credentialId);
await this.credentialRepo
.createQueryBuilder()
.update()
.set({ lastUsedAt: () => "CURRENT_TIMESTAMP" })
.whereInIds(ids)
.execute();
}
return map;
}
@@ -281,12 +297,14 @@ export class ScenarioService {
await this.findOne(scenarioId); // 404 guard
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const orderBy = query.orderBy ?? "createdAt";
const orderDir = query.orderDir ?? "DESC";
const where: Record<string, unknown> = { scenarioId };
if (query.status) where["status"] = query.status;
const [data, total] = await this.runRepo.findAndCount({
where,
relations: ["stepRuns"],
order: { createdAt: "DESC" },
order: { [orderBy]: orderDir },
skip: (page - 1) * limit,
take: limit,
});
@@ -300,15 +318,19 @@ export class ScenarioService {
> {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const where: Record<string, unknown> = {};
if (query.status) where["status"] = query.status;
const [data, total] = await this.runRepo.findAndCount({
where,
relations: ["stepRuns", "scenario"],
order: { createdAt: "DESC" },
skip: (page - 1) * limit,
take: limit,
});
const orderBy = query.orderBy ?? "createdAt";
const orderDir = query.orderDir ?? "DESC";
const qb = this.runRepo
.createQueryBuilder("run")
.leftJoinAndSelect("run.scenario", "scenario");
if (query.status) qb.where("run.status = :status", { status: query.status });
if (orderBy === "scenario.name") {
qb.orderBy("scenario.name", orderDir);
} else {
qb.orderBy(`run.${orderBy}`, orderDir);
}
qb.skip((page - 1) * limit).take(limit);
const [data, total] = await qb.getManyAndCount();
return { data, total, page, limit } as PaginatedResult<
ScenarioRunEntity & { scenario: ScenarioEntity }
>;
@@ -322,7 +344,12 @@ export class ScenarioService {
await this.findOne(scenarioId); // 404 guard
const run = await this.runRepo.findOne({
where: { id: runId, scenarioId },
relations: ["stepRuns", "stepRuns.scenarioStep"],
relations: [
"stepRuns",
"stepRuns.scenarioStep",
"environment",
"session",
],
order: { stepRuns: { order: "ASC" } },
});
if (!run)
@@ -359,6 +386,7 @@ export class ScenarioService {
async createRun(
scenarioId: string,
environmentId: string,
saveSession = false,
): Promise<ScenarioRunEntity> {
const scenario = await this.findOne(scenarioId);
const environment = await this.environmentRepo.findOneBy({
@@ -369,7 +397,12 @@ export class ScenarioService {
}
const run = await this.runRepo.save(
this.runRepo.create({ scenarioId, environmentId, status: "pending" }),
this.runRepo.create({
scenarioId,
environmentId,
status: "pending",
saveSession,
}),
);
const stepRuns = scenario.steps.map((step, index) =>
@@ -386,44 +419,178 @@ export class ScenarioService {
return this.runRepo.findOne({
where: { id: run.id },
relations: ["stepRuns"],
relations: ["stepRuns", "environment", "session"],
order: { stepRuns: { order: "ASC" } },
}) as Promise<ScenarioRunEntity>;
}
// ── Export / Import ───────────────────────────────────────────────────────
async exportScenario(id: string): Promise<ScenarioExportDto> {
async exportScenario(
id: string,
options: { includeEnvironment: boolean; credentialIds: string[] },
): Promise<ExportEntity[]> {
const scenario = await this.findOne(id);
return {
const entities: ExportEntity[] = [];
// Include environment entity if requested and linked
if (options.includeEnvironment && scenario.environment) {
const envDto: EnvironmentExportInlineDto = {
kind: "environment",
id: scenario.environment.id,
name: scenario.environment.name,
description: scenario.environment.description ?? undefined,
data: scenario.environment.data,
};
entities.push(envDto);
}
// Include selected credentials
if (options.credentialIds.length > 0) {
const creds = scenario.scenarioCredentials ?? [];
for (const sc of creds) {
if (
sc.credential &&
options.credentialIds.includes(sc.credential.id)
) {
const credDto: CredentialExportDto = {
kind: "credential",
id: sc.credential.id,
name: sc.credential.name,
data: sc.credential.data,
};
entities.push(credDto);
}
}
}
// Scenario is always last
const allCreds = scenario.scenarioCredentials ?? [];
const credentialMappings = allCreds
.filter(
(sc) =>
options.credentialIds.length === 0 ||
options.credentialIds.includes(sc.credentialId),
)
.map((sc) => ({ credentialId: sc.credentialId, alias: sc.alias }));
const scenarioDto: ScenarioExportDto = {
kind: "scenario",
id: scenario.id,
name: scenario.name,
description: scenario.description ?? undefined,
environmentId: scenario.environmentId ?? undefined,
credentials: credentialMappings.length > 0 ? credentialMappings : undefined,
steps: scenario.steps.map((s) => ({
title: s.title,
execCode: s.execCode,
})),
};
entities.push(scenarioDto);
return entities;
}
async importScenario(dto: ScenarioExportDto): Promise<ScenarioEntity> {
// Upsert: if id provided and entity exists, replace steps; else create new
async importScenario(
payload: ScenarioExportDto | ExportEntity[],
): Promise<ScenarioEntity> {
// Accept plain {name, steps} objects (no kind) as well as the full export format
const raw = payload as unknown as Record<string, unknown>;
if (!Array.isArray(payload) && !raw["kind"]) {
if (typeof raw["name"] !== "string" || !raw["name"]) {
throw new BadRequestException("name is required");
}
if (!Array.isArray(raw["steps"])) {
throw new BadRequestException("steps must be an array");
}
(payload as unknown as Record<string, unknown>)["kind"] = "scenario";
}
const items: ExportEntity[] = Array.isArray(payload) ? payload : [payload];
let scenarioDto: ScenarioExportDto | undefined;
for (const item of items) {
if (item.kind === "environment") {
await this.environmentRepo
.findOneBy({ id: item.id })
.then(async (existing) => {
if (existing) {
Object.assign(existing, {
name: item.name,
description: (item as EnvironmentExportInlineDto).description ?? null,
data: (item as EnvironmentExportInlineDto).data,
});
return this.environmentRepo.save(existing);
}
return this.environmentRepo.save(
this.environmentRepo.create({
id: item.id,
name: item.name,
description: (item as EnvironmentExportInlineDto).description ?? null,
data: (item as EnvironmentExportInlineDto).data,
}),
);
});
} else if (item.kind === "credential") {
const credItem = item as CredentialExportDto;
const existingCred = credItem.id
? await this.credentialRepo.findOneBy({ id: credItem.id })
: null;
if (existingCred) {
existingCred.name = credItem.name;
existingCred.data = credItem.data ?? null;
await this.credentialRepo.save(existingCred);
} else {
await this.credentialRepo.save(
this.credentialRepo.create({
...(credItem.id ? { id: credItem.id } : {}),
name: credItem.name,
data: credItem.data ?? null,
}),
);
}
} else if (!item.kind || item.kind === "scenario") {
scenarioDto = item as ScenarioExportDto;
}
}
if (!scenarioDto) {
throw new BadRequestException("No scenario entity found in import payload");
}
if (typeof scenarioDto.name !== "string" || !scenarioDto.name) {
throw new BadRequestException("name is required");
}
if (!Array.isArray(scenarioDto.steps)) {
throw new BadRequestException("steps must be an array");
}
const dto = scenarioDto;
let scenario: ScenarioEntity;
if (dto.id) {
const existing = await this.scenarioRepo.findOneBy({ id: dto.id });
if (existing) {
existing.name = dto.name;
existing.description = dto.description ?? null;
existing.environmentId = dto.environmentId ?? existing.environmentId;
scenario = await this.scenarioRepo.save(existing);
// Delete old steps and recreate
await this.stepRepo.delete({ scenarioId: scenario.id });
} else {
scenario = await this.scenarioRepo.save(
this.scenarioRepo.create({ id: dto.id, name: dto.name }),
this.scenarioRepo.create({
id: dto.id,
name: dto.name,
description: dto.description ?? null,
environmentId: dto.environmentId ?? null,
}),
);
}
} else {
scenario = await this.scenarioRepo.save(
this.scenarioRepo.create({ name: dto.name }),
this.scenarioRepo.create({
name: dto.name,
description: dto.description ?? null,
environmentId: dto.environmentId ?? null,
}),
);
}
if (dto.steps.length > 0) {
@@ -438,6 +605,18 @@ export class ScenarioService {
await this.stepRepo.save(steps);
await this.normalizeStepOrder(scenario.id);
}
// Restore credential alias mappings
if (dto.credentials && dto.credentials.length > 0) {
await this.scenarioCredRepo.delete({ scenarioId: scenario.id });
const mappings = dto.credentials.map((c) =>
this.scenarioCredRepo.create({
scenarioId: scenario.id,
credentialId: c.credentialId,
alias: c.alias,
}),
);
await this.scenarioCredRepo.save(mappings);
}
return this.findOne(scenario.id);
}
}
@@ -1,8 +1,8 @@
import {
Injectable,
OnModuleDestroy,
BadRequestException,
Injectable,
NotFoundException,
OnModuleDestroy,
} from "@nestjs/common";
import type { Browser, BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger";
+13
View File
@@ -0,0 +1,13 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsOptional } from "class-validator";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { SessionOrderBy } from "./session.service";
const SESSION_ORDER_BY: SessionOrderBy[] = ["id", "sessionName", "status", "lastUsedAt", "createdAt", "updatedAt"];
export class SessionQueryDto extends PaginationQueryDto<SessionOrderBy> {
@ApiPropertyOptional({ enum: SESSION_ORDER_BY })
@IsOptional()
@IsIn(SESSION_ORDER_BY)
declare orderBy?: SessionOrderBy;
}
@@ -1,10 +1,10 @@
import { Injectable } from "@nestjs/common";
import { Interval } from "@nestjs/schedule";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "../config/app.config";
import { Interval } from "@nestjs/schedule";
import { TraceLogger } from "../common/trace-logger";
import { SessionService } from "./session.service";
import { AppConfig } from "../config/app.config";
import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service";
/**
* Periodically:
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more