Compare commits

..
6 Commits
Author SHA1 Message Date
ars9 b26eb10b3d 1.4.0 2026-04-10 13:09:25 +03:00
ars9 32be7c0a59 feat(export-import): add yaml export/import with id upsert for credentials, snippets, and scenarios
- all entities export a kind field (credential/snippet/scenario) for safe type checking on import
- import upserts by id: overwrites if id exists, creates with explicit id otherwise
- scenario export now includes id and step ids; import deletes old steps before recreating
- add GET /:id/export and POST /import endpoints to credential and snippet controllers
- add UuidBadge ui component: shortens uuid to first+last 4 hex chars, tooltip, clipboard copy with animated ClipboardCheck icon pop
- apply UuidBadge across all entity id display sites (detail pages, card footers, table columns)
- add export/import buttons to CredentialsPage, SnippetsPage, CredentialDetailPage, SnippetDetailPage
2026-04-10 13:09:09 +03:00
ars9 1164289173 feat(snippets): add snippets entity, crud, and auto-browser-per-run
- add Snippet entity with name, description, code; full CRUD backend
- add snippets pages (list, create, edit, detail) and nav entry
- add runSnippet helper in code-executor using new Function with args array
- add result param to execute() so validateCode can access exec output
- remove sessionName from steps; each run now spawns its own fresh browser
- fix waitForURL race by polling localStorage for token instead
2026-04-10 00:22:51 +03:00
ars9 1efbbb38a3 feat(scenarios): add step title, scenario credentials, and environment context in executor
- add nullable title column to scenario steps; exposed in create/edit forms and step table
- add scenario-credential join (many-to-many with CredentialEntity) with CRUD endpoints
- expose environment URLs in code executor helpers via helpers.env and helpers.getEnvUrl()
- resolve and cache environment per run from the login step's environmentName in scheduler
- add section spacing and step table title column to ScenarioDetailPage
2026-04-09 23:37:21 +03:00
ars9 1f3a604940 feat(runs): add runs pages, polling, autorefresh indicator, and scheduler fix
- add global runs page and per-scenario runs/run-detail pages
- run detail page polls every 1s until pass/fail, cleans up on unmount
- runs list pages poll every 10s with AutoRefreshIndicator (pulse on data load)
- fix scheduler: set run to pass after empty step loop to prevent stuck in_progress
- fix table header colors and link cell color for readability
- fix play button to navigate to the new run after creation
- fix package.json import paths in server for Docker build context
2026-04-09 21:58:27 +03:00
ars9 ebcb8b8ff4 refactor(client): group pages by entity and add scenario/step crud
- move environment, scenario, session pages into entity subdirs
- add CreateScenarioPage and EditScenarioPage
- add CreateStepPage and EditStepPage with order/type/session/code fields
- add per-step edit and delete row actions on ScenarioDetailPage
- add step api methods (get, create, update, remove) to api client
- add sectionToolbar, formField, fieldLabel, textarea css utilities
2026-04-09 20:45:34 +03:00
80 changed files with 4388 additions and 395 deletions

No files matched your search

