Skip to content

🎥 Make videos programmatically with React

`@remotion/skills-evals`: Add static result sharing (#7419)

Igor Samokhovets5e277b5eb98f
diff --git a/.gitignore b/.gitignore
index 38a2eb1c39..496121eea6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,3 +37,4 @@ packages/example-without-zod/build
packages/docs/out
packages/cloudrun/container/ensure-browser.mjs
packages/skills-evals/.runs
+packages/skills-evals/.site
diff --git a/package.json b/package.json
index c786d7b73c..255303d7d0 100644
--- a/package.json
+++ b/package.json
@@ -92,6 +92,7 @@
"!packages/template-audiogram/whisper.cpp/**",
"!packages/template-vercel/**",
"!packages/skills-evals/.runs/**",
+ "!packages/skills-evals/.site/**",
"!packages/bugs"
],
"catalog": {
diff --git a/packages/skills-evals/README.md b/packages/skills-evals/README.md
index 4510034e8b..3584ad456c 100644
--- a/packages/skills-evals/README.md
+++ b/packages/skills-evals/README.md
@@ -2,4 +2,38 @@
## Usage
-This is an internal package and has no documentation.
+This is an internal package for running and reviewing Remotion skills evals.
+
+```bash
+bun run eval list
+bun run eval run <scenario-id>
+bun run eval compare <scenario-id>
+bun run eval dev
+```
+
+The dev server shows completed runs and comparisons from `.runs`.
+
+## Sharing results
+
+From the dev server, use the `Share` button on a run or comparison page to
+build a static share bundle. On a scenario page, select multiple completed
+results and use `Share selected`.
+
+The share action writes a static site under `.site` and prints a command the
+user can run manually for a one-time Vercel deployment:
+
+```bash
+vercel deploy <output-directory>
+```
+
+You can also export from the CLI:
+
+```bash
+bun run eval export .runs/<scenario-id>/<run-id>/manifest.json
+bun run eval export .runs/comparisons/<scenario-id>/<comparison-id>/comparison.json
+bun run eval export <path-a> <path-b> --out /tmp/skills-evals-share
+```
+
+The exported folder contains `index.html`, `metadata.json`, and a `files/`
+directory with the referenced videos, images, Pi exports, manifests, diffs, and
+logs.
diff --git a/packages/skills-evals/package.json b/packages/skills-evals/package.json
index 65c6eb6dce..8a38e4a63d 100644
--- a/packages/skills-evals/package.json
+++ b/packages/skills-evals/package.json
@@ -9,6 +9,7 @@
"scripts": {
"dev": "bun src/server.tsx",
"eval": "bun src/cli.ts",
+ "export": "bun src/cli.ts export",
"format": "oxfmt src scenarios.ts",
"formatting": "oxfmt src scenarios.ts --check",
"lint": "eslint src && tsgo"
diff --git a/packages/skills-evals/src/app/comparison.tsx b/packages/skills-evals/src/app/comparison.tsx
index b1fa259076..c3ea5ebad7 100644
--- a/packages/skills-evals/src/app/comparison.tsx
+++ b/packages/skills-evals/src/app/comparison.tsx
@@ -10,10 +10,19 @@ import {
Header,
page,
Pill,
+ type RenderOptions,
+ ShareResultButton,
+ ShareResultScript,
toFileUrl,
} from './shared';
-const Artifact = ({manifest}: {manifest: SkillEvalManifest}) => {
+const Artifact = ({
+ manifest,
+ renderOptions,
+}: {
+ manifest: SkillEvalManifest;
+ renderOptions?: RenderOptions;
+}) => {
const artifact = getPreferredArtifact(manifest);
if (!artifact) {
@@ -24,7 +33,7 @@ const Artifact = ({manifest}: {manifest: SkillEvalManifest}) => {
);
}
- const href = toFileUrl(artifact.path);
+ const href = toFileUrl(artifact.path, renderOptions);
if (artifact.type === 'image') {
return (
@@ -52,10 +61,12 @@ const RunPanel = ({
label,
manifest,
manifestPath,
+ renderOptions,
}: {
label: string;
manifest: SkillEvalManifest;
manifestPath: string;
+ renderOptions?: RenderOptions;
}) => {
const artifact = getPreferredArtifact(manifest);
const duration = formatDuration(getDurationMs(manifest));
@@ -68,19 +79,19 @@ const RunPanel = ({
<Pill>Took {duration}</Pill>
<a
className="text-[0.8125rem] text-zinc-600"
- href={toFileUrl(manifest.pi.htmlExport)}
+ href={toFileUrl(manifest.pi.htmlExport, renderOptions)}
>
Pi export
</a>
<a
className="text-[0.8125rem] text-zinc-600"
- href={toFileUrl(manifestPath)}
+ href={toFileUrl(manifestPath, renderOptions)}
>
Manifest
</a>
</div>
</div>
- <Artifact manifest={manifest} />
+ <Artifact manifest={manifest} renderOptions={renderOptions} />
<div className="mt-2 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-zinc-500">
{artifact?.relativePath ?? 'No artifact'}
</div>
@@ -160,7 +171,10 @@ const ComparisonDiffScript = () => (
</>
);
-export const renderComparison = (comparisonData: ComparisonWithManifests) => {
+export const renderComparison = (
+ comparisonData: ComparisonWithManifests,
+ renderOptions?: RenderOptions,
+) => {
const {afterManifest, beforeManifest, comparison, runs, skillDiff} =
comparisonData;
const hasBatch = runs.length > 1;
@@ -172,12 +186,22 @@ export const renderComparison = (comparisonData: ComparisonWithManifests) => {
action={
<div className="flex flex-wrap items-center gap-3">
<Pill>{formatDate(comparison.completedAt)}</Pill>
- <a
- className="text-[0.8125rem] text-zinc-600"
- href={`/scenarios/${encodeURIComponent(comparison.scenarioId)}`}
- >
- Scenario
- </a>
+ {renderOptions?.mode === 'static' ? null : (
+ <a
+ className="text-[0.8125rem] text-zinc-600"
+ href={`/scenarios/${encodeURIComponent(comparison.scenarioId)}`}
+ >
+ Scenario
+ </a>
+ )}
+ {renderOptions?.mode === 'static' || !comparison.evalId ? null : (
+ <ShareResultButton
+ endpoint={`/api/share/eval/${encodeURIComponent(
+ comparison.scenarioId,
+ )}/${encodeURIComponent(comparison.evalId)}`}
+ label="Share eval"
+ />
+ )}
</div>
}
eyebrow="Comparison"
@@ -206,6 +230,7 @@ export const renderComparison = (comparisonData: ComparisonWithManifests) => {
runMetadata?.before.manifestPath ??
comparison.before.manifestPath
}
+ renderOptions={renderOptions}
/>
<RunPanel
label="After"
@@ -214,6 +239,7 @@ export const renderComparison = (comparisonData: ComparisonWithManifests) => {
runMetadata?.after.manifestPath ??
comparison.after.manifestPath
}
+ renderOptions={renderOptions}
/>
</div>
</section>
@@ -248,8 +274,10 @@ export const renderComparison = (comparisonData: ComparisonWithManifests) => {
</details>
</main>
<ComparisonDiffScript />
+ {renderOptions?.mode === 'static' ? null : <ShareResultScript />}
</>
),
+ renderOptions,
title: `${comparison.scenarioId} Comparison`,
});
};
diff --git a/packages/skills-evals/src/app/eval.tsx b/packages/skills-evals/src/app/eval.tsx
new file mode 100644
index 0000000000..d299f4e713
--- /dev/null
+++ b/packages/skills-evals/src/app/eval.tsx
@@ -0,0 +1,267 @@
+import {getSkillEvalName} from '../eval';
+import {readJson} from '../files';
+import type {SkillEval, SkillEvalManifest} from '../manifest';
+import {
+ getPreferredArtifact,
+ loadComparison,
+ type ComparisonWithManifests,
+} from './comparison-data';
+import {
+ formatDate,
+ formatDuration,
+ getDurationMs,
+ Header,
+ page,
+ Pill,
+ type RenderOptions,
+ ShareResultButton,
+ ShareResultScript,
+ toFileUrl,
+} from './shared';
+
+export type SkillEvalWithData =
+ | {
+ evaluation: Extract<SkillEval, {type: 'comparison'}>;
+ comparisonData: ComparisonWithManifests;
+ type: 'comparison';
+ }
+ | {
+ evaluation: Extract<SkillEval, {type: 'run'}>;
+ manifests: SkillEvalManifest[];
+ type: 'run';
+ };
+
+export const loadSkillEvalData = async (
+ evaluation: SkillEval,
+): Promise<SkillEvalWithData | null> => {
+ if (evaluation.type === 'run') {
+ return {
+ evaluation,
+ manifests: await Promise.all(
+ evaluation.runs.map((run) =>
+ readJson<SkillEvalManifest>(run.manifestPath),
+ ),
+ ),
+ type: 'run',
+ };
+ }
+
+ const comparison = await readJson<ComparisonWithManifests['comparison']>(
+ evaluation.comparisonPath,
+ );
+ const comparisonData = await loadComparison(
+ comparison.scenarioId,
+ comparison.id,
+ );
+
+ if (!comparisonData) {
+ return null;
+ }
+
+ return {comparisonData, evaluation, type: 'comparison'};
+};
+
+const Artifact = ({
+ manifest,
+ renderOptions,
+}: {
+ manifest: SkillEvalManifest;
+ renderOptions?: RenderOptions;
+}) => {
+ const artifact = getPreferredArtifact(manifest);
+
+ if (!artifact) {
+ return (
+ <div className="grid aspect-video place-items-center rounded-xl bg-zinc-900 text-[0.8125rem] text-zinc-400">
+ No visual artifact found
+ </div>
+ );
+ }
+
+ const href = toFileUrl(artifact.path, renderOptions);
+
+ if (artifact.type === 'image') {
+ return (
+ <a href={href}>
+ <img
+ alt={artifact.relativePath}
+ className="aspect-video w-full rounded-xl bg-zinc-900 object-contain"
+ src={href}
+ />
+ </a>
+ );
+ }
+
+ return (
+ <video
+ className="aspect-video w-full rounded-xl bg-zinc-900 object-contain"
+ controls
+ preload="metadata"
+ src={href}
+ />
+ );
+};
+
+const PromptCard = ({prompt}: {prompt: string}) => (
+ <details className="min-w-0 rounded-2xl border border-zinc-200 bg-white p-4">
+ <summary className="cursor-pointer text-sm font-semibold">Prompt</summary>
+ <pre className="mt-3 max-h-75 overflow-auto whitespace-pre-wrap rounded-xl border border-zinc-200 bg-zinc-100 p-3 text-xs text-zinc-700">
+ {prompt}
+ </pre>
+ </details>
+);
+
+const RunCard = ({
+ label,
+ manifest,
+ renderOptions,
+}: {
+ label: string;
+ manifest: SkillEvalManifest;
+ renderOptions?: RenderOptions;
+}) => {
+ const artifact = getPreferredArtifact(manifest);
+
+ return (
+ <section className="rounded-2xl border border-zinc-200 bg-white p-3">
+ <div className="mb-2 flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-[0.9375rem] font-semibold">{label}</h2>
+ <p className="mt-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-zinc-500">
+ {artifact?.relativePath ?? 'No artifact'}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <Pill>Took {formatDuration(getDurationMs(manifest))}</Pill>
+ <a
+ className="text-[0.8125rem] text-zinc-600"
+ href={toFileUrl(manifest.pi.htmlExport, renderOptions)}
+ >
+ Pi export
+ </a>
+ </div>
+ </div>
+ <Artifact manifest={manifest} renderOptions={renderOptions} />
+ </section>
+ );
+};
+
+const RunEvalResults = ({
+ evaluation,
+ manifests,
+ renderOptions,
+}: {
+ evaluation: Extract<SkillEval, {type: 'run'}>;
+ manifests: SkillEvalManifest[];
+ renderOptions?: RenderOptions;
+}) => (
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-3">
+ {manifests.map((manifest, index) => (
+ <RunCard
+ key={manifest.runDir}
+ label={`Run #${
+ manifest.evalRunIndex ?? evaluation.runs[index]?.index ?? index + 1
+ }`}
+ manifest={manifest}
+ renderOptions={renderOptions}
+ />
+ ))}
+ </div>
+);
+
+const ComparisonEvalResult = ({
+ comparisonData,
+ renderOptions,
+}: {
+ comparisonData: ComparisonWithManifests;
+ renderOptions?: RenderOptions;
+}) => (
+ <div className="grid gap-4">
+ {comparisonData.runs.map((run) => {
+ const runMetadata = comparisonData.comparison.runs?.find(
+ (candidate) => candidate.index === run.index,
+ );
+ const beforeMetadata =
+ runMetadata?.before ?? comparisonData.comparison.before;
+
+ return (
+ <section className="grid min-w-0 gap-3" key={run.index}>
+ {comparisonData.runs.length > 1 ? (
+ <h2 className="text-[0.9375rem] font-semibold">Run #{run.index}</h2>
+ ) : null}
+ <div className="grid grid-cols-2 gap-3 max-lg:grid-cols-1">
+ <RunCard
+ label={`Before (${beforeMetadata.gitRef ?? beforeMetadata.source})`}
+ manifest={run.beforeManifest}
+ renderOptions={renderOptions}
+ />
+ <RunCard
+ label="After"
+ manifest={run.afterManifest}
+ renderOptions={renderOptions}
+ />
+ </div>
+ </section>
+ );
+ })}
+ </div>
+);
+
+export const renderEval = (
+ data: SkillEvalWithData,
+ renderOptions?: RenderOptions,
+) => {
+ const {evaluation} = data;
+ const evalName = getSkillEvalName(evaluation);
+ const prompt =
+ data.type === 'run'
+ ? data.manifests[0]?.prompt
+ : data.comparisonData.afterManifest.prompt;
+
+ return page({
+ children: (
+ <>
+ <Header
+ action={
+ <div className="flex flex-wrap items-center gap-3">
+ <Pill>{formatDate(evaluation.completedAt)}</Pill>
+ {renderOptions?.mode === 'static' ? null : (
+ <ShareResultButton
+ endpoint={`/api/share/eval/${encodeURIComponent(
+ evaluation.scenarioId,
+ )}/${encodeURIComponent(evaluation.id)}`}
+ label="Share eval"
+ />
+ )}
+ </div>
+ }
+ eyebrow="Eval"
+ subtitle={`${evaluation.scenarioId} - ${
+ evaluation.type === 'run' ? 'Run' : 'Comparison'
+ } eval - ${evaluation.runCount} ${
+ evaluation.runCount === 1 ? 'run' : 'runs'
+ }`}
+ title={evalName}
+ />
+ <main className="grid min-w-0 gap-4">
+ {data.type === 'run' ? (
+ <RunEvalResults
+ evaluation={data.evaluation}
+ manifests={data.manifests}
+ renderOptions={renderOptions}
+ />
+ ) : (
+ <ComparisonEvalResult
+ comparisonData={data.comparisonData}
+ renderOptions={renderOptions}
+ />
+ )}
+ {prompt ? <PromptCard prompt={prompt} /> : null}
+ </main>
+ {renderOptions?.mode === 'static' ? null : <ShareResultScript />}
+ </>
+ ),
+ renderOptions,
+ title: evalName,
+ });
+};
diff --git a/packages/skills-evals/src/app/home.tsx b/packages/skills-evals/src/app/home.tsx
index 21569f015e..3b78a3efa1 100644
--- a/packages/skills-evals/src/app/home.tsx
+++ b/packages/skills-evals/src/app/home.tsx
@@ -1,13 +1,13 @@
import {scenarios, type SkillEvalScenario} from '../../scenarios';
-import type {SkillEvalComparison} from '../manifest';
-import {getLatestComparisonByScenario} from './comparison-data';
+import {listSkillEvals} from '../eval';
+import type {SkillEval} from '../manifest';
import {formatDate, page, Pill} from './shared';
const ScenarioCard = ({
latest,
scenario,
}: {
- latest: SkillEvalComparison | undefined;
+ latest: SkillEval | undefined;
scenario: SkillEvalScenario;
}) => (
<a
@@ -22,15 +22,19 @@ const ScenarioCard = ({
<Pill>{latest ? 'Ready' : 'New'}</Pill>
</div>
<p className="mt-4 text-xs text-zinc-400">
- {latest
- ? `Last run ${formatDate(latest.completedAt)}`
- : 'No comparisons yet.'}
+ {latest ? `Last eval ${formatDate(latest.completedAt)}` : 'No evals yet.'}
</p>
</a>
);
export const renderHome = async () => {
- const latest = await getLatestComparisonByScenario();
+ const latest = new Map<string, SkillEval>();
+
+ for (const evaluation of await listSkillEvals()) {
+ if (!latest.has(evaluation.scenarioId)) {
+ latest.set(evaluation.scenarioId, evaluation);
+ }
+ }
return page({
children: (
diff --git a/packages/skills-evals/src/app/jobs.ts b/packages/skills-evals/src/app/jobs.ts
index 36e21ffdcb..3cc2cd4e40 100644
--- a/packages/skills-evals/src/app/jobs.ts
+++ b/packages/skills-evals/src/app/jobs.ts
@@ -1,10 +1,17 @@
-import {basename} from 'node:path';
+import {join} from 'node:path';
import {scenarios, type SkillEvalScenario} from '../../scenarios';
import {
runSkillEvalComparison,
type SkillEvalComparisonEvent,
type SkillEvalComparisonRunLabel,
} from '../compare';
+import {
+ createSkillEvalId,
+ createSkillEvalName,
+ getSkillEvalDir,
+ toEvalUrl,
+ writeSkillEval,
+} from '../eval';
import {
maxParallelSkillEvalRuns,
validateSkillEvalRunCount,
@@ -21,6 +28,7 @@ export type Job = {
startedAt: string;
status: 'running' | 'completed' | 'failed' | 'skipped';
comparisonUrl?: string;
+ evalUrl?: string;
error?: string;
message?: string;
resultUrl?: string;
@@ -122,6 +130,8 @@ export const startComparison = (
return existingJob;
}
+ const evalId = createSkillEvalId(scenario.id);
+ const evalName = createSkillEvalName({id: evalId, type: 'comparison'});
const job: Job = {
id: `${Date.now()}-${scenario.id}`,
logs: [],
@@ -220,16 +230,32 @@ export const startComparison = (
const comparisonPromise = runSkillEvalComparison(scenario, {
beforeGitRef: options.beforeGitRef,
+ evalId,
onEvent: handleEvent,
runCount,
})
- .then((result) => {
+ .then(async (result) => {
if (result.skipped) {
job.message = result.reason;
job.status = 'skipped';
return;
}
+ await writeSkillEval({
+ comparisonPath: join(
+ result.comparison.comparisonDir,
+ 'comparison.json',
+ ),
+ completedAt: result.comparison.completedAt,
+ createdAt: result.comparison.createdAt,
+ evalDir: getSkillEvalDir(scenario.id, evalId),
+ id: evalId,
+ name: evalName,
+ runCount,
+ scenarioId: scenario.id,
+ type: 'comparison',
+ });
+ job.evalUrl = toEvalUrl({id: evalId, scenarioId: scenario.id});
job.comparisonUrl = toComparisonUrl(result.comparison);
job.message = 'Comparison complete.';
job.status = 'completed';
@@ -255,6 +281,8 @@ export const startRun = (
return existingJob;
}
+ const evalId = createSkillEvalId(scenario.id);
+ const evalName = createSkillEvalName({id: evalId, type: 'run'});
const job: Job = {
id: `${Date.now()}-${scenario.id}`,
logs: [],
@@ -287,6 +315,8 @@ export const startRun = (
startJobRun(run);
const result = await runSkillEval({
...scenario,
+ evalId,
+ evalRunIndex: runIndex,
onPhase: (event) => {
run.status = 'running';
run.message = `${phaseLabels[event.phase]}${
@@ -325,20 +355,30 @@ export const startRun = (
}
},
})
- .then((results) => {
- const result = results[0];
-
- if (!result) {
+ .then(async (results) => {
+ if (results.length === 0) {
throw new Error('No run result was produced.');
}
+ const completedAt = new Date().toISOString();
+ await writeSkillEval({
+ completedAt,
+ createdAt: job.startedAt,
+ evalDir: getSkillEvalDir(scenario.id, evalId),
+ id: evalId,
+ name: evalName,
+ runCount,
+ runs: results.map((result, index) => ({
+ index: index + 1,
+ manifestPath: result.manifestPath,
+ })),
+ scenarioId: scenario.id,
+ type: 'run',
+ });
+ job.evalUrl = toEvalUrl({id: evalId, scenarioId: scenario.id});
job.message =
runCount === 1 ? 'Run complete.' : `${runCount} runs complete.`;
- if (runCount === 1) {
- job.resultUrl = `/runs/${encodeURIComponent(
- result.manifest.id,
- )}/${encodeURIComponent(basename(result.manifest.runDir))}`;
- }
+ job.resultUrl = job.evalUrl;
job.status = 'completed';
})
diff --git a/packages/skills-evals/src/app/routes.ts b/packages/skills-evals/src/app/routes.ts
index 0ace26569f..1491dcaaf5 100644
--- a/packages/skills-evals/src/app/routes.ts
+++ b/packages/skills-evals/src/app/routes.ts
@@ -1,6 +1,9 @@
import type {BunRequest} from 'bun';
+import {loadSkillEval} from '../eval';
+import {exportStaticSite, type StaticExportTarget} from '../export-static-site';
import {renderComparison} from './comparison';
import {loadComparison} from './comparison-data';
+import {loadSkillEvalData, renderEval} from './eval';
import {serveRunFile} from './files';
import {renderHome} from './home';
import {getJob, getScenario, startComparison, startRun} from './jobs';
@@ -14,6 +17,17 @@ const getRunCount = (request: Request) => {
return value === null ? undefined : Number(value);
};
+const shareResponse = async (targets: StaticExportTarget[]) => {
+ try {
+ return json(await exportStaticSite({targets}));
+ } catch (error) {
+ return json(
+ {error: error instanceof Error ? error.message : String(error)},
+ {status: 400},
+ );
+ }
+};
+
export const routes = {
'/': async () => htmlResponse(await renderHome()),
@@ -79,6 +93,17 @@ export const routes = {
},
},
+ '/api/share/eval/:scenarioId/:evalId': {
+ POST: (request: BunRequest<'/api/share/eval/:scenarioId/:evalId'>) =>
+ shareResponse([
+ {
+ evalId: request.params.evalId,
+ scenarioId: request.params.scenarioId,
+ type: 'eval',
+ },
+ ]),
+ },
+
'/comparisons/:scenarioId/:comparisonId': async (
request: BunRequest<'/comparisons/:scenarioId/:comparisonId'>,
) => {
@@ -107,6 +132,22 @@ export const routes = {
return serveRunFile(relativePath);
},
+ '/evals/:scenarioId/:evalId': async (
+ request: BunRequest<'/evals/:scenarioId/:evalId'>,
+ ) => {
+ const evaluation = await loadSkillEval(
+ request.params.scenarioId,
+ request.params.evalId,
+ );
+ const data = evaluation ? await loadSkillEvalData(evaluation) : null;
+
+ if (!data) {
+ return notFound();
+ }
+
+ return htmlResponse(renderEval(data));
+ },
+
'/scenarios/:scenarioId': async (
request: BunRequest<'/scenarios/:scenarioId'>,
) => {
diff --git a/packages/skills-evals/src/app/run.tsx b/packages/skills-evals/src/app/run.tsx
index 0797cb6762..815944cd0e 100644
--- a/packages/skills-evals/src/app/run.tsx
+++ b/packages/skills-evals/src/app/run.tsx
@@ -10,7 +10,10 @@ import {
Header,
page,
Pill,
+ type RenderOptions,
runsRoot,
+ ShareResultButton,
+ ShareResultScript,
toFileUrl,
} from './shared';
@@ -31,7 +34,13 @@ export const loadRun = async (scenarioId: string, runId: string) => {
return manifest;
};
-const Artifact = ({manifest}: {manifest: SkillEvalManifest}) => {
+const Artifact = ({
+ manifest,
+ renderOptions,
+}: {
+ manifest: SkillEvalManifest;
+ renderOptions?: RenderOptions;
+}) => {
const artifact = getPreferredArtifact(manifest);
if (!artifact) {
@@ -42,7 +51,7 @@ const Artifact = ({manifest}: {manifest: SkillEvalManifest}) => {
);
}
- const href = toFileUrl(artifact.path);
+ const href = toFileUrl(artifact.path, renderOptions);
if (artifact.type === 'image') {
return (
@@ -66,7 +75,10 @@ const Artifact = ({manifest}: {manifest: SkillEvalManifest}) => {
);
};
-export const renderRun = (manifest: SkillEvalManifest) =>
+export const renderRun = (
+ manifest: SkillEvalManifest,
+ renderOptions?: RenderOptions,
+) =>
page({
children: (
<>
@@ -74,18 +86,28 @@ export const renderRun = (manifest: SkillEvalManifest) =>
action={
<div className="flex flex-wrap items-center gap-3">
<Pill>Took {formatDuration(getDurationMs(manifest))}</Pill>
+ {renderOptions?.mode === 'static' ? null : (
+ <a
+ className="text-[0.8125rem] text-zinc-600"
+ href={`/scenarios/${encodeURIComponent(manifest.id)}`}
+ >
+ Scenario
+ </a>
+ )}
<a
className="text-[0.8125rem] text-zinc-600"
- href={`/scenarios/${encodeURIComponent(manifest.id)}`}
- >
- Scenario
- </a>
- <a
- className="text-[0.8125rem] text-zinc-600"
- href={toFileUrl(manifest.pi.htmlExport)}
+ href={toFileUrl(manifest.pi.htmlExport, renderOptions)}
>
Pi export
</a>
+ {renderOptions?.mode === 'static' || !manifest.evalId ? null : (
+ <ShareResultButton
+ endpoint={`/api/share/eval/${encodeURIComponent(
+ manifest.id,
+ )}/${encodeURIComponent(manifest.evalId)}`}
+ label="Share eval"
+ />
+ )}
</div>
}
eyebrow="Run"
@@ -94,7 +116,7 @@ export const renderRun = (manifest: SkillEvalManifest) =>
/>
<main className="grid min-w-0 gap-4">
<Card>
- <Artifact manifest={manifest} />
+ <Artifact manifest={manifest} renderOptions={renderOptions} />
</Card>
<details className="min-w-0 rounded-2xl border border-zinc-200 bg-white p-4">
<summary className="cursor-pointer text-sm font-semibold">
@@ -105,7 +127,9 @@ export const renderRun = (manifest: SkillEvalManifest) =>
</pre>
</details>
</main>
+ {renderOptions?.mode === 'static' ? null : <ShareResultScript />}
</>
),
+ renderOptions,
title: `${manifest.id} Run`,
});
diff --git a/packages/skills-evals/src/app/scenario.tsx b/packages/skills-evals/src/app/scenario.tsx
index a24b0942e1..f3ccafcf4a 100644
--- a/packages/skills-evals/src/app/scenario.tsx
+++ b/packages/skills-evals/src/app/scenario.tsx
@@ -1,10 +1,8 @@
-import {basename, join} from 'node:path';
import type {SkillEvalScenario} from '../../scenarios';
import {runCommand} from '../command';
import {getDefaultComparisonBaseRef} from '../compare';
-import {listFilesRecursively, readJson, sanitizePathPart} from '../files';
-import type {SkillEvalComparison, SkillEvalManifest} from '../manifest';
-import {loadComparisons} from './comparison-data';
+import {getSkillEvalName, listSkillEvals, toEvalUrl} from '../eval';
+import type {SkillEval} from '../manifest';
import {
createJobRuns,
formatRunLabel,
@@ -20,8 +18,6 @@ import {
Header,
page,
repoRoot,
- runsRoot,
- toComparisonUrl,
} from './shared';
type SkillDiffState = {
@@ -31,10 +27,11 @@ type SkillDiffState = {
title: string;
};
-type ScenarioRunListItem = {
+type ScenarioEvalListItem = {
completedAt: string;
href: string;
metadata: string;
+ title: string;
};
const getSkillDiffState = async (): Promise<SkillDiffState> => {
@@ -72,67 +69,45 @@ const getSkillDiffState = async (): Promise<SkillDiffState> => {
};
};
-const loadPlainRuns = async (
- scenarioId: string,
-): Promise<SkillEvalManifest[]> => {
- const manifestFiles = (
- await listFilesRecursively(join(runsRoot, sanitizePathPart(scenarioId)))
- ).filter((file) => file.endsWith('/manifest.json'));
-
- return Promise.all(
- manifestFiles.map((file) => readJson<SkillEvalManifest>(file)),
- );
-};
+const evalMetadata = (evaluation: SkillEval) =>
+ evaluation.type === 'run'
+ ? `${evaluation.runCount} ${evaluation.runCount === 1 ? 'run' : 'runs'}`
+ : `${evaluation.runCount} ${
+ evaluation.runCount === 1 ? 'comparison run' : 'comparison runs'
+ }`;
-const toRunListItems = ({
- comparisons,
- runs,
-}: {
- comparisons: SkillEvalComparison[];
- runs: SkillEvalManifest[];
-}) => {
- const items: ScenarioRunListItem[] = [
- ...comparisons.map((comparison) => ({
- completedAt: comparison.completedAt,
- href: toComparisonUrl(comparison),
- metadata:
- comparison.runs && comparison.runs.length > 1
- ? `${comparison.runs.length} comparison runs`
- : `${comparison.before.hash} -> ${comparison.after.hash}`,
- })),
- ...runs.map((run) => ({
- completedAt: run.completedAt,
- href: `/runs/${encodeURIComponent(run.id)}/${encodeURIComponent(
- basename(run.runDir),
- )}`,
- metadata: run.skillSnapshot.hash,
- })),
- ];
-
- return items.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
+const toEvalListItems = async (
+ scenarioId: string,
+): Promise<ScenarioEvalListItem[]> => {
+ const evaluations = await listSkillEvals(scenarioId);
+
+ return evaluations
+ .map((evaluation) => ({
+ completedAt: evaluation.completedAt,
+ href: toEvalUrl(evaluation),
+ metadata: evalMetadata(evaluation),
+ title: getSkillEvalName(evaluation),
+ }))
+ .sort((a, b) => b.completedAt.localeCompare(a.completedAt));
};
-const ScenarioRuns = ({items}: {items: ScenarioRunListItem[]}) => {
+const ScenarioEvals = ({items}: {items: ScenarioEvalListItem[]}) => {
if (items.length === 0) {
- return <p className="text-sm text-zinc-500">No runs yet.</p>;
+ return <p className="text-sm text-zinc-500">No evals yet.</p>;
}
return (
<div className="mt-3 grid">
{items.map((item) => (
<a
- className="flex items-center justify-between gap-4 border-t border-zinc-100 py-3 first:border-t-0 first:pt-0 last:pb-0"
+ className="block border-t border-zinc-100 py-3 first:border-t-0 first:pt-0 last:pb-0"
href={item.href}
key={item.href}
>
- <div>
- <h3 className="text-sm font-semibold text-zinc-800">
- {formatDate(item.completedAt)}
- </h3>
- <p className="mt-1 text-[0.8125rem] text-zinc-500">
- {item.metadata}
- </p>
- </div>
+ <h3 className="text-sm font-semibold text-zinc-800">{item.title}</h3>
+ <p className="mt-1 text-[0.8125rem] text-zinc-500">
+ {item.metadata} - {formatDate(item.completedAt)}
+ </p>
</a>
))}
</div>
@@ -349,6 +324,11 @@ const poll = async (jobId) => {
const job = await response.json();
renderJob(job);
+ if (job.status === 'completed' && job.evalUrl) {
+ location.href = job.evalUrl;
+ return;
+ }
+
if (job.status === 'completed' && job.comparisonUrl) {
location.href = job.comparisonUrl;
return;
@@ -506,11 +486,7 @@ const ActiveJobPanel = ({
export const renderScenario = async (scenario: SkillEvalScenario) => {
const activeJob = getActiveJob(scenario.id);
const skillDiffState = await getSkillDiffState();
- const comparisons = (await loadComparisons()).filter(
- (comparison) => comparison.scenarioId === scenario.id,
- );
- const runs = await loadPlainRuns(scenario.id);
- const runItems = toRunListItems({comparisons, runs});
+ const evalItems = await toEvalListItems(scenario.id);
return page({
children: (
@@ -603,8 +579,8 @@ export const renderScenario = async (scenario: SkillEvalScenario) => {
job={activeJob}
/>
<Card>
- <h2 className="text-[0.9375rem] font-semibold">Runs</h2>
- <ScenarioRuns items={runItems} />
+ <h2 className="text-[0.9375rem] font-semibold">Evals</h2>
+ <ScenarioEvals items={evalItems} />
</Card>
</main>
<ScenarioPageScript
diff --git a/packages/skills-evals/src/app/share.tsx b/packages/skills-evals/src/app/share.tsx
new file mode 100644
index 0000000000..6dc300f524
--- /dev/null
+++ b/packages/skills-evals/src/app/share.tsx
@@ -0,0 +1,61 @@
+import {getSkillEvalName} from '../eval';
+import type {SkillEval} from '../manifest';
+import {formatDate, Header, page, Pill} from './shared';
+
+export type ShareResult = {
+ evaluation: SkillEval;
+ href: string;
+};
+
+const resultMetadata = (result: ShareResult) =>
+ `${result.evaluation.scenarioId} - ${result.evaluation.runCount} ${
+ result.evaluation.runCount === 1 ? 'run' : 'runs'
+ }`;
+
+const resultTitle = (result: ShareResult) =>
+ getSkillEvalName(result.evaluation);
+
+export const renderShareIndex = (results: ShareResult[]) =>
+ page({
+ children: (
+ <>
+ <Header
+ eyebrow="Skills eval share"
+ subtitle={`${results.length} ${
+ results.length === 1 ? 'result' : 'results'
+ } exported for review.`}
+ title="Scenario results"
+ />
+ <main className="grid gap-3">
+ {results.map((result) => (
+ <a
+ className="block rounded-2xl border border-zinc-200 bg-white p-4 hover:border-zinc-300"
+ href={result.href}
+ key={result.href}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-[0.9375rem] font-semibold">
+ {resultTitle(result)}
+ </h2>
+ <p className="mt-1 text-[0.8125rem] text-zinc-500">
+ {resultMetadata(result)}
+ </p>
+ </div>
+ <Pill>
+ {result.evaluation.type === 'run'
+ ? 'Run eval'
+ : 'Comparison eval'}
+ </Pill>
+ </div>
+ <p className="mt-4 text-xs text-zinc-400">
+ {formatDate(result.evaluation.completedAt)}
+ </p>
+ </a>
+ ))}
+ </main>
+ </>
+ ),
+ renderOptions: {mode: 'static'},
+ title: 'Skills Eval Share',
+ });
diff --git a/packages/skills-evals/src/app/shared.tsx b/packages/skills-evals/src/app/shared.tsx
index 63de3cc7d5..74208b283a 100644
--- a/packages/skills-evals/src/app/shared.tsx
+++ b/packages/skills-evals/src/app/shared.tsx
@@ -1,4 +1,4 @@
-import {dirname, join, relative, resolve} from 'node:path';
+import {dirname, isAbsolute, join, relative, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {renderToStaticMarkup} from 'react-dom/server';
import type {SkillEvalComparison} from '../manifest';
@@ -14,28 +14,62 @@ export const comparisonsRoot = join(runsRoot, 'comparisons');
export const port = Number(process.env.PORT ?? 4321);
export const origin = `http://localhost:${port}`;
-const AppLayout = ({children}: {children: React.ReactNode}) => (
+export type RenderMode = 'server' | 'static';
+
+export type RenderOptions = {
+ fileHrefPrefix?: string;
+ mode?: RenderMode;
+};
+
+const defaultRenderOptions = {
+ fileHrefPrefix: '/files',
+ mode: 'server',
+} satisfies Required<RenderOptions>;
+
+export const getRenderOptions = (
+ options: RenderOptions | undefined,
+): Required<RenderOptions> => ({
+ ...defaultRenderOptions,
+ ...options,
+});
+
+const joinHref = (prefix: string, path: string) =>
+ prefix === '' ? path : `${prefix.replace(/\/$/, '')}/${path}`;
+
+const AppLayout = ({
+ children,
+ options,
+}: {
+ children: React.ReactNode;
+ options: Required<RenderOptions>;
+}) => (
<div className="isolate mx-auto max-w-6xl px-6 py-6 max-md:px-4">
- <nav className="mb-8 border-b border-zinc-200 pb-4">
- <a
- className="text-[0.8125rem] font-medium text-zinc-500 hover:text-zinc-900"
- href="/"
- >
- Scenarios
- </a>
- </nav>
+ {options.mode === 'server' ? (
+ <nav className="mb-8 border-b border-zinc-200 pb-4">
+ <a
+ className="text-[0.8125rem] font-medium text-zinc-500 hover:text-zinc-900"
+ href="/"
+ >
+ Scenarios
+ </a>
+ </nav>
+ ) : null}
{children}
</div>
);
export const page = ({
children,
+ renderOptions,
title,
}: {
children: React.ReactNode;
+ renderOptions?: RenderOptions;
title: string;
-}) =>
- `<!doctype html>${renderToStaticMarkup(
+}) => {
+ const options = getRenderOptions(renderOptions);
+
+ return `<!doctype html>${renderToStaticMarkup(
<html>
<head>
<meta charSet="utf-8" />
@@ -44,10 +78,11 @@ export const page = ({
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4" />
</head>
<body className="bg-zinc-50 text-zinc-900 antialiased">
- <AppLayout>{children}</AppLayout>
+ <AppLayout options={options}>{children}</AppLayout>
</body>
</html>,
)}`;
+};
export const Header = ({
action,
@@ -121,14 +156,17 @@ export const getDurationMs = ({
createdAt: string;
}) => new Date(completedAt).getTime() - new Date(createdAt).getTime();
-export const toFileUrl = (file: string) => {
+export const toFileUrl = (file: string, options?: RenderOptions) => {
const relativePath = relative(runsRoot, file);
- if (relativePath.startsWith('..')) {
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) {
throw new Error(`Cannot serve file outside .runs: ${file}`);
}
- return `/files/${relativePath.split(/[\\/]/).map(encodeURIComponent).join('/')}`;
+ return joinHref(
+ getRenderOptions(options).fileHrefPrefix,
+ relativePath.split(/[\\/]/).map(encodeURIComponent).join('/'),
+ );
};
export const toComparisonUrl = (comparison: SkillEvalComparison) =>
@@ -136,6 +174,150 @@ export const toComparisonUrl = (comparison: SkillEvalComparison) =>
comparison.id,
)}`;
+export const ShareResultButton = ({
+ endpoint,
+ label = 'Share',
+}: {
+ endpoint: string;
+ label?: string;
+}) => (
+ <div className="relative">
+ <button
+ className="rounded-full border border-zinc-200 bg-white px-3 py-2 text-[0.8125rem] font-semibold text-zinc-700 hover:border-zinc-300 disabled:bg-zinc-100 disabled:text-zinc-400"
+ data-share-endpoint={endpoint}
+ id="share-result"
+ type="button"
+ >
+ {label}
+ </button>
+ <div
+ aria-live="polite"
+ className="absolute right-0 top-full z-10 mt-2 w-[min(32rem,calc(100vw-2rem))] rounded-2xl border border-zinc-200 bg-white p-3 text-left shadow-[0_16px_40px_rgba(24,24,27,0.12)]"
+ hidden
+ id="share-result-output"
+ />
+ </div>
+);
+
+export const ShareResultScript = () => (
+ <script
+ dangerouslySetInnerHTML={{
+ __html: `
+(() => {
+ const button = document.getElementById('share-result');
+ const output = document.getElementById('share-result-output');
+
+ if (!button || !output) {
+ return;
+ }
+
+ const closeOutput = () => {
+ output.hidden = true;
+ };
+
+ const renderOutput = ({command, isError = false, message, title}) => {
+ output.hidden = false;
+ output.replaceChildren();
+
+ const titleElement = document.createElement('p');
+ titleElement.className = isError ? 'text-sm font-semibold text-red-700' : 'text-sm font-semibold text-zinc-900';
+ titleElement.textContent = title;
+ output.append(titleElement);
+
+ if (message) {
+ const messageElement = document.createElement('p');
+ messageElement.className = isError ? 'mt-1 text-xs text-red-600' : 'mt-1 text-xs text-zinc-500';
+ messageElement.textContent = message;
+ output.append(messageElement);
+ }
+
+ if (!command) {
+ return;
+ }
+
+ const commandRow = document.createElement('div');
+ commandRow.className = 'mt-3 flex items-start gap-2';
+
+ const commandElement = document.createElement('code');
+ commandElement.className = 'min-w-0 flex-1 overflow-auto whitespace-pre rounded-xl bg-zinc-100 px-3 py-2 text-xs text-zinc-700';
+ commandElement.textContent = command;
+ commandRow.append(commandElement);
+
+ const copyButton = document.createElement('button');
+ copyButton.className = 'shrink-0 rounded-full border border-zinc-200 bg-white px-3 py-2 text-xs font-semibold text-zinc-700 hover:border-zinc-300';
+ copyButton.type = 'button';
+ copyButton.textContent = 'Copy';
+ copyButton.addEventListener('click', async () => {
+ await navigator.clipboard?.writeText(command);
+ copyButton.textContent = 'Copied';
+ setTimeout(() => {
+ copyButton.textContent = 'Copy';
+ }, 1500);
+ });
+ commandRow.append(copyButton);
+ output.append(commandRow);
+ };
+
+ document.addEventListener('click', (event) => {
+ if (output.hidden) {
+ return;
+ }
+
+ if (button.contains(event.target) || output.contains(event.target)) {
+ return;
+ }
+
+ closeOutput();
+ });
+
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') {
+ closeOutput();
+ }
+ });
+
+ button.addEventListener('click', async () => {
+ const endpoint = button.dataset.shareEndpoint;
+
+ if (!endpoint) {
+ return;
+ }
+
+ button.disabled = true;
+ renderOutput({
+ message: 'Preparing the static files locally.',
+ title: 'Building share bundle...',
+ });
+
+ try {
+ const response = await fetch(endpoint, {method: 'POST'});
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(result.error || 'Could not build share bundle.');
+ }
+
+ renderOutput({
+ command: result.deployCommand,
+ message: 'Static share bundle is ready. Deploy it with Vercel CLI:',
+ title: 'Share bundle ready',
+ });
+ } catch (error) {
+ renderOutput({
+ isError: true,
+ message: error instanceof Error ? error.message : String(error),
+ title: 'Could not build share bundle',
+ });
+ } finally {
+ button.disabled = false;
+ }
+ });
+})();
+`,
+ }}
+ />
+);
+
export const json = (value: unknown, init?: ResponseInit) =>
new Response(JSON.stringify(value), {
...init,
diff --git a/packages/skills-evals/src/cli.ts b/packages/skills-evals/src/cli.ts
index c9c851f473..5bd3bcf638 100644
--- a/packages/skills-evals/src/cli.ts
+++ b/packages/skills-evals/src/cli.ts
@@ -1,5 +1,15 @@
+import {join} from 'node:path';
import {scenarios} from '../scenarios';
import {runSkillEvalComparison} from './compare';
+import {
+ createSkillEvalId,
+ createSkillEvalName,
+ getSkillEvalDir,
+ getSkillEvalPath,
+ toEvalUrl,
+ writeSkillEval,
+} from './eval';
+import {exportStaticSite} from './export-static-site';
import {maxParallelSkillEvalRuns, validateSkillEvalRunCount} from './run-count';
import {runSkillEval} from './run-skill-eval';
import {runWithConcurrency} from './run-with-concurrency';
@@ -80,6 +90,36 @@ const parseCompareOptions = (args: string[]) => {
};
};
+const parseExportOptions = (args: string[]) => {
+ let outDir: string | undefined;
+ const targets: string[] = [];
+
+ for (let index = 0; index < args.length; index++) {
+ const arg = args[index];
+
+ if (arg === '--out') {
+ const value = args[index + 1];
+
+ if (!value) {
+ throw new Error('Pass a value after --out.');
+ }
+
+ outDir = value;
+ index++;
+ } else if (arg.startsWith('--out=')) {
+ outDir = arg.slice('--out='.length);
+ } else {
+ targets.push(arg);
+ }
+ }
+
+ if (targets.length === 0) {
+ throw new Error('Pass at least one eval path.');
+ }
+
+ return {outDir, targets};
+};
+
const main = async () => {
const command = process.argv[2];
@@ -88,6 +128,7 @@ const main = async () => {
} else if (command === 'compare') {
const scenario = getScenario(process.argv[3]);
const {beforeGitRef, runCount} = parseCompareOptions(process.argv.slice(4));
+ const evalId = createSkillEvalId(scenario.id);
process.stdout.write(
`Comparing ${scenario.id} with ${scenario.model}${
beforeGitRef ? ` against ${beforeGitRef}` : ''
@@ -95,6 +136,7 @@ const main = async () => {
);
const result = await runSkillEvalComparison(scenario, {
beforeGitRef,
+ evalId,
onLog: (chunk) => process.stdout.write(chunk),
runCount,
});
@@ -104,6 +146,18 @@ const main = async () => {
return;
}
+ const evalName = createSkillEvalName({id: evalId, type: 'comparison'});
+ await writeSkillEval({
+ comparisonPath: join(result.comparison.comparisonDir, 'comparison.json'),
+ completedAt: result.comparison.completedAt,
+ createdAt: result.comparison.createdAt,
+ evalDir: getSkillEvalDir(scenario.id, evalId),
+ id: evalId,
+ name: evalName,
+ runCount,
+ scenarioId: scenario.id,
+ type: 'comparison',
+ });
process.stdout.write(
result.comparison.runs
?.map(
@@ -113,7 +167,20 @@ const main = async () => {
.join('') ??
`${scenario.id}: ${result.comparison.before.hash} -> ${result.comparison.after.hash}\n`,
);
+ process.stdout.write(
+ `Eval: ${evalName} - ${serverUrl}${toEvalUrl({id: evalId, scenarioId: scenario.id})}\n`,
+ );
+ process.stdout.write(
+ `Eval metadata: ${getSkillEvalPath(scenario.id, evalId)}\n`,
+ );
process.stdout.write(`Preview: ${serverUrl}\n`);
+ } else if (command === 'export') {
+ const {outDir, targets} = parseExportOptions(process.argv.slice(3));
+ const result = await exportStaticSite({outDir, targets});
+
+ process.stdout.write(`Exported ${result.targetCount} result(s).\n`);
+ process.stdout.write(`Index: ${result.indexHtmlPath}\n`);
+ process.stdout.write(`Deploy: ${result.deployCommand}\n`);
} else if (command === 'list') {
for (const scenario of scenarios) {
process.stdout.write(`${scenario.id}\t${scenario.model}\n`);
@@ -129,6 +196,8 @@ const main = async () => {
const runCount = parseRunCount(process.argv.slice(4));
for (const scenario of scenariosToRun) {
+ const createdAt = new Date().toISOString();
+ const evalId = createSkillEvalId(scenario.id);
process.stdout.write(
`Running ${scenario.id} with ${scenario.model} (${runCount} ${
runCount === 1 ? 'run' : 'runs'
@@ -144,6 +213,8 @@ const main = async () => {
worker: async (runIndex) => {
const result = await runSkillEval({
...scenario,
+ evalId,
+ evalRunIndex: runIndex,
runLabel:
runCount === 1
? undefined
@@ -160,13 +231,35 @@ const main = async () => {
},
});
+ const completedAt = new Date().toISOString();
+ const evalName = createSkillEvalName({id: evalId, type: 'run'});
+ await writeSkillEval({
+ completedAt,
+ createdAt,
+ evalDir: getSkillEvalDir(scenario.id, evalId),
+ id: evalId,
+ name: evalName,
+ runCount,
+ runs: results.map((result, index) => ({
+ index: index + 1,
+ manifestPath: result.manifestPath,
+ })),
+ scenarioId: scenario.id,
+ type: 'run',
+ });
process.stdout.write(
`Completed ${results.length} ${results.length === 1 ? 'run' : 'runs'} for ${scenario.id}\n`,
);
+ process.stdout.write(
+ `Eval: ${evalName} - ${serverUrl}${toEvalUrl({id: evalId, scenarioId: scenario.id})}\n`,
+ );
+ process.stdout.write(
+ `Eval metadata: ${getSkillEvalPath(scenario.id, evalId)}\n`,
+ );
}
} else {
process.stdout.write(
- 'Usage: bun run eval <list|run|compare|dev> [scenario-id|--all] [base-ref] [--runs 1-4]\n',
+ 'Usage: bun run eval <list|run|compare|export|dev> [scenario-id|--all] [base-ref] [--runs 1-4]\n',
);
process.exit(command ? 1 : 0);
}
diff --git a/packages/skills-evals/src/compare.ts b/packages/skills-evals/src/compare.ts
index ac083b5ea4..946909cdb0 100644
--- a/packages/skills-evals/src/compare.ts
+++ b/packages/skills-evals/src/compare.ts
@@ -71,6 +71,7 @@ type SkillEvalComparisonResult =
type SkillEvalComparisonOptions = {
beforeGitRef?: string;
+ evalId?: string;
onEvent?: (event: SkillEvalComparisonEvent) => void;
onLog?: (chunk: string) => void;
runCount?: number;
@@ -232,6 +233,8 @@ export const runSkillEvalComparison = async (
try {
const result = await runSkillEval({
...scenario,
+ evalId: options.evalId,
+ evalRunIndex: runIndex,
onOutput: forwardOutput(label, runIndex),
onPhase: forwardPhase(label, runIndex),
runLabel:
@@ -332,6 +335,7 @@ export const runSkillEvalComparison = async (
completedAt,
comparisonDir,
createdAt,
+ evalId: options.evalId,
id: comparisonId,
runCount,
runs: runPairs,
diff --git a/packages/skills-evals/src/eval.ts b/packages/skills-evals/src/eval.ts
new file mode 100644
index 0000000000..10e9586908
--- /dev/null
+++ b/packages/skills-evals/src/eval.ts
@@ -0,0 +1,124 @@
+import {existsSync} from 'node:fs';
+import {mkdir} from 'node:fs/promises';
+import {dirname, join, resolve} from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {
+ createTimestamp,
+ listFilesRecursively,
+ readJson,
+ sanitizePathPart,
+ writeJson,
+} from './files';
+import type {SkillEval} from './manifest';
+
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+export const evalsRoot = join(packageRoot, '.runs', 'evals');
+
+const evalNameAdjectives = [
+ 'amber',
+ 'bright',
+ 'calm',
+ 'clear',
+ 'cosmic',
+ 'golden',
+ 'lucky',
+ 'quiet',
+ 'silver',
+ 'swift',
+ 'vivid',
+ 'warm',
+];
+
+const evalNameNouns = [
+ 'beacon',
+ 'comet',
+ 'falcon',
+ 'harbor',
+ 'lantern',
+ 'meadow',
+ 'orbit',
+ 'pilot',
+ 'river',
+ 'signal',
+ 'spark',
+ 'voyage',
+];
+
+const hashString = (value: string) => {
+ let hash = 0;
+
+ for (const char of value) {
+ hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
+ }
+
+ return hash;
+};
+
+export const createSkillEvalId = (scenarioId: string) =>
+ `${createTimestamp()}--${sanitizePathPart(scenarioId)}`;
+
+export const createSkillEvalName = ({
+ id,
+ type,
+}: {
+ id: string;
+ type: SkillEval['type'];
+}) => {
+ const hash = hashString(id);
+ const adjective = evalNameAdjectives[hash % evalNameAdjectives.length];
+ const noun =
+ evalNameNouns[
+ Math.floor(hash / evalNameAdjectives.length) % evalNameNouns.length
+ ];
+ const suffix = hash.toString(36).slice(0, 4).toUpperCase();
+ const prefix = type === 'run' ? 'Run' : 'Comparison';
+
+ return `${prefix} ${adjective} ${noun} ${suffix}`;
+};
+
+export const getSkillEvalName = (evaluation: SkillEval) =>
+ evaluation.name || createSkillEvalName(evaluation);
+
+export const getSkillEvalDir = (scenarioId: string, evalId: string) =>
+ join(evalsRoot, sanitizePathPart(scenarioId), evalId);
+
+export const getSkillEvalPath = (scenarioId: string, evalId: string) =>
+ join(getSkillEvalDir(scenarioId, evalId), 'eval.json');
+
+export const toEvalUrl = (evaluation: Pick<SkillEval, 'id' | 'scenarioId'>) =>
+ `/evals/${encodeURIComponent(evaluation.scenarioId)}/${encodeURIComponent(
+ evaluation.id,
+ )}`;
+
+export const writeSkillEval = async (evaluation: SkillEval) => {
+ await mkdir(evaluation.evalDir, {recursive: true});
+ await writeJson(join(evaluation.evalDir, 'eval.json'), evaluation);
+};
+
+export const loadSkillEval = (
+ scenarioId: string,
+ evalId: string,
+): Promise<SkillEval | null> => {
+ const file = getSkillEvalPath(scenarioId, evalId);
+
+ if (!existsSync(file)) {
+ return Promise.resolve(null);
+ }
+
+ return readJson<SkillEval>(file);
+};
+
+export const listSkillEvals = async (scenarioId?: string) => {
+ const root = scenarioId
+ ? join(evalsRoot, sanitizePathPart(scenarioId))
+ : evalsRoot;
+ const files = (await listFilesRecursively(root)).filter((file) =>
+ file.endsWith('/eval.json'),
+ );
+ const evaluations = await Promise.all(
+ files.map((file) => readJson<SkillEval>(file)),
+ );
+
+ return evaluations.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
+};
diff --git a/packages/skills-evals/src/export-static-site.ts b/packages/skills-evals/src/export-static-site.ts
new file mode 100644
index 0000000000..5b0e79c162
--- /dev/null
+++ b/packages/skills-evals/src/export-static-site.ts
@@ -0,0 +1,340 @@
+import {existsSync} from 'node:fs';
+import {cp, mkdir, rm, stat, writeFile} from 'node:fs/promises';
+import {
+ basename,
+ dirname,
+ isAbsolute,
+ join,
+ relative,
+ resolve,
+} from 'node:path';
+import {type ComparisonWithManifests} from './app/comparison-data';
+import {
+ loadSkillEvalData,
+ renderEval,
+ type SkillEvalWithData,
+} from './app/eval';
+import {renderShareIndex, type ShareResult} from './app/share';
+import {packageRoot, type RenderOptions, runsRoot} from './app/shared';
+import {getSkillEvalPath, loadSkillEval} from './eval';
+import {createTimestamp, readJson, sanitizePathPart, writeJson} from './files';
+import type {SkillEval, SkillEvalManifest} from './manifest';
+
+export type StaticExportEvalTarget = {
+ evalId: string;
+ scenarioId: string;
+ type: 'eval';
+};
+
+export type StaticExportTarget = StaticExportEvalTarget | string;
+
+export type ExportStaticSiteOptions = {
+ outDir?: string;
+ targets: StaticExportTarget[];
+};
+
+type ResolvedTarget = {
+ data: SkillEvalWithData;
+ evalPath: string;
+ type: 'eval';
+};
+
+export type ExportStaticSiteResult = {
+ deployCommand: string;
+ indexHtmlPath: string;
+ outDir: string;
+ targetCount: number;
+};
+
+const siteRoot = join(packageRoot, '.site');
+
+const toPosixPath = (path: string) => path.split(/[\\/]/).join('/');
+
+const posixRelativePath = (from: string, to: string) => {
+ const path = toPosixPath(relative(from, to));
+
+ return path === '' ? '.' : path;
+};
+
+const shellQuote = (value: string) => JSON.stringify(value);
+
+const writeHtml = async (file: string, html: string) => {
+ await mkdir(dirname(file), {recursive: true});
+ await writeFile(file, html);
+};
+
+const assertInsideRunsRoot = (file: string) => {
+ const relativePath = relative(runsRoot, file);
+
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) {
+ throw new Error(`Cannot export file outside .runs: ${file}`);
+ }
+
+ return relativePath;
+};
+
+const copyRunAsset = async (outDir: string, file: string) => {
+ if (!existsSync(file)) {
+ return;
+ }
+
+ const relativePath = assertInsideRunsRoot(file);
+ const destination = join(outDir, 'files', relativePath);
+
+ await mkdir(dirname(destination), {recursive: true});
+ await cp(file, destination);
+};
+
+const addIfExists = (assetPaths: Set<string>, file: string | undefined) => {
+ if (file && existsSync(file)) {
+ assetPaths.add(file);
+ }
+};
+
+const collectManifestAssets = (
+ assetPaths: Set<string>,
+ manifest: SkillEvalManifest,
+ manifestPath?: string,
+) => {
+ addIfExists(assetPaths, manifestPath);
+ addIfExists(assetPaths, manifest.pi.htmlExport);
+
+ for (const artifact of manifest.artifacts) {
+ addIfExists(assetPaths, artifact.path);
+ }
+
+ for (const command of Object.values(manifest.commands)) {
+ addIfExists(assetPaths, command.stdoutPath);
+ addIfExists(assetPaths, command.stderrPath);
+ }
+};
+
+const collectComparisonAssets = (
+ assetPaths: Set<string>,
+ comparisonData: ComparisonWithManifests,
+ comparisonPath: string,
+) => {
+ addIfExists(assetPaths, comparisonPath);
+ addIfExists(assetPaths, comparisonData.comparison.skillDiffPath);
+
+ const comparisonRuns = comparisonData.comparison.runs ?? [
+ {
+ after: comparisonData.comparison.after,
+ before: comparisonData.comparison.before,
+ index: 1,
+ },
+ ];
+
+ for (const run of comparisonData.runs) {
+ const metadata = comparisonRuns.find(
+ (candidate) => candidate.index === run.index,
+ );
+
+ collectManifestAssets(
+ assetPaths,
+ run.beforeManifest,
+ metadata?.before.manifestPath,
+ );
+ collectManifestAssets(
+ assetPaths,
+ run.afterManifest,
+ metadata?.after.manifestPath,
+ );
+ }
+};
+
+const collectEvalAssets = (assetPaths: Set<string>, target: ResolvedTarget) => {
+ addIfExists(assetPaths, target.evalPath);
+
+ if (target.data.type === 'run') {
+ for (const [index, manifest] of target.data.manifests.entries()) {
+ collectManifestAssets(
+ assetPaths,
+ manifest,
+ target.data.evaluation.runs[index]?.manifestPath,
+ );
+ }
+
+ return;
+ }
+
+ collectComparisonAssets(
+ assetPaths,
+ target.data.comparisonData,
+ target.data.evaluation.comparisonPath,
+ );
+};
+
+const defaultOutDir = (targets: ResolvedTarget[]) => {
+ if (targets.length === 1) {
+ const target = targets[0];
+
+ return join(
+ siteRoot,
+ 'evals',
+ sanitizePathPart(target.data.evaluation.scenarioId),
+ sanitizePathPart(target.data.evaluation.id),
+ );
+ }
+
+ const scenarioIds = [
+ ...new Set(targets.map((target) => target.data.evaluation.scenarioId)),
+ ];
+
+ return join(
+ siteRoot,
+ 'shares',
+ sanitizePathPart(scenarioIds.length === 1 ? scenarioIds[0] : 'selection'),
+ createTimestamp(),
+ );
+};
+
+const resolveEvalTarget = async (
+ target: StaticExportEvalTarget,
+): Promise<ResolvedTarget> => {
+ const evaluation = await loadSkillEval(target.scenarioId, target.evalId);
+
+ if (!evaluation) {
+ throw new Error(
+ `Could not find eval ${target.scenarioId}/${target.evalId}.`,
+ );
+ }
+
+ const data = await loadSkillEvalData(evaluation);
+
+ if (!data) {
+ throw new Error(
+ `Could not load eval ${target.scenarioId}/${target.evalId}.`,
+ );
+ }
+
+ return {
+ data,
+ evalPath: getSkillEvalPath(target.scenarioId, target.evalId),
+ type: 'eval',
+ };
+};
+
+const resolvePathTarget = async (input: string): Promise<ResolvedTarget> => {
+ const absolutePath = resolve(input);
+ const stats = await stat(absolutePath);
+ const file = stats.isDirectory()
+ ? join(absolutePath, 'eval.json')
+ : absolutePath;
+
+ if (basename(file) === 'eval.json') {
+ const evaluation = await readJson<SkillEval>(file);
+ const data = await loadSkillEvalData(evaluation);
+
+ if (!data) {
+ throw new Error(`Could not load eval from ${file}.`);
+ }
+
+ return {
+ data,
+ evalPath: file,
+ type: 'eval',
+ };
+ }
+
+ throw new Error(`Expected an eval JSON file or directory: ${input}`);
+};
+
+const resolveTarget = (target: StaticExportTarget) => {
+ if (typeof target === 'string') {
+ return resolvePathTarget(target);
+ }
+
+ return resolveEvalTarget(target);
+};
+
+const renderOptionsForPage = (
+ outDir: string,
+ pageDir: string,
+): RenderOptions => ({
+ fileHrefPrefix: posixRelativePath(pageDir, join(outDir, 'files')),
+ mode: 'static',
+});
+
+const evalPagePath = (outDir: string, target: ResolvedTarget) =>
+ join(
+ outDir,
+ 'evals',
+ encodeURIComponent(target.data.evaluation.scenarioId),
+ encodeURIComponent(target.data.evaluation.id),
+ 'index.html',
+ );
+
+const renderEvalPage = async (
+ outDir: string,
+ indexHtmlPath: string,
+ target: ResolvedTarget,
+) => {
+ const evalPageDir = dirname(indexHtmlPath);
+ await writeHtml(
+ indexHtmlPath,
+ renderEval(target.data, renderOptionsForPage(outDir, evalPageDir)),
+ );
+};
+
+export const exportStaticSite = async ({
+ outDir,
+ targets,
+}: ExportStaticSiteOptions): Promise<ExportStaticSiteResult> => {
+ if (targets.length === 0) {
+ throw new Error('Pass at least one eval to export.');
+ }
+
+ const resolvedTargets = await Promise.all(targets.map(resolveTarget));
+ const output = resolve(outDir ?? defaultOutDir(resolvedTargets));
+ const assetPaths = new Set<string>();
+
+ await rm(output, {force: true, recursive: true});
+ await mkdir(output, {recursive: true});
+
+ if (resolvedTargets.length === 1) {
+ const target = resolvedTargets[0];
+ const indexHtmlPath = join(output, 'index.html');
+
+ await renderEvalPage(output, indexHtmlPath, target);
+ collectEvalAssets(assetPaths, target);
+ } else {
+ const shareResults: ShareResult[] = [];
+
+ for (const target of resolvedTargets) {
+ const file = evalPagePath(output, target);
+
+ await renderEvalPage(output, file, target);
+ collectEvalAssets(assetPaths, target);
+ shareResults.push({
+ evaluation: target.data.evaluation,
+ href: `evals/${encodeURIComponent(
+ target.data.evaluation.scenarioId,
+ )}/${encodeURIComponent(target.data.evaluation.id)}/`,
+ });
+ }
+
+ await writeHtml(join(output, 'index.html'), renderShareIndex(shareResults));
+ }
+
+ for (const assetPath of assetPaths) {
+ await copyRunAsset(output, assetPath);
+ }
+
+ await writeJson(join(output, 'metadata.json'), {
+ createdAt: new Date().toISOString(),
+ targets: resolvedTargets.map((target) => ({
+ evalId: target.data.evaluation.id,
+ evalPath: target.evalPath,
+ scenarioId: target.data.evaluation.scenarioId,
+ type: 'eval',
+ })),
+ });
+
+ return {
+ deployCommand: `vercel deploy ${shellQuote(output)}`,
+ indexHtmlPath: join(output, 'index.html'),
+ outDir: output,
+ targetCount: resolvedTargets.length,
+ };
+};
diff --git a/packages/skills-evals/src/index.ts b/packages/skills-evals/src/index.ts
index dd146d21d9..16ea43151e 100644
--- a/packages/skills-evals/src/index.ts
+++ b/packages/skills-evals/src/index.ts
@@ -1,8 +1,19 @@
export {runSkillEvalComparison} from './compare';
+export {
+ createSkillEvalId,
+ createSkillEvalName,
+ getSkillEvalName,
+ getSkillEvalPath,
+ listSkillEvals,
+ loadSkillEval,
+ writeSkillEval,
+} from './eval';
+export {exportStaticSite} from './export-static-site';
export {runSkillEval} from './run-skill-eval';
export {scenarios} from '../scenarios';
export type {
SkillEvalComparison,
+ SkillEval,
SkillEvalManifest,
SkillEvalResult,
} from './manifest';
diff --git a/packages/skills-evals/src/manifest.ts b/packages/skills-evals/src/manifest.ts
index 765112a7dd..2a3867beee 100644
--- a/packages/skills-evals/src/manifest.ts
+++ b/packages/skills-evals/src/manifest.ts
@@ -28,6 +28,8 @@ export type LoggedCommand = Pick<
export type SkillEvalManifest = {
id: string;
+ evalId?: string;
+ evalRunIndex?: number;
model: string;
prompt: string;
createdAt: string;
@@ -80,6 +82,7 @@ export type SkillEvalComparisonRunPair = {
export type SkillEvalComparison = {
id: string;
+ evalId?: string;
scenarioId: string;
createdAt: string;
completedAt: string;
@@ -90,3 +93,30 @@ export type SkillEvalComparison = {
runCount?: number;
runs?: SkillEvalComparisonRunPair[];
};
+
+export type SkillEvalRunEntry = {
+ index: number;
+ manifestPath: string;
+};
+
+type SkillEvalBase = {
+ id: string;
+ scenarioId: string;
+ name: string;
+ createdAt: string;
+ completedAt: string;
+ evalDir: string;
+ runCount: number;
+};
+
+export type SkillEvalRun = SkillEvalBase & {
+ runs: SkillEvalRunEntry[];
+ type: 'run';
+};
+
+export type SkillEvalComparisonEval = SkillEvalBase & {
+ comparisonPath: string;
+ type: 'comparison';
+};
+
+export type SkillEval = SkillEvalComparisonEval | SkillEvalRun;
diff --git a/packages/skills-evals/src/run-skill-eval.ts b/packages/skills-evals/src/run-skill-eval.ts
index eda630345b..4c036b15ed 100644
--- a/packages/skills-evals/src/run-skill-eval.ts
+++ b/packages/skills-evals/src/run-skill-eval.ts
@@ -34,6 +34,8 @@ export type SkillEvalPhaseEvent = {
};
type SkillEvalScenarioInput = SkillEvalScenario & {
+ evalId?: string;
+ evalRunIndex?: number;
onOutput?: (output: SkillEvalOutput) => void;
onPhase?: (event: SkillEvalPhaseEvent) => void;
runRoot?: string;
@@ -379,6 +381,8 @@ export const runSkillEval = async (
const completedAt = new Date().toISOString();
const manifest = {
id: input.id,
+ evalId: input.evalId,
+ evalRunIndex: input.evalRunIndex,
model: input.model,
prompt: input.prompt,
createdAt,