File size: 16,064 Bytes
4e112fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env tsx
// Run the Embed Studio agent on the eval cases (evals/embeds/cases.json) the
// way the editor does - same system prompt, same tools, same data files - then
// render every result through the embed checker.
//
//   npm run eval:embeds                                  # every case, default model
//   npm run eval:embeds -- scaling-law messy-data        # some cases
//   npm run eval:embeds -- --model Qwen/Qwen3-Coder-480B-A35B-Instruct --label qwen-coder
//   npm run eval:embeds -- --max-steps 12 --concurrency 3
//   npm run eval:embeds -- --label qwen-coder --recheck  # re-run the checker only
//   npm run eval:embeds -- --label opus --model claude-opus --import
//     # check charts produced elsewhere: <case>/embed.html (+ reply.txt) in the label dir
//
// Auth: HF_TOKEN from the shell, else the `hf auth login` token. backend/.env
// is deliberately not loaded.
//
// Results land in .embed-evals/<label>/<case>/: embed.html, preview.html (open
// it in a browser), trace.json, screenshots. Compare two runs with
// `npm run eval:compare -- <labelA> <labelB>`.

import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { stepCountIs, streamText, tool, type Tool } from "ai";
import { buildEmbedSystemPrompt, type EmbedChatContext } from "../src/agent/embed-chat.js";
import type { DataFileMeta } from "../src/agent/embed-system-prompt.js";
import { embedTools } from "../src/agent/embed-tools.js";
import { createProvider, DEFAULT_MODEL } from "../src/agent/stream-handler.js";
import { buildEmbedSrcdoc } from "../src/shared/embed-doc.js";
import { extFromName, inferDataShape } from "../../frontend/src/utils/data-files.js";
import { backendDir, checkOne, launchBrowser, reportStatus, type Report } from "./embed-check/check.js";
import { BUILTIN_EMBEDS } from "./embed-check/registry.js";

const EVAL_DIR = join(backendDir, "evals/embeds");
// Same limits as executeToolCall in frontend/src/hooks/useEmbedChat.ts.
const MAX_EMBED_SIZE = 512_000;
const MAX_DATA_INLINE = 120_000;

interface EvalCase {
  id: string;
  prompt: string;
  files: string[];
  start?: string;
  banner?: boolean;
  watch: string[];
  success: string;
}

interface Options {
  ids: string[];
  model: string;
  label: string;
  maxSteps: number;
  concurrency: number;
  recheck: boolean;
  import: boolean;
}

function parseArgs(argv: string[]): Options {
  const model = process.env.HF_INFERENCE_MODEL || DEFAULT_MODEL;
  const opts: Options = { ids: [], model, label: "", maxSteps: 12, concurrency: 3, recheck: false, import: false };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === "--recheck") opts.recheck = true;
    else if (a === "--import") opts.import = true;
    else if (a === "--model") opts.model = argv[++i];
    else if (a === "--label") opts.label = argv[++i];
    else if (a === "--max-steps") opts.maxSteps = Number(argv[++i]);
    else if (a === "--concurrency") opts.concurrency = Math.max(1, Number(argv[++i]));
    else opts.ids.push(a);
  }
  if (!opts.label) {
    const stamp = new Date().toISOString().slice(0, 16).replace(/[-:T]/g, "");
    opts.label = `${opts.model.split("/").pop()!.replace(/[^a-zA-Z0-9.-]+/g, "-")}-${stamp}`;
  }
  return opts;
}

function hfToken(): string {
  if (process.env.HF_TOKEN) return process.env.HF_TOKEN;
  const file = join(process.env.HF_HOME || join(homedir(), ".cache/huggingface"), "token");
  if (existsSync(file)) return readFileSync(file, "utf8").trim();
  throw new Error("No HF token: export HF_TOKEN or run `hf auth login`.");
}

function slugify(raw: string): string {
  const base = raw
    .toLowerCase()
    .replace(/\.html?$/i, "")
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60);
  return base || "chart";
}

interface DataFile extends DataFileMeta {
  content: string;
}

