Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c6158e8e3 | ||
|
|
b4cfe050fa | ||
|
|
a199700878 | ||
|
|
2a46b355db | ||
|
|
a50dce2755 | ||
|
|
8dbd319bba | ||
|
|
67e230a647 | ||
|
|
ad155e269c | ||
|
|
f268d0e3eb | ||
|
|
a779ab4667 | ||
|
|
e6aacc899d |
No files matched your search
@@ -13,3 +13,11 @@ client/dist
|
||||
*storybook.log
|
||||
storybook-static
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
# organization
|
||||
TODO.md
|
||||
|
||||
# IDE/editor
|
||||
.vscode/
|
||||
.idea/
|
||||
.github/
|
||||
+37
-15
@@ -133,13 +133,13 @@ export const environments = {
|
||||
get(id: string): Promise<Environment> {
|
||||
return request(`/environments/${id}`);
|
||||
},
|
||||
create(name: string, data: Environment['data']): Promise<Environment> {
|
||||
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
|
||||
return request('/environments', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, data }),
|
||||
body: JSON.stringify({ name, description, data }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>): Promise<Environment> {
|
||||
return request(`/environments/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -162,8 +162,8 @@ export const environments = {
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const sessions = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}`);
|
||||
list(page = 1, limit = 50, orderBy = 'id', orderDir: 'ASC' | 'DESC' = 'DESC'): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(id: string): Promise<Session> {
|
||||
return request(`/sessions/${id}`);
|
||||
@@ -176,19 +176,24 @@ export const sessions = {
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarios = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'updatedAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
|
||||
return request(`/scenarios/${id}`);
|
||||
},
|
||||
create(name: string): Promise<Scenario> {
|
||||
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
|
||||
return request('/scenarios', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name }),
|
||||
body: JSON.stringify({ name, description, environmentId }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
|
||||
update(id: string, patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>): Promise<Scenario> {
|
||||
return request(`/scenarios/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -216,8 +221,19 @@ export const scenarios = {
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
},
|
||||
exportScenario(id: string): Promise<string> {
|
||||
return request(`/scenarios/${id}/export`);
|
||||
exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] } = {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
},
|
||||
): Promise<string> {
|
||||
const params = new URLSearchParams();
|
||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||
for (const cid of options.credentialIds) {
|
||||
params.append('credentialIds', cid);
|
||||
}
|
||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||
},
|
||||
importScenario(payload: unknown): Promise<Scenario> {
|
||||
return request('/scenarios/import', {
|
||||
@@ -234,12 +250,14 @@ export const runs = {
|
||||
page = 1,
|
||||
limit = 20,
|
||||
status?: string,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<
|
||||
PaginatedResponse<
|
||||
ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }
|
||||
ScenarioRun & { scenario: { id: string; name: string } }
|
||||
>
|
||||
> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
|
||||
if (status) q.set('status', status);
|
||||
return request(`/scenarios/runs?${q}`);
|
||||
},
|
||||
@@ -247,8 +265,10 @@ export const runs = {
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
|
||||
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
|
||||
@@ -279,12 +299,14 @@ export const scenarioCredentials = {
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export const steps = {
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface EnvironmentData {
|
||||
export interface Environment {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
data: EnvironmentData;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -66,6 +67,7 @@ export interface ScenarioStep {
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -82,6 +84,10 @@ export interface ScenarioCredential {
|
||||
export interface Scenario {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
environmentId?: string | null;
|
||||
timeoutSeconds?: number | null;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
steps?: ScenarioStep[];
|
||||
scenarioCredentials?: ScenarioCredential[];
|
||||
createdAt: string;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
.exportModal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.scenarioMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-primary);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.metaLabel {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-primary-fg);
|
||||
opacity: 0.7;
|
||||
min-width: 4rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.metaValue {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-primary-fg);
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.checkboxRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkboxRow input[type='checkbox'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Upload } from 'lucide-react';
|
||||
import { Modal, Button, UuidBadge } from '../../ui';
|
||||
import type { Scenario, ScenarioCredential } from '../../api';
|
||||
import styles from './ExportScenarioModal.module.css';
|
||||
|
||||
export interface ExportScenarioModalProps {
|
||||
open: boolean;
|
||||
scenario: Scenario | null;
|
||||
scenarioCredentials: ScenarioCredential[];
|
||||
environment: Pick<{ id: string; name: string }, 'id' | 'name'> | null;
|
||||
includeEnvironment: boolean;
|
||||
onIncludeEnvironmentChange: (v: boolean) => void;
|
||||
includedCredentialIds: Set<string>;
|
||||
onCredentialToggle: (id: string, checked: boolean) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportScenarioModal({
|
||||
open,
|
||||
scenario,
|
||||
scenarioCredentials,
|
||||
environment,
|
||||
includeEnvironment,
|
||||
onIncludeEnvironmentChange,
|
||||
includedCredentialIds,
|
||||
onCredentialToggle,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.export_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{scenario && (
|
||||
<div className={styles.exportModal}>
|
||||
<div className={styles.scenarioMeta}>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_name')}</span>
|
||||
<span className={styles.metaValue}>{scenario.name}</span>
|
||||
</div>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_id')}</span>
|
||||
<span className={styles.metaValue}>
|
||||
<UuidBadge id={scenario.id} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{environment && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_environment')}</h4>
|
||||
<label className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeEnvironment}
|
||||
onChange={(e) => onIncludeEnvironmentChange(e.target.checked)}
|
||||
/>
|
||||
<span>{environment.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenarioCredentials.length > 0 && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_credentials')}</h4>
|
||||
{scenarioCredentials.map((sc) => (
|
||||
<label key={sc.credentialId} className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includedCredentialIds.has(sc.credentialId)}
|
||||
onChange={(e) => onCredentialToggle(sc.credentialId, e.target.checked)}
|
||||
/>
|
||||
<span>{sc.credential?.name ?? sc.alias}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
|
||||
export { ExportScenarioModal } from './ExportScenarioModal';
|
||||
export type { ExportScenarioModalProps } from './ExportScenarioModal';
|
||||
export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
@@ -36,6 +36,7 @@
|
||||
"updated": "Environment updated",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_description": "Description",
|
||||
"col_data": "Data",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No environments yet.",
|
||||
@@ -56,10 +57,13 @@
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. staging, production",
|
||||
"form_name_required": "Name is required",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this environment",
|
||||
"form_data": "Data (JSON)",
|
||||
"form_data_invalid_json": "Must be a valid JSON object",
|
||||
"back": "Environments",
|
||||
"field_id": "ID",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_data": "Data"
|
||||
@@ -115,12 +119,14 @@
|
||||
"field_updated": "Updated",
|
||||
"field_lastUsed": "Last Used"
|
||||
},
|
||||
"scenarios": { "title": "Scenarios",
|
||||
"scenarios": {
|
||||
"title": "Scenarios",
|
||||
"created": "Scenario created",
|
||||
"updated": "Scenario updated",
|
||||
"run_started": "Scenario run started",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_description": "Description",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No scenarios yet.",
|
||||
"loading": "Loading…",
|
||||
@@ -128,6 +134,7 @@
|
||||
"action_delete": "Delete",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_description": "Description",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
@@ -148,6 +155,11 @@
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Scenario",
|
||||
"edit_title": "Edit Scenario",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this scenario",
|
||||
"form_environment": "Default Environment",
|
||||
"form_environment_none": "None (no default environment)",
|
||||
"field_environment": "Default Environment",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. Login flow",
|
||||
"form_name_required": "Name is required",
|
||||
@@ -169,7 +181,15 @@
|
||||
"run_modal_title": "Select environment",
|
||||
"run_modal_env_label": "Environment",
|
||||
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
|
||||
"run_modal_env_required": "Please select an environment"
|
||||
"run_modal_env_required": "Please select an environment",
|
||||
"export_modal_title": "Export Scenario",
|
||||
"export_include_environment": "Include Environment",
|
||||
"export_include_credentials": "Include Credentials",
|
||||
"form_timeout": "Scenario Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 600",
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
||||
"field_name": "Name",
|
||||
"field_id": "ID"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -205,7 +225,10 @@
|
||||
"form_session_placeholder": "e.g. my-session",
|
||||
"form_session_required": "Session name is required",
|
||||
"form_exec_code": "Exec code",
|
||||
"form_exec_code_placeholder": "return await page.title();"
|
||||
"form_exec_code_placeholder": "return await page.title();",
|
||||
"form_timeout": "Step Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 60",
|
||||
"form_timeout_hint": "Max seconds for this step (default: 60)"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Runs",
|
||||
|
||||
@@ -12,6 +12,7 @@ export function CreateEnvironmentPage() {
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
@@ -42,7 +43,11 @@ export function CreateEnvironmentPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const env = await environments.create(name.trim(), parsedData);
|
||||
const env = await environments.create(
|
||||
name.trim(),
|
||||
parsedData,
|
||||
description.trim() || undefined,
|
||||
);
|
||||
toast.success(t('environments.created'));
|
||||
navigate(`/environments/${env.id}`);
|
||||
} catch (err) {
|
||||
@@ -83,6 +88,15 @@ export function CreateEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -15,6 +15,7 @@ export function EditEnvironmentPage() {
|
||||
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
@@ -28,6 +29,7 @@ export function EditEnvironmentPage() {
|
||||
.then((data) => {
|
||||
setEnv(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
@@ -60,6 +62,7 @@ export function EditEnvironmentPage() {
|
||||
try {
|
||||
await environments.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
data: parsedData,
|
||||
});
|
||||
toast.success(t('environments.updated'));
|
||||
@@ -109,6 +112,15 @@ export function EditEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -117,6 +118,17 @@ export function EnvironmentDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{env.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={env.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
|
||||
<Card>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Activity } from 'lucide-react';
|
||||
import { runs } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -31,34 +33,53 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
};
|
||||
|
||||
type AllRunRow = ScenarioRun & {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
scenario: { id: number; name: string };
|
||||
scenario: { id: string; name: string };
|
||||
};
|
||||
|
||||
export function AllRunsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
|
||||
const {
|
||||
data: items = [],
|
||||
data,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery<AllRunRow[]>({
|
||||
queryKey: ['runs'],
|
||||
queryFn: async () => {
|
||||
const res = await runs.listAll();
|
||||
return res.data as AllRunRow[];
|
||||
},
|
||||
} = useQuery({
|
||||
queryKey: ['runs', sortBy, sortDir, page, pageSize],
|
||||
queryFn: () =>
|
||||
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const items = (data?.data ?? []) as AllRunRow[];
|
||||
const total = data?.total ?? 0;
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => setPage(p);
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const columns: TableColumn<AllRunRow>[] = [
|
||||
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
|
||||
{
|
||||
key: 'scenario',
|
||||
key: 'scenario.name',
|
||||
header: t('runs.col_scenario'),
|
||||
sortable: true,
|
||||
render: (r) => (
|
||||
<span
|
||||
className={styles.linkCell}
|
||||
@@ -75,18 +96,14 @@ export function AllRunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 110,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -109,9 +126,16 @@ export function AllRunsPage() {
|
||||
rowKey={(r) => r.id}
|
||||
loading={isLoading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
Environment,
|
||||
Scenario,
|
||||
ScenarioRun,
|
||||
ScenarioRunStep,
|
||||
ScenarioRunStatus,
|
||||
} from '../../api';
|
||||
import {
|
||||
@@ -22,6 +21,7 @@ import {
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -40,7 +40,7 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
|
||||
type RunRow = ScenarioRun;
|
||||
|
||||
export function RunsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -60,29 +60,74 @@ export function RunsPage() {
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const hasDataRef = useRef(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([scenarios.get(id!), runs.list(id!)])
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
// Keep refs so the poll interval always reads current values
|
||||
const sortByRef = useRef(sortBy);
|
||||
const sortDirRef = useRef(sortDir);
|
||||
const pageRef = useRef(page);
|
||||
const pageSizeRef = useRef(pageSize);
|
||||
sortByRef.current = sortBy;
|
||||
sortDirRef.current = sortDir;
|
||||
pageRef.current = page;
|
||||
pageSizeRef.current = pageSize;
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.get(id!),
|
||||
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
},
|
||||
[id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
load('createdAt', 'desc', 1, 20);
|
||||
pollRef.current = setInterval(
|
||||
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
|
||||
10_000,
|
||||
);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
@@ -117,18 +162,14 @@ export function RunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -151,7 +192,7 @@ export function RunsPage() {
|
||||
]}
|
||||
/>
|
||||
<div className={styles.toolbarActions}>
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={() => load(sortBy, sortDir, page, pageSize)} />
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Play size={14} />
|
||||
{t('runs.action_run')}
|
||||
@@ -165,9 +206,16 @@ export function RunsPage() {
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateScenarioPage() {
|
||||
@@ -12,9 +13,16 @@ export function CreateScenarioPage() {
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
environments.list(1, 200).then((r) => setEnvs(r?.data ?? [])).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
@@ -23,7 +31,7 @@ export function CreateScenarioPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const scenario = await scenarios.create(name.trim());
|
||||
const scenario = await scenarios.create(name.trim(), description.trim() || undefined, environmentId || undefined);
|
||||
toast.success(t('scenarios.created'));
|
||||
navigate(`/scenarios/${scenario.id}`);
|
||||
} catch (err) {
|
||||
@@ -64,6 +72,24 @@ export function CreateScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -16,6 +16,7 @@ export function CreateStepPage() {
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -33,6 +34,7 @@ export function CreateStepPage() {
|
||||
await steps.create(id!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
|
||||
});
|
||||
toast.success(t('steps.created'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
@@ -76,6 +78,15 @@ export function CreateStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -2,9 +2,9 @@ import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Scenario, Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditScenarioPage() {
|
||||
@@ -15,6 +15,10 @@ export function EditScenarioPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState<string>('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -26,8 +30,12 @@ export function EditScenarioPage() {
|
||||
.then((data) => {
|
||||
setScenario(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setEnvironmentId(data.environmentId ?? '');
|
||||
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
environments.list(1, 200).then((r) => setEnvs(r?.data ?? [])).catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
@@ -38,7 +46,12 @@ export function EditScenarioPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await scenarios.update(id!, { name: name.trim() });
|
||||
await scenarios.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
environmentId: environmentId || null,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('scenarios.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
@@ -86,6 +99,33 @@ export function EditScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.form_timeout')}
|
||||
placeholder={t('scenarios.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('scenarios.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -17,6 +17,7 @@ export function EditStepPage() {
|
||||
const [step, setStep] = useState<ScenarioStep | null>(null);
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -28,6 +29,7 @@ export function EditStepPage() {
|
||||
setStep(st);
|
||||
setTitle(st.title ?? '');
|
||||
setExecCode(st.execCode ?? '');
|
||||
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [id, stepId]);
|
||||
@@ -39,6 +41,7 @@ export function EditStepPage() {
|
||||
await steps.update(id!, stepId!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('steps.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
@@ -64,7 +67,7 @@ export function EditStepPage() {
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{ label: t('steps.edit_title', { order: step ? step.order + 1 : stepId }) },
|
||||
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -85,6 +88,15 @@ export function EditStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useEffect, useRef, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
@@ -37,9 +37,11 @@ import {
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import { ExportScenarioModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function ScenarioDetailPage() {
|
||||
@@ -67,11 +69,18 @@ export function ScenarioDetailPage() {
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
const envInitRef = useRef(false);
|
||||
const [pendingDelete, setPendingDelete] = useState<
|
||||
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
|
||||
>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
// Export modal state
|
||||
const [exportModalOpen, setExportModalOpen] = useState(false);
|
||||
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
||||
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
void scenarios
|
||||
@@ -89,11 +98,19 @@ export function ScenarioDetailPage() {
|
||||
.list(1, 200)
|
||||
.then((r) => {
|
||||
setEnvs(r.data);
|
||||
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
// Default selected env to scenario's linked environment (or first env) once both are loaded
|
||||
useEffect(() => {
|
||||
if (envInitRef.current || envs.length === 0) return;
|
||||
envInitRef.current = true;
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0].id);
|
||||
}, [scenario, envs]);
|
||||
|
||||
const reloadScenario = async () => {
|
||||
if (!id) return;
|
||||
const s = await scenarios.get(id);
|
||||
@@ -127,17 +144,36 @@ export function ScenarioDetailPage() {
|
||||
navigate('/scenarios');
|
||||
};
|
||||
|
||||
const handleOpenExportModal = () => {
|
||||
if (!scenario) return;
|
||||
// Initialise all credential checkboxes to checked
|
||||
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
||||
setIncludeEnvironment(true);
|
||||
setExportModalOpen(true);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!scenario) return;
|
||||
const data = await scenarios.exportScenario(scenario.id);
|
||||
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const credIds = Array.from(includedCredentialIds);
|
||||
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
||||
includeEnvironment,
|
||||
credentialIds: credIds,
|
||||
});
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportModalOpen(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteStep = async (stepId: string) => {
|
||||
@@ -252,7 +288,7 @@ export function ScenarioDetailPage() {
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order + 1, width: 60 },
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
@@ -358,7 +394,7 @@ export function ScenarioDetailPage() {
|
||||
<History size={14} />
|
||||
{t('scenarios.action_runs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
@@ -388,6 +424,19 @@ export function ScenarioDetailPage() {
|
||||
items={[
|
||||
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
|
||||
{ term: t('scenarios.field_name'), detail: scenario.name },
|
||||
...(scenario.environment
|
||||
? [{
|
||||
term: t('scenarios.field_environment'),
|
||||
detail: (
|
||||
<a
|
||||
href={`/environments/${scenario.environment.id}`}
|
||||
onClick={(e) => { e.preventDefault(); navigate(`/environments/${scenario.environment!.id}`); }}
|
||||
>
|
||||
{scenario.environment.name}
|
||||
</a>
|
||||
),
|
||||
}]
|
||||
: []),
|
||||
{
|
||||
term: t('scenarios.field_created'),
|
||||
detail: <Timestamp value={scenario.createdAt} />,
|
||||
@@ -400,6 +449,17 @@ export function ScenarioDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{scenario.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={scenario.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenario.steps.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
@@ -594,6 +654,29 @@ export function ScenarioDetailPage() {
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ExportScenarioModal
|
||||
open={exportModalOpen}
|
||||
scenario={scenario}
|
||||
scenarioCredentials={scenarioCreds}
|
||||
environment={
|
||||
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
|
||||
}
|
||||
includeEnvironment={includeEnvironment}
|
||||
onIncludeEnvironmentChange={setIncludeEnvironment}
|
||||
includedCredentialIds={includedCredentialIds}
|
||||
onCredentialToggle={(credId, checked) => {
|
||||
setIncludedCredentialIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (checked) next.add(credId);
|
||||
else next.delete(credId);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
onClose={() => setExportModalOpen(false)}
|
||||
onExport={handleExport}
|
||||
isExporting={isExporting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Select,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
@@ -34,10 +35,22 @@ export function ScenariosPage() {
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
Promise.all([scenarios.list(), environments.list(1, 200)])
|
||||
const [sortBy, setSortBy] = useState('updatedAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
environments.list(1, 200),
|
||||
])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setTotal(scenarioRes?.total ?? 0);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -47,14 +60,34 @@ export function ScenariosPage() {
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
load('updatedAt', 'desc', 1, 10);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
const openRunModal = (id: string) => {
|
||||
setRunScenarioId(id);
|
||||
if (!selectedEnvId && envs.length > 0) {
|
||||
setSelectedEnvId(envs[0].id);
|
||||
}
|
||||
const scenario = items.find((s) => s.id === id);
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
@@ -78,8 +111,7 @@ export function ScenariosPage() {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await scenarios.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
@@ -102,11 +134,12 @@ export function ScenariosPage() {
|
||||
|
||||
const columns: TableColumn<Scenario>[] = [
|
||||
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
|
||||
{
|
||||
key: 'updated',
|
||||
key: 'updatedAt',
|
||||
header: t('scenarios.col_updated'),
|
||||
width: 140,
|
||||
sortable: true,
|
||||
render: (s) => <Timestamp value={s.updatedAt} />,
|
||||
},
|
||||
{
|
||||
@@ -170,9 +203,16 @@ export function ScenariosPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('scenarios.empty')}
|
||||
pageSize={10}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Button,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
@@ -23,25 +24,36 @@ export function SessionsPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [sortBy, setSortBy] = useState('id');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
sessions
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
||||
.then((res) => { setItems(res.data); setTotal(res.total); })
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
}, [load, sortBy, sortDir, page, pageSize]);
|
||||
|
||||
const handleSort = (col: string, dir: SortDirection) => {
|
||||
setSortBy(col);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
@@ -50,17 +62,19 @@ export function SessionsPage() {
|
||||
|
||||
const columns: TableColumn<Session>[] = [
|
||||
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
|
||||
{ key: 'sessionName', header: t('sessions.col_name'), sortable: true, render: (s) => s.sessionName },
|
||||
{
|
||||
key: 'status',
|
||||
header: t('sessions.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'lastUsed',
|
||||
key: 'lastUsedAt',
|
||||
header: t('sessions.col_lastUsed'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
@@ -95,7 +109,13 @@ export function SessionsPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('sessions.empty')}
|
||||
pageSize={10}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(s) => { setPageSize(s); setPage(1); }}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
|
||||
/>
|
||||
|
||||
@@ -27,11 +27,40 @@
|
||||
background: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.thContent {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.thSortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
.sortIcon {
|
||||
opacity: 0.4;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sortIconActive {
|
||||
opacity: 1;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .th {
|
||||
background: var(--color-secondary);
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
/* Rounded top corners on first/last header cells */
|
||||
.th:first-child { border-radius: var(--radius-lg) 0 0 0; }
|
||||
.th:last-child { border-radius: 0 var(--radius-lg) 0 0; }
|
||||
|
||||
+120
-24
@@ -1,13 +1,18 @@
|
||||
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
|
||||
import { Pagination } from '../Pagination/Pagination';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
export interface TableColumn<T> {
|
||||
key: string;
|
||||
header: ReactNode;
|
||||
render: (row: T) => ReactNode;
|
||||
width?: string | number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
/** If true, a sort icon is shown and clicking the header triggers onSort */
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface TableProps<T> {
|
||||
@@ -17,7 +22,10 @@ export interface TableProps<T> {
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
/** Enable built-in client-side pagination with this default page size */
|
||||
/**
|
||||
* Client-side pagination: pass a default page size to enable.
|
||||
* For server-side pagination use `total` + `page` + `onPageChange` instead.
|
||||
*/
|
||||
pageSize?: number;
|
||||
/** Offer a page-size selector when pagination is enabled */
|
||||
pageSizeOptions?: number[];
|
||||
@@ -25,6 +33,21 @@ export interface TableProps<T> {
|
||||
onRowClick?: (row: T) => void;
|
||||
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
|
||||
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
|
||||
/** Currently sorted column key (controlled) */
|
||||
sortBy?: string;
|
||||
/** Current sort direction (controlled) */
|
||||
sortDir?: SortDirection;
|
||||
/** Called when the user clicks a sortable column header */
|
||||
onSort?: (key: string, dir: SortDirection) => void;
|
||||
// ── Server-side pagination (controlled) ──────────────────────────────────
|
||||
/** Total record count from server. Presence switches to server-side pagination mode. */
|
||||
total?: number;
|
||||
/** Controlled current page (1-based). Required when `total` is set. */
|
||||
page?: number;
|
||||
/** Called when the user navigates to a new page. Required when `total` is set. */
|
||||
onPageChange?: (page: number) => void;
|
||||
/** Called when the user changes page size. Optional for server-side pagination. */
|
||||
onPageSizeChange?: (size: number) => void;
|
||||
}
|
||||
|
||||
export function Table<T>({
|
||||
@@ -38,34 +61,85 @@ export function Table<T>({
|
||||
pageSizeOptions,
|
||||
onRowClick,
|
||||
getRowProps,
|
||||
sortBy,
|
||||
sortDir,
|
||||
onSort,
|
||||
total,
|
||||
page: controlledPage,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
}: TableProps<T>) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
|
||||
const [internalPage, setInternalPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
|
||||
|
||||
const paginated = defaultPageSize !== undefined && !loading;
|
||||
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
|
||||
const serverMode = total !== undefined;
|
||||
|
||||
// Reset to page 1 when data changes and current page would be empty
|
||||
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safePage = Math.min(page, Math.max(1, lastPage));
|
||||
const handleSortClick = (key: string) => {
|
||||
if (!onSort) return;
|
||||
const nextDir: SortDirection =
|
||||
sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
|
||||
onSort(key, nextDir);
|
||||
};
|
||||
|
||||
// Client-side pagination
|
||||
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
|
||||
const visibleData = clientPaginated
|
||||
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
|
||||
: data;
|
||||
|
||||
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
|
||||
|
||||
// Server-side pagination display values
|
||||
const serverPage = controlledPage ?? 1;
|
||||
const serverTotal = total ?? 0;
|
||||
|
||||
return (
|
||||
<div className={`${styles.wrapper} ${className ?? ''}`}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={styles.th}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
>
|
||||
{col.header}
|
||||
</th>
|
||||
))}
|
||||
{columns.map((col) => {
|
||||
const isSorted = col.sortable && sortBy === col.key;
|
||||
const SortIcon = isSorted
|
||||
? sortDir === 'asc'
|
||||
? ArrowUp
|
||||
: ArrowDown
|
||||
: ArrowUpDown;
|
||||
|
||||
return (
|
||||
<th
|
||||
key={col.key}
|
||||
className={[
|
||||
styles.th,
|
||||
col.sortable ? styles.thSortable : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
|
||||
>
|
||||
<span className={styles.thContent}>
|
||||
{col.header}
|
||||
{col.sortable && (
|
||||
<SortIcon
|
||||
size={12}
|
||||
className={[
|
||||
styles.sortIcon,
|
||||
isSorted ? styles.sortIconActive : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -122,17 +196,39 @@ export function Table<T>({
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{paginated && data.length > 0 && (
|
||||
{serverMode && serverTotal > 0 && onPageChange && (
|
||||
<Pagination
|
||||
page={safePage}
|
||||
page={serverPage}
|
||||
pageSize={pageSize}
|
||||
total={serverTotal}
|
||||
onPageChange={onPageChange}
|
||||
onPageSizeChange={
|
||||
onPageSizeChange
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageSizeChange(size);
|
||||
}
|
||||
: pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageChange(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
/>
|
||||
)}
|
||||
{clientPaginated && data.length > 0 && (
|
||||
<Pagination
|
||||
page={safeInternalPage}
|
||||
pageSize={pageSize}
|
||||
total={data.length}
|
||||
onPageChange={setPage}
|
||||
onPageChange={setInternalPage}
|
||||
onPageSizeChange={
|
||||
pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
setInternalPage(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ export { Modal } from './Modal/Modal';
|
||||
export type { ModalProps } from './Modal/Modal';
|
||||
|
||||
export { Table } from './Table/Table';
|
||||
export type { TableProps, TableColumn } from './Table/Table';
|
||||
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
|
||||
|
||||
export { UuidBadge } from './UuidBadge/UuidBadge';
|
||||
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
|
||||
Generated
+51
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.6.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.6.1",
|
||||
"workspaces": [
|
||||
"server",
|
||||
"client"
|
||||
@@ -3979,7 +3979,6 @@
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@storybook/addon-a11y": {
|
||||
@@ -7219,6 +7218,16 @@
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/effect": {
|
||||
"version": "3.21.0",
|
||||
"resolved": "https://registry.npmjs.org/effect/-/effect-3.21.0.tgz",
|
||||
"integrity": "sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"fast-check": "^3.23.1"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.332",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.332.tgz",
|
||||
@@ -8118,6 +8127,44 @@
|
||||
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-check": {
|
||||
"version": "3.23.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",
|
||||
"integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/dubzzz"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fast-check"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pure-rand": "^6.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-check/node_modules/pure-rand": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
|
||||
"integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/dubzzz"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fast-check"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
@@ -15987,6 +16034,7 @@
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.6.1",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"server",
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ RUN npm ci --omit=dev -w server
|
||||
COPY --from=builder /app/server/dist ./dist
|
||||
|
||||
# Runtime directories (keys and SQLite DB mounted via volumes)
|
||||
RUN mkdir -p data keys
|
||||
RUN mkdir -p data
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy, CredentialService } from "./credential.service";
|
||||
import { CredentialQueryDto } from "./dto/credential-query.dto";
|
||||
import { 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";
|
||||
@@ -39,7 +39,7 @@ export class CredentialController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all credentials (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated credentials" })
|
||||
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
|
||||
findAll(@Query() query: CredentialQueryDto) {
|
||||
return this.credentialService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "../credential.service";
|
||||
|
||||
const CREDENTIAL_ORDER_BY: CredentialOrderBy[] = ["id", "name", "lastUsedAt"];
|
||||
|
||||
export class CredentialQueryDto extends PaginationQueryDto<CredentialOrderBy> {
|
||||
@ApiPropertyOptional({ enum: CREDENTIAL_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(CREDENTIAL_ORDER_BY)
|
||||
declare orderBy?: CredentialOrderBy;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsString } from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsOptional, IsString } from "class-validator";
|
||||
import { EnvironmentData } from "../environment.entity";
|
||||
|
||||
export class CreateEnvironmentDto {
|
||||
@@ -8,6 +8,11 @@ export class CreateEnvironmentDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: "Generic key-value map for environment metadata",
|
||||
example: {
|
||||
|
||||
@@ -25,6 +25,11 @@ export class EnvironmentExportDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsObject()
|
||||
data: EnvironmentData;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { EnvironmentOrderBy } from "../environment.service";
|
||||
|
||||
const ENVIRONMENT_ORDER_BY: EnvironmentOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
|
||||
|
||||
export class EnvironmentQueryDto extends PaginationQueryDto<EnvironmentOrderBy> {
|
||||
@ApiPropertyOptional({ enum: ENVIRONMENT_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(ENVIRONMENT_ORDER_BY)
|
||||
declare orderBy?: EnvironmentOrderBy;
|
||||
}
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
||||
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";
|
||||
import { EnvironmentService } from "./environment.service";
|
||||
|
||||
@ApiTags("environments")
|
||||
@Controller("environments")
|
||||
@@ -40,7 +40,7 @@ export class EnvironmentController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all environments (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated environments" })
|
||||
findAll(@Query() query: PaginationQueryDto<EnvironmentOrderBy>) {
|
||||
findAll(@Query() query: EnvironmentQueryDto) {
|
||||
return this.environmentService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ export class EnvironmentEntity {
|
||||
@Column({ unique: true })
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column("simple-json")
|
||||
data: EnvironmentData;
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ export class EnvironmentService {
|
||||
kind: "environment",
|
||||
id: env.id,
|
||||
name: env.name,
|
||||
description: env.description ?? undefined,
|
||||
data: env.data,
|
||||
};
|
||||
}
|
||||
@@ -81,18 +82,36 @@ export class EnvironmentService {
|
||||
if (dto.id) {
|
||||
const existing = await this.repo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
Object.assign(existing, { name: dto.name, data: dto.data });
|
||||
Object.assign(existing, {
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
return this.repo.save(
|
||||
this.repo.create({ id: dto.id, name: dto.name, data: dto.data }),
|
||||
this.repo.create({
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const byName = await this.repo.findOneBy({ name: dto.name });
|
||||
if (byName) {
|
||||
Object.assign(byName, { data: dto.data });
|
||||
Object.assign(byName, {
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(byName);
|
||||
}
|
||||
return this.repo.save(this.repo.create({ name: dto.name, data: dto.data }));
|
||||
return this.repo.save(
|
||||
this.repo.create({
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -181,15 +181,20 @@ export class McpService {
|
||||
name: z
|
||||
.string()
|
||||
.describe("Unique environment name, e.g. liquio-diia-stg"),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional markdown description"),
|
||||
data: z
|
||||
.record(z.string(), z.string())
|
||||
.describe("Map of string keys to string values"),
|
||||
},
|
||||
},
|
||||
async ({ name, data }) => {
|
||||
async ({ name, description, data }) => {
|
||||
try {
|
||||
const env = await this.environmentService.create({
|
||||
name,
|
||||
description,
|
||||
data: data as EnvironmentData,
|
||||
});
|
||||
return {
|
||||
@@ -207,20 +212,26 @@ export class McpService {
|
||||
server.registerTool(
|
||||
"update_environment",
|
||||
{
|
||||
description: "Update an existing environment (name and/or data)",
|
||||
description:
|
||||
"Update an existing environment (name, description, and/or data)",
|
||||
inputSchema: {
|
||||
id: z.uuid().describe("Environment ID to update"),
|
||||
name: z.string().optional().describe("New name"),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("New markdown description"),
|
||||
data: z
|
||||
.record(z.string(), z.string())
|
||||
.optional()
|
||||
.describe("New data map"),
|
||||
},
|
||||
},
|
||||
async ({ id, name, data }) => {
|
||||
async ({ id, name, description, data }) => {
|
||||
try {
|
||||
const env = await this.environmentService.update(id, {
|
||||
name,
|
||||
description,
|
||||
data: data as EnvironmentData | undefined,
|
||||
});
|
||||
return {
|
||||
@@ -457,11 +468,30 @@ export class McpService {
|
||||
description: "Create a new scenario",
|
||||
inputSchema: {
|
||||
name: z.string().describe("Scenario name"),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional markdown description"),
|
||||
environmentId: z
|
||||
.uuid()
|
||||
.optional()
|
||||
.describe("Optional linked environment ID"),
|
||||
timeoutSeconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Scenario-level timeout in seconds (default 600)"),
|
||||
},
|
||||
},
|
||||
async ({ name }) => {
|
||||
async ({ name, description, environmentId, timeoutSeconds }) => {
|
||||
try {
|
||||
const scenario = await this.scenarioService.create({ name });
|
||||
const scenario = await this.scenarioService.create({
|
||||
name,
|
||||
description,
|
||||
environmentId,
|
||||
timeoutSeconds,
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{ type: "text" as const, text: JSON.stringify(scenario) },
|
||||
@@ -479,15 +509,36 @@ export class McpService {
|
||||
server.registerTool(
|
||||
"update_scenario",
|
||||
{
|
||||
description: "Update a scenario name",
|
||||
description: "Update a scenario name and/or description",
|
||||
inputSchema: {
|
||||
id: z.uuid().describe("Scenario ID"),
|
||||
name: z.string().optional().describe("New name"),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("New markdown description"),
|
||||
environmentId: z
|
||||
.uuid()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe("Linked environment ID (null to unlink)"),
|
||||
timeoutSeconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe("Scenario-level timeout in seconds (null to reset to default 600)"),
|
||||
},
|
||||
},
|
||||
async ({ id, name }) => {
|
||||
async ({ id, name, description, environmentId, timeoutSeconds }) => {
|
||||
try {
|
||||
const scenario = await this.scenarioService.update(id, { name });
|
||||
const scenario = await this.scenarioService.update(id, {
|
||||
name,
|
||||
description,
|
||||
environmentId,
|
||||
timeoutSeconds,
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{ type: "text" as const, text: JSON.stringify(scenario) },
|
||||
@@ -544,6 +595,12 @@ export class McpService {
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Playwright JS code to execute (exec steps)"),
|
||||
timeoutSeconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Step-level timeout in seconds (default 60, falls back to scenario timeout)"),
|
||||
},
|
||||
},
|
||||
async ({ scenarioId, ...dto }) => {
|
||||
@@ -604,6 +661,13 @@ export class McpService {
|
||||
.describe("New step type"),
|
||||
title: z.string().optional().describe("New step title"),
|
||||
execCode: z.string().optional().describe("New exec code"),
|
||||
timeoutSeconds: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe("Step-level timeout in seconds (null to reset to default)"),
|
||||
},
|
||||
},
|
||||
async ({ scenarioId, stepId, ...dto }) => {
|
||||
@@ -929,7 +993,10 @@ export class McpService {
|
||||
},
|
||||
async ({ id }) => {
|
||||
try {
|
||||
const exported = await this.scenarioService.exportScenario(id);
|
||||
const exported = await this.scenarioService.exportScenario(id, {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
{ type: "text" as const, text: JSON.stringify(exported) },
|
||||
@@ -951,6 +1018,10 @@ export class McpService {
|
||||
"Import a scenario from an export payload, creating a new scenario with all its steps",
|
||||
inputSchema: {
|
||||
name: z.string().describe("Scenario name"),
|
||||
description: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional markdown description"),
|
||||
steps: z
|
||||
.array(
|
||||
z.object({
|
||||
@@ -967,13 +1038,13 @@ export class McpService {
|
||||
.describe("Ordered list of steps"),
|
||||
},
|
||||
},
|
||||
async ({ name, steps }) => {
|
||||
async ({ name, description, steps }) => {
|
||||
try {
|
||||
const scenario = await this.scenarioService.importScenario({
|
||||
kind: "scenario",
|
||||
name,
|
||||
steps: steps as Parameters<
|
||||
typeof this.scenarioService.importScenario
|
||||
>[0]["steps"],
|
||||
description,
|
||||
steps: steps as { title: string | null; execCode: string | null }[],
|
||||
});
|
||||
return {
|
||||
content: [
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, Min } from "class-validator";
|
||||
|
||||
export class CreateScenarioStepDto {
|
||||
@ApiPropertyOptional({ example: "Check login page title" })
|
||||
@@ -12,4 +12,10 @@ export class CreateScenarioStepDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
execCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Step timeout in seconds (default: 60)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number;
|
||||
}
|
||||
@@ -1,9 +1,25 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
|
||||
|
||||
export class CreateScenarioDto {
|
||||
@ApiProperty({ example: "Login and verify cabinet" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional linked environment ID" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Scenario timeout in seconds (default: 600)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number;
|
||||
}
|
||||
@@ -1 +1,15 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { ScenarioOrderBy } from "../scenario.service";
|
||||
|
||||
export { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
|
||||
const SCENARIO_ORDER_BY: ScenarioOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
|
||||
|
||||
export class ScenarioQueryDto extends PaginationQueryDto<ScenarioOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SCENARIO_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SCENARIO_ORDER_BY)
|
||||
declare orderBy?: ScenarioOrderBy;
|
||||
}
|
||||
@@ -1,22 +1,17 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsIn, IsInt, IsOptional, Min } from "class-validator";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { RunStatus } from "../scenario-run.entity";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
|
||||
export class RunsQueryDto {
|
||||
@ApiPropertyOptional({ example: 1, default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number = 1;
|
||||
export type RunOrderBy = "createdAt" | "status" | "scenario.name";
|
||||
|
||||
@ApiPropertyOptional({ example: 20, default: 20 })
|
||||
const RUN_ORDER_BY: RunOrderBy[] = ["createdAt", "status", "scenario.name"];
|
||||
|
||||
export class RunsQueryDto extends PaginationQueryDto<RunOrderBy> {
|
||||
@ApiPropertyOptional({ enum: RUN_ORDER_BY })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
limit?: number = 20;
|
||||
@IsIn(RUN_ORDER_BY)
|
||||
declare orderBy?: RunOrderBy;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: ["pending", "in_progress", "pass", "fail"],
|
||||
|
||||
@@ -4,11 +4,13 @@ import {
|
||||
IsArray,
|
||||
IsIn,
|
||||
IsNotEmpty,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
import { EnvironmentData } from "../../environment/environment.entity";
|
||||
|
||||
export class ScenarioStepExportDto {
|
||||
@ApiPropertyOptional()
|
||||
@@ -24,6 +26,65 @@ export class ScenarioStepExportDto {
|
||||
execCode: string | null;
|
||||
}
|
||||
|
||||
export class CredentialExportDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsIn(["credential"])
|
||||
kind?: "credential";
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
id?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
data?: string | null;
|
||||
}
|
||||
|
||||
export class EnvironmentExportInlineDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsIn(["environment"])
|
||||
kind?: "environment";
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
id?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsObject()
|
||||
data: EnvironmentData;
|
||||
}
|
||||
|
||||
export class ScenarioCredentialMappingDto {
|
||||
@ApiProperty()
|
||||
@IsUUID()
|
||||
credentialId: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
alias: string;
|
||||
}
|
||||
|
||||
export class ScenarioExportDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@@ -46,9 +107,32 @@ export class ScenarioExportDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [ScenarioCredentialMappingDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ScenarioCredentialMappingDto)
|
||||
credentials?: ScenarioCredentialMappingDto[];
|
||||
|
||||
@ApiProperty({ type: [ScenarioStepExportDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ScenarioStepExportDto)
|
||||
steps: ScenarioStepExportDto[];
|
||||
}
|
||||
|
||||
/** Union type for multi-entity export array items */
|
||||
export type ExportEntity =
|
||||
| EnvironmentExportInlineDto
|
||||
| CredentialExportDto
|
||||
| ScenarioExportDto;
|
||||
@@ -18,4 +18,10 @@ export class UpdateScenarioStepDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
execCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Step timeout in seconds (null to use default of 60)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
|
||||
|
||||
export class UpdateScenarioDto {
|
||||
@ApiPropertyOptional({ example: "Updated scenario name" })
|
||||
@@ -7,4 +7,20 @@ export class UpdateScenarioDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Linked environment ID (null to unlink)" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ description: "Scenario timeout in seconds (null to use default of 600)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Injectable, OnModuleInit } from "@nestjs/common";
|
||||
import { Interval } from "@nestjs/schedule";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import * as crypto from "crypto";
|
||||
import { Effect } from "effect";
|
||||
import type { Browser, BrowserContext, Page } from "playwright";
|
||||
import { chromium } from "playwright";
|
||||
import { Repository } from "typeorm";
|
||||
@@ -30,7 +31,7 @@ interface BrowserHandle {
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ScenarioSchedulerService {
|
||||
export class ScenarioSchedulerService implements OnModuleInit {
|
||||
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
|
||||
private readonly activeRuns = new Set<string>();
|
||||
private readonly runBrowsers = new Map<string, BrowserHandle>();
|
||||
@@ -40,6 +41,12 @@ export class ScenarioSchedulerService {
|
||||
private readonly runSnippets = new Map<string, Record<string, string>>();
|
||||
// Cache environment values per run (built once when a run starts)
|
||||
private readonly runEnvironments = new Map<string, EnvironmentData>();
|
||||
// Cache scenario-level timeout (seconds) per run
|
||||
private readonly runScenarioTimeouts = new Map<string, number | null>();
|
||||
|
||||
private static readonly DEFAULT_SCENARIO_TIMEOUT_SEC = 600;
|
||||
private static readonly DEFAULT_STEP_TIMEOUT_SEC = 60;
|
||||
private static readonly CONCURRENCY_LIMIT = 10;
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -57,6 +64,70 @@ export class ScenarioSchedulerService {
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
) {}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
const staleRuns = await this.runRepo.find({
|
||||
where: { status: "in_progress" },
|
||||
});
|
||||
if (staleRuns.length === 0) return;
|
||||
|
||||
this.logger.error(
|
||||
`Server restart detected ${staleRuns.length} in-progress run(s) that cannot be recovered — marking as failed`,
|
||||
);
|
||||
|
||||
for (const run of staleRuns) {
|
||||
this.logger.error(
|
||||
`Run #${run.id}: marked fail due to server restart (playwright session lost)`,
|
||||
);
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.forEach(
|
||||
staleRuns,
|
||||
(run) =>
|
||||
Effect.tryPromise(() =>
|
||||
this.failRun(
|
||||
run.id,
|
||||
"Run aborted: server restarted and playwright session could not be recovered",
|
||||
),
|
||||
).pipe(
|
||||
Effect.catchAll((err) =>
|
||||
Effect.sync(() =>
|
||||
this.logger.error(
|
||||
`Run #${run.id}: failRun threw unexpectedly — ${String(err)}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a run as failed, fails its active step run, cancels any queued
|
||||
* step runs, and persists an error log entry. Use this for all failure paths.
|
||||
*/
|
||||
private async failRun(runId: string, reason: string): Promise<void> {
|
||||
await this.runRepo.update(runId, { status: "fail" });
|
||||
// Fail the actively-running step; cancel anything still queued
|
||||
await this.runStepRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: "fail" })
|
||||
.where("runId = :runId AND status = 'in_progress'", { runId })
|
||||
.execute();
|
||||
await this.runStepRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: "cancelled" })
|
||||
.where("runId = :runId AND status IN (:...statuses)", {
|
||||
runId,
|
||||
statuses: ["pending", "waiting"],
|
||||
})
|
||||
.execute();
|
||||
this.persistLog(runId, null, "error", reason);
|
||||
}
|
||||
|
||||
private persistLog(
|
||||
runId: string,
|
||||
stepRunId: string | null,
|
||||
@@ -98,36 +169,68 @@ export class ScenarioSchedulerService {
|
||||
@Interval(1000)
|
||||
async pickUpPendingRuns(): Promise<void> {
|
||||
const pending = await this.runRepo.find({ where: { status: "pending" } });
|
||||
for (const run of pending) {
|
||||
if (this.activeRuns.has(run.id)) continue;
|
||||
this.activeRuns.add(run.id);
|
||||
run.status = "in_progress";
|
||||
await this.runRepo.save(run);
|
||||
this.logger.log(`Run #${run.id} → in_progress`);
|
||||
// Pre-load credential map for the scenario
|
||||
const credMap = await this.scenarioService
|
||||
.buildCredentialMap(run.scenarioId)
|
||||
.catch(() => ({}) as Record<string, unknown>);
|
||||
this.runCredentials.set(run.id, credMap);
|
||||
// Pre-load snippet map
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
// Pre-load selected environment data
|
||||
const environmentData = await this.environmentRepo
|
||||
.findOneBy({ id: run.environmentId })
|
||||
.then((env) => env?.data ?? {})
|
||||
.catch(() => ({}) as EnvironmentData);
|
||||
this.runEnvironments.set(run.id, environmentData);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
);
|
||||
}
|
||||
const newRuns = pending.filter((run) => !this.activeRuns.has(run.id));
|
||||
if (newRuns.length === 0) return;
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.forEach(
|
||||
newRuns,
|
||||
(run) => {
|
||||
this.activeRuns.add(run.id);
|
||||
return Effect.tryPromise(async () => {
|
||||
run.status = "in_progress";
|
||||
await this.runRepo.save(run);
|
||||
this.logger.log(`Run #${run.id} → in_progress`);
|
||||
const credMap = await this.scenarioService
|
||||
.buildCredentialMap(run.scenarioId)
|
||||
.catch(() => ({}) as Record<string, unknown>);
|
||||
this.runCredentials.set(run.id, credMap);
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
const environmentData = await this.environmentRepo
|
||||
.findOneBy({ id: run.environmentId })
|
||||
.then((env) => env?.data ?? {})
|
||||
.catch(() => ({}) as EnvironmentData);
|
||||
this.runEnvironments.set(run.id, environmentData);
|
||||
const scenario = await this.scenarioService
|
||||
.findOne(run.scenarioId)
|
||||
.catch(() => null);
|
||||
this.runScenarioTimeouts.set(run.id, scenario?.timeoutSeconds ?? null);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchAll((err) =>
|
||||
Effect.promise(async () => {
|
||||
this.activeRuns.delete(run.id);
|
||||
this.runCredentials.delete(run.id);
|
||||
this.runSnippets.delete(run.id);
|
||||
this.runEnvironments.delete(run.id);
|
||||
this.runScenarioTimeouts.delete(run.id);
|
||||
this.logger.error(
|
||||
`Run #${run.id}: setup failed — ${String(err)}`,
|
||||
);
|
||||
await this.failRun(
|
||||
run.id,
|
||||
`Run setup failed: ${String(err)}`,
|
||||
).catch(() => {});
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async processRunToCompletion(runId: string): Promise<void> {
|
||||
const scenarioTimeoutSec =
|
||||
this.runScenarioTimeouts.get(runId) ??
|
||||
ScenarioSchedulerService.DEFAULT_SCENARIO_TIMEOUT_SEC;
|
||||
const scenarioDeadline = Date.now() + scenarioTimeoutSec * 1000;
|
||||
try {
|
||||
let stepRun = await this.runStepRepo.findOne({
|
||||
where: { runId, status: "pending" },
|
||||
@@ -135,6 +238,16 @@ export class ScenarioSchedulerService {
|
||||
order: { order: "ASC" },
|
||||
});
|
||||
while (stepRun) {
|
||||
if (Date.now() >= scenarioDeadline) {
|
||||
this.logger.error(
|
||||
`Run #${runId}: exceeded scenario timeout of ${scenarioTimeoutSec}s`,
|
||||
);
|
||||
await this.failRun(
|
||||
runId,
|
||||
`Scenario timed out after ${scenarioTimeoutSec}s`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.executeStepRun(stepRun);
|
||||
stepRun = await this.runStepRepo.findOne({
|
||||
where: { runId, status: "pending" },
|
||||
@@ -152,12 +265,13 @@ export class ScenarioSchedulerService {
|
||||
this.logger.error(
|
||||
`Run #${runId}: unexpected error: ${(err as Error).message}`,
|
||||
);
|
||||
await this.runRepo.update(runId, { status: "fail" });
|
||||
await this.failRun(runId, `Unexpected error: ${(err as Error).message}`);
|
||||
} finally {
|
||||
this.activeRuns.delete(runId);
|
||||
this.runCredentials.delete(runId);
|
||||
this.runSnippets.delete(runId);
|
||||
this.runEnvironments.delete(runId);
|
||||
this.runScenarioTimeouts.delete(runId);
|
||||
await this.maybePreserveSession(runId);
|
||||
}
|
||||
}
|
||||
@@ -245,7 +359,24 @@ export class ScenarioSchedulerService {
|
||||
.environment(env)
|
||||
.snippets(snips)
|
||||
.build();
|
||||
const { result: execOutput } = await this.codeExecutor.execute(execCtx);
|
||||
|
||||
const scenarioTimeoutSec = this.runScenarioTimeouts.get(stepRun.runId) ?? null;
|
||||
const stepTimeoutSec =
|
||||
step.timeoutSeconds ??
|
||||
scenarioTimeoutSec ??
|
||||
ScenarioSchedulerService.DEFAULT_STEP_TIMEOUT_SEC;
|
||||
const stepTimeoutMs = stepTimeoutSec * 1000;
|
||||
|
||||
const timeoutPromise = new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error(`Step timed out after ${stepTimeoutSec}s`)),
|
||||
stepTimeoutMs,
|
||||
),
|
||||
);
|
||||
const { result: execOutput } = await Promise.race([
|
||||
this.codeExecutor.execute(execCtx),
|
||||
timeoutPromise,
|
||||
]);
|
||||
|
||||
await this.passStepRun(stepRun, null, execOutput);
|
||||
} catch (err) {
|
||||
@@ -353,7 +484,9 @@ export class ScenarioSchedulerService {
|
||||
|
||||
this.logger.log(`Run #${stepRun.runId}: remaining steps cancelled`);
|
||||
|
||||
await this.closeBrowserHandle(stepRun.runId);
|
||||
// Don't close the browser here — maybePreserveSession (called from
|
||||
// processRunToCompletion's finally block) will either preserve it as a
|
||||
// session (saveSession=true) or close it (saveSession=false).
|
||||
await this.runRepo.update(stepRun.runId, { status: "fail" });
|
||||
this.logger.log(`Run #${stepRun.runId} → fail`);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,9 @@ export class ScenarioStepEntity {
|
||||
@Column({ type: "text", nullable: true })
|
||||
execCode: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
@@ -18,12 +18,12 @@ import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.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 { ScenarioQueryDto } from "./dto/pagination-query.dto";
|
||||
import { RunsQueryDto } from "./dto/runs-query.dto";
|
||||
import { ScenarioExportDto } from "./dto/scenario-export.dto";
|
||||
import { ExportEntity } 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";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
|
||||
@ApiTags("scenarios")
|
||||
@Controller("scenarios")
|
||||
@@ -40,16 +40,16 @@ export class ScenarioController {
|
||||
}
|
||||
|
||||
@Post("import")
|
||||
@ApiOperation({ summary: "Import a scenario from an export payload" })
|
||||
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
|
||||
@ApiResponse({ status: 201, description: "Scenario imported" })
|
||||
importScenario(@Body() dto: ScenarioExportDto) {
|
||||
return this.scenarioService.importScenario(dto);
|
||||
importScenario(@Body() payload: unknown) {
|
||||
return this.scenarioService.importScenario(payload as any);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all scenarios (paginated)" })
|
||||
@ApiResponse({ status: 200 })
|
||||
findAll(@Query() query: PaginationQueryDto<ScenarioOrderBy>) {
|
||||
findAll(@Query() query: ScenarioQueryDto) {
|
||||
return this.scenarioService.findAll(query);
|
||||
}
|
||||
|
||||
@@ -96,11 +96,34 @@ export class ScenarioController {
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
async exportScenario(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Query("includeEnvironment") includeEnvironment: string,
|
||||
@Query("credentialIds") credentialIds: string | string[] | undefined,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const payload = await this.scenarioService.exportScenario(id);
|
||||
const credIds: string[] = credentialIds
|
||||
? Array.isArray(credentialIds)
|
||||
? credentialIds
|
||||
: credentialIds.split(",").filter(Boolean)
|
||||
: [];
|
||||
const entities = await this.scenarioService.exportScenario(id, {
|
||||
includeEnvironment: includeEnvironment === "true",
|
||||
credentialIds: credIds,
|
||||
});
|
||||
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
|
||||
return yamlStringify(payload);
|
||||
// Serialize as YAML stream: each entity separated by a comment header
|
||||
const kindLabels: Record<string, string> = {
|
||||
environment: "Environment",
|
||||
credential: "Credential",
|
||||
scenario: "Scenario",
|
||||
};
|
||||
const parts = (entities as ExportEntity[]).map((entity) => {
|
||||
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
|
||||
const comment = `# --- ${label}: ${
|
||||
(entity as any).name ?? (entity as any).id ?? ""
|
||||
} ---`;
|
||||
return `${comment}\n${yamlStringify(entity)}`;
|
||||
});
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
// ── Steps ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -2,10 +2,13 @@ import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
|
||||
@@ -17,6 +20,19 @@ export class ScenarioEntity {
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ nullable: true, type: "text" })
|
||||
environmentId: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
@ManyToOne(() => EnvironmentEntity, { nullable: true, onDelete: "SET NULL", eager: false })
|
||||
@JoinColumn({ name: "environmentId" })
|
||||
environment: EnvironmentEntity | null;
|
||||
|
||||
@OneToMany(() => ScenarioStepEntity, (step) => step.scenario, {
|
||||
cascade: true,
|
||||
eager: false,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
@@ -15,7 +16,12 @@ import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
|
||||
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
|
||||
import { CreateScenarioDto } from "./dto/create-scenario.dto";
|
||||
import { RunsQueryDto } from "./dto/runs-query.dto";
|
||||
import { ScenarioExportDto } from "./dto/scenario-export.dto";
|
||||
import {
|
||||
CredentialExportDto,
|
||||
EnvironmentExportInlineDto,
|
||||
ExportEntity,
|
||||
ScenarioExportDto,
|
||||
} from "./dto/scenario-export.dto";
|
||||
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
||||
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
@@ -77,6 +83,7 @@ export class ScenarioService {
|
||||
"steps",
|
||||
"scenarioCredentials",
|
||||
"scenarioCredentials.credential",
|
||||
"environment",
|
||||
],
|
||||
order: { steps: { order: "ASC" } },
|
||||
});
|
||||
@@ -269,6 +276,15 @@ export class ScenarioService {
|
||||
}
|
||||
map[sc.alias] = parsed;
|
||||
}
|
||||
if (scs.length > 0) {
|
||||
const ids = scs.map((sc) => sc.credentialId);
|
||||
await this.credentialRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ lastUsedAt: () => "CURRENT_TIMESTAMP" })
|
||||
.whereInIds(ids)
|
||||
.execute();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -281,12 +297,14 @@ export class ScenarioService {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
const page = query.page ?? 1;
|
||||
const limit = query.limit ?? 20;
|
||||
const orderBy = query.orderBy ?? "createdAt";
|
||||
const orderDir = query.orderDir ?? "DESC";
|
||||
const where: Record<string, unknown> = { scenarioId };
|
||||
if (query.status) where["status"] = query.status;
|
||||
const [data, total] = await this.runRepo.findAndCount({
|
||||
where,
|
||||
relations: ["stepRuns"],
|
||||
order: { createdAt: "DESC" },
|
||||
order: { [orderBy]: orderDir },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
});
|
||||
@@ -300,15 +318,19 @@ export class ScenarioService {
|
||||
> {
|
||||
const page = query.page ?? 1;
|
||||
const limit = query.limit ?? 20;
|
||||
const where: Record<string, unknown> = {};
|
||||
if (query.status) where["status"] = query.status;
|
||||
const [data, total] = await this.runRepo.findAndCount({
|
||||
where,
|
||||
relations: ["stepRuns", "scenario"],
|
||||
order: { createdAt: "DESC" },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
});
|
||||
const orderBy = query.orderBy ?? "createdAt";
|
||||
const orderDir = query.orderDir ?? "DESC";
|
||||
const qb = this.runRepo
|
||||
.createQueryBuilder("run")
|
||||
.leftJoinAndSelect("run.scenario", "scenario");
|
||||
if (query.status) qb.where("run.status = :status", { status: query.status });
|
||||
if (orderBy === "scenario.name") {
|
||||
qb.orderBy("scenario.name", orderDir);
|
||||
} else {
|
||||
qb.orderBy(`run.${orderBy}`, orderDir);
|
||||
}
|
||||
qb.skip((page - 1) * limit).take(limit);
|
||||
const [data, total] = await qb.getManyAndCount();
|
||||
return { data, total, page, limit } as PaginatedResult<
|
||||
ScenarioRunEntity & { scenario: ScenarioEntity }
|
||||
>;
|
||||
@@ -404,37 +426,171 @@ export class ScenarioService {
|
||||
|
||||
// ── Export / Import ───────────────────────────────────────────────────────
|
||||
|
||||
async exportScenario(id: string): Promise<ScenarioExportDto> {
|
||||
async exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] },
|
||||
): Promise<ExportEntity[]> {
|
||||
const scenario = await this.findOne(id);
|
||||
return {
|
||||
const entities: ExportEntity[] = [];
|
||||
|
||||
// Include environment entity if requested and linked
|
||||
if (options.includeEnvironment && scenario.environment) {
|
||||
const envDto: EnvironmentExportInlineDto = {
|
||||
kind: "environment",
|
||||
id: scenario.environment.id,
|
||||
name: scenario.environment.name,
|
||||
description: scenario.environment.description ?? undefined,
|
||||
data: scenario.environment.data,
|
||||
};
|
||||
entities.push(envDto);
|
||||
}
|
||||
|
||||
// Include selected credentials
|
||||
if (options.credentialIds.length > 0) {
|
||||
const creds = scenario.scenarioCredentials ?? [];
|
||||
for (const sc of creds) {
|
||||
if (
|
||||
sc.credential &&
|
||||
options.credentialIds.includes(sc.credential.id)
|
||||
) {
|
||||
const credDto: CredentialExportDto = {
|
||||
kind: "credential",
|
||||
id: sc.credential.id,
|
||||
name: sc.credential.name,
|
||||
data: sc.credential.data,
|
||||
};
|
||||
entities.push(credDto);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario is always last
|
||||
const allCreds = scenario.scenarioCredentials ?? [];
|
||||
const credentialMappings = allCreds
|
||||
.filter(
|
||||
(sc) =>
|
||||
options.credentialIds.length === 0 ||
|
||||
options.credentialIds.includes(sc.credentialId),
|
||||
)
|
||||
.map((sc) => ({ credentialId: sc.credentialId, alias: sc.alias }));
|
||||
|
||||
const scenarioDto: ScenarioExportDto = {
|
||||
kind: "scenario",
|
||||
id: scenario.id,
|
||||
name: scenario.name,
|
||||
description: scenario.description ?? undefined,
|
||||
environmentId: scenario.environmentId ?? undefined,
|
||||
credentials: credentialMappings.length > 0 ? credentialMappings : undefined,
|
||||
steps: scenario.steps.map((s) => ({
|
||||
title: s.title,
|
||||
execCode: s.execCode,
|
||||
})),
|
||||
};
|
||||
entities.push(scenarioDto);
|
||||
|
||||
return entities;
|
||||
}
|
||||
|
||||
async importScenario(dto: ScenarioExportDto): Promise<ScenarioEntity> {
|
||||
// Upsert: if id provided and entity exists, replace steps; else create new
|
||||
async importScenario(
|
||||
payload: ScenarioExportDto | ExportEntity[],
|
||||
): Promise<ScenarioEntity> {
|
||||
// Accept plain {name, steps} objects (no kind) as well as the full export format
|
||||
const raw = payload as unknown as Record<string, unknown>;
|
||||
if (!Array.isArray(payload) && !raw["kind"]) {
|
||||
if (typeof raw["name"] !== "string" || !raw["name"]) {
|
||||
throw new BadRequestException("name is required");
|
||||
}
|
||||
if (!Array.isArray(raw["steps"])) {
|
||||
throw new BadRequestException("steps must be an array");
|
||||
}
|
||||
(payload as unknown as Record<string, unknown>)["kind"] = "scenario";
|
||||
}
|
||||
|
||||
const items: ExportEntity[] = Array.isArray(payload) ? payload : [payload];
|
||||
|
||||
let scenarioDto: ScenarioExportDto | undefined;
|
||||
for (const item of items) {
|
||||
if (item.kind === "environment") {
|
||||
await this.environmentRepo
|
||||
.findOneBy({ id: item.id })
|
||||
.then(async (existing) => {
|
||||
if (existing) {
|
||||
Object.assign(existing, {
|
||||
name: item.name,
|
||||
description: (item as EnvironmentExportInlineDto).description ?? null,
|
||||
data: (item as EnvironmentExportInlineDto).data,
|
||||
});
|
||||
return this.environmentRepo.save(existing);
|
||||
}
|
||||
return this.environmentRepo.save(
|
||||
this.environmentRepo.create({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: (item as EnvironmentExportInlineDto).description ?? null,
|
||||
data: (item as EnvironmentExportInlineDto).data,
|
||||
}),
|
||||
);
|
||||
});
|
||||
} else if (item.kind === "credential") {
|
||||
const credItem = item as CredentialExportDto;
|
||||
const existingCred = credItem.id
|
||||
? await this.credentialRepo.findOneBy({ id: credItem.id })
|
||||
: null;
|
||||
if (existingCred) {
|
||||
existingCred.name = credItem.name;
|
||||
existingCred.data = credItem.data ?? null;
|
||||
await this.credentialRepo.save(existingCred);
|
||||
} else {
|
||||
await this.credentialRepo.save(
|
||||
this.credentialRepo.create({
|
||||
...(credItem.id ? { id: credItem.id } : {}),
|
||||
name: credItem.name,
|
||||
data: credItem.data ?? null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} else if (!item.kind || item.kind === "scenario") {
|
||||
scenarioDto = item as ScenarioExportDto;
|
||||
}
|
||||
}
|
||||
|
||||
if (!scenarioDto) {
|
||||
throw new BadRequestException("No scenario entity found in import payload");
|
||||
}
|
||||
if (typeof scenarioDto.name !== "string" || !scenarioDto.name) {
|
||||
throw new BadRequestException("name is required");
|
||||
}
|
||||
if (!Array.isArray(scenarioDto.steps)) {
|
||||
throw new BadRequestException("steps must be an array");
|
||||
}
|
||||
|
||||
const dto = scenarioDto;
|
||||
let scenario: ScenarioEntity;
|
||||
if (dto.id) {
|
||||
const existing = await this.scenarioRepo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
existing.name = dto.name;
|
||||
existing.description = dto.description ?? null;
|
||||
existing.environmentId = dto.environmentId ?? existing.environmentId;
|
||||
scenario = await this.scenarioRepo.save(existing);
|
||||
// Delete old steps and recreate
|
||||
await this.stepRepo.delete({ scenarioId: scenario.id });
|
||||
} else {
|
||||
scenario = await this.scenarioRepo.save(
|
||||
this.scenarioRepo.create({ id: dto.id, name: dto.name }),
|
||||
this.scenarioRepo.create({
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
environmentId: dto.environmentId ?? null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
scenario = await this.scenarioRepo.save(
|
||||
this.scenarioRepo.create({ name: dto.name }),
|
||||
this.scenarioRepo.create({
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
environmentId: dto.environmentId ?? null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (dto.steps.length > 0) {
|
||||
@@ -449,6 +605,18 @@ export class ScenarioService {
|
||||
await this.stepRepo.save(steps);
|
||||
await this.normalizeStepOrder(scenario.id);
|
||||
}
|
||||
// Restore credential alias mappings
|
||||
if (dto.credentials && dto.credentials.length > 0) {
|
||||
await this.scenarioCredRepo.delete({ scenarioId: scenario.id });
|
||||
const mappings = dto.credentials.map((c) =>
|
||||
this.scenarioCredRepo.create({
|
||||
scenarioId: scenario.id,
|
||||
credentialId: c.credentialId,
|
||||
alias: c.alias,
|
||||
}),
|
||||
);
|
||||
await this.scenarioCredRepo.save(mappings);
|
||||
}
|
||||
return this.findOne(scenario.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SessionOrderBy } from "./session.service";
|
||||
|
||||
const SESSION_ORDER_BY: SessionOrderBy[] = ["id", "sessionName", "status", "lastUsedAt", "createdAt", "updatedAt"];
|
||||
|
||||
export class SessionQueryDto extends PaginationQueryDto<SessionOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SESSION_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SESSION_ORDER_BY)
|
||||
declare orderBy?: SessionOrderBy;
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SessionQueryDto } from "./session-query.dto";
|
||||
import { SessionContextService } from "./session-context.service";
|
||||
import { SessionOrderBy, SessionService } from "./session.service";
|
||||
import { SessionService } from "./session.service";
|
||||
|
||||
function maskToken(token: string, head = 6, tail = 4): string {
|
||||
if (token.length <= head + tail + 1) return token;
|
||||
@@ -29,7 +29,7 @@ export class SessionController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all stored sessions (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated sessions" })
|
||||
findAll(@Query() query: PaginationQueryDto<SessionOrderBy>) {
|
||||
findAll(@Query() query: SessionQueryDto) {
|
||||
return this.sessionService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { SnippetOrderBy } from "../snippet.service";
|
||||
|
||||
const SNIPPET_ORDER_BY: SnippetOrderBy[] = ["id", "alias", "title"];
|
||||
|
||||
export class SnippetQueryDto extends PaginationQueryDto<SnippetOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SNIPPET_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SNIPPET_ORDER_BY)
|
||||
declare orderBy?: SnippetOrderBy;
|
||||
}
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SnippetQueryDto } from "./dto/snippet-query.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";
|
||||
import { SnippetService } from "./snippet.service";
|
||||
|
||||
@ApiTags("snippets")
|
||||
@Controller("snippets")
|
||||
@@ -40,7 +40,7 @@ export class SnippetController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all snippets (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated snippets" })
|
||||
findAll(@Query() query: PaginationQueryDto<SnippetOrderBy>) {
|
||||
findAll(@Query() query: SnippetQueryDto) {
|
||||
return this.snippetService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -141,4 +141,147 @@ describe("McpController", () => {
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── create_scenario / update_scenario timeoutSeconds ──────────────────────
|
||||
|
||||
describe("create_scenario with timeoutSeconds", () => {
|
||||
it("saves timeoutSeconds on the created scenario", async () => {
|
||||
const { status, rpc } = await mcpCall("create_scenario", {
|
||||
name: "mcp-timeout-sc",
|
||||
timeoutSeconds: 300,
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
const result = rpc.result as { content: { text: string }[] };
|
||||
const created = JSON.parse(result.content[0].text) as {
|
||||
name: string;
|
||||
timeoutSeconds: number | null;
|
||||
};
|
||||
expect(created.name).toBe("mcp-timeout-sc");
|
||||
expect(created.timeoutSeconds).toBe(300);
|
||||
});
|
||||
|
||||
it("stores null timeoutSeconds when not provided", async () => {
|
||||
const { rpc } = await mcpCall("create_scenario", {
|
||||
name: "mcp-no-timeout",
|
||||
});
|
||||
const result = rpc.result as { content: { text: string }[] };
|
||||
const created = JSON.parse(result.content[0].text) as {
|
||||
timeoutSeconds: number | null;
|
||||
};
|
||||
expect(created.timeoutSeconds).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_scenario timeoutSeconds", () => {
|
||||
it("updates and clears timeoutSeconds", async () => {
|
||||
// create
|
||||
const createRpc = (
|
||||
await mcpCall("create_scenario", { name: "mcp-upd-timeout" })
|
||||
).rpc;
|
||||
const created = JSON.parse(
|
||||
(createRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { id: string };
|
||||
|
||||
// set
|
||||
const setRpc = (
|
||||
await mcpCall("update_scenario", {
|
||||
id: created.id,
|
||||
timeoutSeconds: 120,
|
||||
})
|
||||
).rpc;
|
||||
const updated = JSON.parse(
|
||||
(setRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { timeoutSeconds: number | null };
|
||||
expect(updated.timeoutSeconds).toBe(120);
|
||||
|
||||
// clear
|
||||
const clearRpc = (
|
||||
await mcpCall("update_scenario", {
|
||||
id: created.id,
|
||||
timeoutSeconds: null,
|
||||
})
|
||||
).rpc;
|
||||
const cleared = JSON.parse(
|
||||
(clearRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { timeoutSeconds: number | null };
|
||||
expect(cleared.timeoutSeconds).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── create_scenario_step / update_scenario_step timeoutSeconds ────────────
|
||||
|
||||
describe("create_scenario_step with timeoutSeconds", () => {
|
||||
it("saves timeoutSeconds on the created step", async () => {
|
||||
// create a scenario first
|
||||
const scRpc = (
|
||||
await mcpCall("create_scenario", { name: "mcp-step-timeout-parent" })
|
||||
).rpc;
|
||||
const sc = JSON.parse(
|
||||
(scRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { id: string };
|
||||
|
||||
const { status, rpc } = await mcpCall("create_scenario_step", {
|
||||
scenarioId: sc.id,
|
||||
order: 0,
|
||||
type: "exec",
|
||||
execCode: "return 1;",
|
||||
timeoutSeconds: 45,
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
const result = rpc.result as { content: { text: string }[] };
|
||||
const step = JSON.parse(result.content[0].text) as {
|
||||
timeoutSeconds: number | null;
|
||||
};
|
||||
expect(step.timeoutSeconds).toBe(45);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_scenario_step timeoutSeconds", () => {
|
||||
it("updates and clears step timeoutSeconds", async () => {
|
||||
// create scenario + step
|
||||
const scRpc = (
|
||||
await mcpCall("create_scenario", { name: "mcp-step-upd-parent" })
|
||||
).rpc;
|
||||
const sc = JSON.parse(
|
||||
(scRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { id: string };
|
||||
|
||||
const stepRpc = (
|
||||
await mcpCall("create_scenario_step", {
|
||||
scenarioId: sc.id,
|
||||
order: 0,
|
||||
type: "exec",
|
||||
})
|
||||
).rpc;
|
||||
const step = JSON.parse(
|
||||
(stepRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { id: string };
|
||||
|
||||
// set
|
||||
const setRpc = (
|
||||
await mcpCall("update_scenario_step", {
|
||||
scenarioId: sc.id,
|
||||
stepId: step.id,
|
||||
timeoutSeconds: 90,
|
||||
})
|
||||
).rpc;
|
||||
const updated = JSON.parse(
|
||||
(setRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { timeoutSeconds: number | null };
|
||||
expect(updated.timeoutSeconds).toBe(90);
|
||||
|
||||
// clear
|
||||
const clearRpc = (
|
||||
await mcpCall("update_scenario_step", {
|
||||
scenarioId: sc.id,
|
||||
stepId: step.id,
|
||||
timeoutSeconds: null,
|
||||
})
|
||||
).rpc;
|
||||
const cleared = JSON.parse(
|
||||
(clearRpc.result as { content: { text: string }[] }).content[0].text,
|
||||
) as { timeoutSeconds: number | null };
|
||||
expect(cleared.timeoutSeconds).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { getRepositoryToken } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { buildTestApp } from "./app.harness";
|
||||
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
|
||||
import { ScenarioRunEntity } from "../src/scenario/scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "../src/scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "../src/scenario/scenario-run-log.entity";
|
||||
import { ScenarioEntity } from "../src/scenario/scenario.entity";
|
||||
import { ScenarioStepEntity } from "../src/scenario/scenario-step.entity";
|
||||
|
||||
describe("ScenarioSchedulerService.onModuleInit", () => {
|
||||
let app: INestApplication;
|
||||
let scheduler: ScenarioSchedulerService;
|
||||
let scenarioRepo: Repository<ScenarioEntity>;
|
||||
let stepRepo: Repository<ScenarioStepEntity>;
|
||||
let runRepo: Repository<ScenarioRunEntity>;
|
||||
let runStepRepo: Repository<ScenarioRunStepEntity>;
|
||||
let runLogRepo: Repository<ScenarioRunLogEntity>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildTestApp();
|
||||
scheduler = app.get(ScenarioSchedulerService);
|
||||
scenarioRepo = app.get<Repository<ScenarioEntity>>(
|
||||
getRepositoryToken(ScenarioEntity),
|
||||
);
|
||||
stepRepo = app.get<Repository<ScenarioStepEntity>>(
|
||||
getRepositoryToken(ScenarioStepEntity),
|
||||
);
|
||||
runRepo = app.get<Repository<ScenarioRunEntity>>(
|
||||
getRepositoryToken(ScenarioRunEntity),
|
||||
);
|
||||
runStepRepo = app.get<Repository<ScenarioRunStepEntity>>(
|
||||
getRepositoryToken(ScenarioRunStepEntity),
|
||||
);
|
||||
runLogRepo = app.get<Repository<ScenarioRunLogEntity>>(
|
||||
getRepositoryToken(ScenarioRunLogEntity),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function seedScenarioWithStep() {
|
||||
const scenario = await scenarioRepo.save(
|
||||
scenarioRepo.create({ name: "test-scenario" }),
|
||||
);
|
||||
const step = await stepRepo.save(
|
||||
stepRepo.create({ scenarioId: scenario.id, order: 1 }),
|
||||
);
|
||||
return { scenario, step };
|
||||
}
|
||||
|
||||
async function seedRun(
|
||||
scenarioId: string,
|
||||
runStatus: ScenarioRunEntity["status"],
|
||||
) {
|
||||
return runRepo.save(
|
||||
runRepo.create({ scenarioId, status: runStatus }),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedStepRun(
|
||||
runId: string,
|
||||
scenarioStepId: string,
|
||||
status: ScenarioRunStepEntity["status"],
|
||||
) {
|
||||
return runStepRepo.save(
|
||||
runStepRepo.create({ runId, scenarioStepId, order: 1, status }),
|
||||
);
|
||||
}
|
||||
|
||||
// ── tests ──────────────────────────────────────────────────────────────────
|
||||
|
||||
it("does nothing when no in_progress runs exist", async () => {
|
||||
// All existing runs (if any) should already be clean after app init.
|
||||
// This call should be a no-op and not throw.
|
||||
await expect(scheduler.onModuleInit()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails an in_progress run left from a previous server instance", async () => {
|
||||
const { scenario } = await seedScenarioWithStep();
|
||||
const run = await seedRun(scenario.id, "in_progress");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
const updated = await runRepo.findOneByOrFail({ id: run.id });
|
||||
expect(updated.status).toBe("fail");
|
||||
});
|
||||
|
||||
it("leaves pending and completed runs untouched", async () => {
|
||||
const { scenario } = await seedScenarioWithStep();
|
||||
const pending = await seedRun(scenario.id, "pending");
|
||||
const passed = await seedRun(scenario.id, "pass");
|
||||
const failed = await seedRun(scenario.id, "fail");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
expect((await runRepo.findOneByOrFail({ id: pending.id })).status).toBe(
|
||||
"pending",
|
||||
);
|
||||
expect((await runRepo.findOneByOrFail({ id: passed.id })).status).toBe(
|
||||
"pass",
|
||||
);
|
||||
expect((await runRepo.findOneByOrFail({ id: failed.id })).status).toBe(
|
||||
"fail",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails in_progress step runs belonging to the stale run", async () => {
|
||||
const { scenario, step } = await seedScenarioWithStep();
|
||||
const run = await seedRun(scenario.id, "in_progress");
|
||||
const stepRun = await seedStepRun(run.id, step.id, "in_progress");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
const updated = await runStepRepo.findOneByOrFail({ id: stepRun.id });
|
||||
expect(updated.status).toBe("fail");
|
||||
});
|
||||
|
||||
it("cancels pending and waiting step runs of a stale run", async () => {
|
||||
const { scenario, step } = await seedScenarioWithStep();
|
||||
const run = await seedRun(scenario.id, "in_progress");
|
||||
const pendingStep = await seedStepRun(run.id, step.id, "pending");
|
||||
const waitingStep = await seedStepRun(run.id, step.id, "waiting");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
expect(
|
||||
(await runStepRepo.findOneByOrFail({ id: pendingStep.id })).status,
|
||||
).toBe("cancelled");
|
||||
expect(
|
||||
(await runStepRepo.findOneByOrFail({ id: waitingStep.id })).status,
|
||||
).toBe("cancelled");
|
||||
});
|
||||
|
||||
it("does not affect step runs of non-stale runs", async () => {
|
||||
const { scenario, step } = await seedScenarioWithStep();
|
||||
const staleRun = await seedRun(scenario.id, "in_progress");
|
||||
const passedRun = await seedRun(scenario.id, "pass");
|
||||
const staleStep = await seedStepRun(staleRun.id, step.id, "in_progress");
|
||||
const passedStep = await seedStepRun(passedRun.id, step.id, "pass");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
// in_progress step of the stale run → fail
|
||||
expect(
|
||||
(await runStepRepo.findOneByOrFail({ id: staleStep.id })).status,
|
||||
).toBe("fail");
|
||||
// step of a completed run → untouched
|
||||
expect(
|
||||
(await runStepRepo.findOneByOrFail({ id: passedStep.id })).status,
|
||||
).toBe("pass");
|
||||
});
|
||||
|
||||
it("persists an error log entry for each failed run", async () => {
|
||||
const { scenario } = await seedScenarioWithStep();
|
||||
const run = await seedRun(scenario.id, "in_progress");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
// Allow the void log persist to flush (persistLog uses void save)
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
|
||||
const logs = await runLogRepo.findBy({ runId: run.id });
|
||||
expect(logs.length).toBeGreaterThanOrEqual(1);
|
||||
const errorLog = logs.find((l) => l.level === "error");
|
||||
expect(errorLog).toBeDefined();
|
||||
expect(errorLog!.message).toMatch(/server restarted/i);
|
||||
});
|
||||
|
||||
it("handles multiple stale runs in one pass", async () => {
|
||||
const { scenario } = await seedScenarioWithStep();
|
||||
const run1 = await seedRun(scenario.id, "in_progress");
|
||||
const run2 = await seedRun(scenario.id, "in_progress");
|
||||
|
||||
await scheduler.onModuleInit();
|
||||
|
||||
expect((await runRepo.findOneByOrFail({ id: run1.id })).status).toBe(
|
||||
"fail",
|
||||
);
|
||||
expect((await runRepo.findOneByOrFail({ id: run2.id })).status).toBe(
|
||||
"fail",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -81,6 +81,29 @@ describe("ScenarioController", () => {
|
||||
.send({})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("saves timeoutSeconds when provided", async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post("/scenarios")
|
||||
.send({ name: "timeout-sc", timeoutSeconds: 300 })
|
||||
.expect(201);
|
||||
expect(res.body.timeoutSeconds).toBe(300);
|
||||
});
|
||||
|
||||
it("stores null timeoutSeconds when not provided", async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post("/scenarios")
|
||||
.send({ name: "no-timeout-sc" })
|
||||
.expect(201);
|
||||
expect(res.body.timeoutSeconds).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 400 for timeoutSeconds below 1", async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post("/scenarios")
|
||||
.send({ name: "bad-timeout", timeoutSeconds: 0 })
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ── GET /scenarios ─────────────────────────────────────────────────────────
|
||||
@@ -181,6 +204,27 @@ describe("ScenarioController", () => {
|
||||
expect(res.body.name).toBe("patched");
|
||||
});
|
||||
|
||||
it("updates timeoutSeconds", async () => {
|
||||
const sc = await createScenario("timeout-patch");
|
||||
const res = await request(app.getHttpServer())
|
||||
.patch(`/scenarios/${sc.id}`)
|
||||
.send({ timeoutSeconds: 120 })
|
||||
.expect(200);
|
||||
expect(res.body.timeoutSeconds).toBe(120);
|
||||
});
|
||||
|
||||
it("clears timeoutSeconds to null", async () => {
|
||||
const created = await request(app.getHttpServer())
|
||||
.post("/scenarios")
|
||||
.send({ name: "clear-timeout", timeoutSeconds: 120 })
|
||||
.expect(201);
|
||||
const res = await request(app.getHttpServer())
|
||||
.patch(`/scenarios/${created.body.id}`)
|
||||
.send({ timeoutSeconds: null })
|
||||
.expect(200);
|
||||
expect(res.body.timeoutSeconds).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 404 for unknown id", async () => {
|
||||
await request(app.getHttpServer())
|
||||
.patch("/scenarios/00000000-0000-0000-0000-000000000001")
|
||||
@@ -260,6 +304,24 @@ describe("ScenarioController", () => {
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it("saves timeoutSeconds on step when provided", async () => {
|
||||
const sc = await createScenario();
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/scenarios/${sc.id}/steps`)
|
||||
.send({ execCode: "return 1;", timeoutSeconds: 45 })
|
||||
.expect(201);
|
||||
expect(res.body.timeoutSeconds).toBe(45);
|
||||
});
|
||||
|
||||
it("stores null step timeoutSeconds when not provided", async () => {
|
||||
const sc = await createScenario();
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/scenarios/${sc.id}/steps`)
|
||||
.send({ execCode: "return 1;" })
|
||||
.expect(201);
|
||||
expect(res.body.timeoutSeconds).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 404 for unknown scenario", async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post("/scenarios/00000000-0000-0000-0000-000000000001/steps")
|
||||
@@ -320,6 +382,26 @@ describe("ScenarioController", () => {
|
||||
expect(res.body.execCode).toBe("return 99;");
|
||||
});
|
||||
|
||||
it("updates step timeoutSeconds", async () => {
|
||||
const sc = await createScenario();
|
||||
const step = await createStep(sc.id);
|
||||
const res = await request(app.getHttpServer())
|
||||
.patch(`/scenarios/${sc.id}/steps/${step.id}`)
|
||||
.send({ timeoutSeconds: 90 })
|
||||
.expect(200);
|
||||
expect(res.body.timeoutSeconds).toBe(90);
|
||||
});
|
||||
|
||||
it("clears step timeoutSeconds to null", async () => {
|
||||
const sc = await createScenario();
|
||||
const step = await createStep(sc.id, { timeoutSeconds: 90 });
|
||||
const res = await request(app.getHttpServer())
|
||||
.patch(`/scenarios/${sc.id}/steps/${step.id}`)
|
||||
.send({ timeoutSeconds: null })
|
||||
.expect(200);
|
||||
expect(res.body.timeoutSeconds).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 404 for unknown step", async () => {
|
||||
const sc = await createScenario();
|
||||
await request(app.getHttpServer())
|
||||
|
||||
Reference in new issue
Block a user