Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/api/test/static-slice.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
expect(await page.locator("html").getAttribute("data-theme")).toBe("light");
expect(await page.locator("body").evaluate((element: any) => (globalThis as any).getComputedStyle(element).backgroundColor)).toBe("rgb(252, 251, 246)");
await page.getByRole("link", { name: "Job-1", exact: true }).click();
await page.getByRole("button", { name: "Run job", exact: true }).click();
await page.getByRole("button", { name: "More run options", exact: true }).click();
await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
await page.getByLabel("Prompt", { exact: true }).fill("Real invocation");
await page.getByLabel("JSON data (optional)").fill('{"number":7}');
await page.getByRole("button", { name: "Invoke", exact: true }).click();
await page.getByRole("button", { name: "Run with prompt", exact: true }).click();
await page.getByRole("heading", { name: "Trace", exact: true }).waitFor();
const runId = new URL(page.url()).pathname.split("/").at(-1)!;
expect(calls.filter(call => call === `POST /api/v1/jobs/${f.jobIds[1]}/invocations`)).toHaveLength(1);
const row = (await f.db.pool.query("SELECT i.context,jr.state FROM app.invocations i JOIN app.job_runs jr ON jr.tenant_id=i.tenant_id AND jr.invocation_id=i.id WHERE jr.tenant_id=$1 AND jr.id=$2", [f.tenantId, runId])).rows[0];
expect(row).toMatchObject({ state: "queued", context: { manual: { prompt: "Real invocation", data: { number: 7 } } } });
expect(row).toMatchObject({ state: "queued", context: { manual: { prompt: "Real invocation", data: {} } } });
await page.reload(); await page.getByText("No trace events yet.", { exact: true }).waitFor();
await f.db.transaction(async client => {
await client.query("INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,event_type,title,preview_text,display_data) VALUES ($1,$2,1,'canonical','assistant_message','Final output','Safe output','{}')", [f.tenantId, runId]);
Expand Down
46 changes: 27 additions & 19 deletions packages/app/src/features/jobs/invoke.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Dialog } from "../../shared/dialog";
import { Button, Input, Textarea, Label } from "../../shared/ui";
import { Button, Textarea, Label } from "../../shared/ui";
import { useRef, useState, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
Expand All @@ -8,8 +8,8 @@ import { messageOf } from "../auth/session";
export function InvokeJob({ jobId, enabled }: { jobId: string; enabled: boolean }) {
const cache = useQueryClient(), navigate = useNavigate();
const retry = useRef<{ payload: string; key: string } | null>(null);
const [open, setOpen] = useState(false);
const [validation, setValidation] = useState("");
const menuButton = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false), [menuOpen, setMenuOpen] = useState(false);
const mutation = useMutation({ retry: false, mutationFn: async (input: { prompt: string; data?: Record<string, unknown>; name?: string }) => {
const payload = JSON.stringify(input);
if (retry.current?.payload !== payload) retry.current = { payload, key: crypto.randomUUID() };
Expand All @@ -21,23 +21,31 @@ export function InvokeJob({ jobId, enabled }: { jobId: string; enabled: boolean
await cache.invalidateQueries({ queryKey: ["runs"] });
await navigate({ to: "/job-runs/$runId", params: { runId: result.runId } });
} });
function invoke(prompt: string) {
if (!enabled || mutation.isPending) return;
mutation.mutate({ prompt });
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); if (mutation.isPending) return;
const form = new FormData(event.currentTarget); setValidation("");
let data: Record<string, unknown> | undefined;
try {
const raw = String(form.get("data") ?? "").trim();
if (raw) { const parsed: unknown = JSON.parse(raw); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(); data = parsed as Record<string, unknown>; }
} catch { setValidation("JSON data must be an object."); return; }
mutation.mutate({ prompt: String(form.get("prompt") ?? ""), data, ...(String(form.get("name") ?? "").trim() ? { name: String(form.get("name")).trim() } : {}) });
const form = new FormData(event.currentTarget);
invoke(String(form.get("prompt") ?? ""));
}
return <div className="my-4"><Button variant="primary" disabled={!enabled} onClick={() => setOpen(true)}>Run job</Button>{open && <Dialog title="Run job" close={() => setOpen(false)}><p className="mb-5 text-sm text-slate-600 dark:text-slate-400">Start a run with optional instructions and trigger data.</p>
<form onSubmit={submit} className="grid gap-3">
<Label>Run name (optional)<Input name="name" maxLength={120} /></Label>
<Label>Prompt<Textarea name="prompt" maxLength={50000} /></Label>
<Label>JSON data (optional)<Textarea name="data" placeholder={'{"key":"value"}'} /></Label>
<Button variant="primary" disabled={!enabled || mutation.isPending}>{mutation.isPending ? "Invoking…" : "Invoke"}</Button>
{(validation || mutation.error) && <p role="alert">{validation || mutation.error?.message}</p>}
</form>
</Dialog>}</div>;
return <div className="relative my-4 flex items-stretch">
<Button variant="primary" disabled={!enabled || mutation.isPending} onClick={() => invoke("")}>{mutation.isPending ? "Running…" : "Run job"}</Button>
<Button ref={menuButton} variant="primary" disabled={!enabled || mutation.isPending} aria-label="More run options" aria-haspopup="menu" aria-expanded={menuOpen} aria-controls="run-job-menu" className="ml-px rounded-l-none px-2" onClick={() => { mutation.reset(); setMenuOpen(value => !value); }}>▾</Button>
{menuOpen && <div id="run-job-menu" role="menu" aria-label="Run options" className="absolute left-0 top-full z-10 mt-2 min-w-44 rounded-lg border border-stone-200 bg-white p-1 shadow-lg dark:border-slate-700 dark:bg-slate-900">
<button role="menuitem" className="block w-full rounded-md px-3 py-2 text-left text-sm hover:bg-stone-100 dark:hover:bg-slate-800" onClick={() => { setMenuOpen(false); mutation.reset(); menuButton.current?.focus(); setOpen(true); }}>Run with prompt</button>
</div>}
{mutation.error && !open && <p role="alert" className="absolute left-0 top-full mt-3 w-max max-w-[min(28rem,calc(100vw-2rem))]">{mutation.error.message}</p>}
{open && <Dialog title="Run with prompt" close={() => setOpen(false)}>
<form onSubmit={submit} className="grid gap-3">
<Label>Prompt<Textarea name="prompt" maxLength={50000} autoFocus /></Label>
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" onClick={() => setOpen(false)}>Cancel</Button>
<Button variant="primary" disabled={!enabled || mutation.isPending}>{mutation.isPending ? "Invoking…" : "Run with prompt"}</Button>
</div>
{mutation.error && <p role="alert">{mutation.error.message}</p>}
</form>
</Dialog>}
</div>;
}
4 changes: 2 additions & 2 deletions packages/app/src/shared/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Button } from "./ui";
/** Native modal semantics provide focus containment, Escape and focus restoration. */
export function Dialog({ title, close, children }: { title: string; close: () => void; children: ReactNode }) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => { const previous = document.activeElement as HTMLElement | null; ref.current?.showModal(); return () => { ref.current?.close(); previous?.focus(); }; }, []);
return <dialog ref={ref} aria-label={title} onClose={close} className="w-[min(42rem,calc(100vw-2rem))]">
useEffect(() => { const previous = document.activeElement as HTMLElement | null; ref.current?.showModal(); ref.current?.querySelector<HTMLElement>("[autofocus], input, textarea, button")?.focus(); return () => { ref.current?.close(); previous?.focus(); }; }, []);
return <dialog ref={ref} aria-label={title} onClose={close} onClick={event => { if (event.target === event.currentTarget) close(); }} className="w-[min(42rem,calc(100vw-2rem))]">
<div className="mb-5 flex items-start justify-between gap-3"><h2>{title}</h2><Button onClick={close} aria-label={`Close ${title.toLowerCase()}`}>✕</Button></div>{children}
</dialog>;
}
54 changes: 46 additions & 8 deletions packages/app/test/jobs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -100,28 +100,66 @@ test("jobs can sort running and title in both directions with accessible state",
assert.deepEqual(await table.locator("tbody a").allTextContents(), ["Zulu", "Idle", "Beta", "Alpha"]);
await context.close();
});
test("invocation validates JSON, preserves retry idempotency and navigates to lightweight run/trace", async () => {
test("split invocation runs defaults immediately and supports prompt-only modal", async () => {
const { page, context } = await contextFor();
await page.route(`**/api/v1/jobs/${jobId}`, route => route.fulfill({ json: { ...summary, promptTemplate: "Template", runNameTemplate: "", executionTargetId: "local", executionTarget: { connectionId: "local", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: "codex" }, triggers: [], currentRuns: 0, maxConcurrency: 2 } }));
const inputs = [];
await page.route(`**/api/v1/jobs/${jobId}/invocations`, route => {
inputs.push(route.request().postDataJSON());
return inputs.length === 1 ? route.fulfill({ status: 503, json: { error: { code: "unavailable", message: "Try again" } } }) : route.fulfill({ status: 202, json: { runId, invocationId: "invocation", state: "queued", duplicate: true } });
return inputs.length < 3 ? route.fulfill({ status: 503, json: { error: { code: "unavailable", message: "Try again" } } }) : route.fulfill({ status: 202, json: { runId, invocationId: "invocation", state: "queued", duplicate: true } });
});
await page.route(`**/api/v1/runs/${runId}/status`, route => route.fulfill({ json: { id: runId, job_id: jobId, job_name: "Review builds", run_name: "Manual run", state: "succeeded", finalizing: false, trace_revision: "rev-1", artifact_state: "stored", started_at: null, created_at: summary.createdAt, updated_at: summary.updatedAt, destination_url: null } }));
await page.route(`**/api/v1/runs/${runId}/trace-pages?**`, route => route.fulfill({ json: { items: [{ id: "e1", sequence: 1, type: "reasoning", title: "Thinking", preview: "<script>alert('xss')</script>", display: {} }], nextCursor: null, revision: "rev-1", reset: false } }));
await page.goto(origin + "/jobs/" + jobId);
await page.getByRole("button", { name: "Run job", exact: true }).click();
await page.getByLabel("JSON data (optional)").fill("[]"); await page.getByRole("button", { name: "Invoke", exact: true }).click();
await page.getByRole("alert").filter({ hasText: "JSON data must be an object" }).waitFor(); assert.equal(inputs.length, 0);
await page.getByLabel("JSON data (optional)").fill('{"build":42}'); await page.getByLabel("Prompt", { exact: true }).fill("Review");
await page.getByRole("button", { name: "Invoke", exact: true }).click(); await page.getByRole("alert").filter({ hasText: "Try again" }).waitFor();
await page.getByRole("button", { name: "Invoke", exact: true }).click(); await page.waitForURL(`**/job-runs/${runId}?**`);
await page.getByRole("alert").filter({ hasText: "Try again" }).waitFor();
assert.equal(inputs.length, 1); assert.equal(inputs[0].prompt, ""); assert.equal(await page.getByRole("dialog").count(), 0);
await page.getByRole("button", { name: "More run options", exact: true }).click(); await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
assert.equal(await page.getByLabel("Run name (optional)").count(), 0); assert.equal(await page.getByLabel("JSON data (optional)").count(), 0);
await page.mouse.click(1, 1); await page.waitForTimeout(50); assert.equal(await page.getByRole("dialog").count(), 0); assert.equal(inputs.length, 1);
await page.getByRole("button", { name: "More run options", exact: true }).click(); await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
await page.getByLabel("Prompt", { exact: true }).fill("Review");
await page.getByRole("heading", { name: "Run with prompt", exact: true }).click(); assert.equal(await page.getByRole("dialog").count(), 1);
await page.getByRole("button", { name: "Run with prompt", exact: true }).click(); await page.getByRole("alert").filter({ hasText: "Try again" }).waitFor();
await page.getByRole("button", { name: "Run with prompt", exact: true }).click(); await page.waitForURL(`**/job-runs/${runId}?**`);
await page.getByText("Thinking · reasoning", { exact: true }).click();
await page.getByText("<script>alert('xss')</script>", { exact: true }).waitFor();
assert.equal(inputs.length, 2); assert.equal(inputs[0].idempotencyKey, inputs[1].idempotencyKey); assert.deepEqual(inputs[1].data, { build: 42 });
assert.equal(inputs.length, 3); assert.equal(inputs[1].prompt, "Review"); assert.equal(inputs[1].idempotencyKey, inputs[2].idempotencyKey);
assert.equal(await page.locator("main script").count(), 0); await context.close();
});
test("invocation preserves retry idempotency and navigates to lightweight run/trace", async () => {
const { page, context } = await contextFor();
await page.route(`**/api/v1/jobs/${jobId}`, route => route.fulfill({ json: { ...summary, promptTemplate: "Template", runNameTemplate: "", executionTargetId: "local", executionTarget: { connectionId: "local", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: "codex" }, triggers: [], currentRuns: 0, maxConcurrency: 2 } }));
const inputs = [];
await page.route(`**/api/v1/jobs/${jobId}/invocations`, route => {
inputs.push(route.request().postDataJSON());
return inputs.length === 1 ? route.fulfill({ status: 503, json: { error: { code: "unavailable", message: "Try again" } } }) : route.fulfill({ status: 202, json: { runId, invocationId: "invocation", state: "queued", duplicate: true } });
});
await page.route(`**/api/v1/runs/${runId}/status`, route => route.fulfill({ json: { id: runId, job_id: jobId, job_name: "Review builds", run_name: "Manual run", state: "succeeded", finalizing: false, trace_revision: "rev-1", artifact_state: "stored", started_at: null, created_at: summary.createdAt, updated_at: summary.updatedAt, destination_url: null } }));
await page.route(`**/api/v1/runs/${runId}/trace-pages?**`, route => route.fulfill({ json: { items: [{ id: "e1", sequence: 1, type: "reasoning", title: "Thinking", preview: "<script>alert('xss')</script>", display: {} }], nextCursor: null, revision: "rev-1", reset: false } }));
await page.goto(origin + "/jobs/" + jobId);
await page.getByRole("button", { name: "More run options", exact: true }).click();
await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
await page.getByLabel("Prompt", { exact: true }).fill("Review");
await page.getByRole("button", { name: "Run with prompt", exact: true }).click();
await page.getByRole("alert").filter({ hasText: "Try again" }).waitFor();
await page.getByRole("button", { name: "Run with prompt", exact: true }).click(); await page.waitForURL(`**/job-runs/${runId}?**`);
await page.getByText("Thinking · reasoning", { exact: true }).click(); await page.getByText("<script>alert('xss')</script>", { exact: true }).waitFor();
assert.equal(inputs.length, 2); assert.equal(inputs[0].idempotencyKey, inputs[1].idempotencyKey); assert.equal(inputs[1].prompt, "Review");
assert.equal(await page.locator("main script").count(), 0); await context.close();
});
test("prompt modal Escape restores focus and does not run", async () => {
const { page, context } = await contextFor();
await page.route(`**/api/v1/jobs/${jobId}`, route => route.fulfill({ json: { ...summary, promptTemplate: "Template", runNameTemplate: "", executionTargetId: "local", executionTarget: { connectionId: "local", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: "codex" }, triggers: [], currentRuns: 0, maxConcurrency: 2 } }));
const inputs = [];
await page.route(`**/api/v1/jobs/${jobId}/invocations`, route => { inputs.push(route.request().postDataJSON()); return route.fulfill({ status: 202, json: { runId, invocationId: "invocation", state: "queued", duplicate: false } }); });
await page.goto(origin + "/jobs/" + jobId);
await page.getByRole("button", { name: "More run options", exact: true }).click(); await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
await page.getByLabel("Prompt", { exact: true }).fill("Do not run"); await page.keyboard.press("Escape");
assert.equal(inputs.length, 0); assert.equal(await page.getByRole("dialog").count(), 0);
await page.getByRole("button", { name: "More run options", exact: true }).focus(); assert.equal(await page.getByRole("button", { name: "More run options", exact: true }).evaluate(el => el === document.activeElement), true);
await context.close();
});
test("trace reset between requests discards old pages and finalization keeps terminal polling alive", async () => {
const { page, context } = await contextFor();
let statusCalls = 0, reset = false;
Expand Down
Binary file modified packages/app/test/visual/baselines/job-dark-1280.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/job-dark-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/job-light-1280.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/job-light-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/long-job-mobile.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 4 additions & 4 deletions packages/app/test/visual/design.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ test("mobile profile, search and run dialog keyboard/focus behavior; long conten
await page.getByRole("button", { name: "Search jobs and runs", exact: true }).click();
await expect(page.getByRole("combobox", { name: "Search jobs and runs", exact: true })).toBeFocused();
await page.keyboard.press("Escape"); await expect(page.getByRole("dialog")).toHaveCount(0);
const run = page.getByRole("button", { name: "Run job", exact: true }); await run.click();
await page.getByLabel("JSON data (optional)").fill("[]"); await page.getByRole("button", { name: "Invoke", exact: true }).click();
await expect(page.getByRole("alert")).toHaveText("JSON data must be an object.");
await expect(page).toHaveScreenshot("run-dialog-validation-mobile.png");
const run = page.getByRole("button", { name: "More run options", exact: true }); await run.click();
await page.getByRole("menuitem", { name: "Run with prompt", exact: true }).click();
await page.getByLabel("Prompt", { exact: true }).fill("Review");
await expect(page.getByRole("dialog")).toBeVisible();
await page.keyboard.press("Escape"); await expect(run).toBeFocused();
await expect(page.getByText("Prompt template", { exact: true })).toHaveCount(0);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
Expand Down