async function loadDataFiles(names: string[]): Promise<DataFile[]> {
  return Promise.all(names.map(async (name) => {
    const content = await readFile(join(EVAL_DIR, "data", name), "utf8");
    const ext = extFromName(name);
    return { name, ext, size: Buffer.byteLength(content), content, ...inferDataShape(ext, content) };
  }));
}

interface StepTrace {
  text: string;
  finishReason: string;
  toolCalls: { tool: string; input: Record<string, unknown>; output: string }[];
}

interface CaseResult {
  id: string;
  src: string;
  html: string | null;
  reply: string;
  steps: StepTrace[];
  seconds: number;
  usage: { inputTokens?: number; outputTokens?: number };
  error?: string;
}

function describeError(err: unknown): string {
  const body = (err as { responseBody?: string }).responseBody;
  return (err instanceof Error ? err.message : String(err)) + (body ? `: ${body.slice(0, 400)}` : "");
}

function summarizeInput(input: Record<string, unknown>): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(input ?? {})) {
    out[k] = typeof v === "string" && v.length > 200 ? `<${v.length} chars>` : v;
  }
  return out;
}

async function runCase(c: EvalCase, opts: Options, token: string): Promise<CaseResult> {
  const files = await loadDataFiles(c.files);
  const embeds = new Map<string, string>();
  const isBanner = Boolean(c.banner);
  let src = isBanner ? "banner.html" : "d3-chart-eval0.html";
  if (c.start) {
    const seed = BUILTIN_EMBEDS.find((e) => e.name === c.start);
    if (!seed) throw new Error(`${c.id}: unknown start embed ${c.start}`);
    src = `${c.start}.html`;
    embeds.set(src, seed.html);
  }

  const context = (): EmbedChatContext => ({
    embedHtml: embeds.get(src),
    isBanner,
    isScratch: !isBanner && !embeds.get(src) && /^d3-chart-[a-z0-9]+\.html$/i.test(src),
    dataFiles: files.map(({ content: _content, ...meta }) => meta),
    theme: "light",
  });

  const execute = (name: string, input: Record<string, any>): string => {
    switch (name) {
      case "createEmbed": {
        const html = String(input.html ?? "").trim();
        if (!html) return "ERROR: html cannot be empty";
        if (html.length > MAX_EMBED_SIZE) return `ERROR: chart too large (${html.length} bytes, max ${MAX_EMBED_SIZE}). Simplify the code.`;
        let renamed = "";
        if (input.filename && !isBanner) {
          const target = `${slugify(input.filename)}.html`;
          if (target !== src) {
            embeds.delete(src);
            src = target;
            renamed = ` [renamed to ${target}]`;
          }
        }
        embeds.set(src, html);
        return `chart created (${html.split("\n").length} lines, ${html.length} chars)${input.title ? ` - "${input.title}"` : ""}${renamed}`;
      }
      case "patchEmbed": {
        const current = embeds.get(src);
        if (!current) return "ERROR: no chart exists yet. Use createEmbed first.";
        if (!input.search) return "ERROR: search block cannot be empty";
        if (!current.includes(input.search)) return "ERROR: search block not found in current chart. Call readEmbed to see the exact current content, then retry.";
        const patched = current.replace(input.search, input.replace ?? "");
        if (patched.length > MAX_EMBED_SIZE) return `ERROR: patch would exceed size limit (${patched.length} bytes, max ${MAX_EMBED_SIZE}).`;
        embeds.set(src, patched);
        return "patch applied successfully";
      }
      case "readEmbed":
        return embeds.get(src) ?? "(no chart yet)";
      case "listDataFiles":
        if (!files.length) return "(no data files attached)";
        return files.map((f) => {
          const cols = f.columns?.length ? ` columns=[${f.columns.join(", ")}]` : "";
          const rows = f.rowCount !== undefined ? ` rows=${f.rowCount}` : "";
          return `- ${f.name} (${f.ext}, ${f.size} bytes)${rows}${cols}`;
        }).join("\n");
      case "readDataFile": {
        const file = files.find((f) => f.name === input.name);
        if (!file) return `ERROR: data file "${input.name}" not found`;
        if (file.content.length <= MAX_DATA_INLINE) return file.content;
        return file.content.slice(0, MAX_DATA_INLINE) +
          `\n\n[TRUNCATED - full file is ${file.content.length} chars, showing first ${MAX_DATA_INLINE}]`;
      }
      default:
        return `Unknown tool: ${name}`;
    }
  };

  const tools = Object.fromEntries(
    Object.entries(embedTools).map(([name, t]) => [
      name,
      tool({ ...(t as Tool), execute: async (input: Record<string, unknown>) => execute(name, input) } as Tool),
    ]),
  );

  const started = Date.now();
  const result: CaseResult = { id: c.id, src, html: null, reply: "", steps: [], seconds: 0, usage: {} };
  try {
    // Streamed like the editor: a long non-streamed generation hits gateway timeouts.
    const out = streamText({
      model: createProvider(token).chatModel(opts.model),
      system: buildEmbedSystemPrompt(context()),
      // Like the editor: refresh the chart in the prompt and drop past reasoning
      // parts, which some providers reject (see stripReasoningParts).
      prepareStep: ({ messages }) => ({
        system: buildEmbedSystemPrompt(context()),
        messages: messages.map((m) =>
          m.role === "assistant" && Array.isArray(m.content)
            ? { ...m, content: m.content.filter((p) => p.type !== "reasoning") }
            : m,
        ),
      }),
      messages: [{ role: "user", content: c.prompt }],
      tools,
      stopWhen: stepCountIs(opts.maxSteps),
      onStepFinish: (s) => {
        result.steps.push({
          text: s.text,
          finishReason: s.finishReason,
          toolCalls: s.toolCalls.map((call) => {
            const res = s.toolResults.find((r) => r.toolCallId === call.toolCallId);
            const output = typeof res?.output === "string" ? res.output : JSON.stringify(res?.output ?? null);
            return { tool: call.toolName, input: summarizeInput(call.input as Record<string, unknown>), output: output.slice(0, 300) };
          }),
        });
      },
      onError: ({ error }) => { result.error ??= describeError(error); },
    });
    await out.consumeStream({ onError: (error) => { result.error ??= describeError(error); } });
    if (!result.error) {
      result.reply = await out.text;
      const usage = await out.totalUsage;
      result.usage = { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens };
    }
  } catch (err) {
    result.error ??= describeError(err);
  }
  result.seconds = Math.round((Date.now() - started) / 1000);
  result.src = src;
  result.html = embeds.get(src) ?? null;
  return result;
}

