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
7 changes: 3 additions & 4 deletions packages/api/test/static-slice.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
await page.getByText("Final output · assistant_message", { exact: true }).waitFor();
expect(calls.some(call => call === `GET /api/v1/runs/${runId}/status`)).toBe(true);
expect(calls.some(call => call === `GET /api/v1/runs/${runId}`)).toBe(false);
await page.getByLabel("Continuous virtualized trace").check();
const continuous = page.getByRole("region", { name: "Continuous trace" });
await continuous.getByText("Final output · assistant_message", { exact: true }).waitFor();
expect(await continuous.locator("li").count()).toBe(1);
const trace = page.getByRole("region", { name: "Full trace" });
await trace.getByText("Final output · assistant_message", { exact: true }).waitFor();
expect(await trace.locator("li").count()).toBe(1);
expect(failures).toEqual([]);
await context.close();
} finally { await browser.close(); await f.cleanup(); }
Expand Down
35 changes: 31 additions & 4 deletions packages/app/src/features/runs/continuous-trace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
const cache = useQueryClient();
const [focused, setFocused] = useState<number | null>(null), [selection, setSelection] = useState<number[]>([]);
const container = useRef<HTMLDivElement>(null), [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const paginationStarted = useRef(false);
const trace = useInfiniteQuery({ queryKey: ["runs", runId, "continuous-trace", revision], initialPageParam: 0,
queryFn: async ({ signal, pageParam }) => { const { data, error } = await api.GET("/api/v1/runs/{runId}/trace-pages", { signal, params: { path: { runId }, query: { after: pageParam, revision, limit: 200 } } }); if (!data || error) throw new Error(messageOf(error)); return data; },
enabled: !!revision, getNextPageParam: page => page.reset ? undefined : page.nextCursor ?? undefined,
Expand All @@ -24,6 +25,20 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
useEffect(() => { const changed = live.data?.reset ? live.data : trace.data?.pages.find(page => page.reset || page.revision !== revision); if (changed) onReset(changed.revision); }, [live.data, trace.data, revision, onReset]);
useEffect(() => { if (live.data && !live.data.reset && live.data.revision === revision) cache.setQueryData(trace.data ? ["runs", runId, "continuous-trace", revision] : [], (previous: typeof trace.data) => previous ? { ...previous, pages: previous.pages.map((page, index) => index === previous.pages.length - 1 ? live.data! : page) } : previous); }, [live.data, cache, runId, revision]);
const items = trace.data?.pages.filter(page => page.revision === revision && !page.reset).flatMap(page => page.items) ?? [];
const latestAssistant = [...items].reverse().find(event => event.type === "assistant_message");
useEffect(() => {
const element = container.current;
if (!element) return;
const changed = () => { paginationStarted.current = true; };
element.addEventListener("scroll", changed, { passive: true });
return () => element.removeEventListener("scroll", changed);
}, []);
useEffect(() => {
const timer = window.setInterval(() => {
if (paginationStarted.current && trace.hasNextPage && !trace.isFetching) void trace.fetchNextPage();
}, 100);
return () => window.clearInterval(timer);
}, [trace.hasNextPage, trace.isFetching, trace.fetchNextPage]);
useEffect(() => {
const changed = () => {
const current = window.getSelection();
Expand All @@ -38,10 +53,22 @@ export function ContinuousTrace({ runId, revision, active, onReset }: { runId: s
}, []);
const virtualizer = useVirtualizer({ count: items.length, getScrollElement: () => container.current, estimateSize: () => 70, overscan: 8, rangeExtractor: range => [...new Set([...defaultRangeExtractor(range), ...selection, ...(focused === null ? [] : [focused])])].filter(index => index >= 0 && index < items.length).sort((a, b) => a - b), getItemKey: index => `${revision}:${items[index].sequence}:${items[index].id}` });
const virtualItems = virtualizer.getVirtualItems();
useEffect(() => { if ((virtualItems.at(-1)?.index ?? -1) >= items.length - 8 && trace.hasNextPage && !trace.isFetching) void trace.fetchNextPage(); }, [virtualItems, items.length, trace.hasNextPage, trace.isFetching, trace.fetchNextPage]);
return <Card>{trace.error && <p role="alert">{trace.error.message}</p>}{trace.isPending && <p role="status">Loading continuous trace…</p>}
{!trace.isPending && !items.length && <p>No trace events yet.</p>}
<div ref={container} onFocusCapture={e => { const row = (e.target as HTMLElement).closest<HTMLElement>("li[data-index]"); setFocused(row ? Number(row.dataset.index) : null); }} onBlurCapture={e => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(null); }} tabIndex={0} role="region" aria-label="Continuous trace" className="h-[65vh] overflow-auto border p-3">
useEffect(() => {
if ((virtualItems.at(-1)?.index ?? -1) < items.length - 8 || !trace.hasNextPage || trace.isFetching) return;
const timer = window.setTimeout(() => void trace.fetchNextPage(), 100);
return () => window.clearTimeout(timer);
}, [virtualItems, items.length, trace.hasNextPage, trace.isFetching, trace.fetchNextPage]);
useEffect(() => {
if (!trace.hasNextPage || trace.isFetching) return;
const timer = window.setTimeout(() => void trace.fetchNextPage(), 250);
return () => window.clearTimeout(timer);
}, [trace.hasNextPage, trace.isFetching, trace.fetchNextPage]);
return <Card>{trace.error && <p role="alert">{trace.error.message}</p>}{trace.isPending && <p role="status">Loading trace…</p>}
<h3 className="mt-4 text-lg font-semibold">Status</h3>
{latestAssistant ? <div className="mt-2 min-w-0 rounded-lg border border-stone-200 p-3 dark:border-slate-700"><EventBody event={latestAssistant} /></div> : <p className="mt-2 text-sm text-slate-600 dark:text-slate-400">No assistant message yet.</p>}
<h3 className="mt-6 text-lg font-semibold">Full trace</h3>
{!trace.isPending && !items.length && <p className="mt-2 text-sm text-slate-600 dark:text-slate-400">No trace events yet.</p>}
<div ref={container} onFocusCapture={e => { const row = (e.target as HTMLElement).closest<HTMLElement>("li[data-index]"); setFocused(row ? Number(row.dataset.index) : null); }} onBlurCapture={e => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(null); }} tabIndex={0} role="region" aria-label="Full trace" className="mt-2 h-[65vh] min-w-0 max-w-full overflow-auto border p-3">
<ol className="relative" style={{ height: virtualizer.getTotalSize() }} aria-label="Trace events">{virtualItems.map(row => {
const event = items[row.index], key = `${revision}:${event.sequence}:${event.id}`;
return <li key={key} data-index={row.index} ref={virtualizer.measureElement} style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${row.start}px)` }} aria-posinset={row.index + 1} aria-setsize={items.length}>
Expand Down
46 changes: 8 additions & 38 deletions packages/app/src/features/runs/detail.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import { traceClasses } from "./event-body";
import { Disclosure, Summary, Badge, Button, Input, Label, Page } from "../../shared/ui";
import { EventBody } from "./event-body";
import { Badge, Button, Page } from "../../shared/ui";
import { ContinuousTrace } from "./continuous-trace";
import { ExpandedRunDetail } from "./expanded-detail";
import { ReplayTrace } from "./replay";
import { useEffect, useState, useRef } from "react";
import { Link, useLocation, useParams, useSearch, useNavigate } from "@tanstack/react-router";
import { Link, useLocation, useParams, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "factorize-api-client";
import { runStatusQuery, runTraceQuery } from "./queries";
import { runStatusQuery } from "./queries";
import { messageOf } from "../auth/session";
export function RunDetail() {
const { runId } = useParams({ strict: false }), search = useSearch({ strict: false }) as { after: number };
const { runId } = useParams({ strict: false });
const location = useLocation(), navigate = useNavigate(), cache = useQueryClient();
const tab: "trace" | "info" | "settings" = location.pathname.endsWith("/info") ? "info" : location.pathname.endsWith("/settings") ? "settings" : "trace";
const tabPath = (name: "trace" | "info" | "settings"): "/job-runs/$runId" | "/job-runs/$runId/info" | "/job-runs/$runId/settings" => name === "trace" ? "/job-runs/$runId" : name === "info" ? "/job-runs/$runId/info" : "/job-runs/$runId/settings";
const status = useQuery(runStatusQuery(runId!));
const [revision, setRevision] = useState("");
const [continuous, setContinuous] = useState(false);
const [now, setNow] = useState(() => Date.now());
const active = !status.data || !["succeeded", "failed", "stopped"].includes(status.data.state) || status.data.finalizing;
useEffect(() => {
Expand All @@ -35,24 +32,10 @@ export function RunDetail() {
}
finalizedSnapshot.current = next;
}, [status.data?.state, status.data?.finalizing, status.data?.artifact_state, cache, runId]);
const trace = useQuery({ ...runTraceQuery(runId!, revision, search.after, active), enabled: !!revision && !continuous });
useEffect(() => {
const next = trace.data?.reset ? trace.data.revision : status.data?.trace_revision;
if (next && next !== revision) {
if (trace.data?.reset) {
void cache.cancelQueries({ queryKey: ["runs", runId, "status"] });
cache.setQueryData(runStatusQuery(runId!).queryKey, previous => previous ? { ...previous, trace_revision: next } : previous);
}
setRevision(next);
void cache.cancelQueries({ queryKey: ["runs", runId, "trace"] });
cache.removeQueries({ queryKey: ["runs", runId, "trace"] });
void cache.cancelQueries({ queryKey: ["runs", runId, "continuous-trace"] });
cache.removeQueries({ queryKey: ["runs", runId, "continuous-trace"] });
void cache.cancelQueries({ queryKey: ["runs", runId, "continuous-tail"] });
cache.removeQueries({ queryKey: ["runs", runId, "continuous-tail"] });
if (revision || trace.data?.reset) void navigate({ to: tabPath(tab), params: { runId: runId! }, search: { after: 0 }, replace: true });
}
}, [status.data?.trace_revision, trace.data?.revision, trace.data?.reset, revision, cache, runId, navigate]);
const next = status.data?.trace_revision;
if (next && next !== revision) setRevision(next);
}, [status.data?.trace_revision, revision]);
const stop = useMutation({ retry: false, mutationFn: async () => {
const { error } = await api.POST("/api/v1/runs/{runId}/stop", { params: { path: { runId: runId! } } });
if (error) throw new Error(messageOf(error));
Expand Down Expand Up @@ -92,20 +75,7 @@ export function RunDetail() {
</section>
<section role="tabpanel" id="run-panel-trace" aria-labelledby="run-tab-trace" hidden={tab !== "trace"} tabIndex={0}>
<h2 className="my-4 text-xl font-semibold">Trace</h2>
<Label><Input type="checkbox" checked={continuous} onChange={e => setContinuous(e.target.checked)} /> Continuous virtualized trace</Label>
{continuous && <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"] }); }} />}
{!continuous && trace.error && <p role="alert">{trace.error.message}</p>}
{!continuous && trace.isPending && <p role="status">Loading trace…</p>}
{!continuous && trace.data && trace.data.revision === revision && <>
{!trace.data.items.length && <p>No trace events yet.</p>}
<ol className="grid gap-3">{trace.data.items.map(event => <li key={`${revision}:${event.id}:${event.sequence}`}><Disclosure className={traceClasses(event.type)}>
<Summary>{event.title} · {event.type}</Summary><EventBody event={event} />
</Disclosure></li>)}</ol>
<nav aria-label="Trace pages" className="my-4 flex gap-4">
{!!search.after && <Link to={tabPath("trace")} params={{ runId: runId! }} search={{ after: 0 }}>First trace page</Link>}
{trace.data.nextCursor !== null && <Link to={tabPath("trace")} params={{ runId: runId! }} search={{ after: trace.data.nextCursor }}>Next trace page</Link>}
</nav>
</>}
<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>
</Page>;
}
2 changes: 1 addition & 1 deletion packages/app/src/features/runs/event-body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function traceClasses(type: string) {
export function EventBody({ event }: { event: Event }) {
// Raw HTML is rendered as text. No rehype-raw or innerHTML; Markdown's default
// URL transform excludes javascript/data links, and external links are isolated.
if (["user_message", "assistant_message", "reasoning"].includes(event.type)) return <div className="trace-content"><Markdown components={{ code: ({ children, className }) => <code className={className}>{className && typeof children === "string" ? children.split(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b(?:const|let|var|function|return|if|else|import|export|async|await|class|def|true|false|null|None)\b)/g).map((part, index) => /^(?:["']|const\b|let\b|var\b|function\b|return\b|if\b|else\b|import\b|export\b|async\b|await\b|class\b|def\b|true\b|false\b|null\b|None\b)/.test(part) ? <span key={index} className={part.startsWith('"') || part.startsWith("'") ? "text-emerald-800 dark:text-emerald-300" : "text-factorize-700 dark:text-factorize-500"}>{part}</span> : part) : children}</code>, a: ({ children, href }) => <a href={href} target="_blank" rel="noopener noreferrer">{children}</a> }}>{event.preview}</Markdown></div>;
if (["user_message", "assistant_message", "reasoning"].includes(event.type)) return <div className="trace-content"><Markdown components={{ code: ({ children, className }) => <code className={className}>{className && typeof children === "string" ? children.split(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b(?:const|let|var|function|return|if|else|import|export|async|await|class|def|true|false|null|None)\b)/g).map((part, index) => /^(?:["']|const\b|let\b|var\b|function\b|return\b|if\b|else\b|import\b|export\b|async\b|await\b|class\b|def\b|true\b|false\b|null\b|None\b)/.test(part) ? <span key={index} className={part.startsWith('"') || part.startsWith("'") ? "text-emerald-800 dark:text-emerald-300" : "text-factorize-700 dark:text-factorize-500"}>{part}</span> : part) : children}</code>, pre: ({ children }) => <pre tabIndex={0}>{children}</pre>, a: ({ children, href }) => <a href={href} target="_blank" rel="noopener noreferrer">{children}</a> }}>{event.preview}</Markdown></div>;
let content = event.preview;
if (event.type === "tool_call") { try { content = JSON.stringify(JSON.parse(content), null, 2); } catch {} }
return <div>{event.type === "command" && <pre className="whitespace-pre-wrap break-words"><code>{event.title}</code></pre>}<pre className="terminal whitespace-pre-wrap break-words"><code><AnsiText text={content} /></code></pre>{Object.keys(event.display).length > 0 && <Disclosure><Summary>Event metadata</Summary><pre className="whitespace-pre-wrap break-words">{JSON.stringify(event.display, null, 2)}</pre></Disclosure>}</div>;
Expand Down
12 changes: 7 additions & 5 deletions packages/app/test/jobs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ test("invocation validates JSON, preserves retry idempotency and navigates to li
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("heading", { name: "Status", exact: true }).waitFor();
await page.getByText("No assistant message yet.", { exact: true }).waitFor();
await page.getByRole("heading", { name: "Full trace", exact: true }).waitFor();
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 });
Expand Down Expand Up @@ -175,8 +178,7 @@ test("trace reset between requests discards old pages and finalization keeps ter
return route.fulfill({ json: { items: [{ id: reset ? "new" : "old", sequence: 1, type: "assistant_message", title: reset ? "New projection" : "Old projection", preview: "Safe text", display: {} }], nextCursor: reset ? null : 100, revision: reset ? "new" : "old", reset: reset && query.get("revision") === "old" } });
});
await page.goto(origin + "/job-runs/" + runId); await page.getByText("Old projection · assistant_message", { exact: true }).waitFor();
await page.getByRole("link", { name: "Next trace page" }).click(); await page.getByText("New projection · assistant_message", { exact: true }).waitFor();
await page.waitForURL("**?after=0");
await page.getByText("New projection · assistant_message", { exact: true }).waitFor();
assert.equal(await page.getByText("Old projection · assistant_message", { exact: true }).count(), 0);
await page.waitForTimeout(2200); assert.ok(statusCalls >= 2);
await context.close();
Expand All @@ -188,12 +190,12 @@ test("20k-event continuous trace keeps DOM bounded, retains expanded details on
traceRequests++; const query = new URL(route.request().url()).searchParams, reset = !!query.get("revision") && query.get("revision") !== revision, after = reset ? 0 : Number(query.get("after") || 0), limit = Number(query.get("limit")), count = revision === "large" ? 20000 : 1;
return route.fulfill({ json: { items: Array.from({ length: Math.min(limit, count - after) }, (_, index) => ({ id: `${revision}-${after + index + 1}`, sequence: after + index + 1, type: "assistant_message", title: `${revision} event ${after + index + 1}`, preview: "Safe text", display: {} })), nextCursor: after + limit < count ? after + limit : null, revision, reset } });
});
await page.goto(origin + "/job-runs/" + runId); await page.getByLabel("Continuous virtualized trace").check();
const region = page.getByRole("region", { name: "Continuous trace", exact: true });
await page.goto(origin + "/job-runs/" + runId);
const region = page.getByRole("region", { name: "Full trace", exact: true });
await page.getByText("large event 1 · assistant_message", { exact: true }).waitFor(); await page.getByText("large event 1 · assistant_message", { exact: true }).click();
for (let count = 400; count <= 20000; count += 200) {
await region.evaluate(el => { el.scrollTop = el.scrollHeight; });
await page.getByRole("status").filter({ hasText: `${count} events loaded` }).waitFor();
await page.waitForFunction(expected => Math.max(...[...document.querySelectorAll('[role="status"]')].map(element => Number(element.textContent?.match(/^(\d+) events loaded/)?.[1] ?? 0))) >= expected, count);
peakNodes = Math.max(peakNodes, await region.locator("li").count());
}
assert.ok(await region.locator("li").count() < 60); assert.ok(traceRequests <= 110);
Expand Down
Binary file modified packages/app/test/visual/baselines/trace-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/trace-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/trace-failed.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/trace-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/trace-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/trace-running.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading