Compare commits

...
22 Commits
Author SHA1 Message Date
ars9 5ba327b745 1.5.0 2026-04-11 00:53:44 +03:00
ars9 238c52610a refactor(scenario): remove validateCode — assertions live in execCode
- drop validateCode column, DTOs, service mappings, and scheduler branch
- remove parseValidateResult helper and ValidateResult interface
- inject playwright expect into code executor for direct use in execCode
- strip validateCode from MCP tool schemas, client types, and UI forms
2026-04-11 00:52:50 +03:00
ars9 29e91b0078 test(server): align specs with run environment and step schema
- update scenario tests to create runs with required environmentId
- adjust browser controller expectations to session auto-create behavior
- sync playwright/context mocks with current browser service usage
2026-04-11 00:22:58 +03:00
ars9 56d23f913d feat(scenarios): require environment for scenario runs
- require environmentId when creating runs in API and MCP tools

- pass selected environment data into step execution helpers

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

- gate all delete and remove flows behind explicit confirmation dialogs

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

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

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

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

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

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

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

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

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

- prevent environment pages from crashing when legacy records miss data

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

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

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

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

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

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

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

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

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

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

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

- update mcp and scenario tests to match uuid routes and step schema
2026-04-10 16:42:43 +03:00
ars9 673aa0f458 refactor(scenario): remove step type and simplify scheduler to exec-only
- remove StepType, type column, and type field from step entity and DTOs
- remove executeLoginStep, executeSignStep, executeExecStep from scheduler
- inline exec logic directly in executeStepRun; all steps run execCode
- remove AuthService, EnvironmentService, runEnvironments from scheduler
- remove type selector from CreateStepPage and EditStepPage
- remove type badge column from ScenarioDetailPage
- fix useEffect dependency arrays in RunDetailPage (FINAL, id, runId, polling)
- fix duplicate /snippets proxy key in vite.config.ts
- remove unused escapeHtml export from hljs.ts
2026-04-10 16:14:17 +03:00
ars9 1c13e068ad feat(ui): add CodeBlock and CodeEditor components with Monaco and hljs
- add CodeBlock for read-only syntax-highlighted display (hljs, js/json)
- add CodeEditor wrapping Monaco editor with theme sync, focus state, and error state
- replace code textareas in snippet, credential, and step pages with CodeEditor
- replace code <pre> blocks in snippet and credential detail pages with CodeBlock
- make form cards full-width on pages with code editors
- add resize:vertical support to CodeEditor wrapper with automaticLayout
2026-04-10 15:53:26 +03:00
ars9 2046e64428 feat(runs): add log search with backend LIKE filter and pagination
- add Search pill component with lucide icon and focus highlight
- wire debounced search input to GET /run/:id?q= backend filter
- backend filters run logs with LIKE %q% via TypeORM
- add sectionHeadingRow layout for heading + search alignment
- add i18n keys: runs.step_title, logs_search_placeholder
2026-04-10 15:09:05 +03:00
ars9 fd655c3253 feat(runs): add step title column, step descriptions, and snippet logging 2026-04-10 14:56:15 +03:00
ars9 607abcafc5 fix(scenarios): order runs by createdAt desc, scenarios list by updatedAt desc 2026-04-10 13:57:34 +03:00
125 changed files with 5106 additions and 13320 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
.git
.gitignore
node_modules
**/node_modules
**/dist
**/.DS_Store
**/*.log
data
keys
+1 -2
View File
@@ -1,5 +1,4 @@
# runtime / secrets
/keys
# runtime
/data
.env
*.log
+3
View File
@@ -0,0 +1,3 @@
# Frontend API base URL.
# Example for local Docker server: backend container is exposed on localhost:13000.
VITE_API_URL=http://localhost:13000/api/v1
+4
View File
@@ -14,13 +14,17 @@
"format": "prettier --write \"src/**/*.{ts,tsx}\" \".storybook/**/*.{ts,tsx}\""
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
"moment": "^2.30.1",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-i18next": "^17.0.2",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.14.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.8.3"
},
"devDependencies": {
+22
View File
@@ -30,6 +30,28 @@
padding: var(--space-2) 0;
}
.sideContent {
display: flex;
flex-direction: column;
min-height: 100%;
}
.sideFooter {
margin-top: auto;
padding: var(--space-3) var(--space-2) var(--space-2);
border-top: var(--border-width) solid var(--color-border);
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
}
.version {
color: var(--color-text-muted);
font-size: var(--font-size-xs);
white-space: nowrap;
}
.navItem {
display: flex;
align-items: center;
+128 -70
View File
@@ -1,40 +1,91 @@
import { lazy, Suspense } from 'react';
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare, Braces } from 'lucide-react';
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg';
import { EnvironmentsPage } from './pages/environment/EnvironmentsPage';
import { EnvironmentDetailPage } from './pages/environment/EnvironmentDetailPage';
import { CreateEnvironmentPage } from './pages/environment/CreateEnvironmentPage';
import { EditEnvironmentPage } from './pages/environment/EditEnvironmentPage';
import { KeysPage } from './pages/KeysPage';
import { SessionsPage } from './pages/session/SessionsPage';
import { SessionDetailPage } from './pages/session/SessionDetailPage';
import { ScenariosPage } from './pages/scenario/ScenariosPage';
import { ScenarioDetailPage } from './pages/scenario/ScenarioDetailPage';
import { CreateScenarioPage } from './pages/scenario/CreateScenarioPage';
import { EditScenarioPage } from './pages/scenario/EditScenarioPage';
import { CreateStepPage } from './pages/scenario/CreateStepPage';
import { EditStepPage } from './pages/scenario/EditStepPage';
import { RunsPage } from './pages/run/RunsPage';
import { RunDetailPage } from './pages/run/RunDetailPage';
import { AllRunsPage } from './pages/run/AllRunsPage';
import { CredentialsPage } from './pages/credential/CredentialsPage';
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
import { SnippetsPage } from './pages/snippet/SnippetsPage';
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
);
const EnvironmentDetailPage = lazy(() =>
import('./pages/environment/EnvironmentDetailPage').then((m) => ({ default: m.EnvironmentDetailPage })),
);
const CreateEnvironmentPage = lazy(() =>
import('./pages/environment/CreateEnvironmentPage').then((m) => ({ default: m.CreateEnvironmentPage })),
);
const EditEnvironmentPage = lazy(() =>
import('./pages/environment/EditEnvironmentPage').then((m) => ({ default: m.EditEnvironmentPage })),
);
const SessionsPage = lazy(() =>
import('./pages/session/SessionsPage').then((m) => ({ default: m.SessionsPage })),
);
const SessionDetailPage = lazy(() =>
import('./pages/session/SessionDetailPage').then((m) => ({ default: m.SessionDetailPage })),
);
const ScenariosPage = lazy(() =>
import('./pages/scenario/ScenariosPage').then((m) => ({ default: m.ScenariosPage })),
);
const ScenarioDetailPage = lazy(() =>
import('./pages/scenario/ScenarioDetailPage').then((m) => ({ default: m.ScenarioDetailPage })),
);
const CreateScenarioPage = lazy(() =>
import('./pages/scenario/CreateScenarioPage').then((m) => ({ default: m.CreateScenarioPage })),
);
const EditScenarioPage = lazy(() =>
import('./pages/scenario/EditScenarioPage').then((m) => ({ default: m.EditScenarioPage })),
);
const CreateStepPage = lazy(() =>
import('./pages/scenario/CreateStepPage').then((m) => ({ default: m.CreateStepPage })),
);
const EditStepPage = lazy(() =>
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
);
const RunsPage = lazy(() =>
import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })),
);
const RunDetailPage = lazy(() =>
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
);
const AllRunsPage = lazy(() =>
import('./pages/run/AllRunsPage').then((m) => ({ default: m.AllRunsPage })),
);
const CredentialsPage = lazy(() =>
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
);
const CreateCredentialPage = lazy(() =>
import('./pages/credential/CreateCredentialPage').then((m) => ({ default: m.CreateCredentialPage })),
);
const EditCredentialPage = lazy(() =>
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
);
const CredentialDetailPage = lazy(() =>
import('./pages/credential/CredentialDetailPage').then((m) => ({ default: m.CredentialDetailPage })),
);
const SnippetsPage = lazy(() =>
import('./pages/snippet/SnippetsPage').then((m) => ({ default: m.SnippetsPage })),
);
const CreateSnippetPage = lazy(() =>
import('./pages/snippet/CreateSnippetPage').then((m) => ({ default: m.CreateSnippetPage })),
);
const EditSnippetPage = lazy(() =>
import('./pages/snippet/EditSnippetPage').then((m) => ({ default: m.EditSnippetPage })),
);
const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
);
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ 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 },
@@ -49,56 +100,63 @@ export default function App() {
header={
<div className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
<ThemeSwitcher />
</div>
}
width={220}
>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
</nav>
<div className={styles.sideContent}>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
</nav>
<div className={styles.sideFooter}>
<ThemeSwitcher />
<div className={styles.version}>v{__APP_VERSION__}</div>
</div>
</div>
</SidePanel>
<main className={styles.main}>
<Routes>
<Route index element={<Navigate to="/scenarios" replace />} />
<Route path="/environments" element={<EnvironmentsPage />} />
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
<Route path="/keys" element={<KeysPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/sessions/:id" element={<SessionDetailPage />} />
<Route path="/scenarios" element={<ScenariosPage />} />
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
<Route path="/credentials" element={<CredentialsPage />} />
<Route path="/credentials/new" element={<CreateCredentialPage />} />
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
<Route path="/runs" element={<AllRunsPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
<Suspense fallback={<p>Loading…</p>}>
<Routes>
<Route index element={<Navigate to="/scenarios" replace />} />
<Route path="/environments" element={<EnvironmentsPage />} />
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/sessions/:id" element={<SessionDetailPage />} />
<Route path="/scenarios" element={<ScenariosPage />} />
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
<Route path="/credentials" element={<CredentialsPage />} />
<Route path="/credentials/new" element={<CreateCredentialPage />} />
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
<Route path="/runs" element={<AllRunsPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
</Suspense>
</main>
</div>
);
+68 -36
View File
@@ -2,7 +2,6 @@ import type {
PaginatedResponse,
Credential,
Environment,
KeysResponse,
ScenarioCredential,
Session,
Scenario,
@@ -12,25 +11,39 @@ import type {
ScenarioStep,
Snippet,
} from './types';
import { emitApiErrorToast } from '../lib/toast-events';
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
// In production (or when VITE_API_URL is set) we hit the configured origin directly.
const BASE_URL: string = (import.meta.env.VITE_API_URL as string | undefined) ?? '';
// API calls are versioned under /api/v1 by default.
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(/\/$/, '');
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE_URL}${path}`, {
headers: { 'Content-Type': 'application/json', ...init?.headers },
...init,
});
let res: Response;
try {
res = await fetch(`${BASE_URL}${path}`, {
headers: { 'Content-Type': 'application/json', ...init?.headers },
...init,
});
} catch (err) {
const message = (err as Error).message || 'Network request failed';
emitApiErrorToast(message);
throw new Error(message);
}
if (!res.ok) {
const text = await res.text().catch(() => res.statusText);
throw new Error(`${res.status} ${text}`);
const message = `${res.status} ${text}`;
emitApiErrorToast(message);
throw new Error(message);
}
const contentLength = res.headers.get('content-length');
if (res.status === 204 || contentLength === '0') return undefined as T;
const contentType = res.headers.get('content-type')?.toLowerCase() ?? '';
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
if (contentType.includes('application/json')) {
return JSON.parse(text) as T;
}
return text as T;
}
// ── Credentials ───────────────────────────────────────────────────────────────
@@ -77,13 +90,16 @@ export const snippets = {
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
create(payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string }): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(id: string, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
update(
id: string,
patch: Partial<Pick<Snippet, 'alias' | 'title' | 'description' | 'code'>>,
): Promise<Snippet> {
return request(`/snippets/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -112,13 +128,13 @@ export const environments = {
get(id: string): Promise<Environment> {
return request(`/environments/${id}`);
},
create(name: string, urls: Environment['urls']): Promise<Environment> {
create(name: string, data: Environment['data']): Promise<Environment> {
return request('/environments', {
method: 'POST',
body: JSON.stringify({ name, urls }),
body: JSON.stringify({ name, data }),
});
},
update(id: string, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
return request(`/environments/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
@@ -127,13 +143,14 @@ export const environments = {
remove(id: string): Promise<void> {
return request(`/environments/${id}`, { method: 'DELETE' });
},
};
// ── Keys ──────────────────────────────────────────────────────────────────────
export const keys = {
list(): Promise<KeysResponse> {
return request('/keys');
exportEnvironment(id: string): Promise<unknown> {
return request(`/environments/${id}/export`);
},
importEnvironment(payload: unknown): Promise<Environment> {
return request('/environments/import', {
method: 'POST',
body: JSON.stringify(payload),
});
},
};
@@ -155,7 +172,7 @@ export const sessions = {
export const scenarios = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
return request(`/scenarios?page=${page}&limit=${limit}`);
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
},
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
return request(`/scenarios/${id}`);
@@ -175,8 +192,11 @@ export const scenarios = {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: string): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, { method: 'POST' });
run(id: string, environmentId: string): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId }),
});
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}`);
@@ -184,10 +204,14 @@ export const scenarios = {
waitForRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
return request(`/scenarios/${scenarioId}/run/${runId}/wait`, { method: 'POST' });
},
listRuns(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
listRuns(
scenarioId: string,
page = 1,
limit = 20,
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
},
exportScenario(id: string): Promise<unknown> {
exportScenario(id: string): Promise<string> {
return request(`/scenarios/${id}/export`);
},
importScenario(payload: unknown): Promise<Scenario> {
@@ -201,16 +225,29 @@ export const scenarios = {
// ── Runs ─────────────────────────────────────────────────────────────────────
export const runs = {
listAll(page = 1, limit = 20, status?: string): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }>> {
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[] }>> {
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}`);
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
},
};
@@ -236,18 +273,13 @@ export const scenarioCredentials = {
// ── 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 = {
+5 -17
View File
@@ -9,17 +9,14 @@ export interface PaginatedResponse<T> {
// ── Environments ──────────────────────────────────────────────────────────────
export interface EnvironmentUrls {
id_url?: string;
cabinet_url?: string;
admin_url?: string;
export interface EnvironmentData {
[key: string]: string | undefined;
}
export interface Environment {
id: string;
name: string;
urls: EnvironmentUrls;
data: EnvironmentData;
createdAt: string;
updatedAt: string;
}
@@ -39,19 +36,14 @@ export interface Credential {
export interface Snippet {
id: string;
name: string;
alias: string;
title: string;
description: string | null;
code: string;
createdAt: string;
updatedAt: string;
}
// ── Keys ──────────────────────────────────────────────────────────────────────
export interface KeysResponse {
keys: string[];
}
// ── Sessions ──────────────────────────────────────────────────────────────────
export type SessionStatus = 'open' | 'closed';
@@ -68,17 +60,12 @@ export interface Session {
// ── Scenarios ─────────────────────────────────────────────────────────────────
export type StepType = 'login' | 'exec' | 'sign';
export interface ScenarioStep {
id: string;
scenarioId: string;
order: number;
type: StepType;
title: string | null;
sessionName: string | null;
execCode: string | null;
validateCode: string | null;
createdAt: string;
updatedAt: string;
}
@@ -110,6 +97,7 @@ export type LogLevel = 'log' | 'warn' | 'error';
export interface ScenarioRun {
id: string;
scenarioId: string;
environmentId: string;
scenario?: Pick<Scenario, 'id' | 'name'>;
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
+2
View File
@@ -6,3 +6,5 @@ declare module '*.css' {
interface ImportMetaEnv {
readonly VITE_API_URL?: string;
}
declare const __APP_VERSION__: string;
+28 -19
View File
@@ -21,32 +21,33 @@
"title": "Environments",
"col_id": "ID",
"col_name": "Name",
"col_urls": "URLs",
"col_data": "Data",
"col_updated": "Updated",
"empty": "No environments yet.",
"loading": "Loading…",
"no_urls": "No URLs configured.",
"no_data": "No data configured.",
"menu_label": "Environment options",
"action_view": "View details",
"action_delete": "Delete",
"action_add": "Add environment",
"action_edit": "Edit",
"action_export": "Export",
"action_import": "Import",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Environment",
"edit_title": "Edit Environment",
"form_name": "Name",
"form_name_placeholder": "e.g. staging, production",
"form_name_required": "Name is required",
"form_id_url": "ID URL",
"form_cabinet_url": "Cabinet URL",
"form_admin_url": "Admin URL",
"form_data": "Data (JSON)",
"form_data_invalid_json": "Must be a valid JSON object",
"back": "Environments",
"field_id": "ID",
"field_created": "Created",
"field_updated": "Updated",
"section_urls": "URLs"
"section_data": "Data"
},
"credentials": {
"title": "Credentials",
@@ -57,7 +58,7 @@
"action_delete": "Delete",
"action_add": "Add credential",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Credential",
"edit_title": "Edit Credential",
@@ -123,7 +124,7 @@
"action_import": "Import",
"import_error": "Failed to import scenario",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Scenario",
"edit_title": "Edit Scenario",
@@ -144,7 +145,11 @@
"cred_form_cred_required": "Select a credential",
"cred_form_alias": "Alias",
"cred_form_alias_placeholder": "e.g. api_key",
"cred_form_alias_required": "Alias is required"
"cred_form_alias_required": "Alias is required",
"run_modal_title": "Select environment",
"run_modal_env_label": "Environment",
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
"run_modal_env_required": "Please select an environment"
},
"theme": {
"switch_to_light": "Switch to light theme",
@@ -167,7 +172,7 @@
"action_edit": "Edit",
"action_delete": "Delete",
"action_save": "Add step",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"form_order": "Order",
"form_order_invalid": "Order must be a non-negative integer",
@@ -178,9 +183,7 @@
"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: \"…\" };"
"form_exec_code_placeholder": "return await page.title();"
},
"runs": {
"title": "Runs",
@@ -198,7 +201,9 @@
"field_created": "Started",
"field_updated": "Updated",
"steps_heading": "Step runs",
"step_title": "Title",
"logs_heading": "Logs",
"logs_search_placeholder": "Filter logs…",
"step_order": "#",
"step_type": "Type",
"step_session": "Session",
@@ -217,20 +222,24 @@
"action_delete": "Delete",
"action_add": "Add snippet",
"action_save": "Create",
"action_update": "Save changes",
"action_update": "Save",
"action_cancel": "Cancel",
"create_title": "New Snippet",
"edit_title": "Edit Snippet",
"form_name": "Name",
"form_name_placeholder": "e.g. clickLoginButton",
"form_name_required": "Name is required",
"form_alias": "Alias",
"form_alias_placeholder": "e.g. clickLoginButton",
"form_alias_required": "Alias is required",
"form_title": "Title",
"form_title_placeholder": "e.g. Click Login Button",
"form_title_required": "Title is required",
"form_description": "Description",
"form_description_placeholder": "What does this snippet do?",
"form_code": "Code",
"form_code_placeholder": "await page.click('#login-btn');",
"form_code_required": "Code is required",
"field_id": "ID",
"field_name": "Name",
"field_alias": "Alias",
"field_title": "Title",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
+8
View File
@@ -0,0 +1,8 @@
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('json', json);
export default hljs;
+29
View File
@@ -0,0 +1,29 @@
export const API_ERROR_TOAST_EVENT = 'liqa:api-error-toast';
export interface ApiErrorToastDetail {
message: string;
}
export function emitApiErrorToast(message: string): void {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
detail: { message },
}),
);
}
export function subscribeApiErrorToasts(
handler: (message: string) => void,
): () => void {
if (typeof window === 'undefined') return () => {};
const listener = (event: Event) => {
const custom = event as CustomEvent<ApiErrorToastDetail>;
const message = custom.detail?.message;
if (message) handler(message);
};
window.addEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
return () => {
window.removeEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
};
}
+7 -4
View File
@@ -1,14 +1,17 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom';
import './i18n';
import './ui/tokens.css';
import App from './App';
import { ToastProvider } from './ui';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<HashRouter>
<App />
</HashRouter>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</StrictMode>,
);
-44
View File
@@ -1,44 +0,0 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { keys } from '../api';
import { Breadcrumbs, Table, type TableColumn } from '../ui';
import styles from './Page.module.css';
interface KeyRow {
name: string;
}
export function KeysPage() {
const { t } = useTranslation();
const [items, setItems] = useState<KeyRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const columns: TableColumn<KeyRow>[] = [
{ key: 'name', header: t('keys.col_name'), render: (k) => k.name },
];
useEffect(() => {
keys
.list()
.then((res) => setItems(res.keys.map((name) => ({ name }))))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
return (
<div>
<Breadcrumbs items={[{ label: t('keys.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
rowKey={(k) => k.name}
loading={loading}
emptyMessage={t('keys.empty')}
pageSize={10}
pageSizeOptions={[10, 25, 50]}
/>
</div>
);
}
+43 -2
View File
@@ -6,7 +6,7 @@
}
.sectionHeading {
margin: 0;
margin: 0 0 var(--space-3);
line-height: 1;
font-size: var(--font-size-md);
font-weight: 600;
@@ -17,6 +17,13 @@
margin-top: var(--space-6);
}
.sectionHeadingRow {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-3);
}
.breadcrumbs {
margin-bottom: var(--space-4);
}
@@ -92,7 +99,8 @@
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
flex: 1;
min-width: 0;
}
.envCardId {
@@ -138,6 +146,35 @@
color: var(--color-link-hover);
}
.dragHandle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: var(--radius-sm);
cursor: grab;
color: var(--color-text-muted);
}
.dragHandle:hover {
background: color-mix(in srgb, var(--color-secondary) 18%, transparent);
color: var(--color-text);
}
.dragHandle:active {
cursor: grabbing;
}
.dragHandleDisabled {
opacity: 0.45;
cursor: not-allowed;
}
.dragOverRow {
background: color-mix(in srgb, var(--color-primary) 16%, transparent) !important;
}
.envCardHeader button:hover {
background: color-mix(in srgb, currentColor 15%, transparent) !important;
}
@@ -189,6 +226,10 @@
max-width: 540px;
}
.formCardFull {
max-width: none;
}
.formFields {
display: flex;
flex-direction: column;
@@ -1,13 +1,15 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateCredentialPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [data, setData] = useState('');
@@ -36,9 +38,12 @@ export function CreateCredentialPage() {
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success('Credential created');
navigate(`/credentials/${credential.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -49,16 +54,14 @@ export function CreateCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{ label: t('credentials.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
@@ -72,24 +75,32 @@ export function CreateCredentialPage() {
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('credentials.form_data')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
language="json"
value={data}
onChange={(v) => {
setData(v);
setDataError('');
}}
rows={6}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/credentials')}>
<X size={14} />
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('credentials.action_save')}
</Button>
</div>
@@ -1,11 +1,20 @@
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 { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
@@ -15,6 +24,8 @@ export function CredentialDetailPage() {
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
@@ -27,8 +38,14 @@ export function CredentialDetailPage() {
const handleDelete = async () => {
if (!credential) return;
await credentials.remove(credential.id);
navigate('/credentials');
setDeleting(true);
try {
await credentials.remove(credential.id);
navigate('/credentials');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
@@ -48,14 +65,14 @@ export function CredentialDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{ label: credential?.name ?? `#${id}` },
]}
/>
{credential && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
<Upload size={14} />
{t('credentials.action_export')}
</Button>
<Button
@@ -66,7 +83,7 @@ export function CredentialDetailPage() {
<Pencil size={14} />
{t('credentials.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('credentials.action_delete')}
</Button>
@@ -74,31 +91,18 @@ export function CredentialDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_credential', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{credential && (
<>
<div className={styles.detailMeta}>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('credentials.field_id'), detail: <UuidBadge id={credential.id} /> },
{
term: t('credentials.field_last_used'),
detail: credential.lastUsedAt ? (
<Timestamp value={credential.lastUsedAt} />
) : (
'—'
),
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
},
{
term: t('credentials.field_created'),
@@ -110,26 +114,45 @@ export function CredentialDetailPage() {
},
]}
/>
</div>
</Card>
{credential.data && (
<>
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
<Card>
<pre className={styles.codeBlock}>
{(() => {
<CodeBlock
language="json"
code={(() => {
try {
return JSON.stringify(JSON.parse(credential.data), null, 2);
} catch {
return credential.data;
}
})()}
</pre>
/>
</Card>
</>
</div>
)}
</>
)}
<Modal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
</div>
);
}
@@ -1,11 +1,20 @@
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 { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
function CredentialCard({
@@ -95,6 +104,8 @@ export function CredentialsPage() {
const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
@@ -109,9 +120,20 @@ export function CredentialsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await credentials.remove(id);
setItems((prev) => prev.filter((c) => c.id !== id));
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await credentials.remove(deleteId);
setItems((prev) => prev.filter((c) => c.id !== deleteId));
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -131,7 +153,7 @@ export function CredentialsPage() {
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('credentials.title') }]} className={styles.breadcrumbs} />
<Breadcrumbs items={[{ label: t('credentials.title'), icon: <KeyRound size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -141,22 +163,39 @@ export function CredentialsPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('credentials.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading ? (
<p className={styles.muted}>{t('credentials.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((credential) => (
<CredentialCard key={credential.id} credential={credential} onDelete={handleDelete} />
<CredentialCard key={credential.id} credential={credential} onDelete={requestDelete} />
))}
<AddCredentialCard />
</div>
)}
<Modal
open={deleteId != null}
title={t('credentials.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
</div>
);
}
@@ -1,15 +1,17 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditCredentialPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [credential, setCredential] = useState<Credential | null>(null);
const [name, setName] = useState('');
@@ -56,9 +58,12 @@ export function EditCredentialPage() {
name: name.trim(),
data: data.trim() || null,
});
toast.success('Credential updated');
navigate(`/credentials/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -69,7 +74,7 @@ export function EditCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
@@ -79,12 +84,11 @@ export function EditCredentialPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
{!loading && credential && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('credentials.form_name')}
@@ -98,17 +102,23 @@ export function EditCredentialPage() {
required
autoFocus
/>
<Textarea
label={t('credentials.form_data')}
placeholder={t('credentials.form_data_placeholder')}
value={data}
onChange={(e) => {
setData(e.target.value);
setDataError('');
}}
error={dataError || undefined}
rows={6}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('credentials.form_data')}
<span className={styles.requiredMark}> *</span>
</label>
<CodeEditor
language="json"
value={data}
onChange={(v) => {
setData(v);
setDataError('');
}}
rows={6}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
@@ -117,9 +127,11 @@ export function EditCredentialPage() {
variant="secondary"
onClick={() => navigate(`/credentials/${id}`)}
>
<X size={14} />
{t('credentials.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('credentials.action_update')}
</Button>
</div>
@@ -1,19 +1,20 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateEnvironmentPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -23,17 +24,33 @@ export function CreateEnvironmentPage() {
setNameError(t('environments.form_name_required'));
return;
}
let parsedData: Record<string, string | undefined>;
try {
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
throw new Error('invalid');
}
parsedData = Object.fromEntries(
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
k,
v == null ? undefined : String(v),
]),
);
setDataError('');
} catch {
setDataError(t('environments.form_data_invalid_json'));
return;
}
setSaving(true);
setError(null);
try {
const env = await environments.create(name.trim(), {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
});
const env = await environments.create(name.trim(), parsedData);
toast.success('Environment created');
navigate(`/environments/${env.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -44,16 +61,14 @@ export function CreateEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{ label: t('environments.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
@@ -67,34 +82,29 @@ export function CreateEnvironmentPage() {
required
autoFocus
/>
<Input
label={t('environments.form_id_url')}
type="url"
placeholder="https://…"
value={idUrl}
onChange={(e) => setIdUrl(e.target.value)}
/>
<Input
label={t('environments.form_cabinet_url')}
type="url"
placeholder="https://…"
value={cabinetUrl}
onChange={(e) => setCabinetUrl(e.target.value)}
/>
<Input
label={t('environments.form_admin_url')}
type="url"
placeholder="https://…"
value={adminUrl}
onChange={(e) => setAdminUrl(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
language="json"
value={dataJson}
onChange={(v) => {
setDataJson(v);
setDataError('');
}}
rows={8}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/environments')}>
<X size={14} />
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('environments.action_save')}
</Button>
</div>
@@ -1,22 +1,23 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditEnvironmentPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [env, setEnv] = useState<Environment | null>(null);
const [name, setName] = useState('');
const [idUrl, setIdUrl] = useState('');
const [cabinetUrl, setCabinetUrl] = useState('');
const [adminUrl, setAdminUrl] = useState('');
const [dataJson, setDataJson] = useState('{}');
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -28,9 +29,7 @@ export function EditEnvironmentPage() {
.then((data) => {
setEnv(data);
setName(data.name);
setIdUrl(data.urls.id_url ?? '');
setCabinetUrl(data.urls.cabinet_url ?? '');
setAdminUrl(data.urls.admin_url ?? '');
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
@@ -42,20 +41,36 @@ export function EditEnvironmentPage() {
setNameError(t('environments.form_name_required'));
return;
}
let parsedData: Record<string, string | undefined>;
try {
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
throw new Error('invalid');
}
parsedData = Object.fromEntries(
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
k,
v == null ? undefined : String(v),
]),
);
setDataError('');
} catch {
setDataError(t('environments.form_data_invalid_json'));
return;
}
setSaving(true);
setError(null);
try {
await environments.update(id!, {
name: name.trim(),
urls: {
id_url: idUrl.trim() || undefined,
cabinet_url: cabinetUrl.trim() || undefined,
admin_url: adminUrl.trim() || undefined,
},
data: parsedData,
});
toast.success('Environment updated');
navigate(`/environments/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -66,7 +81,7 @@ export function EditEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
@@ -76,12 +91,11 @@ export function EditEnvironmentPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{!loading && env && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('environments.form_name')}
@@ -95,27 +109,20 @@ export function EditEnvironmentPage() {
required
autoFocus
/>
<Input
label={t('environments.form_id_url')}
type="url"
placeholder="https://…"
value={idUrl}
onChange={(e) => setIdUrl(e.target.value)}
/>
<Input
label={t('environments.form_cabinet_url')}
type="url"
placeholder="https://…"
value={cabinetUrl}
onChange={(e) => setCabinetUrl(e.target.value)}
/>
<Input
label={t('environments.form_admin_url')}
type="url"
placeholder="https://…"
value={adminUrl}
onChange={(e) => setAdminUrl(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
<CodeEditor
language="json"
value={dataJson}
onChange={(v) => {
setDataJson(v);
setDataError('');
}}
rows={8}
error={!!dataError}
/>
{dataError && <span className={styles.fieldError}>{dataError}</span>}
</div>
</div>
<div className={styles.formActions}>
@@ -124,9 +131,11 @@ export function EditEnvironmentPage() {
variant="secondary"
onClick={() => navigate(`/environments/${id}`)}
>
<X size={14} />
{t('environments.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('environments.action_update')}
</Button>
</div>
@@ -1,10 +1,11 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Pencil, Trash2 } from 'lucide-react';
import { Upload, Pencil, Trash2, Globe } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
import { Breadcrumbs, Button, Card, DescriptionList, Modal, Timestamp, UuidBadge } from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
@@ -14,6 +15,9 @@ export function EnvironmentDetailPage() {
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
useEffect(() => {
if (!id) return;
@@ -26,8 +30,26 @@ export function EnvironmentDetailPage() {
const handleDelete = async () => {
if (!env) return;
await environments.remove(env.id);
navigate('/environments');
setDeleting(true);
try {
await environments.remove(env.id);
navigate('/environments');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
if (!env) return;
const data = await environments.exportEnvironment(env.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `environment-${env.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
return (
@@ -35,12 +57,16 @@ export function EnvironmentDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), onClick: () => navigate('/environments') },
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{ label: env?.name ?? `#${id}` },
]}
/>
{env && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Upload size={14} />
{t('environments.action_export')}
</Button>
<Button
variant="secondary"
size="sm"
@@ -49,7 +75,7 @@ export function EnvironmentDetailPage() {
<Pencil size={14} />
{t('environments.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('environments.action_delete')}
</Button>
@@ -57,24 +83,15 @@ export function EnvironmentDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_environment', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
{env && (
<>
<div className={styles.detailMeta}>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('environments.field_id'), detail: env.id },
{ term: t('environments.field_id'), detail: <UuidBadge id={env.id} /> },
{
term: t('environments.field_created'),
detail: <Timestamp value={env.createdAt} />,
@@ -85,18 +102,17 @@ export function EnvironmentDetailPage() {
},
]}
/>
</div>
</Card>
<h2 className={styles.sectionHeading}>{t('environments.section_urls')}</h2>
<Card>
{Object.entries(env.urls).filter(([, v]) => v).length === 0 ? (
<p className={styles.muted}>{t('environments.no_urls')}</p>
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
<Card>
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="comfortable"
items={Object.entries(env.urls)
.filter(([, v]) => v)
.map(([key, value]) => ({
layout="grid"
items={dataEntries.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
@@ -107,8 +123,27 @@ export function EnvironmentDetailPage() {
/>
)}
</Card>
</div>
</>
)}
<Modal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
</div>
);
}
+102 -14
View File
@@ -1,16 +1,38 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Settings, ExternalLink, Pencil, Trash2, Plus } from 'lucide-react';
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const urlEntries = Object.entries(env.urls).filter(([, v]) => v);
const dataEntries = Object.entries(env.data ?? {}).filter(([, v]) => v);
const handleExport = async () => {
const data = await environments.exportEnvironment(env.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `environment-${env.name}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
const header = (
<div className={styles.envCardHeader}>
@@ -34,6 +56,11 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
icon: <Pencil size={14} />,
onClick: () => navigate(`/environments/${env.id}/edit`),
},
{
label: t('environments.action_export'),
icon: <Download size={14} />,
onClick: () => void handleExport(),
},
{
label: t('environments.action_delete'),
icon: <Trash2 size={14} />,
@@ -61,15 +88,15 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
footer={footer}
onClick={() => navigate(`/environments/${env.id}`)}
>
{urlEntries.length > 0 && (
{dataEntries.length > 0 && (
<DescriptionList
layout="compact"
truncate
items={urlEntries.map(([key, value]) => ({ term: key, detail: value }))}
items={dataEntries.map(([key, value]) => ({ term: key, detail: value }))}
/>
)}
{urlEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_urls')}</p>
{dataEntries.length === 0 && (
<p className={styles.envCardEmpty}>{t('environments.no_data')}</p>
)}
</Card>
);
@@ -90,9 +117,13 @@ function AddEnvironmentCard() {
export function EnvironmentsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
environments
@@ -106,25 +137,82 @@ export function EnvironmentsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await environments.remove(id);
setItems((prev) => prev.filter((e) => e.id !== id));
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await environments.remove(deleteId);
setItems((prev) => prev.filter((e) => e.id !== deleteId));
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const text = await file.text();
const payload = yamlParse(text) as unknown;
const imported = await environments.importEnvironment(payload);
navigate(`/environments/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
return (
<div>
<Breadcrumbs items={[{ label: t('environments.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('environments.title'), icon: <Globe size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
type="file"
accept=".yaml,.yml,.json"
style={{ display: 'none' }}
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Download size={14} />
{t('environments.action_import')}
</Button>
</div>
</div>
{loading ? (
<p className={styles.muted}>{t('environments.loading')}</p>
) : (
<div className={styles.envGrid}>
{items.map((env) => (
<EnvironmentCard key={env.id} env={env} onDelete={handleDelete} />
<EnvironmentCard key={env.id} env={env} onDelete={requestDelete} />
))}
<AddEnvironmentCard />
</div>
)}
<Modal
open={deleteId != null}
title={t('environments.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
</div>
);
}
+21 -11
View File
@@ -1,9 +1,18 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Activity } from 'lucide-react';
import { runs } from '../../api';
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
import { AutoRefreshIndicator, Badge, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
import {
AutoRefreshIndicator,
Badge,
Breadcrumbs,
Table,
Timestamp,
UuidBadge,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
@@ -35,20 +44,24 @@ export function AllRunsPage() {
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const load = () => {
const load = useCallback(() => {
if (!hasDataRef.current) setLoading(true);
runs
.listAll()
.then((res) => {
setItems(res.data as AllRunRow[]);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
}, []);
useEffect(() => {
setLoading(true);
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
@@ -77,9 +90,7 @@ export function AllRunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 110,
render: (r) => (
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
),
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
@@ -98,11 +109,10 @@ export function AllRunsPage() {
return (
<div>
<div className={styles.pageToolbar}>
<h1 className={styles.pageTitle}>{t('runs.title')}</h1>
<AutoRefreshIndicator active pulseKey={pulseKey} />
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
+71 -20
View File
@@ -19,12 +19,15 @@ import {
Card,
DescriptionList,
Notification,
Pagination,
Search,
Table,
Timestamp,
UuidBadge,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import { ClipboardList, Activity } from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
@@ -56,6 +59,8 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
error: 'error',
};
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
export function RunDetailPage() {
const { t } = useTranslation();
const { id, runId } = useParams<{ id: string; runId: string }>();
@@ -67,10 +72,13 @@ export function RunDetailPage() {
const [error, setError] = useState<string | null>(null);
const [polling, setPolling] = useState(false);
const [pulseKey, setPulseKey] = useState(0);
const [logPage, setLogPage] = useState(1);
const [logSearch, setLogSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
const stopPolling = () => {
if (pollRef.current) {
clearInterval(pollRef.current);
@@ -79,6 +87,35 @@ export function RunDetailPage() {
}
};
const manualRefresh = () => {
if (!id || !runId) return;
runs
.get(id, runId, logSearchRef.current)
.then((r) => {
setRun(r);
setError(null);
setPulseKey((k) => k + 1);
})
.catch((err: Error) => setError(err.message));
};
useEffect(() => {
const t = setTimeout(() => {
setDebouncedSearch(logSearch);
logSearchRef.current = logSearch;
setLogPage(1);
}, 300);
return () => clearTimeout(t);
}, [logSearch]);
useEffect(() => {
if (!id || !runId || polling) return;
runs
.get(id, runId, debouncedSearch)
.then(setRun)
.catch(() => undefined);
}, [id, runId, polling, debouncedSearch]);
useEffect(() => {
if (!id || !runId) return;
let cancelled = false;
@@ -92,7 +129,7 @@ export function RunDetailPage() {
setPolling(true);
pollRef.current = setInterval(async () => {
try {
const updated = await runs.get(id, runId);
const updated = await runs.get(id, runId, logSearchRef.current);
if (cancelled) return;
setRun(updated);
setPulseKey((k) => k + 1);
@@ -103,8 +140,12 @@ export function RunDetailPage() {
}, 1000);
}
})
.catch((err: Error) => { if (!cancelled) setError(err.message); })
.finally(() => { if (!cancelled) setLoading(false); });
.catch((err: Error) => {
if (!cancelled) setError(err.message);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
@@ -115,10 +156,10 @@ export function RunDetailPage() {
const stepColumns: TableColumn<ScenarioRunStep>[] = [
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
{
key: 'type',
header: t('runs.step_type'),
width: 80,
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? '–'}</Badge>,
key: 'title',
header: t('runs.step_title'),
width: 220,
render: (s) => s.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
},
{
key: 'status',
@@ -156,33 +197,29 @@ export function RunDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
label: t('runs.title'),
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
]}
/>
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} />
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} error={!!error} onClick={manualRefresh} />
</div>
{error && (
<Notification variant="error">
{error.startsWith('404') ? t('errors.not_found') : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
{run && (
<>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
@@ -193,7 +230,6 @@ export function RunDetailPage() {
</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} /> },
]}
@@ -215,14 +251,29 @@ export function RunDetailPage() {
{run.logs.length > 0 && (
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
<Search
value={logSearch}
onChange={setLogSearch}
placeholder={t('runs.logs_search_placeholder')}
/>
</div>
<Table
columns={logColumns}
data={run.logs}
data={run.logs.slice((logPage - 1) * LOG_PAGE_SIZE, logPage * LOG_PAGE_SIZE)}
rowKey={(l) => l.id}
loading={false}
emptyMessage=""
/>
{run.logs.length > LOG_PAGE_SIZE && (
<Pagination
page={logPage}
pageSize={LOG_PAGE_SIZE}
total={run.logs.length}
onPageChange={setLogPage}
/>
)}
</div>
)}
</>
+89 -15
View File
@@ -1,10 +1,28 @@
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 { Play, ClipboardList, Activity } from 'lucide-react';
import { environments, scenarios, runs } from '../../api';
import type {
Environment,
Scenario,
ScenarioRun,
ScenarioRunStep,
ScenarioRunStatus,
} from '../../api';
import {
AutoRefreshIndicator,
Badge,
Breadcrumbs,
Button,
Modal,
Select,
Table,
Timestamp,
UuidBadge,
useToast,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import styles from '../Page.module.css';
@@ -28,28 +46,37 @@ export function RunsPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [items, setItems] = useState<RunRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const load = useCallback(() => {
if (!id) return;
setLoading(true);
if (!hasDataRef.current) setLoading(true);
Promise.all([scenarios.get(id!), runs.list(id!)])
.then(([sc, res]) => {
setScenario(sc);
setItems(res.data);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
@@ -57,9 +84,32 @@ export function RunsPage() {
};
}, [load]);
useEffect(() => {
environments
.list(1, 200)
.then((res) => {
setEnvs(res.data);
setSelectedEnvId((prev) => prev || res.data[0]?.id || '');
})
.catch(() => {});
}, []);
const handleRun = async () => {
const run = await scenarios.run(id!);
navigate(`/scenarios/${id}/runs/${run.id}`);
if (!selectedEnvId) {
toast.error(t('scenarios.run_modal_env_required'));
return;
}
setRunning(true);
try {
const run = await scenarios.run(id!, selectedEnvId);
toast.success('Scenario run started');
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const columns: TableColumn<RunRow>[] = [
@@ -68,9 +118,7 @@ export function RunsPage() {
key: 'status',
header: t('runs.col_status'),
width: 100,
render: (r) => (
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
),
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
},
{
key: 'steps',
@@ -91,24 +139,23 @@ export function RunsPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('runs.title') },
{ label: t('runs.title'), icon: <Activity size={14} /> },
]}
/>
<div className={styles.toolbarActions}>
<AutoRefreshIndicator active pulseKey={pulseKey} />
<Button size="sm" onClick={handleRun}>
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
<Button size="sm" onClick={() => setRunModalOpen(true)}>
<Play size={14} />
{t('runs.action_run')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
@@ -119,6 +166,33 @@ export function RunsPage() {
pageSizeOptions={[10, 20, 50]}
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
/>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('runs.action_run')}
</Button>
</>
)}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
)}
</Modal>
</div>
);
}
@@ -1,13 +1,15 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateScenarioPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [nameError, setNameError] = useState('');
@@ -24,9 +26,12 @@ export function CreateScenarioPage() {
setError(null);
try {
const scenario = await scenarios.create(name.trim());
toast.success('Scenario created');
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -37,14 +42,12 @@ export function CreateScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{ label: t('scenarios.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
@@ -64,9 +67,11 @@ export function CreateScenarioPage() {
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/scenarios')}>
<X size={14} />
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('scenarios.action_save')}
</Button>
</div>
+17 -59
View File
@@ -1,57 +1,47 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario, StepType } from '../../api';
import type { CreateStepPayload } from '../../api/client';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
export function CreateStepPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [order, setOrder] = useState('0');
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);
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,
});
toast.success('Step created');
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -62,7 +52,7 @@ export function CreateStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -72,60 +62,28 @@ export function CreateStepPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => setOrder(e.target.value)}
error={errors.order}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate(`/scenarios/${id}`)}>
<X size={14} />
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('steps.action_save')}
</Button>
</div>
+10 -4
View File
@@ -1,15 +1,17 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditScenarioPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [name, setName] = useState('');
@@ -40,9 +42,12 @@ export function EditScenarioPage() {
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
toast.success('Scenario updated');
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -53,7 +58,7 @@ export function EditScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -63,7 +68,6 @@ export function EditScenarioPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{!loading && scenario && (
@@ -90,9 +94,11 @@ export function EditScenarioPage() {
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
<X size={14} />
{t('scenarios.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('scenarios.action_update')}
</Button>
</div>
+14 -65
View File
@@ -1,26 +1,22 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
import { scenarios, steps } from '../../api';
import type { Scenario, ScenarioStep, StepType } from '../../api';
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
import type { Scenario, ScenarioStep } from '../../api';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
export function EditStepPage() {
const { t } = useTranslation();
const { id, stepId } = useParams<{ id: string; stepId: string }>();
const navigate = useNavigate();
const toast = useToast();
const [scenario, setScenario] = useState<Scenario | null>(null);
const [step, setStep] = useState<ScenarioStep | null>(null);
const [order, setOrder] = useState('');
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);
@@ -31,41 +27,28 @@ export function EditStepPage() {
.then(([sc, st]) => {
setScenario(sc);
setStep(st);
setOrder(String(st.order));
setTitle(st.title ?? '');
setType(st.type);
setExecCode(st.execCode ?? '');
setValidateCode(st.validateCode ?? '');
})
.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,
});
toast.success('Step updated');
navigate(`/scenarios/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -76,67 +59,31 @@ export function EditStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{ label: t('steps.edit_title', { order: step?.order ?? stepId }) },
{ label: t('steps.edit_title', { order: step ? step.order + 1 : stepId }) },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('steps.loading')}</p>}
{!loading && step && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('steps.form_order')}
type="number"
min={0}
value={order}
onChange={(e) => {
setOrder(e.target.value);
setOrderError('');
}}
error={orderError || undefined}
/>
<Input
label={t('steps.form_title')}
placeholder={t('steps.form_title_placeholder')}
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Select
label={t('steps.form_type')}
value={type}
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={execCode}
onChange={(e) => setExecCode(e.target.value)}
placeholder={t('steps.form_exec_code_placeholder')}
spellCheck={false}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
<textarea
className={styles.textarea}
rows={6}
value={validateCode}
onChange={(e) => setValidateCode(e.target.value)}
placeholder={t('steps.form_validate_code_placeholder')}
spellCheck={false}
/>
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
</div>
</div>
@@ -146,9 +93,11 @@ export function EditStepPage() {
variant="secondary"
onClick={() => navigate(`/scenarios/${id}`)}
>
<X size={14} />
{t('steps.action_cancel')}
</Button>
<Button type="submit" loading={saving}>
<Save size={14} />
{t('steps.action_update')}
</Button>
</div>
+263 -78
View File
@@ -1,36 +1,31 @@
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 { Play, Pencil, Plus, History, Trash2, Upload, GripVertical, ClipboardList } 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 { environments, scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential, Environment } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Input,
Notification,
Modal,
Select,
Table,
Timestamp,
UuidBadge,
useToast,
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 toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -44,10 +39,21 @@ export function ScenarioDetailPage() {
const [addCredError, setAddCredError] = useState('');
const [addAliasError, setAddAliasError] = useState('');
const [addCredSaving, setAddCredSaving] = useState(false);
const [draggedStepId, setDraggedStepId] = useState<string | null>(null);
const [dragOverStepId, setDragOverStepId] = useState<string | null>(null);
const [reorderingSteps, setReorderingSteps] = useState(false);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const [pendingDelete, setPendingDelete] = useState<
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
>(null);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
scenarios
void scenarios
.get(id)
.then((s) => {
setScenario(s);
@@ -59,12 +65,39 @@ export function ScenarioDetailPage() {
.list(1, 200)
.then((r) => setAllCredentials(r.data))
.catch(() => {});
environments
.list(1, 200)
.then((r) => {
setEnvs(r.data);
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
})
.catch(() => {});
}, [id]);
const reloadScenario = async () => {
if (!id) return;
const s = await scenarios.get(id);
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
};
const handleRun = async () => {
if (!scenario) return;
const run = await scenarios.run(scenario.id);
navigate(`/scenarios/${id}/runs/${run.id}`);
if (!selectedEnvId) {
toast.error(t('scenarios.run_modal_env_required'));
return;
}
setRunning(true);
try {
const run = await scenarios.run(scenario.id, selectedEnvId);
toast.success('Scenario run started');
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const handleDelete = async () => {
@@ -76,7 +109,8 @@ export function ScenarioDetailPage() {
const handleExport = async () => {
if (!scenario) return;
const data = await scenarios.exportScenario(scenario.id);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
@@ -87,16 +121,34 @@ export function ScenarioDetailPage() {
const handleDeleteStep = async (stepId: string) => {
await steps.remove(id!, stepId);
setScenario((prev) =>
prev ? { ...prev, steps: prev.steps.filter((s) => s.id !== stepId) } : prev,
);
await reloadScenario();
};
const handleMoveStep = async (fromStepId: string, toStepId: string) => {
if (!scenario || reorderingSteps) return;
setReorderingSteps(true);
try {
const orderedSteps = [...scenario.steps].sort((a, b) => a.order - b.order);
const toIndex = orderedSteps.findIndex((step) => step.id === toStepId);
if (toIndex < 0) return;
await steps.update(id!, fromStepId, { order: toIndex });
await reloadScenario();
} finally {
setReorderingSteps(false);
}
};
const handleAddCredential = async (e: 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 (!addCredId) {
setAddCredError(t('scenarios.cred_form_cred_required'));
valid = false;
}
if (!addAlias.trim()) {
setAddAliasError(t('scenarios.cred_form_alias_required'));
valid = false;
}
if (!valid) return;
setAddCredSaving(true);
try {
@@ -120,18 +172,73 @@ export function ScenarioDetailPage() {
setScenarioCreds((prev) => prev.filter((sc) => sc.id !== scCredId));
};
const confirmDelete = async () => {
if (!pendingDelete) return;
setDeleting(true);
try {
if (pendingDelete.type === 'scenario') {
await handleDelete();
return;
}
if (pendingDelete.type === 'step') {
await handleDeleteStep(pendingDelete.id);
}
if (pendingDelete.type === 'credential') {
await handleRemoveCredential(pendingDelete.id);
}
setPendingDelete(null);
} finally {
setDeleting(false);
}
};
const stepColumns: TableColumn<ScenarioStep>[] = [
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
{
key: 'type',
header: t('scenarios.step_type'),
width: 90,
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
key: 'drag',
header: '',
width: 44,
align: 'center',
render: (s) => (
<span
role="button"
tabIndex={0}
aria-label="Drag to reorder step"
className={[styles.dragHandle, reorderingSteps ? styles.dragHandleDisabled : '']
.filter(Boolean)
.join(' ')}
draggable={!reorderingSteps}
onClick={(e) => e.stopPropagation()}
onDragStart={(e) => {
if (reorderingSteps) {
e.preventDefault();
return;
}
setDraggedStepId(s.id);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', s.id);
}}
onDragEnd={() => {
setDraggedStepId(null);
setDragOverStepId(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
}
}}
>
<GripVertical size={14} />
</span>
),
},
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order + 1, width: 60 },
{
key: 'title',
header: t('scenarios.step_title'),
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>,
render: (s) =>
s.title ?? (
<span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>
),
},
{
key: 'updated',
@@ -163,7 +270,7 @@ export function ScenarioDetailPage() {
title={t('steps.action_delete')}
onClick={(e) => {
e.stopPropagation();
handleDeleteStep(s.id);
setPendingDelete({ type: 'step', id: s.id });
}}
>
<Trash2 size={14} />
@@ -198,7 +305,7 @@ export function ScenarioDetailPage() {
title={t('scenarios.cred_action_remove')}
onClick={(e) => {
e.stopPropagation();
handleRemoveCredential(sc.id);
setPendingDelete({ type: 'credential', id: sc.id });
}}
>
<Trash2 size={14} />
@@ -212,13 +319,13 @@ export function ScenarioDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{ label: scenario?.name ?? `#${id}` },
]}
/>
{scenario && (
<div className={styles.toolbarActions}>
<Button size="sm" onClick={handleRun}>
<Button size="sm" onClick={() => setRunModalOpen(true)}>
<Play size={14} />
{t('scenarios.action_run')}
</Button>
@@ -227,14 +334,14 @@ export function ScenarioDetailPage() {
{t('scenarios.action_runs')}
</Button>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
<Upload size={14} />
{t('scenarios.action_export')}
</Button>
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
<Pencil size={14} />
{t('scenarios.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setPendingDelete({ type: 'scenario' })}>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
@@ -242,25 +349,16 @@ export function ScenarioDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_scenario', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
{scenario && (
<>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
{
term: t('scenarios.field_created'),
detail: <Timestamp value={scenario.createdAt} />,
@@ -288,6 +386,30 @@ export function ScenarioDetailPage() {
rowKey={(s) => s.id}
loading={false}
emptyMessage=""
getRowProps={(s) => ({
className: dragOverStepId === s.id ? styles.dragOverRow : undefined,
onDragOver: (e) => {
if (reorderingSteps) return;
e.preventDefault();
if (draggedStepId && draggedStepId !== s.id) {
setDragOverStepId(s.id);
}
},
onDragLeave: () => {
if (dragOverStepId === s.id) {
setDragOverStepId(null);
}
},
onDrop: async (e) => {
if (reorderingSteps) return;
e.preventDefault();
const fromId = draggedStepId ?? e.dataTransfer.getData('text/plain');
setDragOverStepId(null);
setDraggedStepId(null);
if (!fromId || fromId === s.id) return;
await handleMoveStep(fromId, s.id);
},
})}
/>
</div>
)}
@@ -315,42 +437,52 @@ export function ScenarioDetailPage() {
{addCredOpen && (
<div style={{ marginBottom: 'var(--space-4)' }}>
<Card className={styles.formCard}>
<form onSubmit={handleAddCredential} noValidate>
<div className={styles.formFields}>
<Select
label={t('scenarios.cred_form_cred')}
value={addCredId}
onChange={(e) => { setAddCredId(e.target.value); setAddCredError(''); }}
error={addCredError || undefined}
options={[
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
]}
/>
<Input
label={t('scenarios.cred_form_alias')}
placeholder={t('scenarios.cred_form_alias_placeholder')}
value={addAlias}
onChange={(e) => { setAddAlias(e.target.value); setAddAliasError(''); }}
error={addAliasError || undefined}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => { setAddCredOpen(false); setAddCredId(''); setAddAlias(''); }}
>
{t('scenarios.cred_action_cancel')}
</Button>
<Button type="submit" size="sm" loading={addCredSaving}>
{t('scenarios.cred_action_save')}
</Button>
</div>
</form>
</Card>
<Card className={styles.formCard}>
<form onSubmit={handleAddCredential} noValidate>
<div className={styles.formFields}>
<Select
label={t('scenarios.cred_form_cred')}
value={addCredId}
onChange={(e) => {
setAddCredId(e.target.value);
setAddCredError('');
}}
error={addCredError || undefined}
options={[
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
]}
/>
<Input
label={t('scenarios.cred_form_alias')}
placeholder={t('scenarios.cred_form_alias_placeholder')}
value={addAlias}
onChange={(e) => {
setAddAlias(e.target.value);
setAddAliasError('');
}}
error={addAliasError || undefined}
/>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => {
setAddCredOpen(false);
setAddCredId('');
setAddAlias('');
}}
>
{t('scenarios.cred_action_cancel')}
</Button>
<Button type="submit" size="sm" loading={addCredSaving}>
{t('scenarios.cred_action_save')}
</Button>
</div>
</form>
</Card>
</div>
)}
@@ -368,6 +500,59 @@ export function ScenarioDetailPage() {
</div>
</>
)}
<Modal
open={pendingDelete != null}
title={
pendingDelete?.type === 'step'
? t('steps.action_delete')
: pendingDelete?.type === 'credential'
? t('scenarios.cred_action_remove')
: t('scenarios.action_delete')
}
onClose={() => !deleting && setPendingDelete(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
Confirm
</Button>
</>
)}
>
{pendingDelete?.type === 'step' && 'Are you sure you want to delete this step?'}
{pendingDelete?.type === 'credential' && 'Are you sure you want to remove this credential from scenario?'}
{pendingDelete?.type === 'scenario' && 'Are you sure you want to delete this scenario?'}
</Modal>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('scenarios.action_run')}
</Button>
</>
)}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
)}
</Modal>
</div>
);
}
+116 -19
View File
@@ -1,26 +1,45 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Plus, Trash2, Upload } from 'lucide-react';
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { scenarios } from '../../api';
import type { Scenario } from '../../api';
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
import { environments, scenarios } from '../../api';
import type { Environment, Scenario } from '../../api';
import {
Breadcrumbs,
Button,
Modal,
Select,
Table,
type TableColumn,
Timestamp,
UuidBadge,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function ScenariosPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const toast = useToast();
const [items, setItems] = useState<Scenario[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
const [running, setRunning] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const fileInputRef = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
scenarios
.list()
.then((res) => setItems(res.data))
Promise.all([scenarios.list(), environments.list(1, 200)])
.then(([scenarioRes, envRes]) => {
setItems(scenarioRes.data);
setEnvs(envRes.data);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
@@ -29,15 +48,39 @@ export function ScenariosPage() {
load();
}, [load]);
const handleRun = async (id: string) => {
const run = await scenarios.run(id);
navigate(`/scenarios/${id}/runs/${run.id}`);
const openRunModal = (id: string) => {
setRunScenarioId(id);
if (!selectedEnvId && envs.length > 0) {
setSelectedEnvId(envs[0].id);
}
};
const handleDelete = async (id: string) => {
await scenarios.remove(id);
setLoading(true);
load();
const handleRun = async () => {
if (!runScenarioId || !selectedEnvId) return;
setRunning(true);
try {
const run = await scenarios.run(runScenarioId, selectedEnvId);
toast.success('Scenario run started');
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
setRunScenarioId(null);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRunning(false);
}
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await scenarios.remove(deleteId);
setLoading(true);
load();
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -70,14 +113,24 @@ export function ScenariosPage() {
align: 'right',
render: (s) => (
<span style={{ display: 'inline-flex', gap: 6 }}>
<Button size="sm" title={t('scenarios.action_run')} onClick={() => handleRun(s.id)}>
<Button
size="sm"
title={t('scenarios.action_run')}
onClick={(e) => {
e.stopPropagation();
openRunModal(s.id);
}}
>
<Play size={14} />
</Button>
<Button
variant="danger"
size="sm"
title={t('scenarios.action_delete')}
onClick={() => handleDelete(s.id)}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
@@ -89,7 +142,7 @@ export function ScenariosPage() {
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
<Breadcrumbs items={[{ label: t('scenarios.title'), icon: <ClipboardList size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -99,7 +152,7 @@ export function ScenariosPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('scenarios.action_import')}
</Button>
<Button size="sm" onClick={() => navigate('/scenarios/new')}>
@@ -108,7 +161,6 @@ export function ScenariosPage() {
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
<Table
columns={columns}
data={items}
@@ -119,6 +171,51 @@ export function ScenariosPage() {
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
/>
<Modal
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('scenarios.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this scenario?
</Modal>
<Modal
open={runScenarioId != null}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunScenarioId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
Cancel
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('scenarios.action_run')}
</Button>
</>
)}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
)}
</Modal>
</div>
);
}
+42 -15
View File
@@ -1,10 +1,19 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function SessionDetailPage() {
@@ -14,6 +23,8 @@ export function SessionDetailPage() {
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
@@ -26,8 +37,14 @@ export function SessionDetailPage() {
const handleDelete = async () => {
if (!session) return;
await sessions.remove(session.id);
navigate('/sessions');
setDeleting(true);
try {
await sessions.remove(session.id);
navigate('/sessions');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
return (
@@ -35,32 +52,24 @@ export function SessionDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('sessions.title'), onClick: () => navigate('/sessions') },
{ label: t('sessions.title'), icon: <Monitor size={14} />, onClick: () => navigate('/sessions') },
{ label: session?.sessionName ?? `#${id}` },
]}
/>
{session && (
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('sessions.action_delete')}
</Button>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_session', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('sessions.loading')}</p>}
{session && (
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('sessions.field_id'), detail: <UuidBadge id={session.id} /> },
{ term: t('sessions.field_name'), detail: session.sessionName },
@@ -92,6 +101,24 @@ export function SessionDetailPage() {
/>
</Card>
)}
<Modal
open={confirmDeleteOpen}
title={t('sessions.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
</div>
);
}
+49 -9
View File
@@ -1,10 +1,19 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Trash2 } from 'lucide-react';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import { Badge, Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
import {
Badge,
Breadcrumbs,
Button,
Modal,
Table,
type TableColumn,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function SessionsPage() {
@@ -13,6 +22,8 @@ export function SessionsPage() {
const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const load = useCallback(() => {
sessions
@@ -26,10 +37,17 @@ export function SessionsPage() {
load();
}, [load]);
const handleDelete = async (id: string) => {
await sessions.remove(id);
setLoading(true);
load();
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await sessions.remove(deleteId);
setLoading(true);
load();
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const columns: TableColumn<Session>[] = [
@@ -57,7 +75,10 @@ export function SessionsPage() {
variant="danger"
size="sm"
title={t('sessions.action_delete')}
onClick={() => handleDelete(s.id)}
onClick={(e) => {
e.stopPropagation();
setDeleteId(s.id);
}}
>
<Trash2 size={14} />
</Button>
@@ -67,8 +88,9 @@ export function SessionsPage() {
return (
<div>
<Breadcrumbs items={[{ label: t('sessions.title') }]} className={styles.breadcrumbs} />
{error && <p className={styles.error}>{error}</p>}
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('sessions.title'), icon: <Monitor size={14} /> }]} />
</div>
<Table
columns={columns}
data={items}
@@ -79,6 +101,24 @@ export function SessionsPage() {
pageSizeOptions={[10, 25, 50]}
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
<Modal
open={deleteId != null}
title={t('sessions.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
</div>
);
}
+52 -28
View File
@@ -1,18 +1,22 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function CreateSnippetPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const toast = useToast();
const [name, setName] = useState('');
const [alias, setAlias] = useState('');
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -20,8 +24,12 @@ export function CreateSnippetPage() {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
if (!alias.trim()) {
setAliasError(t('snippets.form_alias_required'));
valid = false;
}
if (!title.trim()) {
setTitleError(t('snippets.form_title_required'));
valid = false;
}
if (!code.trim()) {
@@ -33,13 +41,17 @@ export function CreateSnippetPage() {
setError(null);
try {
const snippet = await snippets.create({
name: name.trim(),
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet created');
navigate(`/snippets/${snippet.id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -50,59 +62,71 @@ export function CreateSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{ label: t('snippets.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setName(e.target.value);
setNameError('');
setAlias(e.target.value);
setAliasError('');
}}
error={nameError || undefined}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
label={t('snippets.form_title')}
placeholder={t('snippets.form_title_placeholder')}
value={title}
onChange={(e) => {
setTitle(e.target.value);
setTitleError('');
}}
error={titleError || undefined}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
<CodeEditor
value={description}
onChange={setDescription}
language="markdown"
rows={10}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
<CodeEditor
value={code}
onChange={(e) => {
setCode(e.target.value);
onChange={(v) => {
setCode(v);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
rows={14}
error={!!codeError}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
<X size={14} />
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
<Save size={14} />
{t('snippets.action_save')}
</Button>
</div>
+56 -34
View File
@@ -1,21 +1,25 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
import styles from '../Page.module.css';
export function EditSnippetPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const toast = useToast();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [name, setName] = useState('');
const [alias, setAlias] = useState('');
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [aliasError, setAliasError] = useState('');
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -27,7 +31,8 @@ export function EditSnippetPage() {
.get(id)
.then((s) => {
setSnippet(s);
setName(s.name);
setAlias(s.alias);
setTitle(s.title);
setDescription(s.description ?? '');
setCode(s.code);
})
@@ -38,8 +43,12 @@ export function EditSnippetPage() {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
if (!alias.trim()) {
setAliasError(t('snippets.form_alias_required'));
valid = false;
}
if (!title.trim()) {
setTitleError(t('snippets.form_title_required'));
valid = false;
}
if (!code.trim()) {
@@ -51,13 +60,17 @@ export function EditSnippetPage() {
setError(null);
try {
await snippets.update(id!, {
name: name.trim(),
alias: alias.trim(),
title: title.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet updated');
navigate(`/snippets/${id}`);
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
}
@@ -68,9 +81,9 @@ export function EditSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: snippet?.name ?? `#${id}`,
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
},
{ label: t('snippets.edit_title') },
@@ -78,59 +91,68 @@ export function EditSnippetPage() {
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && snippet && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<Card className={styles.formCardFull}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
label={t('snippets.form_alias')}
placeholder={t('snippets.form_alias_placeholder')}
value={alias}
onChange={(e) => {
setName(e.target.value);
setNameError('');
setAlias(e.target.value);
setAliasError('');
}}
error={nameError || undefined}
error={aliasError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
label={t('snippets.form_title')}
placeholder={t('snippets.form_title_placeholder')}
value={title}
onChange={(e) => {
setTitle(e.target.value);
setTitleError('');
}}
error={titleError || undefined}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
<CodeEditor
value={description}
onChange={setDescription}
language="markdown"
rows={10}
/>
</div>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
<CodeEditor
value={code}
onChange={(e) => {
setCode(e.target.value);
onChange={(v) => {
setCode(v);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
rows={14}
error={!!codeError}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/snippets/${id}`)}
>
<Button type="button" variant="secondary" onClick={() => navigate(`/snippets/${id}`)}>
<X size={14} />
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
<Save size={14} />
{t('snippets.action_update')}
</Button>
</div>
+63 -28
View File
@@ -1,11 +1,21 @@
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 { Upload, Pencil, Trash2, Braces } from 'lucide-react';
import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
export function SnippetDetailPage() {
@@ -15,6 +25,8 @@ export function SnippetDetailPage() {
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
if (!id) return;
@@ -27,8 +39,14 @@ export function SnippetDetailPage() {
const handleDelete = async () => {
if (!snippet) return;
await snippets.remove(snippet.id);
navigate('/snippets');
setDeleting(true);
try {
await snippets.remove(snippet.id);
navigate('/snippets');
} finally {
setDeleting(false);
setConfirmDeleteOpen(false);
}
};
const handleExport = async () => {
@@ -38,7 +56,7 @@ export function SnippetDetailPage() {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snippet-${snippet.name}.yaml`;
a.download = `snippet-${snippet.alias}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
@@ -48,14 +66,14 @@ export function SnippetDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: snippet?.name ?? `#${id}` },
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{ label: snippet?.title ?? `#${id}` },
]}
/>
{snippet && (
<div className={styles.toolbarActions}>
<Button variant="secondary" size="sm" onClick={handleExport}>
<Download size={14} />
<Upload size={14} />
{t('snippets.action_export')}
</Button>
<Button
@@ -66,7 +84,7 @@ export function SnippetDetailPage() {
<Pencil size={14} />
{t('snippets.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} />
{t('snippets.action_delete')}
</Button>
@@ -74,29 +92,17 @@ export function SnippetDetailPage() {
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_snippet', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{snippet && (
<>
<div className={styles.detailMeta}>
<Card>
<DescriptionList
layout="comfortable"
layout="grid"
items={[
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
{ term: t('snippets.field_name'), detail: snippet.name },
{
term: t('snippets.field_description'),
detail: snippet.description ?? '—',
},
{ term: t('snippets.field_alias'), detail: snippet.alias },
{ term: t('snippets.field_title'), detail: snippet.title },
{
term: t('snippets.field_created'),
detail: <Timestamp value={snippet.createdAt} />,
@@ -107,18 +113,47 @@ export function SnippetDetailPage() {
},
]}
/>
</div>
</Card>
{snippet.description && (
<div className={styles.stepsSection}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('snippets.field_description')}</h2>
</div>
<Card>
<MarkdownContent content={snippet.description} />
</Card>
</div>
)}
<div className={styles.stepsSection}>
<div className={styles.sectionHeader}>
<div className={styles.sectionHeadingRow}>
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
</div>
<Card>
<pre className={styles.codeBlock}>{snippet.code}</pre>
<CodeBlock code={snippet.code} />
</Card>
</div>
</>
)}
<Modal
open={confirmDeleteOpen}
title={t('snippets.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this snippet?
</Modal>
</div>
);
}
+78 -24
View File
@@ -1,32 +1,48 @@
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 { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
import { parse as yamlParse } from 'yaml';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, Timestamp, UuidBadge } from '../../ui';
import {
Breadcrumbs,
Button,
Card,
ContextMenu,
MarkdownContent,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import styles from '../Page.module.css';
function SnippetCard({
snippet,
onDelete,
}: {
snippet: Snippet;
onDelete: (id: string) => void;
}) {
function firstParagraphBlocks(markdown: string, limit = 2): { preview: string; truncated: boolean } {
const blocks = markdown
.split(/\n\s*\n/g)
.map((block) => block.trim())
.filter(Boolean);
const sliced = blocks.slice(0, limit);
return {
preview: sliced.join('\n\n'),
truncated: blocks.length > limit,
};
}
function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: string) => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{snippet.name}</span>
<span className={styles.envCardName}>{snippet.title}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
<Code size={14} />
<Settings size={14} />
</Button>
}
items={[
@@ -62,9 +78,19 @@ function SnippetCard({
footer={footer}
onClick={() => navigate(`/snippets/${snippet.id}`)}
>
{snippet.description && (
<p className={styles.muted}>{snippet.description}</p>
)}
<p className={styles.muted}>
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
</p>
{snippet.description && (() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
</Card>
);
}
@@ -88,6 +114,8 @@ export function SnippetsPage() {
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const load = () => {
@@ -102,9 +130,20 @@ export function SnippetsPage() {
load();
}, []);
const handleDelete = async (id: string) => {
await snippets.remove(id);
load();
const requestDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = async () => {
if (!deleteId) return;
setDeleting(true);
try {
await snippets.remove(deleteId);
load();
setDeleteId(null);
} finally {
setDeleting(false);
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -124,7 +163,7 @@ export function SnippetsPage() {
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
<Breadcrumbs items={[{ label: t('snippets.title'), icon: <Braces size={14} /> }]} />
<div className={styles.toolbarActions}>
<input
ref={fileInputRef}
@@ -134,26 +173,41 @@ export function SnippetsPage() {
onChange={handleImport}
/>
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload size={14} />
<Download size={14} />
{t('snippets.action_import')}
</Button>
</div>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && (
<div className={styles.envGrid}>
{items.map((s) => (
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
<SnippetCard key={s.id} snippet={s} onDelete={requestDelete} />
))}
{items.length === 0 && (
<p className={styles.muted}>{t('snippets.empty')}</p>
)}
{items.length === 0 && <p className={styles.muted}>{t('snippets.empty')}</p>}
<AddSnippetCard />
</div>
)}
<Modal
open={deleteId != null}
title={t('snippets.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this snippet?
</Modal>
</div>
);
}
@@ -45,6 +45,25 @@
}
}
/* ── Clickable / hover ────────────────────────────────────── */
.clickable {
cursor: pointer;
border-radius: 99px;
padding: 2px 6px;
margin: -2px -6px;
transition: background var(--transition);
}
.clickable:hover {
background: color-mix(in srgb, var(--color-text) 8%, transparent);
}
.clickable:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
/* ── Active state ─────────────────────────────────────────── */
.active .dot::before {
@@ -67,3 +86,18 @@
color: var(--color-text-muted);
opacity: 0.5;
}
/* ── Error state ──────────────────────────────────────────── */
.error .dot::before {
background: var(--color-error-fg);
}
.error .ring {
animation: none;
}
.error .label {
color: var(--color-error-fg);
font-weight: 600;
}
@@ -4,22 +4,39 @@ export interface AutoRefreshIndicatorProps {
active: boolean;
pulseKey?: number;
label?: string;
error?: boolean;
onClick?: () => void;
}
export function AutoRefreshIndicator({ active, pulseKey, label = 'Live' }: AutoRefreshIndicatorProps) {
export function AutoRefreshIndicator({
active,
pulseKey,
label = 'Live',
error = false,
onClick,
}: AutoRefreshIndicatorProps) {
const stateClass = error ? styles.error : active ? styles.active : styles.inactive;
const titleText = error
? 'Refresh failed — click to retry'
: active
? 'Auto-refreshing'
: 'Auto-refresh stopped';
return (
<div
className={[styles.root, active ? styles.active : styles.inactive].join(' ')}
title={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
aria-label={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
className={[styles.root, stateClass, onClick ? styles.clickable : ''].join(' ')}
title={titleText}
aria-label={titleText}
aria-live="polite"
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
onClick={onClick}
onKeyDown={onClick ? (e) => (e.key === 'Enter' || e.key === ' ') && onClick() : undefined}
>
<span className={styles.dot}>
{pulseKey !== undefined && pulseKey > 0 && (
<span key={pulseKey} className={styles.ring} />
)}
{pulseKey !== undefined && pulseKey > 0 && <span key={pulseKey} className={styles.ring} />}
</span>
<span className={styles.label}>{label}</span>
<span className={styles.label}>{error ? 'Error' : label}</span>
</div>
);
}
+1
View File
@@ -9,6 +9,7 @@
border-radius: var(--radius-full);
white-space: nowrap;
line-height: 1.6;
box-shadow: var(--shadow-xs);
}
.dot {
@@ -1,4 +1,6 @@
.nav {
display: flex;
align-items: center;
font-family: var(--font-family);
}
@@ -19,6 +21,9 @@
}
.link {
display: inline-flex;
align-items: center;
gap: var(--space-1);
font-size: var(--font-size-sm);
color: var(--color-text-muted);
text-decoration: none;
@@ -42,6 +47,9 @@
}
.current {
display: inline-flex;
align-items: center;
gap: var(--space-1);
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--color-text);
+4 -3
View File
@@ -3,6 +3,7 @@ import styles from './Breadcrumbs.module.css';
export interface BreadcrumbItem {
label: string;
icon?: React.ReactNode;
href?: string;
onClick?: (e: React.MouseEvent) => void;
}
@@ -35,15 +36,15 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
<li key={i} className={styles.item}>
{isLast ? (
<span className={styles.current} aria-current="page">
{item.label}
{item.icon}{item.label}
</span>
) : item.href ? (
<a href={item.href} className={styles.link} onClick={item.onClick}>
{item.label}
{item.icon}{item.label}
</a>
) : (
<button type="button" className={styles.link} onClick={item.onClick}>
{item.label}
{item.icon}{item.label}
</button>
)}
{!isLast && <span className={styles.separator}>{sep}</span>}
+1
View File
@@ -11,6 +11,7 @@
white-space: nowrap;
outline: none;
text-decoration: none;
box-shadow: var(--shadow-xs);
transition:
background var(--transition),
border-color var(--transition),
+3
View File
@@ -7,6 +7,9 @@
}
.header {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-3) var(--space-6);
font-weight: 600;
font-size: var(--font-size-sm);
@@ -0,0 +1,76 @@
.pre {
margin: 0;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
}
.code {
font-family: var(--font-mono, ui-monospace, 'Cascadia Code', 'Fira Code', monospace);
font-size: var(--font-size-sm);
line-height: 1.6;
display: block;
background: transparent !important;
color: var(--color-text);
}
/* ── highlight.js token overrides (theme-aware) ─────────────────────── */
.code :global(.hljs-comment),
.code :global(.hljs-quote) {
color: var(--hl-comment, #6A8072);
font-style: italic;
}
.code :global(.hljs-keyword),
.code :global(.hljs-selector-tag),
.code :global(.hljs-built_in),
.code :global(.hljs-name),
.code :global(.hljs-tag) {
color: var(--hl-keyword, #A67DCC);
}
.code :global(.hljs-string),
.code :global(.hljs-title),
.code :global(.hljs-section),
.code :global(.hljs-attribute),
.code :global(.hljs-literal),
.code :global(.hljs-template-tag),
.code :global(.hljs-template-variable),
.code :global(.hljs-type),
.code :global(.hljs-addition) {
color: var(--hl-string, #9BB870);
}
.code :global(.hljs-number),
.code :global(.hljs-regexp),
.code :global(.hljs-link) {
color: var(--hl-number, #E8A85F);
}
.code :global(.hljs-function),
.code :global(.hljs-title.hljs-function_) {
color: var(--hl-function, #5BB8D4);
}
.code :global(.hljs-variable),
.code :global(.hljs-params) {
color: var(--hl-variable, #D4A0A0);
}
.code :global(.hljs-property) {
color: var(--hl-property, #79C0C8);
}
.code :global(.hljs-deletion),
.code :global(.hljs-meta) {
color: var(--hl-meta, #A9A3C9);
}
.code :global(.hljs-emphasis) {
font-style: italic;
}
.code :global(.hljs-strong) {
font-weight: 700;
}
+27
View File
@@ -0,0 +1,27 @@
import { useMemo } from 'react';
import hljs from '../../lib/hljs';
import styles from './CodeBlock.module.css';
export interface CodeBlockProps {
code: string;
language?: string;
}
export function CodeBlock({ code, language = 'javascript' }: CodeBlockProps) {
const highlighted = useMemo(() => {
try {
return hljs.highlight(code, { language }).value;
} catch {
return code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
}, [code, language]);
return (
<pre className={styles.pre}>
<code
className={`${styles.code} hljs language-${language}`}
dangerouslySetInnerHTML={{ __html: highlighted }}
/>
</pre>
);
}
@@ -0,0 +1,18 @@
.wrapper {
width: 100%;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
overflow: hidden;
resize: vertical;
min-height: 80px;
transition: border-color var(--transition), box-shadow var(--transition);
}
.focused {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent);
}
.hasError {
border-color: var(--color-danger);
}
+79
View File
@@ -0,0 +1,79 @@
import { useState, useEffect } from 'react';
import Editor, { OnMount } from '@monaco-editor/react';
import styles from './CodeEditor.module.css';
export interface CodeEditorProps {
value: string;
onChange: (value: string) => void;
language?: string;
rows?: number;
error?: boolean;
}
function useMonacoTheme() {
const [theme, setTheme] = useState(() =>
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
);
useEffect(() => {
const observer = new MutationObserver(() => {
setTheme(
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
);
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});
return () => observer.disconnect();
}, []);
return theme;
}
export function CodeEditor({
value,
onChange,
language = 'javascript',
rows = 6,
error = false,
}: CodeEditorProps) {
const theme = useMonacoTheme();
const [focused, setFocused] = useState(false);
const height = rows * 20 + 16;
const handleMount: OnMount = (editor) => {
editor.onDidFocusEditorWidget(() => setFocused(true));
editor.onDidBlurEditorWidget(() => setFocused(false));
};
return (
<div
className={[styles.wrapper, focused ? styles.focused : '', error ? styles.hasError : '']
.filter(Boolean)
.join(' ')}
style={{ height }}
>
<Editor
height="100%"
theme={theme}
language={language}
value={value}
onChange={(v) => onChange(v ?? '')}
onMount={handleMount}
options={{
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 14,
lineHeight: 20,
wordWrap: 'on',
padding: { top: 8, bottom: 8 },
folding: false,
renderLineHighlight: 'line',
scrollbar: { vertical: 'auto', horizontal: 'hidden' },
automaticLayout: true,
}}
/>
</div>
);
}
@@ -45,7 +45,26 @@
max-width: 100%;
}
/* ── Layout modifiers ───────────────────────────────────────── */
/* ── Grid layout ───────────────────────────────────────────── */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: var(--space-4) var(--space-6);
}
.grid .row {
flex-direction: column;
gap: var(--space-1);
}
.grid .term {
margin-bottom: 0;
}
.grid .detail {
font-size: var(--font-size-sm);
}
.inline .row {
flex-direction: row;
@@ -16,8 +16,8 @@ export interface DescriptionListItem {
export interface DescriptionListProps {
items: DescriptionListItem[];
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default) */
layout?: 'inline' | 'compact' | 'comfortable';
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default); 'grid' flows items into a responsive multi-column grid */
layout?: 'inline' | 'compact' | 'comfortable' | 'grid';
/** Truncate detail values with ellipsis; full value shown in a tooltip on hover */
truncate?: boolean;
className?: string;
+1
View File
@@ -23,6 +23,7 @@
height: 36px;
width: 100%;
outline: none;
box-shadow: var(--shadow-xs);
transition: border-color var(--transition), box-shadow var(--transition);
}
@@ -0,0 +1,113 @@
.markdown {
color: var(--color-text);
line-height: 1.65;
font-size: var(--font-size-sm);
}
.markdown > :first-child {
margin-top: 0;
}
.markdown > :last-child {
margin-bottom: 0;
}
.markdown h1,
.markdown h2,
.markdown h3,
.markdown h4,
.markdown h5,
.markdown h6 {
line-height: 1.25;
margin: var(--space-5) 0 var(--space-3);
}
.markdown h1 {
font-size: var(--font-size-lg);
}
.markdown h2 {
font-size: var(--font-size-md);
}
.markdown h3,
.markdown h4,
.markdown h5,
.markdown h6 {
font-size: var(--font-size-sm);
}
.markdown p {
margin: 0 0 var(--space-3);
}
.markdown ul,
.markdown ol {
margin: 0 0 var(--space-3);
padding-left: 1.35rem;
}
.markdown li + li {
margin-top: var(--space-1);
}
.markdown blockquote {
margin: 0 0 var(--space-3);
padding: var(--space-2) var(--space-3);
border-left: 3px solid var(--color-primary);
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
border-radius: var(--radius-sm);
}
.markdown pre {
margin: 0 0 var(--space-3);
padding: var(--space-3);
border-radius: var(--radius-md);
background: var(--color-code-bg, var(--color-bg-raised));
border: var(--border-width) solid var(--color-border);
overflow-x: auto;
}
.markdown code {
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.92em;
}
.markdown :not(pre) > code {
padding: 0.12em 0.4em;
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--color-bg-raised) 60%, var(--color-secondary) 40%);
border: 1px solid var(--color-border);
}
.markdown table {
width: 100%;
border-collapse: collapse;
margin: 0 0 var(--space-3);
}
.markdown th,
.markdown td {
border: var(--border-width) solid var(--color-border);
padding: var(--space-2) var(--space-3);
text-align: left;
vertical-align: top;
}
.markdown th {
background: color-mix(in srgb, var(--color-bg-raised) 85%, var(--color-secondary) 15%);
}
.markdown a {
color: var(--color-link);
}
.markdown a:hover {
color: var(--color-link-hover);
}
.markdown hr {
border: 0;
border-top: var(--border-width) solid var(--color-border);
margin: var(--space-4) 0;
}
@@ -0,0 +1,16 @@
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import styles from './MarkdownContent.module.css';
export interface MarkdownContentProps {
content: string;
className?: string;
}
export function MarkdownContent({ content, className }: MarkdownContentProps) {
return (
<div className={`${styles.markdown}${className ? ` ${className}` : ''}`}>
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
.overlay {
position: fixed;
inset: 0;
z-index: 2000;
background: color-mix(in srgb, #000 45%, transparent);
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4);
}
.dialog {
width: min(520px, 100%);
background-color: var(--color-bg-subtle, #ffffff);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
overflow: hidden;
}
.header {
padding: var(--space-4) var(--space-5) var(--space-2);
}
.title {
margin: 0;
font-size: var(--font-size-md);
color: var(--color-text);
}
.body {
padding: var(--space-2) var(--space-5) var(--space-4);
color: var(--color-text-muted);
}
.footer {
padding: var(--space-3) var(--space-5) var(--space-4);
display: flex;
justify-content: flex-end;
gap: var(--space-2);
}
+41
View File
@@ -0,0 +1,41 @@
import { useEffect } from 'react';
import styles from './Modal.module.css';
export interface ModalProps {
open: boolean;
title: string;
children?: React.ReactNode;
onClose: () => void;
footer?: React.ReactNode;
}
export function Modal({ open, title, children, onClose, footer }: ModalProps) {
useEffect(() => {
if (!open) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [open, onClose]);
if (!open) return null;
return (
<div className={styles.overlay} role="presentation" onClick={onClose}>
<div
className={styles.dialog}
role="dialog"
aria-modal="true"
aria-label={title}
onClick={(event) => event.stopPropagation()}
>
<div className={styles.header}>
<h3 className={styles.title}>{title}</h3>
</div>
<div className={styles.body}>{children}</div>
{footer && <div className={styles.footer}>{footer}</div>}
</div>
</div>
);
}
+36
View File
@@ -0,0 +1,36 @@
.root {
display: inline-flex;
align-items: center;
gap: var(--space-2);
padding: 5px var(--space-3);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-full);
background: var(--color-bg-subtle);
transition: border-color var(--transition), background var(--transition);
}
.root:focus-within {
border-color: var(--color-primary);
background: var(--color-bg);
}
.icon {
color: var(--color-text-muted);
flex-shrink: 0;
display: block;
}
.input {
border: none;
background: transparent;
color: var(--color-text);
font-family: var(--font-family);
font-size: var(--font-size-xs);
outline: none;
width: 180px;
min-width: 0;
}
.input::placeholder {
color: var(--color-text-muted);
}
+23
View File
@@ -0,0 +1,23 @@
import { Search as SearchIcon } from 'lucide-react';
import styles from './Search.module.css';
export interface SearchProps {
value: string;
onChange: (value: string) => void;
placeholder?: string;
}
export function Search({ value, onChange, placeholder = 'Search…' }: SearchProps) {
return (
<div className={styles.root}>
<SearchIcon size={13} className={styles.icon} />
<input
className={styles.input}
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
/>
</div>
);
}
+4 -3
View File
@@ -79,10 +79,11 @@
/* ── Chevron rotation ────────────────────────────────────── */
.chevron {
transition: transform 220ms ease;
/* Points right (→) by default = collapse direction */
transform: rotate(180deg);
/* Points left (←) by default = collapse direction */
}
.collapsed .chevron {
transform: rotate(180deg);
/* Points left (←) = expand direction */
transform: rotate(0deg);
/* Points right (→) = expand direction */
}
+41 -21
View File
@@ -1,4 +1,4 @@
import { useState, type ReactNode } from 'react';
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
import { Pagination } from '../Pagination/Pagination';
import styles from './Table.module.css';
@@ -23,6 +23,8 @@ export interface TableProps<T> {
pageSizeOptions?: number[];
/** Called when a row is clicked */
onRowClick?: (row: T) => void;
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
}
export function Table<T>({
@@ -35,6 +37,7 @@ export function Table<T>({
pageSize: defaultPageSize,
pageSizeOptions,
onRowClick,
getRowProps,
}: TableProps<T>) {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
@@ -79,26 +82,43 @@ export function Table<T>({
</td>
</tr>
) : (
visibleData.map((row) => (
<tr
key={rowKey(row)}
className={[styles.tr, onRowClick ? styles.clickable : '']
.filter(Boolean)
.join(' ')}
onClick={onRowClick ? () => onRowClick(row) : undefined}
>
{columns.map((col) => (
<td
key={col.key}
className={styles.td}
style={{ textAlign: col.align ?? 'left' }}
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
>
{col.render(row)}
</td>
))}
</tr>
))
visibleData.map((row) => {
const rowProps = getRowProps?.(row);
const mergedClassName = [
styles.tr,
onRowClick ? styles.clickable : '',
rowProps?.className ?? '',
]
.filter(Boolean)
.join(' ');
const handleClick = (event: MouseEvent<HTMLTableRowElement>) => {
rowProps?.onClick?.(event);
if (!event.defaultPrevented) {
onRowClick?.(row);
}
};
return (
<tr
key={rowKey(row)}
{...rowProps}
className={mergedClassName}
onClick={onRowClick || rowProps?.onClick ? handleClick : undefined}
>
{columns.map((col) => (
<td
key={col.key}
className={styles.td}
style={{ textAlign: col.align ?? 'left' }}
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
>
{col.render(row)}
</td>
))}
</tr>
);
})
)}
</tbody>
</table>
+4 -2
View File
@@ -1,8 +1,10 @@
import React, { useId } from 'react';
import styles from './Textarea.module.css';
export interface TextareaProps
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'id'> {
export interface TextareaProps extends Omit<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
'id'
> {
label?: string;
hint?: string;
error?: string;
@@ -0,0 +1,87 @@
.viewport {
position: fixed;
top: var(--space-4);
right: var(--space-4);
z-index: 2000;
display: flex;
flex-direction: column;
gap: var(--space-2);
width: min(380px, calc(100vw - (var(--space-4) * 2)));
pointer-events: none;
}
.toast {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-3);
padding: var(--space-3) var(--space-3);
border-radius: var(--radius-md);
border: var(--border-width) solid var(--color-border);
background: var(--color-bg-subtle);
box-shadow: var(--shadow-md);
pointer-events: auto;
opacity: 1;
transform: translateX(0) scale(1);
transition: opacity 100ms ease, transform 100ms ease;
}
.leaving {
opacity: 0;
transform: translateX(8px) scale(0.98);
pointer-events: none;
}
.content {
display: flex;
align-items: flex-start;
gap: var(--space-2);
min-width: 0;
}
.icon {
margin-top: 1px;
flex-shrink: 0;
}
.message {
margin: 0;
font-size: var(--font-size-sm);
line-height: 1.4;
color: var(--color-text);
overflow-wrap: anywhere;
}
.close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: none;
background: transparent;
border-radius: var(--radius-sm);
color: var(--color-text-muted);
cursor: pointer;
flex-shrink: 0;
}
.close:hover {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
.success {
border-color: color-mix(in srgb, var(--color-primary) 50%, var(--color-border));
background: var(--color-success-bg);
}
.error {
border-color: color-mix(in srgb, var(--color-danger) 50%, var(--color-border));
background: var(--color-error-bg);
}
.info {
border-color: color-mix(in srgb, var(--color-secondary-fg) 35%, var(--color-border));
background: var(--color-info-bg);
}
+113
View File
@@ -0,0 +1,113 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import styles from './ToastProvider.module.css';
import { subscribeApiErrorToasts } from '../../lib/toast-events';
type ToastVariant = 'success' | 'error' | 'info';
interface ToastItem {
id: number;
message: string;
variant: ToastVariant;
closing: boolean;
}
interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
const ToastContext = createContext<ToastApi | null>(null);
const ICONS: Record<ToastVariant, React.ReactNode> = {
success: <CheckCircle2 size={16} />,
error: <AlertCircle size={16} />,
info: <Info size={16} />,
};
export interface ToastProviderProps {
children: React.ReactNode;
durationMs?: number;
}
export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProps) {
const EXIT_ANIMATION_MS = 100;
const [items, setItems] = useState<ToastItem[]>([]);
const lastShownAtRef = useRef<Map<string, number>>(new Map());
const remove = useCallback((id: number) => {
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
const dismiss = useCallback((id: number) => {
setItems((prev) =>
prev.map((item) =>
item.id === id ? { ...item, closing: true } : item,
),
);
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
}, [remove]);
const show = useCallback((message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
}, [dismiss, durationMs]);
const api = useMemo<ToastApi>(() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}), [show]);
useEffect(() => {
return subscribeApiErrorToasts((message) => api.error(message));
}, [api]);
return (
<ToastContext.Provider value={api}>
{children}
<div className={styles.viewport} aria-live="polite" aria-atomic="true">
{items.map((item) => (
<div
key={item.id}
className={[styles.toast, styles[item.variant], item.closing ? styles.leaving : '']
.filter(Boolean)
.join(' ')}
role="status"
>
<div className={styles.content}>
<span className={styles.icon} aria-hidden="true">{ICONS[item.variant]}</span>
<p className={styles.message}>{item.message}</p>
</div>
<button
type="button"
className={styles.close}
aria-label="Dismiss notification"
onClick={() => dismiss(item.id)}
>
<X size={14} />
</button>
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+18
View File
@@ -27,12 +27,27 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { ToastProvider, useToast } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
export { Timestamp } from './Timestamp/Timestamp';
export type { TimestampProps } from './Timestamp/Timestamp';
export { Pagination } from './Pagination/Pagination';
export type { PaginationProps } from './Pagination/Pagination';
export { Search } from './Search/Search';
export type { SearchProps } from './Search/Search';
export { CodeBlock } from './CodeBlock/CodeBlock';
export type { CodeBlockProps } from './CodeBlock/CodeBlock';
export { CodeEditor } from './CodeEditor/CodeEditor';
export type { CodeEditorProps } from './CodeEditor/CodeEditor';
export { MarkdownContent } from './MarkdownContent/MarkdownContent';
export type { MarkdownContentProps } from './MarkdownContent/MarkdownContent';
export { ContextMenu } from './ContextMenu/ContextMenu';
export type { ContextMenuProps, ContextMenuItem } from './ContextMenu/ContextMenu';
@@ -42,6 +57,9 @@ export type { DescriptionListProps, DescriptionListItem } from './DescriptionLis
export { Notification } from './Notification/Notification';
export type { NotificationProps, NotificationVariant } from './Notification/Notification';
export { Modal } from './Modal/Modal';
export type { ModalProps } from './Modal/Modal';
export { Table } from './Table/Table';
export type { TableProps, TableColumn } from './Table/Table';
+2 -1
View File
@@ -74,7 +74,8 @@
--border-width: 1.5px;
/* Shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.06);
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.08), 0 0px 1px rgba(0, 0, 0, 0.04);
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.06);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -1px rgba(0, 0, 0, 0.04);
/* Transitions */
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/App.tsx","./src/main.tsx"],"version":"5.8.3"}
{"root":["./src/App.tsx","./src/declarations.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/index.ts","./src/api/types.ts","./src/hooks/useTheme.ts","./src/i18n/index.ts","./src/lib/hljs.ts","./src/lib/toast-events.ts","./src/pages/credential/CreateCredentialPage.tsx","./src/pages/credential/CredentialDetailPage.tsx","./src/pages/credential/CredentialsPage.tsx","./src/pages/credential/EditCredentialPage.tsx","./src/pages/environment/CreateEnvironmentPage.tsx","./src/pages/environment/EditEnvironmentPage.tsx","./src/pages/environment/EnvironmentDetailPage.tsx","./src/pages/environment/EnvironmentsPage.tsx","./src/pages/run/AllRunsPage.tsx","./src/pages/run/RunDetailPage.tsx","./src/pages/run/RunsPage.tsx","./src/pages/scenario/CreateScenarioPage.tsx","./src/pages/scenario/CreateStepPage.tsx","./src/pages/scenario/EditScenarioPage.tsx","./src/pages/scenario/EditStepPage.tsx","./src/pages/scenario/ScenarioDetailPage.tsx","./src/pages/scenario/ScenariosPage.tsx","./src/pages/session/SessionDetailPage.tsx","./src/pages/session/SessionsPage.tsx","./src/pages/snippet/CreateSnippetPage.tsx","./src/pages/snippet/EditSnippetPage.tsx","./src/pages/snippet/SnippetDetailPage.tsx","./src/pages/snippet/SnippetsPage.tsx","./src/ui/index.ts","./src/ui/AutoRefreshIndicator/AutoRefreshIndicator.tsx","./src/ui/Badge/Badge.tsx","./src/ui/Breadcrumbs/Breadcrumbs.tsx","./src/ui/Button/Button.tsx","./src/ui/Card/Card.tsx","./src/ui/CodeBlock/CodeBlock.tsx","./src/ui/CodeEditor/CodeEditor.tsx","./src/ui/ContextMenu/ContextMenu.tsx","./src/ui/DescriptionList/DescriptionList.tsx","./src/ui/Input/Input.tsx","./src/ui/MarkdownContent/MarkdownContent.tsx","./src/ui/Modal/Modal.tsx","./src/ui/Notification/Notification.tsx","./src/ui/Pagination/Pagination.tsx","./src/ui/Search/Search.tsx","./src/ui/Select/Select.tsx","./src/ui/SidePanel/SidePanel.tsx","./src/ui/Table/Table.tsx","./src/ui/Textarea/Textarea.tsx","./src/ui/ThemeSwitcher/ThemeSwitcher.tsx","./src/ui/Timestamp/Timestamp.tsx","./src/ui/Toast/ToastProvider.tsx","./src/ui/UuidBadge/UuidBadge.tsx"],"version":"5.8.3"}
+81 -8
View File
@@ -1,23 +1,96 @@
/// <reference types="vitest/config" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import { playwright } from '@vitest/browser-playwright';
const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
const rootPackageJsonPath = path.resolve(dirname, '../package.json');
const APP_VERSION = (() => {
try {
const json = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf8')) as {
version?: string;
};
return json.version ?? 'dev';
} catch {
return 'dev';
}
})();
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify(APP_VERSION),
},
plugins: [react()],
server: {
proxy: {
'/environments': 'http://localhost:13000',
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': 'http://localhost:13000',
'/sessions': 'http://localhost:13000',
'/scenarios': 'http://localhost:13000',
'/keys': 'http://localhost:13000',
'/login': 'http://localhost:13000',
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (!id.includes('/client/src/') && !id.includes('/node_modules/')) {
return;
}
if (id.includes('/node_modules/lucide-react')) {
return 'icons';
}
if (id.includes('/node_modules/monaco-editor') || id.includes('/node_modules/@monaco-editor')) {
return 'editor';
}
if (
id.includes('/node_modules/react-markdown')
|| id.includes('/node_modules/remark-')
|| id.includes('/node_modules/rehype-')
|| id.includes('/node_modules/unified')
|| id.includes('/node_modules/micromark')
|| id.includes('/node_modules/mdast-')
|| id.includes('/node_modules/hast-')
|| id.includes('/node_modules/unist-')
|| id.includes('/node_modules/vfile')
) {
return 'markdown';
}
if (
id.includes('/node_modules/i18next')
|| id.includes('/node_modules/react-i18next')
) {
return 'i18n';
}
if (id.includes('/node_modules/moment')) {
return 'datetime';
}
if (id.includes('/node_modules/yaml')) {
return 'yaml';
}
if (id.includes('/node_modules/')) {
return 'vendor';
}
if (id.includes('/src/pages/environment/')) {
return 'environments';
}
if (id.includes('/src/pages/scenario/')) {
return 'scenarios';
}
if (id.includes('/src/pages/run/')) {
return 'runs';
}
if (id.includes('/src/pages/snippet/')) {
return 'snippets';
}
if (id.includes('/src/pages/credential/')) {
return 'credentials';
}
if (id.includes('/src/pages/session/')) {
return 'sessions';
}
if (id.includes('/src/api/')) {
return 'api';
}
},
},
},
},
test: {
+2 -2
View File
@@ -1,8 +1,8 @@
services:
server:
build:
context: ./server
dockerfile: Dockerfile
context: .
dockerfile: server/Dockerfile
ports:
- "13000:3000"
env_file:
+35 -35
View File
@@ -1,45 +1,43 @@
# Architecture
```
┌─────────────────────────────────────────┐
│ Browser (React SPA — client/) │
│ │
│ EnvironmentsPage KeysPage │
│ SessionsPage ScenariosPage │
└───────────────────┬─────────────────────┘
│ HTTP REST (:13000)
│
┌──────────────────────────────────────────────────────┐
│ Browser (React SPA - client/) │
│ │
│ Environments Credentials Snippets │
│ Sessions Scenarios Runs │
└─────────────────────────────┬────────────────────────┘
│ HTTP REST (:13000)
│
MCP client (AI agent / VS Code Copilot)
│ HTTP /mcp (Streamable MCP)
│ HTTP /mcp (Streamable MCP)
▼
┌──────────────────────────────────────┐
│ NestJS app (server/src/) │
│ │
│ McpService ← all MCP tools │
│ │
│ AuthService login + sessions │
│ SessionService session CRUD │
│ EnvironmentService environment CRUD │
│ BrowserService ad-hoc browsing │
│ CodeExecutorService sandboxed JS │
│ │
│ ScenarioService scenario CRUD │
│ ScenarioSchedulerService │
│ └─ @Interval(1 s) tick loop │
└──────────────────┬───────────────────┘
│ better-sqlite3 (TypeORM)
▼
data/sessions.db
┌──────────────────────────────────────────────────────┐
│ NestJS app (server/src/) │
│ │
│ McpService all MCP tools │
│ SessionService session persistence │
│ SessionContextService live browser contexts │
│ EnvironmentService environment CRUD + import │
│ CredentialService credential CRUD + import │
│ SnippetService snippet CRUD + import │
│ BrowserService ad-hoc open/exec │
│ CodeExecutorService sandboxed JS runtime │
│ ScenarioService scenarios/steps/runs CRUD │
│ ScenarioSchedulerService @Interval(1 s) run worker │
└───────────────────────┬──────────────────────────────┘
│ better-sqlite3 (TypeORM)
▼
data/sessions.db
```
- **McpService** — registers every MCP tool and delegates to domain services.
- **AuthService** — drives a Playwright browser to log in via a key descriptor; saves cookies + localStorage as a `Session`.
- **SessionService** — stores and retrieves saved browser sessions.
- **EnvironmentService** — stores named environments (URL maps) used by auth and scenarios.
- **BrowserService** — ad-hoc, stateless `open_url` / `exec_code` operations outside the scenario scheduler.
- **CodeExecutorService** — compiles and runs user-supplied Playwright JS inside a sandboxed `async` function with `page`, `context`, and `helpers` in scope.
- **ScenarioService** — CRUD for scenarios, steps, runs, and run logs; import/export.
- **ScenarioSchedulerService** — polls for pending step runs every second and executes them. All steps in the same run share **one browser instance** (see [scenario.md](scenario.md)).
- **McpService** registers MCP tools and delegates to session, environment, browser, and scenario services.
- **SessionService** persists session records in SQLite. **SessionContextService** manages live Playwright contexts for open sessions.
- **EnvironmentService**, **CredentialService**, and **SnippetService** provide CRUD plus import/export upserts.
- **BrowserService** handles stateless ad-hoc automation (`/open`, `/exec`) and session-aware browsing.
- **CodeExecutorService** validates and executes user JS with `page`, `context`, and helper APIs.
- **ScenarioService** manages scenarios, steps, credential aliases, runs, logs, and scenario import/export.
- **ScenarioSchedulerService** polls pending runs every second and executes step runs to completion.
## Client (`client/`)
@@ -47,4 +45,6 @@ A React 19 + TypeScript SPA served separately by Vite during development. In Doc
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses HashRouter so the Vite proxy and server-side routes are never ambiguous.
The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
See [development.md](development.md) for the full client tech stack and directory layout.
+20 -8
View File
@@ -26,8 +26,10 @@ Copy `.env.example` to `.env` and fill in the required values before running.
| Variable | Default | Description |
|---|---|---|
| `PORT` | `3000` | HTTP port |
| `KEYS_DIR` | `keys` | Directory containing `*.json` key descriptors |
| `KEYS_DIR` | `keys` | Directory for key material used by credential/snippet workflows |
| `DB_PATH` | `data/sessions.db` | SQLite database file |
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to Chromium binary. Set automatically in Docker (`/usr/bin/chromium`). |
---
@@ -59,7 +61,13 @@ The server listens on port **3000** by default.
npm -w client run dev
```
The Vite dev server runs on **http://localhost:5173** and proxies all API paths (`/environments`, `/sessions`, `/scenarios`, `/keys`, `/login`, `/mcp`) to the server at `localhost:3000`.
The Vite dev server runs on **http://localhost:5173** and proxies these API prefixes to `localhost:13000` (or `localhost:3000` when running server locally):
- `/environments`
- `/credentials`
- `/snippets`
- `/sessions`
- `/scenarios`
**Production build**:
@@ -201,7 +209,7 @@ docker compose logs -f
## Client overview
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, sessions, keys, and scenarios.
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, credentials, snippets, sessions, scenarios, and runs.
### Tech stack
@@ -221,11 +229,11 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
```
client/
src/
api/ API client modules (environments, keys, sessions, scenarios)
api/ API client modules (environments, credentials, snippets, sessions, scenarios)
hooks/ useTheme (light/dark persistence)
i18n/ i18next bootstrap + locales/en.json
pages/ EnvironmentsPage, KeysPage, SessionsPage, ScenariosPage
ui/ Reusable component library
pages/ Environment/Credential/Snippet/Session/Scenario/Run pages
ui/ Reusable component library
Badge, Breadcrumbs, Button, Card, Input, Select,
SidePanel, Table, ThemeSwitcher, Timestamp
.storybook/
@@ -239,10 +247,14 @@ Hash-based routing (`/#/path`) avoids conflicts with the Vite dev-server proxy.
| Route | Page |
|---|---|
| `/#/environments` | Environment list |
| `/#/keys` | Key list |
| `/#/credentials` | Credential list |
| `/#/snippets` | Snippet list |
| `/#/sessions` | Session list |
| `/#/scenarios` | Scenario list |
| `/#/runs` | Cross-scenario runs list |
### Theming
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar header. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar footer. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
The sidebar footer also shows the app version read from the workspace root `package.json` and injected via Vite `define`.
-20
View File
@@ -1,20 +0,0 @@
# Key descriptors
Each file in `KEYS_DIR` is named `<keyId>.json` and takes one of two forms:
**File key (EDS):**
```json
{
"keyFile": "path/to/key.dat",
"password": "secret"
}
```
`keyFile` is resolved relative to `KEYS_DIR`.
**Login + password:**
```json
{
"login": "user@example.com",
"password": "secret"
}
```
+35 -28
View File
@@ -1,49 +1,56 @@
# MCP tools
## Auth / session
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport).
The server currently registers the following tools.
## Sessions
| Tool | Description |
|---|---|
| `list_keys` | List available key IDs from `KEYS_DIR` |
| `login` | Log in with a key against an environment; stores resulting session |
| `list_sessions` | Paginated list of saved sessions |
| `delete_session` | Delete a session by ID |
| `list_sessions` | List stored sessions (paginated) |
| `delete_session` | Delete a session by UUID |
## Environments
| Tool | Description |
|---|---|
| `list_environments` | Paginated list of environments |
| `get_environment` | Get one environment by ID |
| `create_environment` | Create an environment (`name` + `urls` map) |
| `update_environment` | Update name / urls |
| `delete_environment` | Delete by ID |
| `list_environments` | List environments (paginated) |
| `get_environment` | Get one environment by UUID |
| `create_environment` | Create environment (`name`, `urls`) |
| `update_environment` | Update environment (`id`, optional `name`/`urls`) |
| `delete_environment` | Delete environment by UUID |
`urls` is a free-form map. Recognised keys: `id_url` (auth server), `cabinet_url` (cabinet redirect target), `admin_url`.
`urls` is a free-form key/value map. Common keys: `id_url`, `cabinet_url`, `admin_url`.
## Browser (ad-hoc, stateless)
## Browser (ad-hoc)
| Tool | Description |
|---|---|
| `open_url` | Navigate to a URL and return page content / reader-mode text |
| `exec_code` | Run Playwright JS in a session's browser context |
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
| `exec_code` | Execute Playwright JS with `page` and `context` in scope |
## Scenarios
| Tool | Description |
|---|---|
| `list_scenarios` | Paginated list |
| `get_scenario` | Fetch scenario with all steps |
| `create_scenario` | Create a new scenario by name |
| `update_scenario` | Rename |
| `delete_scenario` | Delete (cascades to steps and runs) |
| `create_scenario_step` | Add a step |
| `get_scenario_step` | Fetch one step |
| `list_scenarios` | List scenarios (paginated) |
| `get_scenario` | Get scenario with steps |
| `create_scenario` | Create scenario by `name` |
| `update_scenario` | Rename scenario |
| `delete_scenario` | Delete scenario |
| `create_scenario_step` | Add step to scenario |
| `get_scenario_step` | Get one step |
| `update_scenario_step` | Update step fields |
| `delete_scenario_step` | Remove a step |
| `list_scenario_runs` | Paginated run history (with optional status filter) |
| `run_scenario` | Trigger an immediate run |
| `get_scenario_run` | Get a run with all step runs and their outputs |
| `wait_for_scenario_run` | Block until run reaches `pass`/`fail`, return full run |
| `export_scenario` | Export scenario as a portable JSON payload |
| `import_scenario` | Import a scenario from an export payload |
| `delete_scenario_step` | Delete step |
| `list_scenario_runs` | List runs for a scenario |
| `run_scenario` | Trigger run for scenario |
| `get_scenario_run` | Get run with step runs and logs |
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
| `export_scenario` | Export scenario payload |
| `import_scenario` | Import scenario payload |
## Notes
- Tool IDs and entity IDs are UUIDs.
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
+60 -58
View File
@@ -1,80 +1,82 @@
# Scenario execution
When a scenario is run, the scheduler creates a `ScenarioRun` with one `ScenarioRunStep` per step. Steps are executed **in order** (by `step.order`), one per scheduler tick.
When a scenario run is created, the server creates one `ScenarioRunStep` per scenario step.
**All steps in the same run share a single Playwright browser instance.** The browser is created on the first `exec` or `sign` step (using session cookies + localStorage), reused for every subsequent step, and closed when the run finishes (pass or fail).
- Step runs are ordered by `step.order`.
- First step run starts as `pending`; the rest start as `waiting`.
- Scheduler tick (`@Interval(1000)`) picks pending runs and processes steps in order.
- Steps in the same run share one Playwright browser/context/page.
## Step types
## Execution model
### `login`
Current scheduler behavior is exec-centric:
Authenticates in a **separate, ephemeral browser** and saves the resulting session to the database. Subsequent exec/sign steps load that session into the shared browser.
- `execCode` is required for a step to pass.
- `validateCode` is optional and runs after `execCode`.
- Legacy step type metadata may still appear in MCP payloads, but run execution is not branched by step type.
`execCode` must be a JSON object:
```json
{ "keyId": "3137411915", "environmentName": "liquio-diia-stg" }
```
## Script runtime
### `exec`
`execCode` and `validateCode` execute as async JavaScript with:
Runs arbitrary Playwright JS on the **shared page**. The page carries over state from the previous step (URL, form inputs, cookies, etc.).
- `page`: Playwright `Page`
- `context`: Playwright `BrowserContext`
- `helpers`: utility object
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
`execCode` is executed as the body of an `async` function with these variables in scope:
`validateCode` additionally receives `result`, which is the value returned by `execCode`.
- `page` — current Playwright `Page`
- `context` — current Playwright `BrowserContext`
- `helpers.dumpDom(selector?)` — returns a simplified DOM string
- `helpers.getStepOutput(order)` — returns the JSON-parsed `output` of a previous step. Positive values are absolute step orders; negative values are relative to the current step (`-1` = previous step).
## Available helpers
Any value returned from `execCode` is JSON-serialised and stored as the `output` field on the `ScenarioRunStep` record. Subsequent steps can read it via `helpers.getStepOutput()`.
- `helpers.dumpDom(selector?)`: simplified DOM snapshot
- `helpers.log(...args)`, `helpers.warn(...args)`, `helpers.error(...args)`: structured step logs
- `helpers.getStepOutput(order)`: prior step output by absolute order (`0`, `1`, ...) or relative (`-1` previous step)
- `helpers.getCredential(alias)`: credential payload assigned to the scenario alias
- `helpers.env`: shallow copy of environment URL map
- `helpers.getEnvUrl(key)`: required environment URL lookup (throws if missing)
- `helpers.runSnippet(name, ...args)`: execute stored snippet code in the same page/context/helpers scope
## Validation contract
`validateCode` may return:
```js
// example execCode
await page.goto('https://cabinet.example.com/tasks/create/987825');
await page.locator('input[name="institution"]').fill('caltech');
await page.locator('button:has-text("Далі")').click();
await page.waitForLoadState('networkidle');
return page.url(); // stored in ScenarioRunStep.output
```
### `sign`
Performs EDS signing on the **current shared page** using a key from `KEYS_DIR`. The step clicks the sign widget, selects the file key method, uploads the key file, enters the password, and submits — all without requiring the step author to handle key material in their code.
`execCode` must be a JSON object:
```json
{ "keyId": "3137411915" }
```
## Validation code
Any step type optionally accepts `validateCode` — Playwright JS that runs on the shared page **after** the main action and must return a result evaluated as:
```js
return { success: true, description: 'Application created' };
return { success: true, description: 'ok' };
// or
return { success: false, description: 'Expected success banner not found' };
// or simply
return someBoolean;
return false;
```
If `success` is false the step (and the whole run) fails with the provided `description`.
Interpretation:
## Run statuses
- Boolean: `true` = pass, `false` = fail
- Object: `success` controls pass/fail; `description` is persisted as step description
`pending` → `in_progress` → `pass` | `fail`
On validation failure, the step fails and the run is marked `fail`.
Individual step runs also expose `waiting` (not yet reached) and `cancelled` (run failed before this step).
## Statuses
## Adding a new scenario (example workflow)
Run status:
```
1. create_environment (if not already present)
2. create_scenario → get scenarioId
3. create_scenario_step type=login, order=0
4. create_scenario_step type=exec, order=1 (navigate + fill form)
5. create_scenario_step type=sign, order=2
6. create_scenario_step type=exec, order=3 (validateCode checks success banner)
7. run_scenario → get runId
8. wait_for_scenario_run (blocks until pass/fail, returns full run with outputs)
```
- `pending`
- `in_progress`
- `pass`
- `fail`
Run-step status:
- `waiting`
- `pending`
- `in_progress`
- `pass`
- `fail`
- `cancelled`
## Example workflow
1. Create environment
2. Create credentials and snippets (optional but common)
3. Create scenario
4. Add ordered steps (`execCode`, optional `validateCode`)
5. Assign credentials to scenario aliases when needed
6. Run scenario
7. Wait for run completion and inspect run logs/outputs
+1540 -9
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.4.0",
"version": "1.5.0",
"private": true,
"workspaces": [
"server",
+9 -6
View File
@@ -4,11 +4,13 @@ FROM node:22-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY server/package.json ./server/
RUN npm ci -w server
COPY nest-cli.json tsconfig*.json ./
COPY src ./src
RUN npm run build
COPY server/nest-cli.json ./server/
COPY server/tsconfig*.json ./server/
COPY server/src ./server/src
RUN npm run -w server build
# ── Runtime stage ─────────────────────────────────────────────────────────────
FROM node:22-slim AS runtime
@@ -27,9 +29,10 @@ ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server/package.json ./server/
RUN npm ci --omit=dev -w server
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/server/dist ./dist
# Runtime directories (keys and SQLite DB mounted via volumes)
RUN mkdir -p data keys
-11239
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -27,6 +27,7 @@
"@nestjs/schedule": "^6.1.1",
"@nestjs/swagger": "^11.2.6",
"@nestjs/typeorm": "^11.0.1",
"@playwright/test": "^1.59.1",
"acorn": "^8.16.0",
"better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1",
@@ -37,6 +38,7 @@
"rxjs": "^7.8.2",
"swagger-ui-express": "^5.0.1",
"typeorm": "^0.3.28",
"yaml": "^2.8.3",
"zod": "^4.3.6"
},
"devDependencies": {
-2
View File
@@ -4,7 +4,6 @@ import { AppConfig, validateAppConfig } from "./config/app.config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScheduleModule } from "@nestjs/schedule";
import { HealthModule } from "./health/health.module";
import { AuthModule } from "./auth/auth.module";
import { BrowserModule } from "./browser/browser.module";
import { SessionEntity } from "./session/session.entity";
import { EnvironmentEntity } from "./environment/environment.entity";
@@ -50,7 +49,6 @@ import { SnippetModule } from "./snippet/snippet.module";
synchronize: true,
}),
}),
AuthModule,
BrowserModule,
EnvironmentModule,
CredentialModule,
-51
View File
@@ -1,51 +0,0 @@
import { Body, Controller, Get, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { AuthService } from "./auth.service";
import { LoginDto } from "./dto/login.dto";
@ApiTags("auth")
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get("keys")
@ApiOperation({
summary: "List available key identifiers from the keys directory",
})
@ApiResponse({
status: 200,
description: "List of key names",
schema: {
properties: { keys: { type: "array", items: { type: "string" } } },
},
})
listKeys(): { keys: string[] } {
return { keys: this.authService.listKeys() };
}
@Post("login")
@ApiOperation({
summary: "Log in using a file key and return the session token",
})
@ApiResponse({
status: 201,
description: "Login successful",
schema: {
properties: {
token: { type: "string" },
sessionName: { type: "string" },
},
},
})
@ApiResponse({ status: 400, description: "Key not found or invalid" })
@ApiResponse({ status: 500, description: "Automation failed" })
login(
@Body() dto: LoginDto,
): Promise<{ token: string; sessionName: string }> {
return this.authService.login(
dto.key,
dto.environmentName,
dto.sessionName,
);
}
}
-13
View File
@@ -1,13 +0,0 @@
import { Module } from "@nestjs/common";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
@Module({
imports: [SessionModule, EnvironmentModule],
controllers: [AuthController],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}
-265
View File
@@ -1,265 +0,0 @@
import {
Injectable,
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "../config/app.config";
import { chromium } from "playwright";
import type { Page } from "playwright";
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import { SessionService } from "../session/session.service";
import { SessionContextService } from "../session/session-context.service";
import { EnvironmentService } from "../environment/environment.service";
interface KeyDescriptor {
keyFile?: string;
login?: string;
password: string;
}
@Injectable()
export class AuthService {
private readonly logger = new TraceLogger(AuthService.name);
private readonly keysDir: string;
constructor(
private readonly config: ConfigService<AppConfig, true>,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly environmentService: EnvironmentService,
) {
this.keysDir = path.resolve(this.config.get("KEYS_DIR"));
}
listKeys(): string[] {
if (!fs.existsSync(this.keysDir)) return [];
return fs
.readdirSync(this.keysDir)
.filter((f) => f.endsWith(".json"))
.map((f) => path.basename(f, ".json"));
}
private loadKeyDescriptor(keyId: string): KeyDescriptor {
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
if (!fs.existsSync(keyJsonPath)) {
throw new BadRequestException(`Key not found: ${keyId}`);
}
try {
return JSON.parse(fs.readFileSync(keyJsonPath, "utf-8")) as KeyDescriptor;
} catch (err) {
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, {
cause: err,
});
}
}
async login(
keyId: string,
environmentName: string,
sessionName?: string,
): Promise<{ token: string; sessionName: string }> {
const resolvedSession = sessionName ?? crypto.randomUUID();
const env = await this.environmentService
.findAll()
.then(({ data }) => data.find((e) => e.name === environmentName));
if (!env)
throw new NotFoundException(`Environment "${environmentName}" not found`);
const loginUrl = env.urls.id_url;
const cabinetUrl = env.urls.cabinet_url;
if (!loginUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing id_url`,
);
if (!cabinetUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing cabinet_url`,
);
const descriptor = this.loadKeyDescriptor(keyId);
const useLoginPassword = !!descriptor.login;
if (!useLoginPassword) {
if (!descriptor.keyFile) {
throw new BadRequestException(
`Key descriptor for "${keyId}" must have either "login" or "keyFile"`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
}
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
this.logger.log(`Navigating to ${loginUrl}`);
await page.goto(loginUrl, { waitUntil: "networkidle" });
if (useLoginPassword) {
// Click "Логін і пароль" auth method
await page.locator('p[aria-label="Логін і пароль"]').click();
// Fill login and password
await page.getByLabel("Електронна пошта").fill(descriptor.login!);
await page.getByLabel("Пароль").fill(descriptor.password);
// Click "Увійти"
await page.locator('button:has-text("Увійти")').click();
} else {
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile!);
// Click "Файловий ключ" button
await page.getByText("Файловий ключ").click();
// Upload key file via hidden file input
const fileInput = page.locator(
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
);
await fileInput.setInputFiles(keyFilePath);
// Enter password
await page
.locator("#id-app-login-file-key-password")
.fill(descriptor.password);
// Click "Продовжити"
await page.locator("#id-app-login-file-key-sign-button").click();
}
// Wait until redirected to cabinet
this.logger.log(`Waiting for redirect to ${cabinetUrl}`);
await page.waitForURL(cabinetUrl, { timeout: 30000 });
// Extract token from localStorage
const token = await page.evaluate(() => localStorage.getItem("token"));
if (!token) {
throw new InternalServerErrorException(
"Login succeeded but token was not found in localStorage",
);
}
// Capture all cookies and localStorage from the browser context
const cookies = await context.cookies();
const localStorageData = await page.evaluate(() => {
const entries: Record<string, string> = {};
for (let i = 0; i < window.localStorage.length; i++) {
const k = window.localStorage.key(i);
if (k !== null) entries[k] = window.localStorage.getItem(k) ?? "";
}
return entries;
});
await this.sessionService.upsert(
resolvedSession,
token,
cookies,
localStorageData,
);
// Register the live Playwright context — browser stays open for reuse
this.sessionContextService.register(
resolvedSession,
browser,
context,
page,
);
this.logger.log(
`Login successful for key ${keyId}, session: ${resolvedSession}`,
);
return { token, sessionName: resolvedSession };
} catch (err) {
// Close browser only on failure — on success it is kept alive in SessionContextService
await browser.close().catch(() => {});
if (
err instanceof BadRequestException ||
err instanceof InternalServerErrorException
) {
throw err;
}
this.logger.error(`Login failed: ${(err as Error).message}`);
throw new InternalServerErrorException(
`Login automation failed: ${(err as Error).message}`,
{ cause: err },
);
}
}
async signWithKey(keyId: string, page: Page): Promise<void> {
const descriptor = this.loadKeyDescriptor(keyId);
if (!descriptor.keyFile) {
throw new BadRequestException(
`Key descriptor for "${keyId}" must have "keyFile" to sign`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
this.logger.log(`Signing with key ${keyId} on page: ${page.url()}`);
// Open the EDS sign widget (skip if it's already open)
const isSignDialogOpen = await page
.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]')
.isVisible()
.catch(() => false);
if (!isSignDialogOpen) {
await page
.locator("button")
.filter({ hasText: /підпис|sign/i })
.first()
.click();
await page.waitForTimeout(500);
}
// Select the file key tab inside the widget
await page
.locator('button, [role="tab"], li')
.filter({ hasText: /файлов|file key/i })
.first()
.click();
await page.waitForTimeout(300);
// Upload the key file
const fileInput = page.locator(
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
);
await fileInput.setInputFiles(keyFilePath);
await page.waitForTimeout(300);
// Enter password
await page.locator('input[type="password"]').fill(descriptor.password);
await page.waitForTimeout(200);
// Submit
await page
.locator("button")
.filter({ hasText: /підпис|sign|підтвер/i })
.last()
.click();
await page.waitForLoadState("networkidle");
this.logger.log(`Sign completed for key ${keyId}`);
}
}
-30
View File
@@ -1,30 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class LoginDto {
@ApiProperty({
description:
"Key identifier — filename (without extension) from the keys/ directory",
example: "3273334361",
})
@IsString()
@IsNotEmpty()
key: string;
@ApiProperty({
description: "Environment name to resolve login/cabinet URLs from",
example: "liquio-diia-stg",
})
@IsString()
@IsNotEmpty()
environmentName: string;
@ApiPropertyOptional({
description:
"Session name to store credentials under. Auto-generated UUID if omitted.",
example: "my-test-session",
})
@IsOptional()
@IsString()
sessionName?: string;
}
+49 -3
View File
@@ -9,8 +9,10 @@ import type { BrowserContext } from "playwright";
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import type { ExecResult } from "../code-executor/code-executor.service";
import type { Cookie } from "playwright";
export type { ExecResult } from "../code-executor/code-executor.service";
@@ -26,9 +28,54 @@ export class BrowserService {
constructor(
private readonly sessionContextService: SessionContextService,
private readonly sessionService: SessionService,
private readonly codeExecutor: CodeExecutorService,
) {}
private parseCookies(raw: string | null | undefined): Cookie[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as unknown;
return Array.isArray(parsed) ? (parsed as Cookie[]) : [];
} catch {
return [];
}
}
private async getOrCreateNamedHandle(sessionName: string) {
try {
return await this.sessionContextService.getHandle(sessionName);
} catch {
this.logger.log(
`[${sessionName}] creating session context automatically`,
);
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext();
const page = await context.newPage();
const existing = await this.sessionService.findBySessionName(sessionName);
const cookies = this.parseCookies(existing?.cookies);
if (cookies.length > 0) {
await context.addCookies(cookies);
}
this.sessionContextService.register(sessionName, browser, context, page);
await this.sessionService.upsert(
sessionName,
existing?.token ?? `auto:${sessionName}`,
await context.cookies(),
{},
);
return { browser, context, page };
}
}
private rethrow(err: unknown, label: string, operation: string): never {
if (err instanceof HttpException) {
throw err;
@@ -90,8 +137,7 @@ export class BrowserService {
this.logger.log(`[${label}] open: ${url}`);
if (sessionName) {
const { context } =
await this.sessionContextService.getHandle(sessionName);
const { context } = await this.getOrCreateNamedHandle(sessionName);
try {
return await this.extractContent(context, url, readerMode, selector);
} catch (err) {
@@ -123,7 +169,7 @@ export class BrowserService {
if (sessionName) {
const { page, context } =
await this.sessionContextService.getHandle(sessionName);
await this.getOrCreateNamedHandle(sessionName);
this.logger.log(`[${label}] exec: using persistent context`);
try {
if (url) {
+1 -1
View File
@@ -4,7 +4,7 @@ import { IsOptional, IsString, IsUrl } from "class-validator";
export class ExecDto {
@ApiPropertyOptional({
description:
"Session name previously created by POST /login. If omitted, executes without a stored session.",
"Optional named browser session. If it does not exist yet, it is created automatically.",
example: "test-session-1",
})
@IsOptional()
+1 -1
View File
@@ -4,7 +4,7 @@ import { IsBoolean, IsOptional, IsString, IsUrl } from "class-validator";
export class OpenDto {
@ApiPropertyOptional({
description:
"Session name previously created by POST /login. If omitted, opens the URL without a stored session.",
"Optional named browser session. If it does not exist yet, it is created automatically.",
example: "test-session-1",
})
@IsOptional()
@@ -6,8 +6,9 @@ import {
import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { expect as playwrightExpect } from "@playwright/test";
import { dumpDom } from "./dom-helpers";
import type { EnvironmentUrls } from "../environment/environment.entity";
import type { EnvironmentData } from "../environment/environment.entity";
export interface ExecResult {
result: unknown;
@@ -49,7 +50,7 @@ export class CodeExecutorService {
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentUrls | null,
environment?: EnvironmentData | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
@@ -61,11 +62,11 @@ export class CodeExecutorService {
.join(" ");
const credMap: Record<string, unknown> = credentials ?? {};
const envUrls: EnvironmentUrls = environment ?? {};
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
// eslint-disable-next-line prefer-const
let pageHelpers: Record<string, unknown>;
const fakeConsole = {
@@ -91,28 +92,31 @@ export class CodeExecutorService {
}
return credMap[alias];
},
/** All URLs defined for the current environment (may be empty if no environment is set). */
env: { ...envUrls },
/** Returns the URL for the given key, or throws if it is not defined. */
/** All values defined for the current environment (may be empty if no environment is set). */
env: { ...envData },
/** Returns the value for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
const value = envUrls[key];
const value = envData[key];
if (value == null) {
throw new Error(
`Environment URL "${key}" is not defined for this environment`,
`Environment value "${key}" is not defined for this environment`,
);
}
return value;
},
/**
* Runs a named snippet by name. Snippets receive the same page/context/helpers
* Runs a snippet by alias. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (name: string, ...args: unknown[]): Promise<unknown> => {
const snippetCode = snippetMap[name];
runSnippet: async (
alias: string,
...args: unknown[]
): Promise<unknown> => {
const snippetCode = snippetMap[alias];
if (snippetCode == null) {
throw new Error(`Snippet "${name}" not found`);
throw new Error(`Snippet alias "${alias}" not found`);
}
const snippetFn = new Function(
"page",
@@ -120,23 +124,39 @@ export class CodeExecutorService {
"helpers",
"console",
"snippetArgs",
"expect",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
);
return snippetFn(page, context, pageHelpers, fakeConsole, args);
return snippetFn(
page,
context,
pageHelpers,
fakeConsole,
args,
playwrightExpect,
);
},
};
// Passing `console` as a named parameter shadows the global in the script scope.
// Passing `console` and `expect` as named parameters exposes them in script scope.
const fn = new Function(
"page",
"context",
"helpers",
"console",
"result",
"expect",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(page, context, pageHelpers, fakeConsole, result);
const execResult = await fn(
page,
context,
pageHelpers,
fakeConsole,
result,
playwrightExpect,
);
return { result: execResult };
} catch (err) {
throw new InternalServerErrorException(
+1 -1
View File
@@ -23,7 +23,7 @@ export class AppConfig {
KEYS_DIR: string = "keys";
@IsString()
DB_PATH: string = "data/sessions.db";
DB_PATH: string = "data/liqa.db";
@IsInt()
@Min(1)
+21 -4
View File
@@ -10,7 +10,12 @@ import {
PaginatedResult,
} from "../common/dto/pagination.dto";
export type CredentialOrderBy = "id" | "name" | "lastUsedAt" | "createdAt" | "updatedAt";
export type CredentialOrderBy =
| "id"
| "name"
| "lastUsedAt"
| "createdAt"
| "updatedAt";
@Injectable()
export class CredentialService {
@@ -44,7 +49,10 @@ export class CredentialService {
return credential;
}
async update(id: string, dto: UpdateCredentialDto): Promise<CredentialEntity> {
async update(
id: string,
dto: UpdateCredentialDto,
): Promise<CredentialEntity> {
const credential = await this.findOne(id);
Object.assign(credential, dto);
return this.repo.save(credential);
@@ -56,7 +64,12 @@ export class CredentialService {
}
exportCredential(credential: CredentialEntity): CredentialExportDto {
return { kind: "credential", id: credential.id, name: credential.name, data: credential.data };
return {
kind: "credential",
id: credential.id,
name: credential.name,
data: credential.data,
};
}
async importCredential(dto: CredentialExportDto): Promise<CredentialEntity> {
@@ -67,7 +80,11 @@ export class CredentialService {
return this.repo.save(existing);
}
return this.repo.save(
this.repo.create({ id: dto.id, name: dto.name, data: dto.data ?? null }),
this.repo.create({
id: dto.id,
name: dto.name,
data: dto.data ?? null,
}),
);
}
return this.repo.save(
@@ -1,5 +1,11 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsIn, IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
import {
IsIn,
IsNotEmpty,
IsOptional,
IsString,
IsUUID,
} from "class-validator";
export class CredentialExportDto {
@ApiPropertyOptional()
@@ -1,6 +1,6 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsObject, IsString } from "class-validator";
import { EnvironmentUrls } from "../environment.entity";
import { EnvironmentData } from "../environment.entity";
export class CreateEnvironmentDto {
@ApiProperty({ example: "liquio-diia-stg" })
@@ -9,13 +9,13 @@ export class CreateEnvironmentDto {
name: string;
@ApiProperty({
description: "Map of URL identifiers to URL strings",
description: "Generic key-value map for environment metadata",
example: {
id_url: "https://id-liquio-diia-stg.kitsoft.ua/",
cabinet_url: "https://cabinet-liquio-diia-stg.kitsoft.ua/",
admin_url: "https://admin-liquio-diia-stg.kitsoft.ua/",
id: "https://id-liquio-diia-stg.kitsoft.ua/",
cabinet: "https://cabinet-liquio-diia-stg.kitsoft.ua/",
feature_flag: "enabled",
},
})
@IsObject()
urls: EnvironmentUrls;
data: EnvironmentData;
}
@@ -0,0 +1,31 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsIn,
IsNotEmpty,
IsObject,
IsOptional,
IsString,
IsUUID,
} from "class-validator";
import { EnvironmentData } from "../environment.entity";
export class EnvironmentExportDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(["environment"])
kind?: "environment";
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
id?: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
name: string;
@ApiProperty()
@IsObject()
data: EnvironmentData;
}
@@ -14,6 +14,7 @@ import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { EnvironmentService } from "./environment.service";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { EnvironmentOrderBy } from "./environment.service";
@@ -30,6 +31,13 @@ export class EnvironmentController {
return this.environmentService.create(dto);
}
@Post("import")
@ApiOperation({ summary: "Import an environment (upsert by id or name)" })
@ApiResponse({ status: 201, description: "Environment imported" })
async importEnvironment(@Body() dto: EnvironmentExportDto) {
return this.environmentService.importEnvironment(dto);
}
@Get()
@ApiOperation({ summary: "List all environments (paginated)" })
@ApiResponse({ status: 200, description: "Paginated environments" })
@@ -37,6 +45,15 @@ export class EnvironmentController {
return this.environmentService.findAll(query);
}
@Get(":id/export")
@ApiOperation({ summary: "Export an environment as a plain object" })
@ApiResponse({ status: 200, description: "Environment export payload" })
@ApiResponse({ status: 404, description: "Environment not found" })
async exportEnvironment(@Param("id", ParseUUIDPipe) id: string) {
const env = await this.environmentService.findOne(id);
return this.environmentService.exportEnvironment(env);
}
@Get(":id")
@ApiOperation({ summary: "Get environment by ID" })
@ApiResponse({ status: 200, description: "Environment record" })
+2 -5
View File
@@ -6,10 +6,7 @@ import {
UpdateDateColumn,
} from "typeorm";
export interface EnvironmentUrls {
id_url?: string;
cabinet_url?: string;
admin_url?: string;
export interface EnvironmentData {
[key: string]: string | undefined;
}
@@ -22,7 +19,7 @@ export class EnvironmentEntity {
name: string;
@Column("simple-json")
urls: EnvironmentUrls;
data: EnvironmentData;
@CreateDateColumn()
createdAt: Date;
@@ -8,6 +8,7 @@ import { Repository } from "typeorm";
import { EnvironmentEntity } from "./environment.entity";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
@@ -64,4 +65,32 @@ export class EnvironmentService {
await this.findOne(id);
await this.repo.delete(id);
}
exportEnvironment(env: EnvironmentEntity): EnvironmentExportDto {
return {
kind: "environment",
id: env.id,
name: env.name,
data: env.data,
};
}
async importEnvironment(dto: EnvironmentExportDto): Promise<EnvironmentEntity> {
if (dto.id) {
const existing = await this.repo.findOneBy({ id: dto.id });
if (existing) {
Object.assign(existing, { name: dto.name, data: dto.data });
return this.repo.save(existing);
}
return this.repo.save(
this.repo.create({ id: dto.id, name: dto.name, data: dto.data }),
);
}
const byName = await this.repo.findOneBy({ name: dto.name });
if (byName) {
Object.assign(byName, { data: dto.data });
return this.repo.save(byName);
}
return this.repo.save(this.repo.create({ name: dto.name, data: dto.data }));
}
}
+7
View File
@@ -4,6 +4,13 @@ import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
@ApiTags("health")
@Controller()
export class HealthController {
@Get("health")
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
health(): { status: string } {
return { status: "ok" };
}
@Get("healthz")
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
+21 -3
View File
@@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "./config/app.config";
import { ValidationPipe } from "@nestjs/common";
import { RequestMethod, ValidationPipe } from "@nestjs/common";
import { TraceLogger } from "./common/trace-logger";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";
@@ -11,11 +11,20 @@ import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { name as pkgName, version as pkgVersion } from "../package.json";
async function bootstrap() {
const API_PREFIX = "api/v1";
const logger = new TraceLogger("Bootstrap");
const app = await NestFactory.create(AppModule, {
logger: new TraceLogger("Bootstrap", { timestamp: true }),
});
app.setGlobalPrefix(API_PREFIX, {
exclude: [
{ path: "health", method: RequestMethod.ALL },
{ path: "healthz", method: RequestMethod.ALL },
{ path: "mcp", method: RequestMethod.ALL },
],
});
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new TraceInterceptor(), new LoggingInterceptor());
@@ -24,6 +33,15 @@ async function bootstrap() {
const port = config.get("PORT");
const nodeEnv = config.get("NODE_ENV");
app.enableCors({
origin: [
"http://localhost:5173",
"http://127.0.0.1:5173",
],
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
credentials: true,
});
const swaggerConfig = new DocumentBuilder()
.setTitle(pkgName)
.setDescription(`${pkgName} API`)
@@ -31,14 +49,14 @@ async function bootstrap() {
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup("api", app, document);
SwaggerModule.setup("docs", app, document);
await app.listen(port);
logger.log(
`Application "${pkgName}" v${pkgVersion} running on port ${port} [${nodeEnv}]`,
);
logger.log(`Swagger UI available at http://localhost:${port}/api`);
logger.log(`Swagger UI available at http://localhost:${port}/docs`);
logger.log(`MCP endpoint available at http://localhost:${port}/mcp`);
}
-2
View File
@@ -1,7 +1,6 @@
import { Module } from "@nestjs/common";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
import { AuthModule } from "../auth/auth.module";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { BrowserModule } from "../browser/browser.module";
@@ -10,7 +9,6 @@ import { ScenarioModule } from "../scenario/scenario.module";
@Module({
imports: [
AuthModule,
SessionModule,
EnvironmentModule,
BrowserModule,
+19 -76
View File
@@ -3,11 +3,10 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import type { Request, Response } from "express";
import { AuthService } from "../auth/auth.service";
import { SessionService } from "../session/session.service";
import { SessionContextService } from "../session/session-context.service";
import { EnvironmentService } from "../environment/environment.service";
import type { EnvironmentUrls } from "../environment/environment.entity";
import type { EnvironmentData } from "../environment/environment.entity";
import { BrowserService } from "../browser/browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "../scenario/scenario.service";
@@ -17,7 +16,6 @@ import pkg from "../../package.json";
@Injectable()
export class McpService {
constructor(
private readonly authService: AuthService,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly environmentService: EnvironmentService,
@@ -33,53 +31,6 @@ export class McpService {
}
private registerTools(server: McpServer): void {
// ── Auth ──────────────────────────────────────────────────────────────────
server.registerTool(
"list_keys",
{ description: "List available key identifiers from the keys directory" },
async () => {
const keys = this.authService.listKeys();
return {
content: [{ type: "text" as const, text: JSON.stringify(keys) }],
};
},
);
server.registerTool(
"login",
{
description:
"Log in using a file key against a named environment and store the session",
inputSchema: {
key: z
.string()
.describe(
"Key identifier (filename without extension from keys/ dir)",
),
environmentName: z
.string()
.describe("Environment name to resolve login/cabinet URLs"),
sessionName: z
.string()
.optional()
.describe(
"Session name to store credentials under. Auto-UUID if omitted.",
),
},
},
async ({ key, environmentName, sessionName }) => {
const result = await this.authService.login(
key,
environmentName,
sessionName,
);
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
},
);
// ── Sessions ──────────────────────────────────────────────────────────────
server.registerTool(
@@ -223,23 +174,21 @@ export class McpService {
server.registerTool(
"create_environment",
{
description: "Create a new named environment with a set of URLs",
description: "Create a new named environment with generic data",
inputSchema: {
name: z
.string()
.describe("Unique environment name, e.g. liquio-diia-stg"),
urls: z
data: z
.record(z.string(), z.string())
.describe(
"Map of URL keys to URL strings (id_url, cabinet_url, admin_url, …)",
),
.describe("Map of string keys to string values"),
},
},
async ({ name, urls }) => {
async ({ name, data }) => {
try {
const env = await this.environmentService.create({
name,
urls: urls as EnvironmentUrls,
data: data as EnvironmentData,
});
return {
content: [{ type: "text" as const, text: JSON.stringify(env) }],
@@ -256,21 +205,21 @@ export class McpService {
server.registerTool(
"update_environment",
{
description: "Update an existing environment (name and/or urls)",
description: "Update an existing environment (name and/or data)",
inputSchema: {
id: z.string().uuid().describe("Environment ID to update"),
name: z.string().optional().describe("New name"),
urls: z
data: z
.record(z.string(), z.string())
.optional()
.describe("New URLs map"),
.describe("New data map"),
},
},
async ({ id, name, urls }) => {
async ({ id, name, data }) => {
try {
const env = await this.environmentService.update(id, {
name,
urls: urls as EnvironmentUrls | undefined,
data: data as EnvironmentData | undefined,
});
return {
content: [{ type: "text" as const, text: JSON.stringify(env) }],
@@ -551,15 +500,11 @@ export class McpService {
.min(0)
.describe("Execution order (ascending)"),
type: z.enum(["login", "exec", "sign"]).describe("Step type"),
sessionName: z.string().describe("Session name used by this step"),
title: z.string().optional().describe("Optional step title"),
execCode: z
.string()
.optional()
.describe("Playwright JS code to execute (exec steps)"),
validateCode: z
.string()
.optional()
.describe("Validation JS code returning { success, description }"),
},
},
async ({ scenarioId, ...dto }) => {
@@ -618,9 +563,8 @@ export class McpService {
.enum(["login", "exec", "sign"])
.optional()
.describe("New step type"),
sessionName: z.string().optional().describe("New session name"),
title: z.string().optional().describe("New step title"),
execCode: z.string().optional().describe("New exec code"),
validateCode: z.string().optional().describe("New validation code"),
},
},
async ({ scenarioId, stepId, ...dto }) => {
@@ -721,11 +665,15 @@ export class McpService {
description: "Trigger an immediate run of a scenario by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID to run"),
environmentId: z
.string()
.uuid()
.describe("Environment ID to run the scenario in"),
},
},
async ({ id }) => {
async ({ id, environmentId }) => {
try {
const run = await this.scenarioService.createRun(id);
const run = await this.scenarioService.createRun(id, environmentId);
return {
content: [{ type: "text" as const, text: JSON.stringify(run) }],
};
@@ -832,11 +780,6 @@ export class McpService {
.nullable()
.optional()
.describe("Exec/sign code"),
validateCode: z
.string()
.nullable()
.optional()
.describe("Validation code"),
}),
)
.describe("Ordered list of steps"),
@@ -4,7 +4,8 @@ import { IsNotEmpty, IsString, IsUUID } from "class-validator";
export class AddScenarioCredentialDto {
@ApiProperty({ example: "uuid-here" })
@IsUUID()
credentialId: string
credentialId: string;
@ApiProperty({ example: "api_key" })
@IsString()
@IsNotEmpty()
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more