Compare commits

...
15 Commits
Author SHA1 Message Date
ars9 4dab218b75 1.6.0 2026-04-14 23:16:44 +03:00
ars9 622924ed53 refactor(nav): reorganize sidebar with dynamic sections at top
- move runs and sessions to top of navigation (most dynamic)
- add visual separator between dynamic and configuration sections
- reorder remaining items: scenarios, snippets, credentials, environments
- implement separator component in nav rendering logic
2026-04-14 23:15:49 +03:00
ars9 6c43b53590 fix(scenarios): add error handling for API calls and dev script with local API
- add catch handler to promises for better error visibility
- use null coalescing operators to prevent undefined accessing
- add dev:compose-api npm script pointing to localhost:13000 API
- include toast dependency in useCallback to avoid stale closures
2026-04-14 23:09:38 +03:00
ars9 e66e53c817 chore: apply code formatting and linting
- format long import statements with consistent line wrapping
- apply consistent indentation across client and server modules
- remove generated tsconfig.tsbuildinfo file
2026-04-14 22:54:03 +03:00
ars9 a71be39076 fix: fix links in scenario service 2026-04-14 21:11:35 +03:00
ars9 5ec9fd0bc3 refactor: add session and environment relationships to scenario run
- add sessionId optional column to ScenarioRunEntity
- add ManyToOne relationship to EnvironmentEntity (with eager loading)
- add ManyToOne relationship to SessionEntity (optional)
- update ScenarioRun client types to include session and environment data
- add environment name and session link to RunDetailPage
- update UI to display save session, environment, and session info
2026-04-14 19:29:48 +03:00
ars9 80d9af42b5 fix: add save session checkbox to run modal on scenarios list page
- add saveSessionFlag state to ScenariosPage
- pass saveSessionFlag to scenarios.run() call
- render save session checkbox in run modal when envs are available
- reset saveSessionFlag after scenario run completes
2026-04-14 19:24:13 +03:00
ars9 dcb002304b feat(run-detail): add expandable step output blocks with json pretty-printing
- add collapsible code blocks for step output with JSON syntax highlighting
- display byte count when output exists but no description available
- support both individual row expansion and header-level expand all toggle
- pretty-print JSON output for improved readability
- wrap log messages in code tags for monospace display
- fix step order numbering to start from 1 instead of 2
2026-04-14 19:19:39 +03:00
ars9 196bf4c2e8 feat: add saveSession flag to create scenario runs
- Add optional `saveSession` boolean parameter to CreateScenarioRunDto
- Add `saveSession` column to ScenarioRunEntity
- When saveSession=true and run completes, preserve the browser context as a named explore session instead of closing it
- Session name follows pattern: run-{runId}
- Automatically extracts token and localStorage for session persistence
- Injected SessionService and SessionContextService into ScenarioSchedulerService
- Updated MCP run_scenario tool to accept saveSession parameter
- Updated UI run dialog with checkbox to enable session preservation
- Client API updated to pass saveSession flag
2026-04-14 18:54:45 +03:00
ars9 0e47623a6b feat(browser,mcp): resolve environment and credentials from DB in exec
- POST /exec now accepts environmentId (UUID) and credentials (alias → UUID)
  instead of raw payloads; resolves entities via EnvironmentService and
  CredentialService before passing data to browserService.exec
- exec_code MCP tool updated with same schema: environmentId + credentials map
- CredentialModule imported into BrowserModule and McpModule
- docs(scenario): rewrite script runtime section for single context argument
- docs(mcp): update exec_code description to reflect new parameter shapes
- style: reorder imports across server source (formatter)
2026-04-14 18:09:28 +03:00
ars9 90be5a5490 refactor(code-executor): migrate user scripts to single context argument
- replace (page, context, helpers) signature with async (context) => {}
- add ScriptContext interface exposing page, browser, env, getEnv,
  getCredential, getStepOutput, runSnippet, dumpDom, log/warn/error
- rename getEnvUrl to getEnv throughout service and docs
- fix step ordering: normalizeStepOrder and run step rows are now 1-based
- migrate existing DB rows (scenario_steps, scenario_run_steps) +1
- update all tests and stored snippet/step code in DB to new API
2026-04-14 17:44:59 +03:00
ars9 1a2e786ca8 feat(browser): add environment, credentials, and script logger to POST /exec
- ExecDto gains optional `environment` and `credentials` fields
- BrowserService.exec forwards both to CodeExecutorService.execute so
  helpers.env, helpers.getEnvUrl(), and helpers.getCredential() work
  identically to scenario-scheduler steps
- script console.log/warn/error now routed through TraceLogger with
  session label prefix
- integration tests cover env/creds injection and missing-alias error
2026-04-14 16:57:06 +03:00
ars9 d34ea9e943 fix(browser): inject snippets into exec_code context; fix(ui): step order starts at 1 in run detail
- BrowserService.exec() now builds snippet map via SnippetService and passes
  it to CodeExecutorService.execute() for both named-session and anonymous paths
- SnippetModule added to BrowserModule imports to wire the dependency
- RunDetailPage step order column renders s.order + 1 (was 0-based)
2026-04-14 16:28:31 +03:00
ars9 310997c3ae feat(mcp): add credential and all-runs tools; replace deprecated z.string().uuid()
- add list_scenario_credentials, add_scenario_credential, remove_scenario_credential tools
- add list_all_runs tool (global across all scenarios)
- replace all deprecated z.string().uuid() with z.uuid() throughout mcp.service
2026-04-14 14:45:55 +03:00
ars9 7acd1bc5a1 feat(client): add nginx config for SPA routing and API proxy
- add try_files fallback to serve index.html for all non-asset paths
- proxy /api/ requests to the server container to avoid HTML being
  returned by nginx for API calls when using full route paths
2026-04-14 13:05:55 +03:00
100 changed files with 1799 additions and 797 deletions

No files matched your search