+2 -1
View File
@@ -20,7 +20,8 @@
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-i18next": "^17.0.2",
"react-router-dom": "^7.14.0"
"react-router-dom": "^7.14.0",
"yaml": "^2.8.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
+42 -9
View File
@@ -1,25 +1,43 @@
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Globe, KeyRound, Monitor, ClipboardList } from 'lucide-react';
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare, Braces } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg';
import { EnvironmentsPage } from './pages/EnvironmentsPage';
import { EnvironmentDetailPage } from './pages/EnvironmentDetailPage';
import { CreateEnvironmentPage } from './pages/CreateEnvironmentPage';
import { EditEnvironmentPage } from './pages/EditEnvironmentPage';
import { EnvironmentsPage } from './pages/environment/EnvironmentsPage';
import { EnvironmentDetailPage } from './pages/environment/EnvironmentDetailPage';
import { CreateEnvironmentPage } from './pages/environment/CreateEnvironmentPage';
import { EditEnvironmentPage } from './pages/environment/EditEnvironmentPage';
import { KeysPage } from './pages/KeysPage';
import { SessionsPage } from './pages/SessionsPage';
import { SessionDetailPage } from './pages/SessionDetailPage';
import { ScenariosPage } from './pages/ScenariosPage';
import { ScenarioDetailPage } from './pages/ScenarioDetailPage';
import { SessionsPage } from './pages/session/SessionsPage';
import { SessionDetailPage } from './pages/session/SessionDetailPage';
import { ScenariosPage } from './pages/scenario/ScenariosPage';
import { ScenarioDetailPage } from './pages/scenario/ScenarioDetailPage';
import { CreateScenarioPage } from './pages/scenario/CreateScenarioPage';
import { EditScenarioPage } from './pages/scenario/EditScenarioPage';
import { CreateStepPage } from './pages/scenario/CreateStepPage';
import { EditStepPage } from './pages/scenario/EditStepPage';
import { RunsPage } from './pages/run/RunsPage';
import { RunDetailPage } from './pages/run/RunDetailPage';
import { AllRunsPage } from './pages/run/AllRunsPage';
import { CredentialsPage } from './pages/credential/CredentialsPage';
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
import { SnippetsPage } from './pages/snippet/SnippetsPage';
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
];
export default function App() {
@@ -63,7 +81,22 @@ export default function App() {
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/sessions/:id" element={<SessionDetailPage />} />
<Route path="/scenarios" element={<ScenariosPage />} />
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
<Route path="/credentials" element={<CredentialsPage />} />
<Route path="/credentials/new" element={<CreateCredentialPage />} />
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
<Route path="/runs" element={<AllRunsPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
</main>
+169 -12
View File
@@ -1,11 +1,16 @@
import type {
PaginatedResponse,
Credential,
Environment,
KeysResponse,
ScenarioCredential,
Session,
Scenario,
ScenarioRun,
ScenarioRunDetail,
ScenarioRunStep,
ScenarioStep,
Snippet,
} from './types';
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
@@ -28,13 +33,83 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
return JSON.parse(text) as T;
}
// ── Credentials ───────────────────────────────────────────────────────────────
export const credentials = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Credential>> {
return request(`/credentials?page=${page}&limit=${limit}`);
},
get(id: string): Promise<Credential> {
return request(`/credentials/${id}`);
},
create(name: string, data?: string): Promise<Credential> {
return request('/credentials', {
method: 'POST',
body: JSON.stringify({ name, data }),
});
},
update(id: string, patch: Partial<Pick<Credential, 'name' | 'data'>>): Promise<Credential> {
return request(`/credentials/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: string): Promise<void> {
return request(`/credentials/${id}`, { method: 'DELETE' });
},
exportCredential(id: string): Promise<unknown> {
return request(`/credentials/${id}/export`);
},
importCredential(payload: unknown): Promise<Credential> {
return request('/credentials/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Snippets ──────────────────────────────────────────────────────────────────
export const snippets = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Snippet>> {
return request(`/snippets?page=${page}&limit=${limit}`);
},
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(id: string, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
return request(`/snippets/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: string): Promise<void> {
return request(`/snippets/${id}`, { method: 'DELETE' });
},
exportSnippet(id: string): Promise<unknown> {
return request(`/snippets/${id}/export`);
},
importSnippet(payload: unknown): Promise<Snippet> {
return request('/snippets/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Environments ──────────────────────────────────────────────────────────────
export const environments = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Environment>> {
return request(`/environments?page=${page}&limit=${limit}`);
},
get(id: number): Promise<Environment> {
get(id: string): Promise<Environment> {
return request(`/environments/${id}`);
},
create(name: string, urls: Environment['urls']): Promise<Environment> {
@@ -43,13 +118,13 @@ export const environments = {
body: JSON.stringify({ name, urls }),
});
},
update(id: number, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
update(id: string, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
return request(`/environments/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/environments/${id}`, { method: 'DELETE' });
},
};
@@ -68,10 +143,10 @@ export const sessions = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
return request(`/sessions?page=${page}&limit=${limit}`);
},
get(id: number): Promise<Session> {
get(id: string): Promise<Session> {
return request(`/sessions/${id}`);
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/sessions/${id}`, { method: 'DELETE' });
},
};
@@ -82,7 +157,7 @@ export const scenarios = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
return request(`/scenarios?page=${page}&limit=${limit}`);
},
get(id: number): Promise<Scenario & { steps: ScenarioStep[] }> {
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
return request(`/scenarios/${id}`);
},
create(name: string): Promise<Scenario> {
@@ -91,25 +166,107 @@ export const scenarios = {
body: JSON.stringify({ name }),
});
},
update(id: number, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
return request(`/scenarios/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: number): Promise<void> {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: number): Promise<ScenarioRun> {
run(id: string): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, { method: 'POST' });
},
getRun(scenarioId: number, runId: number): Promise<ScenarioRun> {
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
},
waitForRun(scenarioId: number, runId: number): Promise<ScenarioRun> {
waitForRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}/wait`, { method: 'POST' });
},
listRuns(scenarioId: number, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun>> {
listRuns(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
exportScenario(id: string): Promise<unknown> {
return request(`/scenarios/${id}/export`);
},
importScenario(payload: unknown): Promise<Scenario> {
return request('/scenarios/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
// ── Runs ─────────────────────────────────────────────────────────────────────
export const runs = {
listAll(page = 1, limit = 20, status?: string): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }>> {
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
if (status) q.set('status', status);
return request(`/scenarios/runs?${q}`);
},
list(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
get(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
},
};
// ── Scenario Credentials ──────────────────────────────────────────────────────
export const scenarioCredentials = {
list(scenarioId: string): Promise<ScenarioCredential[]> {
return request(`/scenarios/${scenarioId}/credentials`);
},
add(scenarioId: string, credentialId: string, alias: string): Promise<ScenarioCredential> {
return request(`/scenarios/${scenarioId}/credentials`, {
method: 'POST',
body: JSON.stringify({ credentialId, alias }),
});
},
remove(scenarioId: string, scCredId: string): Promise<void> {
return request(`/scenarios/${scenarioId}/credentials/${scCredId}`, {
method: 'DELETE',
});
},
};
// ── Scenario Steps ────────────────────────────────────────────────────────────
export interface CreateStepPayload {
title?: string;
order: number;
type: 'login' | 'exec' | 'sign';
execCode?: string;
validateCode?: string;
}
export interface UpdateStepPayload {
title?: string;
order?: number;
type?: 'login' | 'exec' | 'sign';
execCode?: string;
validateCode?: string;
}
export const steps = {
get(scenarioId: string, stepId: string): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`);
},
create(scenarioId: string, payload: CreateStepPayload): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps`, {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(scenarioId: string, stepId: string, payload: UpdateStepPayload): Promise<ScenarioStep> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`, {
method: 'PATCH',
body: JSON.stringify(payload),
});
},
remove(scenarioId: string, stepId: string): Promise<void> {
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
},
};
+75 -9
View File
@@ -17,13 +17,35 @@ export interface EnvironmentUrls {
}
export interface Environment {
id: number;
id: string;
name: string;
urls: EnvironmentUrls;
createdAt: string;
updatedAt: string;
}
// ── Credentials ───────────────────────────────────────────────────────────────
export interface Credential {
id: string;
name: string;
data: string | null;
lastUsedAt: string | null;
createdAt: string;
updatedAt: string;
}
// ── Snippets ──────────────────────────────────────────────────────────────────
export interface Snippet {
id: string;
name: string;
description: string | null;
code: string;
createdAt: string;
updatedAt: string;
}
// ── Keys ──────────────────────────────────────────────────────────────────────
export interface KeysResponse {
@@ -35,7 +57,7 @@ export interface KeysResponse {
export type SessionStatus = 'open' | 'closed';
export interface Session {
id: number;
id: string;
sessionName: string;
token: string;
status: SessionStatus;
@@ -49,31 +71,75 @@ export interface Session {
export type StepType = 'login' | 'exec' | 'sign';
export interface ScenarioStep {
id: number;
scenarioId: number;
id: string;
scenarioId: string;
order: number;
type: StepType;
sessionName: string;
title: string | null;
sessionName: string | null;
execCode: string | null;
validateCode: string | null;
createdAt: string;
updatedAt: string;
}
export interface ScenarioCredential {
id: string;
scenarioId: string;
credentialId: string;
alias: string;
credential: Credential;
createdAt: string;
}
export interface Scenario {
id: number;
id: string;
name: string;
steps?: ScenarioStep[];
scenarioCredentials?: ScenarioCredential[];
createdAt: string;
updatedAt: string;
}
export type ScenarioRunStatus = 'pending' | 'running' | 'pass' | 'fail';
export type ScenarioRunStatus = 'pending' | 'in_progress' | 'pass' | 'fail';
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
export type LogLevel = 'log' | 'warn' | 'error';
export interface ScenarioRun {
id: number;
scenarioId: number;
id: string;
scenarioId: string;
scenario?: Pick<Scenario, 'id' | 'name'>;
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
createdAt: string;
updatedAt: string;
}
export interface ScenarioRunStep {
id: string;
runId: string;
scenarioStepId: string;
scenarioStep: ScenarioStep;
status: RunStepStatus;
order: number;
description: string | null;
output: string | null;
createdAt: string;
updatedAt: string;
}
export interface ScenarioRunLog {
id: string;
runId: string;
stepRunId: string | null;
level: LogLevel;
message: string;
createdAt: string;
}
export interface ScenarioRunDetail extends ScenarioRun {
stepRuns: ScenarioRunStep[];
logs: ScenarioRunLog[];
}
+146 -5
View File
@@ -3,14 +3,19 @@
"not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.",
"not_found_environment": "Environment {{id}} does not exist or has been deleted.",
"not_found_credential": "Credential {{id}} does not exist or has been deleted.",
"not_found_scenario": "Scenario {{id}} does not exist or has been deleted.",
"not_found_snippet": "Snippet {{id}} does not exist or has been deleted.",
"generic": "Something went wrong. Please try again."
},
"nav": {
"environments": "Environments",
"credentials": "Credentials",
"snippets": "Snippets",
"keys": "Keys",
"sessions": "Sessions",
"scenarios": "Scenarios"
"scenarios": "Scenarios",
"runs": "Runs"
},
"environments": {
"title": "Environments",
@@ -43,8 +48,35 @@
"field_updated": "Updated",
"section_urls": "URLs"
},
"credentials": {
"title": "Credentials",
"empty": "No credentials yet.",
"loading": "Loading…",
"menu_label": "Credential options",
"action_edit": "Edit",
"action_delete": "Delete",
"action_add": "Add credential",
"action_save": "Create",
"action_update": "Save changes",
"action_cancel": "Cancel",
"create_title": "New Credential",
"edit_title": "Edit Credential",
"form_name": "Name",
"form_name_placeholder": "e.g. staging-api-key",
"form_name_required": "Name is required",
"form_data": "Data (JSON)",
"form_data_placeholder": "{\"token\": \"…\"}",
"form_data_invalid_json": "Must be valid JSON",
"field_id": "ID",
"field_last_used": "Last Used",
"field_created": "Created",
"field_updated": "Updated",
"section_data": "Data",
"action_export": "Export",
"action_import": "Import",
"import_error": "Failed to import credential"
},
"keys": {
"title": "Keys",
"col_name": "Key name",
"empty": "No key files found."
},
@@ -65,8 +97,7 @@
"field_updated": "Updated",
"field_lastUsed": "Last Used"
},
"scenarios": {
"title": "Scenarios",
"scenarios": { "title": "Scenarios",
"col_id": "ID",
"col_name": "Name",
"col_updated": "Updated",
@@ -81,9 +112,39 @@
"field_updated": "Updated",
"steps_heading": "Steps",
"step_order": "#",
"step_title": "Title",
"step_type": "Type",
"step_session": "Session",
"step_updated": "Updated"
"step_updated": "Updated",
"action_add": "New scenario",
"action_edit": "Edit",
"action_runs": "Runs",
"action_export": "Export",
"action_import": "Import",
"import_error": "Failed to import scenario",
"action_save": "Create",
"action_update": "Save changes",
"action_cancel": "Cancel",
"create_title": "New Scenario",
"edit_title": "Edit Scenario",
"form_name": "Name",
"form_name_placeholder": "e.g. Login flow",
"form_name_required": "Name is required",
"credentials_heading": "Credentials",
"cred_empty": "No credentials assigned.",
"cred_col_alias": "Alias",
"cred_col_name": "Credential",
"cred_col_added": "Added",
"cred_action_add": "Add credential",
"cred_action_remove": "Remove",
"cred_action_save": "Add",
"cred_action_cancel": "Cancel",
"cred_form_cred": "Credential",
"cred_form_cred_placeholder": "Select credential…",
"cred_form_cred_required": "Select a credential",
"cred_form_alias": "Alias",
"cred_form_alias_placeholder": "e.g. api_key",
"cred_form_alias_required": "Alias is required"
},
"theme": {
"switch_to_light": "Switch to light theme",
@@ -97,5 +158,85 @@
"range": "{{from}}–{{to}} of {{total}}",
"per_page": "{{count}} per page",
"page_size": "Items per page"
},
"steps": {
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
"action_add": "Add step",
"action_edit": "Edit",
"action_delete": "Delete",
"action_save": "Add step",
"action_update": "Save changes",
"action_cancel": "Cancel",
"form_order": "Order",
"form_order_invalid": "Order must be a non-negative integer",
"form_title": "Title",
"form_title_placeholder": "e.g. Check login page",
"form_type": "Type",
"form_session": "Session name",
"form_session_placeholder": "e.g. my-session",
"form_session_required": "Session name is required",
"form_exec_code": "Exec code",
"form_exec_code_placeholder": "return await page.title();",
"form_validate_code": "Validate code",
"form_validate_code_placeholder": "return { success: result !== null, description: \"…\" };"
},
"runs": {
"title": "Runs",
"loading": "Loading…",
"empty": "No runs yet.",
"action_run": "Run scenario",
"col_id": "ID",
"col_scenario": "Scenario",
"col_status": "Status",
"col_steps": "Steps",
"col_created": "Started",
"field_id": "ID",
"field_status": "Status",
"field_steps": "Steps",
"field_created": "Started",
"field_updated": "Updated",
"steps_heading": "Step runs",
"logs_heading": "Logs",
"step_order": "#",
"step_type": "Type",
"step_session": "Session",
"step_status": "Status",
"step_description": "Result",
"log_level": "Level",
"log_message": "Message",
"log_time": "Time"
},
"snippets": {
"title": "Snippets",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
"action_edit": "Edit",
"action_delete": "Delete",
"action_add": "Add snippet",
"action_save": "Create",
"action_update": "Save changes",
"action_cancel": "Cancel",
"create_title": "New Snippet",
"edit_title": "Edit Snippet",
"form_name": "Name",
"form_name_placeholder": "e.g. clickLoginButton",
"form_name_required": "Name is required",
"form_description": "Description",
"form_description_placeholder": "What does this snippet do?",
"form_code": "Code",
"form_code_placeholder": "await page.click('#login-btn');",
"form_code_required": "Code is required",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
"section_code": "Code",
"action_export": "Export",
"action_import": "Import",
"import_error": "Failed to import snippet"
}
}
+74 -2
View File
@@ -6,14 +6,15 @@
}
.sectionHeading {
margin: var(--space-6) 0 var(--space-3);
margin: 0;
line-height: 1;
font-size: var(--font-size-md);
font-weight: 600;
color: var(--color-text);
}
.stepsSection {
margin-top: var(--space-2);
margin-top: var(--space-6);
}
.breadcrumbs {
@@ -119,6 +120,24 @@
margin-right: calc(-1 * var(--space-1));
}
.pageTitle {
margin: 0;
font-size: var(--font-size-lg);
font-weight: 700;
color: var(--color-text);
}
.linkCell {
color: var(--color-link);
cursor: pointer;
text-decoration: underline;
text-underline-offset: 2px;
}
.linkCell:hover {
color: var(--color-link-hover);
}
.envCardHeader button:hover {
background: color-mix(in srgb, currentColor 15%, transparent) !important;
}
@@ -183,6 +202,47 @@
justify-content: flex-end;
}
.formField {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.fieldLabel {
font-size: var(--font-size-sm);
font-weight: 500;
color: var(--color-text);
}
.textarea {
width: 100%;
padding: var(--space-2) var(--space-3);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
background: var(--color-bg-input, var(--color-bg-raised));
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
resize: vertical;
transition: border-color var(--transition), box-shadow var(--transition);
box-sizing: border-box;
}
.textarea:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent);
}
/* ── Section toolbar ─────────────────────────────────────────────────────── */
.sectionToolbar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-3);
}
/* ── Environment detail page ────────────────────────────────────────────── */
.detailToolbar {
@@ -252,3 +312,15 @@
.envDetailUrlVal a:hover {
text-decoration: underline;
}
/* ── Code block ────────────────────────────────────────────────────────── */
.codeBlock {
margin: 0;
font-family: var(--font-mono, ui-monospace, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
white-space: pre-wrap;
word-break: break-all;
overflow-x: auto;
}
-141
View File
@@ -1,141 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Trash2 } from 'lucide-react';
import { scenarios } from '../api';
import type { Scenario, ScenarioStep } from '../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Notification,
Table,
Timestamp,
type TableColumn,
} from '../ui';
import styles from './Page.module.css';
const STEP_TYPE_VARIANT: Record<string, 'info' | 'warning' | 'success'> = {
login: 'success',
exec: 'info',
sign: 'warning',
};
export function ScenarioDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
scenarios
.get(Number(id))
.then(setScenario)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleRun = async () => {
if (!scenario) return;
await scenarios.run(scenario.id);
};
const handleDelete = async () => {
if (!scenario) return;
await scenarios.remove(scenario.id);
navigate('/scenarios');
};
const stepColumns: TableColumn<ScenarioStep>[] = [
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'type',
header: t('scenarios.step_type'),
width: 90,
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
},
{ key: 'session', header: t('scenarios.step_session'), render: (s) => s.sessionName },
{
key: 'updated',
header: t('scenarios.step_updated'),
width: 140,
render: (s) => <Timestamp value={s.updatedAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button size="sm" onClick={handleRun}>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_scenario', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{scenario && (
<>
<Card>
<DescriptionList
layout="comfortable"
items={[
{ term: t('scenarios.field_id'), detail: scenario.id },
{ term: t('scenarios.field_name'), detail: scenario.name },
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
},
{
term: t('scenarios.field_updated'),
detail: <Timestamp value={scenario.updatedAt} />,
},
]}
/>
</Card>
{scenario.steps.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Table
columns={stepColumns}
data={scenario.steps}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
/>
</div>
)}
</>
)}
</div>
);
}
@@ -0,0 +1,100 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { credentials } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import styles from '../Page.module.css';
export function CreateCredentialPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [name, setName] = useState('');
const [data, setData] = useState('');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('credentials.form_name_required'));
valid = false;
}
if (data.trim()) {
try {
JSON.parse(data.trim());
} catch {
setDataError(t('credentials.form_data_invalid_json'));
valid = false;
}
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
navigate(`/credentials/${credential.id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{ label: t('credentials.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
placeholder={t('credentials.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/credentials')}>
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('credentials.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,135 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Pencil, Trash2 } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
credentials
.get(id)
.then(setCredential)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!credential) return;
await credentials.remove(credential.id);
navigate('/credentials');
};
const handleExport = async () => {
if (!credential) return;
const data = await credentials.exportCredential(credential.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `credential-${credential.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{ label: credential?.name ?? `#${id}` },
]}
/>
{credential && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
{t('credentials.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/credentials/${credential.id}/edit`)}
>
<Pencil size={14} />
{t('credentials.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('credentials.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_credential', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{credential && (
<>
<div className={styles.detailMeta}>
<DescriptionList
layout="comfortable"
items={[
{ term: t('credentials.field_id'), detail: <UuidBadge id={credential.id} /> },
{
term: t('credentials.field_last_used'),
detail: credential.lastUsedAt ? (
<Timestamp value={credential.lastUsedAt} />
) : (
'—'
),
},
{
term: t('credentials.field_created'),
detail: <Timestamp value={credential.createdAt} />,
},
{
term: t('credentials.field_updated'),
detail: <Timestamp value={credential.updatedAt} />,
},
]}
/>
</div>
{credential.data && (
<>
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
<Card>
<pre className={styles.codeBlock}>
{(() => {
try {
return JSON.stringify(JSON.parse(credential.data), null, 2);
} catch {
return credential.data;
}
})()}
</pre>
</Card>
</>
)}
</>
)}
</div>
);
}
@@ -0,0 +1,162 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, Pencil, Trash2, Plus, Upload } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
function CredentialCard({
credential,
onDelete,
}: {
credential: Credential;
onDelete: (id: string) => void;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{credential.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('credentials.menu_label')}>
<Settings size={14} />
</Button>
}
items={[
{
label: t('credentials.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/credentials/${credential.id}/edit`),
},
{
label: t('credentials.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(credential.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<UuidBadge id={credential.id} />
<Timestamp value={credential.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/credentials/${credential.id}`)}
>
<DescriptionList
layout="compact"
truncate
items={[
{
term: t('credentials.field_last_used'),
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
},
]}
/>
</Card>
);
}
function AddCredentialCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/credentials/new')}>
<Plus size={16} />
{t('credentials.action_add')}
</Button>
</div>
);
}
export function CredentialsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
credentials
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const handleDelete = async (id: string) => {
await credentials.remove(id);
setItems((prev) => prev.filter((c) => c.id !== id));
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await credentials.importCredential(payload);
navigate(`/credentials/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('credentials.title') }]} className={styles.breadcrumbs} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
{t('credentials.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading ? (
<p className={styles.muted}>{t('credentials.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((credential) => (
<CredentialCard key={credential.id} credential={credential} onDelete={handleDelete} />
))}
<AddCredentialCard />
</div>
)}
</div>
);
}
@@ -0,0 +1,131 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import styles from '../Page.module.css';
export function EditCredentialPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [name, setName] = useState('');
const [data, setData] = useState('');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
credentials
.get(id)
.then((c) => {
setCredential(c);
setName(c.name);
setData(c.data ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('credentials.form_name_required'));
valid = false;
}
if (data.trim()) {
try {
JSON.parse(data.trim());
} catch {
setDataError(t('credentials.form_data_invalid_json'));
valid = false;
}
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
navigate(`/credentials/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
},
{ label: t('credentials.edit_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{!loading && credential && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
placeholder={t('credentials.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/credentials/${id}`)}
>
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('credentials.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -1,9 +1,9 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { environments } from '../api';
import { Breadcrumbs, Button, Card, Input } from '../ui';
import styles from './Page.module.css';
import { environments } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function CreateEnvironmentPage() {
const { t } = useTranslation();
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, Input } from '../ui';
import styles from './Page.module.css';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function EditEnvironmentPage() {
const { t } = useTranslation();
@@ -24,7 +24,7 @@ export function EditEnvironmentPage() {
useEffect(() => {
if (!id) return;
environments
.get(Number(id))
.get(id)
.then((data) => {
setEnv(data);
setName(data.name);
@@ -45,7 +45,7 @@ export function EditEnvironmentPage() {
setSaving(true);
setError(null);
try {
await environments.update(Number(id), {
await environments.update(id!, {
name: name.trim(),
urls: {
id_url: idUrl.trim() || undefined,
@@ -2,10 +2,10 @@ import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Pencil, Trash2 } from 'lucide-react';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../ui';
import styles from './Page.module.css';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
@@ -18,7 +18,7 @@ export function EnvironmentDetailPage() {
useEffect(() => {
if (!id) return;
environments
.get(Number(id))
.get(id)
.then(setEnv)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
@@ -2,12 +2,12 @@ import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, ExternalLink, Pencil, Trash2, Plus } from 'lucide-react';
import { environments } from '../api';
import type { Environment } from '../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp } from '../ui';
import styles from './Page.module.css';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: number) => void }) {
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const urlEntries = Object.entries(env.urls).filter(([, v]) => v);
@@ -48,7 +48,7 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: n
const footer = (
<div className={styles.envCardFooter}>
<span className={styles.envCardId}>#{env.id}</span>
<UuidBadge id={env.id} />
<Timestamp value={env.updatedAt} />
</div>
);
@@ -106,7 +106,7 @@ export function EnvironmentsPage() {
load();
}, []);
const handleDelete = async (id: number) => {
const handleDelete = async (id: string) => {
await environments.remove(id);
setItems((prev) => prev.filter((e) => e.id !== id));
};
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { runs } from '../../api';
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import { AutoRefreshIndicator, Badge, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
const STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
type AllRunRow = ScenarioRun & {
stepRuns: ScenarioRunStep[];
scenario: { id: number; 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 load = () => {
runs
.listAll()
.then((res) => {
setItems(res.data as AllRunRow[]);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
useEffect(() => {
setLoading(true);
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
const columns: TableColumn<AllRunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'scenario',
header: t('runs.col_scenario'),
render: (r) => (
<span
className={styles.linkCell}
onClick={(e) => {
e.stopPropagation();
navigate(`/scenarios/${r.scenario.id}`);
}}
>
{r.scenario.name}
</span>
),
},
{
key: 'status',
header: t('runs.col_status'),
width: 110,
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',
header: t('runs.col_created'),
width: 160,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<h1 className={styles.pageTitle}>{t('runs.title')}</h1>
<AutoRefreshIndicator active pulseKey={pulseKey} />
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
/>
</div>
);
}
+232
View File
@@ -0,0 +1,232 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { runs } from '../../api';
import type {
Scenario,
ScenarioRunDetail,
ScenarioRunStep,
ScenarioRunLog,
ScenarioRunStatus,
RunStepStatus,
LogLevel,
} from '../../api';
import { scenarios } from '../../api';
import {
AutoRefreshIndicator,
Badge,
Breadcrumbs,
Card,
DescriptionList,
Notification,
Table,
Timestamp,
UuidBadge,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const RUN_STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
const STEP_STATUS_VARIANT: Record<RunStepStatus, BadgeVariant> = {
waiting: 'neutral',
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
cancelled: 'warning',
};
const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
log: 'neutral',
warn: 'warning',
error: 'error',
};
export function RunDetailPage() {
const { t } = useTranslation();
const { id, runId } = useParams<{ id: string; runId: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [polling, setPolling] = useState(false);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
const stopPolling = () => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
setPolling(false);
}
};
useEffect(() => {
if (!id || !runId) return;
let cancelled = false;
Promise.all([scenarios.get(id), runs.get(id, runId)])
.then(([sc, r]) => {
if (cancelled) return;
setScenario(sc);
setRun(r);
if (!FINAL.includes(r.status)) {
setPolling(true);
pollRef.current = setInterval(async () => {
try {
const updated = await runs.get(id, runId);
if (cancelled) return;
setRun(updated);
setPulseKey((k) => k + 1);
if (FINAL.includes(updated.status)) stopPolling();
} catch {
stopPolling();
}
}, 1000);
}
})
.catch((err: Error) => { if (!cancelled) setError(err.message); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => {
cancelled = true;
stopPolling();
};
}, [id, runId]);
const stepColumns: TableColumn<ScenarioRunStep>[] = [
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
{
key: 'type',
header: t('runs.step_type'),
width: 80,
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? '–'}</Badge>,
},
{
key: 'status',
header: t('runs.step_status'),
width: 110,
render: (s) => (
<Badge variant={STEP_STATUS_VARIANT[s.status]}>{s.status.replace('_', ' ')}</Badge>
),
},
{
key: 'description',
header: t('runs.step_description'),
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
},
];
const logColumns: TableColumn<ScenarioRunLog>[] = [
{
key: 'level',
header: t('runs.log_level'),
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
{
key: 'time',
header: t('runs.log_time'),
width: 160,
render: (l) => <Timestamp value={l.createdAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
label: t('runs.title'),
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
]}
/>
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} />
</div>
{error && (
<Notification variant="error">
{error.startsWith('404') ? t('errors.not_found') : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
{run && (
<>
<Card>
<DescriptionList
layout="comfortable"
items={[
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_steps'), detail: run.stepRuns.length },
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
]}
/>
</Card>
{run.stepRuns.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('runs.steps_heading')}</h2>
<Table
columns={stepColumns}
data={run.stepRuns}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
/>
</div>
)}
{run.logs.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<Table
columns={logColumns}
data={run.logs}
rowKey={(l) => l.id}
loading={false}
emptyMessage=""
/>
</div>
)}
</>
)}
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play } from 'lucide-react';
import { scenarios, runs } from '../../api';
import type { Scenario, ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import { AutoRefreshIndicator, Badge, Breadcrumbs, Button, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
const STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
pending: 'neutral',
in_progress: 'info',
pass: 'success',
fail: 'error',
};
const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
pending: 'Pending',
in_progress: 'Running',
pass: 'Pass',
fail: 'Fail',
};
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
export function RunsPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [items, setItems] = useState<RunRow[]>([]);
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 load = useCallback(() => {
if (!id) return;
setLoading(true);
Promise.all([scenarios.get(id!), runs.list(id!)])
.then(([sc, res]) => {
setScenario(sc);
setItems(res.data);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
useEffect(() => {
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [load]);
const handleRun = async () => {
const run = await scenarios.run(id!);
navigate(`/scenarios/${id}/runs/${run.id}`);
};
const columns: TableColumn<RunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
{
key: 'status',
header: t('runs.col_status'),
width: 100,
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',
header: t('runs.col_created'),
width: 160,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('runs.title') },
]}
/>
<div className={styles.toolbarActions}>
<AutoRefreshIndicator active pulseKey={pulseKey} />
<Button size="sm" onClick={handleRun}>
<Play size={14} />
{t('runs.action_run')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
/>
</div>
);
}
@@ -0,0 +1,77 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function CreateScenarioPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [name, setName] = useState('');
const [nameError, setNameError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const scenario = await scenarios.create(name.trim());
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('scenarios.form_name')}
placeholder={t('scenarios.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/scenarios')}>
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('scenarios.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,136 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios, steps } from '../../api';
import type { Scenario, StepType } from '../../api';
import type { CreateStepPayload } from '../../api/client';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
export function CreateStepPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [order, setOrder] = useState('0');
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [errors, setErrors] = useState<Partial<Record<keyof CreateStepPayload, string>>>({});
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
scenarios.get(id).then(setScenario).catch(() => null);
}, [id]);
const validate = (): boolean => {
const next: typeof errors = {};
if (isNaN(Number(order)) || Number(order) < 0) next.order = t('steps.form_order_invalid');
setErrors(next);
return Object.keys(next).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validate()) return;
setSaving(true);
setError(null);
try {
await steps.create(id!, {
order: Number(order),
title: title.trim() || undefined,
type,
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
});
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => setOrder(e.target.value)}
error={errors.order}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate(`/scenarios/${id}`)}>
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('steps.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,104 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function EditScenarioPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [name, setName] = useState('');
const [nameError, setNameError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
scenarios
.get(id)
.then((data) => {
setScenario(data);
setName(data.name);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('scenarios.edit_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{!loading && scenario && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('scenarios.form_name')}
placeholder={t('scenarios.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('scenarios.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
+160
View File
@@ -0,0 +1,160 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { scenarios, steps } from '../../api';
import type { Scenario, ScenarioStep, StepType } from '../../api';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
export function EditStepPage() {
const { t } = useTranslation();
const { id, stepId } = useParams<{ id: string; stepId: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [step, setStep] = useState<ScenarioStep | null>(null);
const [order, setOrder] = useState('');
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [orderError, setOrderError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id || !stepId) return;
Promise.all([scenarios.get(id), steps.get(id, stepId)])
.then(([sc, st]) => {
setScenario(sc);
setStep(st);
setOrder(String(st.order));
setTitle(st.title ?? '');
setType(st.type);
setExecCode(st.execCode ?? '');
setValidateCode(st.validateCode ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id, stepId]);
const validate = (): boolean => {
let valid = true;
if (isNaN(Number(order)) || Number(order) < 0) {
setOrderError(t('steps.form_order_invalid'));
valid = false;
}
return valid;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validate()) return;
setSaving(true);
setError(null);
try {
await steps.update(id!, stepId!, {
order: Number(order),
title: title.trim() || undefined,
type,
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
});
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.edit_title', { order: step?.order ?? stepId }) },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('steps.loading')}</p>}
{!loading && step && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => {
setOrder(e.target.value);
setOrderError('');
}}
error={orderError || undefined}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
{t('steps.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,373 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Pencil, Plus, History, Trash2, Download } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Input,
Notification,
Select,
Table,
Timestamp,
UuidBadge,
type TableColumn,
} from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPE_VARIANT: Record<string, 'info' | 'warning' | 'success'> = {
login: 'success',
exec: 'info',
sign: 'warning',
};
export function ScenarioDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
const [allCredentials, setAllCredentials] = useState<Credential[]>([]);
const [addCredOpen, setAddCredOpen] = useState(false);
const [addCredId, setAddCredId] = useState('');
const [addAlias, setAddAlias] = useState('');
const [addCredError, setAddCredError] = useState('');
const [addAliasError, setAddAliasError] = useState('');
const [addCredSaving, setAddCredSaving] = useState(false);
useEffect(() => {
if (!id) return;
scenarios
.get(id)
.then((s) => {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
credentialsApi
.list(1, 200)
.then((r) => setAllCredentials(r.data))
.catch(() => {});
}, [id]);
const handleRun = async () => {
if (!scenario) return;
const run = await scenarios.run(scenario.id);
navigate(`/scenarios/${id}/runs/${run.id}`);
};
const handleDelete = async () => {
if (!scenario) return;
await scenarios.remove(scenario.id);
navigate('/scenarios');
};
const handleExport = async () => {
if (!scenario) return;
const data = await scenarios.exportScenario(scenario.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
const handleDeleteStep = async (stepId: string) => {
await steps.remove(id!, stepId);
setScenario((prev) =>
prev ? { ...prev, steps: prev.steps.filter((s) => s.id !== stepId) } : prev,
);
};
const handleAddCredential = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!addCredId) { setAddCredError(t('scenarios.cred_form_cred_required')); valid = false; }
if (!addAlias.trim()) { setAddAliasError(t('scenarios.cred_form_alias_required')); valid = false; }
if (!valid) return;
setAddCredSaving(true);
try {
const sc = await scenarioCredentials.add(id!, addCredId, addAlias.trim());
// Re-fetch the credential object since the response may not include it
const full = await scenarioCredentials.list(id!);
setScenarioCreds(full);
void sc;
setAddCredOpen(false);
setAddCredId('');
setAddAlias('');
} catch (err) {
setAddCredError((err as Error).message);
} finally {
setAddCredSaving(false);
}
};
const handleRemoveCredential = async (scCredId: string) => {
await scenarioCredentials.remove(id!, scCredId);
setScenarioCreds((prev) => prev.filter((sc) => sc.id !== scCredId));
};
const stepColumns: TableColumn<ScenarioStep>[] = [
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'type',
header: t('scenarios.step_type'),
width: 90,
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
},
{
key: 'title',
header: t('scenarios.step_title'),
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>,
},
{
key: 'updated',
header: t('scenarios.step_updated'),
width: 140,
render: (s) => <Timestamp value={s.updatedAt} />,
},
{
key: 'actions',
header: '',
width: 80,
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button
size="sm"
variant="secondary"
title={t('steps.action_edit')}
onClick={(e) => {
e.stopPropagation();
navigate(`/scenarios/${id}/steps/${s.id}/edit`);
}}
>
<Pencil size={14} />
</Button>
<Button
size="sm"
variant="danger"
title={t('steps.action_delete')}
onClick={(e) => {
e.stopPropagation();
handleDeleteStep(s.id);
}}
>
<Trash2 size={14} />
</Button>
</span>
),
},
];
const credColumns: TableColumn<ScenarioCredential>[] = [
{ key: 'alias', header: t('scenarios.cred_col_alias'), render: (sc) => sc.alias },
{
key: 'name',
header: t('scenarios.cred_col_name'),
render: (sc) => sc.credential?.name ?? `#${sc.credentialId}`,
},
{
key: 'added',
header: t('scenarios.cred_col_added'),
width: 140,
render: (sc) => <Timestamp value={sc.createdAt} />,
},
{
key: 'actions',
header: '',
width: 60,
align: 'right',
render: (sc) => (
<Button
size="sm"
variant="danger"
title={t('scenarios.cred_action_remove')}
onClick={(e) => {
e.stopPropagation();
handleRemoveCredential(sc.id);
}}
>
<Trash2 size={14} />
</Button>
),
},
];
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button size="sm" onClick={handleRun}>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/runs`)}>
<History size={14} />
{t('scenarios.action_runs')}
</Button>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
{t('scenarios.action_export')}
</Button>
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
<Pencil size={14} />
{t('scenarios.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_scenario', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{scenario && (
<>
<Card>
<DescriptionList
layout="comfortable"
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
},
{
term: t('scenarios.field_updated'),
detail: <Timestamp value={scenario.updatedAt} />,
},
]}
/>
</Card>
{scenario.steps.length > 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Button size="sm" onClick={() => navigate(`/scenarios/${id}/steps/new`)}>
<Plus size={14} />
{t('steps.action_add')}
</Button>
</div>
<Table
columns={stepColumns}
data={scenario.steps}
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
/>
</div>
)}
{scenario.steps.length === 0 && (
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.steps_heading')}</h2>
<Button size="sm" onClick={() => navigate(`/scenarios/${id}/steps/new`)}>
<Plus size={14} />
{t('steps.action_add')}
</Button>
</div>
</div>
)}
{/* ── Credentials section ──────────────────────────────────── */}
<div className={styles.stepsSection}>
<div className={styles.sectionToolbar}>
<h2 className={styles.sectionHeading}>{t('scenarios.credentials_heading')}</h2>
<Button size="sm" onClick={() => setAddCredOpen((v) => !v)}>
<Plus size={14} />
{t('scenarios.cred_action_add')}
</Button>
</div>
{addCredOpen && (
<div style={{ marginBottom: 'var(--space-4)' }}>
<Card className={styles.formCard}>
<form onSubmit={handleAddCredential} noValidate>
<div className={styles.formFields}>
<Select
label={t('scenarios.cred_form_cred')}
value={addCredId}
onChange={(e) => { setAddCredId(e.target.value); setAddCredError(''); }}
error={addCredError || undefined}
options={[
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
]}
/>
<Input
label={t('scenarios.cred_form_alias')}
placeholder={t('scenarios.cred_form_alias_placeholder')}
value={addAlias}
onChange={(e) => { setAddAlias(e.target.value); setAddAliasError(''); }}
error={addAliasError || undefined}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => { setAddCredOpen(false); setAddCredId(''); setAddAlias(''); }}
>
{t('scenarios.cred_action_cancel')}
</Button>
<Button type="submit" size="sm" loading={addCredSaving}>
{t('scenarios.cred_action_save')}
</Button>
</div>
</form>
</Card>
</div>
)}
{scenarioCreds.length > 0 ? (
<Table
columns={credColumns}
data={scenarioCreds}
rowKey={(sc) => sc.id}
loading={false}
emptyMessage=""
/>
) : (
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
)}
</div>
</>
)}
</div>
);
}
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Trash2 } from 'lucide-react';
import { scenarios } from '../api';
import type { Scenario } from '../api';
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp } from '../ui';
import styles from './Page.module.css';
import { Play, Plus, Trash2, Upload } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function ScenariosPage() {
const { t } = useTranslation();
@@ -14,6 +15,8 @@ export function ScenariosPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
scenarios
.list()
@@ -26,18 +29,33 @@ export function ScenariosPage() {
load();
}, [load]);
const handleRun = async (id: number) => {
await scenarios.run(id);
const handleRun = async (id: string) => {
const run = await scenarios.run(id);
navigate(`/scenarios/${id}/runs/${run.id}`);
};
const handleDelete = async (id: number) => {
const handleDelete = async (id: string) => {
await scenarios.remove(id);
setLoading(true);
load();
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await scenarios.importScenario(payload);
navigate(`/scenarios/${imported.id}`);
} catch (err) {
setError((err as Error).message);
}
};
const columns: TableColumn<Scenario>[] = [
{ key: 'id', header: t('scenarios.col_id'), render: (s) => s.id, width: 60 },
{ 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: 'updated',
@@ -70,7 +88,26 @@ export function ScenariosPage() {
return (
<div>
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
{t('scenarios.action_import')}
</Button>
<Button size="sm" onClick={() => navigate('/scenarios/new')}>
<Plus size={14} />
{t('scenarios.action_add')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
@@ -2,10 +2,10 @@ import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { sessions } from '../api';
import type { Session } from '../api';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../ui';
import styles from './Page.module.css';
import { sessions } from '../../api';
import type { Session } from '../../api';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function SessionDetailPage() {
const { t } = useTranslation();
@@ -18,7 +18,7 @@ export function SessionDetailPage() {
useEffect(() => {
if (!id) return;
sessions
.get(Number(id))
.get(id)
.then(setSession)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
@@ -62,7 +62,7 @@ export function SessionDetailPage() {
<DescriptionList
layout="comfortable"
items={[
{ term: t('sessions.field_id'), detail: session.id },
{ term: t('sessions.field_id'), detail: <UuidBadge id={session.id} /> },
{ term: t('sessions.field_name'), detail: session.sessionName },
{
term: t('sessions.field_status'),
@@ -2,10 +2,10 @@ import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { sessions } from '../api';
import type { Session } from '../api';
import { Badge, Breadcrumbs, Button, Table, type TableColumn, Timestamp } from '../ui';
import styles from './Page.module.css';
import { sessions } from '../../api';
import type { Session } from '../../api';
import { Badge, Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function SessionsPage() {
const { t } = useTranslation();
@@ -26,14 +26,14 @@ export function SessionsPage() {
load();
}, [load]);
const handleDelete = async (id: number) => {
const handleDelete = async (id: string) => {
await sessions.remove(id);
setLoading(true);
load();
};
const columns: TableColumn<Session>[] = [
{ key: 'id', header: t('sessions.col_id'), render: (s) => s.id, width: 60 },
{ key: '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: 'status',
@@ -0,0 +1,113 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import styles from '../Page.module.css';
export function CreateSnippetPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
name: name.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
navigate(`/snippets/${snippet.id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: t('snippets.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
value={code}
onChange={(e) => {
setCode(e.target.value);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
{t('snippets.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,142 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function EditSnippetPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
snippets
.get(id)
.then((s) => {
setSnippet(s);
setName(s.name);
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
navigate(`/snippets/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{
label: snippet?.name ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
},
{ label: t('snippets.edit_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && snippet && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
value={code}
onChange={(e) => {
setCode(e.target.value);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/snippets/${id}`)}
>
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
{t('snippets.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,124 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Pencil, Trash2 } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function SnippetDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
snippets
.get(id)
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!snippet) return;
await snippets.remove(snippet.id);
navigate('/snippets');
};
const handleExport = async () => {
if (!snippet) return;
const data = await snippets.exportSnippet(snippet.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snippet-${snippet.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: snippet?.name ?? `#${id}` },
]}
/>
{snippet && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
{t('snippets.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/snippets/${snippet.id}/edit`)}
>
<Pencil size={14} />
{t('snippets.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('snippets.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_snippet', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{snippet && (
<>
<div className={styles.detailMeta}>
<DescriptionList
layout="comfortable"
items={[
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
{ term: t('snippets.field_name'), detail: snippet.name },
{
term: t('snippets.field_description'),
detail: snippet.description ?? '—',
},
{
term: t('snippets.field_created'),
detail: <Timestamp value={snippet.createdAt} />,
},
{
term: t('snippets.field_updated'),
detail: <Timestamp value={snippet.updatedAt} />,
},
]}
/>
</div>
<div className={styles.stepsSection}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
</div>
<Card>
<pre className={styles.codeBlock}>{snippet.code}</pre>
</Card>
</div>
</>
)}
</div>
);
}
+159
View File
@@ -0,0 +1,159 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Code, Pencil, Trash2, Plus, Upload } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
function SnippetCard({
snippet,
onDelete,
}: {
snippet: Snippet;
onDelete: (id: string) => void;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{snippet.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
<Code size={14} />
</Button>
}
items={[
{
label: t('snippets.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/snippets/${snippet.id}/edit`),
},
{
label: t('snippets.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(snippet.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<UuidBadge id={snippet.id} />
<Timestamp value={snippet.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/snippets/${snippet.id}`)}
>
{snippet.description && (
<p className={styles.muted}>{snippet.description}</p>
)}
</Card>
);
}
function AddSnippetCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/snippets/new')}>
<Plus size={16} />
{t('snippets.action_add')}
</Button>
</div>
);
}
export function SnippetsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const handleDelete = async (id: string) => {
await snippets.remove(id);
load();
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await snippets.importSnippet(payload);
navigate(`/snippets/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
{t('snippets.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && (
<div className={styles.envGrid}>
{items.map((s) => (
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
))}
{items.length === 0 && (
<p className={styles.muted}>{t('snippets.empty')}</p>
)}
<AddSnippetCard />
</div>
)}
</div>
);
}
@@ -0,0 +1,69 @@
.root {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--font-size-xs);
font-family: var(--font-family);
user-select: none;
}
/* ── Dot ──────────────────────────────────────────────────── */
.dot {
position: relative;
width: 10px;
height: 10px;
flex-shrink: 0;
}
.dot::before {
content: '';
position: absolute;
inset: 0;
border-radius: 50%;
transition: background var(--transition);
}
/* ── Pulse ring ───────────────────────────────────────────── */
.ring {
position: absolute;
inset: 0;
border-radius: 50%;
animation: pulse 0.8s ease-out 1;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent);
}
70% {
box-shadow: 0 0 0 7px color-mix(in srgb, var(--color-primary) 0%, transparent);
}
100% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent);
}
}
/* ── Active state ─────────────────────────────────────────── */
.active .dot::before {
background: var(--color-primary);
}
.active .label {
color: var(--color-primary);
font-weight: 600;
}
/* ── Inactive / disabled state ────────────────────────────── */
.inactive .dot::before {
background: var(--color-text-muted);
opacity: 0.4;
}
.inactive .label {
color: var(--color-text-muted);
opacity: 0.5;
}
@@ -0,0 +1,25 @@
import styles from './AutoRefreshIndicator.module.css';
export interface AutoRefreshIndicatorProps {
active: boolean;
pulseKey?: number;
label?: string;
}
export function AutoRefreshIndicator({ active, pulseKey, label = 'Live' }: AutoRefreshIndicatorProps) {
return (
<div
className={[styles.root, active ? styles.active : styles.inactive].join(' ')}
title={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
aria-label={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
aria-live="polite"
>
<span className={styles.dot}>
{pulseKey !== undefined && pulseKey > 0 && (
<span key={pulseKey} className={styles.ring} />
)}
</span>
<span className={styles.label}>{label}</span>
</div>
);
}
+6 -1
View File
@@ -19,12 +19,17 @@
padding: var(--space-3) var(--space-4);
font-weight: 700;
font-size: var(--font-size-xs);
color: var(--color-secondary-fg);
color: #ffffff;
text-transform: uppercase;
letter-spacing: 0.06em;
border-bottom: var(--border-width) solid var(--color-secondary-border);
white-space: nowrap;
background: var(--color-secondary-fg);
}
[data-theme="dark"] .th {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
/* Rounded top corners on first/last header cells */
@@ -0,0 +1,60 @@
.wrapper {
display: flex;
flex-direction: column;
gap: var(--space-1);
font-family: var(--font-family);
width: 100%;
}
.label {
font-size: var(--font-size-sm);
font-weight: 500;
color: var(--color-text);
}
.textarea {
font-family: var(--font-family-mono, monospace);
font-size: var(--font-size-sm);
color: var(--color-text);
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
padding: var(--space-2) var(--space-3);
width: 100%;
outline: none;
resize: vertical;
transition: border-color var(--transition), box-shadow var(--transition);
}
.textarea::placeholder {
color: var(--color-text-muted);
}
.textarea:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}
.textarea:disabled {
opacity: 0.5;
cursor: not-allowed;
background: var(--color-bg-subtle);
}
.hasError {
border-color: var(--color-error-fg);
}
.hasError:focus {
border-color: var(--color-error-fg);
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
}
.hint {
font-size: var(--font-size-xs);
color: var(--color-text-muted);
}
.error {
font-size: var(--font-size-xs);
color: var(--color-error-fg);
}
+40
View File
@@ -0,0 +1,40 @@
import React, { useId } from 'react';
import styles from './Textarea.module.css';
export interface TextareaProps
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'id'> {
label?: string;
hint?: string;
error?: string;
}
export function Textarea({ label, hint, error, className, ...props }: TextareaProps) {
const id = useId();
return (
<div className={styles.wrapper}>
{label && (
<label htmlFor={id} className={styles.label}>
{label}
</label>
)}
<textarea
id={id}
className={[styles.textarea, error ? styles.hasError : '', className]
.filter(Boolean)
.join(' ')}
aria-describedby={error ? `${id}-error` : hint ? `${id}-hint` : undefined}
aria-invalid={error ? true : undefined}
{...props}
/>
{error ? (
<span id={`${id}-error`} className={styles.error} role="alert">
{error}
</span>
) : hint ? (
<span id={`${id}-hint`} className={styles.hint}>
{hint}
</span>
) : null}
</div>
);
}
@@ -0,0 +1,38 @@
.wrapper {
display: inline-flex;
align-items: center;
position: relative;
}
.button {
all: unset;
cursor: pointer;
font: inherit;
color: inherit;
letter-spacing: 0.02em;
}
.button:focus-visible {
outline: 2px solid var(--color-focus-ring);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
.pop {
position: absolute;
left: calc(100% + 4px);
top: 50%;
transform: translateY(-50%);
display: inline-flex;
align-items: center;
color: var(--color-success-fg);
animation: popFade 1s ease forwards;
pointer-events: none;
}
@keyframes popFade {
0% { opacity: 0; transform: translateY(calc(-50% - 4px)); }
20% { opacity: 1; transform: translateY(-50%); }
70% { opacity: 1; transform: translateY(-50%); }
100% { opacity: 0; transform: translateY(calc(-50% - 4px)); }
}
+36
View File
@@ -0,0 +1,36 @@
import { useState } from 'react';
import { ClipboardCheck } from 'lucide-react';
import { Badge } from '../Badge/Badge';
import styles from './UuidBadge.module.css';
export interface UuidBadgeProps {
id: string;
}
export function UuidBadge({ id }: UuidBadgeProps) {
const [copied, setCopied] = useState(false);
const short = `${id.slice(0, 4)}…${id.slice(-4)}`;
const handleClick = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(id).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1000);
});
};
return (
<span className={styles.wrapper} title={copied ? 'Copied!' : id}>
<Badge variant="neutral">
<button type="button" className={styles.button} onClick={handleClick}>
{short}
</button>
</Badge>
{copied && (
<span className={styles.pop} aria-hidden="true">
<ClipboardCheck size={13} />
</span>
)}
</span>
);
}
+9
View File
@@ -1,3 +1,6 @@
export { AutoRefreshIndicator } from './AutoRefreshIndicator/AutoRefreshIndicator';
export type { AutoRefreshIndicatorProps } from './AutoRefreshIndicator/AutoRefreshIndicator';
export { Button } from './Button/Button';
export type { ButtonProps } from './Button/Button';
@@ -7,6 +10,9 @@ export type { BadgeProps, BadgeVariant } from './Badge/Badge';
export { Input } from './Input/Input';
export type { InputProps } from './Input/Input';
export { Textarea } from './Textarea/Textarea';
export type { TextareaProps } from './Textarea/Textarea';
export { Select } from './Select/Select';
export type { SelectProps, SelectOption } from './Select/Select';
@@ -38,3 +44,6 @@ export type { NotificationProps, NotificationVariant } from './Notification/Noti
export { Table } from './Table/Table';
export type { TableProps, TableColumn } from './Table/Table';
export { UuidBadge } from './UuidBadge/UuidBadge';
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
+1
View File
@@ -13,6 +13,7 @@ export default defineConfig({
server: {
proxy: {
'/environments': 'http://localhost:13000',
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': 'http://localhost:13000',
'/sessions': 'http://localhost:13000',
'/scenarios': 'http://localhost:13000',
'/keys': 'http://localhost:13000',
+28 -13
View File
@@ -1,20 +1,19 @@
{
"name": "liquio-qa-bot",
"version": "1.3.0",
"name": "liqa",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "liquio-qa-bot",
"version": "1.3.0",
"name": "liqa",
"version": "1.4.0",
"workspaces": [
"server",
"client"
]
},
"client": {
"name": "liquio-qa-bot-client",
"version": "0.0.1",
"name": "liqa-client",
"dependencies": {
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
@@ -22,7 +21,8 @@
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-i18next": "^17.0.2",
"react-router-dom": "^7.14.0"
"react-router-dom": "^7.14.0",
"yaml": "^2.8.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
@@ -10169,12 +10169,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/liquio-qa-bot": {
"resolved": "server",
"node_modules/liqa-client": {
"resolved": "client",
"link": true
},
"node_modules/liquio-qa-bot-client": {
"resolved": "client",
"node_modules/liqa-server": {
"resolved": "server",
"link": true
},
"node_modules/load-esm": {
@@ -14315,6 +14315,21 @@
"dev": true,
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
"integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
@@ -14400,8 +14415,8 @@
}
},
"server": {
"name": "liquio-qa-bot",
"version": "1.2.0",
"name": "liqa-server",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.3.0",
"version": "1.4.0",
"private": true,
"workspaces": [
"server",
+10
View File
@@ -9,13 +9,18 @@ import { BrowserModule } from "./browser/browser.module";
import { SessionEntity } from "./session/session.entity";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { CredentialEntity } from "./credential/credential.entity";
import { CredentialModule } from "./credential/credential.module";
import { McpModule } from "./mcp/mcp.module";
import { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
import { ScenarioModule } from "./scenario/scenario.module";
import { SnippetEntity } from "./snippet/snippet.entity";
import { SnippetModule } from "./snippet/snippet.module";
@Module({
imports: [
@@ -33,11 +38,14 @@ import { ScenarioModule } from "./scenario/scenario.module";
entities: [
SessionEntity,
EnvironmentEntity,
CredentialEntity,
ScenarioEntity,
ScenarioStepEntity,
ScenarioRunEntity,
ScenarioRunStepEntity,
ScenarioRunLogEntity,
ScenarioCredentialEntity,
SnippetEntity,
],
synchronize: true,
}),
@@ -45,7 +53,9 @@ import { ScenarioModule } from "./scenario/scenario.module";
AuthModule,
BrowserModule,
EnvironmentModule,
CredentialModule,
ScenarioModule,
SnippetModule,
McpModule,
HealthModule,
],
@@ -7,6 +7,7 @@ import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { dumpDom } from "./dom-helpers";
import type { EnvironmentUrls } from "../environment/environment.entity";
export interface ExecResult {
result: unknown;
@@ -47,6 +48,10 @@ export class CodeExecutorService {
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentUrls | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
@@ -55,21 +60,70 @@ export class CodeExecutorService {
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
.join(" ");
const credMap: Record<string, unknown> = credentials ?? {};
const envUrls: EnvironmentUrls = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
// eslint-disable-next-line prefer-const
let pageHelpers: Record<string, unknown>;
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
};
try {
const pageHelpers = {
pageHelpers = {
dumpDom: (selector?: string) => dumpDom(page, selector),
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
};
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
getCredential: (alias: string): unknown => {
if (!(alias in credMap)) {
throw new Error(
`Credential alias "${alias}" not found in this scenario`,
);
}
return credMap[alias];
},
/** All URLs defined for the current environment (may be empty if no environment is set). */
env: { ...envUrls },
/** Returns the URL for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
const value = envUrls[key];
if (value == null) {
throw new Error(
`Environment URL "${key}" is not defined for this environment`,
);
}
return value;
},
/**
* Runs a named snippet by name. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (name: string, ...args: unknown[]): Promise<unknown> => {
const snippetCode = snippetMap[name];
if (snippetCode == null) {
throw new Error(`Snippet "${name}" not found`);
}
const snippetFn = new Function(
"page",
"context",
"helpers",
"console",
"snippetArgs",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
);
return snippetFn(page, context, pageHelpers, fakeConsole, args);
},
};
// Passing `console` as a named parameter shadows the global in the script scope.
@@ -78,11 +132,12 @@ export class CodeExecutorService {
"context",
"helpers",
"console",
"result",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
);
this.logger.debug("Executing user code");
const result = await fn(page, context, pageHelpers, fakeConsole);
return { result };
const execResult = await fn(page, context, pageHelpers, fakeConsole, result);
return { result: execResult };
} catch (err) {
throw new InternalServerErrorException(
`Code execution failed: ${(err as Error).message}`,
@@ -0,0 +1,83 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
ParseUUIDPipe,
Patch,
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
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";
@ApiTags("credentials")
@Controller("credentials")
export class CredentialController {
constructor(private readonly credentialService: CredentialService) {}
@Post()
@ApiOperation({ summary: "Create a new credential" })
@ApiResponse({ status: 201, description: "Credential created" })
create(@Body() dto: CreateCredentialDto) {
return this.credentialService.create(dto);
}
@Post("import")
@ApiOperation({ summary: "Import a credential (upsert by id)" })
@ApiResponse({ status: 201, description: "Credential imported" })
async importCredential(@Body() dto: CredentialExportDto) {
return this.credentialService.importCredential(dto);
}
@Get()
@ApiOperation({ summary: "List all credentials (paginated)" })
@ApiResponse({ status: 200, description: "Paginated credentials" })
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
return this.credentialService.findAll(query);
}
@Get(":id/export")
@ApiOperation({ summary: "Export a credential as a plain object" })
@ApiResponse({ status: 200, description: "Credential export payload" })
@ApiResponse({ status: 404, description: "Credential not found" })
async exportCredential(@Param("id", ParseUUIDPipe) id: string) {
const credential = await this.credentialService.findOne(id);
return this.credentialService.exportCredential(credential);
}
@Get(":id")
@ApiOperation({ summary: "Get credential by ID" })
@ApiResponse({ status: 200, description: "Credential record" })
@ApiResponse({ status: 404, description: "Credential not found" })
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.credentialService.findOne(id);
}
@Patch(":id")
@ApiOperation({ summary: "Update a credential" })
@ApiResponse({ status: 200, description: "Credential updated" })
@ApiResponse({ status: 404, description: "Credential not found" })
update(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateCredentialDto,
) {
return this.credentialService.update(id, dto);
}
@Delete(":id")
@HttpCode(204)
@ApiOperation({ summary: "Delete a credential" })
@ApiResponse({ status: 204, description: "Credential deleted" })
@ApiResponse({ status: 404, description: "Credential not found" })
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.credentialService.remove(id);
}
}
@@ -0,0 +1,28 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";
@Entity("credentials")
export class CredentialEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
name: string;
@Column("text", { nullable: true })
data: string | null;
@Column({ type: "datetime", nullable: true })
lastUsedAt: Date | null;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
@@ -0,0 +1,13 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { CredentialEntity } from "./credential.entity";
import { CredentialService } from "./credential.service";
import { CredentialController } from "./credential.controller";
@Module({
imports: [TypeOrmModule.forFeature([CredentialEntity])],
controllers: [CredentialController],
providers: [CredentialService],
exports: [CredentialService],
})
export class CredentialModule {}
@@ -0,0 +1,77 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
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";
export type CredentialOrderBy = "id" | "name" | "lastUsedAt" | "createdAt" | "updatedAt";
@Injectable()
export class CredentialService {
constructor(
@InjectRepository(CredentialEntity)
private readonly repo: Repository<CredentialEntity>,
) {}
async create(dto: CreateCredentialDto): Promise<CredentialEntity> {
return this.repo.save(this.repo.create({ ...dto, data: dto.data ?? null }));
}
async findAll(
query: PaginationQueryDto<CredentialOrderBy> = {},
): Promise<PaginatedResult<CredentialEntity>> {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const orderBy = query.orderBy ?? "id";
const orderDir = query.orderDir ?? "ASC";
const [data, total] = await this.repo.findAndCount({
order: { [orderBy]: orderDir },
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit };
}
async findOne(id: string): Promise<CredentialEntity> {
const credential = await this.repo.findOneBy({ id });
if (!credential) throw new NotFoundException(`Credential ${id} not found`);
return credential;
}
async update(id: string, dto: UpdateCredentialDto): Promise<CredentialEntity> {
const credential = await this.findOne(id);
Object.assign(credential, dto);
return this.repo.save(credential);
}
async remove(id: string): Promise<void> {
await this.findOne(id);
await this.repo.delete(id);
}
exportCredential(credential: CredentialEntity): CredentialExportDto {
return { kind: "credential", id: credential.id, name: credential.name, data: credential.data };
}
async importCredential(dto: CredentialExportDto): Promise<CredentialEntity> {
if (dto.id) {
const existing = await this.repo.findOneBy({ id: dto.id });
if (existing) {
Object.assign(existing, { name: dto.name, data: dto.data ?? null });
return this.repo.save(existing);
}
return this.repo.save(
this.repo.create({ id: dto.id, name: dto.name, data: dto.data ?? null }),
);
}
return this.repo.save(
this.repo.create({ name: dto.name, data: dto.data ?? null }),
);
}
}
@@ -0,0 +1,17 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class CreateCredentialDto {
@ApiProperty({ example: "my-api-key" })
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional({
description: "JSON-encoded credential payload",
example: '{"token":"abc123","secret":"xyz"}',
})
@IsOptional()
@IsString()
data?: string;
}
@@ -0,0 +1,24 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
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;
}
@@ -0,0 +1,4 @@
import { PartialType } from "@nestjs/swagger";
import { CreateCredentialDto } from "./create-credential.dto";
export class UpdateCredentialDto extends PartialType(CreateCredentialDto) {}
@@ -5,7 +5,7 @@ import {
Get,
HttpCode,
Param,
ParseIntPipe,
ParseUUIDPipe,
Patch,
Post,
Query,
@@ -41,7 +41,7 @@ export class EnvironmentController {
@ApiOperation({ summary: "Get environment by ID" })
@ApiResponse({ status: 200, description: "Environment record" })
@ApiResponse({ status: 404, description: "Environment not found" })
findOne(@Param("id", ParseIntPipe) id: number) {
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.environmentService.findOne(id);
}
@@ -50,7 +50,7 @@ export class EnvironmentController {
@ApiResponse({ status: 200, description: "Environment updated" })
@ApiResponse({ status: 404, description: "Environment not found" })
update(
@Param("id", ParseIntPipe) id: number,
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateEnvironmentDto,
) {
return this.environmentService.update(id, dto);
@@ -61,7 +61,7 @@ export class EnvironmentController {
@ApiOperation({ summary: "Delete an environment" })
@ApiResponse({ status: 204, description: "Environment deleted" })
@ApiResponse({ status: 404, description: "Environment not found" })
remove(@Param("id", ParseIntPipe) id: number) {
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.environmentService.remove(id);
}
}
+2 -2
View File
@@ -15,8 +15,8 @@ export interface EnvironmentUrls {
@Entity("environments")
export class EnvironmentEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({ unique: true })
name: string;
@@ -45,14 +45,14 @@ export class EnvironmentService {
return { data, total, page, limit };
}
async findOne(id: number): Promise<EnvironmentEntity> {
async findOne(id: string): Promise<EnvironmentEntity> {
const env = await this.repo.findOneBy({ id });
if (!env) throw new NotFoundException(`Environment ${id} not found`);
return env;
}
async update(
id: number,
id: string,
dto: UpdateEnvironmentDto,
): Promise<EnvironmentEntity> {
const env = await this.findOne(id);
@@ -60,7 +60,7 @@ export class EnvironmentService {
return this.repo.save(env);
}
async remove(id: number): Promise<void> {
async remove(id: string): Promise<void> {
await this.findOne(id);
await this.repo.delete(id);
}
+1 -1
View File
@@ -8,7 +8,7 @@ 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 { name as pkgName, version as pkgVersion } from "../package.json";
async function bootstrap() {
const logger = new TraceLogger("Bootstrap");
+23 -23
View File
@@ -12,7 +12,7 @@ import { BrowserService } from "../browser/browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "../scenario/scenario.service";
import pkg from "../../../package.json";
import pkg from "../../package.json";
@Injectable()
export class McpService {
@@ -135,7 +135,7 @@ export class McpService {
{
description: "Delete a session by numeric ID (closes it first if open)",
inputSchema: {
id: z.number().int().describe("Session ID to delete"),
id: z.string().uuid().describe("Session ID to delete"),
},
},
async ({ id }) => {
@@ -200,7 +200,7 @@ export class McpService {
{
description: "Get an environment record by ID",
inputSchema: {
id: z.number().int().describe("Environment ID"),
id: z.string().uuid().describe("Environment ID"),
},
},
async ({ id }) => {
@@ -258,7 +258,7 @@ export class McpService {
{
description: "Update an existing environment (name and/or urls)",
inputSchema: {
id: z.number().int().describe("Environment ID to update"),
id: z.string().uuid().describe("Environment ID to update"),
name: z.string().optional().describe("New name"),
urls: z
.record(z.string(), z.string())
@@ -289,7 +289,7 @@ export class McpService {
{
description: "Delete an environment by ID",
inputSchema: {
id: z.number().int().describe("Environment ID to delete"),
id: z.string().uuid().describe("Environment ID to delete"),
},
},
async ({ id }) => {
@@ -443,7 +443,7 @@ export class McpService {
{
description: "Get a scenario with its steps by ID",
inputSchema: {
id: z.number().int().describe("Scenario ID"),
id: z.string().uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -493,7 +493,7 @@ export class McpService {
{
description: "Update a scenario name",
inputSchema: {
id: z.number().int().describe("Scenario ID"),
id: z.string().uuid().describe("Scenario ID"),
name: z.string().optional().describe("New name"),
},
},
@@ -519,7 +519,7 @@ export class McpService {
{
description: "Delete a scenario by ID",
inputSchema: {
id: z.number().int().describe("Scenario ID"),
id: z.string().uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -544,7 +544,7 @@ export class McpService {
{
description: "Add a step to a scenario",
inputSchema: {
scenarioId: z.number().int().describe("Parent scenario ID"),
scenarioId: z.string().uuid().describe("Parent scenario ID"),
order: z
.number()
.int()
@@ -582,8 +582,8 @@ export class McpService {
{
description: "Get a single step of a scenario",
inputSchema: {
scenarioId: z.number().int().describe("Scenario ID"),
stepId: z.number().int().describe("Step ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -606,8 +606,8 @@ export class McpService {
{
description: "Update a step within a scenario",
inputSchema: {
scenarioId: z.number().int().describe("Scenario ID"),
stepId: z.number().int().describe("Step ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
order: z
.number()
.int()
@@ -647,8 +647,8 @@ export class McpService {
{
description: "Delete a step from a scenario",
inputSchema: {
scenarioId: z.number().int().describe("Scenario ID"),
stepId: z.number().int().describe("Step ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -677,7 +677,7 @@ export class McpService {
description:
"List runs for a scenario (paginated, optionally filtered by status)",
inputSchema: {
scenarioId: z.number().int().describe("Scenario ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
status: z
.enum(["pending", "in_progress", "pass", "fail"])
.optional()
@@ -720,7 +720,7 @@ export class McpService {
{
description: "Trigger an immediate run of a scenario by ID",
inputSchema: {
id: z.number().int().describe("Scenario ID to run"),
id: z.string().uuid().describe("Scenario ID to run"),
},
},
async ({ id }) => {
@@ -744,8 +744,8 @@ export class McpService {
description:
"Get a specific scenario run with all step runs and their outputs",
inputSchema: {
scenarioId: z.number().int().describe("Scenario ID"),
runId: z.number().int().describe("Run ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -769,8 +769,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.number().int().describe("Scenario ID"),
runId: z.number().int().describe("Run ID"),
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -794,7 +794,7 @@ export class McpService {
description:
"Export a scenario as a portable JSON payload (name + steps)",
inputSchema: {
id: z.number().int().describe("Scenario ID to export"),
id: z.string().uuid().describe("Scenario ID to export"),
},
},
async ({ id }) => {
@@ -826,7 +826,7 @@ export class McpService {
z.object({
order: z.number().int().min(0).describe("Execution order"),
type: z.enum(["login", "exec", "sign"]).describe("Step type"),
sessionName: z.string().describe("Session name"),
title: z.string().nullable().optional().describe("Step title"),
execCode: z
.string()
.nullable()
@@ -0,0 +1,12 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, IsUUID } from "class-validator";
export class AddScenarioCredentialDto {
@ApiProperty({ example: "uuid-here" })
@IsUUID()
credentialId: string
@ApiProperty({ example: "api_key" })
@IsString()
@IsNotEmpty()
alias: string;
}
@@ -10,6 +10,11 @@ import {
import { StepType } from "../scenario-step.entity";
export class CreateScenarioStepDto {
@ApiPropertyOptional({ example: "Check login page title" })
@IsOptional()
@IsString()
title?: string;
@ApiProperty({ example: 0, description: "Execution order (ascending)" })
@IsInt()
@Min(0)
@@ -19,14 +24,14 @@ export class CreateScenarioStepDto {
@IsIn(["login", "exec", "sign"])
type: StepType;
@ApiProperty({
description:
"Session name used by this step. login steps create it; exec steps consume it.",
@ApiPropertyOptional({
description: "Session name (deprecated — browser is created automatically per run).",
example: "my-session",
})
@IsOptional()
@IsString()
@IsNotEmpty()
sessionName: string;
sessionName?: string;
@ApiPropertyOptional({ example: "return await page.title();" })
@IsOptional()
+20 -2
View File
@@ -7,6 +7,7 @@ import {
IsNotEmpty,
IsOptional,
IsString,
IsUUID,
Min,
ValidateNested,
} from "class-validator";
@@ -22,10 +23,11 @@ export class ScenarioStepExportDto {
@IsIn(["login", "exec", "sign"])
type: StepType;
@ApiProperty()
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
sessionName: string;
title: string | null;
@ApiPropertyOptional()
@IsOptional()
@@ -41,6 +43,22 @@ export class ScenarioStepExportDto {
}
export class ScenarioExportDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(["scenario"])
kind?: "scenario";
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
id?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
title?: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
@@ -10,6 +10,11 @@ import {
import { StepType } from "../scenario-step.entity";
export class UpdateScenarioStepDto {
@ApiPropertyOptional({ example: "Check login page title" })
@IsOptional()
@IsString()
title?: string;
@ApiPropertyOptional({ example: 0 })
@IsOptional()
@IsInt()
@@ -0,0 +1,38 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
Unique,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { CredentialEntity } from "../credential/credential.entity";
@Entity("scenario_credentials")
@Unique(["scenarioId", "alias"])
export class ScenarioCredentialEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column("text")
scenarioId: string;
@Column("text")
credentialId: string;
@Column()
alias: string;
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioId" })
scenario: ScenarioEntity;
@ManyToOne(() => CredentialEntity, { onDelete: "CASCADE", eager: true })
@JoinColumn({ name: "credentialId" })
credential: CredentialEntity;
@CreateDateColumn()
createdAt: Date;
}
@@ -13,18 +13,18 @@ export type LogLevel = "log" | "warn" | "error";
@Entity("scenario_run_logs")
export class ScenarioRunLogEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
runId: number;
@Column("text")
runId: string;
@ManyToOne(() => ScenarioRunEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "runId" })
run: ScenarioRunEntity;
@Column({ nullable: true })
stepRunId: number | null;
@Column({ type: "text", nullable: true })
stepRunId: string | null;
@ManyToOne(() => ScenarioRunStepEntity, {
onDelete: "SET NULL",
@@ -20,11 +20,11 @@ export type RunStepStatus =
@Entity("scenario_run_steps")
export class ScenarioRunStepEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
runId: number;
@Column("text")
runId: string;
@ManyToOne(() => ScenarioRunEntity, (run) => run.stepRuns, {
onDelete: "CASCADE",
@@ -32,8 +32,8 @@ export class ScenarioRunStepEntity {
@JoinColumn({ name: "runId" })
run: ScenarioRunEntity;
@Column()
scenarioStepId: number;
@Column("text")
scenarioStepId: string;
@ManyToOne(() => ScenarioStepEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioStepId" })
+4 -4
View File
@@ -15,11 +15,11 @@ export type RunStatus = "pending" | "in_progress" | "pass" | "fail";
@Entity("scenario_runs")
export class ScenarioRunEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
scenarioId: number;
@Column("text")
scenarioId: string;
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioId" })
@@ -14,7 +14,10 @@ import { ScenarioStepEntity } from "./scenario-step.entity";
import type { ScriptLogger } from "../code-executor/code-executor.service";
import { AuthService } from "../auth/auth.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { SessionService } from "../session/session.service";
import { ScenarioService } from "./scenario.service";
import { EnvironmentService } from "../environment/environment.service";
import type { EnvironmentUrls } from "../environment/environment.entity";
import { SnippetService } from "../snippet/snippet.service";
interface ValidateResult {
success: boolean;
@@ -30,8 +33,14 @@ interface BrowserHandle {
@Injectable()
export class ScenarioSchedulerService {
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
private readonly activeRuns = new Set<number>();
private readonly runBrowsers = new Map<number, BrowserHandle>();
private readonly activeRuns = new Set<string>();
private readonly runBrowsers = new Map<string, BrowserHandle>();
// Cache credential maps per run (built once when a run starts)
private readonly runCredentials = new Map<string, Record<string, unknown>>();
// Cache environment URLs per run (resolved from the first login step)
private readonly runEnvironments = new Map<string, EnvironmentUrls>();
// Cache snippet code map per run (built once when a run starts)
private readonly runSnippets = new Map<string, Record<string, string>>();
constructor(
@InjectRepository(ScenarioRunEntity)
@@ -42,12 +51,14 @@ export class ScenarioSchedulerService {
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
private readonly authService: AuthService,
private readonly codeExecutor: CodeExecutorService,
private readonly sessionService: SessionService,
private readonly scenarioService: ScenarioService,
private readonly environmentService: EnvironmentService,
private readonly snippetService: SnippetService,
) {}
private persistLog(
runId: number,
stepRunId: number | null,
runId: string,
stepRunId: string | null,
level: "log" | "warn" | "error",
message: string,
): void {
@@ -56,7 +67,7 @@ export class ScenarioSchedulerService {
);
}
private stepLogger(stepRunId: number, runId: number): ScriptLogger {
private stepLogger(stepRunId: string, runId: string): ScriptLogger {
return (level, msg) => {
this.logger[level](`StepRun #${stepRunId} script: ${msg}`);
this.persistLog(runId, stepRunId, level, msg);
@@ -81,6 +92,30 @@ export class ScenarioSchedulerService {
};
}
/**
* Finds the first login step for a scenario and returns the environment URLs
* for the environment named in that step's execCode. Returns null if there is
* no login step or the environment cannot be found.
*/
private async resolveRunEnvironment(
scenarioId: string,
): Promise<EnvironmentUrls | null> {
try {
const scenario = await this.scenarioService.findOne(scenarioId);
const loginStep = scenario.steps.find((s) => s.type === "login");
if (!loginStep?.execCode) return null;
const params = JSON.parse(loginStep.execCode) as {
environmentName?: string;
};
if (!params.environmentName) return null;
const { data } = await this.environmentService.findAll({});
const env = data.find((e) => e.name === params.environmentName);
return env?.urls ?? null;
} catch {
return null;
}
}
// ── Job: pick up pending runs and process each to completion ─────────────
@Interval(1000)
@@ -92,6 +127,19 @@ export class ScenarioSchedulerService {
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);
// Resolve environment from the first login step (best-effort)
const envUrls = await this.resolveRunEnvironment(run.scenarioId);
if (envUrls) this.runEnvironments.set(run.id, envUrls);
// Pre-load snippet map
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({} as Record<string, string>));
this.runSnippets.set(run.id, snippetMap);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
this.processRunToCompletion(run.id),
@@ -99,7 +147,7 @@ export class ScenarioSchedulerService {
}
}
private async processRunToCompletion(runId: number): Promise<void> {
private async processRunToCompletion(runId: string): Promise<void> {
try {
let stepRun = await this.runStepRepo.findOne({
where: { runId, status: "pending" },
@@ -114,6 +162,12 @@ export class ScenarioSchedulerService {
order: { order: "ASC" },
});
}
await this.runRepo
.createQueryBuilder()
.update()
.set({ status: "pass" })
.where("id = :id AND status = 'in_progress'", { id: runId })
.execute();
} catch (err) {
this.logger.error(
`Run #${runId}: unexpected error: ${(err as Error).message}`,
@@ -121,6 +175,9 @@ export class ScenarioSchedulerService {
await this.runRepo.update(runId, { status: "fail" });
} finally {
this.activeRuns.delete(runId);
this.runCredentials.delete(runId);
this.runEnvironments.delete(runId);
this.runSnippets.delete(runId);
}
}
@@ -150,43 +207,24 @@ export class ScenarioSchedulerService {
// ── Shared browser per run ─────────────────────────────────────────────────
private async getOrCreateBrowserHandle(
runId: number,
sessionName: string,
): Promise<BrowserHandle> {
private async getOrCreateBrowserHandle(runId: string): Promise<BrowserHandle> {
const existing = this.runBrowsers.get(runId);
if (existing) return existing;
const session = await this.sessionService.findBySessionName(sessionName);
if (!session) throw new Error(`Session not found: ${sessionName}`);
const cookies = JSON.parse(session.cookies) as Parameters<
BrowserContext["addCookies"]
>[0];
const localStorageData: Record<string, string> = JSON.parse(
session.localStorage,
);
const browser = await chromium.launch({
headless: true,
// TODO: env var move to config
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext();
await context.addCookies(cookies);
await context.addInitScript((entries: Record<string, string>) => {
for (const [k, v] of Object.entries(entries))
window.localStorage.setItem(k, v);
}, localStorageData);
const page = await context.newPage();
const handle: BrowserHandle = { browser, context, page };
this.runBrowsers.set(runId, handle);
this.logger.log(`Run #${runId}: browser created (session: ${sessionName})`);
this.logger.log(`Run #${runId}: browser created`);
return handle;
}
private async closeBrowserHandle(runId: number): Promise<void> {
private async closeBrowserHandle(runId: string): Promise<void> {
const handle = this.runBrowsers.get(runId);
if (!handle) return;
this.runBrowsers.delete(runId);
@@ -224,7 +262,7 @@ export class ScenarioSchedulerService {
const loginResult = await this.authService.login(
params.keyId,
params.environmentName,
step.sessionName,
step.sessionName ?? undefined,
);
this.logger.log(
`StepRun #${stepRun.id}: login OK, session=${loginResult.sessionName}`,
@@ -233,7 +271,6 @@ export class ScenarioSchedulerService {
if (step.validateCode) {
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
this.codeExecutor.validate(step.validateCode);
const { result } = await this.codeExecutor.execute(
@@ -242,6 +279,10 @@ export class ScenarioSchedulerService {
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
this.makeGetStepOutput(stepRun),
this.runCredentials.get(stepRun.runId),
this.runEnvironments.get(stepRun.runId),
this.runSnippets.get(stepRun.runId),
null,
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
@@ -261,15 +302,20 @@ export class ScenarioSchedulerService {
this.codeExecutor.validate(step.execCode);
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
const getStepOutput = this.makeGetStepOutput(stepRun);
const creds = this.runCredentials.get(stepRun.runId);
const env = this.runEnvironments.get(stepRun.runId);
const snips = this.runSnippets.get(stepRun.runId);
const { result: execOutput } = await this.codeExecutor.execute(
page,
context,
step.execCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
creds,
env,
snips,
);
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
@@ -281,6 +327,10 @@ export class ScenarioSchedulerService {
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
creds,
env,
snips,
execOutput,
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
@@ -306,7 +356,6 @@ export class ScenarioSchedulerService {
const { page, context } = await this.getOrCreateBrowserHandle(
stepRun.runId,
step.sessionName,
);
await this.authService.signWithKey(params.keyId, page);
this.logger.log(`StepRun #${stepRun.id}: sign OK`);
@@ -319,6 +368,10 @@ export class ScenarioSchedulerService {
step.validateCode,
this.stepLogger(stepRun.id, stepRun.runId),
this.makeGetStepOutput(stepRun),
this.runCredentials.get(stepRun.runId),
this.runEnvironments.get(stepRun.runId),
this.runSnippets.get(stepRun.runId),
null,
);
const vr = this.parseValidateResult(result);
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
+9 -6
View File
@@ -13,11 +13,11 @@ export type StepType = "login" | "exec" | "sign";
@Entity("scenario_steps")
export class ScenarioStepEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
scenarioId: number;
@Column("text")
scenarioId: string;
@ManyToOne(() => ScenarioEntity, (scenario) => scenario.steps, {
onDelete: "CASCADE",
@@ -31,8 +31,11 @@ export class ScenarioStepEntity {
@Column({ type: "text" })
type: StepType;
@Column({ type: "text" })
sessionName: string;
@Column({ type: "text", nullable: true })
title: string | null;
@Column({ type: "text", nullable: true })
sessionName: string | null;
@Column({ type: "text", nullable: true })
execCode: string | null;
+60 -18
View File
@@ -5,7 +5,7 @@ import {
Get,
HttpCode,
Param,
ParseIntPipe,
ParseUUIDPipe,
Patch,
Post,
Query,
@@ -16,6 +16,7 @@ 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";
@@ -49,11 +50,18 @@ export class ScenarioController {
return this.scenarioService.findAll(query);
}
@Get("runs")
@ApiOperation({ summary: "List runs across all scenarios (paginated, filterable by status)" })
@ApiResponse({ status: 200 })
findAllRuns(@Query() query: RunsQueryDto) {
return this.scenarioService.findAllRuns(query);
}
@Get(":id")
@ApiOperation({ summary: "Get a scenario with its steps" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findOne(@Param("id", ParseIntPipe) id: number) {
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.findOne(id);
}
@@ -62,7 +70,7 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
update(
@Param("id", ParseIntPipe) id: number,
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateScenarioDto,
) {
return this.scenarioService.update(id, dto);
@@ -73,7 +81,7 @@ export class ScenarioController {
@ApiOperation({ summary: "Delete a scenario and all its steps" })
@ApiResponse({ status: 204 })
@ApiResponse({ status: 404, description: "Scenario not found" })
remove(@Param("id", ParseIntPipe) id: number) {
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.remove(id);
}
@@ -81,7 +89,7 @@ export class ScenarioController {
@ApiOperation({ summary: "Export a scenario as a portable JSON payload" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
exportScenario(@Param("id", ParseIntPipe) id: number) {
exportScenario(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.exportScenario(id);
}
@@ -92,7 +100,7 @@ export class ScenarioController {
@ApiResponse({ status: 201, description: "Step created" })
@ApiResponse({ status: 404, description: "Scenario not found" })
createStep(
@Param("id", ParseIntPipe) id: number,
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: CreateScenarioStepDto,
) {
return this.scenarioService.createStep(id, dto);
@@ -103,8 +111,8 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
findStep(
@Param("id", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
) {
return this.scenarioService.findStep(id, stepId);
}
@@ -114,8 +122,8 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
updateStep(
@Param("id", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
@Body() dto: UpdateScenarioStepDto,
) {
return this.scenarioService.updateStep(id, stepId, dto);
@@ -127,12 +135,46 @@ export class ScenarioController {
@ApiResponse({ status: 204 })
@ApiResponse({ status: 404, description: "Scenario or step not found" })
removeStep(
@Param("id", ParseIntPipe) id: number,
@Param("stepId", ParseIntPipe) stepId: number,
@Param("id", ParseUUIDPipe) id: string,
@Param("stepId", ParseUUIDPipe) stepId: string,
) {
return this.scenarioService.removeStep(id, stepId);
}
// ── Credentials ───────────────────────────────────────────────────────────
@Get(":id/credentials")
@ApiOperation({ summary: "List credentials assigned to a scenario" })
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findScenarioCredentials(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.findScenarioCredentials(id);
}
@Post(":id/credentials")
@ApiOperation({ summary: "Add a credential to a scenario with an alias" })
@ApiResponse({ status: 201, description: "Credential added" })
@ApiResponse({ status: 404, description: "Scenario or credential not found" })
@ApiResponse({ status: 409, description: "Alias already used in this scenario" })
addScenarioCredential(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: AddScenarioCredentialDto,
) {
return this.scenarioService.addScenarioCredential(id, dto);
}
@Delete(":id/credentials/:scCredId")
@HttpCode(204)
@ApiOperation({ summary: "Remove a credential from a scenario" })
@ApiResponse({ status: 204 })
@ApiResponse({ status: 404, description: "Scenario or credential assignment not found" })
removeScenarioCredential(
@Param("id", ParseUUIDPipe) id: string,
@Param("scCredId", ParseUUIDPipe) scCredId: string,
) {
return this.scenarioService.removeScenarioCredential(id, scCredId);
}
// ── Runs ──────────────────────────────────────────────────────────────────
@Get(":id/runs")
@@ -142,7 +184,7 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
findRuns(
@Param("id", ParseIntPipe) id: number,
@Param("id", ParseUUIDPipe) id: string,
@Query() query: RunsQueryDto,
) {
return this.scenarioService.findRuns(id, query);
@@ -152,7 +194,7 @@ export class ScenarioController {
@ApiOperation({ summary: "Create a new run for a scenario" })
@ApiResponse({ status: 201, description: "Run created with step runs" })
@ApiResponse({ status: 404, description: "Scenario not found" })
createRun(@Param("id", ParseIntPipe) id: number) {
createRun(@Param("id", ParseUUIDPipe) id: string) {
return this.scenarioService.createRun(id);
}
@@ -161,8 +203,8 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
findRun(
@Param("id", ParseIntPipe) id: number,
@Param("runId", ParseIntPipe) runId: number,
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
) {
return this.scenarioService.findRun(id, runId);
}
@@ -176,8 +218,8 @@ export class ScenarioController {
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario or run not found" })
waitForRun(
@Param("id", ParseIntPipe) id: number,
@Param("runId", ParseIntPipe) runId: number,
@Param("id", ParseUUIDPipe) id: string,
@Param("runId", ParseUUIDPipe) runId: string,
) {
return this.scenarioService.waitForRun(id, runId);
}
+9 -2
View File
@@ -7,11 +7,12 @@ import {
OneToMany,
} from "typeorm";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
@Entity("scenarios")
export class ScenarioEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
name: string;
@@ -22,6 +23,12 @@ export class ScenarioEntity {
})
steps: ScenarioStepEntity[];
@OneToMany(() => ScenarioCredentialEntity, (sc) => sc.scenario, {
cascade: true,
eager: false,
})
scenarioCredentials: ScenarioCredentialEntity[];
@CreateDateColumn()
createdAt: Date;
+8
View File
@@ -5,12 +5,16 @@ 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 { CredentialEntity } from "../credential/credential.entity";
import { ScenarioService } from "./scenario.service";
import { ScenarioController } from "./scenario.controller";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { AuthModule } from "../auth/auth.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SnippetModule } from "../snippet/snippet.module";
@Module({
imports: [
@@ -20,10 +24,14 @@ import { SessionModule } from "../session/session.module";
ScenarioRunEntity,
ScenarioRunStepEntity,
ScenarioRunLogEntity,
ScenarioCredentialEntity,
CredentialEntity,
]),
AuthModule,
CodeExecutorModule,
SessionModule,
EnvironmentModule,
SnippetModule,
],
controllers: [ScenarioController],
providers: [ScenarioService, ScenarioSchedulerService],
+145 -23
View File
@@ -1,4 +1,4 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { ConflictException, Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
@@ -6,10 +6,13 @@ 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 { CredentialEntity } from "../credential/credential.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,
@@ -33,6 +36,10 @@ export class ScenarioService {
private readonly runStepRepo: Repository<ScenarioRunStepEntity>,
@InjectRepository(ScenarioRunLogEntity)
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
@InjectRepository(ScenarioCredentialEntity)
private readonly scenarioCredRepo: Repository<ScenarioCredentialEntity>,
@InjectRepository(CredentialEntity)
private readonly credentialRepo: Repository<CredentialEntity>,
) {}
// ── Scenarios ─────────────────────────────────────────────────────────────
@@ -56,23 +63,23 @@ export class ScenarioService {
return { data, total, page, limit };
}
async findOne(id: number): Promise<ScenarioEntity> {
async findOne(id: string): Promise<ScenarioEntity> {
const scenario = await this.scenarioRepo.findOne({
where: { id },
relations: ["steps"],
relations: ["steps", "scenarioCredentials", "scenarioCredentials.credential"],
order: { steps: { order: "ASC" } },
});
if (!scenario) throw new NotFoundException(`Scenario ${id} not found`);
return scenario;
}
async update(id: number, dto: UpdateScenarioDto): Promise<ScenarioEntity> {
async update(id: string, dto: UpdateScenarioDto): Promise<ScenarioEntity> {
const scenario = await this.findOne(id);
Object.assign(scenario, dto);
return this.scenarioRepo.save(scenario);
}
async remove(id: number): Promise<void> {
async remove(id: string): Promise<void> {
await this.findOne(id);
await this.scenarioRepo.delete(id);
}
@@ -80,7 +87,7 @@ export class ScenarioService {
// ── Steps ─────────────────────────────────────────────────────────────────
async createStep(
scenarioId: number,
scenarioId: string,
dto: CreateScenarioStepDto,
): Promise<ScenarioStepEntity> {
await this.findOne(scenarioId);
@@ -95,8 +102,8 @@ export class ScenarioService {
}
async findStep(
scenarioId: number,
stepId: number,
scenarioId: string,
stepId: string,
): Promise<ScenarioStepEntity> {
const step = await this.stepRepo.findOneBy({ id: stepId, scenarioId });
if (!step)
@@ -107,8 +114,8 @@ export class ScenarioService {
}
async updateStep(
scenarioId: number,
stepId: number,
scenarioId: string,
stepId: string,
dto: UpdateScenarioStepDto,
): Promise<ScenarioStepEntity> {
const step = await this.findStep(scenarioId, stepId);
@@ -116,13 +123,91 @@ export class ScenarioService {
return this.stepRepo.save(step);
}
async removeStep(scenarioId: number, stepId: number): Promise<void> {
async removeStep(scenarioId: string, stepId: string): Promise<void> {
await this.findStep(scenarioId, stepId);
await this.stepRepo.delete(stepId);
}
// ── Scenario Credentials ──────────────────────────────────────────────────
async findScenarioCredentials(
scenarioId: string,
): Promise<ScenarioCredentialEntity[]> {
await this.findOne(scenarioId); // 404 guard
return this.scenarioCredRepo.find({
where: { scenarioId },
relations: ["credential"],
order: { alias: "ASC" },
});
}
async addScenarioCredential(
scenarioId: string,
dto: AddScenarioCredentialDto,
): Promise<ScenarioCredentialEntity> {
await this.findOne(scenarioId); // 404 guard
const credential = await this.credentialRepo.findOneBy({
id: dto.credentialId,
});
if (!credential)
throw new NotFoundException(`Credential ${dto.credentialId} not found`);
const existing = await this.scenarioCredRepo.findOneBy({
scenarioId,
alias: dto.alias,
});
if (existing)
throw new ConflictException(
`Alias "${dto.alias}" already used in this scenario`,
);
const sc = this.scenarioCredRepo.create({
scenarioId,
credentialId: dto.credentialId,
alias: dto.alias,
});
return this.scenarioCredRepo.save(sc);
}
async removeScenarioCredential(
scenarioId: string,
scCredId: string,
): Promise<void> {
await this.findOne(scenarioId); // 404 guard
const sc = await this.scenarioCredRepo.findOneBy({
id: scCredId,
scenarioId,
});
if (!sc)
throw new NotFoundException(
`Scenario credential ${scCredId} not found in scenario ${scenarioId}`,
);
await this.scenarioCredRepo.delete(scCredId);
}
/**
* Builds a map of alias → parsed credential data for use in code execution.
* Returns null values for credentials with no data.
*/
async buildCredentialMap(scenarioId: string): Promise<Record<string, unknown>> {
const scs = await this.findScenarioCredentials(scenarioId);
const map: Record<string, unknown> = {};
for (const sc of scs) {
let parsed: unknown = null;
if (sc.credential.data) {
try {
parsed = JSON.parse(sc.credential.data);
} catch {
parsed = sc.credential.data;
}
}
map[sc.alias] = parsed;
}
return map;
}
// ── Runs ──────────────────────────────────────────────────────────────────
async findRuns(
scenarioId: number,
scenarioId: string,
query: RunsQueryDto,
): Promise<PaginatedResult<ScenarioRunEntity>> {
await this.findOne(scenarioId); // 404 guard
@@ -140,9 +225,28 @@ export class ScenarioService {
return { data, total, page, limit };
}
async findAllRuns(
query: RunsQueryDto,
): Promise<PaginatedResult<ScenarioRunEntity & { scenario: ScenarioEntity }>> {
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: { id: "DESC", stepRuns: { order: "ASC" } },
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit } as PaginatedResult<
ScenarioRunEntity & { scenario: ScenarioEntity }
>;
}
async findRun(
scenarioId: number,
runId: number,
scenarioId: string,
runId: string,
): Promise<ScenarioRunEntity & { logs: ScenarioRunLogEntity[] }> {
await this.findOne(scenarioId); // 404 guard
const run = await this.runRepo.findOne({
@@ -162,8 +266,8 @@ export class ScenarioService {
}
async waitForRun(
scenarioId: number,
runId: number,
scenarioId: string,
runId: string,
timeoutMs = 300_000,
): Promise<ScenarioRunEntity & { logs: ScenarioRunLogEntity[] }> {
const deadline = Date.now() + timeoutMs;
@@ -181,7 +285,7 @@ export class ScenarioService {
return this.findRun(scenarioId, runId);
}
async createRun(scenarioId: number): Promise<ScenarioRunEntity> {
async createRun(scenarioId: string): Promise<ScenarioRunEntity> {
const scenario = await this.findOne(scenarioId);
const run = await this.runRepo.save(
@@ -209,14 +313,16 @@ export class ScenarioService {
// ── Export / Import ───────────────────────────────────────────────────────
async exportScenario(id: number): Promise<ScenarioExportDto> {
async exportScenario(id: string): Promise<ScenarioExportDto> {
const scenario = await this.findOne(id);
return {
kind: "scenario",
id: scenario.id,
name: scenario.name,
steps: scenario.steps.map((s) => ({
order: s.order,
type: s.type,
sessionName: s.sessionName,
title: s.title,
execCode: s.execCode,
validateCode: s.validateCode,
})),
@@ -224,16 +330,32 @@ export class ScenarioService {
}
async importScenario(dto: ScenarioExportDto): Promise<ScenarioEntity> {
const scenario = await this.scenarioRepo.save(
this.scenarioRepo.create({ name: dto.name }),
);
// Upsert: if id provided and entity exists, replace steps; else create new
let scenario: ScenarioEntity;
if (dto.id) {
const existing = await this.scenarioRepo.findOneBy({ id: dto.id });
if (existing) {
existing.name = dto.name;
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 }),
);
}
} else {
scenario = await this.scenarioRepo.save(
this.scenarioRepo.create({ name: dto.name }),
);
}
if (dto.steps.length > 0) {
const steps = dto.steps.map((s) =>
this.stepRepo.create({
scenarioId: scenario.id,
order: s.order,
type: s.type,
sessionName: s.sessionName,
title: s.title ?? null,
execCode: s.execCode ?? null,
validateCode: s.validateCode ?? null,
}),
@@ -110,7 +110,7 @@ export class SessionContextService implements OnModuleDestroy {
* Close the context (if open) and delete the session record from DB.
* Throws 404 if the session ID does not exist.
*/
async delete(id: number): Promise<void> {
async delete(id: string): Promise<void> {
const session = await this.sessionService.findById(id);
if (!session) {
throw new NotFoundException(`Session ${id} not found`);
+3 -3
View File
@@ -5,7 +5,7 @@ import {
HttpCode,
NotFoundException,
Param,
ParseIntPipe,
ParseUUIDPipe,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
@@ -38,7 +38,7 @@ export class SessionController {
@ApiOperation({ summary: "Get a session by ID" })
@ApiResponse({ status: 200, description: "Session found" })
@ApiResponse({ status: 404, description: "Session not found" })
async findOne(@Param("id", ParseIntPipe) id: number) {
async findOne(@Param("id", ParseUUIDPipe) id: string) {
const session = await this.sessionService.findById(id);
if (!session) throw new NotFoundException(`Session ${id} not found`);
const {
@@ -58,7 +58,7 @@ export class SessionController {
@ApiOperation({ summary: "Delete a session by ID (closes it first if open)" })
@ApiResponse({ status: 204, description: "Session deleted" })
@ApiResponse({ status: 404, description: "Session not found" })
async remove(@Param("id", ParseIntPipe) id: number): Promise<void> {
async remove(@Param("id", ParseUUIDPipe) id: string): Promise<void> {
await this.sessionContextService.delete(id);
}
}
+2 -2
View File
@@ -10,8 +10,8 @@ export type SessionStatus = "open" | "closed";
@Entity("sessions")
export class SessionEntity {
@PrimaryGeneratedColumn()
id: number;
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({ unique: true })
sessionName: string;
+2 -2
View File
@@ -72,7 +72,7 @@ export class SessionService implements OnApplicationBootstrap {
return this.repo.findOneBy({ sessionName });
}
findById(id: number): Promise<SessionEntity | null> {
findById(id: string): Promise<SessionEntity | null> {
return this.repo.findOneBy({ id });
}
@@ -137,7 +137,7 @@ export class SessionService implements OnApplicationBootstrap {
return { data, total, page, limit };
}
async remove(id: number): Promise<void> {
async remove(id: string): Promise<void> {
await this.repo.delete(id);
}
}
@@ -0,0 +1,19 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class CreateSnippetDto {
@ApiProperty({ example: "clickLoginButton" })
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional({ example: "Clicks the login button and waits for navigation" })
@IsOptional()
@IsString()
description?: string;
@ApiProperty({ example: "await page.click('#login-btn');\nawait page.waitForNavigation();" })
@IsString()
@IsNotEmpty()
code: string;
}
@@ -0,0 +1,28 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
export class SnippetExportDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(["snippet"])
kind?: "snippet";
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
id?: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string | null;
@ApiProperty()
@IsString()
code: string;
}
@@ -0,0 +1,21 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class UpdateSnippetDto {
@ApiPropertyOptional({ example: "clickLoginButton" })
@IsOptional()
@IsString()
@IsNotEmpty()
name?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
code?: string;
}
+84
View File
@@ -0,0 +1,84 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
ParseUUIDPipe,
Patch,
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { SnippetService, SnippetOrderBy } from "./snippet.service";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
@ApiTags("snippets")
@Controller("snippets")
export class SnippetController {
constructor(private readonly snippetService: SnippetService) {}
@Post()
@ApiOperation({ summary: "Create a new snippet" })
@ApiResponse({ status: 201, description: "Snippet created" })
@ApiResponse({ status: 409, description: "Name already taken" })
create(@Body() dto: CreateSnippetDto) {
return this.snippetService.create(dto);
}
@Post("import")
@ApiOperation({ summary: "Import a snippet (upsert by id)" })
@ApiResponse({ status: 201, description: "Snippet imported" })
async importSnippet(@Body() dto: SnippetExportDto) {
return this.snippetService.importSnippet(dto);
}
@Get()
@ApiOperation({ summary: "List all snippets (paginated)" })
@ApiResponse({ status: 200, description: "Paginated snippets" })
findAll(@Query() query: PaginationQueryDto<SnippetOrderBy>) {
return this.snippetService.findAll(query);
}
@Get(":id/export")
@ApiOperation({ summary: "Export a snippet as a plain object" })
@ApiResponse({ status: 200, description: "Snippet export payload" })
@ApiResponse({ status: 404, description: "Snippet not found" })
async exportSnippet(@Param("id", ParseUUIDPipe) id: string) {
const snippet = await this.snippetService.findOne(id);
return this.snippetService.exportSnippet(snippet);
}
@Get(":id")
@ApiOperation({ summary: "Get snippet by ID" })
@ApiResponse({ status: 200, description: "Snippet record" })
@ApiResponse({ status: 404, description: "Snippet not found" })
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.snippetService.findOne(id);
}
@Patch(":id")
@ApiOperation({ summary: "Update a snippet" })
@ApiResponse({ status: 200, description: "Snippet updated" })
@ApiResponse({ status: 404, description: "Snippet not found" })
@ApiResponse({ status: 409, description: "Name already taken" })
update(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateSnippetDto,
) {
return this.snippetService.update(id, dto);
}
@Delete(":id")
@HttpCode(204)
@ApiOperation({ summary: "Delete a snippet" })
@ApiResponse({ status: 204, description: "Snippet deleted" })
@ApiResponse({ status: 404, description: "Snippet not found" })
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.snippetService.remove(id);
}
}
+34
View File
@@ -0,0 +1,34 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";
@Entity("snippets")
export class SnippetEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
/** Unique identifier used to call the snippet: helpers.runSnippet('mySnippet', ...) */
@Column({ unique: true })
name: string;
@Column("text", { nullable: true })
description: string | null;
/**
* The snippet body — written as a regular async function body.
* It receives the same `page`, `context`, and `helpers` as exec code, plus
* any positional `...args` passed by the caller.
*/
@Column("text")
code: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { SnippetEntity } from "./snippet.entity";
import { SnippetService } from "./snippet.service";
import { SnippetController } from "./snippet.controller";
@Module({
imports: [TypeOrmModule.forFeature([SnippetEntity])],
controllers: [SnippetController],
providers: [SnippetService],
exports: [SnippetService],
})
export class SnippetModule {}
+116
View File
@@ -0,0 +1,116 @@
import {
ConflictException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { SnippetEntity } from "./snippet.entity";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
export type SnippetOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@Injectable()
export class SnippetService {
constructor(
@InjectRepository(SnippetEntity)
private readonly repo: Repository<SnippetEntity>,
) {}
async create(dto: CreateSnippetDto): Promise<SnippetEntity> {
const existing = await this.repo.findOneBy({ name: dto.name });
if (existing) {
throw new ConflictException(`Snippet "${dto.name}" already exists`);
}
return this.repo.save(
this.repo.create({ ...dto, description: dto.description ?? null }),
);
}
async findAll(
query: PaginationQueryDto<SnippetOrderBy> = {},
): Promise<PaginatedResult<SnippetEntity>> {
const page = query.page ?? 1;
const limit = query.limit ?? 50;
const orderBy = query.orderBy ?? "id";
const orderDir = query.orderDir ?? "ASC";
const [data, total] = await this.repo.findAndCount({
order: { [orderBy]: orderDir },
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit };
}
async findOne(id: string): Promise<SnippetEntity> {
const snippet = await this.repo.findOneBy({ id });
if (!snippet) throw new NotFoundException(`Snippet ${id} not found`);
return snippet;
}
async update(id: string, dto: UpdateSnippetDto): Promise<SnippetEntity> {
const snippet = await this.findOne(id);
if (dto.name && dto.name !== snippet.name) {
const conflict = await this.repo.findOneBy({ name: dto.name });
if (conflict) throw new ConflictException(`Snippet "${dto.name}" already exists`);
}
Object.assign(snippet, dto);
return this.repo.save(snippet);
}
async remove(id: string): Promise<void> {
await this.findOne(id);
await this.repo.delete(id);
}
/** Returns a name→code map for all snippets (used by the executor). */
async buildSnippetMap(): Promise<Record<string, string>> {
const { data } = await this.findAll({ limit: 1000 });
return Object.fromEntries(data.map((s) => [s.name, s.code]));
}
exportSnippet(snippet: SnippetEntity): SnippetExportDto {
return {
kind: "snippet",
id: snippet.id,
name: snippet.name,
description: snippet.description,
code: snippet.code,
};
}
async importSnippet(dto: SnippetExportDto): Promise<SnippetEntity> {
if (dto.id) {
const existing = await this.repo.findOneBy({ id: dto.id });
if (existing) {
Object.assign(existing, {
name: dto.name,
description: dto.description ?? null,
code: dto.code,
});
return this.repo.save(existing);
}
return this.repo.save(
this.repo.create({
id: dto.id,
name: dto.name,
description: dto.description ?? null,
code: dto.code,
}),
);
}
return this.repo.save(
this.repo.create({
name: dto.name,
description: dto.description ?? null,
code: dto.code,
}),
);
}
}