async function pool<T, R>(items: T[], size: number, fn: (item: T) => Promise<R>): Promise<R[]> {
  const results: R[] = new Array(items.length);
  let next = 0;
  await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i]);
    }
  }));
  return results;
}

const opts = parseArgs(process.argv.slice(2));
const allCases = JSON.parse(await readFile(join(EVAL_DIR, "cases.json"), "utf8")) as EvalCase[];
let cases = opts.ids.length ? allCases.filter((c) => opts.ids.includes(c.id)) : allCases;
if (!cases.length) {
  console.error(`No case matches ${opts.ids.join(", ")}. Known: ${allCases.map((c) => c.id).join(", ")}`);
  process.exit(2);
}
const runDir = resolve(backendDir, ".embed-evals", opts.label);
await mkdir(runDir, { recursive: true });
const previousRun = existsSync(join(runDir, "run.json"))
  ? JSON.parse(await readFile(join(runDir, "run.json"), "utf8")) as { model: string; promptHash: string; summary: { id: string }[] }
  : null;
let results: CaseResult[];
let promptHash: string;

if (opts.import) {
  promptHash = createHash("sha256").update(buildEmbedSystemPrompt({})).digest("hex").slice(0, 12);
  cases = cases.filter((c) => existsSync(join(runDir, c.id, "embed.html")));
  results = await Promise.all(cases.map(async (c) => {
    const replyFile = join(runDir, c.id, "reply.txt");
    return {
      id: c.id, src: `${c.id}.html`, seconds: 0, usage: {},
      html: await readFile(join(runDir, c.id, "embed.html"), "utf8"),
      reply: existsSync(replyFile) ? (await readFile(replyFile, "utf8")).trim() : "",
      // The external harness was handed every attached file up front.
      steps: [{ text: "", finishReason: "imported", toolCalls: c.files.map((name) => ({ tool: "readDataFile", input: { name }, output: "" })) }],
    };
  }));
  console.log(`import label=${opts.label} model=${opts.model} cases=${cases.length}`);
} else if (opts.recheck) {
  if (!previousRun) {
    console.error(`--recheck needs an existing run in ${runDir}`);
    process.exit(2);
  }
  opts.model = previousRun.model;
  promptHash = previousRun.promptHash;
  cases = cases.filter((c) => existsSync(join(runDir, c.id, "trace.json")));
  results = await Promise.all(cases.map(async (c) => {
    const trace = JSON.parse(await readFile(join(runDir, c.id, "trace.json"), "utf8"));
    const htmlFile = join(runDir, c.id, "embed.html");
    return { ...trace, html: existsSync(htmlFile) ? await readFile(htmlFile, "utf8") : null } as CaseResult;
  }));
  console.log(`recheck label=${opts.label} cases=${cases.length}`);
} else {
  const token = hfToken();
  promptHash = createHash("sha256").update(buildEmbedSystemPrompt({})).digest("hex").slice(0, 12);
  console.log(`model=${opts.model} label=${opts.label} prompt=${promptHash} cases=${cases.length}`);
  results = await pool(cases, opts.concurrency, async (c) => {
    const r = await runCase(c, opts, token);
    const calls = r.steps.flatMap((s) => s.toolCalls.map((t) => t.tool));
    console.log(`  ${c.id}: ${r.error ? `error (${r.error.slice(0, 120)})` : r.html ? "chart" : "no chart"} in ${r.seconds}s, ${r.steps.length} steps [${calls.join(", ")}]`);
    return r;
  });
}

