Skip to content
Merged
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
2 changes: 1 addition & 1 deletion packages/api/test/job-lifecycle.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
await complete(a, other, "succeeded");
await Promise.all([deliver(), deliver()]);
expect(await invocations(a, target.id)).toHaveLength(2);
}, 10_000);
}, 20_000);

it("does not create lifecycle work from unrelated prompt edits or re-enabling", async () => {
const a = await tenant(), source = await job(a);
Expand Down
4 changes: 2 additions & 2 deletions packages/api/test/static-slice.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
expect(failures).toEqual([]);
await context.close();
} finally { await browser.close(); await f.cleanup(); }
}, 30000);
}, 90_000);
it("edits a real job with a racing write, reconciles safely and creates/revokes a real API key", async () => {
const f = await loadingFixture(url!), browser = await chromium.launch({ headless: true });
try {
Expand Down Expand Up @@ -136,6 +136,6 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
expect((await f.db.pool.query("SELECT revoked_at FROM app.access_tokens WHERE tenant_id=$1", [f.tenantId])).rows[0].revoked_at).not.toBeNull();
await context.close();
} finally { await browser.close(); await f.cleanup(); }
}, 30000);
}, 90_000);

});
2 changes: 1 addition & 1 deletion packages/api/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
test: { exclude: ["test/**/*.e2e.test.ts", "**/node_modules/**", "**/.git/**"] },
test: { hookTimeout: 30_000, exclude: ["test/**/*.e2e.test.ts", "**/node_modules/**", "**/.git/**"] },
});
13 changes: 9 additions & 4 deletions packages/app/src/features/runs/continuous-trace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function conversation(events: Event[]): ConversationItem[] {
return result;
}

