feat(snippets): add snippets entity, crud, and auto-browser-per-run

- add Snippet entity with name, description, code; full CRUD backend
- add snippets pages (list, create, edit, detail) and nav entry
- add runSnippet helper in code-executor using new Function with args array
- add result param to execute() so validateCode can access exec output
- remove sessionName from steps; each run now spawns its own fresh browser
- fix waitForURL race by polling localStorage for token instead
This commit is contained in:
2026-04-10 00:22:51 +03:00
parent 1efbbb38a3
commit 1164289173
26 changed files with 876 additions and 89 deletions
+10 -1
View File
@@ -1,6 +1,6 @@
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare } from 'lucide-react';
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare, Braces } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui';
@@ -25,10 +25,15 @@ import { CredentialsPage } from './pages/credential/CredentialsPage';
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
import { SnippetsPage } from './pages/snippet/SnippetsPage';
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
@@ -87,6 +92,10 @@ export default function App() {
<Route path="/credentials/new" element={<CreateCredentialPage />} />
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
<Route path="/snippets" element={<SnippetsPage />} />
<Route path="/snippets/new" element={<CreateSnippetPage />} />
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
<Route path="/runs" element={<AllRunsPage />} />
<Route path="*" element={<Navigate to="/scenarios" replace />} />
</Routes>
+27 -2
View File
@@ -10,6 +10,7 @@ import type {
ScenarioRunDetail,
ScenarioRunStep,
ScenarioStep,
Snippet,
} from './types';
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
@@ -58,6 +59,32 @@ export const credentials = {
},
};
// ── Snippets ──────────────────────────────────────────────────────────────────
export const snippets = {
list(page = 1, limit = 50): Promise<PaginatedResponse<Snippet>> {
return request(`/snippets?page=${page}&limit=${limit}`);
},
get(id: number): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
});
},
update(id: number, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
return request(`/snippets/${id}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
},
remove(id: number): Promise<void> {
return request(`/snippets/${id}`, { method: 'DELETE' });
},
};
// ── Environments ──────────────────────────────────────────────────────────────
export const environments = {
@@ -184,7 +211,6 @@ export interface CreateStepPayload {
title?: string;
order: number;
type: 'login' | 'exec' | 'sign';
sessionName: string;
execCode?: string;
validateCode?: string;
}
@@ -193,7 +219,6 @@ export interface UpdateStepPayload {
title?: string;
order?: number;
type?: 'login' | 'exec' | 'sign';
sessionName?: string;
execCode?: string;
validateCode?: string;
}
+12 -1
View File
@@ -35,6 +35,17 @@ export interface Credential {
updatedAt: string;
}
// ── Snippets ──────────────────────────────────────────────────────────────────
export interface Snippet {
id: number;
name: string;
description: string | null;
code: string;
createdAt: string;
updatedAt: string;
}
// ── Keys ──────────────────────────────────────────────────────────────────────
export interface KeysResponse {
@@ -65,7 +76,7 @@ export interface ScenarioStep {
order: number;
type: StepType;
title: string | null;
sessionName: string;
sessionName: string | null;
execCode: string | null;
validateCode: string | null;
createdAt: string;
+30
View File
@@ -5,11 +5,13 @@
"not_found_environment": "Environment {{id}} does not exist or has been deleted.",
"not_found_credential": "Credential {{id}} does not exist or has been deleted.",
"not_found_scenario": "Scenario {{id}} does not exist or has been deleted.",
"not_found_snippet": "Snippet {{id}} does not exist or has been deleted.",
"generic": "Something went wrong. Please try again."
},
"nav": {
"environments": "Environments",
"credentials": "Credentials",
"snippets": "Snippets",
"keys": "Keys",
"sessions": "Sessions",
"scenarios": "Scenarios",
@@ -199,5 +201,33 @@
"log_level": "Level",
"log_message": "Message",
"log_time": "Time"
},
"snippets": {
"title": "Snippets",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
"action_edit": "Edit",
"action_delete": "Delete",
"action_add": "Add snippet",
"action_save": "Create",
"action_update": "Save changes",
"action_cancel": "Cancel",
"create_title": "New Snippet",
"edit_title": "Edit Snippet",
"form_name": "Name",
"form_name_placeholder": "e.g. clickLoginButton",
"form_name_required": "Name is required",
"form_description": "Description",
"form_description_placeholder": "What does this snippet do?",
"form_code": "Code",
"form_code_placeholder": "await page.click('#login-btn');",
"form_code_required": "Code is required",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_created": "Created",
"field_updated": "Updated",
"section_code": "Code"
}
}
-5
View File
@@ -119,11 +119,6 @@ export function RunDetailPage() {
width: 80,
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? ''}</Badge>,
},
{
key: 'session',
header: t('runs.step_session'),
render: (s) => s.scenarioStep?.sessionName ?? '',
},
{
key: 'status',
header: t('runs.step_status'),
@@ -18,7 +18,6 @@ export function CreateStepPage() {
const [order, setOrder] = useState('0');
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [sessionName, setSessionName] = useState('');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [errors, setErrors] = useState<Partial<Record<keyof CreateStepPayload, string>>>({});
@@ -32,7 +31,6 @@ export function CreateStepPage() {
const validate = (): boolean => {
const next: typeof errors = {};
if (!sessionName.trim()) next.sessionName = t('steps.form_session_required');
if (isNaN(Number(order)) || Number(order) < 0) next.order = t('steps.form_order_invalid');
setErrors(next);
return Object.keys(next).length === 0;
@@ -48,7 +46,6 @@ export function CreateStepPage() {
order: Number(order),
title: title.trim() || undefined,
type,
sessionName: sessionName.trim(),
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
});
@@ -100,17 +97,6 @@ export function CreateStepPage() {
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<Input
label={t('steps.form_session')}
placeholder={t('steps.form_session_placeholder')}
value={sessionName}
onChange={(e) => {
setSessionName(e.target.value);
setErrors((prev) => ({ ...prev, sessionName: undefined }));
}}
error={errors.sessionName}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
@@ -18,10 +18,8 @@ export function EditStepPage() {
const [order, setOrder] = useState('');
const [title, setTitle] = useState('');
const [type, setType] = useState<StepType>('exec');
const [sessionName, setSessionName] = useState('');
const [execCode, setExecCode] = useState('');
const [validateCode, setValidateCode] = useState('');
const [sessionError, setSessionError] = useState('');
const [orderError, setOrderError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -36,7 +34,6 @@ export function EditStepPage() {
setOrder(String(st.order));
setTitle(st.title ?? '');
setType(st.type);
setSessionName(st.sessionName);
setExecCode(st.execCode ?? '');
setValidateCode(st.validateCode ?? '');
})
@@ -46,10 +43,6 @@ export function EditStepPage() {
const validate = (): boolean => {
let valid = true;
if (!sessionName.trim()) {
setSessionError(t('steps.form_session_required'));
valid = false;
}
if (isNaN(Number(order)) || Number(order) < 0) {
setOrderError(t('steps.form_order_invalid'));
valid = false;
@@ -67,7 +60,6 @@ export function EditStepPage() {
order: Number(order),
title: title.trim() || undefined,
type,
sessionName: sessionName.trim(),
execCode: execCode.trim() || undefined,
validateCode: validateCode.trim() || undefined,
});
@@ -124,17 +116,6 @@ export function EditStepPage() {
onChange={(e) => setType(e.target.value as StepType)}
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
/>
<Input
label={t('steps.form_session')}
placeholder={t('steps.form_session_placeholder')}
value={sessionName}
onChange={(e) => {
setSessionName(e.target.value);
setSessionError('');
}}
error={sessionError || undefined}
required
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
<textarea
@@ -117,7 +117,7 @@ export function ScenarioDetailPage() {
{
key: 'title',
header: t('scenarios.step_title'),
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{s.sessionName}</span>,
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>,
},
{
key: 'updated',
@@ -0,0 +1,113 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { snippets } from '../../api';
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
import styles from '../Page.module.css';
export function CreateSnippetPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
name: name.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
navigate(`/snippets/${snippet.id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: t('snippets.create_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
value={code}
onChange={(e) => {
setCode(e.target.value);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
{t('snippets.action_save')}
</Button>
</div>
</Card>
</form>
</div>
);
}
@@ -0,0 +1,142 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, Input } from '../../ui';
import styles from '../Page.module.css';
export function EditSnippetPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [code, setCode] = useState('');
const [nameError, setNameError] = useState('');
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
snippets
.get(Number(id))
.then((s) => {
setSnippet(s);
setName(s.name);
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
setNameError(t('snippets.form_name_required'));
valid = false;
}
if (!code.trim()) {
setCodeError(t('snippets.form_code_required'));
valid = false;
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(Number(id), {
name: name.trim(),
description: description.trim() || undefined,
code: code.trim(),
});
navigate(`/snippets/${id}`);
} catch (err) {
setError((err as Error).message);
} finally {
setSaving(false);
}
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{
label: snippet?.name ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
},
{ label: t('snippets.edit_title') },
]}
/>
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && snippet && (
<form onSubmit={handleSubmit} noValidate>
<Card className={styles.formCard}>
<div className={styles.formFields}>
<Input
label={t('snippets.form_name')}
placeholder={t('snippets.form_name_placeholder')}
value={name}
onChange={(e) => {
setName(e.target.value);
setNameError('');
}}
error={nameError || undefined}
required
autoFocus
/>
<Input
label={t('snippets.form_description')}
placeholder={t('snippets.form_description_placeholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={styles.formField}>
<label className={styles.fieldLabel}>
{t('snippets.form_code')}
<span className={styles.requiredMark}> *</span>
</label>
<textarea
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
rows={14}
value={code}
onChange={(e) => {
setCode(e.target.value);
setCodeError('');
}}
placeholder={t('snippets.form_code_placeholder')}
spellCheck={false}
/>
{codeError && <span className={styles.fieldError}>{codeError}</span>}
</div>
</div>
<div className={styles.formActions}>
<Button
type="button"
variant="secondary"
onClick={() => navigate(`/snippets/${id}`)}
>
{t('snippets.action_cancel')}
</Button>
<Button type="submit" disabled={saving}>
{t('snippets.action_update')}
</Button>
</div>
</Card>
</form>
)}
</div>
);
}
@@ -0,0 +1,107 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Pencil, Trash2 } from 'lucide-react';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
import styles from '../Page.module.css';
export function SnippetDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
snippets
.get(Number(id))
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleDelete = async () => {
if (!snippet) return;
await snippets.remove(snippet.id);
navigate('/snippets');
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
{ label: snippet?.name ?? `#${id}` },
]}
/>
{snippet && (
<div className={styles.toolbarActions}>
<Button
variant="secondary"
size="sm"
onClick={() => navigate(`/snippets/${snippet.id}/edit`)}
>
<Pencil size={14} />
{t('snippets.action_edit')}
</Button>
<Button variant="danger" size="sm" onClick={handleDelete}>
<Trash2 size={14} />
{t('snippets.action_delete')}
</Button>
</div>
)}
</div>
{error && (
<Notification
variant="error"
title={error.startsWith('404') ? t('errors.not_found') : undefined}
>
{error.startsWith('404') ? t('errors.not_found_snippet', { id }) : error}
</Notification>
)}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{snippet && (
<>
<div className={styles.detailMeta}>
<DescriptionList
layout="comfortable"
items={[
{ term: t('snippets.field_id'), detail: snippet.id },
{ term: t('snippets.field_name'), detail: snippet.name },
{
term: t('snippets.field_description'),
detail: snippet.description ?? '—',
},
{
term: t('snippets.field_created'),
detail: <Timestamp value={snippet.createdAt} />,
},
{
term: t('snippets.field_updated'),
detail: <Timestamp value={snippet.updatedAt} />,
},
]}
/>
</div>
<div className={styles.stepsSection}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
</div>
<Card>
<pre className={styles.codeBlock}>{snippet.code}</pre>
</Card>
</div>
</>
)}
</div>
);
}
+129
View File
@@ -0,0 +1,129 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Code, Pencil, Trash2, Plus } from 'lucide-react';
import { snippets } from '../../api';
import type { Snippet } from '../../api';
import { Breadcrumbs, Button, Card, ContextMenu, Timestamp } from '../../ui';
import styles from '../Page.module.css';
function SnippetCard({
snippet,
onDelete,
}: {
snippet: Snippet;
onDelete: (id: number) => void;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
const header = (
<div className={styles.envCardHeader}>
<span className={styles.envCardName}>{snippet.name}</span>
<div onClick={(e) => e.stopPropagation()}>
<ContextMenu
align="right"
trigger={
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
<Code size={14} />
</Button>
}
items={[
{
label: t('snippets.action_edit'),
icon: <Pencil size={14} />,
onClick: () => navigate(`/snippets/${snippet.id}/edit`),
},
{
label: t('snippets.action_delete'),
icon: <Trash2 size={14} />,
variant: 'danger',
onClick: () => onDelete(snippet.id),
},
]}
/>
</div>
</div>
);
const footer = (
<div className={styles.envCardFooter}>
<span className={styles.envCardId}>#{snippet.id}</span>
<Timestamp value={snippet.updatedAt} />
</div>
);
return (
<Card
className={styles.envCard}
header={header}
headerVariant="primary"
footer={footer}
onClick={() => navigate(`/snippets/${snippet.id}`)}
>
{snippet.description && (
<p className={styles.muted}>{snippet.description}</p>
)}
</Card>
);
}
function AddSnippetCard() {
const { t } = useTranslation();
const navigate = useNavigate();
return (
<div className={styles.envCardAdd}>
<Button variant="ghost" onClick={() => navigate('/snippets/new')}>
<Plus size={16} />
{t('snippets.action_add')}
</Button>
</div>
);
}
export function SnippetsPage() {
const { t } = useTranslation();
const [items, setItems] = useState<Snippet[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = () => {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
useEffect(() => {
load();
}, []);
const handleDelete = async (id: number) => {
await snippets.remove(id);
load();
};
return (
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
</div>
{error && <p className={styles.error}>{error}</p>}
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
{!loading && (
<div className={styles.envGrid}>
{items.map((s) => (
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
))}
{items.length === 0 && (
<p className={styles.muted}>{t('snippets.empty')}</p>
)}
<AddSnippetCard />
</div>
)}
</div>
);
}
+1 -1
View File
@@ -13,7 +13,7 @@ export default defineConfig({
server: {
proxy: {
'/environments': 'http://localhost:13000',
'/credentials': 'http://localhost:13000',
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': 'http://localhost:13000',
'/sessions': 'http://localhost:13000',
'/scenarios': 'http://localhost:13000',
'/keys': 'http://localhost:13000',