+1
View File
@@ -12,3 +12,4 @@ server/dist
client/dist
*storybook.log
storybook-static
tsconfig.tsbuildinfo
+1
View File
@@ -15,5 +15,6 @@ RUN npm run -w client build
FROM nginx:alpine AS runtime
COPY --from=builder /app/client/dist /usr/share/nginx/html
COPY client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+17
View File
@@ -0,0 +1,17 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://server:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+3
View File
@@ -4,10 +4,12 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"test:compile": "tsc --noEmit",
"test:storybook": "vitest run --project storybook",
"lint": "eslint src .storybook",
"lint:fix": "eslint src .storybook --fix",
@@ -15,6 +17,7 @@
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
+6
View File
@@ -95,6 +95,12 @@
background: var(--color-secondary-hover);
}
.navSeparator {
height: var(--border-width);
background: var(--color-border);
margin: var(--space-2) var(--space-2);
}
.main {
flex: 1;
overflow-y: auto;
+42 -26
View File
@@ -11,13 +11,19 @@ const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
);
const EnvironmentDetailPage = lazy(() =>
import('./pages/environment/EnvironmentDetailPage').then((m) => ({ default: m.EnvironmentDetailPage })),
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
default: m.EnvironmentDetailPage,
})),
);
const CreateEnvironmentPage = lazy(() =>
import('./pages/environment/CreateEnvironmentPage').then((m) => ({ default: m.CreateEnvironmentPage })),
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
default: m.CreateEnvironmentPage,
})),
);
const EditEnvironmentPage = lazy(() =>
import('./pages/environment/EditEnvironmentPage').then((m) => ({ default: m.EditEnvironmentPage })),
import('./pages/environment/EditEnvironmentPage').then((m) => ({
default: m.EditEnvironmentPage,
})),
);
const SessionsPage = lazy(() =>
@@ -46,9 +52,7 @@ const EditStepPage = lazy(() =>
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
);
const RunsPage = lazy(() =>
import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })),
);
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
const RunDetailPage = lazy(() =>
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
);
@@ -60,13 +64,17 @@ const CredentialsPage = lazy(() =>
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
);
const CreateCredentialPage = lazy(() =>
import('./pages/credential/CreateCredentialPage').then((m) => ({ default: m.CreateCredentialPage })),
import('./pages/credential/CreateCredentialPage').then((m) => ({
default: m.CreateCredentialPage,
})),
);
const EditCredentialPage = lazy(() =>
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
);
const CredentialDetailPage = lazy(() =>
import('./pages/credential/CredentialDetailPage').then((m) => ({ default: m.CredentialDetailPage })),
import('./pages/credential/CredentialDetailPage').then((m) => ({
default: m.CredentialDetailPage,
})),
);
const SnippetsPage = lazy(() =>
@@ -82,13 +90,17 @@ const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
);
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
const NAV: (
| { path: string; labelKey: string; Icon: LucideIcon }
| { separator: true }
)[] = [
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ separator: true },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
];
export default function App() {
@@ -106,18 +118,22 @@ export default function App() {
>
<div className={styles.sideContent}>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
{NAV.map((item, index) =>
'separator' in item ? (
<div key={`separator-${index}`} className={styles.navSeparator} />
) : (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(item.labelKey)}
</NavLink>
),
)}
</nav>
<div className={styles.sideFooter}>
+9 -4
View File
@@ -15,7 +15,10 @@ import { emitApiErrorToast } from '../lib/toast-events';
// API calls are versioned under /api/v1 by default.
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(/\/$/, '');
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
/\/$/,
'',
);
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
@@ -90,7 +93,9 @@ export const snippets = {
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string }): Promise<Snippet> {
create(
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
@@ -192,10 +197,10 @@ export const scenarios = {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: string, environmentId: string): Promise<ScenarioRun> {
run(id: string, environmentId: string, saveSession?: boolean): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId }),
body: JSON.stringify({ environmentId, saveSession }),
});
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
+4
View File
@@ -98,7 +98,11 @@ export interface ScenarioRun {
id: string;
scenarioId: string;
environmentId: string;
sessionId?: string | null;
saveSession: boolean;
scenario?: Pick<Scenario, 'id' | 'name'>;
environment?: Pick<Environment, 'id' | 'name'>;
session?: { id: string; sessionName: string };
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
createdAt: string;
@@ -0,0 +1,45 @@
import { useTranslation } from 'react-i18next';
import { X, Trash2 } from 'lucide-react';
import { Modal, Button } from '../../ui';
export interface DeleteConfirmationModalProps {
open: boolean;
title: string;
message: string;
onClose: () => void;
onConfirm: () => void;
isDeleting: boolean;
}
export function DeleteConfirmationModal({
open,
title,
message,
onClose,
onConfirm,
isDeleting,
}: DeleteConfirmationModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={title}
onClose={() => !isDeleting && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isDeleting}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={onConfirm} disabled={isDeleting}>
<Trash2 size={14} />
{t('common.button_delete')}
</Button>
</>
}
>
{message}
</Modal>
);
}
@@ -0,0 +1,80 @@
import { useTranslation } from 'react-i18next';
import { X, Play } from 'lucide-react';
import { Modal, Button, Select } from '../../ui';
import type { Environment } from '../../api';
export interface RunScenarioModalProps {
open: boolean;
environments: Environment[];
selectedEnvId: string;
onEnvSelect: (envId: string) => void;
saveSessionFlag: boolean;
onSaveSessionChange: (flag: boolean) => void;
onClose: () => void;
onRun: () => void;
isRunning: boolean;
actionLabel?: string;
}
export function RunScenarioModal({
open,
environments,
selectedEnvId,
onEnvSelect,
saveSessionFlag,
onSaveSessionChange,
onClose,
onRun,
isRunning,
actionLabel,
}: RunScenarioModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={t('scenarios.run_modal_title')}
onClose={() => !isRunning && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isRunning}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={onRun} disabled={isRunning || !selectedEnvId}>
<Play size={14} />
{actionLabel || t('scenarios.action_run')}
</Button>
</>
}
>
{environments.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => onEnvSelect(e.target.value)}
options={environments.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{
display: 'flex',
alignItems: 'center',
marginTop: '1rem',
gap: '0.5rem',
}}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => onSaveSessionChange(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
);
}
+4
View File
@@ -0,0 +1,4 @@
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
export { RunScenarioModal } from './RunScenarioModal';
export type { RunScenarioModalProps } from './RunScenarioModal';
+24
View File
@@ -1,4 +1,17 @@
{
"common": {
"button_cancel": "Cancel",
"button_confirm": "Confirm",
"button_delete": "Delete",
"confirm_delete_credential": "Are you sure you want to delete this credential?",
"confirm_delete_environment": "Are you sure you want to delete this environment?",
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
"confirm_delete_step": "Are you sure you want to delete this step?",
"confirm_delete_session": "Are you sure you want to delete this session?",
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
"save_session": "Save session"
},
"errors": {
"not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.",
@@ -19,6 +32,8 @@
},
"environments": {
"title": "Environments",
"created": "Environment created",
"updated": "Environment updated",
"col_id": "ID",
"col_name": "Name",
"col_data": "Data",
@@ -51,6 +66,8 @@
},
"credentials": {
"title": "Credentials",
"created": "Credential created",
"updated": "Credential updated",
"empty": "No credentials yet.",
"loading": "Loading…",
"menu_label": "Credential options",
@@ -99,6 +116,9 @@
"field_lastUsed": "Last Used"
},
"scenarios": { "title": "Scenarios",
"created": "Scenario created",
"updated": "Scenario updated",
"run_started": "Scenario run started",
"col_id": "ID",
"col_name": "Name",
"col_updated": "Updated",
@@ -165,6 +185,8 @@
"page_size": "Items per page"
},
"steps": {
"created": "Step created",
"updated": "Step updated",
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
@@ -215,6 +237,8 @@
},
"snippets": {
"title": "Snippets",
"created": "Snippet created",
"updated": "Snippet updated",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
+6 -5
View File
@@ -6,6 +6,7 @@ export interface ApiErrorToastDetail {
export function emitApiErrorToast(message: string): void {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
detail: { message },
@@ -13,17 +14,17 @@ export function emitApiErrorToast(message: string): void {
);
}
export function subscribeApiErrorToasts(
handler: (message: string) => void,
): () => void {
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
if (typeof window === 'undefined') return () => {};
const listener = (event: Event) => {
const custom = event as CustomEvent<ApiErrorToastDetail>;
const message = custom.detail?.message;
if (message) handler(message);
};
window.addEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
return () => {
window.removeEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
};
}
+10 -5
View File
@@ -1,17 +1,22 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './i18n';
import './ui/tokens.css';
import App from './App';
import { ToastProvider } from './ui';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
<QueryClientProvider client={queryClient}>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</QueryClientProvider>
</StrictMode>,
);
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
@@ -16,9 +16,8 @@ export function CreateCredentialPage() {
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -35,14 +34,12 @@ export function CreateCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success('Credential created');
toast.success(t('credentials.created'));
navigate(`/credentials/${credential.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -54,7 +51,11 @@ export function CreateCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: t('credentials.create_title') },
]}
/>
@@ -6,15 +6,8 @@ import { CodeBlock } from '../../ui';
import { stringify as yamlStringify } from 'yaml';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
@@ -23,7 +16,6 @@ export function CredentialDetailPage() {
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -32,7 +24,6 @@ export function CredentialDetailPage() {
credentials
.get(id)
.then(setCredential)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -65,7 +56,11 @@ export function CredentialDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: credential?.name ?? `#${id}` },
]}
/>
@@ -136,23 +131,14 @@ export function CredentialDetailPage() {
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -11,10 +11,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function CredentialCard({
@@ -103,7 +103,6 @@ export function CredentialsPage() {
const navigate = useNavigate();
const [items, setItems] = useState<Credential[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -112,7 +111,6 @@ export function CredentialsPage() {
credentials
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -145,8 +143,8 @@ export function CredentialsPage() {
const payload = yamlParse(text) as unknown;
const imported = await credentials.importCredential(payload);
navigate(`/credentials/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -179,23 +177,14 @@ export function CredentialsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('credentials.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { KeyRound, X, Save } from 'lucide-react';
@@ -20,7 +20,6 @@ export function EditCredentialPage() {
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -31,11 +30,10 @@ export function EditCredentialPage() {
setName(c.name);
setData(c.data ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -52,17 +50,15 @@ export function EditCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
toast.success('Credential updated');
toast.success(t('credentials.updated'));
navigate(`/credentials/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -74,7 +70,11 @@ export function EditCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
@@ -16,9 +16,8 @@ export function CreateEnvironmentPage() {
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -42,14 +41,12 @@ export function CreateEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
const env = await environments.create(name.trim(), parsedData);
toast.success('Environment created');
toast.success(t('environments.created'));
navigate(`/environments/${env.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -61,7 +58,11 @@ export function CreateEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: t('environments.create_title') },
]}
/>
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Globe, Save } from 'lucide-react';
@@ -20,7 +20,6 @@ export function EditEnvironmentPage() {
const [dataError, setDataError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -31,11 +30,10 @@ export function EditEnvironmentPage() {
setName(data.name);
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -59,17 +57,15 @@ export function EditEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
await environments.update(id!, {
name: name.trim(),
data: parsedData,
});
toast.success('Environment updated');
toast.success(t('environments.updated'));
navigate(`/environments/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +77,11 @@ export function EditEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
@@ -1,20 +1,29 @@
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Upload, Pencil, Trash2, Globe } from 'lucide-react';
import { useNavigate, useParams } from 'react-router-dom';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Modal, Timestamp, UuidBadge } from '../../ui';
import { environments } from '../../api';
import { DeleteConfirmationModal } from '../../components/modals';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Timestamp,
UuidBadge,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const toast = useToast();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
@@ -24,9 +33,9 @@ export function EnvironmentDetailPage() {
environments
.get(id)
.then(setEnv)
.catch((err: Error) => setError(err.message))
.catch((err: Error) => toast.error((err as Error).message))
.finally(() => setLoading(false));
}, [id]);
}, [id, toast]);
const handleDelete = async () => {
if (!env) return;
@@ -57,7 +66,11 @@ export function EnvironmentDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: env?.name ?? `#${id}` },
]}
/>
@@ -107,12 +120,12 @@ export function EnvironmentDetailPage() {
<div className={styles.stepsSection}>
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
<Card>
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
@@ -120,30 +133,21 @@ export function EnvironmentDetailPage() {
</a>
),
}))}
/>
)}
</Card>
/>
)}
</Card>
</div>
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -12,10 +12,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
@@ -120,7 +120,6 @@ export function EnvironmentsPage() {
const navigate = useNavigate();
const [items, setItems] = useState<Environment[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -129,7 +128,6 @@ export function EnvironmentsPage() {
environments
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -162,8 +160,8 @@ export function EnvironmentsPage() {
const payload = yamlParse(text) as unknown;
const imported = await environments.importEnvironment(payload);
navigate(`/environments/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -196,23 +194,14 @@ export function EnvironmentsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('environments.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+22 -32
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Activity } from 'lucide-react';
@@ -39,35 +39,20 @@ export function AllRunsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [items, setItems] = useState<AllRunRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const 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(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
const {
data: items = [],
isLoading,
error,
refetch,
} = useQuery<AllRunRow[]>({
queryKey: ['runs'],
queryFn: async () => {
const res = await runs.listAll();
return res.data as AllRunRow[];
},
refetchInterval: 10_000,
staleTime: 0,
});
const columns: TableColumn<AllRunRow>[] = [
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
@@ -110,14 +95,19 @@ export function AllRunsPage() {
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
<AutoRefreshIndicator
active
pulseKey={items.length}
error={!!error}
onClick={() => refetch()}
/>
</div>
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
loading={isLoading}
emptyMessage={t('runs.empty')}
pageSize={20}
pageSizeOptions={[10, 20, 50]}
+168 -23
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { runs } from '../../api';
import type {
@@ -17,8 +17,8 @@ import {
Badge,
Breadcrumbs,
Card,
CodeBlock,
DescriptionList,
Notification,
Pagination,
Search,
Table,
@@ -27,7 +27,7 @@ import {
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import { ClipboardList, Activity } from 'lucide-react';
import { ChevronDown, ChevronRight, ClipboardList, Activity } from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
@@ -75,6 +75,8 @@ export function RunDetailPage() {
const [logPage, setLogPage] = useState(1);
const [logSearch, setLogSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [expandAll, setExpandAll] = useState(false);
const [expandedStepIds, setExpandedStepIds] = useState<Set<string>>(new Set());
const logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -171,8 +173,109 @@ export function RunDetailPage() {
},
{
key: 'description',
header: t('runs.step_description'),
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
header: (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<span>{t('runs.step_description')}</span>
{run?.stepRuns.some((s) => s.output) && (
<button
onClick={() => {
if (expandAll) {
setExpandAll(false);
setExpandedStepIds(new Set());
} else {
setExpandAll(true);
setExpandedStepIds(
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
);
}
}}
style={{
background: 'none',
border: 'none',
padding: '0 4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
color: 'inherit',
}}
title={expandAll ? 'Collapse all' : 'Expand all'}
>
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
</div>
),
render: (s) => {
const isExpanded = expandAll || expandedStepIds.has(s.id);
return (
<div>
<div
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
marginBottom: isExpanded && s.output ? '8px' : 0,
}}
>
{s.output && (
<button
onClick={() => {
const newSet = new Set(expandedStepIds);
if (newSet.has(s.id)) {
newSet.delete(s.id);
} else {
newSet.add(s.id);
}
setExpandedStepIds(newSet);
}}
style={{
background: 'none',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
flexShrink: 0,
marginTop: '2px',
}}
>
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
<code style={{ wordBreak: 'break-word' }}>
{s.description ? (
s.description
) : s.output ? (
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
) : (
<span className={styles.muted}>–</span>
)}
</code>
</div>
{isExpanded && s.output && (
<div style={{ marginLeft: '24px' }}>
<CodeBlock
code={(() => {
try {
return JSON.stringify(JSON.parse(s.output), null, 2);
} catch {
return s.output;
}
})()}
language="json"
/>
</div>
)}
</div>
);
},
},
];
@@ -183,7 +286,11 @@ export function RunDetailPage() {
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
{
key: 'message',
header: t('runs.log_message'),
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
},
{
key: 'time',
header: t('runs.log_time'),
@@ -197,9 +304,13 @@ export function RunDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
@@ -207,10 +318,15 @@ export function RunDetailPage() {
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
{ label: `${runId}` },
]}
/>
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} error={!!error} onClick={manualRefresh} />
<AutoRefreshIndicator
active={polling}
pulseKey={pulseKey}
error={!!error}
onClick={manualRefresh}
/>
</div>
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
@@ -220,19 +336,48 @@ export function RunDetailPage() {
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
]}
items={(() => {
const items = [
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
];
if (run.environment) {
items.push({
term: 'Environment',
detail: (
<Link
to={`/environments/${run.environment.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.environment.name}
</Link>
),
});
}
if (run.session) {
items.push({
term: 'Session',
detail: (
<Link
to={`/sessions/${run.session.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.session.sessionName}
</Link>
),
});
}
return items;
})()}
/>
</Card>
+9 -6
View File
@@ -76,7 +76,6 @@ export function RunsPage() {
}, [id]);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
@@ -102,7 +101,7 @@ export function RunsPage() {
setRunning(true);
try {
const run = await scenarios.run(id!, selectedEnvId);
toast.success('Scenario run started');
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
@@ -139,7 +138,11 @@ export function RunsPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -171,16 +174,16 @@ export function RunsPage() {
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('runs.action_run')}
</Button>
</>
)}
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -14,23 +14,20 @@ export function CreateScenarioPage() {
const [name, setName] = useState('');
const [nameError, setNameError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const scenario = await scenarios.create(name.trim());
toast.success('Scenario created');
toast.success(t('scenarios.created'));
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -42,7 +39,11 @@ export function CreateScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: t('scenarios.create_title') },
]}
/>
+8 -7
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -17,7 +17,6 @@ export function CreateStepPage() {
const [title, setTitle] = useState('');
const [execCode, setExecCode] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,20 +26,18 @@ export function CreateStepPage() {
.catch(() => null);
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.create(id!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
});
toast.success('Step created');
toast.success(t('steps.created'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -52,7 +49,11 @@ export function CreateStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -18,7 +18,6 @@ export function EditScenarioPage() {
const [nameError, setNameError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -28,25 +27,22 @@ export function EditScenarioPage() {
setScenario(data);
setName(data.name);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
toast.success('Scenario updated');
toast.success(t('scenarios.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -58,7 +54,11 @@ export function EditScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
+8 -8
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, ClipboardList } from 'lucide-react';
@@ -19,7 +19,6 @@ export function EditStepPage() {
const [execCode, setExecCode] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id || !stepId) return;
@@ -30,24 +29,21 @@ export function EditStepPage() {
setTitle(st.title ?? '');
setExecCode(st.execCode ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id, stepId]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.update(id!, stepId!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
});
toast.success('Step updated');
toast.success(t('steps.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -59,7 +55,11 @@ export function EditStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -1,10 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Pencil, Plus, History, Trash2, Upload, GripVertical, ClipboardList } from 'lucide-react';
import {
Play,
Pencil,
Plus,
History,
Trash2,
Upload,
GripVertical,
ClipboardList,
} from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { environments, scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential, Environment } from '../../api';
import {
environments,
scenarios,
steps,
scenarioCredentials,
credentials as credentialsApi,
} from '../../api';
import type {
Scenario,
ScenarioStep,
ScenarioCredential,
Credential,
Environment,
} from '../../api';
import {
Breadcrumbs,
Button,
@@ -28,7 +49,6 @@ export function ScenarioDetailPage() {
const toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
@@ -44,6 +64,7 @@ export function ScenarioDetailPage() {
const [reorderingSteps, setReorderingSteps] = useState(false);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
const [pendingDelete, setPendingDelete] = useState<
@@ -59,7 +80,6 @@ export function ScenarioDetailPage() {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
credentialsApi
.list(1, 200)
@@ -89,10 +109,11 @@ export function ScenarioDetailPage() {
}
setRunning(true);
try {
const run = await scenarios.run(scenario.id, selectedEnvId);
toast.success('Scenario run started');
const run = await scenarios.run(scenario.id, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -138,7 +159,7 @@ export function ScenarioDetailPage() {
}
};
const handleAddCredential = async (e: React.FormEvent) => {
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!addCredId) {
@@ -319,7 +340,11 @@ export function ScenarioDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: scenario?.name ?? `#${id}` },
]}
/>
@@ -341,7 +366,11 @@ export function ScenarioDetailPage() {
<Pencil size={14} />
{t('scenarios.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={() => setPendingDelete({ type: 'scenario' })}>
<Button
variant="danger"
size="sm"
onClick={() => setPendingDelete({ type: 'scenario' })}
>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
@@ -511,46 +540,58 @@ export function ScenarioDetailPage() {
: t('scenarios.action_delete')
}
onClose={() => !deleting && setPendingDelete(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
Confirm
{t('common.button_confirm')}
</Button>
</>
)}
}
>
{pendingDelete?.type === 'step' && 'Are you sure you want to delete this step?'}
{pendingDelete?.type === 'credential' && 'Are you sure you want to remove this credential from scenario?'}
{pendingDelete?.type === 'scenario' && 'Are you sure you want to delete this scenario?'}
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('scenarios.action_run')}
</Button>
</>
)}
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => setSaveSessionFlag(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
</div>
+36 -21
View File
@@ -24,11 +24,11 @@ export function ScenariosPage() {
const toast = useToast();
const [items, setItems] = useState<Scenario[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
const [envs, setEnvs] = useState<Environment[]>([]);
const [selectedEnvId, setSelectedEnvId] = useState('');
@@ -37,12 +37,14 @@ export function ScenariosPage() {
const load = useCallback(() => {
Promise.all([scenarios.list(), environments.list(1, 200)])
.then(([scenarioRes, envRes]) => {
setItems(scenarioRes.data);
setEnvs(envRes.data);
setItems(scenarioRes?.data ?? []);
setEnvs(envRes?.data ?? []);
})
.catch((err) => {
toast.error((err as Error).message);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
}, [toast]);
useEffect(() => {
load();
@@ -59,10 +61,11 @@ export function ScenariosPage() {
if (!runScenarioId || !selectedEnvId) return;
setRunning(true);
try {
const run = await scenarios.run(runScenarioId, selectedEnvId);
toast.success('Scenario run started');
const run = await scenarios.run(runScenarioId, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
setRunScenarioId(null);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -92,8 +95,8 @@ export function ScenariosPage() {
const payload = yamlParse(text) as unknown;
const imported = await scenarios.importScenario(payload);
navigate(`/scenarios/${imported.id}`);
} catch (err) {
setError((err as Error).message);
} catch {
// Import errors are silently ignored
}
};
@@ -176,25 +179,25 @@ export function ScenariosPage() {
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('scenarios.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this scenario?
{t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runScenarioId != null}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunScenarioId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
Cancel
@@ -203,17 +206,29 @@ export function ScenariosPage() {
{t('scenarios.action_run')}
</Button>
</>
)}
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => setSelectedEnvId(e.target.value)}
options={envs.map((env) => ({ value: env.id, label: env.name }))}
/>
<label
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
>
<input
type="checkbox"
checked={saveSessionFlag}
onChange={(e) => setSaveSessionFlag(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
</div>
+13 -28
View File
@@ -4,16 +4,8 @@ import { useTranslation } from 'react-i18next';
import { Trash2, Monitor } from 'lucide-react';
import { sessions } from '../../api';
import type { Session } from '../../api';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionDetailPage() {
@@ -22,7 +14,6 @@ export function SessionDetailPage() {
const navigate = useNavigate();
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -31,7 +22,6 @@ export function SessionDetailPage() {
sessions
.get(id)
.then(setSession)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -52,7 +42,11 @@ export function SessionDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('sessions.title'), icon: <Monitor size={14} />, onClick: () => navigate('/sessions') },
{
label: t('sessions.title'),
icon: <Monitor size={14} />,
onClick: () => navigate('/sessions'),
},
{ label: session?.sessionName ?? `#${id}` },
]}
/>
@@ -102,23 +96,14 @@ export function SessionDetailPage() {
</Card>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('sessions.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+7 -18
View File
@@ -8,12 +8,12 @@ import {
Badge,
Breadcrumbs,
Button,
Modal,
Table,
type TableColumn,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionsPage() {
@@ -21,7 +21,6 @@ export function SessionsPage() {
const navigate = useNavigate();
const [items, setItems] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
@@ -29,7 +28,6 @@ export function SessionsPage() {
sessions
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
@@ -102,23 +100,14 @@ export function SessionsPage() {
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
/>
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('sessions.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, SubmitEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
@@ -19,9 +19,8 @@ export function CreateSnippetPage() {
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -38,7 +37,6 @@ export function CreateSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
alias: alias.trim(),
@@ -46,11 +44,10 @@ export function CreateSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet created');
toast.success(t('snippets.created'));
navigate(`/snippets/${snippet.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -62,7 +59,11 @@ export function CreateSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: t('snippets.create_title') },
]}
/>
+8 -8
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { X, Save, Braces } from 'lucide-react';
@@ -23,7 +23,6 @@ export function EditSnippetPage() {
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -36,11 +35,10 @@ export function EditSnippetPage() {
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -57,7 +55,6 @@ export function EditSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(id!, {
alias: alias.trim(),
@@ -65,11 +62,10 @@ export function EditSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet updated');
toast.success(t('snippets.updated'));
navigate(`/snippets/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +77,11 @@ export function EditSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
+14 -8
View File
@@ -24,7 +24,6 @@ export function SnippetDetailPage() {
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -33,7 +32,6 @@ export function SnippetDetailPage() {
snippets
.get(id)
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -66,7 +64,11 @@ export function SnippetDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: snippet?.title ?? `#${id}` },
]}
/>
@@ -141,18 +143,22 @@ export function SnippetDetailPage() {
open={confirmDeleteOpen}
title={t('snippets.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
<Button
variant="secondary"
onClick={() => setConfirmDeleteOpen(false)}
disabled={deleting}
>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+21 -19
View File
@@ -17,7 +17,10 @@ import {
} from '../../ui';
import styles from '../Page.module.css';
function firstParagraphBlocks(markdown: string, limit = 2): { preview: string; truncated: boolean } {
function firstParagraphBlocks(
markdown: string,
limit = 2,
): { preview: string; truncated: boolean } {
const blocks = markdown
.split(/\n\s*\n/g)
.map((block) => block.trim())
@@ -81,16 +84,17 @@ function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: s
<p className={styles.muted}>
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
</p>
{snippet.description && (() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
{snippet.description &&
(() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
</Card>
);
}
@@ -113,7 +117,6 @@ export function SnippetsPage() {
const navigate = useNavigate();
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -122,7 +125,6 @@ export function SnippetsPage() {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -155,8 +157,8 @@ export function SnippetsPage() {
const payload = yamlParse(text) as unknown;
const imported = await snippets.importSnippet(payload);
navigate(`/snippets/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -195,18 +197,18 @@ export function SnippetsPage() {
open={deleteId != null}
title={t('snippets.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+6 -3
View File
@@ -36,15 +36,18 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
<li key={i} className={styles.item}>
{isLast ? (
<span className={styles.current} aria-current="page">
{item.icon}{item.label}
{item.icon}
{item.label}
</span>
) : item.href ? (
<a href={item.href} className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</a>
) : (
<button type="button" className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</button>
)}
{!isLast && <span className={styles.separator}>{sep}</span>}
+34 -45
View File
@@ -1,9 +1,8 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import styles from './ToastProvider.module.css';
import { subscribeApiErrorToasts } from '../../lib/toast-events';
type ToastVariant = 'success' | 'error' | 'info';
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
interface ToastItem {
id: number;
@@ -12,15 +11,6 @@ interface ToastItem {
closing: boolean;
}
interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
const ToastContext = createContext<ToastApi | null>(null);
const ICONS: Record<ToastVariant, React.ReactNode> = {
success: <CheckCircle2 size={16} />,
error: <AlertCircle size={16} />,
@@ -41,33 +31,38 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
const dismiss = useCallback((id: number) => {
setItems((prev) =>
prev.map((item) =>
item.id === id ? { ...item, closing: true } : item,
),
);
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
}, [remove]);
const dismiss = useCallback(
(id: number) => {
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
},
[remove],
);
const show = useCallback((message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const show = useCallback(
(message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
}, [dismiss, durationMs]);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
},
[dismiss, durationMs],
);
const api = useMemo<ToastApi>(() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}), [show]);
const api = useMemo<ToastApi>(
() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}),
[show],
);
useEffect(() => {
return subscribeApiErrorToasts((message) => api.error(message));
@@ -86,7 +81,9 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
role="status"
>
<div className={styles.content}>
<span className={styles.icon} aria-hidden="true">{ICONS[item.variant]}</span>
<span className={styles.icon} aria-hidden="true">
{ICONS[item.variant]}
</span>
<p className={styles.message}>{item.message}</p>
</div>
<button
@@ -103,11 +100,3 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
</ToastContext.Provider>
);
}
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+12
View File
@@ -0,0 +1,12 @@
import { createContext } from 'react';
export type ToastVariant = 'success' | 'error' | 'info';
export interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
export const ToastContext = createContext<ToastApi | null>(null);
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { ToastContext, type ToastApi } from './toast-context';
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+2 -1
View File
@@ -27,8 +27,9 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { ToastProvider, useToast } from './Toast/ToastProvider';
export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
export { useToast } from './Toast/useToast';
export { Timestamp } from './Timestamp/Timestamp';
export type { TimestampProps } from './Timestamp/Timestamp';
-1
View File
@@ -1 +0,0 @@
{"root":["./src/App.tsx","./src/declarations.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/index.ts","./src/api/types.ts","./src/hooks/useTheme.ts","./src/i18n/index.ts","./src/lib/hljs.ts","./src/lib/toast-events.ts","./src/pages/credential/CreateCredentialPage.tsx","./src/pages/credential/CredentialDetailPage.tsx","./src/pages/credential/CredentialsPage.tsx","./src/pages/credential/EditCredentialPage.tsx","./src/pages/environment/CreateEnvironmentPage.tsx","./src/pages/environment/EditEnvironmentPage.tsx","./src/pages/environment/EnvironmentDetailPage.tsx","./src/pages/environment/EnvironmentsPage.tsx","./src/pages/run/AllRunsPage.tsx","./src/pages/run/RunDetailPage.tsx","./src/pages/run/RunsPage.tsx","./src/pages/scenario/CreateScenarioPage.tsx","./src/pages/scenario/CreateStepPage.tsx","./src/pages/scenario/EditScenarioPage.tsx","./src/pages/scenario/EditStepPage.tsx","./src/pages/scenario/ScenarioDetailPage.tsx","./src/pages/scenario/ScenariosPage.tsx","./src/pages/session/SessionDetailPage.tsx","./src/pages/session/SessionsPage.tsx","./src/pages/snippet/CreateSnippetPage.tsx","./src/pages/snippet/EditSnippetPage.tsx","./src/pages/snippet/SnippetDetailPage.tsx","./src/pages/snippet/SnippetsPage.tsx","./src/ui/index.ts","./src/ui/AutoRefreshIndicator/AutoRefreshIndicator.tsx","./src/ui/Badge/Badge.tsx","./src/ui/Breadcrumbs/Breadcrumbs.tsx","./src/ui/Button/Button.tsx","./src/ui/Card/Card.tsx","./src/ui/CodeBlock/CodeBlock.tsx","./src/ui/CodeEditor/CodeEditor.tsx","./src/ui/ContextMenu/ContextMenu.tsx","./src/ui/DescriptionList/DescriptionList.tsx","./src/ui/Input/Input.tsx","./src/ui/MarkdownContent/MarkdownContent.tsx","./src/ui/Modal/Modal.tsx","./src/ui/Notification/Notification.tsx","./src/ui/Pagination/Pagination.tsx","./src/ui/Search/Search.tsx","./src/ui/Select/Select.tsx","./src/ui/SidePanel/SidePanel.tsx","./src/ui/Table/Table.tsx","./src/ui/Textarea/Textarea.tsx","./src/ui/ThemeSwitcher/ThemeSwitcher.tsx","./src/ui/Timestamp/Timestamp.tsx","./src/ui/Toast/ToastProvider.tsx","./src/ui/UuidBadge/UuidBadge.tsx"],"version":"5.8.3"}
+1 -1
View File
@@ -28,7 +28,7 @@ The server currently registers the following tools.
| Tool | Description |
|---|---|
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
| `exec_code` | Execute Playwright JS with `page` and `context` in scope |
| `exec_code` | Execute Playwright JS — script receives a single `context` argument (see `scenario.md`). Optional `environmentId` (UUID) resolves environment from DB for `context.getEnv()`. Optional `credentials` (`{ alias: credentialUUID }`) resolves credentials from DB for `context.getCredential(alias)`. |
## Scenarios
+19 -15
View File
@@ -17,24 +17,28 @@ Current scheduler behavior is exec-centric:
## Script runtime
`execCode` and `validateCode` execute as async JavaScript with:
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
- `page`: Playwright `Page`
- `context`: Playwright `BrowserContext`
- `helpers`: utility object
```js
async (context) => {
// your code here
}
```
Available in scope:
- `context.page`: Playwright `Page`
- `context.browser`: Playwright `BrowserContext`
- `context.env`: shallow copy of environment key/value map
- `context.getEnv(key)`: required environment value lookup (throws if missing)
- `context.getCredential(alias)`: credential payload assigned to the scenario alias
- `context.getStepOutput(order)`: prior step output by absolute order (`1`, `2`, ...) or relative (`-1` = previous step)
- `context.dumpDom(selector?)`: simplified DOM snapshot
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: structured step logs
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
`validateCode` additionally receives `result`, which is the value returned by `execCode`.
## Available helpers
- `helpers.dumpDom(selector?)`: simplified DOM snapshot
- `helpers.log(...args)`, `helpers.warn(...args)`, `helpers.error(...args)`: structured step logs
- `helpers.getStepOutput(order)`: prior step output by absolute order (`0`, `1`, ...) or relative (`-1` previous step)
- `helpers.getCredential(alias)`: credential payload assigned to the scenario alias
- `helpers.env`: shallow copy of environment URL map
- `helpers.getEnvUrl(key)`: required environment URL lookup (throws if missing)
- `helpers.runSnippet(name, ...args)`: execute stored snippet code in the same page/context/helpers scope
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
## Validation contract
+27 -2
View File
@@ -1,12 +1,12 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "liqa",
"version": "1.5.0",
"version": "1.6.0",
"workspaces": [
"server",
"client"
@@ -16,6 +16,7 @@
"name": "liqa-client",
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
@@ -4202,6 +4203,30 @@
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.99.0.tgz",
"integrity": "sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.99.0.tgz",
"integrity": "sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==",
"dependencies": {
"@tanstack/query-core": "5.99.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.6.0",
"private": true,
"workspaces": [
"server",
+11 -11
View File
@@ -1,23 +1,23 @@
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { AppConfig, validateAppConfig } from "./config/app.config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScheduleModule } from "@nestjs/schedule";
import { HealthModule } from "./health/health.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module";
import { SessionEntity } from "./session/session.entity";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { AppConfig, validateAppConfig } from "./config/app.config";
import { CredentialEntity } from "./credential/credential.entity";
import { CredentialModule } from "./credential/credential.module";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { HealthModule } from "./health/health.module";
import { McpModule } from "./mcp/mcp.module";
import { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioModule } from "./scenario/scenario.module";
import { SessionEntity } from "./session/session.entity";
import { SnippetEntity } from "./snippet/snippet.entity";
import { SnippetModule } from "./snippet/snippet.module";
+32 -4
View File
@@ -1,9 +1,11 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { OpenDto } from "./dto/open.dto";
import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto";
@ApiTags("browser")
@Controller()
@@ -11,6 +13,8 @@ export class BrowserController {
constructor(
private readonly browserService: BrowserService,
private readonly codeExecutor: CodeExecutorService,
private readonly environmentService: EnvironmentService,
private readonly credentialService: CredentialService,
) {}
@Post("open")
@@ -54,8 +58,32 @@ export class BrowserController {
@ApiResponse({ status: 400, description: "Invalid input" })
@ApiResponse({ status: 404, description: "Session not found" })
@ApiResponse({ status: 500, description: "Execution failed" })
exec(@Body() dto: ExecDto): Promise<ExecResult> {
async exec(@Body() dto: ExecDto): Promise<ExecResult> {
this.codeExecutor.validate(dto.code);
return this.browserService.exec(dto.sessionName, dto.code, dto.url);
// Resolve environment from DB
let environment: Record<string, string | undefined> | undefined;
if (dto.environmentId) {
const env = await this.environmentService.findOne(dto.environmentId);
environment = env.data;
}
// Resolve credentials from DB (alias → payload)
let credentials: Record<string, unknown> | undefined;
if (dto.credentials && Object.keys(dto.credentials).length > 0) {
credentials = {};
for (const [alias, credId] of Object.entries(dto.credentials)) {
const cred = await this.credentialService.findOne(credId);
credentials[alias] = cred.data ? JSON.parse(cred.data) : {};
}
}
return this.browserService.exec(
dto.sessionName,
dto.code,
dto.url,
environment,
credentials,
);
}
}
+12 -3
View File
@@ -1,11 +1,20 @@
import { Module } from "@nestjs/common";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialModule } from "../credential/credential.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { BrowserController } from "./browser.controller";
import { BrowserService } from "./browser.service";
import { SessionModule } from "../session/session.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
@Module({
imports: [SessionModule, CodeExecutorModule],
imports: [
SessionModule,
CodeExecutorModule,
SnippetModule,
EnvironmentModule,
CredentialModule,
],
controllers: [BrowserController],
providers: [BrowserService],
exports: [BrowserService],
+50 -14
View File
@@ -1,18 +1,22 @@
import { Readability } from "@mozilla/readability";
import {
Injectable,
HttpException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { chromium } from "playwright";
import type { BrowserContext } from "playwright";
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import type { BrowserContext, Cookie } from "playwright";
import { chromium } from "playwright";
import type {
ExecResult,
ScriptLogger,
} from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import type { ExecResult } from "../code-executor/code-executor.service";
import type { Cookie } from "playwright";
import { SnippetService } from "../snippet/snippet.service";
export type { ExecResult } from "../code-executor/code-executor.service";
@@ -30,6 +34,7 @@ export class BrowserService {
private readonly sessionContextService: SessionContextService,
private readonly sessionService: SessionService,
private readonly codeExecutor: CodeExecutorService,
private readonly snippetService: SnippetService,
) {}
private parseCookies(raw: string | null | undefined): Cookie[] {
@@ -164,20 +169,34 @@ export class BrowserService {
sessionName: string | undefined,
code: string,
url?: string,
environment?: EnvironmentData,
credentials?: Record<string, unknown>,
): Promise<ExecResult> {
const label = sessionName ?? "anonymous";
if (sessionName) {
const { page, context } =
await this.getOrCreateNamedHandle(sessionName);
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
this.logger.log(`[${label}] exec: using persistent context`);
const snippets = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
try {
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
await page.goto(url, { waitUntil: "networkidle" });
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: context,
code,
log: scriptLogger,
credentials,
environment,
snippets,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
@@ -186,13 +205,20 @@ export class BrowserService {
}
// Anonymous — ephemeral browser
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
// instead of launching a new browser for each request.
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
@@ -200,7 +226,17 @@ export class BrowserService {
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: browserContext,
code,
log: scriptLogger,
credentials,
environment,
snippets: snippetMap,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
+21 -3
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsUrl } from "class-validator";
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
export class ExecDto {
@ApiPropertyOptional({
@@ -22,9 +22,27 @@ export class ExecDto {
@ApiProperty({
description:
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
example: "return await page.title();",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
example: "return await context.page.title();",
})
@IsString()
code: string;
@ApiPropertyOptional({
description:
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
})
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({
description:
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
})
@IsOptional()
@IsObject()
credentials?: Record<string, string>;
}
@@ -3,12 +3,13 @@ import {
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { expect as playwrightExpect } from "@playwright/test";
import { dumpDom } from "./dom-helpers";
import { parse } from "acorn";
import type { BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import type { DomNode } from "./dom-helpers";
import { dumpDom } from "./dom-helpers";
export interface ExecResult {
result: unknown;
@@ -19,6 +20,41 @@ export type ScriptLogger = (
message: string,
) => void;
/** The `context` object available inside user scripts as the sole argument. */
export interface ScriptContext {
/** Playwright Page for the current session. */
page: Page;
/** Playwright BrowserContext for the current session. */
browser: BrowserContext;
/** All environment values for the current run (empty object if none set). */
env: Record<string, string | undefined>;
/** Returns the environment value for `key`, or throws if not defined. */
getEnv: (key: string) => string;
/** Returns the credential value for `alias`, or throws if not found. */
getCredential: (alias: string) => unknown;
/** Returns the serialised output of a previous step by order index (negative = relative). */
getStepOutput: (order: number) => Promise<unknown>;
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
dumpDom: (selector?: string) => Promise<DomNode>;
log: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
/** Runs a named snippet with the same context, plus any extra positional args. */
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
}
export interface ExecContext {
page: Page;
browser: BrowserContext;
code: string;
log?: ScriptLogger;
getStepOutput?: (order: number) => Promise<unknown>;
credentials?: Record<string, unknown>;
environment?: EnvironmentData | null;
snippets?: Record<string, string> | null;
result?: unknown;
}
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
@@ -28,7 +64,7 @@ export class CodeExecutorService {
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
const wrapped = `async function __validate__(context) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
@@ -40,20 +76,22 @@ export class CodeExecutorService {
}
/**
* Executes `code` as an async function body with `page` and `context` in
* scope. Always call `validate()` before this method.
* Executes `code` as an async function body with a single `context` argument
* that exposes page, browser, env helpers, credentials, snippets, and logging.
* Always call `validate()` before this method.
*/
async execute(
page: Page,
context: BrowserContext,
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentData | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
async execute(ctx: ExecContext): Promise<ExecResult> {
const {
page,
browser,
code,
log,
getStepOutput,
credentials,
environment,
snippets,
result,
} = ctx;
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
const toStr = (args: unknown[]) =>
@@ -65,9 +103,8 @@ export class CodeExecutorService {
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
let pageHelpers: Record<string, unknown>;
// scriptContext is referenced by runSnippet, so we declare it first.
let scriptContext: ScriptContext;
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
@@ -78,7 +115,9 @@ export class CodeExecutorService {
};
try {
pageHelpers = {
scriptContext = {
page,
browser,
dumpDom: (selector?: string) => dumpDom(page, selector),
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
@@ -92,10 +131,8 @@ export class CodeExecutorService {
}
return credMap[alias];
},
/** All values defined for the current environment (may be empty if no environment is set). */
env: { ...envData },
/** Returns the value for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
getEnv: (key: string): string => {
const value = envData[key];
if (value == null) {
throw new Error(
@@ -104,12 +141,6 @@ export class CodeExecutorService {
}
return value;
},
/**
* Runs a snippet by alias. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (
alias: string,
...args: unknown[]
@@ -119,40 +150,28 @@ export class CodeExecutorService {
throw new Error(`Snippet alias "${alias}" not found`);
}
const snippetFn = new Function(
"page",
"context",
"helpers",
"console",
"snippetArgs",
"expect",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
);
return snippetFn(
page,
context,
pageHelpers,
fakeConsole,
args,
playwrightExpect,
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
);
return snippetFn(scriptContext, fakeConsole, args, playwrightExpect);
},
};
// Passing `console` and `expect` as named parameters exposes them in script scope.
// `console`, `result`, and `expect` are injected as named parameters so
// existing scripts that reference them directly still work.
const fn = new Function(
"page",
"context",
"helpers",
"console",
"result",
"expect",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
`return (async (context) => { ${code} })(context)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(
page,
context,
pageHelpers,
scriptContext,
fakeConsole,
result,
playwrightExpect,
@@ -0,0 +1,61 @@
import type { BrowserContext, Page } from "playwright";
import type { EnvironmentData } from "../environment/environment.entity";
import type { ExecContext, ScriptLogger } from "./code-executor.service";
export class ExecContextBuilder {
private readonly ctx: Partial<ExecContext> = {};
page(page: Page): this {
this.ctx.page = page;
return this;
}
browser(browser: BrowserContext): this {
this.ctx.browser = browser;
return this;
}
code(code: string): this {
this.ctx.code = code;
return this;
}
log(log: ScriptLogger): this {
this.ctx.log = log;
return this;
}
getStepOutput(fn: (order: number) => Promise<unknown>): this {
this.ctx.getStepOutput = fn;
return this;
}
credentials(credentials: Record<string, unknown>): this {
this.ctx.credentials = credentials;
return this;
}
environment(environment: EnvironmentData | null): this {
this.ctx.environment = environment;
return this;
}
snippets(snippets: Record<string, string> | null): this {
this.ctx.snippets = snippets;
return this;
}
result(result: unknown): this {
this.ctx.result = result;
return this;
}
build(): ExecContext {
if (!this.ctx.page) throw new Error("ExecContextBuilder: page is required");
if (!this.ctx.browser)
throw new Error("ExecContextBuilder: browser is required");
if (this.ctx.code === undefined)
throw new Error("ExecContextBuilder: code is required");
return this.ctx as ExecContext;
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
import { IsInt, IsString, Min, Max } from "class-validator";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import { IsInt, IsString, Max, Min, validateSync } from "class-validator";
import pkg from "../../package.json";
@@ -11,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { CredentialOrderBy } from "./credential.service";
import { CredentialOrderBy, CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
@ApiTags("credentials")
@Controller("credentials")
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { CredentialController } from "./credential.controller";
import { CredentialEntity } from "./credential.entity";
import { CredentialService } from "./credential.service";
import { CredentialController } from "./credential.controller";
@Module({
imports: [TypeOrmModule.forFeature([CredentialEntity])],
+5 -5
View File
@@ -1,14 +1,14 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "./credential.entity";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
export type CredentialOrderBy =
| "id"
@@ -11,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
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";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentOrderBy, EnvironmentService } from "./environment.service";
@ApiTags("environments")
@Controller("environments")
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { EnvironmentController } from "./environment.controller";
import { EnvironmentEntity } from "./environment.entity";
import { EnvironmentService } from "./environment.service";
import { EnvironmentController } from "./environment.controller";
@Module({
imports: [TypeOrmModule.forFeature([EnvironmentEntity])],
@@ -5,14 +5,14 @@ import {
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { EnvironmentEntity } from "./environment.entity";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentEntity } from "./environment.entity";
export type EnvironmentOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -75,7 +75,9 @@ export class EnvironmentService {
};
}
async importEnvironment(dto: EnvironmentExportDto): Promise<EnvironmentEntity> {
async importEnvironment(
dto: EnvironmentExportDto,
): Promise<EnvironmentEntity> {
if (dto.id) {
const existing = await this.repo.findOneBy({ id: dto.id });
if (existing) {
+1 -1
View File
@@ -6,8 +6,8 @@ import {
HttpException,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { TraceLogger } from "../common/trace-logger";
@Catch(BadRequestException, InternalServerErrorException)
export class HttpExceptionFilter implements ExceptionFilter {
@@ -4,9 +4,9 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger";
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
+1 -1
View File
@@ -4,8 +4,8 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import type { Request } from "express";
import * as crypto from "crypto";
import type { Request } from "express";
import { Observable } from "rxjs";
import { traceStorage } from "../common/trace-context";
+9 -12
View File
@@ -1,14 +1,14 @@
import { NestFactory } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "./config/app.config";
import { RequestMethod, ValidationPipe } from "@nestjs/common";
import { TraceLogger } from "./common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { TraceInterceptor } from "./interceptors/trace.interceptor";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { name as pkgName, version as pkgVersion } from "../package.json";
import { AppModule } from "./app.module";
import { TraceLogger } from "./common/trace-logger";
import { AppConfig } from "./config/app.config";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { TraceInterceptor } from "./interceptors/trace.interceptor";
async function bootstrap() {
const API_PREFIX = "api/v1";
@@ -34,10 +34,7 @@ async function bootstrap() {
const nodeEnv = config.get("NODE_ENV");
app.enableCors({
origin: [
"http://localhost:5173",
"http://127.0.0.1:5173",
],
origin: ["http://localhost:5173", "http://127.0.0.1:5173"],
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
credentials: true,
});
+6 -4
View File
@@ -1,16 +1,18 @@
import { Module } from "@nestjs/common";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { BrowserModule } from "../browser/browser.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialModule } from "../credential/credential.module";
import { EnvironmentModule } from "../environment/environment.module";
import { ScenarioModule } from "../scenario/scenario.module";
import { SessionModule } from "../session/session.module";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
@Module({
imports: [
SessionModule,
EnvironmentModule,
CredentialModule,
BrowserModule,
CodeExecutorModule,
ScenarioModule,
+210 -28
View File
@@ -7,6 +7,7 @@ import { SessionService } from "../session/session.service";
import { SessionContextService } from "../session/session-context.service";
import { EnvironmentService } from "../environment/environment.service";
import type { EnvironmentData } from "../environment/environment.entity";
import { CredentialService } from "../credential/credential.service";
import { BrowserService } from "../browser/browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "../scenario/scenario.service";
@@ -19,6 +20,7 @@ export class McpService {
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly environmentService: EnvironmentService,
private readonly credentialService: CredentialService,
private readonly browserService: BrowserService,
private readonly codeExecutor: CodeExecutorService,
private readonly scenarioService: ScenarioService,
@@ -86,7 +88,7 @@ export class McpService {
{
description: "Delete a session by numeric ID (closes it first if open)",
inputSchema: {
id: z.string().uuid().describe("Session ID to delete"),
id: z.uuid().describe("Session ID to delete"),
},
},
async ({ id }) => {
@@ -151,7 +153,7 @@ export class McpService {
{
description: "Get an environment record by ID",
inputSchema: {
id: z.string().uuid().describe("Environment ID"),
id: z.uuid().describe("Environment ID"),
},
},
async ({ id }) => {
@@ -207,7 +209,7 @@ export class McpService {
{
description: "Update an existing environment (name and/or data)",
inputSchema: {
id: z.string().uuid().describe("Environment ID to update"),
id: z.uuid().describe("Environment ID to update"),
name: z.string().optional().describe("New name"),
data: z
.record(z.string(), z.string())
@@ -238,7 +240,7 @@ export class McpService {
{
description: "Delete an environment by ID",
inputSchema: {
id: z.string().uuid().describe("Environment ID to delete"),
id: z.uuid().describe("Environment ID to delete"),
},
},
async ({ id }) => {
@@ -309,7 +311,7 @@ export class McpService {
"exec_code",
{
description:
"Execute arbitrary Playwright JavaScript with `page` and `context` in scope",
"Execute Playwright JS — script receives a single `context` argument (see scenario.md). Use `environmentId` (UUID) and `credentials` (alias → credential UUID) to resolve data from the DB and enable context.getEnv() / context.getCredential() / context.runSnippet().",
inputSchema: {
sessionName: z
.string()
@@ -320,19 +322,56 @@ export class McpService {
code: z
.string()
.describe(
"JavaScript code body to execute (async-safe, may use `page` and `context`)",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
),
url: z
.string()
.url()
.optional()
.describe("Optional URL to navigate to before running code"),
environmentId: z
.string()
.uuid()
.optional()
.describe(
"UUID of an existing environment entity. Its key/value data is available via context.env and context.getEnv().",
),
credentials: z
.record(z.string(), z.string())
.optional()
.describe(
"Map of alias → credential UUID. Each credential is loaded from the DB and available via context.getCredential(alias).",
),
},
},
async ({ sessionName, code, url }) => {
async ({ sessionName, code, url, environmentId, credentials }) => {
try {
this.codeExecutor.validate(code);
const result = await this.browserService.exec(sessionName, code, url);
let environment: EnvironmentData | undefined;
if (environmentId) {
const env = await this.environmentService.findOne(environmentId);
environment = env.data;
}
let resolvedCredentials: Record<string, unknown> | undefined;
if (credentials && Object.keys(credentials).length > 0) {
resolvedCredentials = {};
for (const [alias, credId] of Object.entries(credentials)) {
const cred = await this.credentialService.findOne(credId);
resolvedCredentials[alias] = cred.data
? JSON.parse(cred.data)
: {};
}
}
const result = await this.browserService.exec(
sessionName,
code,
url,
environment,
resolvedCredentials,
);
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
@@ -392,7 +431,7 @@ export class McpService {
{
description: "Get a scenario with its steps by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -442,7 +481,7 @@ export class McpService {
{
description: "Update a scenario name",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
name: z.string().optional().describe("New name"),
},
},
@@ -468,7 +507,7 @@ export class McpService {
{
description: "Delete a scenario by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID"),
id: z.uuid().describe("Scenario ID"),
},
},
async ({ id }) => {
@@ -493,7 +532,7 @@ export class McpService {
{
description: "Add a step to a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Parent scenario ID"),
scenarioId: z.uuid().describe("Parent scenario ID"),
order: z
.number()
.int()
@@ -527,8 +566,8 @@ export class McpService {
{
description: "Get a single step of a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -551,8 +590,8 @@ export class McpService {
{
description: "Update a step within a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
order: z
.number()
.int()
@@ -591,8 +630,8 @@ export class McpService {
{
description: "Delete a step from a scenario",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
stepId: z.string().uuid().describe("Step ID"),
scenarioId: z.uuid().describe("Scenario ID"),
stepId: z.uuid().describe("Step ID"),
},
},
async ({ scenarioId, stepId }) => {
@@ -621,7 +660,7 @@ export class McpService {
description:
"List runs for a scenario (paginated, optionally filtered by status)",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
scenarioId: z.uuid().describe("Scenario ID"),
status: z
.enum(["pending", "in_progress", "pass", "fail"])
.optional()
@@ -664,16 +703,23 @@ export class McpService {
{
description: "Trigger an immediate run of a scenario by ID",
inputSchema: {
id: z.string().uuid().describe("Scenario ID to run"),
id: z.uuid().describe("Scenario ID to run"),
environmentId: z
.string()
.uuid()
.describe("Environment ID to run the scenario in"),
saveSession: z
.boolean()
.optional()
.describe("Save session after run completes"),
},
},
async ({ id, environmentId }) => {
async ({ id, environmentId, saveSession }) => {
try {
const run = await this.scenarioService.createRun(id, environmentId);
const run = await this.scenarioService.createRun(
id,
environmentId,
saveSession,
);
return {
content: [{ type: "text" as const, text: JSON.stringify(run) }],
};
@@ -692,8 +738,8 @@ export class McpService {
description:
"Get a specific scenario run with all step runs and their outputs",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
scenarioId: z.uuid().describe("Scenario ID"),
runId: z.uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -717,8 +763,8 @@ export class McpService {
description:
"Block until a scenario run reaches pass or fail (max 5 min), then return the full run with step outputs",
inputSchema: {
scenarioId: z.string().uuid().describe("Scenario ID"),
runId: z.string().uuid().describe("Run ID"),
scenarioId: z.uuid().describe("Scenario ID"),
runId: z.uuid().describe("Run ID"),
},
},
async ({ scenarioId, runId }) => {
@@ -736,13 +782,149 @@ export class McpService {
},
);
server.registerTool(
"list_scenario_credentials",
{
description: "List credentials assigned to a scenario",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
},
},
async ({ scenarioId }) => {
try {
const creds =
await this.scenarioService.findScenarioCredentials(scenarioId);
return {
content: [{ type: "text" as const, text: JSON.stringify(creds) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"add_scenario_credential",
{
description:
"Add a credential to a scenario with an alias (used in snippets)",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
credentialId: z.uuid().describe("Credential ID to associate"),
alias: z
.string()
.describe(
"Alias used to reference this credential in step code, e.g. pkcs_key",
),
},
},
async ({ scenarioId, credentialId, alias }) => {
try {
const result = await this.scenarioService.addScenarioCredential(
scenarioId,
{ credentialId, alias },
);
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"remove_scenario_credential",
{
description: "Remove a credential assignment from a scenario",
inputSchema: {
scenarioId: z.uuid().describe("Scenario ID"),
scenarioCredentialId: z
.uuid()
.describe(
"Scenario-credential assignment ID (not the credential ID)",
),
},
},
async ({ scenarioId, scenarioCredentialId }) => {
try {
await this.scenarioService.removeScenarioCredential(
scenarioId,
scenarioCredentialId,
);
return {
content: [
{
type: "text" as const,
text: `Credential assignment ${scenarioCredentialId} removed from scenario ${scenarioId}`,
},
],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"list_all_runs",
{
description:
"List runs across all scenarios (paginated, filterable by status)",
inputSchema: {
status: z
.enum(["pending", "in_progress", "pass", "fail"])
.optional()
.describe("Filter by run status"),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number (default 1)"),
limit: z
.number()
.int()
.min(1)
.optional()
.describe("Items per page (default 20)"),
},
},
async ({ status, page, limit }) => {
try {
const result = await this.scenarioService.findAllRuns({
status,
page,
limit,
});
return {
content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
} catch (err) {
return {
isError: true,
content: [{ type: "text" as const, text: (err as Error).message }],
};
}
},
);
server.registerTool(
"export_scenario",
{
description:
"Export a scenario as a portable JSON payload (name + steps)",
inputSchema: {
id: z.string().uuid().describe("Scenario ID to export"),
id: z.uuid().describe("Scenario ID to export"),
},
},
async ({ id }) => {
@@ -1,7 +1,11 @@
import { IsNotEmpty, IsUUID } from "class-validator";
import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from "class-validator";
export class CreateScenarioRunDto {
@IsUUID()
@IsNotEmpty()
environmentId: string;
@IsBoolean()
@IsOptional()
saveSession?: boolean;
}
@@ -12,5 +12,4 @@ export class CreateScenarioStepDto {
@IsString()
@IsNotEmpty()
execCode?: string;
}
@@ -22,7 +22,6 @@ export class ScenarioStepExportDto {
@IsString()
@IsNotEmpty()
execCode: string | null;
}
export class ScenarioExportDto {
@@ -18,5 +18,4 @@ export class UpdateScenarioStepDto {
@IsString()
@IsNotEmpty()
execCode?: string;
}
@@ -1,5 +1,5 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsNotEmpty } from "class-validator";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class UpdateScenarioDto {
@ApiPropertyOptional({ example: "Updated scenario name" })
@@ -1,14 +1,14 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
Unique,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { CredentialEntity } from "../credential/credential.entity";
import { ScenarioEntity } from "./scenario.entity";
@Entity("scenario_credentials")
@Unique(["scenarioId", "alias"])
@@ -1,13 +1,13 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
export type LogLevel = "log" | "warn" | "error";
@@ -1,11 +1,11 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
+23 -7
View File
@@ -1,15 +1,17 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
JoinColumn,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { SessionEntity } from "../session/session.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioEntity } from "./scenario.entity";
export type RunStatus = "pending" | "in_progress" | "pass" | "fail";
@@ -21,16 +23,30 @@ export class ScenarioRunEntity {
@Column("text")
scenarioId: string;
@Column("text", { default: "" })
environmentId: string;
@Column("text", { nullable: true, default: null })
environmentId: string | null;
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
@JoinColumn({ name: "scenarioId" })
scenario: ScenarioEntity;
@ManyToOne(() => EnvironmentEntity, { onDelete: "SET NULL", nullable: true })
@JoinColumn({ name: "environmentId" })
environment: EnvironmentEntity;
@Column("text", { nullable: true, default: null })
sessionId: string | null;
@ManyToOne(() => SessionEntity, { onDelete: "SET NULL", nullable: true })
@JoinColumn({ name: "sessionId" })
session: SessionEntity | null;
@Column({ type: "text", default: "pending" })
status: RunStatus;
@Column({ type: "boolean", default: false })
saveSession: boolean;
@OneToMany(() => ScenarioRunStepEntity, (rs) => rs.run, {
cascade: true,
eager: false,
@@ -1,21 +1,27 @@
import { Injectable } from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { traceStorage } from "../common/trace-context";
import { Interval } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import * as crypto from "crypto";
import { chromium } from "playwright";
import type { Browser, BrowserContext, Page } from "playwright";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { chromium } from "playwright";
import { Repository } from "typeorm";
import type { ScriptLogger } from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { ScenarioService } from "./scenario.service";
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
import { traceStorage } from "../common/trace-context";
import { TraceLogger } from "../common/trace-logger";
import {
EnvironmentData,
EnvironmentEntity,
} from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { SnippetService } from "../snippet/snippet.service";
import { EnvironmentEntity, EnvironmentData } from "../environment/environment.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioService } from "./scenario.service";
interface BrowserHandle {
browser: Browser;
@@ -47,6 +53,8 @@ export class ScenarioSchedulerService {
private readonly codeExecutor: CodeExecutorService,
private readonly scenarioService: ScenarioService,
private readonly snippetService: SnippetService,
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
) {}
private persistLog(
@@ -72,7 +80,7 @@ export class ScenarioSchedulerService {
): (order: number) => Promise<unknown> {
return async (order: number) => {
const targetOrder = order < 0 ? stepRun.order + order : order;
if (targetOrder < 0) return null;
if (targetOrder < 1) return null;
const sr = await this.runStepRepo.findOne({
where: { runId: stepRun.runId, order: targetOrder },
});
@@ -110,7 +118,7 @@ export class ScenarioSchedulerService {
const environmentData = await this.environmentRepo
.findOneBy({ id: run.environmentId })
.then((env) => env?.data ?? {})
.catch(() => ({} as EnvironmentData));
.catch(() => ({}) as EnvironmentData);
this.runEnvironments.set(run.id, environmentData);
const traceId = crypto.randomUUID();
void traceStorage.run({ traceId }, () =>
@@ -150,6 +158,61 @@ export class ScenarioSchedulerService {
this.runCredentials.delete(runId);
this.runSnippets.delete(runId);
this.runEnvironments.delete(runId);
await this.maybePreserveSession(runId);
}
}
/**
* If the run was created with saveSession=true, promote the run's browser
* context to a named explore session instead of closing it.
*/
private async maybePreserveSession(runId: string): Promise<void> {
const run = await this.runRepo.findOneBy({ id: runId });
if (!run?.saveSession) {
await this.closeBrowserHandle(runId);
return;
}
const handle = this.runBrowsers.get(runId);
if (!handle) {
return;
}
const sessionName = `run-${runId}`;
try {
const cookies = await handle.context.cookies();
const localStorage = await handle.page
.evaluate(() => ({ ...window.localStorage }))
.catch((): Record<string, string> => ({}));
const token =
(localStorage["accessToken"] as string | undefined) ??
(localStorage["token"] as string | undefined) ??
cookies.find((c) => c.name === "token")?.value ??
"";
const session = await this.sessionService.upsert(
sessionName,
token,
cookies,
localStorage,
);
await this.runRepo.update(runId, { sessionId: session.id });
this.sessionContextService.register(
sessionName,
handle.browser,
handle.context,
handle.page,
);
// Remove from runBrowsers so closeBrowserHandle won't close it
this.runBrowsers.delete(runId);
this.logger.log(
`Run #${runId}: browser preserved as session "${sessionName}" (${session.id})`,
);
} catch (err) {
this.logger.warn(
`Run #${runId}: failed to preserve session — ${(err as Error).message}`,
);
await this.closeBrowserHandle(runId);
}
}
@@ -172,16 +235,17 @@ export class ScenarioSchedulerService {
const creds = this.runCredentials.get(stepRun.runId);
const snips = this.runSnippets.get(stepRun.runId);
const env = this.runEnvironments.get(stepRun.runId);
const { result: execOutput } = await this.codeExecutor.execute(
page,
context,
step.execCode,
this.stepLogger(stepRun.id, stepRun.runId),
getStepOutput,
creds,
env,
snips,
);
const execCtx = new ExecContextBuilder()
.page(page)
.browser(context)
.code(step.execCode)
.log(this.stepLogger(stepRun.id, stepRun.runId))
.getStepOutput(getStepOutput)
.credentials(creds)
.environment(env)
.snippets(snips)
.build();
const { result: execOutput } = await this.codeExecutor.execute(execCtx);
await this.passStepRun(stepRun, null, execOutput);
} catch (err) {
@@ -259,7 +323,8 @@ export class ScenarioSchedulerService {
],
});
if (remaining === 0) {
await this.closeBrowserHandle(stepRun.runId);
// Don't close the browser here — maybePreserveSession will handle it
// (either preserving it if saveSession=true, or closing if false)
await this.runRepo.update(stepRun.runId, { status: "pass" });
this.logger.log(`Run #${stepRun.runId} → pass (all steps passed)`);
}
+4 -4
View File
@@ -1,11 +1,11 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
+12 -9
View File
@@ -14,17 +14,16 @@ import {
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Response } from "express";
import { stringify as yamlStringify } from "yaml";
import { ScenarioService } from "./scenario.service";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import { PaginationQueryDto } from "./dto/pagination-query.dto";
import { ScenarioOrderBy } from "./scenario.service";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { CreateScenarioRunDto } from "./dto/create-scenario-run.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { PaginationQueryDto } from "./dto/pagination-query.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { ScenarioOrderBy, ScenarioService } from "./scenario.service";
@ApiTags("scenarios")
@Controller("scenarios")
@@ -215,7 +214,11 @@ export class ScenarioController {
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: CreateScenarioRunDto,
) {
return this.scenarioService.createRun(id, dto.environmentId);
return this.scenarioService.createRun(
id,
dto.environmentId,
dto.saveSession,
);
}
@Get(":id/run/:runId")
+4 -4
View File
@@ -1,13 +1,13 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
@Entity("scenarios")
export class ScenarioEntity {
+11 -11
View File
@@ -1,20 +1,20 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { ScenarioService } from "./scenario.service";
import { ScenarioController } from "./scenario.controller";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioController } from "./scenario.controller";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioService } from "./scenario.service";
@Module({
imports: [
+31 -20
View File
@@ -5,25 +5,25 @@ import {
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Like, Repository } from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "../credential/credential.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
import { CreateScenarioDto } from "./dto/create-scenario.dto";
import { RunsQueryDto } from "./dto/runs-query.dto";
import { ScenarioExportDto } from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
import { ScenarioEntity } from "./scenario.entity";
export { PaginatedResult } from "../common/dto/pagination.dto";
export type ScenarioOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -104,8 +104,8 @@ export class ScenarioService {
});
for (let i = 0; i < ordered.length; i += 1) {
const step = ordered[i];
if (step.order !== i) {
step.order = i;
if (step.order !== i + 1) {
step.order = i + 1;
await this.stepRepo.save(step);
}
}
@@ -120,7 +120,7 @@ export class ScenarioService {
const created = await this.stepRepo.save(
this.stepRepo.create({
...dto,
order: currentCount,
order: currentCount + 1,
scenarioId,
title: dto.title ?? null,
execCode: dto.execCode ?? null,
@@ -322,7 +322,12 @@ export class ScenarioService {
await this.findOne(scenarioId); // 404 guard
const run = await this.runRepo.findOne({
where: { id: runId, scenarioId },
relations: ["stepRuns", "stepRuns.scenarioStep"],
relations: [
"stepRuns",
"stepRuns.scenarioStep",
"environment",
"session",
],
order: { stepRuns: { order: "ASC" } },
});
if (!run)
@@ -359,6 +364,7 @@ export class ScenarioService {
async createRun(
scenarioId: string,
environmentId: string,
saveSession = false,
): Promise<ScenarioRunEntity> {
const scenario = await this.findOne(scenarioId);
const environment = await this.environmentRepo.findOneBy({
@@ -369,7 +375,12 @@ export class ScenarioService {
}
const run = await this.runRepo.save(
this.runRepo.create({ scenarioId, environmentId, status: "pending" }),
this.runRepo.create({
scenarioId,
environmentId,
status: "pending",
saveSession,
}),
);
const stepRuns = scenario.steps.map((step, index) =>
@@ -386,7 +397,7 @@ export class ScenarioService {
return this.runRepo.findOne({
where: { id: run.id },
relations: ["stepRuns"],
relations: ["stepRuns", "environment", "session"],
order: { stepRuns: { order: "ASC" } },
}) as Promise<ScenarioRunEntity>;
}
@@ -1,8 +1,8 @@
import {
Injectable,
OnModuleDestroy,
BadRequestException,
Injectable,
NotFoundException,
OnModuleDestroy,
} from "@nestjs/common";
import type { Browser, BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger";
@@ -1,10 +1,10 @@
import { Injectable } from "@nestjs/common";
import { Interval } from "@nestjs/schedule";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "../config/app.config";
import { Interval } from "@nestjs/schedule";
import { TraceLogger } from "../common/trace-logger";
import { SessionService } from "./session.service";
import { AppConfig } from "../config/app.config";
import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service";
/**
* Periodically:
+2 -3
View File
@@ -9,10 +9,9 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { SessionService } from "./session.service";
import { SessionContextService } from "./session-context.service";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { SessionOrderBy } from "./session.service";
import { SessionContextService } from "./session-context.service";
import { SessionOrderBy, SessionService } from "./session.service";
function maskToken(token: string, head = 6, tail = 4): string {
if (token.length <= head + tail + 1) return token;
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+3 -3
View File
@@ -1,10 +1,10 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { SessionEntity } from "./session.entity";
import { SessionService } from "./session.service";
import { SessionController } from "./session.controller";
import { SessionContextService } from "./session-context.service";
import { SessionSchedulerService } from "./session-scheduler.service";
import { SessionController } from "./session.controller";
import { SessionEntity } from "./session.entity";
import { SessionService } from "./session.service";
@Module({
imports: [TypeOrmModule.forFeature([SessionEntity])],
+4 -4
View File
@@ -1,13 +1,13 @@
import { Injectable, OnApplicationBootstrap } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { LessThan, Repository } from "typeorm";
import { SessionEntity } from "./session.entity";
import { TraceLogger } from "../common/trace-logger";
import type { Cookie } from "playwright";
import { LessThan, Repository } from "typeorm";
import {
PaginationQueryDto,
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { TraceLogger } from "../common/trace-logger";
import { SessionEntity } from "./session.entity";
export type SessionOrderBy =
| "id"
+4 -4
View File
@@ -11,11 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { SnippetService, SnippetOrderBy } from "./snippet.service";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetOrderBy, SnippetService } from "./snippet.service";
@ApiTags("snippets")
@Controller("snippets")
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { SnippetController } from "./snippet.controller";
import { SnippetEntity } from "./snippet.entity";
import { SnippetService } from "./snippet.service";
import { SnippetController } from "./snippet.controller";
@Module({
imports: [TypeOrmModule.forFeature([SnippetEntity])],
+17 -8
View File
@@ -6,16 +6,21 @@ import {
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { SnippetEntity } from "./snippet.entity";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetEntity } from "./snippet.entity";
export type SnippetOrderBy = "id" | "alias" | "title" | "createdAt" | "updatedAt";
export type SnippetOrderBy =
| "id"
| "alias"
| "title"
| "createdAt"
| "updatedAt";
@Injectable()
export class SnippetService implements OnModuleInit {
@@ -47,7 +52,9 @@ export class SnippetService implements OnModuleInit {
async create(dto: CreateSnippetDto): Promise<SnippetEntity> {
const existing = await this.repo.findOneBy({ alias: dto.alias });
if (existing) {
throw new ConflictException(`Snippet alias "${dto.alias}" already exists`);
throw new ConflictException(
`Snippet alias "${dto.alias}" already exists`,
);
}
return this.repo.save(
this.repo.create({
@@ -85,7 +92,9 @@ export class SnippetService implements OnModuleInit {
if (dto.alias && dto.alias !== snippet.alias) {
const conflict = await this.repo.findOneBy({ alias: dto.alias });
if (conflict)
throw new ConflictException(`Snippet alias "${dto.alias}" already exists`);
throw new ConflictException(
`Snippet alias "${dto.alias}" already exists`,
);
}
Object.assign(snippet, dto);
return this.repo.save(snippet);
+119
View File
@@ -3,6 +3,8 @@ import { getRepositoryToken } from "@nestjs/typeorm";
import request from "supertest";
import { buildTestApp } from "./app.harness";
import { SessionEntity } from "../src/session/session.entity";
import { EnvironmentEntity } from "../src/environment/environment.entity";
import { CredentialEntity } from "../src/credential/credential.entity";
import { Repository } from "typeorm";
/**
@@ -15,6 +17,8 @@ import { Repository } from "typeorm";
describe("BrowserController", () => {
let app: INestApplication;
let sessionRepo: Repository<SessionEntity>;
let environmentRepo: Repository<EnvironmentEntity>;
let credentialRepo: Repository<CredentialEntity>;
const FAKE_SESSION = "test-browser-session";
@@ -23,6 +27,12 @@ describe("BrowserController", () => {
sessionRepo = app.get<Repository<SessionEntity>>(
getRepositoryToken(SessionEntity),
);
environmentRepo = app.get<Repository<EnvironmentEntity>>(
getRepositoryToken(EnvironmentEntity),
);
credentialRepo = app.get<Repository<CredentialEntity>>(
getRepositoryToken(CredentialEntity),
);
// Seed a session with minimal but valid JSON so the browser code can
// deserialise it (it will still fail to open a real page, tested separately)
@@ -40,6 +50,33 @@ describe("BrowserController", () => {
await app.close();
});
async function createEnvironment(
data: Record<string, string | undefined>,
name = `browser-env-${Math.random().toString(36).slice(2, 8)}`,
): Promise<string> {
const environment = await environmentRepo.save(
environmentRepo.create({
name,
data,
}),
);
return environment.id;
}
async function createCredential(
data: Record<string, unknown>,
name = `browser-cred-${Math.random().toString(36).slice(2, 8)}`,
): Promise<string> {
const credential = await credentialRepo.save(
credentialRepo.create({
name,
data: JSON.stringify(data),
lastUsedAt: null,
}),
);
return credential.id;
}
// ── POST /open ─────────────────────────────────────────────────────────────
describe("POST /open", () => {
@@ -135,5 +172,87 @@ describe("BrowserController", () => {
.expect(201);
expect(res.body).toEqual({ result: 42 });
});
it("exposes environment via context.env in a named session", async () => {
const environmentId = await createEnvironment({
BASE_URL: "https://env.example.com",
});
const res = await request(app.getHttpServer())
.post("/exec")
.send({
sessionName: "no-such-session",
code: "return context.env.BASE_URL;",
environmentId,
})
.expect(201);
expect(res.body).toEqual({ result: "https://env.example.com" });
});
it("exposes environment via context.env in a sessionless exec", async () => {
const environmentId = await createEnvironment({ KEY: "value123" });
const res = await request(app.getHttpServer())
.post("/exec")
.send({
code: "return context.env.KEY;",
environmentId,
})
.expect(201);
expect(res.body).toEqual({ result: "value123" });
});
it("exposes credentials via context.getCredential in a named session", async () => {
const credentialId = await createCredential({
username: "user1",
password: "pass1",
});
const res = await request(app.getHttpServer())
.post("/exec")
.send({
sessionName: "no-such-session",
code: "return context.getCredential('admin');",
credentials: { admin: credentialId },
})
.expect(201);
expect(res.body).toEqual({
result: { username: "user1", password: "pass1" },
});
});
it("exposes credentials via context.getCredential in a sessionless exec", async () => {
const credentialId = await createCredential({ token: "abc" });
const res = await request(app.getHttpServer())
.post("/exec")
.send({
code: "return context.getCredential('svc');",
credentials: { svc: credentialId },
})
.expect(201);
expect(res.body).toEqual({ result: { token: "abc" } });
});
it("throws when getCredential is called with an unknown alias", async () => {
const res = await request(app.getHttpServer())
.post("/exec")
.send({
code: "return context.getCredential('missing');",
credentials: {},
})
.expect(500);
expect(res.body.message).toMatch(/missing/);
});
it("environment and credentials default to empty when omitted", async () => {
const res = await request(app.getHttpServer())
.post("/exec")
.send({
code: "return Object.keys(context.env).length === 0 ? 'empty' : 'not-empty';",
})
.expect(201);
expect(res.body).toEqual({ result: "empty" });
});
});
});
+3 -1
View File
@@ -160,7 +160,9 @@ describe("EnvironmentController", () => {
});
it("returns 404 for unknown id", async () => {
await request(app.getHttpServer()).get("/environments/00000000-0000-0000-0000-000000000001").expect(404);
await request(app.getHttpServer())
.get("/environments/00000000-0000-0000-0000-000000000001")
.expect(404);
});
it("returns 400 for non-numeric id", async () => {
+4 -1
View File
@@ -75,7 +75,10 @@ describe("McpController", () => {
it("returns MCP error for removed tool", async () => {
const { status, rpc } = await mcpCall("list_keys");
expect(status).toBe(200);
const result = rpc.result as { isError: boolean; content?: { text: string }[] };
const result = rpc.result as {
isError: boolean;
content?: { text: string }[];
};
expect(result.isError).toBe(true);
});
});
+10 -10
View File
@@ -1,6 +1,6 @@
/**
* Integration tests for ScenarioRunStepEntity.output column and the
* helpers.getStepOutput() API available inside exec step scripts.
* context.getStepOutput() API available inside exec step scripts.
*
* Strategy:
* - Seed a session row so the scheduler can create a browser context.
@@ -17,7 +17,7 @@ import { ScenarioService } from "../src/scenario/scenario.service";
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
import { EnvironmentEntity } from "../src/environment/environment.entity";
describe("ScenarioRunStepEntity.output + helpers.getStepOutput", () => {
describe("ScenarioRunStepEntity.output + context.getStepOutput", () => {
let app: INestApplication;
let dataSource: DataSource;
let scenarioService: ScenarioService;
@@ -135,15 +135,15 @@ describe("ScenarioRunStepEntity.output + helpers.getStepOutput", () => {
});
});
// ── helpers.getStepOutput ──────────────────────────────────────────────────
// ── context.getStepOutput ──────────────────────────────────────────────────
describe("helpers.getStepOutput()", () => {
describe("context.getStepOutput()", () => {
it("returns output of a previous step by absolute order", async () => {
await seedSession();
const scId = await createScenario("getStepOutput-absolute");
await createStep(scId, 0, "return 99;");
// Step 1 reads step 0's output via absolute index 0
await createStep(scId, 1, "return await helpers.getStepOutput(0);");
// Step 1 reads step 1's output via absolute index 1 (1-based)
await createStep(scId, 1, "return await context.getStepOutput(1);");
const runId = await runScenario(scId);
const rows = await dataSource.query(
@@ -159,7 +159,7 @@ describe("ScenarioRunStepEntity.output + helpers.getStepOutput", () => {
const scId = await createScenario("getStepOutput-relative");
await createStep(scId, 0, 'return "step-zero";');
// Step 1 uses relative index -1 to reference step 0
await createStep(scId, 1, "return await helpers.getStepOutput(-1);");
await createStep(scId, 1, "return await context.getStepOutput(-1);");
const runId = await runScenario(scId);
const rows = await dataSource.query(
@@ -173,7 +173,7 @@ describe("ScenarioRunStepEntity.output + helpers.getStepOutput", () => {
await seedSession();
const scId = await createScenario("getStepOutput-missing");
// Step 0 tries to read step order 99 which does not exist
await createStep(scId, 0, "return await helpers.getStepOutput(99);");
await createStep(scId, 0, "return await context.getStepOutput(99);");
const runId = await runScenario(scId);
const row = await dataSource.query(
@@ -190,12 +190,12 @@ describe("ScenarioRunStepEntity.output + helpers.getStepOutput", () => {
await createStep(
scId,
1,
"const prev = await helpers.getStepOutput(-1); return [...prev, 3];",
"const prev = await context.getStepOutput(-1); return [...prev, 3];",
);
await createStep(
scId,
2,
"const prev = await helpers.getStepOutput(-1); return [...prev, 4];",
"const prev = await context.getStepOutput(-1); return [...prev, 4];",
);
const runId = await runScenario(scId);
+48 -31
View File
@@ -163,7 +163,9 @@ describe("ScenarioController", () => {
});
it("returns 404 for unknown id", async () => {
await request(app.getHttpServer()).get("/scenarios/00000000-0000-0000-0000-000000000001").expect(404);
await request(app.getHttpServer())
.get("/scenarios/00000000-0000-0000-0000-000000000001")
.expect(404);
});
});
@@ -199,7 +201,9 @@ describe("ScenarioController", () => {
});
it("returns 404 for unknown id", async () => {
await request(app.getHttpServer()).delete("/scenarios/00000000-0000-0000-0000-000000000001").expect(404);
await request(app.getHttpServer())
.delete("/scenarios/00000000-0000-0000-0000-000000000001")
.expect(404);
});
});
@@ -216,7 +220,7 @@ describe("ScenarioController", () => {
.expect(201);
expect(res.body.id).toBeDefined();
expect(res.body.order).toBe(0);
expect(res.body.order).toBe(1);
});
it("creates a step without execCode", async () => {
@@ -274,7 +278,7 @@ describe("ScenarioController", () => {
.expect(200);
const orders = res.body.steps.map((s: { order: number }) => s.order);
expect(orders).toEqual([0, 1, 2]);
expect(orders).toEqual([1, 2, 3]);
});
});
@@ -327,8 +331,8 @@ describe("ScenarioController", () => {
it("reorders by exact target index", async () => {
const sc = await createScenario();
const stepA = await createStep(sc.id, { title: "A" });
const stepB = await createStep(sc.id, { title: "B" });
const stepC = await createStep(sc.id, { title: "C" });
await createStep(sc.id, { title: "B" });
await createStep(sc.id, { title: "C" });
const stepD = await createStep(sc.id, { title: "D" });
await request(app.getHttpServer())
@@ -339,12 +343,15 @@ describe("ScenarioController", () => {
let res = await request(app.getHttpServer())
.get(`/scenarios/${sc.id}`)
.expect(200);
expect(
res.body.steps.map((s: { title: string }) => s.title),
).toEqual(["B", "C", "A", "D"]);
expect(
res.body.steps.map((s: { order: number }) => s.order),
).toEqual([0, 1, 2, 3]);
expect(res.body.steps.map((s: { title: string }) => s.title)).toEqual([
"B",
"C",
"A",
"D",
]);
expect(res.body.steps.map((s: { order: number }) => s.order)).toEqual([
0, 1, 2, 3,
]);
await request(app.getHttpServer())
.patch(`/scenarios/${sc.id}/steps/${stepD.id}`)
@@ -354,12 +361,15 @@ describe("ScenarioController", () => {
res = await request(app.getHttpServer())
.get(`/scenarios/${sc.id}`)
.expect(200);
expect(
res.body.steps.map((s: { title: string }) => s.title),
).toEqual(["D", "B", "C", "A"]);
expect(
res.body.steps.map((s: { order: number }) => s.order),
).toEqual([0, 1, 2, 3]);
expect(res.body.steps.map((s: { title: string }) => s.title)).toEqual([
"D",
"B",
"C",
"A",
]);
expect(res.body.steps.map((s: { order: number }) => s.order)).toEqual([
0, 1, 2, 3,
]);
});
});
@@ -395,9 +405,7 @@ describe("ScenarioController", () => {
expect(Array.isArray(res.stepRuns)).toBe(true);
expect(res.stepRuns).toHaveLength(3);
const statuses = res.stepRuns.map(
(s: { status: string }) => s.status,
);
const statuses = res.stepRuns.map((s: { status: string }) => s.status);
expect(statuses[0]).toBe("pending");
expect(statuses[1]).toBe("waiting");
expect(statuses[2]).toBe("waiting");
@@ -495,9 +503,18 @@ describe("ScenarioController", () => {
it("exports steps ordered by sequential position", async () => {
const sc = await createScenario("export-order");
await createStep(sc.id, { sessionName: "s", execCode: "return 'first';" });
await createStep(sc.id, { sessionName: "s", execCode: "return 'second';" });
await createStep(sc.id, { sessionName: "s", execCode: "return 'third';" });
await createStep(sc.id, {
sessionName: "s",
execCode: "return 'first';",
});
await createStep(sc.id, {
sessionName: "s",
execCode: "return 'second';",
});
await createStep(sc.id, {
sessionName: "s",
execCode: "return 'third';",
});
const res = await request(app.getHttpServer())
.get(`/scenarios/${sc.id}/export`)
@@ -573,7 +590,7 @@ describe("ScenarioController", () => {
expect(res.body.name).toBe("imported scenario");
expect(res.body.steps).toHaveLength(3);
expect(res.body.steps.map((s: { order: number }) => s.order)).toEqual([
0, 1, 2,
1, 2, 3,
]);
});
@@ -616,9 +633,7 @@ describe("ScenarioController", () => {
expect(importRes.body.name).toBe("roundtrip");
expect(importRes.body.steps).toHaveLength(1);
expect(importRes.body.steps[0].execCode).toBe(
exported.steps[0].execCode,
);
expect(importRes.body.steps[0].execCode).toBe(exported.steps[0].execCode);
});
it("imports with empty steps array", async () => {
@@ -663,7 +678,7 @@ describe("ScenarioController", () => {
const sc = await createScenario();
await createStep(sc.id, { order: 0 });
const runRes = await createRun(sc.id);
const runId = runRes.id;
const runId = runRes.id;
const res = await request(app.getHttpServer())
.get(`/scenarios/${sc.id}/run/${runId}`)
@@ -689,7 +704,7 @@ describe("ScenarioController", () => {
.expect(200);
const orders = res.body.stepRuns.map((s: { order: number }) => s.order);
expect(orders).toEqual([0, 1, 2]);
expect(orders).toEqual([1, 2, 3]);
});
it("returns 404 for unknown run", async () => {
@@ -766,7 +781,9 @@ describe("ScenarioController", () => {
it("returns 404 for unknown run", async () => {
const sc = await createScenario();
await request(app.getHttpServer())
.post(`/scenarios/${sc.id}/run/00000000-0000-0000-0000-000000000001/wait`)
.post(
`/scenarios/${sc.id}/run/00000000-0000-0000-0000-000000000001/wait`,
)
.expect(404);
});
+3 -1
View File
@@ -141,7 +141,9 @@ describe("SessionController", () => {
});
it("returns 404 for unknown id", async () => {
await request(app.getHttpServer()).delete("/sessions/00000000-0000-0000-0000-000000000001").expect(404);
await request(app.getHttpServer())
.delete("/sessions/00000000-0000-0000-0000-000000000001")
.expect(404);
});
it("returns 400 for non-numeric id", async () => {