export function ContinuousTrace({ runId, revision, active, onReset }: { runId: string; revision: string; active: boolean; onReset: (revision: string) => void }) {
export function ContinuousTrace({ runId, revision, active, onReset, preview = false }: { runId: string; revision: string; active: boolean; onReset: (revision: string) => void; preview?: boolean }) {
const [liveItems, setLiveItems] = useState<Event[]>([]);
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const [pullDistance, setPullDistance] = useState(0);
Expand All @@ -40,7 +40,7 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
queryKey: ["runs", runId, "conversation-trace", revision],
initialPageParam: { mode: "recent" } as PageParam,
queryFn: async ({ signal, pageParam }) => {
const query = pageParam.mode === "recent" ? { recent: true, revision: pageParam.revision, limit: 100 } : { before: pageParam.cursor, revision: pageParam.revision, limit: 100 };
const query = pageParam.mode === "recent" ? { recent: true, revision: pageParam.revision, limit: preview ? 20 : 100 } : { before: pageParam.cursor, revision: pageParam.revision, limit: 100 };
const { data, error } = await api.GET("/api/v1/runs/{runId}/trace-pages", { signal, params: { path: { runId }, query } });
if (!data || error) throw new Error(messageOf(error));
return data;
Expand All @@ -53,7 +53,7 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
const latestSequence = items.at(-1)?.sequence ?? 0;
const live = useQuery({
queryKey: ["runs", runId, "conversation-tail", revision, latestSequence],
enabled: active && !!trace.data && !trace.isFetching,
enabled: !preview && active && !!trace.data && !trace.isFetching,
queryFn: async ({ signal }) => {
const { data, error } = await api.GET("/api/v1/runs/{runId}/trace-pages", { signal, params: { path: { runId }, query: { after: latestSequence, revision, limit: 100 } } });
if (!data || error) throw new Error(messageOf(error)); return data;
Expand Down Expand Up @@ -135,7 +135,12 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
observer.observe(element);
return () => { window.removeEventListener("resize", resize); observer.disconnect(); };
}, []);
const grouped = conversation(items);
const grouped = conversation(preview ? items.slice(-10) : items);
if (preview) return <div data-run-trace data-run-trace-preview aria-label="Recent run trace" className="space-y-4">
{trace.error && <p role="alert">{trace.error.message}</p>}{trace.isPending && <p role="status">Loading conversation…</p>}
{!trace.isPending && !grouped.length && <p className="text-sm text-slate-600 dark:text-slate-400">No assistant messages yet.</p>}
{grouped.map((item, index) => item.kind === "assistant" ? <article key={item.event.id} className="min-w-0"><EventBody event={item.event} /></article> : <Disclosure key={item.events[0]?.id + ":" + index} className={traceClasses("tool_call")} open={expanded.has(item.events[0]?.id + ":" + index)} onToggle={event => { const key = item.events[0]?.id + ":" + index; const open = event.currentTarget.open; setExpanded(previous => { const next = new Set(previous); open ? next.add(key) : next.delete(key); return next; }); }}><Summary>{item.count} Tool Call{item.count === 1 ? "" : "s"}</Summary><div className="space-y-3">{item.events.map(event => <div key={event.id}><EventBody event={event} /></div>)}</div></Disclosure>)}
</div>;
return <>{trace.error && <p role="alert">{trace.error.message}</p>}{trace.isPending && <p role="status">Loading conversation…</p>}
<div ref={scrollRef} data-run-trace-scroll aria-label="Run trace" className="-mx-4 h-[min(60rem,calc(100svh-18rem))] min-h-64 w-[calc(100%+2rem)] min-w-0 overflow-y-auto overscroll-contain p-0 sm:mx-0 sm:h-[min(60rem,calc(100svh-18rem))] sm:w-auto" onScroll={updateScrollState} onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd} onTouchCancel={onTouchEnd}>
{(pullDistance > 0 || pullLoading) && <p data-run-trace-pull role="status" aria-live="polite" className="sticky top-0 z-10 -mb-8 flex h-8 items-center justify-center bg-stone-50/90 text-xs font-medium text-slate-600 backdrop-blur dark:bg-slate-950/90 dark:text-slate-400">{pullLoading ? "Loading older events…" : pullDistance >= 56 ? "Release to load older events" : `Pull to load older events · ${Math.round((pullDistance / 56) * 100)}%`}</p>}
Expand Down
17 changes: 9 additions & 8 deletions packages/app/src/features/runs/detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function RunDetail() {
const { runId } = useParams({ strict: false });
const location = useLocation(), navigate = useNavigate(), cache = useQueryClient();
const tab: "trace" | "info" = location.pathname.endsWith("/info") ? "info" : "trace";
const fullTrace = location.pathname.endsWith("/trace");
const tabPath = (name: "trace" | "info"): "/job-runs/$runId" | "/job-runs/$runId/info" => name === "trace" ? "/job-runs/$runId" : "/job-runs/$runId/info";
const status = useQuery(runStatusQuery(runId!));
const [revision, setRevision] = useState("");
Expand Down Expand Up @@ -62,16 +63,16 @@ export function RunDetail() {
</>}
{!status.data && <ResourceHeader type="Run" title="Run" />}
{stop.error && <p role="alert">{stop.error.message}</p>}
<nav role="tablist" aria-label="Run details" className="mt-5 flex gap-1 overflow-x-auto border-b border-stone-200 dark:border-slate-700">
{!fullTrace && <nav role="tablist" aria-label="Run details" className="mt-5 flex gap-1 overflow-x-auto border-b border-stone-200 dark:border-slate-700">
{(["trace", "info"] as const).map((name, index, tabs) => <Link key={name} to={tabPath(name)} params={{ runId: runId! }} search={{ after: 0 }} role="tab" id={`run-tab-${name}`} aria-controls={`run-panel-${name}`} aria-selected={tab === name} tabIndex={tab === name ? 0 : -1}
className={`min-h-11 shrink-0 border-b-2 px-4 py-3 text-sm capitalize ${tab === name ? "border-factorize-500 font-semibold" : "border-transparent text-slate-600 hover:border-stone-300 dark:text-slate-400"}`}
onKeyDown={event => {
const next = event.key === "ArrowRight" ? (index + 1) % tabs.length : event.key === "ArrowLeft" ? (index + tabs.length - 1) % tabs.length : event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : null;
if (next === null) return;
event.preventDefault(); void navigate({ to: tabPath(tabs[next]), params: { runId: runId! }, search: { after: 0 } }).then(() => document.getElementById(`run-tab-${tabs[next]}`)?.focus());
}}>{name === "info" ? "Info" : name[0].toUpperCase() + name.slice(1)}</Link>)}
</nav>
<section role="tabpanel" id="run-panel-info" aria-labelledby="run-tab-info" hidden={tab !== "info"} tabIndex={0}>
</nav>}
{!fullTrace && <section role="tabpanel" id="run-panel-info" aria-labelledby="run-tab-info" hidden={tab !== "info"} tabIndex={0}>
{status.data && <dl className="my-4 grid min-w-0 gap-4 sm:grid-cols-2">
<div><dt className="text-sm font-semibold text-slate-700 dark:text-slate-300">Created</dt><dd className="break-words text-sm text-slate-600 dark:text-slate-400">{new Date(status.data.created_at).toLocaleString()}</dd></div>
<div><dt className="text-sm font-semibold text-slate-700 dark:text-slate-300">Started</dt><dd className="break-words text-sm text-slate-600 dark:text-slate-400">{status.data.started_at ? new Date(status.data.started_at).toLocaleString() : "Not started yet"}</dd></div>
Expand All @@ -81,10 +82,10 @@ export function RunDetail() {
</dl>}
<ExpandedRunDetail runId={runId!} />
{status.data && !active ? <ReplayTrace runId={runId!} /> : <p className="my-4">Replay is available after the run finishes and trace finalization completes.</p>}
</section>
<section role="tabpanel" id="run-panel-trace" aria-labelledby="run-tab-trace" hidden={tab !== "trace"} tabIndex={0} className="flex min-h-0 flex-col">
<h2 className="my-4 text-xl font-semibold">Trace</h2>
<ContinuousTrace key={revision} runId={runId!} revision={revision} active={active} onReset={next => { if (next === revision) return; void cache.cancelQueries({ queryKey: ["runs", runId, "continuous-trace"] }); cache.removeQueries({ queryKey: ["runs", runId, "continuous-trace"] }); setRevision(next); cache.setQueryData(runStatusQuery(runId!).queryKey, previous => previous ? { ...previous, trace_revision: next } : previous); cache.removeQueries({ queryKey: ["runs", runId, "continuous-tail"] }); }} />
</section>
</section>}
{(fullTrace || tab === "trace") && <section role="tabpanel" id="run-panel-trace" aria-labelledby="run-tab-trace" hidden={!fullTrace && tab !== "trace"} tabIndex={0} className="flex min-h-0 flex-col">
{fullTrace ? <><Breadcrumb><Link to="/job-runs/$runId" params={{ runId: runId! }}>Run overview</Link></Breadcrumb><h2 className="my-4 text-xl font-semibold">Full trace</h2></> : <div className="my-4 flex flex-wrap items-center justify-between gap-3"><h2 className="text-xl font-semibold">Trace</h2><a className="rounded-lg border border-stone-300 px-3 py-2 text-sm font-medium hover:bg-stone-100 dark:border-slate-700 dark:hover:bg-slate-800" href={`/job-runs/${encodeURIComponent(runId!)}/trace`} target="_blank" rel="noopener noreferrer">Show full trace</a></div>}
<ContinuousTrace key={`${revision}:${fullTrace}`} runId={runId!} revision={revision} active={active} preview={!fullTrace} onReset={next => { if (next === revision) return; void cache.cancelQueries({ queryKey: ["runs", runId, "continuous-trace"] }); cache.removeQueries({ queryKey: ["runs", runId, "continuous-trace"] }); setRevision(next); cache.setQueryData(runStatusQuery(runId!).queryKey, previous => previous ? { ...previous, trace_revision: next } : previous); cache.removeQueries({ queryKey: ["runs", runId, "continuous-tail"] }); }} />
</section>}
</Page>;
}
9 changes: 5 additions & 4 deletions packages/app/test/editor.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ before(async () => {
after(async () => { await browser?.close(); if (server) await new Promise(resolve => server.close(resolve)); });
async function setup(options) {
const context = await browser.newContext(options), page = await context.newPage();
await page.route("**/api/v1/runs?**", route => route.fulfill({ json: { items: [], nextCursor: null } })); page.setDefaultTimeout(10000);
await page.route("**/api/v1/runs?**", route => route.fulfill({ json: { items: [], nextCursor: null } })); page.setDefaultTimeout(30000);
await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "tenant", name: "Workspace" }, capabilities: [], expiresAt: "2026-10-10T00:00:00Z" } }));
await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [{ connectionId: "vm", agentKind: "codex", tags: [], models: ["gpt-6"] }], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } }));
await page.route("**/api/v1/trigger-contexts", route => route.fulfill({ json: { manual: [{ path: "prompt", type: "string", description: "Manual prompt" }] } }));
Expand Down Expand Up @@ -152,16 +152,17 @@ test("template insertion escapes values and navigation protects unsaved work", a
const { context, page } = await setup(); await page.route(`**/api/v1/jobs/${id}`, route => route.fulfill({ json: initial }));
await page.goto(origin + `/jobs/${id}/edit`); await page.getByText("Insert a prompt template variable", { exact: true }).click(); await page.getByLabel("Prompt template", { exact: true }).focus(); await page.getByLabel("Prompt template", { exact: true }).press("End"); await page.getByRole("button", { name: "trigger-1.prompt", exact: true }).click();
assert.equal(await page.getByLabel("Prompt template", { exact: true }).inputValue(), "Original prompt{{trigger-1.prompt}}");
page.once("dialog", dialog => dialog.dismiss()); await page.locator("main").getByRole("link", { name: "Projects", exact: true }).click(); assert.ok(page.url().includes("/settings")); await context.close();
await page.locator("main").getByRole("link", { name: "Projects", exact: true }).click(); assert.equal(new URL(page.url()).pathname, `/jobs/${id}/settings`, page.url()); await context.close();
});
test("provider editor fetches only the selected provider and submits project/matching/conditions configuration explicitly", async () => {
const { context, page } = await setup(); const reads = [], writes = []; let current = structuredClone(initial);
await page.route(`**/api/v1/jobs/${id}`, route => { if (route.request().method() === "GET") return route.fulfill({ json: current }); const body = route.request().postDataJSON(); writes.push(body); current = { ...current, ...body, triggers: body.triggers.map((trigger, index) => ({ ...trigger, id: trigger.id ?? `00000000-0000-4000-8000-00000000000${index + 4}`, jobId: id, createdAt: initial.createdAt, updatedAt: initial.updatedAt })) }; return route.fulfill({ json: current }); });
await page.route("**/api/v1/providers/**", route => { reads.push(new URL(route.request().url()).pathname); return route.fulfill({ json: route.request().url().endsWith("/projects") ? [{ id: "project", name: "Release" }] : { statuses: [{ id: "done", name: "Done" }], users: [], labels: [] } }); });
await page.route("**/api/v1/job-conditions/test", route => route.fulfill({ json: { decision: "match", details: [] } }));
let conditionTests = 0; await page.route("**/api/v1/job-conditions/test", route => { conditionTests++; return route.fulfill({ json: { decision: "match", details: [] } }); });
await page.goto(origin + `/jobs/${id}/edit`); assert.equal(reads.length, 0); await page.getByLabel("New trigger kind").selectOption("webhook"); await page.getByRole("button", { name: "Add trigger" }).click();
await page.getByLabel("Linear project").selectOption("project"); await page.getByRole("button", { name: "Add matching rule" }).click(); await page.getByLabel("Match value").selectOption("done"); await page.getByLabel("Conditions JSON (optional)").fill('{"all":[{"fact":"webhook","path":"$.issue.id","operator":"equal","value":"i1"}]}');
await page.getByText("Test webhook conditions", { exact: true }).click(); await page.getByRole("button", { name: "Test conditions", exact: true }).click({ force: true }); await page.getByRole("status").filter({ hasText: "Conditions match the example webhook." }).waitFor(); assert.equal(await page.getByText('"decision": "match"', { exact: false }).count(), 0);
await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor();
await page.getByText("Test webhook conditions", { exact: true }).click(); const testButton = page.getByRole("button", { name: "Test conditions", exact: true }); await page.waitForFunction(() => { const button = [...document.querySelectorAll("button")].find(element => element.textContent?.trim() === "Test conditions"); return button && !button.disabled; }); await testButton.click(); await page.getByRole("status").filter({ hasText: "Conditions match the example webhook." }).waitFor(); assert.equal(conditionTests, 1); assert.equal(await page.getByText('"decision": "match"', { exact: false }).count(), 0);
await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor();
assert.ok(reads.every(path => path.startsWith("/api/v1/providers/linear/"))); assert.deepEqual(writes[0].triggers[1].config, { provider: "linear", projectId: "project", matchRules: [{ type: "status", targetId: "done" }], conditions: { all: [{ fact: "webhook", path: "$.issue.id", operator: "equal", value: "i1" }] } }); assert.equal(writes[0].triggers[0].id, triggerId); await context.close();
});
Expand Down
2 changes: 2 additions & 0 deletions packages/app/test/functional/critical.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ test("conversation trace renders assistant messages and uses document scrolling"
await mockApi(page, { long: true });
await page.goto(origin + "/job-runs/" + "00000000-0000-4000-8000-000000000002");
await expect(page.getByText("Release ready", { exact: true })).toBeVisible();
await expect(page.getByRole("link", { name: "Show full trace" })).toHaveAttribute("target", "_blank");
await expect(page.getByRole("link", { name: "Show full trace" })).toHaveAttribute("href", /\/job-runs\/00000000-0000-4000-8000-000000000002\/trace$/);
await expect(page.getByText("Full trace", { exact: true })).toHaveCount(0);
await expect(page.getByText("events loaded", { exact: false })).toHaveCount(0);
expect(await page.locator("[data-run-trace]").evaluate(element => getComputedStyle(element).overflow)).not.toBe("auto");
Expand Down
4 changes: 2 additions & 2 deletions packages/app/test/runs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ test("run rename supports keyboard save and cancel, validates names, and preserv
await page.getByRole("button", { name: "Rename", exact: true }).click(); await page.getByRole("textbox", { name: "Run name" }).fill("Saved name"); await page.keyboard.press("Enter"); await page.getByRole("heading", { name: "Saved name", exact: true }).waitFor(); assert.deepEqual(saves, [{ name: "Saved name", expectedName: "Original run" }]);
await page.reload(); await page.getByRole("heading", { name: "Saved name", exact: true }).waitFor(); await context.close();
});
test("run trace uses pull-to-load history, preserves the anchor, and never crashes on disclosure toggles", async () => {
test("full run trace uses pull-to-load history, preserves the anchor, and never crashes on disclosure toggles", async () => {
const { context, page } = await setup(); const requests = [];
const event = (sequence, type = "assistant_message") => ({ id: `trace-${sequence}`, sequence, type, title: `Trace ${sequence}`, preview: `Trace ${sequence}`, display: {} });
const longCommand = `start-${"x".repeat(5000)}-end`;
Expand All @@ -160,7 +160,7 @@ test("run trace uses pull-to-load history, preserves the anchor, and never crash
if (url.searchParams.has("after")) return route.fulfill({ json: { items: [], nextCursor: null, previousCursor: null, revision: "rev", reset: false } });
return route.fulfill({ json: { items: recent, nextCursor: null, previousCursor: 10, revision: "rev", reset: false } });
});
await page.goto(origin + "/job-runs/" + runId); const scroller = page.locator("[data-run-trace-scroll]");
await page.goto(origin + "/job-runs/" + runId + "/trace"); const scroller = page.locator("[data-run-trace-scroll]");
await page.getByText("Trace 24", { exact: true }).waitFor();
const tracePanel = page.locator("#run-panel-trace");
assert.equal(await tracePanel.locator(":scope > section").count(), 0, "trace should not contain a redundant nested section");
Expand Down
Loading