const browser = await launchBrowser();
const summary: Record<string, unknown>[] = [];
try {
  for (const [i, r] of results.entries()) {
    const c = cases[i];
    const dir = join(runDir, c.id);
    await mkdir(dir, { recursive: true });
    let report: Report | null = null;
    if (r.html) {
      await writeFile(join(dir, "embed.html"), r.html);
      const preview = buildEmbedSrcdoc(r.html, { isDark: false, fullBleed: Boolean(c.banner) })
        .replace("</head>", "<style>html { background: var(--page-bg); }</style></head>");
      await writeFile(join(dir, "preview.html"), preview);
      report = await checkOne(browser, { name: c.id, html: r.html, banner: Boolean(c.banner) }, { widths: [360, 760], out: runDir });
    }
    await writeFile(join(dir, "trace.json"), JSON.stringify({ case: c, ...r, html: undefined, check: report }, null, 2));
    const status = r.error ? "ERROR" : report ? reportStatus(report) : "NO CHART";
    const toolCalls = r.steps.reduce((n, s) => n + s.toolCalls.length, 0);
    const read = new Set(r.steps.flatMap((s) => s.toolCalls.filter((t) => t.tool === "readDataFile").map((t) => t.input.name)));
    const unread = c.files.filter((f) => !read.has(f));
    summary.push({ id: c.id, status, fails: report?.fails.length ?? 0, warns: report?.warns.length ?? 0, unreadFiles: unread.length, toolCalls, seconds: r.seconds, chars: r.html?.length ?? 0 });
  }
} finally {
  await browser.close();
}

// Partial runs and rechecks keep the other cases of the same label.
const kept = (previousRun?.summary ?? []).filter((s) => !summary.some((n) => n.id === s.id));
const merged = allCases.map((c) => [...kept, ...summary].find((s) => s.id === c.id)).filter(Boolean);
await writeFile(join(runDir, "run.json"), JSON.stringify({ model: opts.model, promptHash, date: new Date().toISOString(), maxSteps: opts.maxSteps, summary: merged }, null, 2));
console.log("");
console.table(summary);
console.log(`\nResults: ${runDir.replace(`${backendDir}/`, "")}`);