From daecf3d539345b96729fae9bd35d92a3ed69ee39 Mon Sep 17 00:00:00 2001 From: Andrii Arsenin Date: Thu, 1 Oct 2026 14:45:03 +0300 Subject: [PATCH] feat(client): add code reference modal to step and snippet editors - a (?) button next to the Code label on the step and snippet create/edit pages opens a reference of the script runtime: globals, every context member with examples, and pitfalls such as awaiting getStepOutput and assert - the reference lives in components/modals/code-help.md and is rendered as markdown - Modal takes size="lg" for document-like content; the dialog is capped to the viewport and its body scrolls, focusable when lg so the keyboard can scroll it - docs/scenario.md notes that getStepOutput is async and points to the in-app reference to keep in sync --- client/.storybook/stories/Modal.stories.tsx | 37 +++- .../modals/CodeHelpModal.module.css | 20 ++ .../src/components/modals/CodeHelpModal.tsx | 54 +++++ client/src/components/modals/code-help.md | 186 ++++++++++++++++++ client/src/components/modals/index.ts | 2 + client/src/i18n/locales/en.json | 5 + client/src/pages/Page.module.css | 6 + client/src/pages/scenario/CreateStepPage.tsx | 6 +- client/src/pages/scenario/EditStepPage.tsx | 6 +- .../src/pages/snippet/CreateSnippetPage.tsx | 12 +- client/src/pages/snippet/EditSnippetPage.tsx | 12 +- client/src/ui/Modal/Modal.module.css | 8 + client/src/ui/Modal/Modal.tsx | 11 +- docs/scenario.md | 4 +- 14 files changed, 354 insertions(+), 15 deletions(-) create mode 100644 client/src/components/modals/CodeHelpModal.module.css create mode 100644 client/src/components/modals/CodeHelpModal.tsx create mode 100644 client/src/components/modals/code-help.md diff --git a/client/.storybook/stories/Modal.stories.tsx b/client/.storybook/stories/Modal.stories.tsx index 0ee07d0..5ff89ef 100644 --- a/client/.storybook/stories/Modal.stories.tsx +++ b/client/.storybook/stories/Modal.stories.tsx @@ -4,13 +4,22 @@ import { expect, userEvent, within } from 'storybook/test'; import { Modal } from '../../src/ui/Modal/Modal'; import { Button } from '../../src/ui/Button/Button'; -function ModalDemo({ title, body }: { title: string; body: string }) { +function ModalDemo({ + title, + body, + size, +}: { + title: string; + body: React.ReactNode; + size?: 'md' | 'lg'; +}) { const [open, setOpen] = useState(false); return ( <> setOpen(false)} footer={ @@ -61,3 +70,29 @@ export const ClosesOnEscapeAndBackdrop: Story = { await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument(); }, }; + +export const Large: Story = { + args: { + title: 'Code reference', + size: 'lg', + body: ( + <> + {Array.from({ length: 60 }, (_, i) => ( +

Paragraph {i + 1} of a long, document-like modal body.

+ ))} + + ), + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole('button', { name: 'Open modal' })); + const dialog = canvas.getByRole('dialog', { name: 'Code reference' }); + // The dialog stays within the viewport; its body scrolls instead. + await expect(dialog.getBoundingClientRect().height).toBeLessThanOrEqual(window.innerHeight); + const body = within(dialog).getByText( + 'Paragraph 1 of a long, document-like modal body.', + ).parentElement!; + await expect(body.scrollHeight).toBeGreaterThan(body.clientHeight); + await expect(within(dialog).getByRole('button', { name: 'Confirm' })).toBeVisible(); + }, +}; diff --git a/client/src/components/modals/CodeHelpModal.module.css b/client/src/components/modals/CodeHelpModal.module.css new file mode 100644 index 0000000..e64428f --- /dev/null +++ b/client/src/components/modals/CodeHelpModal.module.css @@ -0,0 +1,20 @@ +.helpButton { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 2px; + border: none; + border-radius: var(--radius-sm); + background: none; + color: var(--color-text-muted); + cursor: pointer; +} + +.helpButton:hover { + color: var(--color-primary); +} + +.helpButton:focus-visible { + outline: none; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.35); +} diff --git a/client/src/components/modals/CodeHelpModal.tsx b/client/src/components/modals/CodeHelpModal.tsx new file mode 100644 index 0000000..2f11032 --- /dev/null +++ b/client/src/components/modals/CodeHelpModal.tsx @@ -0,0 +1,54 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { CircleHelp, X } from 'lucide-react'; +import { Modal, Button, MarkdownContent } from '../../ui'; +import content from './code-help.md?raw'; +import styles from './CodeHelpModal.module.css'; + +export interface CodeHelpModalProps { + open: boolean; + onClose: () => void; +} + +/** Reference for the script runtime (`context`, `expect`, ...) available to step and snippet code. */ +export function CodeHelpModal({ open, onClose }: CodeHelpModalProps) { + const { t } = useTranslation(); + + return ( + + + {t('code_help.close')} + + } + > + + + ); +} + +/** A (?) button that opens the {@link CodeHelpModal}; place it next to a code field label. */ +export function CodeHelpButton() { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + + return ( + <> + + setOpen(false)} /> + + ); +} diff --git a/client/src/components/modals/code-help.md b/client/src/components/modals/code-help.md new file mode 100644 index 0000000..cd01cd7 --- /dev/null +++ b/client/src/components/modals/code-help.md @@ -0,0 +1,186 @@ +Step code and snippet code are the **body of an async function**. Use `await` freely; whatever you `return` becomes the step (or snippet) output. + +```js +async (context) => { + // your code here +} +``` + +All steps of a run share one browser, one browser context and one page, so state carries over from step to step: the current URL, cookies, local storage, open dialogs. + +A step **passes** when its code returns, and **fails** when it throws or exceeds its timeout. When a step fails, the remaining steps are cancelled, and a screenshot and the page HTML are saved to the run's files. + +## Globals + +| Name | Description | +| --- | --- | +| `context` | The run context, described below. | +| `expect` | Playwright's [`expect`](https://playwright.dev/docs/test-assertions), with auto-retrying web assertions. | +| `console` | Writes to the run log: `log`/`info` → `log`, plus `warn`, `error` and `debug`. | +| `args` | **Snippets only.** The extra arguments passed to `context.runSnippet(name, ...args)`. | + +Code runs in the server process with Node.js. It is trusted code, not sandboxed. + +## Browser + +### `context.page` + +The Playwright [`Page`](https://playwright.dev/docs/api/class-page) of the run. + +```js +await context.page.goto(context.getEnv("base_url")); +await context.page.getByRole("button", { name: "Sign in" }).click(); +await expect(context.page.locator("h1")).toHaveText("Dashboard"); +``` + +### `context.browser` + +The Playwright [`BrowserContext`](https://playwright.dev/docs/api/class-browsercontext) the page belongs to. Use it for cookies, storage state, extra pages and HTTP requests that share the browser's cookies. + +```js +const cookies = await context.browser.cookies(); +const res = await context.browser.request.get(context.getEnv("api_url") + "/me"); +``` + +### `context.dumpDom(selector?)` → `Promise` + +Returns a simplified tree of the live DOM, starting at `selector` (default `"body"`). Decorative and layout elements are filtered out. The tree keeps landmarks, interactive elements, and elements with `role`, `data-testid`, `data-qa`, `data-action` or `data-element-id`. Each node has `tag` and `children`, plus `role`, `testid`, `id`, `name`, `type`, `text`, `href`, `checked`, `disabled`, etc. when they are present. This is useful for finding selectors without a screenshot. + +If nothing matches `selector`, it returns a node with `tag: "ERROR"` instead of throwing. + +```js +context.log("Login form:", await context.dumpDom("form")); +``` + +## Environment + +### `context.env` + +A copy of the selected environment's key/value map, `{}` when there is none. A missing key reads as `undefined`. + +### `context.getEnv(key)` → `string` + +Returns the environment value for `key`, and **throws** if it is not defined. Prefer it over `context.env[key]` for required settings: the step then fails with a clear message. + +```js +const baseUrl = context.getEnv("base_url"); +const locale = context.env.locale ?? "en"; +``` + +## Credentials + +### `context.getCredential(alias)` → `unknown` + +Returns the payload of the credential assigned to this scenario under `alias` (see **Credentials** on the scenario page). JSON data is returned parsed, anything else as a string. **Throws** if no credential has that alias. + +```js +const { username, password } = context.getCredential("admin"); +await context.page.getByLabel("Username").fill(username); +await context.page.getByLabel("Password").fill(password); +``` + +## Step outputs + +### `context.getStepOutput(order)` → `Promise` + +Returns the output (the return value) of another step in the same run. **It is async, so `await` it.** + +- A positive `order` is absolute: `1` is the first step. +- A negative `order` is relative: `-1` is the previous step. + +Returns `null` if that step does not exist, has not run, or returned nothing. A step's output is stored as JSON, so only JSON-serializable values come back as they were returned (no functions, `Date` becomes a string, Playwright objects are not usable). + +```js +// step 2 +return { orderId: await context.page.locator("#order-id").textContent() }; + +// step 3 +const { orderId } = await context.getStepOutput(-1); +``` + +## Logging + +### `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)` + +Write an entry with that level to the run log. `console.*` does the same. Strings, numbers and booleans are joined with spaces into the message. Objects and arrays are kept separate as structured **data**, shown pretty-printed under the message: one object is stored as is, several are stored as an array. + +```js +context.log("Created user", user.id, user); // message "Created user 42", data = user +``` + +Every entry is tagged with where it came from: `step:`, or `snippet:` while a snippet runs. + +## Assertions + +### `context.assert(fn, description)` → `Promise` + +Runs `fn` (sync or async) and requires it to return exactly `true`. + +- On success, it logs `description` (tagged `assertion:pass`). +- If `fn` returns anything else or throws, it logs `Assertion failed: ` as an error (tagged `assertion:fail`) and throws, which fails the step. + +Await it, or a failure will not stop the step. + +```js +await context.assert( + async () => (await context.page.locator(".cart-item").count()) === 3, + "Cart contains 3 items", +); +``` + +Use `expect` instead for assertions that wait and retry until the page matches, e.g. `await expect(locator).toBeVisible()`. + +## Snippets + +### `context.runSnippet(name, ...args)` → `Promise` + +Runs a stored snippet with the same `context` (same page, environment and credentials) and returns the snippet's return value. Extra arguments are available inside the snippet as `args`. + +- `name` is the snippet alias, which runs its latest version. +- `alias@` (e.g. `login@3`) pins a specific version. + +Start, finish and failure are logged. If the snippet throws, the error propagates and fails the calling step unless you catch it. Snippets can call other snippets. + +```js +// step code +const user = await context.runSnippet("login", "admin", { remember: true }); + +// snippet "login" +const [alias, opts] = args; +const { username, password } = context.getCredential(alias); +// ... +return { username }; +``` + +## Files + +### `context.getScenarioFiles(opts?)` → `Promise<{ items, total }>` + +Lists the files uploaded to this scenario (see **Files** on the scenario page). `opts` takes `limit` and `offset` for paging. Each item has `id`, `name`, `mimeType`, `size`, `sha256` and `path`, the absolute path on the server's disk, which you can pass to Playwright: + +```js +const { items } = await context.getScenarioFiles(); +const doc = items.find((f) => f.name === "contract.pdf"); +await context.page.locator("input[type=file]").setInputFiles(doc.path); +``` + +### `context.downloadFile(url, opts?)` → `Promise` + +Fetches `url` on the server and saves the response as a file of the current run. It returns the same fields as a scenario file (`id`, `name`, `mimeType`, `size`, `sha256`, `path`). + +- `opts`: `method`, `headers`, `body` (a string) and `filename`. Without `filename`, the last segment of the URL path is used, and the MIME type is derived from the file extension. +- Redirects are followed. Any final status other than 200 throws. The limits are 100 MB and a 30 s timeout. +- `url` may be a `data:` URI (`data:;base64,` or `data:,`), which saves content generated in the script without a network request. Pass `filename` in this case. +- Only works during a real scenario run. It throws in ad-hoc execution such as the `exec_code` MCP tool. +- This is a server-side request: it does **not** send the browser's cookies. Pass them in `headers` if the URL needs a session. + +```js +await context.downloadFile( + "data:application/json;base64," + btoa(JSON.stringify(report)), + { filename: "report.json" }, +); +``` + +## Timeouts + +Each step has its own timeout, or else the scenario's timeout, or else 60 s. The whole run fails once it exceeds the scenario's timeout (600 s by default). That check happens between steps. diff --git a/client/src/components/modals/index.ts b/client/src/components/modals/index.ts index 6ca120a..9e73fdb 100644 --- a/client/src/components/modals/index.ts +++ b/client/src/components/modals/index.ts @@ -6,3 +6,5 @@ export { RunScenarioModal } from './RunScenarioModal'; export type { RunScenarioModalProps } from './RunScenarioModal'; export { ExportLogsModal } from './ExportLogsModal'; export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal'; +export { CodeHelpModal, CodeHelpButton } from './CodeHelpModal'; +export type { CodeHelpModalProps } from './CodeHelpModal'; diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.json index c67816a..1ce077b 100644 --- a/client/src/i18n/locales/en.json +++ b/client/src/i18n/locales/en.json @@ -12,6 +12,11 @@ "confirm_remove_credential": "Are you sure you want to remove this credential from scenario?", "save_session": "Save session" }, + "code_help": { + "open": "Code reference", + "title": "Code reference", + "close": "Close" + }, "errors": { "not_found": "Not found", "not_found_session": "Session {{id}} does not exist or has been deleted.", diff --git a/client/src/pages/Page.module.css b/client/src/pages/Page.module.css index a299cb7..e094bcd 100644 --- a/client/src/pages/Page.module.css +++ b/client/src/pages/Page.module.css @@ -255,6 +255,12 @@ color: var(--color-text); } +.labelRow { + display: flex; + align-items: center; + gap: var(--space-1); +} + .textarea { width: 100%; padding: var(--space-2) var(--space-3); diff --git a/client/src/pages/scenario/CreateStepPage.tsx b/client/src/pages/scenario/CreateStepPage.tsx index fc01299..3529cba 100644 --- a/client/src/pages/scenario/CreateStepPage.tsx +++ b/client/src/pages/scenario/CreateStepPage.tsx @@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react'; import { scenarios, steps } from '../../api'; import type { Scenario } from '../../api'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; +import { CodeHelpButton } from '../../components/modals'; import styles from '../Page.module.css'; export function CreateStepPage() { @@ -77,7 +78,10 @@ export function CreateStepPage() { onChange={(e) => setTitle(e.target.value)} />
- +
+ + +
setTitle(e.target.value)} />
- +
+ + +
- +
+ + +
{ diff --git a/client/src/pages/snippet/EditSnippetPage.tsx b/client/src/pages/snippet/EditSnippetPage.tsx index f1f5fa5..f6b9855 100644 --- a/client/src/pages/snippet/EditSnippetPage.tsx +++ b/client/src/pages/snippet/EditSnippetPage.tsx @@ -6,6 +6,7 @@ import { X, Save, Braces } from 'lucide-react'; import { snippets } from '../../api'; import type { Snippet } from '../../api'; import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui'; +import { CodeHelpButton } from '../../components/modals'; import styles from '../Page.module.css'; export function EditSnippetPage() { @@ -134,10 +135,13 @@ export function EditSnippetPage() { />
- +
+ + +
{ diff --git a/client/src/ui/Modal/Modal.module.css b/client/src/ui/Modal/Modal.module.css index dc9dedc..94f7abd 100644 --- a/client/src/ui/Modal/Modal.module.css +++ b/client/src/ui/Modal/Modal.module.css @@ -16,6 +16,13 @@ border-radius: var(--radius-lg); box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent); overflow: hidden; + display: flex; + flex-direction: column; + max-height: 100%; +} + +.lg { + width: min(880px, 100%); } .header { @@ -31,6 +38,7 @@ .body { padding: var(--space-2) var(--space-5) var(--space-4); color: var(--color-text-muted); + overflow-y: auto; } .footer { diff --git a/client/src/ui/Modal/Modal.tsx b/client/src/ui/Modal/Modal.tsx index d15b971..29873f7 100644 --- a/client/src/ui/Modal/Modal.tsx +++ b/client/src/ui/Modal/Modal.tsx @@ -7,9 +7,11 @@ export interface ModalProps { children?: React.ReactNode; onClose: () => void; footer?: React.ReactNode; + /** `lg` widens the dialog for long, document-like content. */ + size?: 'md' | 'lg'; } -export function Modal({ open, title, children, onClose, footer }: ModalProps) { +export function Modal({ open, title, children, onClose, footer, size = 'md' }: ModalProps) { useEffect(() => { if (!open) return; const onKeyDown = (event: KeyboardEvent) => { @@ -24,7 +26,7 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) { return (

{title}

-
{children}
+ {/* Long (lg) content scrolls; make it focusable so the keyboard can scroll it. */} +
+ {children} +
{footer &&
{footer}
}
diff --git a/docs/scenario.md b/docs/scenario.md index 7738347..a159c5e 100644 --- a/docs/scenario.md +++ b/docs/scenario.md @@ -32,7 +32,7 @@ Available on `context`: - `context.env`: shallow copy of the environment's key/value map - `context.getEnv(key)`: environment value lookup (throws if missing) - `context.getCredential(alias)`: payload of the credential assigned to the scenario under `alias` (parsed JSON when the data is JSON; throws if missing) -- `context.getStepOutput(order)`: output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none +- `context.getStepOutput(order)`: async (`await` it); output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none - `context.dumpDom(selector?)`: simplified DOM snapshot of the page (or of one element) - `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`: run log entries - `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw @@ -47,6 +47,8 @@ Also in scope: Code is syntax-checked before it runs, and executes in the server process: it's trusted code, not sandboxed. +The step and snippet editors have a (?) button next to the Code label that opens a reference of this runtime in the UI. Its content is [client/src/components/modals/code-help.md](../client/src/components/modals/code-help.md): keep it in sync with this section when the `context` API changes. + ## Run logs Each run log entry (`level`, `message`, `createdAt`) also carries a `context`: where the message was generated. Contexts: