Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Evaluation Center: Benchmarks become Project-level peers of agents, created with AI or by hand and optimized against (#596)

Yaowei Zheng744bbca639cb
diff --git a/changelog/unreleased/2026-09-02-evaluation-center.md b/changelog/unreleased/2026-09-02-evaluation-center.md
new file mode 100644
index 00000000..7a83154f
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-evaluation-center.md
@@ -0,0 +1,36 @@
+# The Evaluation Center creates and optimizes Benchmarks
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `skills`, `docs`
+- **PR:** [#596](https://github.com/Prism-Shadow/penguin-harness/pull/596)
+
+[中文版](2026-09-02-evaluation-center.zh.md)
+
+A Benchmark became a peer of an agent rather than something an agent owns: it moved to the Project level, one Benchmark can evaluate several agents, and the agent under test is recorded on each evaluation. The Evaluation Center was rebuilt around that and around the loop a first-timer needs — create a Benchmark, read its scores, hand it to an optimizer — each step one click away, with the prompts written for the person.
+
+## Details
+
+- Benchmarks moved from `agents/<agent>/benchmarks/<id>/` to the Project's `benchmarks/<id>/`, a sibling of `agents/`. `benchmark_config.toml` (title, description, runs) records no agent; every `scoreboard.yaml` evaluation carries the agent it tested as `agent_id`, written right after `time`. Files stayed the single source of truth.
+- `agent_id`, `model_id` and `thinking_level` form an evaluation's **label**: three parts, written out as the legend text a series is recognized by (`<agent_id> · <model_id> · <thinking_level>`). The Benchmark chart plots time against score and draws one series per label, so only comparable scores share a line; a record with no label falls into a grey series. The Agent State `version` and the `provider` stay outside the label. Successive versions of one agent on one runtime are the trend the loop exists to show and belong on one line — the example Benchmark's three evaluations are now a single connected line — and a series has to be identifiable from the text its legend prints, which names the model id rather than the group it is served from. Each point names the version it tested in its hover bubble, the evaluation table keeps its own version column, and a card's score change is still measured against the previous evaluation under the same label.
+- A row of the evaluation table no longer unfolds inside the table. Clicking it opens an **evaluation dialog**, shaped like the case dialog beside it: the series label with the tested agent's avatar and the version it tested, the stored Score, cost and duration, the evaluation's summary with its title and body shown separately, and the per-case table, whose rows still expand to the raw result of every Run and the Session it ran in. A case named in there opens the case dialog over it.
+- Both detail dialogs end in an **Ask AI** button, which opens the Create-with-AI dialog as a question rather than a request to build something: the prompt box arrives filled in (why this evaluation came out as it did, or what this case tests), the same question leads the example buttons (so it can be brought back after trying one of the three others), and a fixed tail hands over the facts on screen. For an evaluation that is the Benchmark id and directory, the time, the series label, the version, the provider / model / thinking level, the total and per-case scores, every run's Session id and the summary, with a request to read `scoreboard.yaml` and the named Traces, explain how the scores came about, name the weak cases and suggest a next step. For a case it is the Benchmark and case ids, the `statement/README.md` and `rubric/README.md` paths, and how the latest evaluation's runs scored it, with a request to explain what the case tests, what a strong answer looks like and how the rubric discriminates. Neither asks for a change — the cases are frozen and the tested agent is not the subject — and both leave through the kit's single exit, prefilled into a new conversation with the Project's default agent.
+- The case dialog's file browser is now the shared read-only file browser (`FileBrowser`): the Workspace files panel's tree on the left — task materials and rubric as its two top-level folders, listed level by level — and one preview pane on the right; the plugin detail Modal uses the same component, so the three browsers share one style.
+- The page: one flat list, no per-agent grouping. A title with the search box (over titles, descriptions and the agents a Benchmark has evaluated) and the two create buttons beside it, the three step cards under them, and one card per Benchmark carrying its title and directory name, the case and run counts, the last evaluation time, the agents it has evaluated, the newest score with its change, and a score sparkline — the list column, the header and the cards in the Agents page's shape.
+- Opening a Benchmark **enters** it. A card, or its **View** button, navigates to that Benchmark's own page at `/benchmark/:benchmarkId` — the existing detail (chart, evaluation table, case browser) and a back button to the list — instead of expanding a second pane beside the list. An id that resolves to nothing, a deleted Benchmark or a stale link, says so and keeps the way back. Empty states carry the guide and the same pair of buttons, and `?agentId=` narrows the list to the Benchmarks that have evaluated that agent.
+- **Create with AI** and **Create manually** are the kit's two buttons, side by side and the same pair the scheduled-tasks tab uses, each opening its own path. The AI one adds a Test Agent picker above the prompt, four scenario examples written the way the draft page's benchmark example is — Benchmark id, capability, case count, techniques, desired baseline and pilot limit, line by line — and deliberately small and hard (three cases each, hidden preconditions, vague or conflicting input, strict deliverables, a desired baseline below 50), and a fixed tail that hands the `benchmark-design` Skill the agent id, a desired baseline score, a pilot-iteration limit and the layout to write; the composed prompt is prefilled into a new conversation and sending stays the user's move. The manual one is a form — title, id proposed from the title, description, runs per case, and per case a directory suffix, title, statement and rubric, with format hints on screen and a folded note on what makes a rubric discriminating — and it no longer asks which agent the Benchmark belongs to.
+- Under the title stand three separate step cards — three across on a wide screen, stacked on a narrow one — each carrying its number, its title and one sentence that says where on the page to do it (the create buttons at the top right; Use → Evaluate and Use → Optimize on a Benchmark); nothing stands above or beside them, and nothing is drawn between them: the numbers carry the order.
+- `benchmark_config.toml` carries a `status`: `draft` while `benchmark-design` is still writing the cases and calibrating their difficulty, `published` once the Formal Baseline is recorded (the Skill flips it itself; a hand-made Benchmark and the built-in example are published from the start, and a config without the field reads as published). A draft is masked in the Evaluation Center: the card dims under an overlay that says it is still being built, Use and View are disabled, its page shows the same notice instead of the cases and the chart, and only the owner's delete icon stays live so a failed calibration can be cleaned up. `agent-optimization` refuses a draft. A third value, `failed`, is written by `benchmark-design` when calibration ends without a Pilot result it can freeze: the card and the page then carry a creation-failed notice instead, the only way out is to delete the Benchmark and create it again, and `agent-evaluation` and `agent-optimization` both refuse it.
+- Sessions gain a third origin, `benchmark`: the conversation Use → Evaluate / Optimize opens is created with it, and `agent-evaluation` launches every Test Session with `penguin run --source benchmark`. The session list files them into an **Evaluations** folder beside Subagents and Scheduled — an evaluation used to pour its Case × Run Sessions into the tested agent's active list. A benchmark Session is never auto-opened as the last conversation.
+- A group whose only conversations sit inside its folders — no active row of its own, which is what an evaluation's per-case Workspaces and an agent that only ran evaluations look like — now collapses by default and sorts after the other groups of its mode (pinned groups excepted), in both workspace and agent grouping; its header is dimmed and counts the folded rows, and opening it once keeps it open for that Project. Before, every such Workspace surfaced as a full group at the top of the list.
+- **Use**, on a card and in the Benchmark page's header alike, opens one dialog: a segmented control at the top, and an Evaluate tab beside the Optimize one. Evaluate is a form (the tested agent, defaulting to the one the newest evaluation tested; the evaluator agent, warned when it lacks the `agent-evaluation` Skill; the model of the evaluation conversation, picked with the Project settings' own model picker and preset to the Project's default model; runs per case; an optional note) over a new prompt tail that asks for the full Case × runs matrix through self-spawned `agent-evaluation` subagents, requires every result's `agent_id` / `provider` / `model_id` / `thinking_level` to agree, averages per case and per evaluation as the scoreboard contract says, and appends exactly one labelled evaluation to `scoreboard.yaml` without touching the tested agent or the Benchmark. Optimize kept its form and tail, and now points an agent with no baseline at the Evaluate tab. Both tabs preview the full prompt and share one exit — prefilled into a new conversation, for the user to read and send.
+- Neither tab offers a free-text "with AI" shape beside its form: the one exit already opens the assembled prompt in an editable composer, so a second free-prompt path over the same parameters would only split the entry point in two.
+- A card's actions are **Use**, **View** and, for the owner, the Agents list's delete icon, which confirms before removing the directory whole. A card carries no overflow menu: the directory path it would have held stands beside the title on the Benchmark's own page instead, in mono, with a button that copies it.
+- Server: the Benchmark routes moved to `/api/projects/:projectId/benchmarks` and dropped their `agentId` segment, membership and ownership now being checked at the Project level. `POST` (owner only) writes `benchmark_config.toml`, a `scoreboard.yaml` holding `evaluations: []`, and each case's `statement/README.md` (the title as its heading) and `rubric/README.md`, answering 409 `benchmark_exists` for a taken id; `DELETE …/benchmarks/:id` removes the directory whole. A listed Benchmark reports `agentIds`, the distinct agents its evaluations name in first-seen order, and each evaluation reports `agentId` (`null` when the record carries none).
+- The list only returns directories holding a `benchmark_config.toml`. Deleting a Benchmark while an evaluation is still running leaves a directory behind — the run keeps writing to the paths it was deleted from — and that debris no longer appears as a Benchmark with a placeholder title. A Benchmark that has never been evaluated has its config and still lists.
+- The `benchmark-design`, `agent-evaluation` and `agent-optimization` Skills read and write the Project-level path, state that a Benchmark may evaluate several agents with `test_agent_id` naming the one a request evaluates, return `agent_id` in the evaluation protocol, and write it into every scoreboard entry they append. The `agent-tuning` plugin version became `2026.09.14.3`.
+- The example Benchmark is provisioned whenever a Project has no `benchmarks/` directory at all — when its `default_agent` is initialized, and again the first time that agent is loaded, so a data root that predates the example gets one. The check is on the directory, not on the example inside it: deleting the example while `benchmarks/` remains is a decision that stands. Its three sample evaluations are labelled `agent_id: default_agent`.
+- A Benchmark's cases are frozen once it exists: neither the Web App nor the server API can edit a statement or a rubric, because changing the questions would make the scores already on the scoreboard incomparable. Asking different questions means creating a new Benchmark; the calibration AI does while writing the cases happens before the baseline and is part of creating them.
+- The "Create with AI" bridge accepts a `modelRef`, which the Optimize dialog uses to pin the model of the optimizer's conversation.
+- A `benchmarks/` directory left under an agent by an earlier version is not read by this version; nothing migrates or deletes it.
+- The Web App, server API and self-improvement docs describe the page, the routes and the storage layout in both languages.
diff --git a/changelog/unreleased/2026-09-02-evaluation-center.zh.md b/changelog/unreleased/2026-09-02-evaluation-center.zh.md
new file mode 100644
index 00000000..29ffadb3
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-evaluation-center.zh.md
@@ -0,0 +1,36 @@
+# 评估中心可以创建与优化 Benchmark
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `skills`, `docs`
+- **PR:** [#596](https://github.com/Prism-Shadow/penguin-harness/pull/596)
+
+[English](2026-09-02-evaluation-center.md)
+
+Benchmark 从属于 Agent 变成与 Agent 平级:它移到 Project 层级,一个 Benchmark 可以评测多个 Agent,被测 Agent 记录在每条 evaluation 上。评估中心围绕这一点、也围绕新手需要的闭环重做——出一套 Benchmark、看它的分数、交给优化者——每一步都只需一次点击,提示词替人写好。
+
+## 细节
+
+- Benchmark 从 `agents/<agent>/benchmarks/<id>/` 移到 Project 的 `benchmarks/<id>/`,与 `agents/` 平级。`benchmark_config.toml`(title、description、runs)不记录任何 Agent;`scoreboard.yaml` 的每条 evaluation 以 `agent_id` 记录本轮被测的 Agent,位置紧接 `time`。磁盘文件仍是唯一真相来源。
+- `agent_id`、`model_id` 与 `thinking_level` 合成一条 evaluation 的**标签**:三者,写出来就是图例用以辨认系列的那行文字(`<agent_id> · <model_id> · <thinking_level>`)。Benchmark 曲线以时间为横轴、分数为纵轴,按标签分系列,只有可比的分数才落在同一条线上;没有标签的记录归入灰色系列。Agent State `version` 与 `provider` 都不进标签:同一被测 Agent 在同一 Runtime 下的历次版本正是这套闭环要显示的走势,本该连成一条线(示例 Benchmark 的三条评估现在就是一条连续的线);而系列必须能从图例那行文字认出来,那行文字写的是模型 id,不是它由哪个 provider 提供。版本号标在每个点的悬停提示里,评估明细表自带一列版本号,卡片上的分数增减仍以同标签的上一条评估为基准。
+- 评估明细表的行不再在表内展开。点击一行打开**评估详情弹窗**,与旁边的题目详情弹窗同一形制:顶部是系列标签、被测 Agent 头像与本次的版本号,其下为记录中的 Score、成本与耗时,再下是这次评估的说明(标题与正文分开展示)与单题得分表,题目行仍可展开逐次 run 的原始结果及其 Session id。在其中点开某道题,题目详情弹窗叠在它之上。
+- 两个详情弹窗的页脚都有**问 AI**:它把「用 AI 创建」弹窗改成提问而非下单——提示词框已经填好(这次评估为什么是这个结果 / 这道题考什么),示例按钮里排在最前的就是这个默认问题、后面三个示例可以替换它,固定尾部把屏幕上的事实一并交出去。评估这一侧是 Benchmark id 与目录、评估时间、系列标签、版本、provider / 模型 / 思考等级、总分与逐题得分、逐次 run 的 Session id 与评估说明,并要求读取 `scoreboard.yaml` 与上列 Trace 后解释分数从何而来、指出薄弱题目、给出下一步建议。题目这一侧是 Benchmark id 与题目 id、`statement/README.md` 与 `rubric/README.md` 的路径,以及最近一次评估在这道题上的逐次结果,并要求解释这道题考什么、怎样才算答好、评分细则如何区分优劣。两者都不要求任何改动——题目已冻结,被测 Agent 也不是提问的对象——出口同为套件唯一的那个:预填进与 Project 默认 Agent 的新对话。
+- 题目详情的文件浏览改用共享的只读文件浏览器组件(`FileBrowser`):左侧是 Workspace 文件面板同款的文件树——任务材料与评分标准是它的两个顶层目录,逐级懒加载——右侧是同一个预览面板;插件详情弹窗也改用它,三处浏览器从此一个样式。
+- 页面:单层平铺列表,不再按 Agent 分组。标题旁并排搜索框(按标题、描述与评测过的 Agent 过滤)与两个创建按钮,其下是三张步骤卡片;每个 Benchmark 一张卡片,显示标题与目录名、题数与运行次数、最近评估时间、评测过的 Agent、最新分数与增减、分数走势小折线——列宽、页头与卡片都取智能体页面的形制。
+- 打开 Benchmark 是**进入**它。点击卡片或其**查看**按钮进入该 Benchmark 自己的页面 `/benchmark/:benchmarkId`——原有的详情(图表、评估明细表、题目浏览器)与一个返回列表的按钮——不再在列表旁展开第二个窗格。地址里的 id 指不到东西时(Benchmark 已删除、链接过期)页面说明情况并留着返回的路。空态带指南与同样的两个按钮;`?agentId=` 把列表收窄为评测过该 Agent 的 Benchmark。
+- **用 AI 创建**与**手动创建**是套件提供的两个并排按钮,与定时任务页是同一对,各自打开一条路径。「用 AI 创建」在提示词上方加了被测 Agent 选择、四个场景示例——按首页「构建通用决策智能体和评测基准」示例的结构逐行写出 Benchmark id、capability、题量、出题手法、期望基线分与 Pilot 上限,题量少(各 3 道)而难:隐藏的先验条件、模糊或互相冲突的输入、严格的交付格式,期望基线分压到 50 以下——以及一段固定尾部——把 Agent id、期望基线分、Pilot 迭代上限与要写出的目录结构交给 `benchmark-design` 技能;写好的提示词预填进新对话,发送由用户决定。「手动创建」是一张表单——标题、随标题拟定的 id、描述、每题运行次数,以及每道题的目录名后缀、标题、题干与评分细则,格式提示常驻、「什么样的评分细则有区分度」折叠在旁——不再询问 Benchmark 属于哪个 Agent。
+- 标题下是三张独立的步骤卡片——宽屏三列并排,窄屏纵向堆叠——每张写出序号、标题与一句话操作说明(右上角的创建按钮;某个 Benchmark 上的「使用」→「评估」与「使用」→「优化」);卡片上方与旁边不再有别的文字,卡片之间也不画任何东西,顺序由序号交代。
+- `benchmark_config.toml` 新增 `status`:`benchmark-design` 仍在出题与校准难度时为 `draft`,记录 Formal Baseline 后由技能自己改为 `published`(手动创建与内置示例一开始就是 `published`,没有该字段的旧配置也按 `published` 读)。草稿在评估中心被遮罩:卡片变淡、覆一层「构建中」的提示,「使用」与「查看」禁用,页面正文以同样的提示代替题目与曲线,只有 owner 的删除图标仍可用,便于清理校准失败的草稿。`agent-optimization` 拒绝草稿。第三种取值 `failed` 由 `benchmark-design` 在校准结束却没有任何可冻结的 Pilot 结果时写入:此时卡片与页面改为「创建失败」提示,唯一的出路是删除这个 Benchmark 后重新创建,`agent-evaluation` 与 `agent-optimization` 也都会拒绝它。
+- Session 来源新增 `benchmark`:「使用 → 评估 / 优化」开出的对话以它创建,`agent-evaluation` 也以 `penguin run --source benchmark` 启动每个被测会话。会话列表把它们归入与子智能体、定时任务并列的**评估任务**子夹——此前一次评估会把 Case × Run 个会话一股脑倒进被测 Agent 的活跃列表。评估任务会话不会被当作最近一次对话自动打开。
+- 只有折叠会话、没有任何活跃会话的分组——评估为每道题建的 Workspace、只跑过评估的 Agent 都是这样——现在默认折叠并排在同一分组模式的最后(置顶者除外),按 Workspace 与按 Agent 分组同理;分组头变浅、计数为折叠会话数,点开一次后按 Project 记住。此前每个这样的 Workspace 都作为完整分组挤在列表顶部。
+- 卡片与 Benchmark 页头的**使用**打开同一个弹窗:顶部分段控件,「评估」tab 与「优化」tab 并列。「评估」是表单(被测 Agent,缺省为最近一条评估的那个;执行评估的 Agent,未装 `agent-evaluation` 技能时提示;评估会话使用的模型,用 Project 默认设置里同一个模型选择器、缺省即当前 Project 的默认模型;每题运行次数;可选说明),其新增的提示词尾部要求经自调用的 `agent-evaluation` 子会话跑完整的 Case × runs 矩阵,校验每条结果的 `agent_id` / `provider` / `model_id` / `thinking_level` 一致,按记分契约求各题与整体平均,并只向 `scoreboard.yaml` 追加一条带标签的 evaluation,不修改被测 Agent 与 Benchmark。「优化」保留原有的表单与尾部,所选被测 Agent 尚无基线时改为提示先到「评估」取得。两个 tab 都可折叠展开完整提示词,并共用一个出口——预填进新对话,交由用户过目后发送。
+- 两个 tab 都只有表单,没有并列的「用 AI」自由文本形态:唯一的出口本就把拼好的提示词开在可编辑的输入框里,再加一条参数相同的自由提示词路径只会把入口劈成两半。
+- 卡片上的动作是**使用**、**查看**,以及 owner 才有的、与智能体列表相同的删除图标——确认后整目录删除。卡片没有溢出菜单:本该放在其中的目录路径改列在 Benchmark 自己页面的标题旁,以等宽字体显示并附一个复制按钮。
+- 服务端:Benchmark 接口移到 `/api/projects/:projectId/benchmarks`,去掉了 `agentId` 段,成员与 owner 校验都在 Project 层级进行。`POST`(仅 owner)写入 `benchmark_config.toml`、内容为 `evaluations: []` 的 `scoreboard.yaml`,以及每道题的 `statement/README.md`(标题为其一级标题)与 `rubric/README.md`,id 已被占用时返回 409 `benchmark_exists`;`DELETE …/benchmarks/:id` 整目录删除。列表中的每个 Benchmark 带 `agentIds`,即其 evaluations 按首次出现顺序去重后的被测 Agent;每条 evaluation 带 `agentId`(记录中没有时为 `null`)。
+- 列表只返回带 `benchmark_config.toml` 的目录。在评测运行期间删除 Benchmark 会留下一个目录——该次运行仍在向被删除的路径写入——这类残留不再以占位标题出现在列表中。从未评测过的 Benchmark 带有配置文件,照常列出。
+- `benchmark-design`、`agent-evaluation` 与 `agent-optimization` 三个技能改读写 Project 层级的路径,写明一个 Benchmark 可以评测多个 Agent、`test_agent_id` 指的是本次请求评测的那一个,在评测协议中返回 `agent_id`,并把它写进每条追加的记分条目。`agent-tuning` 插件版本更新为 `2026.09.14.3`。
+- 示例 Benchmark 的预置条件改为「Project 没有 `benchmarks/` 目录」——`default_agent` 初始化时预置,此后每次装载也会补,因此早于该示例的存量数据根在首次装载时同样得到它。判定在目录一级而非示例本身:`benchmarks/` 还在时删掉示例是一个会被尊重的决定。三条示例评估都标注 `agent_id: default_agent`。
+- Benchmark 创建即冻结题目:Web App 与服务端接口都不能改题干或评分细则——改题会让记分板上已有的分数不再可比。要换题只能新建一个 Benchmark;AI 出题过程中的校准发生在基线确立之前,属于创建的一部分。
+- 「用 AI 创建」桥接接受 `modelRef`,优化弹窗用它固定优化会话的模型。
+- 早先版本留在 Agent 目录下的 `benchmarks/` 不被本版本读取,也不迁移、不删除。
+- Web App、服务端 API 与自我进化文档以两种语言描述了新页面、接口与存储结构。
diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts
index d85c0c92..92a7bdd5 100644
--- a/packages/cli/src/commands/run.ts
+++ b/packages/cli/src/commands/run.ts
@@ -3,8 +3,8 @@
*
* penguin run -m <msg> [--project-id <id>] [--agent-id <id>] [--workspace <path>]
* [--model-id <id> --provider <group>] [--approve <mode>]
- * [--thinking <level>] [--session <session_id>] [--background]
- * [--goal [budget]] [--json] [--server <url>]
+ * [--thinking <level>] [--session <session_id>] [--source benchmark]
+ * [--background] [--goal [budget]] [--json] [--server <url>]
*
* The CLI is a thin client: it creates a Session over the API (or reuses `--session`),
* POSTs the task, subscribes to the SSE stream and renders OmniMessages until the task
@@ -15,8 +15,10 @@
* default_project / default_agent); Workspace = the CLI's cwd (resolved locally —
* server and CLI share the machine in the default flow); model = the Project default;
* approval mode allow-all (the historical run default).
- * - `--session` accepts a full id or a unique fragment; it excludes `--workspace` and
- * the model pair (neither can change after creation); `--approve` PATCHes the mode.
+ * - `--session` accepts a full id or a unique fragment; it excludes `--workspace`, the
+ * model pair and `--source` (none can change after creation); `--approve` PATCHes the mode.
+ * - `--source benchmark` marks a NEW Session as created by a Benchmark evaluation: the Web
+ * App files it under the Evaluations folder of its session list.
* - `--background`: POST the task and exit immediately, printing the session id
* (`{"sessionId"}` under `--json`) — the task keeps running on the server.
* - `--json` (non-background): suppress rendering; print `{sessionId, status, text}`
@@ -63,6 +65,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
.option("--approve <mode>", t.common.approve)
.option("--thinking <level>", t.common.thinking)
.option("--session <sessionId>", t.run.session)
+ .option("--source <source>", t.run.source)
.option("--background", t.run.background)
.option("--timeout <duration>", t.common.timeout)
.option("--goal [budget]", t.run.goal)
@@ -93,8 +96,18 @@ export function registerRunCommand(program: Command, t: Messages): void {
return;
}
}
- if (opts.session !== undefined && (opts.workspace || opts.modelId || opts.provider)) {
- // Workspace and model are fixed at creation; a reused Session keeps its own.
+ // `benchmark` is the only origin a client may set: the server writes `subagent` and
+ // `schedule` itself, so any other value is rejected here rather than sent.
+ if (opts.source !== undefined && String(opts.source) !== "benchmark") {
+ process.stderr.write(`${t.error(t.run.sourceInvalid(String(opts.source)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ if (
+ opts.session !== undefined &&
+ (opts.workspace || opts.modelId || opts.provider || opts.source)
+ ) {
+ // Workspace, model and origin are fixed at creation; a reused Session keeps its own.
process.stderr.write(`${t.error(t.run.sessionNoOverride())}\n`);
process.exitCode = 1;
return;
@@ -156,6 +169,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
: caller
? { approvalMode: caller.approvalMode }
: {}),
+ ...(opts.source !== undefined ? { source: "benchmark" as const } : {}),
});
if (thinking === undefined && caller?.thinkingLevel !== undefined) {
callerThinking = caller.thinkingLevel;
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index c07b0307..46727e75 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -106,10 +106,14 @@ export interface Messages {
goal: string;
/** run's --session: reuse an existing Session (full id or unique fragment). */
session: string;
+ /** run's --source: mark the NEW Session as created by a Benchmark evaluation. */
+ source: string;
/** run's --background: POST the task and exit immediately, printing the session id. */
background: string;
- /** --session combined with --workspace / the model pair: neither can change after creation. */
+ /** --session combined with --workspace / the model pair / --source: all fixed at creation. */
sessionNoOverride(): string;
+ /** --source given a value other than `benchmark` (the only origin a client may set). */
+ sourceInvalid(value: string): string;
/** --background never waits, so a wait budget cannot apply to it. */
timeoutWithBackground(): string;
};
@@ -655,9 +659,13 @@ const en: Messages = {
message: "Prompt for this Task",
goal: "Goal mode: loop until the goal completes; optional token budget (e.g. 500k, 2m)",
session: "Reuse an existing Session (full id or a unique fragment, e.g. the 8-hex tail)",
+ source:
+ "Mark the new session as created by a Benchmark evaluation (`benchmark`); the Web App files it under the Evaluations folder",
background: "Post the task and exit immediately, printing the session id",
sessionNoOverride: () =>
- "--session reuses an existing Session: --workspace, --model-id and --provider cannot be combined with it (neither can change after creation).",
+ "--session reuses an existing Session: --workspace, --model-id, --provider and --source cannot be combined with it (none can change after creation).",
+ sourceInvalid: (value) =>
+ `Invalid --source value "${value}". The only accepted value is benchmark.`,
timeoutWithBackground: () =>
"--timeout bounds the wait, and --background does not wait: drop one of them.",
},
@@ -1178,9 +1186,11 @@ const zh: Messages = {
message: "本次 Task 的 Prompt",
goal: "目标模式:循环运行直至目标完成;可选 token 预算(如 500k、2m)",
session: "复用既有 Session(完整 id 或唯一片段,如末尾 8 位十六进制)",
+ source: "把新建会话标记为 Benchmark 评估创建(`benchmark`);Web App 将其归入「评估任务」子夹",
background: "提交任务后立即退出,打印 session id",
sessionNoOverride: () =>
- "--session 复用既有 Session:不能与 --workspace、--model-id、--provider 同时使用(二者创建后不可更换)。",
+ "--session 复用既有 Session:不能与 --workspace、--model-id、--provider、--source 同时使用(Workspace、模型与来源创建后不可更换)。",
+ sourceInvalid: (value) => `无效的 --source 取值 "${value}"。唯一可用取值为 benchmark。`,
timeoutWithBackground: () => "--timeout 限定等待,而 --background 不等待:二者去其一。",
},
chat: {
diff --git a/packages/cli/src/server-session.ts b/packages/cli/src/server-session.ts
index aa854414..c7a9cf09 100644
--- a/packages/cli/src/server-session.ts
+++ b/packages/cli/src/server-session.ts
@@ -60,6 +60,8 @@ export interface CreateSessionArgs {
modelId?: string;
provider?: string;
approvalMode?: string;
+ /** Marks the new Session as created by a Benchmark evaluation (the only origin a client may set). */
+ source?: "benchmark";
}
/** POST .../sessions with the CLI's client hint. */
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 4cb96637..76e474dc 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -219,8 +219,8 @@ export interface CreateSessionOptions {
baseUrl?: string;
/** Internal use: this Session's depth in the subagent spawn chain (0 at the top level), used to cap spawn depth. */
subagentDepth?: number;
- /** Session origin recorded in session_meta (absent = user-created); the subagent spawn site passes "subagent", callers driven by a scheduled task pass "schedule". */
- source?: "subagent" | "schedule";
+ /** Session origin recorded in session_meta (absent = user-created); the subagent spawn site passes "subagent", callers driven by a scheduled task pass "schedule", and a Benchmark evaluation or optimization passes "benchmark". */
+ source?: "subagent" | "schedule" | "benchmark";
}
export interface ResumeSessionOptions {
@@ -252,7 +252,7 @@ interface SessionSpec {
*/
thinkingLevel: ThinkingLevelName | null | undefined;
subagentDepth: number;
- source?: "subagent" | "schedule";
+ source?: "subagent" | "schedule" | "benchmark";
}
/**
@@ -716,9 +716,9 @@ export class Agent {
// No level at resume: the host re-applies its stored value (Session.thinkingLevel) when it holds one,
// and contexts opened without a pin read the Agent config's chain (the same chain
// createSession uses). The origin carries over from the original session_meta (a
- // resumed scheduled/subagent Session stays marked); the on-disk value is untrusted: only
- // the exact known origins pass, junk written by a third party is dropped rather than
- // cast through.
+ // resumed subagent / scheduled / benchmark Session stays marked); the on-disk value
+ // is untrusted: only the exact known origins pass, junk written by a third party is
+ // dropped rather than cast through.
const spec: SessionSpec = {
sessionId,
workspaceDir,
@@ -727,7 +727,9 @@ export class Agent {
baseUrl,
thinkingLevel: undefined,
subagentDepth: 0,
- ...(meta.source === "subagent" || meta.source === "schedule" ? { source: meta.source } : {}),
+ ...(meta.source === "subagent" || meta.source === "schedule" || meta.source === "benchmark"
+ ? { source: meta.source }
+ : {}),
};
// The context follows the Trace. A context a completed compaction closed is opened here
// for the first time — nothing was produced under any configuration yet — so it is
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index 17fb7533..d3a39560 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -131,8 +131,8 @@ export interface SessionMetaPayload {
agent_state: string;
/** Absolute path to the Workspace. */
workspace: string;
- /** Session origin: spawned by a subagent / triggered by a scheduled task; absent = user-created. */
- source?: "subagent" | "schedule";
+ /** Session origin: spawned by a subagent / triggered by a scheduled task / created by a Benchmark evaluation or optimization; absent = user-created. */
+ source?: "subagent" | "schedule" | "benchmark";
}
// ---------------------------------------------------------------------------
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index 5d435c0a..49542bfc 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -183,6 +183,18 @@ export async function loadAgentState(opts?: {
`Invalid Agent State config: ${configPath} is empty, corrupted, or missing the system_prompt field.`,
);
}
+ // The example Benchmark is provisioned on this path too, not only at initialization: a
+ // Project whose benchmarks/ directory does not exist gets one the first time its
+ // default_agent is loaded, which is what gives a data root created before this provisioning
+ // existed the same example a fresh one has. Best effort — opening a model context must not
+ // fail because a directory could not be written.
+ if (agentId === DEFAULT_AGENT_ID) {
+ try {
+ await provisionExampleBenchmark(root, projectId);
+ } catch {
+ // Nothing to do: the evaluation center simply starts out empty.
+ }
+ }
return {
root,
projectId,
@@ -230,9 +242,11 @@ export async function loadAgentState(opts?: {
atomicWriteFile(agentsMdPath(root, projectId, agentId), agentsMd, { followSymlinks: true }),
...plugins.map((plugin) => installPlugin(root, projectId, agentId, plugin)),
// The example Benchmark is only provisioned alongside default_agent (so the evaluation
- // center has data out of the box): idempotently skipped if benchmarks/ already exists,
- // and not created for plain Agents.
- ...(agentId === DEFAULT_AGENT_ID ? [provisionExampleBenchmark(root, projectId, agentId)] : []),
+ // center has data out of the box). It lands in the Project's benchmarks/, a sibling of
+ // agents/: skipped whenever that directory already exists, and never written for a plain
+ // Agent, whose creation is not a Project's first day. Awaited here, unlike on the load
+ // path — a Project's first day is the one moment a failure is worth reporting.
+ ...(agentId === DEFAULT_AGENT_ID ? [provisionExampleBenchmark(root, projectId)] : []),
]);
// system_config.yaml is written last: its existence is the "initialization complete" marker
// (the load/init decision point). If this fails partway (disk full / crash), the next run
diff --git a/packages/core/src/state/example-benchmark.ts b/packages/core/src/state/example-benchmark.ts
index cd0f30dc..6c001928 100644
--- a/packages/core/src/state/example-benchmark.ts
+++ b/packages/core/src/state/example-benchmark.ts
@@ -1,12 +1,21 @@
/**
* Provisioning of the example Benchmark.
*
- * When default_agent is initialized, it preprovisions `benchmarks/example-benchmark/`: two
- * sample cases (each with statement/ and rubric/ indexed by a README.md),
- * benchmark_config.toml (runs = 2), and a scoreboard.yaml with three sample evaluations —
- * so the evaluation center has data out of the box. Its description states plainly that this
- * is a built-in example and the whole directory can be deleted or replaced. Only
- * default_agent gets this; ordinary Agents do not.
+ * A Project whose `benchmarks/` directory does not exist yet gets the Project-level
+ * `benchmarks/example-benchmark/`: two sample cases (each with statement/ and rubric/ indexed
+ * by a README.md), benchmark_config.toml (runs = 2, status = published — the example is a
+ * finished Benchmark, not one a Skill is still writing), and a scoreboard.yaml with three sample
+ * evaluations, each labelled with default_agent as the Agent it tested — so the evaluation
+ * center has data out of the box. Its description states plainly that this is a built-in
+ * example and the whole directory can be deleted or replaced. Provisioning rides on
+ * default_agent alone, on both its initialization and every later load; creating or loading an
+ * ordinary Agent provisions nothing.
+ *
+ * The check is on the DIRECTORY, not on the example inside it: deleting the example while
+ * keeping `benchmarks/` (which is what deleting it through the Evaluation Center leaves behind,
+ * and what a Project holding Benchmarks of its own looks like) is a decision, and writing the
+ * example back on the next load would undo it. Removing `benchmarks/` whole asks for the
+ * example again, which is also how a data root that predates this provisioning gets one.
*
* Scoring numbers follow the current Scoreboard contract: every Case is scored out of 100;
* Case metrics are model-written Run averages and Evaluation metrics are model-written Case
@@ -18,7 +27,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { stringify as stringifyToml } from "smol-toml";
import { stringify as stringifyYaml } from "yaml";
-import { benchmarksDir } from "./paths.js";
+import { DEFAULT_AGENT_ID, benchmarksDir } from "./paths.js";
/** Directory name of the example Benchmark (the directory name is also its identifier). */
export const EXAMPLE_BENCHMARK_ID = "example-benchmark";
@@ -30,6 +39,7 @@ const EXAMPLE_BENCHMARK_CONFIG = {
"A built-in example benchmark so the evaluation charts have data out of the box. " +
"Replace it with your own.",
runs: 2,
+ status: "published",
};
/** Two sample cases: statement and scoring rubric (in English, 3-5 lines each). */
@@ -81,11 +91,13 @@ interface ExampleRun {
/**
* Raw runs for the three sample evaluations (case-level and evaluation-level metrics are
- * computed from these, keeping the numbers self-consistent). Each carries the model actually
- * used for that round; the examples all use deepseek-v4-pro at medium thinking.
+ * computed from these, keeping the numbers self-consistent). Each carries the Agent it tested
+ * and the model actually used for that round; the examples all evaluate default_agent on
+ * deepseek-v4-pro at medium thinking, so they share one chart series.
*/
const EXAMPLE_EVALUATIONS: Array<{
time: string;
+ agent_id: string;
version: number;
provider: string;
model_id: string;
@@ -96,6 +108,7 @@ const EXAMPLE_EVALUATIONS: Array<{
}> = [
{
time: "2026-07-14T09:30:00Z",
+ agent_id: DEFAULT_AGENT_ID,
version: 1,
provider: "deepseek",
model_id: "deepseek-v4-pro",
@@ -144,6 +157,7 @@ const EXAMPLE_EVALUATIONS: Array<{
},
{
time: "2026-07-15T09:30:00Z",
+ agent_id: DEFAULT_AGENT_ID,
version: 2,
provider: "deepseek",
model_id: "deepseek-v4-pro",
@@ -192,6 +206,7 @@ const EXAMPLE_EVALUATIONS: Array<{
},
{
time: "2026-07-16T09:30:00Z",
+ agent_id: DEFAULT_AGENT_ID,
version: 3,
provider: "deepseek",
model_id: "deepseek-v4-pro",
@@ -270,6 +285,7 @@ function averageKnownCost(values: Array<number | null>): number | null {
export function buildExampleScoreboard(): {
evaluations: Array<{
time: string;
+ agent_id: string;
version: number;
provider: string;
model_id: string;
@@ -299,6 +315,7 @@ export function buildExampleScoreboard(): {
}));
return {
time: e.time,
+ agent_id: e.agent_id,
version: e.version,
provider: e.provider,
model_id: e.model_id,
@@ -315,24 +332,20 @@ export function buildExampleScoreboard(): {
}
/**
- * Provisions the example Benchmark: if `benchmarks/` already exists (the user already has a
- * case library), does nothing; otherwise creates `benchmarks/example-benchmark/` (config, the
- * two sample cases, and the scoreboard). Callers are restricted to the default_agent
- * initialization path (see agent-state.ts).
+ * Provisions the example Benchmark into the Project's `benchmarks/`: if that directory exists at
+ * all — holding the example, the user's own Benchmarks, or nothing — does nothing; otherwise
+ * creates `benchmarks/example-benchmark/` (config, the two sample cases, and the scoreboard).
+ * Callers are restricted to default_agent's initialization and load paths (see agent-state.ts).
*/
-export async function provisionExampleBenchmark(
- root: string,
- projectId: string,
- agentId: string,
-): Promise<void> {
- const dir = benchmarksDir(root, projectId, agentId);
+export async function provisionExampleBenchmark(root: string, projectId: string): Promise<void> {
+ const dir = benchmarksDir(root, projectId);
+ const benchDir = path.join(dir, EXAMPLE_BENCHMARK_ID);
try {
await fs.access(dir);
return;
} catch {
- // benchmarks/ does not exist: proceed with provisioning.
+ // The Project has no benchmarks/ at all: proceed with provisioning.
}
- const benchDir = path.join(dir, EXAMPLE_BENCHMARK_ID);
await Promise.all(
EXAMPLE_CASES.flatMap((c) => [
fs.mkdir(path.join(benchDir, c.id, "statement"), { recursive: true }),
diff --git a/packages/core/src/state/paths.ts b/packages/core/src/state/paths.ts
index f123499b..bc31ab0b 100644
--- a/packages/core/src/state/paths.ts
+++ b/packages/core/src/state/paths.ts
@@ -144,9 +144,15 @@ export function scheduleDir(root: string, projectId: string, agentId: string): s
return path.join(agentStateDir(root, projectId, agentId), "schedule");
}
-/** `<agentDir>/benchmarks`, the capability-evaluation question bank and scores (doesn't exist when unconfigured). */
-export function benchmarksDir(root: string, projectId: string, agentId: string): string {
- return path.join(agentDir(root, projectId, agentId), "benchmarks");
+/**
+ * `<projectDir>/benchmarks`, the Project's capability-evaluation question banks and scores, a
+ * sibling of `agents/` (doesn't exist when unconfigured). A Benchmark is a peer of an Agent, not
+ * something an Agent owns: one Benchmark can evaluate several Agents, and the Agent under test is
+ * recorded on each scoreboard evaluation. Benchmarks written under an Agent directory by an
+ * earlier version are not read from here.
+ */
+export function benchmarksDir(root: string, projectId: string): string {
+ return path.join(projectDir(root, projectId), "benchmarks");
}
/** `<agentDir>/snapshots`, Agent State version snapshots (doesn't exist when unconfigured). */
diff --git a/packages/core/test/example-benchmark.test.ts b/packages/core/test/example-benchmark.test.ts
index b5d3e825..6be7ab65 100644
--- a/packages/core/test/example-benchmark.test.ts
+++ b/packages/core/test/example-benchmark.test.ts
@@ -1,8 +1,10 @@
/**
* Example Benchmark provisioning tests:
- * default_agent initialization pre-seeds benchmarks/example-benchmark/ (a parseable config,
- * runs=2, a scoreboard with three self-consistent evaluations); an ordinary Agent gets none;
- * provisioning is skipped idempotently when benchmarks/ already exists.
+ * default_agent initialization pre-seeds the Project-level benchmarks/example-benchmark/ (a
+ * parseable config, runs=2, a scoreboard with three self-consistent evaluations labelled with
+ * the Agent they tested); an ordinary Agent's creation seeds nothing; the decision is made on
+ * the benchmarks/ DIRECTORY, so a Project that already holds Benchmarks of its own gets no
+ * example, and loading default_agent re-creates one only when that directory is gone.
*/
import fs from "node:fs/promises";
import os from "node:os";
@@ -56,6 +58,7 @@ interface CaseScore extends Omit<RunScore, "session_id"> {
}
interface Evaluation extends Omit<CaseScore, "case" | "runs"> {
time: string;
+ agent_id: string;
version: number;
provider: string;
model_id: string;
@@ -68,18 +71,16 @@ interface Evaluation extends Omit<CaseScore, "case" | "runs"> {
describe("example benchmark provisioning", () => {
it("default_agent init creates a parseable example benchmark (config + scoreboard + cases)", async () => {
await loadAgentState({ init: {} });
- const dir = path.join(
- benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID),
- EXAMPLE_BENCHMARK_ID,
- );
+ const dir = path.join(benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID), EXAMPLE_BENCHMARK_ID);
- // benchmark_config.toml: title/description/runs=2; contains no model reference (the model
- // is recorded on each evaluation instead).
+ // benchmark_config.toml: title/description/runs=2/status=published; contains no model
+ // reference (the model is recorded on each evaluation instead).
const config = parseToml(await fs.readFile(path.join(dir, "benchmark_config.toml"), "utf8"));
expect(config.title).toBe("Example Benchmark");
expect(String(config.description)).toContain("built-in example");
expect(String(config.description)).toContain("Replace it with your own");
expect(Number(config.runs)).toBe(2);
+ expect(config.status).toBe("published");
expect(config).not.toHaveProperty("provider");
expect(config).not.toHaveProperty("model_id");
@@ -106,14 +107,16 @@ describe("example benchmark provisioning", () => {
const scores = scoreboard.evaluations.map((e) => e.score);
expect(scores[0]!).toBeLessThan(scores[1]!);
expect(scores[1]!).toBeLessThan(scores[2]!);
- // Each evaluation carries the actual model used for that run (as a pair) and a summary
- // title; the example consistently uses deepseek-v4-pro.
+ // Each evaluation carries the Agent it tested, the actual model used for that run (as a
+ // pair) and a summary title; the example consistently evaluates default_agent on
+ // deepseek-v4-pro.
expect(scoreboard.evaluations.map((e) => e.model_id)).toEqual([
"deepseek-v4-pro",
"deepseek-v4-pro",
"deepseek-v4-pro",
]);
for (const e of scoreboard.evaluations) {
+ expect(e.agent_id).toBe(DEFAULT_AGENT_ID);
expect(e.provider).toBe("deepseek");
expect(e.thinking_level).toBe("medium");
expect(e.summary_title.length).toBeGreaterThan(0);
@@ -155,24 +158,43 @@ describe("example benchmark provisioning", () => {
}
});
- it("provisionProjectAgents also seeds the example benchmark for default_agent", async () => {
+ it("provisionProjectAgents seeds the example benchmark at the Project level", async () => {
await provisionProjectAgents({ root: tmpRoot, projectId: "proj_x" });
- expect(
- await exists(
- path.join(benchmarksDir(tmpRoot, "proj_x", DEFAULT_AGENT_ID), EXAMPLE_BENCHMARK_ID),
- ),
- ).toBe(true);
+ expect(await exists(path.join(benchmarksDir(tmpRoot, "proj_x"), EXAMPLE_BENCHMARK_ID))).toBe(
+ true,
+ );
});
- it("does not create benchmarks for a non-default agent", async () => {
+ it("does not create benchmarks when a non-default agent is created", async () => {
await loadAgentState({ init: {}, agentId: "worker" });
- expect(await exists(benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, "worker"))).toBe(false);
+ expect(await exists(benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID))).toBe(false);
+ });
+
+ it("writes no example into a benchmarks/ directory that already holds a Benchmark", async () => {
+ const dir = benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID);
+ // The directory is the decision: a Project that already keeps Benchmarks of its own is not
+ // a Project's first day, so the example is not added beside them.
+ await fs.mkdir(path.join(dir, "swe-bench-v1"), { recursive: true });
+ await loadAgentState({ init: {} });
+ expect(await fs.readdir(dir)).toEqual(["swe-bench-v1"]);
+ });
+
+ it("loading default_agent re-creates the example when benchmarks/ is gone", async () => {
+ await loadAgentState({ init: {} });
+ const dir = benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID);
+ await fs.rm(dir, { recursive: true, force: true });
+ // The load path, not the init path: an existing Agent is only read, and a data root that
+ // predates this provisioning gets its example on that first load.
+ await loadAgentState();
+ expect(await exists(path.join(dir, EXAMPLE_BENCHMARK_ID, "benchmark_config.toml"))).toBe(true);
});
- it("skips provisioning when benchmarks/ already exists (idempotent, no clobber)", async () => {
- const dir = benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
- await fs.mkdir(dir, { recursive: true });
+ it("loading default_agent does not write the example back once it alone was deleted", async () => {
await loadAgentState({ init: {} });
+ const dir = benchmarksDir(tmpRoot, DEFAULT_PROJECT_ID);
+ await fs.rm(path.join(dir, EXAMPLE_BENCHMARK_ID), { recursive: true, force: true });
+ await loadAgentState();
+ // benchmarks/ is still there, so deleting the example is a decision that stands.
expect(await fs.readdir(dir)).toEqual([]);
});
});
diff --git a/packages/docs/content/architecture.en.md b/packages/docs/content/architecture.en.md
index 99bda88c..92e0fd7b 100644
--- a/packages/docs/content/architecture.en.md
+++ b/packages/docs/content/architecture.en.md
@@ -63,7 +63,7 @@ Item by item (design → owner → carrying file or module):
| Secrets | File layer | Vault: `agent_state/.vault.toml`; model credentials: `.project_config.toml` (both 0600) |
| The model table and the default model | File layer | `<project>/.project_config.toml` |
| Run history (the sole source of truth for recovery) | File layer | `traces/<date>/<session>_<index>.jsonl` — see [Sessions & Traces](/sessions-and-traces) |
-| Benchmark cases and scores | File layer | `benchmarks/<id>/` — see [Self-Improvement](/self-improvement) |
+| Benchmark cases and scores | File layer | `<project>/benchmarks/<id>/` — see [Self-Improvement](/self-improvement) |
| Snapshots | File layer | `snapshots/v<version>.tar.gz`; the export/import service lives in the Server |
| Streaming rendering, approval UI, charts | CLI / Web | `cli/src`, `web/src` (pure rendering, no engine logic) |
diff --git a/packages/docs/content/architecture.zh.md b/packages/docs/content/architecture.zh.md
index 922b3ccd..f9277cb5 100644
--- a/packages/docs/content/architecture.zh.md
+++ b/packages/docs/content/architecture.zh.md
@@ -63,7 +63,7 @@ PenguinHarness 是一个 pnpm monorepo,核心是 `@prismshadow/penguin-core`
| 密钥 | 文件层 | Vault:`agent_state/.vault.toml`;模型凭据:`.project_config.toml`(均 0600) |
| 模型表与默认模型 | 文件层 | `<project>/.project_config.toml` |
| 运行历史(恢复的唯一事实来源) | 文件层 | `traces/<date>/<session>_<index>.jsonl`,见 [Session 与 Trace](/sessions-and-traces) |
-| Benchmark 题库与评分 | 文件层 | `benchmarks/<id>/`,见[自我进化](/self-improvement) |
+| Benchmark 题库与评分 | 文件层 | `<project>/benchmarks/<id>/`,见[自我进化](/self-improvement) |
| 快照 | 文件层 | `snapshots/v<version>.tar.gz`;导入导出服务在 Server |
| 流式渲染、审批 UI、统计图表 | CLI / Web | `cli/src`、`web/src`(纯渲染,不含引擎逻辑) |
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 0e231740..781282ba 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -51,6 +51,7 @@ penguin run -m "long job" --background # returns the session id i
| `--approve <mode>` | Approval mode, see below (default `allow-all`). With `--session` it PATCHes the session's sticky mode |
| `--thinking <level>` | Pins the session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`) before the task; it applies from the session's next LLM request. Omitted, the session's pinned level (else the Agent config) applies |
| `--session <sessionId>` | Reuse an existing session (full id or unique fragment) instead of creating one; excludes `--workspace` and the model pair |
+| `--source <source>` | Marks the new session as created by a Benchmark evaluation; the only value is `benchmark`, and the Web App files such sessions under the Evaluations folder of the session list. Excludes `--session` |
| `--background` | POST the task and exit immediately, printing the session id (`{"sessionId"}` under `--json`); the task keeps running on the server — follow it with `penguin logs -f` |
| `--timeout <duration>` | Soft-yield wait budget (see Global conventions): at expiry, print what has rendered plus a dim still-running line with the session id (`{sessionId, status: "running", text}` under `--json`) and exit 0 — the task is not aborted. `--timeout 0` returns right after the POST (`{sessionId, status: "running"}` under `--json`, no `text`). Excludes `--background` |
| `--goal [budget]` | Goal mode: the message is the objective and the server loops until a terminal state; the optional value is a token budget (e.g. `500k`) |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index e5d26808..5908b19f 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -51,6 +51,7 @@ penguin run -m "长任务" --background # 立即返回 session id
| `--approve <mode>` | 审批模式,见下文(缺省 `allow-all`)。与 `--session` 同用时 PATCH 该会话的粘性模式 |
| `--thinking <level>` | 发起任务前把会话的思考等级钉为 `low` / `medium` / `high` / `xhigh` / `max`,自会话的下一次 LLM 请求起生效。省略时按会话钉定值(否则 Agent 配置)生效 |
| `--session <sessionId>` | 复用既有 Session(完整 id 或唯一片段),不再新建;不能与 `--workspace` 及模型对同用 |
+| `--source <source>` | 把新建会话标记为 Benchmark 评估创建;唯一取值为 `benchmark`,Web App 会把这类会话归入会话列表的「评估任务」子夹。不能与 `--session` 同用 |
| `--background` | 提交任务后立即退出并打印 session id(`--json` 下为 `{"sessionId"}`);任务在服务端继续运行,可用 `penguin logs -f` 跟随 |
| `--timeout <duration>` | 软让出等待预算(见「全局约定」):到时打印已渲染内容与一行暗色「仍在运行」提示(含 session id;`--json` 下为 `{sessionId, status: "running", text}`)并以 0 退出——任务不被中止。`--timeout 0` 在 POST 后立即返回(`--json` 下为 `{sessionId, status: "running"}`,无 `text`)。不能与 `--background` 同用 |
| `--goal [budget]` | 目标模式:消息即目标,服务端循环直至终态;可选值为 token 预算(如 `500k`) |
diff --git a/packages/docs/content/self-improvement.en.md b/packages/docs/content/self-improvement.en.md
index 98d11509..06f422a1 100644
--- a/packages/docs/content/self-improvement.en.md
+++ b/packages/docs/content/self-improvement.en.md
@@ -14,7 +14,7 @@ Self-improvement in PenguinHarness uses Skills to orchestrate the ordinary Agent
| Evaluator | Leaf worker created through `run_subagent`; runs and scores one Benchmark Case run |
| Optimizer | New top-level Agent that directly follows `agent-optimization` |
-The Builder and Optimizer directly follow their Skills in their own top-level Sessions. Evaluators are created through `run_subagent`; each follows `agent-evaluation` and uses the Penguin CLI to launch the specified Target Agent in an isolated Workspace identified by an absolute path. The Penguin CLI launches the Target Agent for the requested Case run.
+The Builder and Optimizer directly follow their Skills in their own top-level Sessions. Evaluators are created through `run_subagent`; each follows `agent-evaluation` and uses the Penguin CLI to launch the specified Target Agent in an isolated Workspace identified by an absolute path. The Penguin CLI launches the Target Agent for the requested Case run. The launch passes `--source benchmark`, so every Test Session lands in the Evaluations folder of the Web App's session list instead of the Test Agent's active conversations.
## Two independent steps
@@ -38,13 +38,17 @@ Invalid evaluations and correction reruns do not count toward the round limit. O
Every accepted Candidate is appended to and verified in the Scoreboard immediately. A strictly higher Evaluation score decides acceptance; the first comparison directly compares the Candidate's multi-Run average with the Formal Baseline's one-Run score without backfilling the Baseline. Whether the predicted Case behavior changed is reported separately so unrelated single-run variation is not presented as causal evidence. Agent optimization requires a complete Formal Baseline in the Scoreboard — without one there is no improvement to compare against.
+## From the Evaluation Center
+
+The Web App's Evaluation Center starts the same two Sessions without a hand-written prompt. **Create with AI** takes the Test Agent and a description and prefills the `benchmark-design` request — agent id, a desired baseline score, a pilot-iteration limit — into a new conversation with the Project's default agent; **Create manually** writes a Benchmark from a form in the layout below, ready for evaluation, and asks for no owning Agent. **Use** opens one dialog with two tabs: **Evaluate** prefills the `agent-evaluation` request — Test Agent picked in the form, Benchmark id, runs per case — into a new conversation with the evaluator agent of your choice, and **Optimize** prefills the `agent-optimization` request — the same Test Agent and Benchmark id plus round limit and target score — into one with the optimizer agent. Every entry only prefills: sending is the user's decision in that conversation. The evaluation runtime is never chosen there: an evaluation takes the Test Agent's own configured model and thinking level, and the Optimizer reuses the pair and thinking level the baseline recorded.
+
## Benchmark storage
-Benchmarks are stored per Agent under `benchmarks/<id>/`:
+Benchmarks belong to the Project, stored in `<root>/<project>/benchmarks/<id>/`, a sibling of `agents/`. A Benchmark and an Agent are peers rather than one owning the other: a Benchmark can evaluate several Agents and an Agent can be evaluated by several Benchmarks, so `benchmark_config.toml` names no Agent — the Agent under test is recorded on each evaluation instead.
```text
-benchmarks/<id>/
-├── benchmark_config.toml # Benchmark configuration (Builder runs is fixed at 1)
+<project>/benchmarks/<id>/
+├── benchmark_config.toml # Benchmark configuration: title, description, runs (Builder runs is fixed at 1), status
├── <case-id>/
│ ├── statement/ # the task given to the Target Agent
│ └── rubric/ # private scoring rubric, isolated from the Target Agent
@@ -53,8 +57,13 @@ benchmarks/<id>/
The separation of `rubric/` from `statement/` is deliberate: the Target Agent sees only the task statement and never touches the scoring rubric.
+`benchmark_config.toml` is what makes a directory a Benchmark: a directory under `benchmarks/` without one is not listed. Deleting a Benchmark while an evaluation is still running leaves such a directory behind, because the running evaluation keeps writing to the paths it was deleted from. A Benchmark that has simply never been evaluated still has its config and is listed as usual; a leftover directory is safe to delete by hand.
+
+`status` says whether the Benchmark is finished: `draft` while `benchmark-design` is still writing its cases and calibrating their difficulty, which the Web App masks — no Use, no detail — `published` once the Formal Baseline is recorded, and `failed` once `benchmark-design` reports `calibration_failed`, meaning no valid Pilot result could be frozen. A failed Benchmark is unusable: the Web App masks it as a failed creation and asks the user to delete it and create it again. A Benchmark created by hand and the built-in example are published from the start. A config without the field, or with any value other than `draft` or `failed`, reads as published.
+
Each evaluation record in `scoreboard.yaml` is timestamped and carries:
+- `agent_id`, the Agent that round evaluated. Together with `model_id` and `thinking_level` it forms the record's **label**: the trend chart plots time against score and draws one series per label, and only scores under the same label are comparable. The Agent State `version` is not part of it — successive versions of one Agent on one runtime are the trend the chart exists to show, so they share a line and each point names its version on hover. A record written before evaluations carried an Agent reads as unlabelled and falls into the chart's grey series;
- the evaluation runtime: a user-specified `(provider, model_id)` pair takes priority, otherwise the pair is inherited from the Builder Session; `thinking_level` is read from the Target Agent config and does not depend on Trace metadata;
- `summary_title` and `summary` (the round's conclusion and the hypothesis for the next one);
- Score, cost, and duration averages written by the model — Case-level values average Runs and Evaluation-level values average Cases; Run cost preserves its recorded precision, cost averages ignore `null` inputs and remain `null` only when every contributing cost is unknown; Score uses two decimals, cost averages use six decimals, and `duration_ms` is an integer;
@@ -62,7 +71,7 @@ Each evaluation record in `scoreboard.yaml` is timestamped and carries:
Every Run and every Case has a fixed maximum Score of 100, so Scoreboard entries do not carry `max_score`. The server and Web UI trust the stored aggregate values and do not recompute or cross-check them. Old Scoreboard formats are not migrated or backfilled.
-The built-in `default_agent` ships with an example Benchmark (`packages/core/src/state/example-benchmark.ts`) so the evaluation pages have data out of the box; the whole directory can be deleted or replaced at any time.
+Initializing a Project's `default_agent` seeds an example Benchmark at the Project level (`packages/core/src/state/example-benchmark.ts`), its three sample evaluations labelled `agent_id: default_agent`, so the evaluation pages have data out of the box; the whole directory can be deleted or replaced at any time.
## Snapshots and versions
@@ -72,7 +81,7 @@ Before each optimization round, the Agent State is packed into `snapshots/v<vers
- Every Evaluator run is an ordinary Session with a full Trace;
- Scoreboard records link back to those Sessions via `session_id`; see [Sessions & Traces](/sessions-and-traces);
-- The Web evaluation pages are read-only views of these files; the trend chart shows Score only, while the detail table shows model ID and thinking level as separate columns. See the [Web App Guide](/web-app).
+- The Web evaluation pages are read-only views of these files; the trend chart shows Score only, while the detail table shows the Agent under test, model ID and thinking level as separate columns. See the [Web App Guide](/web-app).
Scores are not black-box output: every number can be traced back to the run that produced it.
diff --git a/packages/docs/content/self-improvement.zh.md b/packages/docs/content/self-improvement.zh.md
index 60784b1d..f3a0a2c4 100644
--- a/packages/docs/content/self-improvement.zh.md
+++ b/packages/docs/content/self-improvement.zh.md
@@ -14,7 +14,7 @@ PenguinHarness 中的自我进化由 Skill 编排普通的 Agent 机制完成:
| Evaluator | `run_subagent` 创建的叶子 Worker,执行并评分一次 Benchmark Case 运行 |
| Optimizer | 新顶层 Agent,直接执行 `agent-optimization` |
-Builder 和 Optimizer 在各自的顶层 Session 中直接遵循对应 Skill。Evaluator 通过 `run_subagent` 创建,遵循 `agent-evaluation`,并通过 Penguin CLI 在绝对路径的隔离 Workspace 中启动指定的 Target Agent。Penguin CLI 在每次请求中启动 Target Agent 完成对应的 Case Run。
+Builder 和 Optimizer 在各自的顶层 Session 中直接遵循对应 Skill。Evaluator 通过 `run_subagent` 创建,遵循 `agent-evaluation`,并通过 Penguin CLI 在绝对路径的隔离 Workspace 中启动指定的 Target Agent。Penguin CLI 在每次请求中启动 Target Agent 完成对应的 Case Run。启动时传入 `--source benchmark`,因此每个 Test Session 都会落到 Web App 会话列表的「评估任务」子夹,而不是留在 Test Agent 的活跃对话中。
## 两个独立步骤
@@ -38,13 +38,17 @@ Builder 和 Optimizer 在各自的顶层 Session 中直接遵循对应 Skill。E
每个 Accepted Candidate 立即写入并校验 Scoreboard。Evaluation 分数严格提高决定是否接受;第一次比较允许直接用 Candidate 的多 Run 平均分比较 Formal Baseline 的单 Run 分数,不为 Baseline 补跑。假设是否在预期 Case 上得到支持单独报告,避免把单次运行中的无关波动解释为改动因果。Agent 优化要求 Scoreboard 中已有完整 Formal Baseline——没有基线,就没有可比较的提升。
+## 从评估中心发起
+
+Web App 的评估中心不需要手写提示词就能启动同样的两个 Session。**用 AI 创建**选定被测 Agent 并描述需求后,把 `benchmark-design` 请求——Agent id、期望基线分、Pilot 迭代上限——预填进与 Project 默认 Agent 的新对话;**手动创建**则按下文的目录结构从表单写出一个 Benchmark,可直接评测,且不要求指定所属 Agent。**使用**打开一个含两个 tab 的弹窗:**评估**把 `agent-evaluation` 请求——在表单中选择的被测 Agent、Benchmark id、每题运行次数——预填进与所选执行评估 Agent 的新对话,**优化**把 `agent-optimization` 请求——同样的被测 Agent 与 Benchmark id,另加最多轮数与目标分数——预填进与所选优化 Agent 的新对话。这些入口都只做预填:发送由用户在对话里决定。评测 Runtime 从不在那里选择:评估取被测 Agent 当前配置的模型与思考等级,Optimizer 沿用基线记录的模型对与推理强度。
+
## Benchmark 存储
-Benchmark 按 Agent 存放在 `benchmarks/<id>/` 下:
+Benchmark 属于 Project,存放在与 `agents/` 平级的 `<root>/<project>/benchmarks/<id>/` 下。Benchmark 与 Agent 是平级关系而非从属:一个 Benchmark 可以评测多个 Agent,一个 Agent 也可以被多个 Benchmark 评测,因此 `benchmark_config.toml` 不记录任何 Agent——被测 Agent 记录在每条 evaluation 上。
```text
-benchmarks/<id>/
-├── benchmark_config.toml # Benchmark 配置(Builder 的 runs 固定为 1)
+<project>/benchmarks/<id>/
+├── benchmark_config.toml # Benchmark 配置:title、description、runs(Builder 的 runs 固定为 1)、status
├── <case-id>/
│ ├── statement/ # 交给 Target Agent 的任务描述
│ └── rubric/ # 私有评分标准,对 Target Agent 隔离
@@ -53,8 +57,13 @@ benchmarks/<id>/
`rubric/` 与 `statement/` 的隔离是刻意设计:Target Agent 只能看到题面,永远接触不到评分标准。
+`benchmark_config.toml` 是目录成为 Benchmark 的标志:`benchmarks/` 下缺少该文件的目录不会被列出。在评测运行期间删除 Benchmark 会留下这样的目录——正在运行的评测仍在向被删除的路径写入。从未评测过的 Benchmark 仍带有配置文件,照常列出;残留目录可以手工删除。
+
+`status` 表示这个 Benchmark 是否已经完成:`benchmark-design` 仍在出题与校准难度时为草稿 `draft`,Web App 对其遮罩——不能使用、也看不到详情;记录 Formal Baseline 后为发布 `published`;`benchmark-design` 报告 `calibration_failed`(没有任何可冻结的有效 Pilot 结果)时为失败 `failed`。失败的 Benchmark 不可用:Web App 同样遮罩,提示创建失败、请删除后重新创建。手动创建的 Benchmark 与内置示例一开始就是 `published`。没有该字段、或取值既不是 `draft` 也不是 `failed` 的配置,都按 `published` 读。
+
`scoreboard.yaml` 中的每条评测记录带时间戳,并记录:
+- `agent_id`,本轮评测的被测 Agent。它与 `model_id`、`thinking_level` 合成该条记录的**标签**:走势图以时间为横轴、分数为纵轴,按标签分系列,只有同一标签下的分数才可比。Agent State `version` 不进标签——同一被测 Agent 在同一 Runtime 下的历次版本正是走势图要显示的东西,因此它们连成一条线,版本号标在每个点的悬停提示里。评估记录写于 evaluation 尚未携带 Agent 之前时归为未标注,落在图表的灰色系列;
- 本轮 Runtime:用户显式指定的 `(provider, model_id)` 成对值优先,否则继承 Builder Session;`thinking_level` 从 Target Agent 配置读取,不依赖 Trace 元数据;
- `summary_title` 与 `summary`(本轮结论与下一轮假设);
- 由模型写入的 Score、成本与耗时平均值——Case 级对 Runs 求平均,Evaluation 级对 Cases 求平均;单次 Run 成本保留记录中的原始精度,成本平均值忽略 `null`,全部未知时才为 `null`;Score 保留两位小数,成本平均值保留六位小数,`duration_ms` 取整;
@@ -62,7 +71,7 @@ benchmarks/<id>/
每个 Run 和每个 Case 都固定满分 100,因此 Scoreboard 不再记录 `max_score`。服务端与 Web UI 直接信任已写入的聚合值,不重算、不交叉校验;旧 Scoreboard 不迁移、不回填。
-内置的 `default_agent` 预置了一个示例 Benchmark(`packages/core/src/state/example-benchmark.ts`),评测页面开箱即有数据;整个目录可随时删除或替换。
+初始化 Project 的 `default_agent` 时会在 Project 层级预置一个示例 Benchmark(`packages/core/src/state/example-benchmark.ts`),三条示例评估都标注 `agent_id: default_agent`,评测页面开箱即有数据;整个目录可随时删除或替换。
## Snapshot 与版本
@@ -72,7 +81,7 @@ benchmarks/<id>/
- 每次 Evaluator 运行都是一个普通的 Session,留有完整 Trace;
- scoreboard 记录通过 `session_id` 链接回这些 Session,见 [Session 与 Trace](/sessions-and-traces);
-- Web 的评测页面是这些文件的只读视图;折线图只展示 Score,明细表将模型 ID 与推理强度分列显示。见 [Web App 指南](/web-app)。
+- Web 的评测页面是这些文件的只读视图;折线图只展示 Score,明细表将被测 Agent、模型 ID 与推理强度分列显示。见 [Web App 指南](/web-app)。
分数不是黑盒输出:任何一个数字都可以回溯到产生它的那次运行。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index ec0cbc47..0ac2ca2e 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -228,7 +228,6 @@ The paths below omit the `/api/projects/:projectId` prefix.
| GET | `/api/plugins` (global) | The plugin library by category — every plugin with its skills' metadata and hook points (any logged-in user) |
| GET | `/api/plugins/:plugin/files` (global) | Everything one library plugin ships as text keyed by path — each skill's installable SKILL.md and reference files under `skills/<name>/`, the hook scripts under `hooks/` — for the plugin detail view's file browser (any logged-in user) |
| DELETE | /agents/:agentId/hooks/:name | Uninstall a hook package |
-| GET | /agents/:agentId/benchmarks | Benchmark scoring data (read-only) |
### Schedules
@@ -239,12 +238,25 @@ The paths below omit the `/api/projects/:projectId` prefix.
Schedule writes are owner-only. A task in new-Session mode carries `modelId` and `provider` together or not at all; the pair is checked against the Project's model table when the task is saved and again when the scheduler reconciles it.
+### Benchmarks
+
+Benchmarks hang off the Project, not off an Agent: one Benchmark evaluates as many Agents as it is pointed at, and each evaluation names the Agent it tested (`agentId`, `null` on a record that carries none). A summary's `agentIds` lists those Agents in first-seen order. The paths below again omit the `/api/projects/:projectId` prefix.
+
+| Method | Path | Description |
+| --- | --- | --- |
+| GET | /benchmarks | Benchmark scoring data — only directories holding a `benchmark_config.toml`; one without it (what a Benchmark deleted mid-evaluation leaves behind) is skipped; each entry carries `status` (`draft` while the Skill is still building it, `failed` when its calibration never finished, else `published`) |
+| POST | /benchmarks | Create a Benchmark by hand (owner only): `{ id, title, description?, runs?, cases: [{ id, title, statement, rubric }] }` → 201 `{ benchmark }`. The server writes `benchmark_config.toml` (with `status = "published"`), a `scoreboard.yaml` with `evaluations: []`, and each case's `statement/README.md` (the title as its heading) and `rubric/README.md`; ids follow the agent-id alphabet, case ids start with `CASE-`; 409 `benchmark_exists` when the directory is already there |
+| DELETE | /benchmarks/:benchmarkId | Remove a Benchmark directory whole — cases, config and scoreboard (owner only; 204, 404 when absent) |
+| GET | /benchmarks/:benchmarkId/cases | Case list of one Benchmark: id and the statement README's heading. Rubrics are never returned |
+| GET | /benchmarks/:benchmarkId/cases/:caseId/files | Browse one case's `statement/`; add `/rubric` before `/files` for the rubric side |
+| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | Read one file from that material (`?path=`, `?preview=1`, `?download=1`), with the same inline hardening as Workspace files |
+
### Session Creation and Directory Browsing
| Method | Path | Description |
| --- | --- | --- |
| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it |
-| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter |
+| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter; `source` accepts only `"benchmark"` (a Benchmark evaluation or optimization), since `subagent` and `schedule` are set by the server itself |
| GET | /dirs?path= | Server-side directory browser (backs the Workspace picker) |
On Session creation, `modelId` and `provider` are both-or-neither: send the complete pair to pick a model, or omit both to take the Project's default model — one without the other is a 400. The Workspace defaults to an auto-created temporary workspace, and the approval mode defaults to `allow-all`.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 7fb650b9..edf8a516 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -228,7 +228,6 @@ PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不
| GET | `/api/plugins`(全局) | 按分类列出插件库——每个插件带其 Skill 元数据与钩子点(任意已登录用户) |
| GET | `/api/plugins/:plugin/files`(全局) | 单个库内插件携带的全部文件,按路径键入的文本——各 Skill 的可安装 SKILL.md 与参考文件在 `skills/<name>/` 下,钩子脚本在 `hooks/` 下——供插件详情弹窗的文件浏览器使用(任意已登录用户) |
| DELETE | /agents/:agentId/hooks/:name | 卸载钩子包 |
-| GET | /agents/:agentId/benchmarks | Benchmark 评分数据(只读) |
### Schedule
@@ -239,12 +238,25 @@ PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不
Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与 `provider` 要么成对给出、要么都不给;该二元组会在任务保存时以及调度器对账时对照 Project 模型表校验。
+### Benchmark
+
+Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过哪些 Agent 由使用者决定,每条 evaluation 记录本轮被测的 Agent(`agentId`,记录中没有时为 `null`)。汇总项的 `agentIds` 按首次出现顺序列出这些 Agent。以下路径同样省略前缀 `/api/projects/:projectId`。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| GET | /benchmarks | Benchmark 评分数据——只返回带 `benchmark_config.toml` 的目录;缺少该文件的目录(评测运行期间删除 Benchmark 所留下的残留)会被跳过;每条带 `status`(技能仍在构建时为 `draft`,校准未能完成时为 `failed`,否则 `published`) |
+| POST | /benchmarks | 手动新建 Benchmark(仅 owner):`{ id, title, description?, runs?, cases: [{ id, title, statement, rubric }] }` → 201 `{ benchmark }`。服务端写入 `benchmark_config.toml`(其中 `status = "published"`)、内容为 `evaluations: []` 的 `scoreboard.yaml`,以及每道题的 `statement/README.md`(标题为其一级标题)与 `rubric/README.md`;id 沿用 Agent id 的字符规则,题目 id 以 `CASE-` 开头;目录已存在时返回 409 `benchmark_exists` |
+| DELETE | /benchmarks/:benchmarkId | 整目录删除一个 Benchmark——题目、配置与记分板(仅 owner;204,不存在返回 404) |
+| GET | /benchmarks/:benchmarkId/cases | 单个 Benchmark 的题目列表:题目 id 与题干 README 的一级标题;评分细则永不返回 |
+| GET | /benchmarks/:benchmarkId/cases/:caseId/files | 浏览某道题的 `statement/`;在 `/files` 前加 `/rubric` 即评分细则一侧 |
+| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | 读取该材料下的单个文件(`?path=`、`?preview=1`、`?download=1`),内联渲染的加固规则与 Workspace 文件一致 |
+
### Session 创建与目录浏览
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出 |
-| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤 |
+| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤;`source` 只接受 `"benchmark"`(Benchmark 评估或优化创建),`subagent` 与 `schedule` 由服务端自己写入 |
| GET | /dirs?path= | 服务器端目录浏览(Workspace 选择器数据源) |
创建 Session 时,`modelId` 与 `provider` 要么成对给出、要么都不给:给出完整二元组即指定模型,两个都省略则取 Project 默认模型,只给一个返回 400。Workspace 默认自动创建临时工作区,审批模式默认 `allow-all`。
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index f49e3590..2b13df61 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -27,6 +27,8 @@ The data root is the `PENGUIN_HOME` environment variable, defaulting to `~/.peng
```text
<root>/<project>/
├── .project_config.toml # Project-level models & credentials (hidden file, 0600)
+├── benchmarks/ # capability Benchmark cases and scores, one directory per
+│ # Benchmark — a peer of the Agents, evaluating any of them
└── agents/
└── <agent>/
├── agent_state/ # system_config.yaml, AGENTS.md, .vault.toml,
@@ -42,7 +44,6 @@ The data root is the `PENGUIN_HOME` environment variable, defaulting to `~/.peng
│ # installed once for any task; project dependencies stay
│ # in the project
├── workspaces/ # temporary Workspaces (tmp-<8hex>)
- ├── benchmarks/ # capability Benchmark cases and scores
└── snapshots/ # Agent State version snapshots
```
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index 34c88011..895474f8 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -27,6 +27,8 @@ PenguinHarness 的全部运行数据都落在本地文件系统:配置是可
```text
<root>/<project>/
├── .project_config.toml # Project 级模型与凭证(隐藏文件,0600)
+├── benchmarks/ # 能力评测题库与得分,每个 Benchmark 一个目录——与各 Agent
+│ # 平级,可评测其中任意一个
└── agents/
└── <agent>/
├── agent_state/ # system_config.yaml、AGENTS.md、.vault.toml、
@@ -40,7 +42,6 @@ PenguinHarness 的全部运行数据都落在本地文件系统:配置是可
│ # 按需创建——属于系统提示词约定而非代码创建的路径,使工具在任何
│ # 任务中都只装一次;项目自身的依赖仍留在项目内
├── workspaces/ # 临时 Workspace(tmp-<8hex>)
- ├── benchmarks/ # 能力评测题库与得分
└── snapshots/ # Agent State 版本快照
```
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index b3b085c2..57b3876b 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -50,7 +50,7 @@ A row's actions come at two levels:
Beside a row's title sit its status marks: a turning hourglass while the Session runs (a squeezing bar while it compacts), a green dot once a run finished that you have not looked at yet, and a small green activity trace while the Session still owns **background tasks** — commands running on past their yield window and background subagents mid-round. Its tooltip counts them ("2 background tasks"). The mark is independent of the others: an idle conversation whose dev server is still up keeps it, and it disappears the moment the last task ends, pushed live without a refresh.
-Pinning is offered only in the active list — the archived, subagent and scheduled folders leave it out — and a pinned conversation sorts to the top of its group. The choice is remembered per Project in the browser.
+Below a group's active rows stand its collapsed folders — Subagents, Scheduled, Evaluations and Archived — each loading its rows only once it is opened. **Evaluations** holds the conversations the Evaluation Center's **Use → Evaluate / Optimize** opens and the Test Sessions the evaluation Skill launches for every Case × Run, so an evaluation no longer floods the tested agent's list. A group with no active conversation of its own — only rows inside its folders, which is what an evaluation's per-case Workspaces and an agent that has only ever run evaluations look like — is collapsed by default and sorted after the other groups of its mode (pinned groups excepted), its header dimmed and counting the folded rows; open it once and it stays open for that Project. Pinning is offered only in the active list — the folders leave it out — and a pinned conversation sorts to the top of its group. The choice is remembered per Project in the browser.
An expanded folder reveals ten conversations at a time, the window the active list above it already uses: **Show N more chats** reveals ten more per click — rows already in memory first, and a page is fetched from the server only when they run short, so a fetch that returns more than a page leaves the extra rows in memory rather than on screen. As soon as the folder shows more than those first ten a **Show less** row stands beside the reveal row and folds it back to them; the reveal row itself disappears once the folder's whole share is on screen.
@@ -131,7 +131,7 @@ Scheduled tasks fire on a fixed period (minimum 5 minutes) and run only while th
## Plugin Library (/plugins)
-Browse the plugin library by category — skills and session hooks alike — install a plugin onto an Agent (its skills and hook package together), update installs the library has moved past, or quick-invoke a skill into a chat draft. Each card carries a semantic metadata line (`v<version> · updated N days ago · used by N agents`) and opens a detail Modal: the plugin's full description and the hook points its hook package answers at, then a file browser over everything it ships — a tree on the left with one collapsible group per skill (its SKILL.md and reference files) and one for the hook scripts, any number open at once, and a preview on the right that renders the selected file without leaving the summary or the tree.
+Browse the plugin library by category — skills and session hooks alike — install a plugin onto an Agent (its skills and hook package together), update installs the library has moved past, or quick-invoke a skill into a chat draft. Each card carries a semantic metadata line (`v<version> · updated N days ago · used by N agents`) and opens a detail Modal: the plugin's full description and the hook points its hook package answers at, then a file browser over everything it ships — the same component the Benchmark case dialog uses, with the Workspace files panel's tree on the left, one collapsible group per skill (its SKILL.md and reference files) and one for the hook scripts, any number open at once, and a preview on the right that renders the selected file without leaving the summary or the tree.
## Model Configuration (/models)
@@ -147,9 +147,20 @@ The header carries the two create buttons (owner only). **Create with AI** hands
- Two things a chart cannot draw. A bucket with **no rate** — an entity that made no request in it, or a bucket with no cache traffic — has its line carried across at the top of the axis so the stroke stays continuous; the hover table prints a dash there, never a percentage, and a real 0% (requests were made and all of them failed) still prints 0%. A bucket that recorded **nothing at all** is not plotted: every chart drops it and packs the rest left to right, so all four share one x axis that skips the quiet intervals and carries a break mark at each skip. Emptiness is judged per bucket, never per entity — an interval anything ran in stays, with the entities that were idle in it showing their zeros and dashes;
- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling). Its **Clear** (Project owner only) deletes the rows the current range and Agent filter lists — the trailing window or calendar preset the picker holds, named as such in the confirmation, or a custom range named by its dates; an admin's clear also takes the unattributed rows only admins see.
-## Benchmark (/benchmark)
+## Evaluation Center (/benchmark)
-Read-only scoreboards per Benchmark: switch the metric (score / cost / duration), drill into each Case's runs, and jump to the linked Session and Trace. Works together with the [Self-Improvement](/self-improvement) workflow.
+Every Benchmark of the Project, one card each — a Benchmark belongs to the Project, not to an agent, so the list is a flat one: the title and directory name, the description, the case and run counts, when it was last evaluated, the agents it has evaluated, a sparkline of the scoreboard, and the newest score with its change from the previous evaluation under the same label. Clicking a card, or **View**, enters that Benchmark's own page (`/benchmark/<benchmark>`) — the score chart over time, the evaluation table with per-case and per-run rows, and the case browser (the same file browser as the plugin detail: the Workspace panel's tree on the left — task materials and rubric as its two top-level folders, listed level by level — and a read-only preview on the right) — with a back button to the list. A Benchmark whose config says `status = "draft"` — the agent is still writing and calibrating it — is masked: the card dims under a notice that it is being built, **Use** and **View** are disabled, and its page shows the same notice in place of the cases and the chart; only the owner's delete icon stays live. One whose config says `status = "failed"` — its difficulty calibration never finished — is masked the same way, under a "creation failed" notice asking the user to delete the Benchmark and create it again. The mask lifts once the status is `published`. Under the title stand three separate step cards, one per step of the loop — **Create**, **Evaluate**, **Optimize** — each with its number, its title and one sentence saying where to do it: creating is the two buttons at the top right, and evaluating and optimizing are **Use** on a Benchmark followed by the matching tab. The conversations **Use** opens, and the Test Sessions an evaluation launches for every Case × Run, are filed under the session list's **Evaluations** folder.
+
+- Two buttons sit side by side at the top right, the same pair the agent's scheduled-tasks tab uses: the magic wand goes to AI, the hand to the form. **Create with AI** asks for the Test Agent and a description of the capability and scenarios; the prompt's fixed tail hands the `benchmark-design` Skill the agent id, a desired baseline score and a pilot-iteration limit, and asks for the baseline to be taken. **Create manually** is a form — title, id, description, runs per case, and one statement plus rubric per case, with no owning agent to pick — that the server writes to disk in the layout the Skills read (`POST …/benchmarks`, owner only).
+- **Use**, on a card and in the Benchmark page's header, opens one dialog with two tabs over a single exit. **Evaluate** puts an agent on the frozen cases: the tested agent (the one the newest evaluation tested, by default), the evaluator agent (with a warning when it lacks the `agent-evaluation` Skill), the model of the evaluation conversation (the Project settings' own model picker, preset to the Project's default model), runs per case, and an optional note. Its prompt asks for the full Case × runs matrix through self-spawned `agent-evaluation` subagents, requires every result's agent, model pair and thinking level to agree, and appends exactly one labelled evaluation to `scoreboard.yaml` — the tested agent and the Benchmark are left untouched. **Optimize** is the optimizer form: the optimizer agent (warned the same way), the **agent under test**, the model of the optimizer's own conversation (the same picker, preset the same way), runs per case, a round limit, a target score (ten above that agent's baseline by default) and an optional focus; an agent with no baseline here is told to take one on the Evaluate tab first. Both tabs preview the full prompt and both end the same way, at **Edit in a new conversation**: the prompt is prefilled into the composer and sending it is yours to decide. The evaluation runtime is never picked in this dialog — Evaluate takes the tested agent's own configured model and thinking level, and Optimize reuses what the baseline recorded.
+- The chart plots time against score and draws one series per **label** — agent id, model id and thinking level — so only comparable scores share a line; a record with no label falls into a grey series. The Agent State version is deliberately not part of the label: successive versions of one agent on the same model and thinking level stay on one line, which is exactly where an improvement is supposed to become visible, and each point names the version it tested in its hover bubble. The evaluation table keeps a version column of its own, and names the agent under test in another.
+- Clicking a row of the evaluation table opens that **evaluation in a dialog**, in the same shape as the case dialog: the series label with the tested agent and the version at the top, the Score, cost and duration under it, the evaluation's own summary (its title and its body shown separately), and the per-case table, whose rows expand to the raw result of every Run with the Session it ran in. A case named in there opens the case dialog on top of it.
+- Both dialogs end in an **Ask AI** button. It opens the prompt dialog with a question already in the box — why this evaluation came out as it did, or what this case tests — the same question leading the examples so it can be brought back after trying one of the three others, and a fixed tail carrying the facts on screen: for an evaluation, the Benchmark id and directory, the time, the series label, the version, the runtime, the total and per-case scores, every run's Session id and the summary; for a case, its `statement/README.md` and `rubric/README.md` paths and how the latest evaluation's runs scored it. The agent is asked to read those files and Traces and explain what it finds — the cases are frozen and the tested agent is not the subject of the question — and the exit is the same **Edit in a new conversation**.
+- A card's actions are **Use**, **View** and — for the owner — a delete icon, which removes the directory whole after a confirmation (`DELETE …/benchmarks/:id`). The Benchmark's own page names its directory, `benchmarks/<benchmark>`, beside the title, with a button that copies the path. `/benchmark?agentId=` narrows the list to the Benchmarks that have evaluated that agent.
+- **A Benchmark's cases are frozen once it exists.** Neither the Web App nor the server API can edit a statement or a rubric after creation: changing the questions would make the scores already on the scoreboard incomparable, so asking different questions means creating a new Benchmark. The calibration AI does while writing the cases happens before the baseline is taken, and is part of creating them.
+- Every Project carries the example Benchmark, `example-benchmark`, whenever the Project has no `benchmarks/` directory: it is provisioned when the Project's `default_agent` is initialized and again the first time that agent is loaded, so a data root older than the example gets one too. Deleting the example while `benchmarks/` remains — holding other Benchmarks, or nothing — is a decision that stands; removing the whole directory asks for the example back.
+
+Works together with the [Self-Improvement](/self-improvement) workflow.
## System Settings
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 8c117f6a..6b9a920d 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -50,7 +50,7 @@ penguin web
会话行标题旁是它的状态标记:Session 运行中是翻转的沙漏(压缩中是向中线合拢的压缩标),有一条你还没看过的回复时是一枚绿点,会话仍有**后台任务**——超过 yield 窗口继续运行的命令、正在跑一轮的后台子智能体——时另有一枚小小的绿色活动波形标记,悬停显示数量(「2 个后台任务」)。这枚标记与其他标记互不影响:dev server 还开着的空闲对话照样带着它,最后一项后台任务结束的那一刻它即消失,由服务端实时推送、无需刷新。
-置顶只在活跃列表里出现(已归档、子智能体与定时任务的折叠夹中没有这一项),置顶的会话排在所属分组的最前面,该状态按 Project 记在浏览器本地。
+每个分组的活跃会话之下是它的折叠夹——子智能体、定时任务、评估任务与已归档——各自展开时才加载其中的会话。**评估任务**收纳评估中心「使用 → 评估 / 优化」开出的对话,以及评估技能为每个 Case × Run 启动的被测会话,一次评估不会再把这些会话一股脑倒进被测 Agent 的列表。自己没有任何活跃会话、只有折叠夹里那些会话的分组——评估为每道题建的 Workspace、只跑过评估的 Agent 都是这样——默认折叠并排在同一分组方式的最后(置顶的分组除外),分组头变浅、计数为折叠会话数,点开一次后按 Project 记住。置顶只在活跃列表里出现(这些折叠夹中都没有这一项),置顶的会话排在所属分组的最前面,该状态按 Project 记在浏览器本地。
展开的折叠夹一次只显示十个对话,与上方活跃列表同一口径:**展开其余 N 个对话**每次再显示十个——先显示内存里已加载的行,不够时才向服务端再取一页,因此一次取回多于一页时,多出来的行留在内存里而不落到屏幕上。折叠夹显示的行数一超过最前十条,**收起**一行便与展开行并列出现,把它折回这十条;展开行本身则在本夹份额全部显示后消失。
@@ -130,7 +130,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,
## 插件库(/plugins)
-按分类浏览插件库——Skill 与会话钩子都在这里——把插件安装到指定 Agent(Skill 与钩子包一并装入)、更新落后于库的已装副本,或把某个 Skill 一键带入 Chat 草稿快速调用。每张卡片带一行语义化元信息(`v<版本> · N 天前更新 · N 个 Agent 在用`),点开即详情弹窗:插件完整描述与钩子包应答的钩子点,其下是它携带全部文件的浏览器——左侧文件树按 Skill 分组(各自的 SKILL.md 与参考文件)、钩子脚本单独一组,可同时展开任意多组;右侧预览所选文件,摘要与文件树始终在场。
+按分类浏览插件库——Skill 与会话钩子都在这里——把插件安装到指定 Agent(Skill 与钩子包一并装入)、更新落后于库的已装副本,或把某个 Skill 一键带入 Chat 草稿快速调用。每张卡片带一行语义化元信息(`v<版本> · N 天前更新 · N 个 Agent 在用`),点开即详情弹窗:插件完整描述与钩子包应答的钩子点,其下是它携带全部文件的浏览器,与 Benchmark 题目详情共用同一个文件浏览器组件(Workspace 文件面板同款文件树 + 只读预览)——左侧文件树按 Skill 分组(各自的 SKILL.md 与参考文件)、钩子脚本单独一组,可同时展开任意多组;右侧预览所选文件,摘要与文件树始终在场。
## 模型配置(/models)
@@ -146,9 +146,20 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,
- 有两种情况图画不出来。**没有比率**的桶——该对象在这个桶里一次请求都没发,或该桶没有缓存流量——折线沿坐标轴顶部横穿过去,只为让线保持连续;悬停表格在该处显示「—」而非百分比,而真正的 0%(发了请求且全部失败)仍然显示 0%。**什么都没记录**的桶一律不画:四张图都丢弃它、把其余的从左往右依次排开,因此共用同一条会跳过空闲区间的横轴,跳过处画有断轴标记。空与不空按桶判断、绝不按单个对象判断——只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列显示 0 与「—」;
- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。其**清空**(仅 Project owner)删除当前范围与 Agent 筛选所列的记录——确认框按档位名点出范围(如「近 7 天内」「最近一小时内」),自定义范围才写起止日期;管理员的清空同时带走只有管理员看得到的无归属记录。
-## Benchmark(/benchmark)
+## 评估中心(/benchmark)
-只读展示各 Benchmark 的评分板,可切换指标(得分 / 费用 / 耗时),下钻查看每个 Case 的多次运行结果,并跳转到关联的 Session 与 Trace。配合[自我进化](/self-improvement)工作流使用。
+Project 的全部 Benchmark 平铺列出,每个 Benchmark 一张卡片——Benchmark 属于 Project 而非某个 Agent,因此页面不按 Agent 分组:标题与目录名、描述、题数与每题运行次数、最近评估时间、评测过的 Agent、评分板的分数走势小折线,以及最新分数与相对同标签上一条评估的增减。点击卡片或**查看**进入这个 Benchmark 自己的页面(`/benchmark/<benchmark>`)——以时间为横轴的分数曲线、带单题与逐次运行行的评估明细表、题目浏览器(题目浏览器与插件详情共用同一个文件浏览器:左侧是 Workspace 文件面板同款的文件树——任务材料与评分标准是它的两个顶层目录,逐级懒加载——右侧是只读预览)——页头的返回按钮回到列表。配置里 `status = "draft"` 的 Benchmark(智能体仍在出题与校准)会被遮罩:卡片变淡并覆一层「构建中」提示,**使用**与**查看**禁用,其页面正文也以同样的提示代替题目与曲线;只有 owner 的删除图标仍可用。配置里 `status = "failed"` 的 Benchmark(难度校准未能完成)同样被遮罩,提示改为「创建失败」,请用户删除后重新创建。状态改为 `published` 后遮罩解除。标题下是三张独立的步骤卡片,一步一张——**出题**、**评估**、**优化**——各写序号、标题与一句话操作说明:出题用右上角的两个创建按钮,评估与优化都是在某个 Benchmark 上按**使用**再选对应的 tab。**使用**开出的对话,以及一次评估为每个 Case × Run 启动的被测会话,都归入会话列表的**评估任务**折叠夹。
+
+- 右上并排两个按钮,与智能体设置的定时任务页是同一对:魔法棒走 AI,手掌走表单。**用 AI 创建**要求选定被测 Agent 并描述要考察的能力与场景;提示词的固定尾部把 Agent id、期望基线分与 Pilot 迭代上限交给 `benchmark-design` 技能,并要求取得基线分。**手动创建**是一张表单——标题、id、描述、每题运行次数、每道题的题干与评分细则,不再选择所属 Agent——由服务端按技能读取的目录结构落盘(`POST …/benchmarks`,仅 owner)。
+- 卡片与 Benchmark 页面头部的**使用**打开同一个弹窗,顶部两个 tab 共用一个出口。**评估**把一个智能体放到已冻结的题目上:被测 Agent(缺省为最近一条评估的 Agent)、执行评估的 Agent(未装 `agent-evaluation` 技能时有提示)、评估会话使用的模型(与 Project 默认设置同一个模型选择器,缺省即当前 Project 的默认模型)、每题运行次数与可选说明。它的提示词要求经自调用的 `agent-evaluation` 子会话跑完整的 Case × runs 矩阵,校验每条结果的被测 Agent、成对模型与思考等级一致,并只向 `scoreboard.yaml` 追加一条带标签的评估——不动被测 Agent,也不动 Benchmark。**优化**是优化表单:执行优化的 Agent(同样会提示缺技能)、**被测 Agent**、优化会话自身使用的模型(同一个选择器、同样的缺省)、每题运行次数、最多轮数、目标分数(缺省比该 Agent 的基线高 10 分)与可选的优化重点;所选被测 Agent 在此还没有基线时,提示先到「评估」取得一条。两个 tab 都可折叠展开完整提示词,也都以同一个出口结束——**在新对话中编辑**:提示词预填进输入框,发不发送由你决定。评测 Runtime 不在这个弹窗里选——「评估」取被测 Agent 当前配置的模型与思考等级,「优化」沿用基线记录的那一套。
+- 曲线以时间为横轴、分数为纵轴,按**标签**分系列——标签为被测 Agent id、模型 id 与思考等级三者,只有同标签的分数才可比;没有标签的旧记录归入灰色系列。Agent State 版本号刻意不进标签:同一被测 Agent 在同一模型与思考等级下的历次版本连成一条线,进步正应该在这条线上看出来,版本号则标在每个点的悬停提示里。评估明细表自带一列版本号,另有一列写明被测 Agent。
+- 点击评估明细表的一行打开该次**评估详情弹窗**,形制与题目详情弹窗一致:顶部是系列标签、被测 Agent 与版本,其下为 Score、成本与耗时,再下是这次评估自己的说明(标题与正文分开展示)与单题得分表,题目行可展开逐次 run 的原始结果及其 Session id。在其中点开某道题,题目详情弹窗叠在它之上。
+- 两个弹窗的页脚都有**问 AI**:打开提示词弹窗,问题已经填好(这次评估为什么是这个结果 / 这道题考什么),示例按钮里排在最前的就是这个默认问题(试过别的示例后一键换回),后面另有三个可替换的示例,固定尾部把屏幕上的事实一并交出去——评估这一侧是 Benchmark id 与目录、评估时间、系列标签、版本、评测 Runtime、总分与逐题得分、逐次 run 的 Session id 与评估说明;题目这一侧是 `statement/README.md` 与 `rubric/README.md` 的路径,以及最近一次评估在这道题上的逐次结果。它只被要求读这些文件与 Trace 后作出解释:题目已冻结,被测 Agent 也不是这个问题的对象。出口同为**在新对话中编辑**。
+- 卡片上的动作是**使用**、**查看**,以及 owner 才有的删除图标——确认后整目录删除(`DELETE …/benchmarks/:id`)。Benchmark 自己的页面在标题旁写出它的目录 `benchmarks/<benchmark>`,并附一个复制路径的按钮。`/benchmark?agentId=` 把列表收窄为评测过该 Agent 的 Benchmark。
+- **Benchmark 创建即冻结题目。** Web App 与服务端接口都没有改题的入口:改动题干或评分细则会让记分板上已有的分数不再可比,因此要换题只能新建一个 Benchmark。AI 出题过程中的校准发生在基线确立之前,属于创建的一部分。
+- 每个 Project 都带示例 Benchmark `example-benchmark`,判定在于 Project 有没有 `benchmarks/` 目录:`default_agent` 初始化时预置,此后每次装载也会补——因此早于该示例的存量数据根在首次装载时同样得到它。`benchmarks/` 还在(无论里面有别的 Benchmark 还是空的)时删掉示例是一个会被尊重的决定;整个目录删除才会要回示例。
+
+配合[自我进化](/self-improvement)工作流使用。
## 系统设置
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index e46a54ed..f25eb46c 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -41,8 +41,8 @@ export type ApprovalMode = "allow-all" | "deny-all" | "read-only" | "always-ask"
/** Session run status: idle / Task in progress / compacting. */
export type SessionStatus = "idle" | "running" | "compacting";
-/** Session source marker (default = user-created): triggered by Schedule / registered as a subagent session. */
-export type SessionSource = "schedule" | "subagent";
+/** Session source marker (default = user-created): triggered by Schedule / registered as a subagent session / created by a Benchmark evaluation or optimization. */
+export type SessionSource = "schedule" | "subagent" | "benchmark";
// ---------------------------------------------------------------------------
// Authentication and users
@@ -1357,7 +1357,7 @@ export interface SessionBackgroundTasks {
}
/**
- * Session list category, the sidebar's four-way split applied server-side: archived wins
+ * Session list category, the sidebar's five-way split applied server-side: archived wins
* regardless of origin (archiving is an explicit user action), then the origin's bucket,
* and a Session with no (or an unknown) source is `active` — user-created rows.
*/
@@ -1433,6 +1433,13 @@ export interface SessionCreateRequest {
* serve every row regardless of client.
*/
client?: "web" | "cli";
+ /**
+ * Marks the Session as created by a Benchmark evaluation or optimization (the Evaluation
+ * Center's Use flows, and the Test Sessions agent-evaluation launches through the CLI). Only
+ * this value is accepted from a client: `subagent` and `schedule` are written by the server
+ * itself. The Web App files such Sessions into the Evaluations folder of the session list.
+ */
+ source?: "benchmark";
}
export interface SessionCreateResponse {
@@ -3215,7 +3222,7 @@ export interface AgentImportResponse {
}
// ---------------------------------------------------------------------------
-// Benchmark scoring (read-only display)
+// Benchmark scoring (display), manual creation and deletion
// ---------------------------------------------------------------------------
/** Raw result of a single run (a scoreboard per-case runs[] entry). */
@@ -3243,6 +3250,11 @@ export interface BenchmarkCaseScore {
export interface BenchmarkEvaluation {
/** Evaluation timestamp (ISO 8601). */
time: string;
+ /**
+ * Agent under test in this round (the `agent_id` field), part of the record's label; `null`
+ * when the record carries none, as a Benchmark evaluates whichever Agents it is pointed at.
+ */
+ agentId: string | null;
/** Evaluation summary title (a one-line conclusion; shown separately from the body summary; required when generating, tolerated as unset when displaying). */
summaryTitle?: string;
/** Evaluation summary body: how the score was derived, what optimizations were made to the Agent this round (required when generating, tolerated as unset when displaying). */
@@ -3264,6 +3276,12 @@ export interface BenchmarkEvaluation {
cases: BenchmarkCaseScore[];
}
+/**
+ * Whether the Skill that builds a Benchmark is done with it, and how it ended; see
+ * `BenchmarkSummary.status`.
+ */
+export type BenchmarkStatus = "draft" | "published" | "failed";
+
export interface BenchmarkSummary {
/** Directory name is the identifier (semantic naming, e.g. swe-bench-v1). */
id: string;
@@ -3272,10 +3290,26 @@ export interface BenchmarkSummary {
description?: string;
/** Number of runs per case (the `runs` field in benchmark_config.toml, ≥1; defaults to 1). */
runs?: number;
+ /**
+ * `draft` while the Skill that builds the Benchmark is still writing its cases and
+ * calibrating their difficulty — the Web App masks such a Benchmark; `published` once the
+ * Benchmark is frozen and its Formal Baseline recorded; `failed` when calibration ended
+ * without a Pilot result that could be frozen, which leaves the Benchmark unusable — the Web
+ * App masks it too and says it has to be deleted and created again. benchmark_config.toml is
+ * read literally: only `draft` is a draft and only `failed` is a failure, so a missing field,
+ * or any other value, reads as published.
+ */
+ status: BenchmarkStatus;
/** Case count (number of case subfolders). */
caseCount: number;
/** Time-ordered evaluation records (the evaluations[] in scoreboard.yaml). */
evaluations: BenchmarkEvaluation[];
+ /**
+ * Agents this Benchmark has evaluated: the distinct non-null `agentId`s of `evaluations`, in
+ * first-seen order. Empty while nothing has been evaluated — a Benchmark names no Agent of its
+ * own.
+ */
+ agentIds: string[];
}
export interface BenchmarksResponse {
@@ -3295,6 +3329,39 @@ export interface BenchmarkCasesResponse {
cases: BenchmarkCaseSummary[];
}
+/**
+ * POST /api/projects/:p/benchmarks (owner only): create a Benchmark by hand. The
+ * server writes the on-disk layout the evaluation Skills read — `benchmark_config.toml`, a
+ * `scoreboard.yaml` holding `evaluations: []`, and one `<case id>/` per case with
+ * `statement/README.md` and `rubric/README.md`. 409 `benchmark_exists` when the directory is
+ * already there; nothing is merged into an existing Benchmark.
+ */
+export interface BenchmarkCreateRequest {
+ /** Directory name, which is the identifier: letters, digits, `_` and `-` only. */
+ id: string;
+ title: string;
+ description?: string;
+ /** Runs per case for the optimization loop (integer ≥ 1; default 1). */
+ runs?: number;
+ /** At least one case; ids must be unique within the request. */
+ cases: BenchmarkCreateCase[];
+}
+
+export interface BenchmarkCreateCase {
+ /** Case directory name: `CASE-` followed by letters, digits, `_` and `-` (for example `CASE-001-excel-task`). */
+ id: string;
+ /** Written as the statement README's first heading, which the case list reads back as the case title. */
+ title: string;
+ /** Statement body (Markdown), written after that heading; the Target Agent sees only this side. */
+ statement: string;
+ /** Scoring rubric (Markdown, items totalling 100 points), written verbatim as `rubric/README.md`. */
+ rubric: string;
+}
+
+export interface BenchmarkCreateResponse {
+ benchmark: BenchmarkSummary;
+}
+
// ---------------------------------------------------------------------------
// Plugin library, and an Agent's installed skills and hooks
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index f633db87..e4382e4d 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -1283,11 +1283,11 @@ export function createApp(
app.route("/api/projects/:projectId/agents", agentsRoutes(deps));
app.route("/api/projects/:projectId/dirs", dirsRoutes(deps));
app.route("/api/projects/:projectId/dir-skills", directorySkillsRoutes(deps));
+ app.route("/api/projects/:projectId/benchmarks", benchmarksRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/config", agentConfigRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/vault", vaultRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/memory", memoryRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/schedules", scheduleRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/benchmarks", benchmarksRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/skills", agentSkillsRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/plugins", agentPluginsRoutes(deps));
app.route("/api/projects/:projectId/agents/:agentId/hooks", agentHooksRoutes(deps));
diff --git a/packages/server/src/db/repos/trace-index.ts b/packages/server/src/db/repos/trace-index.ts
index cd269449..f1375d65 100644
--- a/packages/server/src/db/repos/trace-index.ts
+++ b/packages/server/src/db/repos/trace-index.ts
@@ -5,6 +5,7 @@
*/
import type { DatabaseSync } from "node:sqlite";
import type { SessionSource } from "../../api/types.js";
+import { asSessionSource } from "../../runtime/session-sources.js";
/** One indexed Trace shard. */
export interface TraceFileRow {
@@ -48,7 +49,7 @@ function mapSession(r: Record<string, unknown>): TraceSessionRow {
projectId: r.project_id as string,
agentId: r.agent_id as string,
// Narrowed on read as well as write: junk in a hand-edited DB must not leak out as a source.
- source: source === "subagent" || source === "schedule" ? source : null,
+ source: asSessionSource(source) ?? null,
workspace: (r.workspace as string | null) ?? "",
title: (r.title as string | null) ?? null,
provider: (r.provider as string | null) ?? null,
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 4d4e9b84..fa6041ab 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -70,7 +70,7 @@ CREATE TABLE IF NOT EXISTS sessions (
fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted
last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill
created_at TEXT NOT NULL
-); -- the schedule/subagent SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)
+); -- the subagent/schedule/benchmark SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)
CREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);
CREATE TABLE IF NOT EXISTS usage_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -176,7 +176,7 @@ CREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at
session_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
- source TEXT, -- session_meta origin: 'subagent' | 'schedule' | NULL = user-created (or head not yet readable)
+ source TEXT, -- session_meta origin: 'subagent' | 'schedule' | 'benchmark' | NULL = user-created (or head not yet readable)
workspace TEXT NOT NULL DEFAULT '',
title TEXT, -- first-prompt fallback title (sessions.title always wins when present)
provider TEXT, -- model reference from session_meta (CLI adoption reads it from here; NULL = meta unreadable / legacy without provider)
diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.ts
index 7b00b9db..f8632232 100644
--- a/packages/server/src/http/routes/agent-traces.ts
+++ b/packages/server/src/http/routes/agent-traces.ts
@@ -43,6 +43,7 @@ const SESSION_CATEGORIES: readonly SessionCategory[] = [
"active",
"subagent",
"schedule",
+ "benchmark",
"archived",
];
diff --git a/packages/server/src/http/routes/benchmarks.ts b/packages/server/src/http/routes/benchmarks.ts
index 84eeb168..302a2095 100644
--- a/packages/server/src/http/routes/benchmarks.ts
+++ b/packages/server/src/http/routes/benchmarks.ts
@@ -1,34 +1,92 @@
/**
- * Benchmark scoring routes:
- * GET /api/projects/:p/agents/:a/benchmarks (any member, read-only)
- * GET /api/projects/:p/agents/:a/benchmarks/:benchmarkId/cases
- * GET /api/projects/:p/agents/:a/benchmarks/:benchmarkId/cases/:caseId/files
- * GET /api/projects/:p/agents/:a/benchmarks/:benchmarkId/cases/:caseId/files/content
- * GET /api/projects/:p/agents/:a/benchmarks/:benchmarkId/cases/:caseId/rubric/files
- * GET /api/projects/:p/agents/:a/benchmarks/:benchmarkId/cases/:caseId/rubric/files/content
- * Returns the Agent's Benchmark list (title/description from benchmark_config.toml)
+ * Benchmark routes, Project-level because a Benchmark is a peer of an Agent rather than
+ * something an Agent owns — which Agents it has evaluated comes from its scoreboard:
+ * GET /api/projects/:p/benchmarks (any member, read-only)
+ * POST /api/projects/:p/benchmarks (owner: create a Benchmark by hand)
+ * DELETE /api/projects/:p/benchmarks/:benchmarkId (owner: remove the directory whole)
+ * GET /api/projects/:p/benchmarks/:benchmarkId/cases
+ * GET /api/projects/:p/benchmarks/:benchmarkId/cases/:caseId/files
+ * GET /api/projects/:p/benchmarks/:benchmarkId/cases/:caseId/files/content
+ * GET /api/projects/:p/benchmarks/:benchmarkId/cases/:caseId/rubric/files
+ * GET /api/projects/:p/benchmarks/:benchmarkId/cases/:caseId/rubric/files/content
+ * Returns the Project's Benchmark list (title/description from benchmark_config.toml)
* along with the evaluations[] from scoreboard.yaml.
*/
import { Hono, type Context } from "hono";
+import { isValidId } from "@prismshadow/penguin-core";
import type { AppEnv } from "../../auth/middleware.js";
import type { AppDeps } from "../../app.js";
-import type { CaseMaterial } from "../../api/types.js";
-import { requireValidId } from "../validate.js";
+import type { BenchmarkCreateResponse, CaseMaterial } from "../../api/types.js";
+import type { BenchmarkCaseInput } from "../../services/benchmark-service.js";
+import {
+ badRequest,
+ optionalNumber,
+ optionalString,
+ readJson,
+ requireString,
+ requireValidId,
+} from "../validate.js";
const TEXT_PREVIEW_BYTES = 256 * 1024;
+/** Case directories carry the `CASE-` prefix the reader lists by; the rest is the shared id alphabet. */
+const CASE_ID_PATTERN = /^CASE-[A-Za-z0-9_-]+$/;
+const MAX_CASES = 100;
+const MAX_TITLE = 200;
+const MAX_DESCRIPTION = 2000;
+/** Statement and rubric bodies: generous, but a hand-written case is a page, not a corpus. */
+const MAX_BODY = 100_000;
+/**
+ * Runs per case. Every run is one evaluation of the Test Agent, so the count multiplies the cost
+ * of each optimization round; the Web App's Optimize dialog refuses anything beyond this, which a
+ * stored value has to stay within to remain usable.
+ */
+const MAX_RUNS = 1000;
+
+/** A required Markdown body: present, within the cap, and not blank. */
+function requireText(obj: Record<string, unknown>, key: string, maxLen: number, label: string) {
+ const v = requireString(obj, key, { maxLen, label });
+ if (v.trim() === "") throw badRequest(`${label} must not be blank.`);
+ return v;
+}
+
+/** The `cases` array of a create request: non-empty, capped, unique `CASE-…` ids, every text present. */
+function requireCases(body: Record<string, unknown>): BenchmarkCaseInput[] {
+ const raw = body.cases;
+ if (!Array.isArray(raw) || raw.length === 0) throw badRequest("cases must be a non-empty array.");
+ if (raw.length > MAX_CASES) throw badRequest(`cases must hold at most ${MAX_CASES} entries.`);
+ const seen = new Set<string>();
+ return raw.map((item, i) => {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
+ throw badRequest(`cases[${i}] must be an object.`);
+ }
+ const c = item as Record<string, unknown>;
+ const id = requireString(c, "id", { maxLen: 100, label: `cases[${i}].id` });
+ if (!CASE_ID_PATTERN.test(id)) {
+ throw badRequest(
+ `cases[${i}].id must start with "CASE-" and use only letters, digits, "_" and "-".`,
+ );
+ }
+ if (seen.has(id)) throw badRequest(`cases[${i}].id is a duplicate: ${id}`);
+ seen.add(id);
+ return {
+ id,
+ title: requireText(c, "title", MAX_TITLE, `cases[${i}].title`),
+ statement: requireText(c, "statement", MAX_BODY, `cases[${i}].statement`),
+ rubric: requireText(c, "rubric", MAX_BODY, `cases[${i}].rubric`),
+ };
+ });
+}
+
function listCaseFiles(deps: AppDeps, material: CaseMaterial) {
return async (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
const benchmarkId = requireValidId(c, "benchmarkId");
const caseId = requireValidId(c, "caseId");
deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- await deps.agentConfigService.requireExists(projectId, agentId);
return c.json(
await deps.benchmarks.listCaseFiles(
projectId,
- agentId,
benchmarkId,
caseId,
c.req.query("path") ?? "",
@@ -41,17 +99,14 @@ function listCaseFiles(deps: AppDeps, material: CaseMaterial) {
function readCaseFile(deps: AppDeps, material: CaseMaterial) {
return async (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
const benchmarkId = requireValidId(c, "benchmarkId");
const caseId = requireValidId(c, "caseId");
deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- await deps.agentConfigService.requireExists(projectId, agentId);
const download = c.req.query("download") === "1";
const boundedPreview = !download && c.req.query("preview") === "1";
const { data, fileName, contentType, scriptable, truncated } =
await deps.benchmarks.readCaseFile(
projectId,
- agentId,
benchmarkId,
caseId,
c.req.query("path") ?? "",
@@ -80,19 +135,48 @@ export function benchmarksRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- await deps.agentConfigService.requireExists(projectId, agentId);
- return c.json(await deps.benchmarks.list(projectId, agentId));
+ return c.json(await deps.benchmarks.list(projectId));
+ });
+
+ app.post("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ // Writing into the Project's benchmarks directory is Project management: owner only, like
+ // schedules and imports.
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ const body = await readJson(c);
+ const id = requireString(body, "id", { minLen: 1, maxLen: 100 });
+ if (!isValidId(id)) throw badRequest('id may only contain letters, digits, "_" and "-".');
+ const title = requireText(body, "title", MAX_TITLE, "title");
+ const description = optionalString(body, "description", { maxLen: MAX_DESCRIPTION });
+ const runs = optionalNumber(body, "runs", { integer: true }) ?? 1;
+ if (runs < 1 || runs > MAX_RUNS) {
+ throw badRequest(`runs must be an integer between 1 and ${MAX_RUNS}.`);
+ }
+ const cases = requireCases(body);
+ const benchmark = await deps.benchmarks.create(projectId, {
+ id,
+ title,
+ ...(description !== undefined ? { description } : {}),
+ runs,
+ cases,
+ });
+ return c.json({ benchmark } satisfies BenchmarkCreateResponse, 201);
+ });
+
+ app.delete("/:benchmarkId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const benchmarkId = requireValidId(c, "benchmarkId");
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ await deps.benchmarks.remove(projectId, benchmarkId);
+ return c.body(null, 204);
});
app.get("/:benchmarkId/cases", async (c) => {
const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
const benchmarkId = requireValidId(c, "benchmarkId");
deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- await deps.agentConfigService.requireExists(projectId, agentId);
- return c.json(await deps.benchmarks.listCases(projectId, agentId, benchmarkId));
+ return c.json(await deps.benchmarks.listCases(projectId, benchmarkId));
});
app.get("/:benchmarkId/cases/:caseId/files", listCaseFiles(deps, "statement"));
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index a9f30198..e2d27dd0 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -188,6 +188,7 @@ const SESSION_CATEGORIES: readonly SessionCategory[] = [
"active",
"subagent",
"schedule",
+ "benchmark",
"archived",
];
@@ -483,6 +484,9 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// Creating-client hint stored on the row ("cli" from the CLI; default "web").
// Informational provenance only — lists serve every row regardless.
const client = optionalEnum(body, "client", ["web", "cli"] as const);
+ // The only origin a client may set: `subagent` and `schedule` are written by the server
+ // itself, so anything but `benchmark` is a 400 rather than a silently ignored field.
+ const source = optionalEnum(body, "source", ["benchmark"] as const);
let workspace = optionalString(body, "workspace", { minLen: 1, label: "workspace" });
if (workspace !== undefined) {
// An explicitly specified Workspace must be an existing directory (never auto-created); reachability is determined by file permissions.
@@ -496,6 +500,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
...(workspace !== undefined ? { workspace } : {}),
...(approvalMode !== undefined ? { approvalMode } : {}),
...(client !== undefined ? { client } : {}),
+ ...(source !== undefined ? { source } : {}),
});
return c.json({ session } satisfies SessionCreateResponse, 201);
});
diff --git a/packages/server/src/runtime/session-sources.ts b/packages/server/src/runtime/session-sources.ts
index 3dbae53a..21490a4e 100644
--- a/packages/server/src/runtime/session-sources.ts
+++ b/packages/server/src/runtime/session-sources.ts
@@ -18,7 +18,7 @@ import type { SessionSource } from "../api/types.js";
* parties — is treated as absent rather than cast through.
*/
export function asSessionSource(v: unknown): SessionSource | undefined {
- return v === "schedule" || v === "subagent" ? v : undefined;
+ return v === "schedule" || v === "subagent" || v === "benchmark" ? v : undefined;
}
export class SessionSources {
diff --git a/packages/server/src/services/benchmark-service.ts b/packages/server/src/services/benchmark-service.ts
index 28c7cbe8..c571192a 100644
--- a/packages/server/src/services/benchmark-service.ts
+++ b/packages/server/src/services/benchmark-service.ts
@@ -1,11 +1,16 @@
/**
- * Benchmark score reading (read-only display): walks `benchmarks/<id>/`, reads
- * `benchmark_config.toml` (title, description, per-case run count `runs`) and
- * `scoreboard.yaml` (evaluations[], each case carries its model-written averages
- * and a runs array).
- * Content is created and refined by benchmark_builder; the server only reads it.
- * Missing or corrupt files always degrade gracefully (title falls back to the
- * directory name, scores come back empty) rather than throwing.
+ * Benchmark score reading: walks the Project's `benchmarks/<id>/`, reads
+ * `benchmark_config.toml` (title, description, per-case run count `runs`, and the build
+ * `status`: `draft` while the Benchmark is still being written, `failed` when its calibration
+ * never produced a result to freeze, `published` otherwise) and `scoreboard.yaml`
+ * (evaluations[], each carrying the Agent it tested, each case its model-written averages and
+ * a runs array).
+ * Content is normally created and refined by the benchmark-design Skill; the server also
+ * writes the same layout for a Benchmark created by hand (`create`) and removes a Benchmark
+ * directory whole (`remove`), and never touches a scoreboard.
+ * `benchmark_config.toml` is what makes a directory a Benchmark: `list` skips one without it.
+ * Files that are there but corrupt degrade gracefully (title falls back to the directory
+ * name, scores come back empty) rather than throwing.
*
* Case and Evaluation averages are authoritative file values. The server validates
* the current shape but never recomputes aggregates and does not migrate or backfill
@@ -14,8 +19,8 @@
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { parse as parseToml } from "smol-toml";
-import { parse as parseYaml } from "yaml";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import { benchmarksDir } from "@prismshadow/penguin-core";
import type {
BenchmarkCaseScore,
@@ -23,6 +28,7 @@ import type {
BenchmarkCasesResponse,
BenchmarkEvaluation,
BenchmarkRunScore,
+ BenchmarkStatus,
BenchmarkSummary,
BenchmarksResponse,
CaseMaterial,
@@ -37,6 +43,22 @@ import { HttpError } from "../http/errors.js";
const STATEMENT_TITLE_READ_BYTES = 64 * 1024;
+/** One case of a hand-made Benchmark; ids are validated by the route before they reach the filesystem. */
+export interface BenchmarkCaseInput {
+ id: string;
+ title: string;
+ statement: string;
+ rubric: string;
+}
+
+export interface BenchmarkCreateInput {
+ id: string;
+ title: string;
+ description?: string;
+ runs: number;
+ cases: BenchmarkCaseInput[];
+}
+
function asRecord(v: unknown): Record<string, unknown> {
return v !== null && typeof v === "object" && !Array.isArray(v)
? (v as Record<string, unknown>)
@@ -72,6 +94,15 @@ function stringOr(v: unknown): string | undefined {
return typeof v === "string" && v !== "" ? v : undefined;
}
+/**
+ * The Agent under test on one evaluation. Unlike the runtime fields it never invalidates a
+ * record: a scoreboard written before evaluations carried one still displays, unlabelled.
+ */
+function agentIdOr(v: unknown): string | null {
+ const value = typeof v === "string" ? v.trim() : "";
+ return value !== "" ? value : null;
+}
+
function isWithin(parent: string, child: string): boolean {
const relative = path.relative(parent, child);
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
@@ -142,6 +173,7 @@ function toCase(v: unknown): BenchmarkCaseScore | null {
function toEvaluation(v: unknown): BenchmarkEvaluation | null {
const r = asRecord(v);
const time = r.time instanceof Date ? r.time.toISOString() : r.time;
+ const agentId = agentIdOr(r.agent_id);
const score = scoreOr(r.score);
const cost = nullableCostOr(r.cost);
const durationMs = nonNegativeIntegerOr(r.duration_ms);
@@ -174,6 +206,7 @@ function toEvaluation(v: unknown): BenchmarkEvaluation | null {
const cases = parsedCases as BenchmarkCaseScore[];
return {
time,
+ agentId,
...(summaryTitle !== undefined ? { summaryTitle } : {}),
...(summary !== undefined ? { summary } : {}),
modelId,
@@ -193,8 +226,8 @@ export class BenchmarkService {
private readonly workspaceFiles: WorkspaceFilesService,
) {}
- async list(projectId: string, agentId: string): Promise<BenchmarksResponse> {
- const dir = benchmarksDir(this.root, projectId, agentId);
+ async list(projectId: string): Promise<BenchmarksResponse> {
+ const dir = benchmarksDir(this.root, projectId);
let items: Array<{ name: string; isDir: boolean }>;
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
@@ -204,17 +237,110 @@ export class BenchmarkService {
}
const benchmarks: BenchmarkSummary[] = [];
for (const item of items.filter((i) => i.isDir).sort((a, b) => a.name.localeCompare(b.name))) {
- benchmarks.push(await this.readBenchmark(path.join(dir, item.name), item.name));
+ const benchDir = path.join(dir, item.name);
+ // Only `benchmark_config.toml` makes a directory a Benchmark — it is the file the
+ // evaluation Skills require, and without it there is no title and no run count. A
+ // Benchmark deleted while an evaluation is still running comes back as the paths that
+ // run keeps writing, config not among them; that debris is not a Benchmark and is not
+ // listed. Absence of results is not absence of a Benchmark: one that has never run has
+ // its config and lists as usual.
+ try {
+ await fs.access(path.join(benchDir, "benchmark_config.toml"));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ continue;
+ }
+ benchmarks.push(await this.readBenchmark(benchDir, item.name));
}
return { benchmarks };
}
- async listCases(
- projectId: string,
- agentId: string,
- benchmarkId: string,
- ): Promise<BenchmarkCasesResponse> {
- const baseDir = benchmarksDir(this.root, projectId, agentId);
+ /**
+ * Creates `benchmarks/<id>/` in the layout the evaluation Skills read: `benchmark_config.toml`
+ * (title, description, runs, status), `scoreboard.yaml` with an empty evaluations list, and
+ * per case `statement/README.md` (`# <title>`, then the statement) and `rubric/README.md` (the
+ * rubric verbatim). An existing directory is a 409, never merged into: a Benchmark's scores stay
+ * comparable only while its cases are rewritten by nothing but the Skills. A half-written
+ * directory is removed again when a later write fails.
+ */
+ async create(projectId: string, input: BenchmarkCreateInput): Promise<BenchmarkSummary> {
+ const dir = benchmarksDir(this.root, projectId);
+ const benchDir = path.join(dir, input.id);
+ await fs.mkdir(dir, { recursive: true });
+ try {
+ // A non-recursive mkdir is the existence check: it fails atomically on a directory
+ // that is already there, so two creates of one id cannot both proceed.
+ await fs.mkdir(benchDir);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
+ throw new HttpError(409, "benchmark_exists", `Benchmark already exists: ${input.id}`);
+ }
+ throw error;
+ }
+ try {
+ const config = {
+ title: input.title,
+ ...(input.description !== undefined && input.description !== ""
+ ? { description: input.description }
+ : {}),
+ runs: input.runs,
+ // A Benchmark made by hand is complete the moment it is submitted: its cases are
+ // written and frozen, so nothing is left for a Skill to finish.
+ status: "published",
+ };
+ await fs.writeFile(
+ path.join(benchDir, "benchmark_config.toml"),
+ `${stringifyToml(config)}\n`,
+ "utf8",
+ );
+ await fs.writeFile(
+ path.join(benchDir, "scoreboard.yaml"),
+ stringifyYaml({ evaluations: [] }),
+ "utf8",
+ );
+ for (const item of input.cases) {
+ const caseDir = path.join(benchDir, item.id);
+ await fs.mkdir(path.join(caseDir, "statement"), { recursive: true });
+ await fs.mkdir(path.join(caseDir, "rubric"), { recursive: true });
+ await fs.writeFile(
+ path.join(caseDir, "statement", "README.md"),
+ `# ${item.title.trim()}\n\n${item.statement.trim()}\n`,
+ "utf8",
+ );
+ await fs.writeFile(
+ path.join(caseDir, "rubric", "README.md"),
+ `${item.rubric.trim()}\n`,
+ "utf8",
+ );
+ }
+ } catch (error) {
+ await fs.rm(benchDir, { recursive: true, force: true });
+ throw error;
+ }
+ return this.readBenchmark(benchDir, input.id);
+ }
+
+ /**
+ * Removes `benchmarks/<id>/` whole — cases, config and scoreboard. Only a real directory
+ * counts as existing: a symlink there is not followed, so nothing outside the Project's own
+ * benchmarks directory can be deleted through this route.
+ */
+ async remove(projectId: string, benchmarkId: string): Promise<void> {
+ const benchDir = path.join(benchmarksDir(this.root, projectId), benchmarkId);
+ let isDirectory = false;
+ try {
+ isDirectory = (await fs.lstat(benchDir)).isDirectory();
+ } catch {
+ // Missing: reported below as not found.
+ }
+ if (!isDirectory) {
+ throw new HttpError(404, "not_found", `Benchmark does not exist: ${benchmarkId}`);
+ }
+ await fs.rm(benchDir, { recursive: true, force: true });
+ }
+
+ async listCases(projectId: string, benchmarkId: string): Promise<BenchmarkCasesResponse> {
+ const baseDir = benchmarksDir(this.root, projectId);
const benchDir = path.join(baseDir, benchmarkId);
let entries: Array<{ name: string; isDirectory(): boolean }>;
let realBaseDir: string;
@@ -238,7 +364,6 @@ export class BenchmarkService {
try {
const statementDir = await this.caseMaterialRoot(
projectId,
- agentId,
benchmarkId,
entry.name,
"statement",
@@ -258,49 +383,34 @@ export class BenchmarkService {
async listCaseFiles(
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
rel: string,
material: CaseMaterial,
): Promise<WorkspaceFilesResponse> {
- const materialRoot = await this.caseMaterialRoot(
- projectId,
- agentId,
- benchmarkId,
- caseId,
- material,
- );
+ const materialRoot = await this.caseMaterialRoot(projectId, benchmarkId, caseId, material);
return this.workspaceFiles.list(materialRoot, rel);
}
async readCaseFile(
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
rel: string,
material: CaseMaterial,
options?: WorkspaceFileReadOptions,
): Promise<WorkspaceFileContent> {
- const materialRoot = await this.caseMaterialRoot(
- projectId,
- agentId,
- benchmarkId,
- caseId,
- material,
- );
+ const materialRoot = await this.caseMaterialRoot(projectId, benchmarkId, caseId, material);
return this.workspaceFiles.read(materialRoot, rel, options);
}
private async caseMaterialRoot(
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
material: CaseMaterial,
): Promise<string> {
- const benchDir = path.join(benchmarksDir(this.root, projectId, agentId), benchmarkId);
+ const benchDir = path.join(benchmarksDir(this.root, projectId), benchmarkId);
const caseDir = path.join(benchDir, caseId);
const materialRoot = path.join(caseDir, material);
try {
@@ -323,12 +433,13 @@ export class BenchmarkService {
}
private async readBenchmark(benchDir: string, id: string): Promise<BenchmarkSummary> {
- // benchmark_config.toml: title, description, and per-case run count (falls back
- // to defaults if corrupt). The model isn't part of the config — each evaluation
+ // benchmark_config.toml: title, description, per-case run count and build status (falls
+ // back to defaults if corrupt). The model isn't part of the config — each evaluation
// carries the Model actually used for that run.
let title = id;
let description: string | undefined;
let runs: number | undefined;
+ let status: BenchmarkStatus = "published";
try {
const config = asRecord(
parseToml(await fs.readFile(path.join(benchDir, "benchmark_config.toml"), "utf8")),
@@ -341,6 +452,12 @@ export class BenchmarkService {
if (configRuns !== undefined && Number.isInteger(configRuns) && configRuns >= 1) {
runs = configRuns;
}
+ // The two states that make a Benchmark unusable are literal: "draft" while it is still
+ // being built, "failed" when its calibration never produced a result to freeze. A config
+ // written before this field existed has none, and an unrecognized value is neither, so
+ // both read as published.
+ const raw = stringOr(config.status);
+ status = raw === "draft" ? "draft" : raw === "failed" ? "failed" : "published";
} catch {
// Missing or corrupt: title falls back to the directory name.
}
@@ -374,8 +491,18 @@ export class BenchmarkService {
title,
...(description !== undefined ? { description } : {}),
...(runs !== undefined ? { runs } : {}),
+ status,
caseCount,
evaluations,
+ // Which Agents this Benchmark has evaluated is a fact of its scoreboard, not of its
+ // config: first-seen order, so the list reads in the order the Agents were tested.
+ agentIds: [
+ ...new Set(
+ evaluations
+ .map((evaluation) => evaluation.agentId)
+ .filter((agentId): agentId is string => agentId !== null),
+ ),
+ ],
};
}
}
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 49d25dc1..e983880c 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -238,7 +238,13 @@ export class SessionService {
}
const want = paging ? paging.offset + paging.limit : Infinity;
- const counts: SessionCategoryCounts = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const counts: SessionCategoryCounts = {
+ active: 0,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ };
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
const workspaceLatest: Record<string, string> = {};
const matched: SessionRow[] = [];
@@ -251,6 +257,7 @@ export class SessionService {
active: 0,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
ws[cat] += 1;
@@ -328,8 +335,12 @@ export class SessionService {
provider?: string;
workspace?: string;
approvalMode?: ApprovalMode;
- /** Session source marker (schedule when triggered by a scheduled task; defaults to user-created). */
- source?: "schedule";
+ /**
+ * Session source marker: `schedule` when triggered by a scheduled task, `benchmark` when
+ * created by a Benchmark evaluation or optimization (the only value a client may send);
+ * defaults to user-created.
+ */
+ source?: "schedule" | "benchmark";
/**
* Creating-client hint stored on the index row (`POST .../sessions` body `client`):
* "cli" from the CLI, defaulting to "web". Purely informational — lists no longer
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index bcb84a08..3793cf5f 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -1501,7 +1501,7 @@ export class TraceService {
const category: SessionCategory =
(row?.archivedAt ?? null) !== null
? "archived"
- : source === "subagent" || source === "schedule"
+ : source === "subagent" || source === "schedule" || source === "benchmark"
? source
: "active";
return { category, workspace: row?.workspace ?? facts?.workspace ?? "" };
@@ -1533,7 +1533,13 @@ export class TraceService {
// Classify every group once; the same result drives the category filter, the
// counts AND the returned fields, so a row can never appear in a bucket its own
// `category` denies. Every Session is listed whichever client created it.
- const counts: SessionCategoryCounts = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const counts: SessionCategoryCounts = {
+ active: 0,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ };
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
const factsById = new Map<string, TraceSessionFacts>();
const visible: string[] = [];
@@ -1546,6 +1552,7 @@ export class TraceService {
active: 0,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
ws[facts.category] += 1;
diff --git a/packages/server/test/agent-trace-detail.test.ts b/packages/server/test/agent-trace-detail.test.ts
index 6fa6bfa6..3e89e29b 100644
--- a/packages/server/test/agent-trace-detail.test.ts
+++ b/packages/server/test/agent-trace-detail.test.ts
@@ -117,11 +117,18 @@ describe("agent-trace-detail", () => {
]);
expect(paged.sessions![0]!.category).toBe("active");
expect(paged.sessions![0]!.workspace).toBe("/tmp/w");
- expect(paged.counts).toEqual({ active: 1, subagent: 0, schedule: 0, archived: 0 });
+ expect(paged.counts).toEqual({
+ active: 1,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
expect(paged.workspaceCounts!["/tmp/w"]).toEqual({
active: 1,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
diff --git a/packages/server/test/benchmarks.test.ts b/packages/server/test/benchmarks.test.ts
index 7ee23851..5bc9d470 100644
--- a/packages/server/test/benchmarks.test.ts
+++ b/packages/server/test/benchmarks.test.ts
@@ -1,20 +1,25 @@
/**
- * Benchmark scoreboard read integration tests (read-only display): benchmark_config.toml title/description and runs
- * pass-through (falls back to directory name if missing), scoreboard.yaml v2's
- * evaluations[] (summary pass-through, model-written Case/Evaluation averages and per-case
- * runs arrays), rejection of legacy Scoreboard entries, case count, empty when
- * unconfigured, permissions (members can read,
- * outsiders get 404).
+ * Benchmark API integration tests: benchmark_config.toml title/description, runs and status
+ * pass-through (only a literal draft status locks a Benchmark; a directory without a config is
+ * not listed), scoreboard.yaml v2's
+ * evaluations[] (summary pass-through, the Agent each evaluation tested, model-written
+ * Case/Evaluation averages and per-case runs arrays), rejection of legacy Scoreboard entries,
+ * case count, empty when unconfigured, permissions (members can read, outsiders get 404), and
+ * the owner-only create (the on-disk layout the Skills read) and delete routes.
*
- * Tested with a plain Agent (no sample Benchmark pre-installed); default_agent's sample
- * Benchmark assertions live in builtin-agents.test.ts.
+ * Benchmarks are Project-level, so a new Project arrives with default_agent's sample
+ * Benchmark; setup deletes that one directory to isolate these cases, keeping `benchmarks/`
+ * itself. Its own assertions live in builtin-agents.test.ts.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { parse as parseToml } from "smol-toml";
import { benchmarksDir } from "@prismshadow/penguin-core";
import type {
BenchmarkCasesResponse,
+ BenchmarkCreateRequest,
+ BenchmarkCreateResponse,
BenchmarksResponse,
ProjectCreateResponse,
WorkspaceFilesResponse,
@@ -22,8 +27,6 @@ import type {
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const AGENT = "bench_agent";
-
describe("benchmarks api", () => {
let t: TestApp;
let owner: ReturnType<typeof apiClient>;
@@ -44,11 +47,14 @@ describe("benchmarks api", () => {
await owner.post("/api/projects", { projectId: "owner_a-bench", name: "Bench project" })
).json()) as ProjectCreateResponse;
projectId = created.project.projectId;
- // A plain Agent has no sample Benchmark pre-installed (only default_agent provides one).
- expect((await owner.post(`/api/projects/${projectId}/agents`, { agentId: AGENT })).status).toBe(
- 201,
- );
- base = `/api/projects/${projectId}/agents/${AGENT}/benchmarks`;
+ // Creating the Project seeded default_agent's sample Benchmark at the Project level; these
+ // cases start from an empty benchmarks directory. Only the example goes — the directory
+ // itself stays, because its absence is what asks for the example to be provisioned again.
+ await fs.rm(path.join(benchmarksDir(t.root, projectId), "example-benchmark"), {
+ recursive: true,
+ force: true,
+ });
+ base = `/api/projects/${projectId}/benchmarks`;
expect(
(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,
).toBe(201);
@@ -64,7 +70,7 @@ describe("benchmarks api", () => {
});
it("current scoreboard: model-written averages, runtime, and runs pass through", async () => {
- const dir = path.join(benchmarksDir(t.root, projectId, AGENT), "swe-bench-v2");
+ const dir = path.join(benchmarksDir(t.root, projectId), "swe-bench-v2");
await fs.mkdir(path.join(dir, "CASE-001-excel-task", "statement"), { recursive: true });
await fs.mkdir(path.join(dir, "CASE-001-excel-task", "statement", "assets"), {
recursive: true,
@@ -126,6 +132,7 @@ describe("benchmarks api", () => {
[
"evaluations:",
' - time: "2026-07-16T10:00:00Z"',
+ ' agent_id: "default_agent"',
" version: 3",
' provider: "deepseek"',
' model_id: "deepseek-v4-pro"',
@@ -164,6 +171,46 @@ describe("benchmarks api", () => {
" cost: null",
" duration_ms: 40000",
' session_id: "session-run-4"',
+ // A second Agent evaluated by the same Benchmark: the two are peers, and one
+ // Benchmark measures as many Agents as it is pointed at.
+ ' - time: "2026-07-17T10:00:00Z"',
+ ' agent_id: "report_writer"',
+ " version: 1",
+ ' provider: "deepseek"',
+ ' model_id: "deepseek-v4-pro"',
+ ' thinking_level: "medium"',
+ " score: 55",
+ " cost: null",
+ " duration_ms: 30000",
+ " cases:",
+ ' - case: "CASE-001-excel-task"',
+ " score: 55",
+ " cost: null",
+ " duration_ms: 30000",
+ " runs:",
+ " - score: 55",
+ " cost: null",
+ " duration_ms: 30000",
+ ' session_id: "session-run-5"',
+ // Recorded before evaluations named an Agent: still listed, just unlabelled.
+ ' - time: "2026-07-18T10:00:00Z"',
+ " version: 1",
+ ' provider: "deepseek"',
+ ' model_id: "deepseek-v4-pro"',
+ ' thinking_level: "medium"',
+ " score: 60",
+ " cost: null",
+ " duration_ms: 31000",
+ " cases:",
+ ' - case: "CASE-001-excel-task"',
+ " score: 60",
+ " cost: null",
+ " duration_ms: 31000",
+ " runs:",
+ " - score: 60",
+ " cost: null",
+ " duration_ms: 31000",
+ ' session_id: "session-run-6"',
].join("\n"),
"utf8",
);
@@ -175,13 +222,20 @@ describe("benchmarks api", () => {
title: "SWE Bench v2",
description: "Example",
runs: 2,
+ status: "published",
caseCount: 2,
});
// config carries no model reference (the model lives on each evaluation).
expect("modelId" in bench).toBe(false);
expect("provider" in bench).toBe(false);
+ // The Agents a Benchmark has evaluated come from its scoreboard, in first-seen order; an
+ // evaluation without an agent_id contributes none.
+ expect(bench.agentIds).toEqual(["default_agent", "report_writer"]);
+ expect(bench.evaluations[2]!.agentId).toBeNull();
const evaluation = bench.evaluations[0]!;
- // The evaluation entry carries this run's model (as a pair) and a summary title (curve series / title-body are displayed separately).
+ // The evaluation entry carries the Agent it tested, this run's model (as a pair) and a
+ // summary title (curve series / title-body are displayed separately).
+ expect(evaluation.agentId).toBe("default_agent");
expect(evaluation.provider).toBe("deepseek");
expect(evaluation.modelId).toBe("deepseek-v4-pro");
expect(evaluation.thinkingLevel).toBe("medium");
@@ -301,7 +355,7 @@ describe("benchmarks api", () => {
});
it("does not migrate or backfill legacy Scoreboard entries", async () => {
- const dir = path.join(benchmarksDir(t.root, projectId, AGENT), "swe-bench-v1");
+ const dir = path.join(benchmarksDir(t.root, projectId), "swe-bench-v1");
await fs.mkdir(path.join(dir, "CASE-001-excel-task", "statement"), { recursive: true });
await fs.writeFile(path.join(dir, "benchmark_config.toml"), `title = "SWE Bench v1"\n`, "utf8");
await fs.writeFile(
@@ -326,23 +380,210 @@ describe("benchmarks api", () => {
].join("\n"),
"utf8",
);
- // A benchmark with no config file: title falls back to the directory name, config runs field is absent by default.
- await fs.mkdir(path.join(benchmarksDir(t.root, projectId, AGENT), "empty-bench"), {
- recursive: true,
- });
-
const res = (await (await member.get(base)).json()) as BenchmarksResponse;
- expect(res.benchmarks.map((b) => b.id)).toEqual(["empty-bench", "swe-bench-v1"]);
- const bench = res.benchmarks[1]!;
+ expect(res.benchmarks.map((b) => b.id)).toEqual(["swe-bench-v1"]);
+ const bench = res.benchmarks[0]!;
expect(bench).toMatchObject({ title: "SWE Bench v1", caseCount: 1 });
expect("runs" in bench).toBe(false);
expect(bench.evaluations).toEqual([]);
+
+ expect((await outsider.get(base)).status).toBe(404);
+ });
+
+ it("lists a Benchmark that has never run, but not a directory without a config", async () => {
+ const dir = benchmarksDir(t.root, projectId);
+ // Deleted mid-evaluation: the run kept writing, so the directory is back with a case and
+ // a scoreboard but no config. Not a Benchmark — it must not reach the Evaluation Center.
+ await fs.mkdir(path.join(dir, "half-deleted", "CASE-001-excel-task", "statement"), {
+ recursive: true,
+ });
+ await fs.writeFile(
+ path.join(dir, "half-deleted", "CASE-001-excel-task", "statement", "README.md"),
+ "# Case 001: Excel cleanup\n",
+ "utf8",
+ );
+ await fs.writeFile(
+ path.join(dir, "half-deleted", "scoreboard.yaml"),
+ "evaluations: []\n",
+ "utf8",
+ );
+ // Created and never evaluated: a config, cases, and no scoreboard at all. Still a
+ // Benchmark — having no scores yet is not the same as being incomplete.
+ await fs.mkdir(path.join(dir, "never-run", "CASE-001-report", "statement"), {
+ recursive: true,
+ });
+ await fs.writeFile(
+ path.join(dir, "never-run", "benchmark_config.toml"),
+ 'title = "Report writing"\nruns = 2\n',
+ "utf8",
+ );
+
+ const res = (await (await member.get(base)).json()) as BenchmarksResponse;
+ expect(res.benchmarks.map((b) => b.id)).toEqual(["never-run"]);
expect(res.benchmarks[0]).toMatchObject({
- title: "empty-bench",
- caseCount: 0,
+ title: "Report writing",
+ runs: 2,
+ caseCount: 1,
evaluations: [],
});
+ });
- expect((await outsider.get(base)).status).toBe(404);
+ it("reads status from the config: literal draft and failed are themselves, everything else is published", async () => {
+ const dir = benchmarksDir(t.root, projectId);
+ // Still being written by benchmark-design: the Benchmark is not usable yet.
+ await fs.mkdir(path.join(dir, "draft-bench"), { recursive: true });
+ await fs.writeFile(
+ path.join(dir, "draft-bench", "benchmark_config.toml"),
+ 'title = "Draft"\nruns = 1\nstatus = "draft"\n',
+ "utf8",
+ );
+ // Calibration never produced a Pilot result to freeze: the Benchmark is unusable.
+ await fs.mkdir(path.join(dir, "failed-bench"), { recursive: true });
+ await fs.writeFile(
+ path.join(dir, "failed-bench", "benchmark_config.toml"),
+ 'title = "Failed"\nruns = 1\nstatus = "failed"\n',
+ "utf8",
+ );
+ // Written before the field existed: no status at all is not a lock.
+ await fs.mkdir(path.join(dir, "legacy-bench"), { recursive: true });
+ await fs.writeFile(
+ path.join(dir, "legacy-bench", "benchmark_config.toml"),
+ 'title = "Legacy"\nruns = 1\n',
+ "utf8",
+ );
+ // Neither is a value nobody defined.
+ await fs.mkdir(path.join(dir, "unknown-bench"), { recursive: true });
+ await fs.writeFile(
+ path.join(dir, "unknown-bench", "benchmark_config.toml"),
+ 'title = "Unknown"\nruns = 1\nstatus = "someday"\n',
+ "utf8",
+ );
+
+ const res = (await (await member.get(base)).json()) as BenchmarksResponse;
+ expect(res.benchmarks.map((b) => [b.id, b.status])).toEqual([
+ ["draft-bench", "draft"],
+ ["failed-bench", "failed"],
+ ["legacy-bench", "published"],
+ ["unknown-bench", "published"],
+ ]);
+ });
+
+ /** A well-formed create request; the tests below vary one field at a time. */
+ const createBody: BenchmarkCreateRequest = {
+ id: "report-writing-v1",
+ title: "Report writing",
+ description: "Hard cases for the report writer",
+ runs: 2,
+ cases: [
+ {
+ id: "CASE-001-contradictions",
+ title: "Contradicting sources",
+ statement: "Write a report from the two briefs in this Workspace.\n",
+ rubric: "- 60 pts: names the contradiction.\n- 40 pts: picks the dated source.\n",
+ },
+ {
+ id: "CASE-002-format",
+ title: "Strict format",
+ statement: "Follow the template exactly.",
+ rubric: "- 100 pts: every template section present.",
+ },
+ ],
+ };
+
+ it("owner creates a Benchmark by hand and the server writes the Skill layout", async () => {
+ const res = await owner.post(base, createBody);
+ expect(res.status).toBe(201);
+ const { benchmark } = (await res.json()) as BenchmarkCreateResponse;
+ expect(benchmark).toEqual({
+ id: "report-writing-v1",
+ title: "Report writing",
+ description: "Hard cases for the report writer",
+ runs: 2,
+ status: "published",
+ caseCount: 2,
+ evaluations: [],
+ // A Benchmark names no Agent of its own: it has evaluated none until it is run.
+ agentIds: [],
+ });
+
+ const dir = path.join(benchmarksDir(t.root, projectId), "report-writing-v1");
+ expect(parseToml(await fs.readFile(path.join(dir, "benchmark_config.toml"), "utf8"))).toEqual({
+ title: "Report writing",
+ description: "Hard cases for the report writer",
+ runs: 2,
+ status: "published",
+ });
+ expect(await fs.readFile(path.join(dir, "scoreboard.yaml"), "utf8")).toBe("evaluations: []\n");
+ // The statement README opens with the title as its heading (what the case list reads
+ // back); the rubric is written verbatim, trimmed to one trailing newline.
+ expect(
+ await fs.readFile(
+ path.join(dir, "CASE-001-contradictions", "statement", "README.md"),
+ "utf8",
+ ),
+ ).toBe("# Contradicting sources\n\nWrite a report from the two briefs in this Workspace.\n");
+ expect(
+ await fs.readFile(path.join(dir, "CASE-001-contradictions", "rubric", "README.md"), "utf8"),
+ ).toBe("- 60 pts: names the contradiction.\n- 40 pts: picks the dated source.\n");
+
+ const list = (await (await member.get(base)).json()) as BenchmarksResponse;
+ expect(list.benchmarks.map((b) => b.id)).toEqual(["report-writing-v1"]);
+ const cases = (await (
+ await member.get(`${base}/report-writing-v1/cases`)
+ ).json()) as BenchmarkCasesResponse;
+ expect(cases.cases).toEqual([
+ { id: "CASE-001-contradictions", title: "Contradicting sources" },
+ { id: "CASE-002-format", title: "Strict format" },
+ ]);
+
+ // The same id again is a conflict, and the first Benchmark is left as it was.
+ const again = await owner.post(base, { ...createBody, title: "Overwrite attempt" });
+ expect(again.status).toBe(409);
+ expect(((await again.json()) as { error: { code: string } }).error.code).toBe(
+ "benchmark_exists",
+ );
+ expect(
+ parseToml(await fs.readFile(path.join(dir, "benchmark_config.toml"), "utf8")),
+ ).toMatchObject({ title: "Report writing" });
+ });
+
+ it("rejects malformed create requests and non-owners without writing anything", async () => {
+ const first = createBody.cases[0]!;
+ const bad: unknown[] = [
+ { ...createBody, id: "../escape" },
+ { ...createBody, id: "" },
+ { ...createBody, title: " " },
+ { ...createBody, runs: 0 },
+ { ...createBody, runs: 1.5 },
+ { ...createBody, runs: 1001 },
+ { ...createBody, cases: [] },
+ { ...createBody, cases: [{ ...first, id: "excel-task" }] },
+ { ...createBody, cases: [{ ...first, id: "CASE-001/../x" }] },
+ { ...createBody, cases: [first, first] },
+ { ...createBody, cases: [{ ...first, rubric: "" }] },
+ ];
+ for (const body of bad) {
+ expect((await owner.post(base, body)).status, JSON.stringify(body)).toBe(400);
+ }
+ expect((await member.post(base, createBody)).status).toBe(403);
+ expect((await outsider.post(base, createBody)).status).toBe(404);
+ // A missing Project is a 404 before any validation.
+ expect((await owner.post("/api/projects/nobody/benchmarks", createBody)).status).toBe(404);
+ expect(((await (await owner.get(base)).json()) as BenchmarksResponse).benchmarks).toEqual([]);
+ });
+
+ it("owner deletes a Benchmark directory whole; members and outsiders cannot", async () => {
+ expect((await owner.post(base, createBody)).status).toBe(201);
+ const dir = path.join(benchmarksDir(t.root, projectId), "report-writing-v1");
+ expect((await member.delete(`${base}/report-writing-v1`)).status).toBe(403);
+ expect((await outsider.delete(`${base}/report-writing-v1`)).status).toBe(404);
+ await expect(fs.access(dir)).resolves.toBeUndefined();
+
+ expect((await owner.delete(`${base}/report-writing-v1`)).status).toBe(204);
+ await expect(fs.access(dir)).rejects.toThrow();
+ expect(((await (await owner.get(base)).json()) as BenchmarksResponse).benchmarks).toEqual([]);
+ // Gone, or never there: both are a plain 404.
+ expect((await owner.delete(`${base}/report-writing-v1`)).status).toBe(404);
+ expect((await owner.delete(`${base}/never-existed`)).status).toBe(404);
});
});
diff --git a/packages/server/test/builtin-agents.test.ts b/packages/server/test/builtin-agents.test.ts
index 17bd0662..26ff2e81 100644
--- a/packages/server/test/builtin-agents.test.ts
+++ b/packages/server/test/builtin-agents.test.ts
@@ -101,10 +101,10 @@ describe("built-in Agent provisioning", () => {
await expectBuiltinAgents(created.project.projectId);
});
- it("default_agent ships a sample Benchmark readable via GET /benchmarks", async () => {
+ it("default_agent seeds the Project's sample Benchmark, readable via GET /benchmarks", async () => {
const projects = (await (await owner.get("/api/projects")).json()) as ProjectsResponse;
const projectId = projects.projects[0]!.projectId;
- const res = await owner.get(`/api/projects/${projectId}/agents/default_agent/benchmarks`);
+ const res = await owner.get(`/api/projects/${projectId}/benchmarks`);
expect(res.status).toBe(200);
const body = (await res.json()) as BenchmarksResponse;
const bench = body.benchmarks.find((b) => b.id === "example-benchmark")!;
@@ -115,7 +115,10 @@ describe("built-in Agent provisioning", () => {
expect(bench.runs).toBe(2);
expect(bench.caseCount).toBe(2);
expect(bench.evaluations).toHaveLength(3);
+ // The sample evaluations all test default_agent, so the Benchmark reports exactly it.
+ expect(bench.agentIds).toEqual(["default_agent"]);
for (const evaluation of bench.evaluations) {
+ expect(evaluation.agentId).toBe("default_agent");
expect(evaluation.thinkingLevel).toBe("medium");
expect(evaluation.summary).toBeTruthy();
expect(evaluation.cases).toHaveLength(2);
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 9beb8538..70d4f521 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -355,10 +355,22 @@ describe("session-index", () => {
// counts=1 returns totals over the whole list, not the returned page — with or without a filter.
const counted = await list("?category=active&counts=1&limit=1");
expect(counted.sessions).toHaveLength(1);
- expect(counted.counts).toEqual({ active: 2, subagent: 1, schedule: 1, archived: 2 });
+ expect(counted.counts).toEqual({
+ active: 2,
+ subagent: 1,
+ schedule: 1,
+ benchmark: 0,
+ archived: 2,
+ });
const full = await list("?counts=1");
expect(full.sessions).toHaveLength(6);
- expect(full.counts).toEqual({ active: 2, subagent: 1, schedule: 1, archived: 2 });
+ expect(full.counts).toEqual({
+ active: 2,
+ subagent: 1,
+ schedule: 1,
+ benchmark: 0,
+ archived: 2,
+ });
expect((await list("")).counts).toBeUndefined();
expect((await list("")).workspaceCounts).toBeUndefined();
expect((await list("")).workspaceLatest).toBeUndefined();
@@ -371,9 +383,10 @@ describe("session-index", () => {
active: 0,
subagent: 1,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
- const summed = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const summed = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
for (const ws of Object.values(byWorkspace)) {
for (const key of Object.keys(summed) as (keyof typeof summed)[]) summed[key] += ws[key];
}
@@ -384,6 +397,26 @@ describe("session-index", () => {
expect((await api.get(`${base()}?counts=yes`)).status).toBe(400);
});
+ it("a Session created with source benchmark lists under the benchmark category", async () => {
+ await configureModels();
+ const res = await api.post(base(), { source: "benchmark" });
+ expect(res.status).toBe(201);
+ const { session } = (await res.json()) as SessionCreateResponse;
+ // The origin is read back from the just-created core Session's session_meta, so the
+ // create response already carries it.
+ expect(session.source).toBe("benchmark");
+
+ const counted = (await (await api.get(`${base()}?counts=1`)).json()) as SessionsResponse;
+ expect(counted.counts?.benchmark).toBe(1);
+ const filtered = (await (
+ await api.get(`${base()}?category=benchmark`)
+ ).json()) as SessionsResponse;
+ expect(filtered.sessions.map((s) => s.sessionId)).toEqual([session.sessionId]);
+
+ // Only `benchmark` may be set by a client: the server writes the other origins itself.
+ expect((await api.post(base(), { source: "schedule" })).status).toBe(400);
+ });
+
it("workspaceGroup pages one Workspace group's own stream, temporary workspaces as one group", async () => {
// Rows are inserted straight into the index: the group filter reads the stored path, and
// going through create() would only add realpath validation this has nothing to say about.
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index cf65d46b..d329d7f9 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -876,17 +876,19 @@ describe("trace-service", () => {
expect(byId.get(S)!.workspace).toBe("/ws/one");
expect(byId.get(s2)!.category).toBe("subagent"); // untracked but registry-known
expect(byId.get(s3)!.category).toBe("active");
- expect(res.counts).toEqual({ active: 1, subagent: 1, schedule: 0, archived: 1 });
+ expect(res.counts).toEqual({ active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 1 });
expect(res.workspaceCounts!["/ws/one"]).toEqual({
active: 0,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 1,
});
expect(res.workspaceCounts!["/ws/two"]).toEqual({
active: 1,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
@@ -899,7 +901,13 @@ describe("trace-service", () => {
);
expect(active.sessions!.map((x) => x.sessionId)).toEqual([s3]);
expect(active.totalSessions).toBe(1);
- expect(active.counts).toEqual({ active: 1, subagent: 1, schedule: 0, archived: 1 });
+ expect(active.counts).toEqual({
+ active: 1,
+ subagent: 1,
+ schedule: 0,
+ benchmark: 0,
+ archived: 1,
+ });
const archived = await h.service.agentTraces(
P,
A,
@@ -922,7 +930,13 @@ describe("trace-service", () => {
const first = await service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(first.sessions![0]!.category).toBe("subagent");
expect(first.sessions![0]!.workspace).toBe("/ws/child");
- expect(first.counts).toEqual({ active: 0, subagent: 1, schedule: 0, archived: 0 });
+ expect(first.counts).toEqual({
+ active: 0,
+ subagent: 1,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
// The observation landed in the shared registry (single source of truth) at registration.
expect(harness.sources.get(S)).toBe("subagent");
const reads = harness.traceIndex.counters.headReads;
@@ -955,7 +969,13 @@ describe("trace-service", () => {
const listed = await h.service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(listed.sessions!.map((x) => x.sessionId)).toEqual([childSid, cliSid, webSid]);
expect(listed.totalSessions).toBe(3);
- expect(listed.counts).toEqual({ active: 2, subagent: 1, schedule: 0, archived: 0 });
+ expect(listed.counts).toEqual({
+ active: 2,
+ subagent: 1,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
h.close();
});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 9f3d9862..5ed1faf6 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -27,6 +27,8 @@ import type {
AuthLoginRequest,
AuthResponse,
BenchmarkCasesResponse,
+ BenchmarkCreateRequest,
+ BenchmarkCreateResponse,
BenchmarksResponse,
CaseMaterial,
ChatDefaultsDto,
@@ -1213,46 +1215,59 @@ export const removeAgentSkill = (projectId: string, agentId: string, name: strin
{ method: "DELETE" },
);
-// Benchmark scoring (read-only display) -------------------------------------------------------
+// Benchmarks (scores, manual creation and deletion) -------------------------------------------
+// Benchmarks sit at the Project level, beside agents rather than under one: a Benchmark can
+// evaluate many agents, so no agent id travels in these paths.
-export const listBenchmarks = (projectId: string, agentId: string) =>
- apiFetch<BenchmarksResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/benchmarks`,
- );
+export const listBenchmarks = (projectId: string) =>
+ apiFetch<BenchmarksResponse>(`/api/projects/${encodeURIComponent(projectId)}/benchmarks`);
-export const listBenchmarkCases = (projectId: string, agentId: string, benchmarkId: string) =>
+export const listBenchmarkCases = (projectId: string, benchmarkId: string) =>
apiFetch<BenchmarkCasesResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +
- `/benchmarks/${encodeURIComponent(benchmarkId)}/cases`,
+ `/api/projects/${encodeURIComponent(projectId)}/benchmarks/${encodeURIComponent(benchmarkId)}` +
+ `/cases`,
+ );
+
+/** Creates a Benchmark by hand (owner only); the server writes the on-disk layout. 409 `benchmark_exists` on a taken id. */
+export const createBenchmark = (projectId: string, body: BenchmarkCreateRequest) =>
+ apiFetch<BenchmarkCreateResponse>(`/api/projects/${encodeURIComponent(projectId)}/benchmarks`, {
+ method: "POST",
+ body,
+ });
+
+/** Removes a Benchmark directory whole — cases, config and scoreboard (owner only; 204). */
+export const deleteBenchmark = (projectId: string, benchmarkId: string) =>
+ apiFetch<void>(
+ `/api/projects/${encodeURIComponent(projectId)}/benchmarks/${encodeURIComponent(benchmarkId)}`,
+ { method: "DELETE" },
);
const benchmarkCaseFilesPath = (
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
material: CaseMaterial,
) =>
- `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +
- `/benchmarks/${encodeURIComponent(benchmarkId)}/cases/${encodeURIComponent(caseId)}` +
+ `/api/projects/${encodeURIComponent(projectId)}/benchmarks/${encodeURIComponent(benchmarkId)}` +
+ `/cases/${encodeURIComponent(caseId)}` +
`${material === "rubric" ? "/rubric" : ""}/files`;
export const listBenchmarkCaseFiles = (
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
path: string,
material: CaseMaterial,
) =>
apiFetch<WorkspaceFilesResponse>(
- benchmarkCaseFilesPath(projectId, agentId, benchmarkId, caseId, material),
- { query: { path } },
+ benchmarkCaseFilesPath(projectId, benchmarkId, caseId, material),
+ {
+ query: { path },
+ },
);
export const benchmarkCaseFileUrl = (
projectId: string,
- agentId: string,
benchmarkId: string,
caseId: string,
path: string,
@@ -1261,7 +1276,6 @@ export const benchmarkCaseFileUrl = (
): string => {
const base = `${benchmarkCaseFilesPath(
projectId,
- agentId,
benchmarkId,
caseId,
material,
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 7cb0bef8..91066984 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -54,11 +54,13 @@ import {
aggregateWorkspaceLatest,
clampGroupPage,
completeWorkspaceGroups,
+ foldedShare,
groupPageCount,
groupPageOf,
groupPageSlice,
groupSessionsByTime,
groupSessionsByWorkspace,
+ isFolderOnly,
matchesSessionQuery,
partitionSessions,
revealPlan,
@@ -267,6 +269,15 @@ const menuSectionClass =
*/
const collapsedGroupsKey = (projectId: string) => `penguin.sidebarCollapsedGroups.${projectId}`;
const pinnedGroupsKey = (projectId: string) => `penguin.sidebarPinnedGroups.${projectId}`;
+/**
+ * Opened folder-only groups, in a set of their own because the two say opposite things: a
+ * group that opens by default stores the keys the user CLOSED, while a folder-only group
+ * (collapsed by default — session-grouping.ts's isFolderOnly) stores the keys the user
+ * OPENED. A group that gains an active row stops being folder-only and is simply read out of
+ * the other set again, which is why neither set ever has to be rewritten.
+ */
+const expandedFolderOnlyGroupsKey = (projectId: string) =>
+ `penguin.sidebarExpandedFolderGroups.${projectId}`;
/** Reads a persisted group-key set (no Project yet / corrupted storage degrade to empty). */
function loadGroupSet(storageKey: string | null): ReadonlySet<string> {
if (!storageKey) return new Set();
@@ -289,15 +300,40 @@ function saveGroupSet(storageKey: string | null, next: ReadonlySet<string>): voi
}
/**
- * Open-state key of a collapsed folder (subagent / scheduled / archived) inside a group:
- * each folder has its own state. "\0" never appears in Agent ids or Workspace paths, so
- * the composite never collides across groups or with plain group keys.
+ * Open-state key of a collapsed folder (subagent / scheduled / evaluations / archived) inside
+ * a group: each folder has its own state. "\0" never appears in Agent ids or Workspace paths,
+ * so the composite never collides across groups or with plain group keys.
*/
const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0${groupKey}`;
/** Collapse-state key of the parked-drafts group ("\0" keeps it clear of Agent ids and Workspace paths). */
const DRAFTS_GROUP_KEY = "\0drafts";
+/**
+ * One group's active and folded shares — what decides whether it is folder-only, and the
+ * count its dimmed header then carries. The server's exact per-category totals are raised,
+ * category by category, by the rows already in memory: the counts are taken at fetch time, so
+ * a conversation created since exists only as a loaded row (the rule a workspace group's
+ * header count already applies to its active share).
+ */
+const groupShares = (
+ totals: SessionCategoryCounts | undefined,
+ rows: readonly SessionInfo[],
+): { active: number; folded: number } => {
+ const counts: SessionCategoryCounts = {
+ active: 0,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ };
+ for (const s of rows) counts[sessionCategory(s)] += 1;
+ counts.active = Math.max(counts.active, totals?.active ?? 0);
+ for (const category of FOLDER_CATEGORIES)
+ counts[category] = Math.max(counts[category], totals?.[category] ?? 0);
+ return { active: counts.active, folded: foldedShare(counts) };
+};
+
/** Standing "no Session is scheduled", so the first render has something to hold before any answer. */
const NO_SCHEDULED_SESSIONS: ReadonlySet<string> = new Set();
@@ -389,6 +425,8 @@ export function Sidebar({
const scheduledSessions = pendingScheduled ?? lastScheduledRef.current;
const collapseStoreKey = currentProjectId === null ? null : collapsedGroupsKey(currentProjectId);
const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);
+ const folderOnlyStoreKey =
+ currentProjectId === null ? null : expandedFolderOnlyGroupsKey(currentProjectId);
/** Collapsed page-nav group (the 智能体 → 评估中心 entries; expanded by default, the choice persists across sessions). */
const [navCollapsed, setNavCollapsed] = useState(initialNavGroupCollapsed);
/** Grouping mode of the Session list (Workspace by default; the choice persists across sessions). */
@@ -401,6 +439,10 @@ export function Sidebar({
const [pinnedGroups, setPinnedGroups] = useState<ReadonlySet<string>>(() =>
loadGroupSet(pinStoreKey),
);
+ /** Folder-only groups the user has opened (they render collapsed by default), keyed like collapsedGroups but persisted in their own set — the two record opposite choices (see expandedFolderOnlyGroupsKey). */
+ const [expandedFolderOnlyGroups, setExpandedFolderOnlyGroups] = useState<ReadonlySet<string>>(
+ () => loadGroupSet(folderOnlyStoreKey),
+ );
/** Pinned conversations (bubbled to the top of their group's active list), Session ids; persisted per Project frontend-side (lib/pinned-sessions.ts). */
const [pinnedSessions, setPinnedSessions] = useState<ReadonlySet<string>>(() =>
loadPinnedSessions(currentProjectId),
@@ -462,6 +504,7 @@ export function Sidebar({
useEffect(() => {
setCollapsedGroups(loadGroupSet(collapseStoreKey));
setPinnedGroups(loadGroupSet(pinStoreKey));
+ setExpandedFolderOnlyGroups(loadGroupSet(folderOnlyStoreKey));
setPinnedSessions(loadPinnedSessions(currentProjectId));
setSessionOrder(loadSessionOrder(currentProjectId, groupMode));
setGroupOrder(loadGroupOrder(currentProjectId, groupMode));
@@ -471,8 +514,8 @@ export function Sidebar({
setGroupCaps(new Map());
setFolderCaps(new Map());
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [collapseStoreKey, pinStoreKey, currentProjectId]);
- /** Expanded folders (subagent / scheduled / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
+ }, [collapseStoreKey, pinStoreKey, folderOnlyStoreKey, currentProjectId]);
+ /** Expanded folders (subagent / scheduled / evaluations / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());
/** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */
const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());
@@ -550,10 +593,43 @@ export function Sidebar({
[sessions, workspaceGroupCounts, workspaceGroupLatest, registeredWorkspaces],
);
+ /**
+ * The folder-only groups of each mode: group key → the conversations folded inside it. A
+ * group with no active conversation of its own but rows inside its folders — the Workspace
+ * an evaluation creates per Case × Run, an Agent that has only ever been evaluated — folds
+ * up, sorts behind the other groups of its mode and wears a dimmed header carrying that
+ * count.
+ *
+ * Read off the group lists BEFORE they are ordered: the ordering consumes this, so it
+ * cannot be what feeds it. The search query is deliberately not part of it either — a query
+ * hides rows rather than emptying a group, and a list that folded and reshuffled itself as
+ * the user typed would be unreadable.
+ */
+ const folderOnlyAgents = useMemo(() => {
+ const out = new Map<string, number>();
+ for (const agent of agents) {
+ const shares = groupShares(
+ countsByAgent.get(agent.agentId),
+ byAgent.get(agent.agentId) ?? [],
+ );
+ if (isFolderOnly(shares.active, shares.folded)) out.set(agent.agentId, shares.folded);
+ }
+ return out;
+ }, [agents, countsByAgent, byAgent]);
+ const folderOnlyWorkspaceGroups = useMemo(() => {
+ const out = new Map<string, number>();
+ for (const group of workspaceGroups) {
+ const shares = groupShares(workspaceGroupCounts.get(group.key)?.totals, group.sessions);
+ if (isFolderOnly(shares.active, shares.folded)) out.set(group.key, shares.folded);
+ }
+ return out;
+ }, [workspaceGroups, workspaceGroupCounts]);
+
// Pinned groups first within each mode, then the manual drag order within each pin
- // partition. Nothing dragged yet = an empty order = the automatic sort untouched
- // (recency for Workspace groups with the temp group last, the configured Agent order
- // for Agents), which is also what a group with no stored place falls back to.
+ // partition, and the folder-only groups behind the rest of the unpinned cluster (a pinned
+ // one stays where it was pinned). Nothing dragged yet = an empty order = the automatic
+ // sort untouched (recency for Workspace groups with the temp group last, the configured
+ // Agent order for Agents), which is also what a group with no stored place falls back to.
// The stored array belongs to the mode it was loaded for: handing an Agent list an
// order of Workspace keys is a no-op only as long as the two key namespaces cannot
// collide, and it costs the empty-order fast path on every render of the other mode.
@@ -562,16 +638,18 @@ export function Sidebar({
orderGroups(agents, (a) => a.agentId, {
pinned: pinnedGroups,
order: groupMode === "agent" ? groupOrder : [],
+ demote: (a) => folderOnlyAgents.has(a.agentId),
}),
- [agents, pinnedGroups, groupOrder, groupMode],
+ [agents, pinnedGroups, groupOrder, groupMode, folderOnlyAgents],
);
const orderedWorkspaceGroups = useMemo(
() =>
orderGroups(workspaceGroups, (g) => g.key, {
pinned: pinnedGroups,
order: groupMode === "workspace" ? groupOrder : [],
+ demote: (g) => folderOnlyWorkspaceGroups.has(g.key),
}),
- [workspaceGroups, pinnedGroups, groupOrder, groupMode],
+ [workspaceGroups, pinnedGroups, groupOrder, groupMode, folderOnlyWorkspaceGroups],
);
// The FULL displayed group sequences a drop commits — every group of the mode, not the
@@ -590,18 +668,27 @@ export function Sidebar({
? TIME_FOLDERS_GROUP_KEY
: workspaceGroupKey(s.workspace);
- const toggleGroup = (key: string) => {
+ /**
+ * Collapse/expand a group. A folder-only group flips the OTHER set: it is collapsed by
+ * default, so what persists is the fact that the user opened it (expandedFolderOnlyGroupsKey).
+ */
+ const toggleGroup = (key: string, folderOnly = false) => {
// Inert while searching: groups render force-opened then, so a click would change
// nothing on screen while silently rewriting the persisted collapse state — the user
// would find groups flipped once the query clears.
if (searching) return;
// Computed outside the state updater (theme.tsx convention): the persistence write is a
// side effect, and updaters must stay pure (double-invoked in StrictMode).
- const next = new Set(collapsedGroups);
+ const next = new Set(folderOnly ? expandedFolderOnlyGroups : collapsedGroups);
if (next.has(key)) next.delete(key);
else next.add(key);
- setCollapsedGroups(next);
- saveGroupSet(collapseStoreKey, next);
+ if (folderOnly) {
+ setExpandedFolderOnlyGroups(next);
+ saveGroupSet(folderOnlyStoreKey, next);
+ } else {
+ setCollapsedGroups(next);
+ saveGroupSet(collapseStoreKey, next);
+ }
};
/** Pin / unpin a group (same toggle-and-persist convention as toggleGroup). */
@@ -688,6 +775,7 @@ export function Sidebar({
active: rows,
subagent: [],
schedule: [],
+ benchmark: [],
archived: [],
});
@@ -1266,9 +1354,9 @@ export function Sidebar({
scheduled={scheduledSessions.has(s.sessionId)}
pinned={pinnedSessions.has(s.sessionId)}
// Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /
- // archived) are ordered chronologically inside their folder and never pass
- // through orderSessionRows, so a pin there would write an id, light the
- // glyph, move nothing — and then shift the active list's drag partition.
+ // evaluations / archived) are ordered chronologically inside their folder and
+ // never pass through orderSessionRows, so a pin there would write an id, light
+ // the glyph, move nothing — and then shift the active list's drag partition.
canPin={activeList}
// Last ACTIVITY, not creation: the server stamps lastActiveAt when a run
// starts and again when it ends, so a running row shows its run-start time
@@ -1331,7 +1419,7 @@ export function Sidebar({
};
/**
- * Collapsed-by-default lazy folder (subagent / scheduled / archived): nothing is
+ * Collapsed-by-default lazy folder (subagent / scheduled / evaluations / archived): nothing is
* fetched until the first expand, and once open the folder reveals and pages
* independently with its own "More" and "show less" rows. Everything is driven by the
* group's **own** exact server share (`totals` — the Agent's counts in agent mode, the
@@ -1429,9 +1517,9 @@ export function Sidebar({
/**
* Expanded group body shared by both modes: active user rows (display-capped; "More"
* reveals and loads further **active-only** pages — the folders below never feed it) +
- * the collapsed-by-default subagent / scheduled / archived folders, each loading on
- * first expand and paging on its own. `totals` / `agentsFor` carry the group's exact
- * server share and its fetch fan-out set per category.
+ * the collapsed-by-default subagent / scheduled / evaluations / archived folders, each
+ * loading on first expand and paging on its own. `totals` / `agentsFor` carry the group's
+ * exact server share and its fetch fan-out set per category.
*/
const renderGroupBody = (
groupKey: string,
@@ -1532,8 +1620,8 @@ export function Sidebar({
)}
{/* Folders (collapsed by default): subagent first — spawned from the conversations
- at hand — then scheduled background runs, then archived (archived wins over the
- origin folders). */}
+ at hand — then scheduled background runs, then the Evaluation Center's runs, then
+ archived (archived wins over the origin folders). */}
{folders}
</>
);
@@ -2010,7 +2098,13 @@ export function Sidebar({
const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);
if (searching && groupRows.length === 0) return null;
const parts = partitionSessions(groupRows);
- const collapsed = !searching && collapsedGroups.has(agent.agentId);
+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
+ const foldedOnly = folderOnlyAgents.get(agent.agentId);
+ const collapsed =
+ !searching &&
+ (foldedOnly === undefined
+ ? collapsedGroups.has(agent.agentId)
+ : !expandedFolderOnlyGroups.has(agent.agentId));
const pinned = pinnedGroups.has(agent.agentId);
const drag = groupDragProps(agent.agentId, agentGroupSequence);
return (
@@ -2019,7 +2113,7 @@ export function Sidebar({
<GroupHeader
{...drag.header}
open={!collapsed}
- onToggle={() => toggleGroup(agent.agentId)}
+ onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}
icon={
<AgentAvatar
id={agent.agentId}
@@ -2030,6 +2124,15 @@ export function Sidebar({
}
label={agentDisplayName(agent)}
uppercase
+ {...(foldedOnly === undefined
+ ? {}
+ : {
+ // An Agent header carries no count otherwise; a folder-only one says
+ // what it holds, because everything it holds is behind its folders.
+ count: foldedOnly,
+ muted: true,
+ title: S.chat.folderOnlyGroup(foldedOnly),
+ })}
actions={
<>
<GroupPinButton pinned={pinned} onToggle={() => togglePin(agent.agentId)} />
@@ -2082,8 +2185,23 @@ export function Sidebar({
const groupRows = filterRows(group.sessions);
if (searching && groupRows.length === 0) return null;
const parts = partitionSessions(groupRows);
- const collapsed = !searching && collapsedGroups.has(group.key);
+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
+ const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);
+ const collapsed =
+ !searching &&
+ (foldedOnly === undefined
+ ? collapsedGroups.has(group.key)
+ : !expandedFolderOnlyGroups.has(group.key));
const pinned = pinnedGroups.has(group.key);
+ /**
+ * Header tooltip: the full Workspace path, or — for a folder-only group — the
+ * sentence that says what the dimmed header and its count mean, which carries that
+ * same path inside it.
+ */
+ const headerTitle =
+ foldedOnly === undefined
+ ? group.fullPath
+ : S.chat.folderOnlyGroup(foldedOnly, group.fullPath ?? undefined);
const drag = groupDragProps(group.key, workspaceGroupSequence);
/** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
const counts = workspaceGroupCounts.get(group.key);
@@ -2095,12 +2213,13 @@ export function Sidebar({
<GroupBlock key={group.key} dropEdge={drag.dropEdge}>
{/* Group header: collapse toggle (folder icon + directory basename + count, full
path in the tooltip; the count = the group's active conversations only, exact
- server share, loaded rows win a disagreement — the folders never feed it) +
+ server share, loaded rows win a disagreement — the folders never feed it,
+ except in a folder-only group, where they are all there is to count) +
pin + new chat in this Workspace; also the group's drag handle. */}
<GroupHeader
{...drag.header}
open={!collapsed}
- onToggle={() => toggleGroup(group.key)}
+ onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}
icon={
/* Folder opens and closes with the group */
<span className="shrink-0 text-gray-400 dark:text-gray-500">
@@ -2112,11 +2231,14 @@ export function Sidebar({
}
label={group.temp ? S.chat.tempWorkspaces : group.label}
count={
- searching
- ? parts.active.length
- : Math.max(counts?.totals.active ?? 0, parts.active.length)
+ foldedOnly !== undefined
+ ? foldedOnly
+ : searching
+ ? parts.active.length
+ : Math.max(counts?.totals.active ?? 0, parts.active.length)
}
- {...(group.fullPath !== null ? { title: group.fullPath } : {})}
+ muted={foldedOnly !== undefined}
+ {...(headerTitle !== null ? { title: headerTitle } : {})}
actions={
<>
<GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
diff --git a/packages/web/src/components/ui/file-browser.tsx b/packages/web/src/components/ui/file-browser.tsx
new file mode 100644
index 00000000..678d7781
--- /dev/null
+++ b/packages/web/src/components/ui/file-browser.tsx
@@ -0,0 +1,330 @@
+/**
+ * The read-only file browser: the shared `FileTree` in an aside on the left, one preview pane
+ * on the right. The plugin detail Modal and the Benchmark case dialog are both this, so files
+ * that cannot be edited are read the same way wherever they are met — the Workspace files
+ * panel draws the same tree, with its own editing, HTML sandbox and selection machinery
+ * around it.
+ *
+ * What this owns is the layout and the preview: the two panes, their scroll caps, the header
+ * line naming what is open with its Download link, and how each kind of file is drawn —
+ * markdown through the chat markdown pipeline, text through the code block, an image and a
+ * PDF from their own URLs.
+ *
+ * What the host owns is where the files come from: how the rows are produced (the plugin
+ * groups a listing it already holds, the case dialog lists one directory per level as it is
+ * opened), how a preview's content is fetched, and what a relative markdown reference points
+ * at. A row's `path` is the only identifier here — it is what the tree highlights, what
+ * `onOpenFile` hands back and what the header prints — so a host whose paths are not unique
+ * on their own (the case dialog's two materials) prefixes them itself.
+ */
+import { useMemo } from "react";
+import type { CSSProperties, ReactNode } from "react";
+import ReactMarkdown from "react-markdown";
+import type { Components } from "react-markdown";
+import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
+import { SETTLED_MD_COMPONENTS } from "../../features/chat/md";
+import { bodyWithoutFrontmatter } from "../../lib/frontmatter";
+import type { FileTreeRow } from "../../lib/file-tree";
+import { S } from "../../lib/strings";
+import { extOf, previewKindFor } from "../../lib/workspace-tree";
+import { CodeBlock } from "../../features/chat/code-block";
+import { languageForExtension } from "../../features/chat/code-languages";
+import { FileTree } from "./file-tree";
+import type { TreeToggle } from "./file-tree";
+import { SkeletonList } from "./skeleton";
+
+/** A reference naming a scheme of its own (`https:`, `mailto:`) points outside the browsed files. */
+const EXTERNAL_REF_RE = /^[a-z][a-z0-9+.-]*:/i;
+
+/** Past this size, highlighting a text preview costs more than the colours are worth. */
+const HIGHLIGHT_LIMIT = 64 * 1024;
+
+/** Tree column width when the host names none, in px. */
+const DEFAULT_TREE_WIDTH = 220;
+
+/** Default pane heights on a wide screen, in vh: the tree's scroll cap, the preview's box. */
+const DEFAULT_TREE_MAX_HEIGHT = 50;
+const DEFAULT_PREVIEW_HEIGHT = 50;
+
+/** How a read-only preview draws a file. */
+export type FileBrowserPreviewKind = "text" | "md" | "image" | "pdf" | "unsupported";
+
+/**
+ * How a file previews here, from its name: the Workspace panel's own classification, minus the
+ * two answers a read-only browser cannot give. HTML reads as its source, since rendering it
+ * would need the panel's sandboxed frame; a name that says nothing reads as unsupported, since
+ * nobody here is reading the first bytes to find out.
+ */
+export function previewKindOf(name: string): FileBrowserPreviewKind {
+ const kind = previewKindFor(name);
+ if (kind === "html") return "text";
+ return kind === "unknown" ? "unsupported" : kind;
+}
+
+/** The file in the preview pane, and everything it takes to draw it. */
+export interface FileBrowserPreview {
+ /** The tree row path of the previewed file (what `selectedPath` highlights). */
+ path: string;
+ name: string;
+ kind: FileBrowserPreviewKind;
+ /** text / md content once loaded. */
+ content?: string;
+ truncated?: boolean;
+ loading?: boolean;
+ error?: string;
+ /** Where an image / pdf is served from; absent for in-memory text. */
+ url?: string;
+ /** A download link in the header when present. */
+ downloadUrl?: string;
+}
+
+export function FileBrowser<Row extends FileTreeRow>({
+ rows,
+ treeLabel,
+ selectedPath,
+ loadingDirs,
+ toggled = null,
+ rowTrailing,
+ treeLoading = false,
+ treeError = null,
+ headerFallback,
+ headerPath,
+ preview,
+ emptyPreview,
+ stripFrontmatter = false,
+ resolveRef,
+ treeWidth = DEFAULT_TREE_WIDTH,
+ treeMaxHeight = DEFAULT_TREE_MAX_HEIGHT,
+ previewHeight = DEFAULT_PREVIEW_HEIGHT,
+ minHeight,
+ className = "",
+ onToggleDir,
+ onOpenFile,
+}: {
+ rows: readonly Row[];
+ /** The tree's accessible name. */
+ treeLabel: string;
+ selectedPath: string | null;
+ /** Directories whose listing is in flight: the row dims and reports `aria-busy`. */
+ loadingDirs?: ReadonlySet<string>;
+ /** The directory last opened or closed, whose subtree animates. Null: nothing to animate. */
+ toggled?: TreeToggle | null;
+ /** Trailing content on a row, after its name — a file's size, a directory's badge. */
+ rowTrailing?: (row: Row) => ReactNode;
+ /** The listing is in flight: with no rows to draw, both panes wait with a skeleton. */
+ treeLoading?: boolean;
+ /** The listing failed: the aside says so, above whatever rows it does have. */
+ treeError?: string | null;
+ /** The header line while nothing is previewed: the plugin's name, the case's id. */
+ headerFallback: string;
+ /** What the header prints in place of the previewed row's own path. */
+ headerPath?: string;
+ preview: FileBrowserPreview | null;
+ /** The preview body while nothing is selected. */
+ emptyPreview: string;
+ /** Markdown: drop a leading frontmatter block before rendering. */
+ stripFrontmatter?: boolean;
+ /**
+ * What a relative markdown reference points at: the URL to load an image from, and the tree
+ * path a link opens in place. Called only for a reference that is neither an in-page anchor
+ * nor a scheme of its own; null leaves the reference as the file wrote it.
+ */
+ resolveRef?: (ref: string) => { url: string; treePath?: string } | null;
+ /** Tree column width on a wide screen, in px. */
+ treeWidth?: number;
+ /** Scroll cap of the tree pane on a wide screen, in vh. */
+ treeMaxHeight?: number;
+ /** Fixed height of the preview body, in vh. */
+ previewHeight?: number;
+ /** Floor under the whole browser, in vh; omitted, the panes decide its height. */
+ minHeight?: number;
+ className?: string;
+ onToggleDir: (dir: string) => void;
+ onOpenFile: (path: string) => void;
+}) {
+ // The sizes ride in as custom properties rather than as classes: a media query decides where
+ // each one applies (the tree column exists only from `md` up), which an inline style cannot
+ // say, and a class name composed at runtime is one Tailwind never sees to generate.
+ const sizes = {
+ "--fb-tree-width": `${treeWidth}px`,
+ "--fb-tree-max-height": `${treeMaxHeight}vh`,
+ "--fb-preview-height": `${previewHeight}vh`,
+ "--fb-min-height": minHeight === undefined ? "0px" : `${minHeight}vh`,
+ } as CSSProperties;
+
+ /**
+ * The markdown adapters, rebuilt only when the host's resolver changes: react-markdown takes
+ * these as element types, so a fresh map every render would remount the whole body.
+ */
+ const markdownComponents = useMemo<Components>(() => {
+ /** What a reference of the file's own points at; null for an external or unresolved one. */
+ const target = (ref: string): { url: string; treePath?: string } | null => {
+ if (EXTERNAL_REF_RE.test(ref)) return null;
+ return resolveRef?.(ref) ?? null;
+ };
+ // The chat's settled adapters underneath (the code-block chrome for fenced code), with the
+ // link and image adapters replaced by ones that know the browsed files.
+ return {
+ ...SETTLED_MD_COMPONENTS,
+ img: ({ src, alt }) => {
+ const resolved = typeof src === "string" ? target(src) : null;
+ const url = resolved === null ? src : resolved.url;
+ return <img src={url} alt={alt ?? ""} loading="lazy" className="max-w-full" />;
+ },
+ a: ({ href, children }) => {
+ // An in-page anchor keeps the default behaviour; a link out of the browsed files opens
+ // in a tab of its own, so it never navigates the app away from what is being read.
+ if (typeof href !== "string" || href.startsWith("#")) return <a href={href}>{children}</a>;
+ if (EXTERNAL_REF_RE.test(href)) {
+ return (
+ <a href={href} target="_blank" rel="noreferrer">
+ {children}
+ </a>
+ );
+ }
+ const resolved = target(href);
+ if (resolved === null) return <a href={href}>{children}</a>;
+ const treePath = resolved.treePath;
+ return (
+ <a
+ href={resolved.url}
+ onClick={(event) => {
+ // A file this browser holds opens in the preview pane instead of navigating.
+ if (treePath === undefined) return;
+ event.preventDefault();
+ onOpenFile(treePath);
+ }}
+ >
+ {children}
+ </a>
+ );
+ },
+ };
+ }, [resolveRef, onOpenFile]);
+
+ /** What the header names: the file that is open, or what the browser is over while none is. */
+ const headerLine = (): string => {
+ if (preview === null) return headerFallback;
+ return headerPath ?? preview.path;
+ };
+
+ /** The note under a preview that stopped short of the whole file. */
+ const truncatedNote = (p: FileBrowserPreview): ReactNode => {
+ if (p.truncated !== true) return null;
+ return <p className="mt-2 text-xs text-gray-400">{S.files.previewTruncated}</p>;
+ };
+
+ const previewBody = (): ReactNode => {
+ if (preview === null) {
+ // Nothing open yet. While the listing is still in flight there is nothing to open
+ // either, so the pane waits with the tree rather than announcing an empty browser; a
+ // listing that failed is done waiting, and the host's empty text says what happened.
+ if (treeLoading && treeError === null) return <SkeletonList rows={8} />;
+ return <p className="text-sm text-gray-400">{emptyPreview}</p>;
+ }
+ if (preview.loading === true) return <SkeletonList rows={8} />;
+ if (preview.error !== undefined) return <p className="text-sm text-red-500">{preview.error}</p>;
+ if (preview.kind === "image") {
+ return (
+ <img
+ src={preview.url}
+ alt={preview.name}
+ loading="lazy"
+ className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"
+ />
+ );
+ }
+ if (preview.kind === "pdf") {
+ return (
+ <iframe
+ src={preview.url}
+ title={preview.name}
+ className="h-[50vh] w-full rounded-md border border-gray-200 dark:border-gray-800"
+ />
+ );
+ }
+ if (preview.kind === "md") {
+ const text = preview.content ?? "";
+ return (
+ <>
+ <div className="md-body text-sm text-gray-800 dark:text-gray-100">
+ <ReactMarkdown
+ remarkPlugins={REMARK_PLUGINS}
+ rehypePlugins={REHYPE_PLUGINS}
+ components={markdownComponents}
+ >
+ {stripFrontmatter ? bodyWithoutFrontmatter(text) : text}
+ </ReactMarkdown>
+ </div>
+ {truncatedNote(preview)}
+ </>
+ );
+ }
+ if (preview.kind === "text") {
+ const code = preview.content ?? "";
+ return (
+ <>
+ <CodeBlock
+ language={languageForExtension(extOf(preview.name))}
+ code={code}
+ highlight={code.length <= HIGHLIGHT_LIMIT}
+ />
+ {truncatedNote(preview)}
+ </>
+ );
+ }
+ return <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>;
+ };
+
+ return (
+ <div
+ style={sizes}
+ className={`grid min-h-[var(--fb-min-height)] grid-cols-1 overflow-hidden rounded-md border border-gray-200 md:grid-cols-[var(--fb-tree-width)_minmax(0,1fr)] dark:border-gray-800 ${className}`}
+ >
+ {/* Both panes scroll on their own inside fixed heights, so whatever the host draws above
+ the browser stays put while a file is read. */}
+ <aside className="border-b border-gray-200 bg-gray-50/60 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-950/30">
+ <div className="max-h-44 overflow-y-auto md:max-h-[var(--fb-tree-max-height)]">
+ {treeError !== null && <p className="px-3 py-2 text-xs text-red-500">{treeError}</p>}
+ {/* A `tree` with no `treeitem` in it is not one: while the listing is in flight, or
+ when it failed or held nothing, the aside carries the skeleton or the error and
+ no tree at all. */}
+ {rows.length === 0 && treeLoading && treeError === null && <SkeletonList rows={3} />}
+ {rows.length > 0 && (
+ <FileTree
+ rows={rows}
+ label={treeLabel}
+ selectedPath={selectedPath}
+ loadingDirs={loadingDirs}
+ toggled={toggled}
+ rowTrailing={rowTrailing}
+ emptyLabel={S.files.empty}
+ onToggleDir={onToggleDir}
+ onOpenFile={onOpenFile}
+ />
+ )}
+ </div>
+ </aside>
+
+ <section className="min-w-0">
+ <div className="flex min-h-11 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">
+ <div className="min-w-0 flex-1">
+ <p className="truncate font-mono text-xs text-gray-500">{headerLine()}</p>
+ </div>
+ {preview !== null && preview.downloadUrl !== undefined && (
+ <a
+ href={preview.downloadUrl}
+ download={preview.name}
+ className="rounded-md px-2.5 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
+ >
+ {S.files.download}
+ </a>
+ )}
+ </div>
+ <div className="max-h-[var(--fb-preview-height)] min-h-[var(--fb-preview-height)] overflow-auto p-3">
+ {previewBody()}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsx
index a53da716..a247760b 100644
--- a/packages/web/src/components/ui/group-list.tsx
+++ b/packages/web/src/components/ui/group-list.tsx
@@ -292,6 +292,7 @@ export function GroupHeader({
icon,
label,
uppercase = false,
+ muted = false,
count,
title,
actions,
@@ -309,6 +310,8 @@ export function GroupHeader({
label: string;
/** Agent names render uppercase-tracked (sidebar convention); a directory basename's casing is meaningful, so workspace groups don't. */
uppercase?: boolean;
+ /** Dim the label one step (folder-only groups: nothing active of their own); the count keeps its own class. */
+ muted?: boolean;
/** Optional trailing count (workspace groups: the group's active total). */
count?: number;
/** Optional tooltip (workspace groups: the full path). */
@@ -347,7 +350,7 @@ export function GroupHeader({
<span
className={`min-w-0 truncate text-xs font-semibold ${
uppercase ? "uppercase tracking-wide " : ""
- }text-gray-500 dark:text-gray-400`}
+ }${muted ? "text-gray-400 dark:text-gray-500" : "text-gray-500 dark:text-gray-400"}`}
>
{label}
</span>
diff --git a/packages/web/src/features/ai-create/ai-bridge.ts b/packages/web/src/features/ai-create/ai-bridge.ts
index 180c18d4..d2df3f07 100644
--- a/packages/web/src/features/ai-create/ai-bridge.ts
+++ b/packages/web/src/features/ai-create/ai-bridge.ts
@@ -13,6 +13,7 @@
*/
import { useCallback } from "react";
import { useNavigate } from "react-router";
+import type { ModelRefDto } from "@prismshadow/penguin-server/api";
import { useAuth } from "../../state/auth";
import { useProject } from "../../state/project";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
@@ -29,6 +30,10 @@ export interface AiChatRequest {
workspace?: string;
/** Skills to preselect in the composer; absent or empty clears a stale selection. */
skills?: string[];
+ /** Pins the new conversation's model (a paired reference); absent, the draft keeps its cached carry-over. */
+ modelRef?: ModelRefDto;
+ /** Marks the new conversation as a Benchmark evaluation / optimization run; the sidebar files it under the Evaluations folder. */
+ source?: "benchmark";
}
/** What the draft page finds in `location.state` after openAiChat. */
@@ -39,9 +44,10 @@ export interface AiChatRouteState {
/**
* The draft cache entry for a request, merged over what the active slot holds so the model
- * carry-over survives. A leftover `/agent` handoff chip is dropped: it would forward the prompt
- * to a different agent than the one named here. The text is marked as composed rather than typed
- * (`aiPrefill`, see draft-cache.ts), which is what keeps it from outliving the draft it seeds.
+ * carry-over survives unless the request pins a model of its own. A leftover `/agent` handoff
+ * chip is dropped: it would forward the prompt to a different agent than the one named here. The
+ * text is marked as composed rather than typed (`aiPrefill`, see draft-cache.ts), which is what
+ * keeps it from outliving the draft it seeds.
*/
export function buildAiDraft(existing: DraftCache, req: AiChatRequest): DraftCache {
const draft: DraftCache = {
@@ -52,6 +58,11 @@ export function buildAiDraft(existing: DraftCache, req: AiChatRequest): DraftCac
aiPrefill: true,
};
if (req.workspace !== undefined) draft.workspace = req.workspace;
+ if (req.modelRef !== undefined) draft.modelRef = req.modelRef;
+ // Carried only for the request that asks for it: a mark the slot still holds from an earlier
+ // composed prompt would otherwise follow an unrelated conversation into the Evaluations folder.
+ if (req.source !== undefined) draft.source = req.source;
+ else delete draft.source;
delete draft.handoffAgentId;
return draft;
}
diff --git a/packages/web/src/features/ai-create/ai-create-panel.tsx b/packages/web/src/features/ai-create/ai-create-panel.tsx
index d1d58a9d..7ca737e9 100644
--- a/packages/web/src/features/ai-create/ai-create-panel.tsx
+++ b/packages/web/src/features/ai-create/ai-create-panel.tsx
@@ -51,6 +51,26 @@ export interface AiCreatePanelProps {
/** Minimum height of the prompt box, in rows; it grows with its content beyond that. */
const MIN_ROWS = 6;
+/**
+ * The folded preview of what is actually sent, with a copy button. Shown wherever a surface
+ * appends a fixed tail to the draft — this panel, and the dialogs that collect the tail's
+ * parameters in a form of their own instead.
+ */
+export function PromptFold({ text }: { text: string }) {
+ return (
+ <HelpFold title={S.aiCreate.fullPrompt} flush>
+ <div className="relative">
+ <pre className="max-h-48 overflow-auto rounded-md border border-gray-200 bg-gray-50 p-2 pr-8 font-sans text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300">
+ {text}
+ </pre>
+ <div className="absolute top-1.5 right-1.5">
+ <CopyButton text={text} label={S.aiCreate.copyPrompt} />
+ </div>
+ </div>
+ </HelpFold>
+ );
+}
+
const exampleClass =
"min-w-0 rounded-md border px-2.5 py-1.5 text-left transition-colors duration-150 " +
"disabled:cursor-not-allowed disabled:opacity-60";
@@ -164,18 +184,7 @@ export function AiCreatePanel({
</div>
)}
- {fullPrompt !== null && (
- <HelpFold title={S.aiCreate.fullPrompt} flush>
- <div className="relative">
- <pre className="max-h-48 overflow-auto rounded-md border border-gray-200 bg-gray-50 p-2 pr-8 font-sans text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300">
- {fullPrompt}
- </pre>
- <div className="absolute top-1.5 right-1.5">
- <CopyButton text={fullPrompt} label={S.aiCreate.copyPrompt} />
- </div>
- </div>
- </HelpFold>
- )}
+ {fullPrompt !== null && <PromptFold text={fullPrompt} />}
</div>
);
}
diff --git a/packages/web/src/features/ai-create/index.ts b/packages/web/src/features/ai-create/index.ts
index a5c2d41c..81953813 100644
--- a/packages/web/src/features/ai-create/index.ts
+++ b/packages/web/src/features/ai-create/index.ts
@@ -7,7 +7,7 @@ export { aiChatRouteState, buildAiDraft, useAiBridge } from "./ai-bridge";
export type { AiChatRequest, AiChatRouteState } from "./ai-bridge";
export { DEFAULT_AGENT_ID, pickDefaultAgent } from "./default-agent";
export { composeAiPrompt } from "./ai-create-prompt";
-export { AiCreatePanel } from "./ai-create-panel";
+export { AiCreatePanel, PromptFold } from "./ai-create-panel";
export type { AiCreatePanelProps, AiExample } from "./ai-create-panel";
export { AiCreateModal } from "./ai-create-modal";
export type { AiCreateModalProps } from "./ai-create-modal";
diff --git a/packages/web/src/features/benchmark/ask-ai-modal.tsx b/packages/web/src/features/benchmark/ask-ai-modal.tsx
new file mode 100644
index 00000000..ec138ee7
--- /dev/null
+++ b/packages/web/src/features/benchmark/ask-ai-modal.tsx
@@ -0,0 +1,48 @@
+/**
+ * "Ask AI" from a Benchmark detail dialog: the Create-with-AI kit's dialog, seeded with a
+ * question rather than a description of something to build, and carrying the facts already on
+ * screen as its fixed tail. The two dialogs that open it — one evaluation, one case — differ
+ * only in their question, their examples and that tail, so everything else is settled here:
+ * the Project's agents, and therefore the default agent the kit hands the prompt to, and the
+ * one way out, which prefills a new conversation and leaves pressing Send to the reader.
+ */
+import { useProject } from "../../state/project";
+import { AiCreateModal } from "../ai-create";
+import type { AiExample } from "../ai-create";
+
+export interface AskAiModalProps {
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ /** One line under the title saying what the agent is given and what it does with it. */
+ description: string;
+ /** Seeds the prompt box; the reader edits it before sending. */
+ question: string;
+ examples: AiExample[];
+ /** The structured facts appended after the question, previewed in the dialog's prompt fold. */
+ tail: string;
+}
+
+export function AskAiModal({
+ open,
+ onClose,
+ title,
+ description,
+ question,
+ examples,
+ tail,
+}: AskAiModalProps) {
+ const { agents } = useProject();
+ return (
+ <AiCreateModal
+ open={open}
+ onClose={onClose}
+ title={title}
+ description={description}
+ initialValue={question}
+ examples={examples}
+ tail={tail}
+ agents={agents}
+ />
+ );
+}
diff --git a/packages/web/src/features/benchmark/benchmark-case-browser.tsx b/packages/web/src/features/benchmark/benchmark-case-browser.tsx
index 4bca9894..e0d3b55c 100644
--- a/packages/web/src/features/benchmark/benchmark-case-browser.tsx
+++ b/packages/web/src/features/benchmark/benchmark-case-browser.tsx
@@ -1,91 +1,125 @@
+/**
+ * The Benchmark case dialog's files: the shared read-only browser (the one the plugin detail
+ * Modal draws) over a case's two materials. The tree's two top-level directories are the
+ * materials themselves — the task materials the tested agent is given, and the rubric it never
+ * sees — both open from the start, each listed one directory per level as it is opened, the
+ * way the Workspace files panel lists.
+ *
+ * Row paths carry the material they belong to (`statement/README.md`), since the two are
+ * separate file spaces whose paths would otherwise collide; every request splits the material
+ * back off before asking for a path inside it. The statement's own README opens by itself once
+ * its listing arrives, so the dialog lands on what the case is about.
+ */
import { useCallback, useEffect, useRef, useState } from "react";
+import type { ReactNode } from "react";
import type {
BenchmarkCaseSummary,
CaseMaterial,
WorkspaceFileEntry,
- WorkspaceFilesResponse,
} from "@prismshadow/penguin-server/api";
-import ReactMarkdown from "react-markdown";
-import type { Components } from "react-markdown";
-import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
import * as api from "../../api/endpoints";
import { apiErrorText } from "../../lib/api-error";
import { joinWorkspacePath } from "../../lib/file-path";
import { formatBytes } from "../../lib/format";
import { S } from "../../lib/strings";
-import { SkeletonList } from "../../components/ui/skeleton";
-import { CodeBlock } from "../chat/code-block";
+import {
+ ancestorDirs,
+ baseName,
+ expandTo,
+ parentDir,
+ withExpanded,
+} from "../../lib/workspace-tree";
+import type { Listings } from "../../lib/workspace-tree";
+import type { FileTreeRow } from "../../lib/file-tree";
+import { FileBrowser, previewKindOf } from "../../components/ui/file-browser";
+import type { FileBrowserPreview } from "../../components/ui/file-browser";
+import type { TreeToggle } from "../../components/ui/file-tree";
-const TEXT_EXTS = new Set([
- "txt",
- "md",
- "json",
- "js",
- "mjs",
- "cjs",
- "ts",
- "tsx",
- "jsx",
- "py",
- "sh",
- "bash",
- "yaml",
- "yml",
- "toml",
- "css",
- "html",
- "htm",
- "csv",
- "log",
- "xml",
- "ini",
- "conf",
- "sql",
- "svg",
-]);
-const IMAGE_EXTS = new Set(["png", "jpg", "jpeg", "gif", "webp"]);
-const EXTERNAL_REF_RE = /^[a-z][a-z0-9+.-]*:/i;
-const HIGHLIGHT_LIMIT = 64 * 1024;
-
-interface Preview {
+/** One row of the case tree: a shared tree row, which material it came from, and a file's size. */
+export interface CaseTreeRow extends FileTreeRow {
material: CaseMaterial;
- path: string;
- name: string;
- kind: "text" | "md" | "image" | "pdf" | "unsupported";
- content?: string;
- truncated?: boolean;
- loading?: boolean;
- error?: string;
-}
-
-interface Props {
- projectId: string;
- agentId: string;
- benchmarkId: string;
- caseSummary: BenchmarkCaseSummary;
+ /** Bytes on a file row, 0 on a directory. */
+ sizeBytes: number;
}
-interface MaterialGroupProps extends Props {
+/** A material as the tree draws it: which one, and the name of the folder it stands under. */
+export interface CaseMaterialSpec {
material: CaseMaterial;
label: string;
- hiddenLabel?: string;
- defaultOpen?: boolean;
- /** Auto-preview this group's root readme.md on first load. Exactly one group (the statement)
- * may carry it: both groups now open by default, and two racing auto-previews would leave the
- * preview pane on whichever listing happened to resolve last. */
- autoPreviewReadme?: boolean;
- onPreview: (material: CaseMaterial, path: string) => void;
}
-function extOf(name: string): string {
- const index = name.lastIndexOf(".");
- return index >= 0 ? name.slice(index + 1).toLowerCase() : name.toLowerCase();
+/** The two materials' own tree paths, which are also the directories the tree opens with. */
+const MATERIAL_PATHS = ["statement", "rubric"];
+
+/**
+ * The rows the tree draws, top to bottom: one directory row per material, then a depth-first
+ * walk into every open directory whose listing has arrived. An open directory that is still
+ * loading contributes its own row and no children — `loaded: false` is what tells the tree so.
+ *
+ * `listings` and `expanded` are keyed by tree path, a material's own row being its bare name,
+ * so one map and one set cover both materials without either shadowing the other.
+ */
+export function caseTreeRows(
+ materials: readonly CaseMaterialSpec[],
+ listings: Listings,
+ expanded: ReadonlySet<string>,
+): CaseTreeRow[] {
+ const rows: CaseTreeRow[] = [];
+ const walk = (material: CaseMaterial, dir: string, depth: number): void => {
+ const entries = listings.get(dir) ?? [];
+ for (const [index, entry] of entries.entries()) {
+ const path = joinWorkspacePath(dir, entry.name);
+ const isDir = entry.kind === "dir";
+ const open = isDir && expanded.has(path);
+ const children = isDir ? listings.get(path) : undefined;
+ rows.push({
+ path,
+ name: entry.name,
+ kind: entry.kind,
+ depth,
+ posInSet: index + 1,
+ setSize: entries.length,
+ expanded: open,
+ loaded: !isDir || children !== undefined,
+ empty: isDir && children !== undefined && children.length === 0,
+ material,
+ sizeBytes: entry.sizeBytes,
+ });
+ if (open && children !== undefined) walk(material, path, depth + 1);
+ }
+ };
+ for (const [index, spec] of materials.entries()) {
+ const children = listings.get(spec.material);
+ const open = expanded.has(spec.material);
+ rows.push({
+ path: spec.material,
+ name: spec.label,
+ kind: "dir",
+ depth: 0,
+ posInSet: index + 1,
+ setSize: materials.length,
+ expanded: open,
+ loaded: children !== undefined,
+ empty: children !== undefined && children.length === 0,
+ material: spec.material,
+ sizeBytes: 0,
+ });
+ if (open && children !== undefined) walk(spec.material, spec.material, 1);
+ }
+ return rows;
}
-function dirOf(filePath: string): string {
- return filePath.includes("/") ? filePath.slice(0, filePath.lastIndexOf("/")) : "";
+/** The material a tree path belongs to, and the path inside it ("" for the material's own row). */
+function splitTreePath(treePath: string): { material: CaseMaterial; path: string } {
+ const cut = treePath.indexOf("/");
+ const head = cut < 0 ? treePath : treePath.slice(0, cut);
+ return {
+ material: head === "rubric" ? "rubric" : "statement",
+ path: cut < 0 ? "" : treePath.slice(cut + 1),
+ };
}
+/** A reference written inside a file, resolved against the directory that file sits in. */
function resolveRelative(baseDir: string, ref: string): string {
const out = ref.startsWith("/") || baseDir === "" ? [] : baseDir.split("/");
for (const segment of ref.split("/")) {
@@ -96,176 +130,27 @@ function resolveRelative(baseDir: string, ref: string): string {
return out.join("/");
}
-function languageFor(name: string): string {
- const ext = extOf(name);
- return (
- {
- json: "json",
- md: "markdown",
- js: "javascript",
- mjs: "javascript",
- cjs: "javascript",
- jsx: "jsx",
- ts: "typescript",
- tsx: "tsx",
- py: "python",
- sh: "shellscript",
- bash: "shellscript",
- yaml: "yaml",
- yml: "yaml",
- toml: "toml",
- css: "css",
- html: "html",
- htm: "html",
- xml: "xml",
- sql: "sql",
- svg: "xml",
- }[ext] ?? "text"
- );
+interface Props {
+ projectId: string;
+ benchmarkId: string;
+ caseSummary: BenchmarkCaseSummary;
}
-function MaterialGroup({
- projectId,
- agentId,
- benchmarkId,
- caseSummary,
- material,
- label,
- hiddenLabel,
- defaultOpen = false,
- autoPreviewReadme = false,
- onPreview,
-}: MaterialGroupProps) {
- const [open, setOpen] = useState(defaultOpen);
- const [path, setPath] = useState("");
- /** Bound to the path it was fetched for: entry targets join against `base`, so a click on a
- * row that is momentarily stale (the fetch effect nulls the listing, but the state update
- * commits one frame later) cannot compound segments onto an already-advanced `path`. */
- const [listing, setListing] = useState<{ base: string; res: WorkspaceFilesResponse } | null>(
- null,
- );
+export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary }: Props) {
+ /** Listings by tree path; a missing key means "not fetched yet". */
+ const [listings, setListings] = useState<Listings>(() => new Map());
+ /** Both materials start open, so the case's files are in view without a click. */
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set(MATERIAL_PATHS));
+ const [loadingDirs, setLoadingDirs] = useState<ReadonlySet<string>>(() => new Set());
const [listError, setListError] = useState<string | null>(null);
- const initialReadmeOpened = useRef(false);
-
- useEffect(() => {
- if (!open) return;
- setListing(null);
- setListError(null);
- let cancelled = false;
- api
- .listBenchmarkCaseFiles(projectId, agentId, benchmarkId, caseSummary.id, path, material)
- .then((data) => {
- if (cancelled) return;
- setListing({ base: path, res: data });
- if (autoPreviewReadme && path === "" && !initialReadmeOpened.current) {
- initialReadmeOpened.current = true;
- const readme = data.entries.find(
- (entry) => entry.kind === "file" && entry.name.toLowerCase() === "readme.md",
- );
- if (readme) onPreview(material, readme.name);
- }
- })
- .catch((error: unknown) => {
- if (!cancelled) setListError(apiErrorText(error));
- });
- return () => {
- cancelled = true;
- };
- }, [
- projectId,
- agentId,
- benchmarkId,
- caseSummary.id,
- material,
- autoPreviewReadme,
- onPreview,
- open,
- path,
- ]);
-
- const crumbs = path === "" ? [] : path.split("/");
-
- const openEntry = (entry: WorkspaceFileEntry) => {
- if (listing === null) return; // rows only render out of a loaded listing
- const target = joinWorkspacePath(listing.base, entry.name);
- if (entry.kind === "dir") {
- setPath(target);
- return;
- }
- onPreview(material, target);
- };
-
- return (
- <div className="border-b border-gray-200 last:border-b-0 dark:border-gray-800">
- <button
- type="button"
- aria-expanded={open}
- onClick={() => setOpen((value) => !value)}
- className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-800/60"
- >
- <span className="text-xs text-gray-400">{open ? "▾" : "▸"}</span>
- <span className="min-w-0 flex-1 text-sm font-medium">{label}</span>
- {hiddenLabel && (
- <span className="shrink-0 rounded bg-gray-200/70 px-1.5 py-0.5 text-[10px] text-gray-500 dark:bg-gray-800 dark:text-gray-400">
- {hiddenLabel}
- </span>
- )}
- </button>
- {open && (
- <div>
- {crumbs.length > 0 && (
- <div className="flex flex-wrap items-center gap-1 border-t border-gray-100 px-5 py-1.5 dark:border-gray-800/70">
- <button
- type="button"
- onClick={() => setPath("")}
- className="rounded px-1 py-0.5 text-xs text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800"
- >
- {label}
- </button>
- {crumbs.map((segment, index) => (
- <span key={`${segment}-${index}`} className="flex min-w-0 items-center gap-1">
- <span className="text-gray-300 dark:text-gray-700">/</span>
- <button
- type="button"
- onClick={() => setPath(crumbs.slice(0, index + 1).join("/"))}
- className="max-w-24 truncate rounded px-1 py-0.5 text-xs text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800"
- >
- {segment}
- </button>
- </span>
- ))}
- </div>
- )}
- {listError && <p className="px-6 py-2 text-xs text-red-500">{listError}</p>}
- {!listing && !listError && <SkeletonList rows={3} />}
- {listing?.res.entries.length === 0 && (
- <p className="px-6 py-2 text-xs text-gray-400">{S.files.empty}</p>
- )}
- {listing?.res.entries.map((entry) => (
- <button
- key={`${entry.kind}/${entry.name}`}
- type="button"
- onClick={() => openEntry(entry)}
- className="flex w-full items-center gap-2 border-t border-gray-100 px-6 py-2 text-left hover:bg-gray-100 dark:border-gray-800/70 dark:hover:bg-gray-800/60"
- >
- <span className="text-sm text-gray-400">{entry.kind === "dir" ? "▸" : "·"}</span>
- <span className="min-w-0 flex-1 truncate text-sm">{entry.name}</span>
- {entry.kind === "file" && (
- <span className="shrink-0 text-[11px] text-gray-400">
- {formatBytes(entry.sizeBytes)}
- </span>
- )}
- </button>
- ))}
- </div>
- )}
- </div>
- );
-}
-
-export function BenchmarkCaseBrowser({ projectId, agentId, benchmarkId, caseSummary }: Props) {
- const [preview, setPreview] = useState<Preview | null>(null);
+ /** The directory whose subtree the tree should animate — the one just clicked. */
+ const [toggled, setToggled] = useState<TreeToggle | null>(null);
+ const [preview, setPreview] = useState<FileBrowserPreview | null>(null);
+ /** Answers to superseded preview requests are dropped rather than painted over the new one. */
const previewRequest = useRef(0);
+ /** Per-directory request counter, for the same reason, one listing at a time. */
+ const dirRequest = useRef<Map<string, number>>(new Map());
+ const readmeOpened = useRef(false);
const fileUrl = useCallback(
(
@@ -273,216 +158,203 @@ export function BenchmarkCaseBrowser({ projectId, agentId, benchmarkId, caseSumm
filePath: string,
options?: { download?: boolean; preview?: boolean },
) =>
- api.benchmarkCaseFileUrl(
- projectId,
- agentId,
- benchmarkId,
- caseSummary.id,
- filePath,
- material,
- options,
- ),
- [projectId, agentId, benchmarkId, caseSummary.id],
+ api.benchmarkCaseFileUrl(projectId, benchmarkId, caseSummary.id, filePath, material, options),
+ [projectId, benchmarkId, caseSummary.id],
);
- const previewPath = useCallback(
- async (material: CaseMaterial, filePath: string) => {
- const request = ++previewRequest.current;
- const name = filePath.includes("/")
- ? filePath.slice(filePath.lastIndexOf("/") + 1)
- : filePath;
- const ext = extOf(name);
- if (IMAGE_EXTS.has(ext)) {
- setPreview({ material, path: filePath, name, kind: "image" });
- return;
- }
- if (ext === "pdf") {
- setPreview({ material, path: filePath, name, kind: "pdf" });
- return;
+ /**
+ * Fetches one directory's listing into the tree, keyed by its tree path. Resolves with the
+ * entries, or null when the request failed or a newer one for the same directory overtook it.
+ */
+ const loadDir = useCallback(
+ async (treePath: string): Promise<readonly WorkspaceFileEntry[] | null> => {
+ const { material, path } = splitTreePath(treePath);
+ const seq = (dirRequest.current.get(treePath) ?? 0) + 1;
+ dirRequest.current.set(treePath, seq);
+ const current = (): boolean => dirRequest.current.get(treePath) === seq;
+ setLoadingDirs((s) => new Set(s).add(treePath));
+ try {
+ const res = await api.listBenchmarkCaseFiles(
+ projectId,
+ benchmarkId,
+ caseSummary.id,
+ path,
+ material,
+ );
+ if (!current()) return null;
+ setListings((m) => new Map(m).set(treePath, res.entries));
+ setListError(null);
+ return res.entries;
+ } catch (error) {
+ if (!current()) return null;
+ setListError(apiErrorText(error));
+ return null;
+ } finally {
+ if (current()) {
+ setLoadingDirs((s) => {
+ const next = new Set(s);
+ next.delete(treePath);
+ return next;
+ });
+ }
}
- const isMarkdown = ext === "md";
- if (!TEXT_EXTS.has(ext)) {
- setPreview({ material, path: filePath, name, kind: "unsupported" });
+ },
+ [projectId, benchmarkId, caseSummary.id],
+ );
+
+ /** Opens a file in the preview pane: the text kinds are read, the rest are served by URL. */
+ const openFile = useCallback(
+ async (treePath: string): Promise<void> => {
+ const { material, path } = splitTreePath(treePath);
+ const name = baseName(path);
+ const kind = previewKindOf(name);
+ const base: FileBrowserPreview = {
+ path: treePath,
+ name,
+ kind,
+ url: fileUrl(material, path),
+ downloadUrl: fileUrl(material, path, { download: true }),
+ };
+ const request = ++previewRequest.current;
+ if (kind !== "text" && kind !== "md") {
+ setPreview(base);
return;
}
- setPreview({
- material,
- path: filePath,
- name,
- kind: isMarkdown ? "md" : "text",
- loading: true,
- });
+ setPreview({ ...base, loading: true });
try {
- const response = await fetch(fileUrl(material, filePath, { preview: true }), {
+ const response = await fetch(fileUrl(material, path, { preview: true }), {
credentials: "same-origin",
});
if (!response.ok) throw new Error(String(response.status));
const content = await response.text();
if (request !== previewRequest.current) return;
setPreview({
- material,
- path: filePath,
- name,
- kind: isMarkdown ? "md" : "text",
+ ...base,
content,
truncated: response.headers.get("x-content-truncated") === "1",
});
} catch (error) {
if (request !== previewRequest.current) return;
- setPreview({
- material,
- path: filePath,
- name,
- kind: isMarkdown ? "md" : "text",
- error: apiErrorText(error),
- });
+ setPreview({ ...base, error: apiErrorText(error) });
}
},
[fileUrl],
);
- const downloadUrl = preview ? fileUrl(preview.material, preview.path, { download: true }) : null;
- const previewMaterialLabel =
- preview?.material === "rubric" ? S.benchmark.rubric : S.benchmark.taskMaterials;
+ // A different case is a different set of files: nothing of the last one carries over.
+ useEffect(() => {
+ setListings(new Map());
+ setExpanded(new Set(MATERIAL_PATHS));
+ setLoadingDirs(new Set());
+ setListError(null);
+ setToggled(null);
+ setPreview(null);
+ // The request counters are deliberately not reset: a listing still in flight for the case
+ // being left would otherwise match the new case's first request and land in its tree.
+ readmeOpened.current = false;
+ }, [projectId, benchmarkId, caseSummary.id]);
- const markdownComponents: Components = {
- img: ({ src, alt }) => (
- <img
- src={
- typeof src === "string" && !EXTERNAL_REF_RE.test(src)
- ? fileUrl(
- preview?.material ?? "statement",
- resolveRelative(dirOf(preview?.path ?? ""), src),
- )
- : src
- }
- alt={alt ?? ""}
- loading="lazy"
- className="max-w-full"
- />
- ),
- a: ({ href, children }) => {
- if (typeof href !== "string" || href.startsWith("#")) return <a href={href}>{children}</a>;
- if (EXTERNAL_REF_RE.test(href)) {
- return (
- <a href={href} target="_blank" rel="noreferrer">
- {children}
- </a>
- );
- }
- const target = resolveRelative(dirOf(preview?.path ?? ""), href);
- const material = preview?.material ?? "statement";
- return (
- <a
- href={fileUrl(material, target)}
- onClick={(event) => {
- event.preventDefault();
- void previewPath(material, target);
- }}
- >
- {children}
- </a>
+ useEffect(() => {
+ void loadDir("rubric");
+ // The statement's own README is what the case is about, so it opens by itself; the rubric
+ // side carries no such auto-preview, or the two listings would race for the pane.
+ void loadDir("statement").then((entries) => {
+ if (entries === null || readmeOpened.current) return;
+ const readme = entries.find(
+ (entry) => entry.kind === "file" && entry.name.toLowerCase() === "readme.md",
);
+ if (readme === undefined) return;
+ readmeOpened.current = true;
+ void openFile(joinWorkspacePath("statement", readme.name));
+ });
+ }, [loadDir, openFile]);
+
+ /** Opens or closes a directory; a first open fetches its listing. */
+ const toggleDir = (dir: string): void => {
+ const open = !expanded.has(dir);
+ setExpanded((s) => withExpanded(s, dir, open));
+ // The serial makes toggling the same directory again a new event for the tree to animate.
+ setToggled((last) => ({ dir, open, serial: (last?.serial ?? 0) + 1 }));
+ if (open && !listings.has(dir)) void loadDir(dir);
+ };
+
+ /**
+ * Opens a file and makes its row reachable: a link inside a Markdown file can point at a
+ * directory the tree has never listed, and a preview of a file with no row to highlight
+ * would leave the tree pointing at the file before it.
+ */
+ const openAndReveal = (treePath: string): void => {
+ setExpanded((s) => expandTo(s, treePath));
+ for (const dir of ancestorDirs(treePath)) {
+ if (dir !== "" && !listings.has(dir)) void loadDir(dir);
+ }
+ void openFile(treePath);
+ };
+
+ /** A relative reference in a previewed Markdown file, resolved within its own material. */
+ const resolveRef = useCallback(
+ (ref: string): { url: string; treePath?: string } | null => {
+ if (preview === null) return null;
+ const { material, path } = splitTreePath(preview.path);
+ const target = resolveRelative(parentDir(path), ref);
+ return { url: fileUrl(material, target), treePath: joinWorkspacePath(material, target) };
},
+ [preview, fileUrl],
+ );
+
+ const materials: CaseMaterialSpec[] = [
+ { material: "statement", label: S.benchmark.taskMaterials },
+ { material: "rubric", label: S.benchmark.rubric },
+ ];
+
+ /** The header names the material and the path inside it, not the prefixed tree path. */
+ const headerPath = (): string | undefined => {
+ if (preview === null) return undefined;
+ const { material, path } = splitTreePath(preview.path);
+ const label = material === "rubric" ? S.benchmark.rubric : S.benchmark.taskMaterials;
+ return `${label} / ${path}`;
};
- return (
- <div className="grid min-h-[58vh] grid-cols-1 overflow-hidden rounded-md border border-gray-200 md:grid-cols-[240px_minmax(0,1fr)] dark:border-gray-800">
- <aside className="border-b border-gray-200 bg-gray-50/60 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-950/30">
- <div className="max-h-44 overflow-y-auto md:max-h-[53vh]">
- <MaterialGroup
- projectId={projectId}
- agentId={agentId}
- benchmarkId={benchmarkId}
- caseSummary={caseSummary}
- material="statement"
- label={S.benchmark.taskMaterials}
- defaultOpen
- autoPreviewReadme
- onPreview={previewPath}
- />
- <MaterialGroup
- projectId={projectId}
- agentId={agentId}
- benchmarkId={benchmarkId}
- caseSummary={caseSummary}
- material="rubric"
- label={S.benchmark.rubric}
- hiddenLabel={S.benchmark.agentHidden}
- defaultOpen
- onPreview={previewPath}
- />
- </div>
- </aside>
+ const rowTrailing = (row: CaseTreeRow): ReactNode => {
+ // The rubric is what the case is scored against, and the tested agent never sees it: the
+ // badge says so where the folder is, rather than in a note under the tree.
+ if (row.depth === 0) {
+ if (row.material !== "rubric") return null;
+ return (
+ <span className="shrink-0 rounded bg-gray-200/70 px-1.5 py-0.5 text-[10px] text-gray-500 dark:bg-gray-800 dark:text-gray-400">
+ {S.benchmark.agentHidden}
+ </span>
+ );
+ }
+ if (row.kind !== "file") return null;
+ return (
+ <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">
+ {formatBytes(row.sizeBytes)}
+ </span>
+ );
+ };
- <section className="min-w-0">
- <div className="flex min-h-11 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">
- <div className="min-w-0 flex-1">
- <p className="truncate font-mono text-xs text-gray-500">
- {preview ? `${previewMaterialLabel} / ${preview.path}` : caseSummary.id}
- </p>
- </div>
- {downloadUrl && preview && (
- <a
- href={downloadUrl}
- download={preview.name}
- className="rounded-md px-2.5 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- {S.files.download}
- </a>
- )}
- </div>
- <div className="max-h-[52vh] min-h-[52vh] overflow-auto p-3">
- {!preview ? (
- <p className="text-sm text-gray-400">{S.benchmark.caseFileUnavailable}</p>
- ) : preview.loading ? (
- <SkeletonList rows={8} />
- ) : preview.error ? (
- <p className="text-sm text-red-500">{preview.error}</p>
- ) : preview.kind === "image" ? (
- <img
- src={fileUrl(preview.material, preview.path)}
- alt={preview.name}
- loading="lazy"
- className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"
- />
- ) : preview.kind === "pdf" ? (
- <iframe
- src={fileUrl(preview.material, preview.path)}
- title={preview.name}
- className="h-[50vh] w-full rounded-md border border-gray-200 dark:border-gray-800"
- />
- ) : preview.kind === "md" ? (
- <>
- <div className="md-body text-sm text-gray-800 dark:text-gray-100">
- <ReactMarkdown
- remarkPlugins={REMARK_PLUGINS}
- rehypePlugins={REHYPE_PLUGINS}
- components={markdownComponents}
- >
- {preview.content ?? ""}
- </ReactMarkdown>
- </div>
- {preview.truncated && (
- <p className="mt-2 text-xs text-gray-400">{S.files.previewTruncated}</p>
- )}
- </>
- ) : preview.kind === "text" ? (
- <>
- <CodeBlock
- language={languageFor(preview.name)}
- code={preview.content ?? ""}
- highlight={(preview.content?.length ?? 0) <= HIGHLIGHT_LIMIT}
- />
- {preview.truncated && (
- <p className="mt-2 text-xs text-gray-400">{S.files.previewTruncated}</p>
- )}
- </>
- ) : (
- <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>
- )}
- </div>
- </section>
- </div>
+ return (
+ <FileBrowser
+ rows={caseTreeRows(materials, listings, expanded)}
+ treeLabel={S.files.treeLabel}
+ selectedPath={preview?.path ?? null}
+ loadingDirs={loadingDirs}
+ toggled={toggled}
+ rowTrailing={rowTrailing}
+ treeLoading={listings.size === 0 && listError === null}
+ treeError={listError}
+ headerFallback={caseSummary.id}
+ headerPath={headerPath()}
+ preview={preview}
+ emptyPreview={S.benchmark.caseFileUnavailable}
+ resolveRef={resolveRef}
+ treeWidth={240}
+ treeMaxHeight={53}
+ previewHeight={52}
+ minHeight={58}
+ onToggleDir={toggleDir}
+ onOpenFile={openAndReveal}
+ />
);
}
diff --git a/packages/web/src/features/benchmark/benchmark-detail-page.tsx b/packages/web/src/features/benchmark/benchmark-detail-page.tsx
new file mode 100644
index 00000000..ac59350d
--- /dev/null
+++ b/packages/web/src/features/benchmark/benchmark-detail-page.tsx
@@ -0,0 +1,178 @@
+/**
+ * One Benchmark's own page (`/benchmark/:benchmarkId`): its title with the directory the files
+ * live in, the Use entry point, and the detail itself — chart, evaluation table, case browser.
+ * Opening a Benchmark enters this page the way an Agent's card enters its settings, so the back
+ * button is the way out rather than a close cross. An id that no longer resolves — a deleted
+ * Benchmark or a stale link — says so in place of the detail and keeps that way out.
+ */
+import { useEffect, useState } from "react";
+import { useNavigate, useParams } from "react-router";
+import type { BenchmarkSummary, ModelsResponse } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { useProject } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { CopyButton, ROW_COPY_CLASS } from "../../components/ui/copy-button";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Skeleton } from "../../components/ui/skeleton";
+import { BenchmarkDetail } from "./benchmark-detail";
+import { benchmarkPath } from "./benchmark-prompts";
+import { UseBenchmarkModal } from "./use-benchmark-modal";
+
+/** Back to the list: the arrow-left every detail page's back button carries. */
+const BACK_ICON = "M15 18l-6-6 6-6M9 12h12";
+
+export function BenchmarkDetailPage() {
+ const params = useParams<{ benchmarkId: string }>();
+ const benchmarkId = params.benchmarkId ?? "";
+ const navigate = useNavigate();
+ const { currentProject, agents } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+
+ const [benchmark, setBenchmark] = useState<BenchmarkSummary | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** The Project's list came back without this id: the Benchmark was deleted, or the link is stale. */
+ const [missing, setMissing] = useState(false);
+ const [models, setModels] = useState<ModelsResponse | null>(null);
+ const [using, setUsing] = useState(false);
+
+ useDocumentTitle(benchmark?.title ?? S.benchmark.title);
+
+ // The Project's list is the only read that carries a Benchmark's scoreboard, so the page takes
+ // it whole and picks its own out of it.
+ useEffect(() => {
+ if (!projectId || benchmarkId === "") return;
+ let cancelled = false;
+ setBenchmark(null);
+ setError(null);
+ setMissing(false);
+ api
+ .listBenchmarks(projectId)
+ .then((data) => {
+ if (cancelled) return;
+ const found = data.benchmarks.find((b) => b.id === benchmarkId) ?? null;
+ setBenchmark(found);
+ setMissing(found === null);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, benchmarkId]);
+
+ // The Project's models, for the Use dialog's conversation-model picker; a failure just leaves
+ // the picker at the Project default.
+ useEffect(() => {
+ if (!projectId) return;
+ let cancelled = false;
+ api
+ .getModels(projectId)
+ .then((res) => {
+ if (!cancelled) setModels(res);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId]);
+
+ if (!projectId) return null;
+
+ // A Benchmark that is not published has no settled cases or scores to show and nothing to
+ // evaluate against: a draft is still being written and calibrated by the agent, and a failed
+ // one never finished calibrating and can only be deleted.
+ const masked = benchmark !== null && benchmark.status !== "published";
+ const failed = benchmark !== null && benchmark.status === "failed";
+
+ let body;
+ if (error !== null) {
+ body = <p className="text-sm text-red-600 dark:text-red-400">{error}</p>;
+ } else if (missing) {
+ body = <EmptyState title={S.benchmark.notFound} description={S.benchmark.notFoundHint} />;
+ } else if (benchmark === null) {
+ body = (
+ <div className="space-y-3">
+ <Skeleton className="h-6 w-64" />
+ <Skeleton className="h-32 w-full" />
+ </div>
+ );
+ } else if (masked) {
+ body = failed ? (
+ <EmptyState
+ title={S.benchmark.creationFailed}
+ description={S.benchmark.creationFailedDetail}
+ />
+ ) : (
+ <EmptyState title={S.benchmark.building} description={S.benchmark.buildingDetail} />
+ );
+ } else {
+ body = <BenchmarkDetail projectId={projectId} benchmark={benchmark} />;
+ }
+
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <div className="mx-auto max-w-4xl">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => navigate("/benchmark")}
+ className="-ml-2 mb-3 text-gray-500 dark:text-gray-400"
+ >
+ <GlyphIcon d={BACK_ICON} size={ICON_SIZE.rowLead} />
+ {S.benchmark.backToList}
+ </Button>
+ {/* The Benchmark's name, the directory its files live in, and the Use entry point. The
+ case counts and the description are the detail's own, one block below. A Benchmark
+ tests whichever Agents its scoreboard names, so no single Agent is named up here. A
+ Benchmark that is not published, reached by its address, keeps the path but drops
+ Use, and shows the building or creation-failed notice in place of the detail. */}
+ <div className="mb-4 flex flex-wrap items-center gap-x-2 gap-y-1">
+ <h1 className="min-w-0 truncate text-xl font-semibold">
+ {benchmark?.title ?? benchmarkId}
+ </h1>
+ {/* A Benchmark that no longer resolves has no directory to name and nothing to use:
+ the title and the way back are all this row keeps. */}
+ {benchmark && (
+ <>
+ <span className="flex min-w-0 flex-1 items-center gap-1">
+ <span className="min-w-0 truncate font-mono text-xs text-gray-400 dark:text-gray-500">
+ {benchmarkPath(benchmark.id)}
+ </span>
+ <CopyButton
+ text={benchmarkPath(benchmark.id)}
+ label={S.benchmark.copyPath}
+ className={ROW_COPY_CLASS}
+ />
+ </span>
+ {!masked && (
+ <Button size="sm" variant="primary" onClick={() => setUsing(true)}>
+ {S.benchmark.use}
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ {body}
+ </div>
+
+ {using && benchmark !== null && !masked && (
+ <UseBenchmarkModal
+ key={benchmark.id}
+ open
+ onClose={() => setUsing(false)}
+ projectId={projectId}
+ benchmark={benchmark}
+ agents={agents}
+ models={models}
+ initialTab="evaluate"
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/benchmark/benchmark-detail.tsx b/packages/web/src/features/benchmark/benchmark-detail.tsx
new file mode 100644
index 00000000..d0d404ec
--- /dev/null
+++ b/packages/web/src/features/benchmark/benchmark-detail.tsx
@@ -0,0 +1,464 @@
+/**
+ * One Benchmark's detail: case counts and description, the case list, a Score-only chart grouped
+ * into series by each Evaluation's label — the tested Agent, the model and the thinking level —
+ * and the evaluation table, which spells that label out across its Agent, version, model and
+ * thinking-level columns. A row there opens that evaluation in a dialog, a case opens the case
+ * browser in another, and either dialog can hand what it shows to an agent as a question. This
+ * is the body of the Benchmark's own page (the title lives in that page's header), which mounts
+ * it once its Benchmark has been read, so nothing stays open from the Benchmark before it.
+ */
+import { useEffect, useState } from "react";
+import type {
+ BenchmarkCaseSummary,
+ BenchmarkEvaluation,
+ BenchmarkSummary,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime, formatMoney, formatScore, humanizeDuration } from "../../lib/format";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk } from "../../lib/tone";
+import { useTheme } from "../../state/theme";
+import type { Currency } from "../../state/theme";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { MAGIC_WAND_ICON } from "../../components/ui/icons";
+import { Modal } from "../../components/ui/modal";
+import { NEUTRAL_SERIES, seriesColor } from "../../lib/category-colors";
+import { lineSegments, makeRangeGeom, segmentPath } from "../usage/chart-geom";
+import { ChartFrame, useChartWidth } from "../usage/chart-svg";
+import { AskAiModal } from "./ask-ai-modal";
+import { BenchmarkCaseBrowser } from "./benchmark-case-browser";
+import {
+ evaluationLabel,
+ labelSeries,
+ scoreScale,
+ scoreValues,
+ seriesValues,
+} from "./benchmark-metrics";
+import type { EvaluationSeries } from "./benchmark-metrics";
+import { askCaseExamples, askCaseTail } from "./benchmark-prompts";
+import type { AskCaseParams } from "./benchmark-prompts";
+import { EvaluationDetailModal } from "./evaluation-detail-modal";
+
+/**
+ * Score-over-time line chart: one x slot per evaluation in scoreboard order, labeled with its
+ * timestamp. Scores remain valid on 0..100, while the visible y-axis is padded around the
+ * observed range and clamped to those limits. Evaluations are grouped by label, so a change of
+ * tested Agent or of runtime starts its own series instead of bending one, while a new Agent
+ * State version of the same agent continues the line and names its version in the bubble.
+ */
+function ScoreTrendChart({
+ evaluations,
+ series,
+}: {
+ evaluations: BenchmarkEvaluation[];
+ series: EvaluationSeries[];
+}) {
+ const [hover, setHover] = useState<number | null>(null);
+ const [ref, width] = useChartWidth();
+
+ const values = scoreValues(evaluations);
+ const scale = scoreScale(values);
+ const geom = makeRangeGeom(evaluations.length, scale.min, scale.max, width);
+ const dates = evaluations.map((e) => formatDateTime(e.time));
+
+ return (
+ <div ref={ref}>
+ {width > 0 && (
+ <ChartFrame
+ geom={geom}
+ fmtY={formatScore}
+ dates={dates}
+ hover={hover}
+ onHover={setHover}
+ yTicks={scale.ticks}
+ bubble={(i) => {
+ const e = evaluations[i]!;
+ const v = values[i] ?? null;
+ // Time, then the score with the Agent State version that earned it, then the series
+ // label, spelled by the same helper the legend reads. A version is a point on a
+ // series rather than a series of its own, so this bubble is where it is read.
+ const label = evaluationLabel(e);
+ return (
+ <>
+ <p className="text-gray-400">{formatDateTime(e.time)}</p>
+ <p className="font-mono">
+ {v === null ? "—" : formatScore(v)}
+ {e.version !== undefined && (
+ <span className="ml-1.5 text-gray-400">v{e.version}</span>
+ )}
+ </p>
+ <p className="font-mono text-gray-400">
+ {label.unlabeled ? S.benchmark.unlabeled : label.text}
+ </p>
+ </>
+ );
+ }}
+ >
+ {series.map((s, si) => {
+ const segments = lineSegments(seriesValues(evaluations, s));
+ return (
+ <g
+ key={s.unlabeled ? "unlabeled" : s.key}
+ className={(s.unlabeled ? NEUTRAL_SERIES : seriesColor(si)).text}
+ >
+ {segments.map((seg, k) => {
+ return (
+ <g key={k}>
+ {seg.length > 1 && (
+ <path
+ d={segmentPath(geom, seg)}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ opacity={hover !== null ? 0.35 : 1}
+ />
+ )}
+ {seg.map((p) => (
+ <circle
+ key={p.index}
+ cx={geom.x(p.index)}
+ cy={geom.y(p.value)}
+ r={hover === p.index ? 4 : 2.5}
+ className="fill-current"
+ opacity={hover !== null && hover !== p.index ? 0.25 : 1}
+ />
+ ))}
+ </g>
+ );
+ })}
+ </g>
+ );
+ })}
+ </ChartFrame>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Score chart + label legend. The legend prints the three parts a series is keyed by: the
+ * tested Agent, the model and the thinking level. The version a point tested is not one of
+ * them — it stands in that point's bubble and in the evaluation table's own column.
+ */
+function TrendSection({ evaluations }: { evaluations: BenchmarkEvaluation[] }) {
+ const series = labelSeries(evaluations);
+ const labelOf = (s: EvaluationSeries): string => (s.unlabeled ? S.benchmark.unlabeled : s.text);
+ return (
+ <div>
+ <p className="mb-1 text-xs font-semibold text-gray-500">
+ {S.benchmark.trendTitle(S.benchmark.colScore)}
+ </p>
+ {series.length >= 2 && (
+ <div className="mb-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
+ {series.map((s, i) => (
+ <span
+ key={s.unlabeled ? "unlabeled" : s.key}
+ className="flex items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400"
+ >
+ <span
+ className={`inline-block h-2 w-2 shrink-0 rounded-sm ${(s.unlabeled ? NEUTRAL_SERIES : seriesColor(i)).swatch}`}
+ />
+ <span className="font-mono">{labelOf(s)}</span>
+ </span>
+ ))}
+ </div>
+ )}
+ <ScoreTrendChart evaluations={evaluations} series={series} />
+ </div>
+ );
+}
+
+const CELL = "px-3 py-2";
+
+/** One evaluation record: a clickable row; the detail it used to unfold is a dialog of its own. */
+function EvaluationRow({
+ evaluation,
+ onOpen,
+ currency,
+}: {
+ evaluation: BenchmarkEvaluation;
+ onOpen: () => void;
+ currency: Currency;
+}) {
+ return (
+ <tr
+ onClick={onOpen}
+ className="cursor-pointer border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40"
+ >
+ <td className={CELL}>
+ {/* The row is what a mouse clicks, and this is the same target for a keyboard: a table
+ row cannot be a button, so the cell that names the record carries the real one. */}
+ <button
+ type="button"
+ className="text-xs hover:underline"
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpen();
+ }}
+ >
+ {formatDateTime(evaluation.time)}
+ </button>
+ </td>
+ <td className={`${CELL} text-xs text-gray-500 dark:text-gray-400`}>
+ {evaluation.agentId ? (
+ <span className="flex items-center gap-1.5">
+ <AgentAvatar
+ id={evaluation.agentId}
+ size={ICON_SIZE.rowLead}
+ className="shrink-0 rounded"
+ />
+ <span className="min-w-0 truncate font-mono">{evaluation.agentId}</span>
+ </span>
+ ) : (
+ <span className="text-gray-400">—</span>
+ )}
+ </td>
+ <td className={`${CELL} font-mono text-xs text-gray-500 dark:text-gray-400`}>
+ {evaluation.version !== undefined ? `v${evaluation.version}` : "—"}
+ </td>
+ <td
+ className={`${CELL} max-w-40 truncate font-mono text-xs text-gray-500 dark:text-gray-400`}
+ title={evaluation.provider}
+ >
+ {evaluation.modelId}
+ </td>
+ <td className={`${CELL} font-mono text-xs text-gray-500 dark:text-gray-400`}>
+ {evaluation.thinkingLevel}
+ </td>
+ <td className={`${CELL} font-mono text-xs font-semibold tabular-nums`}>
+ {formatScore(evaluation.score)}
+ </td>
+ <td className={`${CELL} font-mono text-xs tabular-nums text-gray-500 dark:text-gray-400`}>
+ {formatMoney(evaluation.cost, currency)}
+ </td>
+ <td className={`${CELL} font-mono text-xs tabular-nums text-gray-500 dark:text-gray-400`}>
+ {evaluation.durationMs !== undefined ? humanizeDuration(evaluation.durationMs) : "—"}
+ </td>
+ </tr>
+ );
+}
+
+/**
+ * What the case question carries beyond the ids: the two material paths follow from the ids
+ * themselves, so all this adds is how the newest evaluation scored this case and which Session
+ * each of its runs ran in. Null when no evaluation has scored it — a Benchmark can be read
+ * before it has ever been run.
+ */
+function caseAskParams(
+ benchmarkId: string,
+ caseId: string,
+ evaluations: readonly BenchmarkEvaluation[],
+): AskCaseParams {
+ const newest = evaluations[evaluations.length - 1];
+ const scored = newest?.cases.find((c) => c.case === caseId);
+ return {
+ benchmarkId,
+ caseId,
+ latest:
+ newest !== undefined && scored !== undefined
+ ? {
+ time: formatDateTime(newest.time),
+ score: formatScore(scored.score),
+ runs: scored.runs.map((run) => ({
+ score: formatScore(run.score),
+ sessionId: run.sessionId,
+ })),
+ }
+ : null,
+ };
+}
+
+function CasesSection({
+ cases,
+ error,
+ onOpenCase,
+}: {
+ cases: BenchmarkCaseSummary[] | null;
+ error: string | null;
+ onOpenCase: (caseId: string) => void;
+}) {
+ return (
+ <div>
+ <p className="mb-1 text-xs font-semibold text-gray-500">{S.benchmark.cases}</p>
+ <div className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ {error && <p className={`px-3 py-2 text-xs ${toneInk.danger}`}>{error}</p>}
+ {!cases && !error && <p className="px-3 py-2 text-xs text-gray-400">{S.common.loading}</p>}
+ {cases?.map((item) => {
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => onOpenCase(item.id)}
+ className="flex w-full items-center gap-3 border-b border-gray-100 px-3 py-2 text-left transition-colors last:border-b-0 hover:bg-gray-50 dark:border-gray-800/70 dark:hover:bg-gray-800/50"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium text-gray-800 dark:text-gray-200">
+ {item.title}
+ </span>
+ <span className="block truncate font-mono text-[11px] text-gray-400">
+ {item.id}
+ </span>
+ </span>
+ {/* Styled as the quiet gray action the Workspace download link is, not as a
+ link: the row itself is the button, so an accent-colored label here read as
+ a second, separately clickable target. Hover feedback comes from the row. */}
+ <span className="shrink-0 rounded-md px-2.5 py-1 text-xs font-medium text-gray-600 dark:text-gray-300">
+ {S.benchmark.viewCase}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export function BenchmarkDetail({
+ projectId,
+ benchmark: bm,
+}: {
+ projectId: string;
+ benchmark: BenchmarkSummary;
+}) {
+ const { currency } = useTheme();
+ const [caseStatements, setCaseStatements] = useState<BenchmarkCaseSummary[] | null>(null);
+ const [caseError, setCaseError] = useState<string | null>(null);
+ const [openCaseId, setOpenCaseId] = useState<string | null>(null);
+ /** Which evaluation's dialog is open, as a position in scoreboard order. */
+ const [openEvaluationIndex, setOpenEvaluationIndex] = useState<number | null>(null);
+ /** The case whose Ask AI dialog is open; kept as an id so it cannot outlive its case dialog. */
+ const [askingCaseId, setAskingCaseId] = useState<string | null>(null);
+
+ useEffect(() => {
+ setCaseStatements(null);
+ setCaseError(null);
+ setOpenCaseId(null);
+ setOpenEvaluationIndex(null);
+ setAskingCaseId(null);
+ let cancelled = false;
+ api
+ .listBenchmarkCases(projectId, bm.id)
+ .then((data) => {
+ if (!cancelled) setCaseStatements(data.cases);
+ })
+ .catch((error: unknown) => {
+ if (!cancelled) setCaseError(apiErrorText(error));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, bm.id]);
+
+ // The Scoreboard append order is the evaluation sequence. Preserve it even when a malformed
+ // timestamp would otherwise reorder Agent versions; the detail table shows that sequence newest first.
+ const evaluations = [...bm.evaluations];
+ const caseTitles = new Map(caseStatements?.map((item) => [item.id, item.title]) ?? []);
+ const openCase = caseStatements?.find((item) => item.id === openCaseId) ?? null;
+ const openEvaluation =
+ openEvaluationIndex === null ? null : (evaluations[openEvaluationIndex] ?? null);
+
+ return (
+ <div className="mx-auto max-w-4xl space-y-4">
+ {/* The tested Agent and the runtime belong to each Evaluation and are shown in the detail
+ table, not here: this Benchmark's cases are the same set whoever is being scored. */}
+ <div>
+ <p className="text-xs text-gray-500">
+ {S.benchmark.caseCount(bm.caseCount)} · {S.benchmark.runsPerCase(bm.runs ?? 1)}
+ </p>
+ {bm.description && (
+ <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{bm.description}</p>
+ )}
+ </div>
+
+ <CasesSection cases={caseStatements} error={caseError} onOpenCase={setOpenCaseId} />
+
+ {evaluations.length === 0 ? (
+ <EmptyState title={S.benchmark.noEvaluations} description={S.benchmark.noEvaluationsHint} />
+ ) : (
+ <>
+ <TrendSection evaluations={evaluations} />
+
+ <div>
+ <p className="mb-1 text-xs font-semibold text-gray-500">{S.benchmark.evaluations}</p>
+ <div className="overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ <table className="w-full min-w-[820px] text-left text-sm">
+ <thead>
+ <tr className="border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900">
+ <th className="px-3 py-2.5">{S.common.time}</th>
+ <th className="px-3 py-2.5">{S.benchmark.agentColumn}</th>
+ <th className="px-3 py-2.5">{S.benchmark.colVersion}</th>
+ <th className="px-3 py-2.5">{S.benchmark.colModel}</th>
+ <th className="px-3 py-2.5">{S.benchmark.colThinkingLevel}</th>
+ <th className="px-3 py-2.5">{S.benchmark.colScore}</th>
+ <th className="px-3 py-2.5">{S.common.cost}</th>
+ <th className="px-3 py-2.5">{S.benchmark.colDuration}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {/* Newest first on screen, while the index stays the scoreboard position the
+ dialog is opened by. */}
+ {evaluations
+ .map((ev, index) => ({ ev, index }))
+ .reverse()
+ .map(({ ev, index }) => (
+ <EvaluationRow
+ key={index}
+ evaluation={ev}
+ onOpen={() => setOpenEvaluationIndex(index)}
+ currency={currency}
+ />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </>
+ )}
+ {openEvaluation && (
+ <EvaluationDetailModal
+ benchmarkId={bm.id}
+ evaluation={openEvaluation}
+ caseTitles={caseTitles}
+ onOpenCase={setOpenCaseId}
+ currency={currency}
+ onClose={() => setOpenEvaluationIndex(null)}
+ />
+ )}
+ {openCase && (
+ <Modal
+ open
+ title={openCase.title}
+ widthClass="sm:max-w-6xl"
+ onClose={() => {
+ setOpenCaseId(null);
+ setAskingCaseId(null);
+ }}
+ footer={
+ <Button size="sm" variant="secondary" onClick={() => setAskingCaseId(openCase.id)}>
+ <GlyphIcon d={MAGIC_WAND_ICON} />
+ {S.benchmark.askAi}
+ </Button>
+ }
+ >
+ <BenchmarkCaseBrowser projectId={projectId} benchmarkId={bm.id} caseSummary={openCase} />
+ </Modal>
+ )}
+ {openCase && askingCaseId === openCase.id && (
+ <AskAiModal
+ open
+ onClose={() => setAskingCaseId(null)}
+ title={S.benchmark.askCaseTitle}
+ description={S.benchmark.askCaseDescription}
+ question={S.benchmark.askCaseDefault}
+ examples={askCaseExamples()}
+ tail={askCaseTail(caseAskParams(bm.id, openCase.id, evaluations))}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/benchmark/benchmark-metrics.ts b/packages/web/src/features/benchmark/benchmark-metrics.ts
index ece1fcda..9491921e 100644
--- a/packages/web/src/features/benchmark/benchmark-metrics.ts
+++ b/packages/web/src/features/benchmark/benchmark-metrics.ts
@@ -1,6 +1,11 @@
/**
- * Score-only data helpers and per-runtime series grouping for the Benchmark center chart.
- * Series share one time axis and use each Evaluation's authoritative stored Score.
+ * Score-only data helpers and per-label series grouping for the Benchmark center chart.
+ * Series share one time axis and use each Evaluation's authoritative stored Score. A record's
+ * label — the tested Agent, the model it ran on and the thinking level — is what makes two
+ * scores comparable, so it is what a series is keyed by and what a score change is measured
+ * within. The Agent State version is not part of it: successive versions of one agent on one
+ * runtime are the trend the loop exists to show, so they stay on one line, and each point
+ * carries its version in the chart's hover label and in the evaluation table's own column.
*/
/** Minimal Evaluation shape needed to read Score (BenchmarkEvaluation is a superset). */
@@ -52,53 +57,171 @@ export function scoreScale(values: readonly (number | null)[]): ScoreScale {
return { min, max, ticks };
}
-/** Minimal evaluation shape needed for series grouping (BenchmarkEvaluation is a superset). */
-export interface ModelRefLike {
+/** Minimal evaluation shape a label is read from (BenchmarkEvaluation is a superset). */
+export interface EvaluationLabelLike {
+ /** The Agent under test; null or absent on records written before Benchmarks left the Agent. */
+ agentId?: string | null;
+ /** On the record and deliberately outside the key: a version is a point on a series, not a series. */
+ version?: number;
+ /** On the record and deliberately outside the key — see evaluationLabel. */
+ provider?: string;
modelId?: string;
thinkingLevel?: string;
}
-/** One chart series: the set of evaluations sharing the same (modelId, thinkingLevel). */
+/** One evaluation's label: its series key, the text a legend prints, and whether it is untagged. */
+export interface EvaluationLabel {
+ /** Grouping key; "" for a record missing the tested Agent or the model. */
+ key: string;
+ /** Legend text, empty parts omitted; "" when the record is unlabeled — the caller names that series. */
+ text: string;
+ unlabeled: boolean;
+}
+
+/**
+ * The label of one evaluation: the tested Agent, the model and the thinking level, keyed and
+ * printed as the same three parts. Two fields the record also carries stay outside the key. The
+ * Agent State version is what a series is watched across — keying on it would cut the line into
+ * one point per version, exactly where an improvement is meant to become visible. The provider
+ * is outside it because a series has to be identifiable from its legend text, and that text
+ * prints the model id a reader recognizes rather than the group it is served from. A record
+ * with no tested Agent or no model cannot be placed on either axis of comparison, so it is
+ * unlabeled and shares one series.
+ */
+export function evaluationLabel(e: EvaluationLabelLike): EvaluationLabel {
+ const agentId = e.agentId ?? "";
+ const modelId = e.modelId ?? "";
+ if (agentId === "" || modelId === "") return { key: "", text: "", unlabeled: true };
+ const parts = [agentId, modelId, e.thinkingLevel ?? ""];
+ return {
+ key: parts.join("\u0000"),
+ text: parts.filter((part) => part !== "").join(" · "),
+ unlabeled: false,
+ };
+}
+
+/** One chart series: the evaluations sharing one label. */
export interface EvaluationSeries {
- /** Grouping key (internal grouping only, not used as an id; empty string for untagged model). */
+ /** Grouping key (internal grouping only, not used as an id; "" for the unlabeled series). */
key: string;
- modelId?: string;
- thinkingLevel?: string;
+ /** Legend text; "" for the unlabeled series. */
+ text: string;
+ unlabeled: boolean;
/** Matching evaluation indices: global time-axis positions, shared across all series on the same x-axis. */
indices: number[];
}
/**
- * Groups evaluations into series by model ID and thinking level, deliberately ignoring provider.
- * Runtime combinations are ordered by first appearance (color is picked from SERIES_COLORS by
- * series index); defensive records with no model tag are grouped into a trailing unnamed series.
+ * Groups evaluations into series by label, ordered by first appearance (color is picked from
+ * SERIES_COLORS by series index); records with no label are grouped into a trailing gray series.
*/
-export function modelSeries(evaluations: readonly ModelRefLike[]): EvaluationSeries[] {
+export function labelSeries(evaluations: readonly EvaluationLabelLike[]): EvaluationSeries[] {
const map = new Map<string, EvaluationSeries>();
evaluations.forEach((e, index) => {
- const labeled = e.modelId !== undefined && e.modelId !== "";
- const key = labeled ? `${e.modelId}\u0000${e.thinkingLevel ?? ""}` : "";
- let series = map.get(key);
+ const label = evaluationLabel(e);
+ let series = map.get(label.key);
if (!series) {
- series = {
- key,
- ...(labeled && e.modelId !== undefined ? { modelId: e.modelId } : {}),
- ...(labeled && e.thinkingLevel !== undefined ? { thinkingLevel: e.thinkingLevel } : {}),
- indices: [],
- };
- map.set(key, series);
+ series = { key: label.key, text: label.text, unlabeled: label.unlabeled, indices: [] };
+ map.set(label.key, series);
}
series.indices.push(index);
});
const all = [...map.values()];
- return [...all.filter((x) => x.key !== ""), ...all.filter((x) => x.key === "")];
+ return [...all.filter((x) => !x.unlabeled), ...all.filter((x) => x.unlabeled)];
}
/** A series' Score sequence; indices outside this series are null, keeping the global time axis. */
export function seriesValues(
- evaluations: readonly (MetricSourceLike & ModelRefLike)[],
+ evaluations: readonly (MetricSourceLike & EvaluationLabelLike)[],
series: EvaluationSeries,
): (number | null)[] {
const own = new Set(series.indices);
return scoreValues(evaluations).map((v, i) => (own.has(i) ? v : null));
}
+
+/** Minimal evaluation shape for the list rows: the stored Score and when it was recorded. */
+export interface TrendSourceLike extends MetricSourceLike {
+ time: string;
+}
+
+/** Finite Scores in scoreboard order — the row sparkline's series (a malformed value is skipped, never drawn as zero). */
+export function sparklineSeries(evaluations: readonly MetricSourceLike[]): number[] {
+ return scoreValues(evaluations).filter((v): v is number => v !== null);
+}
+
+export interface LatestScore {
+ score: number;
+ /** Change from the previous finite Score carrying the same label; null when that label has no earlier record. */
+ delta: number | null;
+ /** When the newest scored evaluation was recorded. */
+ time: string;
+}
+
+/**
+ * The newest finite Score, its time, and its change from the previous score of the same label.
+ * Only same-label scores are comparable — another agent, another model or another thinking
+ * level is a different measurement — so a newest record whose label appears for the first time
+ * reports no change at all rather than a difference against something else. A new Agent State
+ * version of the same agent on the same runtime is the comparison this number exists for, and
+ * is measured, not excluded.
+ */
+export function latestWithDelta(
+ evaluations: readonly (TrendSourceLike & EvaluationLabelLike)[],
+): LatestScore | null {
+ const scored = evaluations.filter((e) => typeof e.score === "number" && Number.isFinite(e.score));
+ const last = scored[scored.length - 1];
+ if (!last) return null;
+ const key = evaluationLabel(last).key;
+ let previous: (TrendSourceLike & EvaluationLabelLike) | undefined;
+ for (let i = scored.length - 2; i >= 0; i -= 1) {
+ if (evaluationLabel(scored[i]!).key === key) {
+ previous = scored[i];
+ break;
+ }
+ }
+ return {
+ score: last.score,
+ delta: previous ? last.score - previous.score : null,
+ time: last.time,
+ };
+}
+
+/** The same, narrowed to one tested Agent: the baseline the optimize dialog works from. */
+export function latestScoreOfAgent(
+ evaluations: readonly (TrendSourceLike & EvaluationLabelLike)[],
+ agentId: string,
+): LatestScore | null {
+ if (agentId === "") return null;
+ return latestWithDelta(evaluations.filter((e) => (e.agentId ?? "") === agentId));
+}
+
+/**
+ * Default optimization target: ten points above the baseline as a whole number, capped at the
+ * 100-point scale; 80 when nothing is scored yet (the optimizer then still needs a baseline,
+ * which the dialog says out loud).
+ */
+export function defaultTargetScore(baseline: number | null): number {
+ if (baseline === null) return 80;
+ return Math.min(100, Math.ceil(baseline) + 10);
+}
+
+/**
+ * Whether a row survives the search box: a case-insensitive substring of its title, description
+ * or id, or of any tested Agent's id or name. Names are looked up in the Project's agent list;
+ * an id evaluated by a since-deleted Agent still matches on the id itself.
+ */
+export function matchesBenchmarkQuery(
+ benchmark: { id: string; title: string; description?: string; agentIds?: readonly string[] },
+ agents: readonly { agentId: string; name?: string }[],
+ query: string,
+): boolean {
+ const q = query.trim().toLowerCase();
+ if (q === "") return true;
+ const haystack = [benchmark.title, benchmark.description ?? "", benchmark.id];
+ for (const agentId of benchmark.agentIds ?? []) {
+ haystack.push(agentId);
+ const name = agents.find((a) => a.agentId === agentId)?.name;
+ if (name !== undefined) haystack.push(name);
+ }
+ return haystack.some((s) => s.toLowerCase().includes(q));
+}
diff --git a/packages/web/src/features/benchmark/benchmark-page.tsx b/packages/web/src/features/benchmark/benchmark-page.tsx
index cf3704da..e89a6165 100644
--- a/packages/web/src/features/benchmark/benchmark-page.tsx
+++ b/packages/web/src/features/benchmark/benchmark-page.tsx
@@ -1,649 +1,526 @@
/**
- * Benchmark page (read-only display):
- * the left directory lists Benchmarks grouped by Agent (the scoreboard is only fetched once
- * expanded); the right side shows the selected Benchmark's title info, a Score-only chart grouped
- * into series by each Evaluation's model ID and thinking level, and an evaluation detail table
- * with separate model ID and thinking-level columns. Rows expand to show the evaluation summary
- * and per-case scores, and Case rows further expand to show the raw results of each Run with a
- * Session link.
- * With a ?agentId= deep link, only the target Agent is expanded by default.
+ * Evaluation Center: every Benchmark of the Project as one card, with the loop a novice needs
+ * spelled out in a standing block under the title — write the cases, evaluate an agent on them,
+ * optimize it against the scores. A Benchmark sits beside the agents rather than under one, so
+ * the page is a flat list and the agents a card names are the ones its scoreboard has tested.
+ * Each card carries the newest Score with its change against the previous record of the same
+ * label, a sparkline of the scoreboard, when it was last evaluated, and its actions; opening one
+ * enters the Benchmark's own page (`/benchmark/:benchmarkId`) instead of splitting this one in
+ * two, the way an Agent's card enters its settings. `?agentId=` narrows the list to the
+ * Benchmarks that tested that Agent.
*/
import { useEffect, useState } from "react";
-import { useSearchParams } from "react-router";
+import { useNavigate, useSearchParams } from "react-router";
import type {
- BenchmarkCaseScore,
- BenchmarkCaseSummary,
- BenchmarkEvaluation,
+ AgentSummary,
BenchmarkSummary,
+ ModelsResponse,
} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
-import { formatDateTime, formatMoney, formatScore, humanizeDuration } from "../../lib/format";
+import { formatRelativeShort, formatScore, signedDelta } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { STAT_ICONS } from "../../lib/stat-icons";
+import { toneInk } from "../../lib/tone";
import { agentDisplayName, useProject } from "../../state/project";
-import { useTheme } from "../../state/theme";
-import type { Currency } from "../../state/theme";
+import { useLocale } from "../../state/locale";
import { AgentAvatar } from "../../components/ui/agent-avatar";
-import { Chevron } from "../../components/ui/chevron";
-import { Truncated } from "../../components/ui/truncated";
+import { Button } from "../../components/ui/button";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
import { EmptyState } from "../../components/ui/empty-state";
-import { Modal } from "../../components/ui/modal";
-import { SkeletonList } from "../../components/ui/skeleton";
-import { NEUTRAL_SERIES, seriesColor } from "../../lib/category-colors";
-import { lineSegments, makeRangeGeom, segmentPath } from "../usage/chart-geom";
-import { ChartFrame, useChartWidth } from "../usage/chart-svg";
-import { modelSeries, scoreScale, scoreValues, seriesValues } from "./benchmark-metrics";
-import type { EvaluationSeries } from "./benchmark-metrics";
-import { BenchmarkCaseBrowser } from "./benchmark-case-browser";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Input } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { Skeleton, SkeletonCard } from "../../components/ui/skeleton";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { AiCreateModal, CreateButtons, pickDefaultAgent } from "../ai-create";
+import { latestWithDelta, matchesBenchmarkQuery, sparklineSeries } from "./benchmark-metrics";
+import { benchmarkCreateExamples, benchmarkCreateTail } from "./benchmark-prompts";
+import { benchmarkRoute } from "./benchmark-route";
+import { CreateBenchmarkModal } from "./create-benchmark-modal";
+import { ScoreSparkline } from "./score-sparkline";
+import { UseBenchmarkModal } from "./use-benchmark-modal";
-interface Selection {
- agentId: string;
- benchmark: BenchmarkSummary;
-}
+/** Delete (trash can), the same card-row mark the Agents list carries. */
+const TRASH_ICON =
+ "M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6";
-/** Expandable tree node for a single Agent (benchmarks are only fetched once expanded; same shape as the AgentNode on the trace observability page). */
-function AgentNode({
- projectId,
- agentId,
- name,
- defaultOpen,
- selection,
- onSelect,
-}: {
- projectId: string;
- agentId: string;
- name: string;
- /** Whether initially expanded: all expanded when there's no deep link; only the target Agent expanded with a ?agentId= deep link. */
- defaultOpen: boolean;
- selection: Selection | null;
- onSelect: (sel: Selection) => void;
-}) {
- const [open, setOpen] = useState(defaultOpen);
- const [benchmarks, setBenchmarks] = useState<BenchmarkSummary[] | null>(null);
- const [error, setError] = useState<string | null>(null);
+/** How many tested Agents a card names before the rest fold into a "+n". */
+const AVATARS_SHOWN = 3;
- useEffect(() => {
- if (!open || benchmarks) return;
- api
- .listBenchmarks(projectId, agentId)
- .then((data) => setBenchmarks(data.benchmarks))
- .catch((e: unknown) => setError(apiErrorText(e)));
- }, [open, benchmarks, projectId, agentId]);
+function deltaTone(delta: number | null): string {
+ if (delta === null || delta === 0) return toneInk.muted;
+ return delta > 0 ? toneInk.success : toneInk.danger;
+}
+/**
+ * The three steps of the loop, a card each: three across from `md` up, stacked below. Every card
+ * names its step and says where on this page to do it — the create buttons at the top right,
+ * Use → Evaluate and Use → Optimize on a Benchmark — and nothing else stands above or beside
+ * them: the maintainer wants the three stages alone, without a how-to line or the Skill names
+ * in grey. Nothing is drawn between the cards — the numbers already carry the order, and an
+ * arrow would only survive one of the two layouts.
+ */
+function GuideSteps() {
return (
- <li className="pt-2.5">
- <div className="flex items-center px-1 pb-0.5">
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-label={open ? S.nav.collapseGroup : S.nav.expandGroup}
- className="flex min-w-0 flex-1 items-center gap-1 rounded px-1 py-0.5 text-left transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/50"
+ <div className="mt-3 grid md:grid-cols-3 gap-3">
+ {S.benchmark.guideFlow.map((step, i) => (
+ <div
+ key={step.title}
+ className="min-w-0 rounded-md border border-gray-200 bg-gray-50 px-4 py-3 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900/40 dark:text-gray-400"
>
- <AgentAvatar id={agentId} name={name} size={18} className="shrink-0 rounded" />
- <span className="min-w-0 truncate text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
- {name}
+ <span className="flex flex-wrap items-baseline gap-x-1.5">
+ <span className="font-mono tabular-nums text-gray-400 dark:text-gray-500">{i + 1}</span>
+ <span className="font-semibold text-gray-900 dark:text-gray-100">{step.title}</span>
</span>
- <Chevron open={open} size={12} className="text-gray-400" />
- <span className="min-w-0 flex-1" />
- </button>
- </div>
- {open && (
- <div className="anim-fade">
- {error && <p className="px-2.5 py-1 text-xs text-red-500">{error}</p>}
- {!benchmarks && !error && (
- <p className="px-2.5 py-1 text-xs text-gray-400">{S.common.loading}</p>
- )}
- {benchmarks && benchmarks.length === 0 && (
- <p className="px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600">
- {S.benchmark.emptyAgent}
- </p>
- )}
- <ul className="space-y-0.5">
- {benchmarks?.map((b) => {
- const active = selection?.agentId === agentId && selection.benchmark.id === b.id;
- return (
- <li key={b.id}>
- <button
- type="button"
- onClick={() => onSelect({ agentId, benchmark: b })}
- className={`flex w-full items-center gap-1.5 rounded-md px-2.5 py-1.5 text-left transition-colors duration-150 ${
- active
- ? "bg-gray-200/70 dark:bg-gray-800"
- : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"
- }`}
- >
- <Truncated
- text={b.title}
- className={`min-w-0 flex-1 text-sm ${
- active
- ? "font-medium text-gray-900 dark:text-gray-100"
- : "text-gray-700 dark:text-gray-300"
- }`}
- />
- <span className="shrink-0 font-mono text-[11px] text-gray-400">
- {b.caseCount}
- </span>
- </button>
- </li>
- );
- })}
- </ul>
+ <p className="mt-1 leading-relaxed">{step.text}</p>
</div>
- )}
- </li>
+ ))}
+ </div>
);
}
/**
- * Score-over-time line chart. Scores remain valid on 0..100, while the visible y-axis is padded
- * around the observed range and clamped to those limits. Evaluations remain grouped by model ID
- * and thinking level so a runtime change stays visible without adding other metric modes.
+ * The Agents a Benchmark has scored, newest scoreboard order first: three tiles and a "+n" for
+ * the rest. The names are in the group's tooltip rather than beside each tile — a card that
+ * tested five agents would otherwise be a list of names with a Benchmark somewhere in it.
*/
-function ScoreTrendChart({
- evaluations,
- series,
+function TestedAgents({
+ agentIds,
+ nameOf,
}: {
- evaluations: BenchmarkEvaluation[];
- series: EvaluationSeries[];
+ agentIds: readonly string[];
+ nameOf: (agentId: string) => string;
}) {
- const [hover, setHover] = useState<number | null>(null);
- const [ref, width] = useChartWidth();
-
- const values = scoreValues(evaluations);
- const scale = scoreScale(values);
- const geom = makeRangeGeom(evaluations.length, scale.min, scale.max, width);
- const dates = evaluations.map((e) => formatDateTime(e.time));
-
+ if (agentIds.length === 0) return null;
+ const shown = agentIds.slice(0, AVATARS_SHOWN);
+ const rest = agentIds.length - shown.length;
return (
- <div ref={ref}>
- {width > 0 && (
- <ChartFrame
- geom={geom}
- fmtY={formatScore}
- dates={dates}
- hover={hover}
- onHover={setHover}
- yTicks={scale.ticks}
- bubble={(i) => {
- const e = evaluations[i]!;
- const v = values[i] ?? null;
- return (
- <>
- <p className="text-gray-400">{formatDateTime(e.time)}</p>
- <p className="font-mono">
- {v === null ? "—" : formatScore(v)}
- {e.version !== undefined && (
- <span className="ml-1.5 text-gray-400">v{e.version}</span>
- )}
- </p>
- <p className="font-mono text-gray-400">
- {e.modelId} · {e.thinkingLevel}
- </p>
- </>
- );
- }}
- >
- {series.map((s, si) => {
- const segments = lineSegments(seriesValues(evaluations, s));
- return (
- <g
- key={s.key === "" ? "unlabeled" : s.key}
- className={(s.modelId ? seriesColor(si) : NEUTRAL_SERIES).text}
- >
- {segments.map((seg, k) => {
- return (
- <g key={k}>
- {seg.length > 1 && (
- <path
- d={segmentPath(geom, seg)}
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- opacity={hover !== null ? 0.35 : 1}
- />
- )}
- {seg.map((p) => (
- <circle
- key={p.index}
- cx={geom.x(p.index)}
- cy={geom.y(p.value)}
- r={hover === p.index ? 4 : 2.5}
- className="fill-current"
- opacity={hover !== null && hover !== p.index ? 0.25 : 1}
- />
- ))}
- </g>
- );
- })}
- </g>
- );
- })}
- </ChartFrame>
+ <div
+ className="hidden shrink-0 items-center gap-1 sm:flex"
+ title={`${S.benchmark.testedAgents}: ${agentIds.map(nameOf).join(", ")}`}
+ >
+ {shown.map((agentId) => (
+ <AgentAvatar
+ key={agentId}
+ id={agentId}
+ name={nameOf(agentId)}
+ size={ICON_SIZE.rowLead}
+ className="shrink-0 rounded"
+ />
+ ))}
+ {rest > 0 && (
+ <span className="text-[11px] tabular-nums text-gray-400 dark:text-gray-500">+{rest}</span>
)}
</div>
);
}
/**
- * Score chart + runtime legend. Provider is deliberately not part of chart identity.
+ * One Benchmark in the Agents list's card shape: an info column of title, description and stats,
+ * then the Agents it has tested, the sparkline, the newest Score with its change from the
+ * previous record of the same label, and the actions. The info column is the card's main button
+ * — it enters the Benchmark's page — so everything inside it is phrasing content rather than a
+ * nested block. A card that is not published is masked under a notice — still being built for a
+ * draft, creation failed for a Benchmark whose calibration never finished — with only the delete
+ * icon left live.
*/
-function TrendSection({ evaluations }: { evaluations: BenchmarkEvaluation[] }) {
- const series = modelSeries(evaluations);
- const labelOf = (s: EvaluationSeries): string => {
- if (!s.modelId) return S.benchmark.legendUnlabeled;
- return s.thinkingLevel ? `${s.modelId} · ${s.thinkingLevel}` : s.modelId;
- };
+function BenchmarkCard({
+ benchmark,
+ locale,
+ nameOf,
+ canDelete,
+ onOpen,
+ onUse,
+ onDelete,
+}: {
+ benchmark: BenchmarkSummary;
+ locale: "zh" | "en";
+ nameOf: (agentId: string) => string;
+ canDelete: boolean;
+ onOpen: () => void;
+ onUse: () => void;
+ onDelete: () => void;
+}) {
+ const latest = latestWithDelta(benchmark.evaluations);
+ const series = sparklineSeries(benchmark.evaluations);
+ // A Benchmark that is not published is masked and inert: a draft is still being written and
+ // calibrated by the agent, and a failed one never finished calibrating and can only be thrown
+ // away. Only the owner's delete stays above the mask, which is how either is cleaned up.
+ const masked = benchmark.status !== "published";
+ const failed = benchmark.status === "failed";
return (
- <div>
- <p className="mb-1 text-xs font-semibold text-gray-500">
- {S.benchmark.trendTitle(S.benchmark.colScore)}
- </p>
- {series.length >= 2 && (
- <div className="mb-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
- {series.map((s, i) => (
+ <div className="relative flex flex-wrap items-center gap-x-6 gap-y-2 rounded-md border border-gray-200 bg-white px-5 py-4 dark:border-gray-800 dark:bg-gray-900">
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={masked}
+ className="min-w-[14rem] flex-1 text-left"
+ >
+ <span className="flex items-center gap-2">
+ <span className="min-w-0 truncate text-base font-bold">{benchmark.title}</span>
+ <span className="hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500">
+ {benchmark.id}
+ </span>
+ </span>
+ {/* An empty description still takes its line, so the cards keep one height. */}
+ <span className="mt-1.5 block min-h-4 truncate text-xs text-gray-500 dark:text-gray-400">
+ {benchmark.description ?? ""}
+ </span>
+ <span className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
+ <span className="shrink-0">{S.benchmark.caseCount(benchmark.caseCount)}</span>
+ <span className="shrink-0">{S.benchmark.runsPerCase(benchmark.runs ?? 1)}</span>
+ {latest && (
<span
- key={s.key === "" ? "unlabeled" : s.key}
- className="flex items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400"
+ className={`inline-flex shrink-0 items-center ${ICON_GAP.tight}`}
+ title={S.benchmark.lastEvaluated(formatRelativeShort(latest.time, locale))}
>
- <span
- className={`inline-block h-2 w-2 shrink-0 rounded-sm ${(s.modelId ? seriesColor(i) : NEUTRAL_SERIES).swatch}`}
- />
- <span className="font-mono">{labelOf(s)}</span>
+ <GlyphIcon d={STAT_ICONS.elapsed} size={ICON_SIZE.inlineGlyph} />
+ {formatRelativeShort(latest.time, locale)}
</span>
- ))}
+ )}
+ </span>
+ </button>
+ <TestedAgents agentIds={benchmark.agentIds} nameOf={nameOf} />
+ {series.length > 0 && (
+ <div className="hidden shrink-0 md:block">
+ <ScoreSparkline values={series} label={S.benchmark.sparklineLabel(series.length)} />
</div>
)}
- <ScoreTrendChart evaluations={evaluations} series={series} />
- </div>
- );
-}
-
-const CELL = "px-3 py-2";
-
-/** One evaluation record: main row + a sub-table of per-Case scores that expands on click. */
-function EvaluationRow({
- evaluation,
- caseTitles,
- onOpenCase,
- currency,
-}: {
- evaluation: BenchmarkEvaluation;
- caseTitles: ReadonlyMap<string, string>;
- onOpenCase: (caseId: string) => void;
- currency: Currency;
-}) {
- const [open, setOpen] = useState(false);
- return (
- <>
- <tr
- onClick={() => setOpen((v) => !v)}
- className="cursor-pointer border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40"
- >
- <td className={CELL}>
- <span className="flex items-center gap-1.5 text-xs">
- <Chevron open={open} size={12} className="text-gray-400" />
- {formatDateTime(evaluation.time)}
+ <div className="w-16 shrink-0 text-right">
+ {latest ? (
+ <>
+ <span
+ className="block font-mono text-sm font-semibold tabular-nums"
+ title={S.benchmark.latestScoreLabel}
+ >
+ {formatScore(latest.score)}
+ </span>
+ <span className={`block truncate text-[11px] tabular-nums ${deltaTone(latest.delta)}`}>
+ {latest.delta === null
+ ? S.benchmark.firstEvaluation
+ : latest.delta === 0
+ ? "0"
+ : signedDelta(formatScore(latest.delta))}
+ </span>
+ </>
+ ) : (
+ <span className="block text-xs text-gray-400 dark:text-gray-500">
+ {S.benchmark.notEvaluated}
</span>
- </td>
- <td className={`${CELL} font-mono text-xs text-gray-500 dark:text-gray-400`}>
- {evaluation.version !== undefined ? `v${evaluation.version}` : "—"}
- </td>
- <td
- className={`${CELL} max-w-40 truncate font-mono text-xs text-gray-500 dark:text-gray-400`}
- title={evaluation.provider}
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {/* One dialog behind "Use", opened on its Evaluate tab: evaluating an agent is what a
+ Benchmark is for, and optimizing it is the tab next door. */}
+ <Button size="sm" variant="primary" onClick={onUse} disabled={masked}>
+ {S.benchmark.use}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onOpen} disabled={masked}>
+ {S.benchmark.view}
+ </Button>
+ {canDelete && (
+ <Button
+ size="icon"
+ variant="danger"
+ title={S.benchmark.deleteBenchmark}
+ aria-label={S.benchmark.deleteBenchmark}
+ onClick={onDelete}
+ className={masked ? "relative z-10" : undefined}
+ >
+ <GlyphIcon d={TRASH_ICON} size={ICON_SIZE.iconButton} />
+ </Button>
+ )}
+ </div>
+ {masked && (
+ <div
+ role="note"
+ title={failed ? S.benchmark.creationFailedHint : S.benchmark.buildingHint}
+ className="absolute inset-0 flex cursor-not-allowed flex-col items-center justify-center gap-1 rounded-md bg-white/75 px-4 text-center backdrop-blur-[1px] dark:bg-gray-900/75"
>
- {evaluation.modelId}
- </td>
- <td className={`${CELL} font-mono text-xs text-gray-500 dark:text-gray-400`}>
- {evaluation.thinkingLevel}
- </td>
- <td className={`${CELL} font-mono text-xs font-semibold tabular-nums`}>
- {formatScore(evaluation.score)}
- </td>
- <td className={`${CELL} font-mono text-xs tabular-nums text-gray-500 dark:text-gray-400`}>
- {formatMoney(evaluation.cost, currency)}
- </td>
- <td className={`${CELL} font-mono text-xs tabular-nums text-gray-500 dark:text-gray-400`}>
- {evaluation.durationMs !== undefined ? humanizeDuration(evaluation.durationMs) : "—"}
- </td>
- </tr>
- {open && (
- <tr className="border-b border-gray-100 last:border-b-0 dark:border-gray-800/60">
- <td colSpan={7} className="bg-gray-50/80 px-3 py-2 dark:bg-gray-950/40">
- {/* Evaluation summary title and body are displayed separately when present. */}
- {(evaluation.summaryTitle || evaluation.summary) && (
- <div className="mb-2">
- {evaluation.summaryTitle ? (
- <p className="text-xs font-semibold text-gray-700 dark:text-gray-200">
- {evaluation.summaryTitle}
- </p>
- ) : (
- <p className="text-xs font-semibold text-gray-500">{S.benchmark.summaryLabel}</p>
- )}
- {evaluation.summary && (
- <p className="mt-0.5 whitespace-pre-wrap text-xs text-gray-600 dark:text-gray-300">
- {evaluation.summary}
- </p>
- )}
- </div>
- )}
- <table className="w-full text-left">
- <thead>
- <tr className="text-xs text-gray-500">
- <th className="px-2 py-1 font-medium">{S.benchmark.colCase}</th>
- <th className="px-2 py-1 font-medium">{S.benchmark.colScore}</th>
- <th className="px-2 py-1 font-medium">{S.common.cost}</th>
- <th className="px-2 py-1 font-medium">{S.benchmark.colDuration}</th>
- <th className="px-2 py-1 font-medium">{S.benchmark.colSession}</th>
- </tr>
- </thead>
- <tbody>
- {evaluation.cases.map((c) => (
- <CaseRow
- key={c.case}
- caseScore={c}
- title={caseTitles.get(c.case)}
- onOpenCase={caseTitles.has(c.case) ? onOpenCase : undefined}
- currency={currency}
- />
- ))}
- </tbody>
- </table>
- </td>
- </tr>
- )}
- </>
- );
-}
-
-/**
- * Session id, for correlating a Run with what the side panel shows. It used to deep-link into the
- * Traces page; reading a Trace is now the side panel's job alone, so this is identification only.
- */
-function SessionCell({ sessionId }: { sessionId?: string }) {
- if (!sessionId) return <span className="text-gray-400">—</span>;
- return (
- <span className="font-mono text-gray-600 dark:text-gray-300" title={sessionId}>
- {sessionId}
- </span>
- );
-}
-
-/**
- * Score row for one Case: stored Case averages are authoritative. Expanding shows raw Run
- * results; the UI never recomputes averages.
- */
-function CaseRow({
- caseScore: c,
- title,
- onOpenCase,
- currency,
-}: {
- caseScore: BenchmarkCaseScore;
- title?: string;
- onOpenCase?: (caseId: string) => void;
- currency: Currency;
-}) {
- const [open, setOpen] = useState(false);
- const runs = c.runs;
- return (
- <>
- <tr
- onClick={() => setOpen((v) => !v)}
- className="cursor-pointer text-xs transition-colors duration-150 hover:bg-gray-100/70 dark:hover:bg-gray-800/40"
- >
- <td className="px-2 py-1">
- <span className="flex items-start gap-1.5">
- <Chevron open={open} size={12} className="text-gray-400" />
- <span className="min-w-0">
- {onOpenCase ? (
- <button
- type="button"
- className="block text-left font-medium text-gray-800 hover:underline dark:text-gray-200"
- onClick={(event) => {
- event.stopPropagation();
- onOpenCase(c.case);
- }}
- >
- {title ?? c.case}
- </button>
- ) : (
- <span className="block font-medium text-gray-800 dark:text-gray-200">
- {title ?? c.case}
- </span>
- )}
- {title && title !== c.case && (
- <span className="block font-mono text-[11px] text-gray-400">{c.case}</span>
- )}
- </span>
+ {/* A failed creation is the one thing here the user has to act on, so its title takes
+ the danger ink; the line under it stays secondary text either way. */}
+ <span
+ className={`text-sm font-medium ${failed ? toneInk.danger : "text-gray-700 dark:text-gray-200"}`}
+ >
+ {failed ? S.benchmark.creationFailed : S.benchmark.building}
</span>
- </td>
- <td className="px-2 py-1 font-mono tabular-nums">{formatScore(c.score)}</td>
- <td className="px-2 py-1 font-mono tabular-nums text-gray-500 dark:text-gray-400">
- {formatMoney(c.cost, currency)}
- </td>
- <td className="px-2 py-1 font-mono tabular-nums text-gray-500 dark:text-gray-400">
- {c.durationMs !== undefined ? humanizeDuration(c.durationMs) : "—"}
- </td>
- <td className="px-2 py-1">
- <span className="text-gray-400">—</span>
- </td>
- </tr>
- {open &&
- runs.map((run, i) => (
- <tr key={i} className="text-xs text-gray-500 dark:text-gray-400">
- {/* Indented run index row: #1, #2, ... (case-level metrics are their average) */}
- <td className="py-1 pl-7 pr-2 font-mono">
- {S.benchmark.colRun} #{i + 1}
- </td>
- <td className="px-2 py-1 font-mono tabular-nums">{formatScore(run.score)}</td>
- <td className="px-2 py-1 font-mono tabular-nums">{formatMoney(run.cost, currency)}</td>
- <td className="px-2 py-1 font-mono tabular-nums">
- {run.durationMs !== undefined ? humanizeDuration(run.durationMs) : "—"}
- </td>
- <td className="px-2 py-1">
- <SessionCell {...(run.sessionId ? { sessionId: run.sessionId } : {})} />
- </td>
- </tr>
- ))}
- </>
+ <span className="text-xs text-gray-500 dark:text-gray-400">
+ {failed ? S.benchmark.creationFailedHint : S.benchmark.buildingHint}
+ </span>
+ </div>
+ )}
+ </div>
);
}
-function CasesSection({
- cases,
- error,
- onOpenCase,
-}: {
- cases: BenchmarkCaseSummary[] | null;
- error: string | null;
- onOpenCase: (caseId: string) => void;
-}) {
+/** Card-shaped placeholders, so nothing shifts when the fetch lands. */
+function CardSkeletons({ rows }: { rows: number }) {
return (
- <div>
- <p className="mb-1 text-xs font-semibold text-gray-500">{S.benchmark.cases}</p>
- <div className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
- {error && <p className="px-3 py-2 text-xs text-red-500">{error}</p>}
- {!cases && !error && <p className="px-3 py-2 text-xs text-gray-400">{S.common.loading}</p>}
- {cases?.map((item) => {
- return (
- <button
- key={item.id}
- type="button"
- onClick={() => onOpenCase(item.id)}
- className="flex w-full items-center gap-3 border-b border-gray-100 px-3 py-2 text-left transition-colors last:border-b-0 hover:bg-gray-50 dark:border-gray-800/70 dark:hover:bg-gray-800/50"
- >
- <span className="min-w-0 flex-1">
- <span className="block text-sm font-medium text-gray-800 dark:text-gray-200">
- {item.title}
- </span>
- <span className="block truncate font-mono text-[11px] text-gray-400">
- {item.id}
- </span>
- </span>
- {/* Styled as the quiet gray action the Workspace download link is, not as a
- link: the row itself is the button, so an accent-colored label here read as
- a second, separately clickable target. Hover feedback comes from the row. */}
- <span className="shrink-0 rounded-md px-2.5 py-1 text-xs font-medium text-gray-600 dark:text-gray-300">
- {S.benchmark.viewCase}
- </span>
- </button>
- );
- })}
- </div>
+ <div className="space-y-3">
+ {Array.from({ length: rows }, (_, i) => (
+ <SkeletonCard key={i} className="flex flex-wrap items-center gap-x-6 gap-y-2 px-5 py-4">
+ <div className="min-w-[14rem] flex-1">
+ <Skeleton className="h-[18px] w-40" />
+ <Skeleton className="mt-1.5 h-4 w-2/3" />
+ <Skeleton className="mt-1.5 h-4 w-48" />
+ </div>
+ <Skeleton className="hidden h-9 w-24 md:block" />
+ <Skeleton className="h-8 w-44" />
+ </SkeletonCard>
+ ))}
</div>
);
}
export function BenchmarkPage() {
useDocumentTitle(S.benchmark.title);
- const { currentProject, agents, agentsLoading } = useProject();
- const { currency } = useTheme();
+ const navigate = useNavigate();
+ const { currentProject, currentAgent, agents } = useProject();
+ const { locale } = useLocale();
const projectId = currentProject?.projectId ?? null;
- // ?agentId= deep link (entered from the "Benchmark" tab on the Agent settings page): only the target Agent is expanded by default.
- const [searchParams] = useSearchParams();
- const focusAgentId = searchParams.get("agentId");
- const [selection, setSelection] = useState<Selection | null>(null);
- const [caseStatements, setCaseStatements] = useState<BenchmarkCaseSummary[] | null>(null);
- const [caseError, setCaseError] = useState<string | null>(null);
- const [openCaseId, setOpenCaseId] = useState<string | null>(null);
+ const isOwner = currentProject?.role === "owner";
+ // ?agentId= (entered from an Agent): the list narrows to the Benchmarks that tested it.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const filterAgentId = searchParams.get("agentId");
- // Clear the selection when the Project changes.
- useEffect(() => {
- setSelection(null);
- }, [projectId]);
+ const [benchmarks, setBenchmarks] = useState<BenchmarkSummary[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [query, setQuery] = useState("");
+ const [models, setModels] = useState<ModelsResponse | null>(null);
+ const [aiOpen, setAiOpen] = useState(false);
+ const [aiTarget, setAiTarget] = useState("");
+ const [manualOpen, setManualOpen] = useState(false);
+ /** The Benchmark whose Use dialog is open, if any. */
+ const [using, setUsing] = useState<string | null>(null);
+ const [deleting, setDeleting] = useState<string | null>(null);
+ const [deleteBusy, setDeleteBusy] = useState(false);
+ // Benchmarks belong to the Project, so the page reads one list — and a Project change starts
+ // it over rather than showing the previous Project's cards while the next list is in flight.
useEffect(() => {
- setCaseStatements(null);
- setCaseError(null);
- setOpenCaseId(null);
- if (!projectId || !selection) return;
+ if (!projectId) return;
let cancelled = false;
+ setBenchmarks(null);
+ setError(null);
api
- .listBenchmarkCases(projectId, selection.agentId, selection.benchmark.id)
+ .listBenchmarks(projectId)
.then((data) => {
- if (!cancelled) setCaseStatements(data.cases);
+ if (!cancelled) setBenchmarks(data.benchmarks);
})
- .catch((error: unknown) => {
- if (!cancelled) setCaseError(apiErrorText(error));
+ .catch((e: unknown) => {
+ if (!cancelled) setError(apiErrorText(e));
});
return () => {
cancelled = true;
};
- }, [projectId, selection]);
+ }, [projectId]);
+
+ // The Project's models, for the Use dialog's conversation-model picker; a failure just
+ // leaves the picker at the Project default.
+ useEffect(() => {
+ if (!projectId) return;
+ let cancelled = false;
+ api
+ .getModels(projectId)
+ .then((res) => {
+ if (!cancelled) setModels(res);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId]);
if (!projectId) return null;
- const bm = selection?.benchmark ?? null;
- // The Scoreboard append order is the evaluation sequence. Preserve it even when a malformed
- // timestamp would otherwise reorder Agent versions; the detail table shows that sequence newest first.
- const evaluations = bm ? [...bm.evaluations] : [];
- const caseTitles = new Map(caseStatements?.map((item) => [item.id, item.title]) ?? []);
- const openCase = caseStatements?.find((item) => item.id === openCaseId) ?? null;
+ const agentOf = (agentId: string): AgentSummary | undefined =>
+ agents.find((a) => a.agentId === agentId);
+ const nameOf = (agentId: string): string => {
+ const agent = agentOf(agentId);
+ return agent ? agentDisplayName(agent) : agentId;
+ };
+
+ const fallbackAgent = currentAgent?.agentId ?? pickDefaultAgent(agents)?.agentId ?? "";
+ const openAi = () => {
+ setAiTarget(filterAgentId ?? fallbackAgent);
+ setAiOpen(true);
+ };
+ const open = (benchmarkId: string) => navigate(benchmarkRoute(benchmarkId));
+ const clearAgentFilter = () =>
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete("agentId");
+ return next;
+ },
+ { replace: true },
+ );
- return (
- <div className="flex h-full flex-col md:flex-row">
- {/* Directory tree: Agent -> Benchmark (left column on >=md; collapsible top area on <md) */}
- <aside className="max-h-52 shrink-0 overflow-y-auto border-b border-gray-200 bg-gray-50 px-1 py-2 md:max-h-none md:w-72 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-900">
- <p className="px-3 pb-1 text-xs font-bold uppercase tracking-wide text-gray-500">
- {S.benchmark.title}
- </p>
- {agentsLoading ? (
- <SkeletonList rows={4} />
- ) : (
- <ul>
- {agents.map((a) => (
- <AgentNode
- key={a.agentId}
- projectId={projectId}
- agentId={a.agentId}
- name={agentDisplayName(a)}
- defaultOpen={focusAgentId === null || focusAgentId === a.agentId}
- selection={selection}
- onSelect={setSelection}
- />
- ))}
- </ul>
- )}
- </aside>
+ const benchmarkOf = (benchmarkId: string | null): BenchmarkSummary | null =>
+ benchmarkId === null ? null : (benchmarks?.find((b) => b.id === benchmarkId) ?? null);
+ const usingBenchmark = benchmarkOf(using);
+ const deletingBenchmark = benchmarkOf(deleting);
- <section className="min-w-0 flex-1 overflow-y-auto p-3 md:p-4">
- {selection && bm ? (
- // Changing the key on Benchmark switch resets expand state (a detail row's open doesn't linger across Benchmarks).
- <div key={`${selection.agentId}/${bm.id}`} className="mx-auto max-w-4xl space-y-4">
- {/* Runtime belongs to each Evaluation and is shown in the detail table. */}
- <div>
- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
- <h1 className="min-w-0 truncate text-lg font-semibold">{bm.title}</h1>
- <span className="text-xs text-gray-500">{S.benchmark.caseCount(bm.caseCount)}</span>
- </div>
- {bm.description && (
- <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{bm.description}</p>
- )}
- </div>
+ const confirmDelete = async () => {
+ if (deleting === null) return;
+ const benchmarkId = deleting;
+ setDeleteBusy(true);
+ try {
+ await api.deleteBenchmark(projectId, benchmarkId);
+ toastSuccess(S.benchmark.deleted);
+ setBenchmarks((prev) => (prev ?? []).filter((b) => b.id !== benchmarkId));
+ setDeleting(null);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setDeleteBusy(false);
+ }
+ };
- <CasesSection cases={caseStatements} error={caseError} onOpenCase={setOpenCaseId} />
+ const rows = (benchmarks ?? [])
+ .filter((b) => filterAgentId === null || b.agentIds.includes(filterAgentId))
+ .filter((b) => matchesBenchmarkQuery(b, agents, query));
- {evaluations.length === 0 ? (
- <EmptyState title={S.benchmark.noEvaluations} />
- ) : (
- <>
- <TrendSection evaluations={evaluations} />
+ let body;
+ if (error !== null) {
+ body = <p className={`px-1 text-xs ${toneInk.danger}`}>{error}</p>;
+ } else if (benchmarks === null) {
+ body = <CardSkeletons rows={4} />;
+ } else if (benchmarks.length === 0) {
+ body = (
+ <EmptyState
+ title={S.benchmark.emptyTitle}
+ description={S.benchmark.emptyDescription}
+ action={<CreateButtons size="sm" onAi={openAi} onManual={() => setManualOpen(true)} />}
+ />
+ );
+ } else if (rows.length === 0) {
+ body = <EmptyState title={S.benchmark.noMatches} />;
+ } else {
+ body = (
+ <div className="space-y-3">
+ {rows.map((b) => (
+ <BenchmarkCard
+ key={b.id}
+ benchmark={b}
+ locale={locale}
+ nameOf={nameOf}
+ canDelete={isOwner}
+ onOpen={() => open(b.id)}
+ onUse={() => setUsing(b.id)}
+ onDelete={() => setDeleting(b.id)}
+ />
+ ))}
+ </div>
+ );
+ }
- <div>
- <p className="mb-1 text-xs font-semibold text-gray-500">
- {S.benchmark.evaluations}
- </p>
- <div className="overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
- <table className="w-full min-w-[720px] text-left text-sm">
- <thead>
- <tr className="border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900">
- <th className="px-3 py-2.5">{S.common.time}</th>
- <th className="px-3 py-2.5">{S.benchmark.colVersion}</th>
- <th className="px-3 py-2.5">{S.benchmark.colModel}</th>
- <th className="px-3 py-2.5">{S.benchmark.colThinkingLevel}</th>
- <th className="px-3 py-2.5">{S.benchmark.colScore}</th>
- <th className="px-3 py-2.5">{S.common.cost}</th>
- <th className="px-3 py-2.5">{S.benchmark.colDuration}</th>
- </tr>
- </thead>
- <tbody>
- {[...evaluations].reverse().map((ev, i) => (
- <EvaluationRow
- key={i}
- evaluation={ev}
- caseTitles={caseTitles}
- onOpenCase={setOpenCaseId}
- currency={currency}
- />
- ))}
- </tbody>
- </table>
- </div>
- </div>
- </>
- )}
- {openCase && (
- <Modal
- open
- title={openCase.title}
- widthClass="sm:max-w-6xl"
- onClose={() => setOpenCaseId(null)}
- >
- <BenchmarkCaseBrowser
- projectId={projectId}
- agentId={selection.agentId}
- benchmarkId={bm.id}
- caseSummary={openCase}
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <div className="mx-auto max-w-5xl">
+ {/* The title row, the intro block and the step cards share one block, so the gap below
+ stays one gap — the Agents and Models headers have the same shape. */}
+ <div className="mb-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h1 className="text-xl font-semibold">{S.benchmark.title}</h1>
+ {/* Search plus the two create entry points. Below sm the search box takes a line of
+ its own and the pair of buttons wraps under it: three controls sharing a phone's
+ width would leave the box too narrow to read what was typed into it. */}
+ <div className="flex min-w-0 max-w-full grow flex-wrap items-center gap-2 sm:grow-0">
+ <div className="w-full min-w-0 sm:w-56 sm:flex-none">
+ <Input
+ size="sm"
+ aria-label={S.benchmark.searchPlaceholder}
+ placeholder={S.benchmark.searchPlaceholder}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
/>
- </Modal>
- )}
+ </div>
+ <CreateButtons size="sm" onAi={openAi} onManual={() => setManualOpen(true)} />
+ </div>
+ </div>
+ <GuideSteps />
+ </div>
+
+ {/* What the address is filtering by, and the way out of it: the list is narrowed by a
+ query parameter, which nothing else on the page would otherwise account for. */}
+ {filterAgentId !== null && (
+ <div className="mb-3 flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
+ <AgentAvatar
+ id={filterAgentId}
+ name={nameOf(filterAgentId)}
+ size={ICON_SIZE.rowLead}
+ className="shrink-0 rounded"
+ />
+ <span className="min-w-0 truncate" title={nameOf(filterAgentId)}>
+ {S.benchmark.filterByAgent(filterAgentId)}
+ </span>
+ <Button size="sm" variant="ghost" onClick={clearAgentFilter}>
+ {S.benchmark.clearFilter}
+ </Button>
</div>
- ) : (
- <EmptyState title={S.benchmark.selectBenchmark} />
)}
- </section>
+
+ {body}
+ </div>
+
+ <AiCreateModal
+ open={aiOpen}
+ onClose={() => setAiOpen(false)}
+ title={S.benchmark.aiCreateTitle}
+ description={S.benchmark.aiCreateDescription}
+ agents={agents}
+ examples={benchmarkCreateExamples()}
+ {...(aiTarget !== "" ? { tail: benchmarkCreateTail(aiTarget) } : {})}
+ intro={
+ <Select
+ size="sm"
+ label={S.benchmark.targetAgent}
+ hint={S.benchmark.targetAgentHint}
+ value={aiTarget}
+ onChange={(e) => setAiTarget(e.target.value)}
+ >
+ {agents.map((a) => (
+ <option key={a.agentId} value={a.agentId}>
+ {agentDisplayName(a)}
+ </option>
+ ))}
+ </Select>
+ }
+ />
+ <CreateBenchmarkModal
+ open={manualOpen}
+ onClose={() => setManualOpen(false)}
+ projectId={projectId}
+ onCreated={(benchmark) => open(benchmark.id)}
+ />
+ {usingBenchmark && (
+ <UseBenchmarkModal
+ key={usingBenchmark.id}
+ open
+ onClose={() => setUsing(null)}
+ projectId={projectId}
+ benchmark={usingBenchmark}
+ agents={agents}
+ models={models}
+ initialTab="evaluate"
+ />
+ )}
+ <ConfirmModal
+ open={deleting !== null}
+ title={S.benchmark.deleteBenchmark}
+ onClose={() => setDeleting(null)}
+ onConfirm={() => void confirmDelete()}
+ confirmLabel={S.common.delete}
+ busy={deleteBusy}
+ >
+ <p className="text-sm text-gray-700 dark:text-gray-200">
+ {S.benchmark.deleteConfirm(deletingBenchmark?.title ?? deleting ?? "")}
+ </p>
+ </ConfirmModal>
</div>
);
}
diff --git a/packages/web/src/features/benchmark/benchmark-prompts.ts b/packages/web/src/features/benchmark/benchmark-prompts.ts
new file mode 100644
index 00000000..d3314e5c
--- /dev/null
+++ b/packages/web/src/features/benchmark/benchmark-prompts.ts
@@ -0,0 +1,174 @@
+/**
+ * The prompts the Evaluation Center sends through the "Create with AI" bridge, and the small
+ * id helpers of its manual form. Every prompt ends in a fixed tail that names the Skill to use
+ * and the parameters it requires — the Test Agent, the Benchmark id, run and round counts, the
+ * target score — so a novice's one-line wish arrives as a request the Skill can act on without
+ * asking anything back. The two "Ask AI" tails are the same shape pointed the other way: they
+ * name no Skill and ask for no change, carrying the facts already on screen — an evaluation's
+ * scores and Session ids, or a case's two material paths — so the answer is read out of the
+ * files rather than guessed. The wording lives in the dictionaries; this module only assembles it.
+ */
+import { S } from "../../lib/strings";
+import { composeAiPrompt } from "../ai-create/ai-create-prompt";
+import type { AiExample } from "../ai-create/ai-create-panel";
+
+/** Directory names and Benchmark ids share the Agent id alphabet. */
+export const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
+
+/**
+ * Upper bound on runs per case, matched by the create route: every run is one evaluation of the
+ * Test Agent, so the count multiplies the cost of each evaluation and optimization round. The
+ * Use dialog refuses anything beyond it, so a Benchmark must not be created above it either.
+ */
+export const MAX_RUNS = 1000;
+
+/** A digits-only runs field within [1, MAX_RUNS]. */
+export function isValidRuns(raw: string): boolean {
+ if (!/^\d+$/.test(raw)) return false;
+ const n = Number.parseInt(raw, 10);
+ return n >= 1 && n <= MAX_RUNS;
+}
+
+/** What the New Benchmark dialog's tail asks the `benchmark-design` Skill to do for a tested Agent. */
+export function benchmarkCreateTail(targetAgentId: string): string {
+ return S.benchmark.aiCreateTail(targetAgentId);
+}
+
+export function benchmarkCreateExamples(): AiExample[] {
+ return Object.entries(S.benchmark.aiCreateExamples).map(([key, ex]) => ({
+ key,
+ label: ex.label,
+ description: ex.description,
+ prompt: ex.prompt,
+ }));
+}
+
+/** The parameters the `agent-evaluation` Skill requires, as the Evaluate tab collects them. */
+export interface EvaluateParams {
+ /** The Agent under test: the one the matrix is run against, picked in the dialog. */
+ targetAgentId: string;
+ benchmarkId: string;
+ /** Runs per case; the matrix is Case x runs. */
+ runs: number;
+}
+
+export function evaluateTail(params: EvaluateParams): string {
+ return S.benchmark.evaluateTail(params);
+}
+
+/** The whole Evaluate prompt: the optional note first, then the parameter tail. */
+export function buildEvaluatePrompt(note: string, params: EvaluateParams): string {
+ return composeAiPrompt(note, evaluateTail(params));
+}
+
+/** The parameters the `agent-optimization` Skill requires, as the Optimize tab collects them. */
+export interface OptimizeParams {
+ /** The Agent under test: the one the optimizer edits, picked in the dialog. */
+ targetAgentId: string;
+ benchmarkId: string;
+ /** Runs per case for every Candidate. */
+ runs: number;
+ /** Complete valid Candidate rounds before the optimizer stops. */
+ roundLimit: number;
+ /** Reaching it ends the loop early. */
+ targetScore: number;
+}
+
+export function optimizeTail(params: OptimizeParams): string {
+ return S.benchmark.optimizeTail(params);
+}
+
+/** The whole Optimize prompt: the optional focus text first, then the parameter tail. */
+export function buildOptimizePrompt(focus: string, params: OptimizeParams): string {
+ return composeAiPrompt(focus, optimizeTail(params));
+}
+
+/** One case's line in the evaluation question: as the dialog prints it, plus every run's Session id. */
+export interface AskEvaluationCase {
+ /** The case directory name. */
+ id: string;
+ score: string;
+ cost: string;
+ duration: string;
+ /** Session id per run, in run order; empty when no run recorded one. */
+ sessionIds: string[];
+}
+
+/**
+ * The facts the evaluation dialog's question carries. Scores, costs and durations arrive
+ * already formatted, exactly as the dialog prints them: the display currency and the duration
+ * units are the reader's own settings, and a prompt quoting raw numbers would disagree with the
+ * screen it was asked from. An absent summary is "", never a placeholder sentence.
+ */
+export interface AskEvaluationParams {
+ benchmarkId: string;
+ time: string;
+ /** The series label text, or the unlabeled placeholder the legend uses. */
+ label: string;
+ version: number;
+ provider: string;
+ modelId: string;
+ thinkingLevel: string;
+ score: string;
+ cost: string;
+ duration: string;
+ summaryTitle: string;
+ summary: string;
+ cases: AskEvaluationCase[];
+}
+
+export function askEvaluationTail(params: AskEvaluationParams): string {
+ return S.benchmark.askEvaluationTail(params);
+}
+
+/** The canned questions of the evaluation dialog's Ask AI panel, the default question first — the box opens on it, and the leading button is how a reader gets back to it after trying another. */
+export function askEvaluationExamples(): AiExample[] {
+ return Object.entries(S.benchmark.askEvaluationExamples).map(([key, ex]) => ({
+ key,
+ label: ex.label,
+ prompt: ex.prompt,
+ }));
+}
+
+/** The facts the case dialog's question carries; formatted values as above. */
+export interface AskCaseParams {
+ benchmarkId: string;
+ caseId: string;
+ /** This case's results in the newest evaluation; null when the Benchmark has none yet. */
+ latest: { time: string; score: string; runs: { score: string; sessionId: string }[] } | null;
+}
+
+export function askCaseTail(params: AskCaseParams): string {
+ return S.benchmark.askCaseTail(params);
+}
+
+/** The canned questions of the case dialog's Ask AI panel, the default question first (see askEvaluationExamples). */
+export function askCaseExamples(): AiExample[] {
+ return Object.entries(S.benchmark.askCaseExamples).map(([key, ex]) => ({
+ key,
+ label: ex.label,
+ prompt: ex.prompt,
+ }));
+}
+
+/** A Benchmark's directory relative to the Project's App Data Dir — beside `agents/`, not under one. */
+export function benchmarkPath(benchmarkId: string): string {
+ return `benchmarks/${benchmarkId}`;
+}
+
+/**
+ * A directory-name proposal from a title: ASCII letters and digits kept (lowercased), any run
+ * of other characters folded into one hyphen, edges trimmed. A title with no ASCII word — a
+ * Chinese one — yields "", and the form then asks for an id outright.
+ */
+export function slugFromTitle(title: string): string {
+ return title
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+}
+
+/** `CASE-NNN-<slug>`: the case directory name from its 1-based position and slug. */
+export function caseId(index: number, slug: string): string {
+ return `CASE-${String(index).padStart(3, "0")}-${slug}`;
+}
diff --git a/packages/web/src/features/benchmark/benchmark-route.ts b/packages/web/src/features/benchmark/benchmark-route.ts
new file mode 100644
index 00000000..37cf1dd8
--- /dev/null
+++ b/packages/web/src/features/benchmark/benchmark-route.ts
@@ -0,0 +1,6 @@
+/**
+ * Where one Benchmark's page lives. A Benchmark belongs to the Project rather than to an Agent,
+ * so its directory name alone identifies it, and the list and the router read one spelling of it.
+ */
+export const benchmarkRoute = (benchmarkId: string): string =>
+ `/benchmark/${encodeURIComponent(benchmarkId)}`;
diff --git a/packages/web/src/features/benchmark/create-benchmark-modal.tsx b/packages/web/src/features/benchmark/create-benchmark-modal.tsx
new file mode 100644
index 00000000..91fccc04
--- /dev/null
+++ b/packages/web/src/features/benchmark/create-benchmark-modal.tsx
@@ -0,0 +1,298 @@
+/**
+ * The manual New Benchmark form: title, id, description, runs per case and a list of cases, each
+ * a statement and a rubric. No Agent is chosen here — a Benchmark belongs to the Project and
+ * records the Agent it tested on each evaluation instead. The server writes the on-disk layout;
+ * the form keeps a first-timer on the rails — format hints stay visible while typing, and the
+ * semantics (what a rubric is, why it never reaches the tested agent, what makes one
+ * discriminating) sit behind the "?" marks. Mounted fresh on every open.
+ */
+import { useRef, useState } from "react";
+import type { BenchmarkSummary } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk } from "../../lib/tone";
+import { Button } from "../../components/ui/button";
+import { FieldLabel } from "../../components/ui/field";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { PlusIcon } from "../../components/ui/icons";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { Input, Textarea } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
+import { TRASH_ICON } from "../../components/ui/session-row-menu";
+import { toastSuccess } from "../../components/ui/toast";
+import { ID_PATTERN, caseId, isValidRuns, slugFromTitle } from "./benchmark-prompts";
+
+interface CaseDraft {
+ /** Stable React key, independent of position, so removing a case keeps the others' state. */
+ key: number;
+ slug: string;
+ title: string;
+ statement: string;
+ rubric: string;
+}
+
+type CaseErrors = Partial<Record<"slug" | "title" | "statement" | "rubric", string>>;
+
+interface FormErrors {
+ id?: string;
+ title?: string;
+ runs?: string;
+ /** Keyed by CaseDraft.key, not by position: removing a case must not move another one's errors onto it. */
+ cases: Record<number, CaseErrors>;
+}
+
+export interface CreateBenchmarkModalProps {
+ open: boolean;
+ onClose: () => void;
+ projectId: string;
+ onCreated: (benchmark: BenchmarkSummary) => void;
+}
+
+export function CreateBenchmarkModal(props: CreateBenchmarkModalProps) {
+ return props.open ? <CreateBenchmarkDialog {...props} /> : null;
+}
+
+const digits = (v: string) => v.replace(/[^\d]/g, "");
+/** Spreads an error message into a field only when there is one (an explicit undefined is not an absent prop). */
+const errorProp = (message: string | undefined) =>
+ message !== undefined ? { error: message } : {};
+
+function CreateBenchmarkDialog({ onClose, projectId, onCreated }: CreateBenchmarkModalProps) {
+ const keyRef = useRef(0);
+ const newCase = (): CaseDraft => ({
+ key: keyRef.current++,
+ slug: "",
+ title: "",
+ statement: "",
+ rubric: "",
+ });
+ const [title, setTitle] = useState("");
+ const [id, setId] = useState("");
+ // The id follows the title until it is edited by hand.
+ const [idTouched, setIdTouched] = useState(false);
+ const [description, setDescription] = useState("");
+ const [runs, setRuns] = useState("1");
+ const [cases, setCases] = useState<CaseDraft[]>(() => [newCase()]);
+ const [errors, setErrors] = useState<FormErrors>({ cases: {} });
+ const [busy, setBusy] = useState(false);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+
+ const updateCase = (key: number, patch: Partial<CaseDraft>) =>
+ setCases((prev) => prev.map((c) => (c.key === key ? { ...c, ...patch } : c)));
+
+ const validate = (): FormErrors => {
+ const next: FormErrors = { cases: {} };
+ if (title.trim() === "") next.title = S.common.requiredField;
+ if (id.trim() === "") next.id = S.common.requiredField;
+ else if (!ID_PATTERN.test(id.trim())) next.id = S.benchmark.invalidId;
+ if (!isValidRuns(runs)) next.runs = S.benchmark.invalidRuns;
+ for (const c of cases) {
+ const e: CaseErrors = {};
+ if (c.slug.trim() === "") e.slug = S.common.requiredField;
+ else if (!ID_PATTERN.test(c.slug.trim())) e.slug = S.benchmark.invalidId;
+ if (c.title.trim() === "") e.title = S.common.requiredField;
+ if (c.statement.trim() === "") e.statement = S.common.requiredField;
+ if (c.rubric.trim() === "") e.rubric = S.common.requiredField;
+ next.cases[c.key] = e;
+ }
+ return next;
+ };
+ const hasErrors = (e: FormErrors) =>
+ e.id !== undefined ||
+ e.title !== undefined ||
+ e.runs !== undefined ||
+ Object.values(e.cases).some((c) => Object.keys(c).length > 0);
+
+ const submit = async () => {
+ const next = validate();
+ setErrors(next);
+ if (hasErrors(next)) return;
+ setBusy(true);
+ setSubmitError(null);
+ try {
+ const trimmedDescription = description.trim();
+ const res = await api.createBenchmark(projectId, {
+ id: id.trim(),
+ title: title.trim(),
+ ...(trimmedDescription !== "" ? { description: trimmedDescription } : {}),
+ runs: Number.parseInt(runs, 10),
+ cases: cases.map((c, i) => ({
+ id: caseId(i + 1, c.slug.trim()),
+ title: c.title.trim(),
+ statement: c.statement,
+ rubric: c.rubric,
+ })),
+ });
+ toastSuccess(S.benchmark.created);
+ onCreated(res.benchmark);
+ onClose();
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 409) {
+ setErrors((prev) => ({ ...prev, id: S.benchmark.idExists }));
+ } else {
+ setSubmitError(apiErrorText(e));
+ }
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open
+ title={S.benchmark.manualCreateTitle}
+ onClose={onClose}
+ widthClass="sm:max-w-2xl"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {busy ? S.common.saving : S.benchmark.createSubmit}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-4">
+ <p className="text-sm text-gray-600 dark:text-gray-300">{S.benchmark.manualCreateIntro}</p>
+ <Input
+ label={S.benchmark.titleField}
+ required
+ value={title}
+ onChange={(e) => {
+ setTitle(e.target.value);
+ if (!idTouched) setId(slugFromTitle(e.target.value));
+ }}
+ {...errorProp(errors.title)}
+ />
+ <Input
+ label={S.benchmark.idField}
+ hint={S.benchmark.idHint}
+ required
+ value={id}
+ className="font-mono"
+ onChange={(e) => {
+ setIdTouched(true);
+ setId(e.target.value);
+ }}
+ {...errorProp(errors.id)}
+ />
+ <Textarea
+ label={S.benchmark.descriptionField}
+ hint={S.benchmark.descriptionHint}
+ rows={2}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ <Input
+ label={S.benchmark.runsField}
+ hint={S.benchmark.runsHint}
+ info={S.benchmark.runsInfo}
+ infoLabel={S.benchmark.runsField}
+ inputMode="numeric"
+ value={runs}
+ onChange={(e) => setRuns(digits(e.target.value))}
+ {...errorProp(errors.runs)}
+ />
+
+ <div>
+ <div className="mb-2 flex items-center gap-1">
+ <FieldLabel block={false}>{S.benchmark.casesTitle}</FieldLabel>
+ <InfoPopover label={S.benchmark.casesTitle}>{S.benchmark.casesInfo}</InfoPopover>
+ </div>
+ <div className="space-y-3">
+ {cases.map((c, i) => {
+ const e = errors.cases[c.key] ?? {};
+ const dirName = caseId(i + 1, c.slug.trim() || "<slug>");
+ return (
+ <div
+ key={c.key}
+ className="rounded-md border border-gray-200 p-3 dark:border-gray-800"
+ >
+ <div className="mb-2 flex items-center gap-2">
+ <span className="text-xs font-semibold text-gray-600 dark:text-gray-300">
+ {S.benchmark.caseHeading(i + 1)}
+ </span>
+ <span className="min-w-0 flex-1 truncate font-mono text-[11px] text-gray-400">
+ {dirName}
+ </span>
+ {cases.length > 1 && (
+ <Button
+ size="icon"
+ variant="ghost"
+ title={S.benchmark.removeCase}
+ aria-label={S.benchmark.removeCase}
+ onClick={() => setCases((prev) => prev.filter((x) => x.key !== c.key))}
+ >
+ <GlyphIcon d={TRASH_ICON} size={ICON_SIZE.iconButton} />
+ </Button>
+ )}
+ </div>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <Input
+ size="sm"
+ label={S.benchmark.caseSlugField}
+ required
+ hint={S.benchmark.caseSlugHint(dirName)}
+ value={c.slug}
+ className="font-mono"
+ onChange={(event) => updateCase(c.key, { slug: event.target.value })}
+ {...errorProp(e.slug)}
+ />
+ <Input
+ size="sm"
+ label={S.benchmark.caseTitleField}
+ required
+ value={c.title}
+ onChange={(event) => updateCase(c.key, { title: event.target.value })}
+ {...errorProp(e.title)}
+ />
+ </div>
+ <div className="mt-3">
+ <Textarea
+ size="sm"
+ label={S.benchmark.caseStatementField}
+ required
+ hint={S.benchmark.caseStatementHint}
+ rows={4}
+ value={c.statement}
+ onChange={(event) => updateCase(c.key, { statement: event.target.value })}
+ {...errorProp(e.statement)}
+ />
+ </div>
+ <div className="mt-3">
+ <Textarea
+ size="sm"
+ label={S.benchmark.caseRubricField}
+ required
+ hint={S.benchmark.caseRubricHint}
+ info={S.benchmark.rubricInfo}
+ infoLabel={S.benchmark.caseRubricField}
+ rows={4}
+ value={c.rubric}
+ onChange={(event) => updateCase(c.key, { rubric: event.target.value })}
+ {...errorProp(e.rubric)}
+ />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ <Button
+ size="sm"
+ className="mt-2"
+ onClick={() => setCases((prev) => [...prev, newCase()])}
+ >
+ <PlusIcon />
+ {S.benchmark.addCase}
+ </Button>
+ </div>
+ {submitError !== null && <p className={`text-xs ${toneInk.danger}`}>{submitError}</p>}
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/benchmark/evaluation-detail-modal.tsx b/packages/web/src/features/benchmark/evaluation-detail-modal.tsx
new file mode 100644
index 00000000..68b3efb3
--- /dev/null
+++ b/packages/web/src/features/benchmark/evaluation-detail-modal.tsx
@@ -0,0 +1,295 @@
+/**
+ * One evaluation, in a dialog of its own — the same form the case dialog takes, because both
+ * are one row of a table opened up rather than a second table unfolded inside the first. It
+ * carries what the row could only summarize: the series this score belongs to, the Agent State
+ * version it tested (the version no longer splits a series, so this is where a reader finds
+ * it), the three stored metrics, the evaluation's own summary, and the per-case scores with the
+ * raw result of every Run and the Session it ran in. Nothing here is recomputed: every number
+ * is the one the scoreboard stores. Its footer asks the Project's default agent about the
+ * result instead of explaining it on screen, since the explanation lives in the Traces.
+ */
+import { useState } from "react";
+import type { BenchmarkCaseScore, BenchmarkEvaluation } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { formatDateTime, formatMoney, formatScore, humanizeDuration } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import type { Currency } from "../../state/theme";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
+import { Chevron } from "../../components/ui/chevron";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { MAGIC_WAND_ICON } from "../../components/ui/icons";
+import { Modal } from "../../components/ui/modal";
+import { AskAiModal } from "./ask-ai-modal";
+import { evaluationLabel } from "./benchmark-metrics";
+import { askEvaluationExamples, askEvaluationTail } from "./benchmark-prompts";
+import type { AskEvaluationParams } from "./benchmark-prompts";
+
+/** Session id, for correlating a Run with what the side panel shows: identification only, reading a Trace is the side panel's job. */
+function SessionCell({ sessionId }: { sessionId?: string }) {
+ if (!sessionId) return <span className="text-gray-400">—</span>;
+ return (
+ <span className="font-mono text-gray-600 dark:text-gray-300" title={sessionId}>
+ {sessionId}
+ </span>
+ );
+}
+
+/**
+ * Score row for one Case: stored Case averages are authoritative. Expanding shows raw Run
+ * results; the UI never recomputes averages.
+ */
+function CaseRow({
+ caseScore: c,
+ title,
+ onOpenCase,
+ currency,
+}: {
+ caseScore: BenchmarkCaseScore;
+ title?: string;
+ onOpenCase?: (caseId: string) => void;
+ currency: Currency;
+}) {
+ const [open, setOpen] = useState(false);
+ const runs = c.runs;
+ return (
+ <>
+ <tr
+ onClick={() => setOpen((v) => !v)}
+ className="cursor-pointer text-xs transition-colors duration-150 hover:bg-gray-100/70 dark:hover:bg-gray-800/40"
+ >
+ <td className="px-2 py-1">
+ <span className="flex items-start gap-1.5">
+ <Chevron open={open} size={12} className="text-gray-400" />
+ <span className="min-w-0">
+ {onOpenCase ? (
+ <button
+ type="button"
+ className="block text-left font-medium text-gray-800 hover:underline dark:text-gray-200"
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenCase(c.case);
+ }}
+ >
+ {title ?? c.case}
+ </button>
+ ) : (
+ <span className="block font-medium text-gray-800 dark:text-gray-200">
+ {title ?? c.case}
+ </span>
+ )}
+ {title && title !== c.case && (
+ <span className="block font-mono text-[11px] text-gray-400">{c.case}</span>
+ )}
+ </span>
+ </span>
+ </td>
+ <td className="px-2 py-1 font-mono tabular-nums">{formatScore(c.score)}</td>
+ <td className="px-2 py-1 font-mono tabular-nums text-gray-500 dark:text-gray-400">
+ {formatMoney(c.cost, currency)}
+ </td>
+ <td className="px-2 py-1 font-mono tabular-nums text-gray-500 dark:text-gray-400">
+ {c.durationMs !== undefined ? humanizeDuration(c.durationMs) : "—"}
+ </td>
+ <td className="px-2 py-1">
+ <span className="text-gray-400">—</span>
+ </td>
+ </tr>
+ {open &&
+ runs.map((run, i) => (
+ <tr key={i} className="text-xs text-gray-500 dark:text-gray-400">
+ {/* Indented run index row: #1, #2, ... (case-level metrics are their average) */}
+ <td className="py-1 pl-7 pr-2 font-mono">
+ {S.benchmark.colRun} #{i + 1}
+ </td>
+ <td className="px-2 py-1 font-mono tabular-nums">{formatScore(run.score)}</td>
+ <td className="px-2 py-1 font-mono tabular-nums">{formatMoney(run.cost, currency)}</td>
+ <td className="px-2 py-1 font-mono tabular-nums">
+ {run.durationMs !== undefined ? humanizeDuration(run.durationMs) : "—"}
+ </td>
+ <td className="px-2 py-1">
+ <SessionCell {...(run.sessionId ? { sessionId: run.sessionId } : {})} />
+ </td>
+ </tr>
+ ))}
+ </>
+ );
+}
+
+/** One of the three stored metrics: its name over its value, the Score carrying the weight. */
+function Metric({ label, value, strong }: { label: string; value: string; strong?: boolean }) {
+ return (
+ <span className="min-w-0">
+ <span className="block text-[11px] text-gray-500 dark:text-gray-400">{label}</span>
+ <span
+ className={`block font-mono text-xs tabular-nums ${strong ? "font-semibold" : "text-gray-600 dark:text-gray-300"}`}
+ >
+ {value}
+ </span>
+ </span>
+ );
+}
+
+/**
+ * What the "Ask AI" question carries: this evaluation's facts, formatted exactly as the dialog
+ * prints them, so the prompt and the screen it was asked from agree on every number.
+ */
+function askParams(
+ benchmarkId: string,
+ evaluation: BenchmarkEvaluation,
+ labelText: string,
+ currency: Currency,
+): AskEvaluationParams {
+ return {
+ benchmarkId,
+ time: formatDateTime(evaluation.time),
+ label: labelText,
+ version: evaluation.version,
+ provider: evaluation.provider,
+ modelId: evaluation.modelId,
+ thinkingLevel: evaluation.thinkingLevel,
+ score: formatScore(evaluation.score),
+ cost: formatMoney(evaluation.cost, currency),
+ duration: humanizeDuration(evaluation.durationMs),
+ summaryTitle: evaluation.summaryTitle ?? "",
+ summary: evaluation.summary ?? "",
+ cases: evaluation.cases.map((c) => ({
+ id: c.case,
+ score: formatScore(c.score),
+ cost: formatMoney(c.cost, currency),
+ duration: humanizeDuration(c.durationMs),
+ sessionIds: c.runs.map((run) => run.sessionId).filter((id) => id !== ""),
+ })),
+ };
+}
+
+export function EvaluationDetailModal({
+ benchmarkId,
+ evaluation,
+ caseTitles,
+ onOpenCase,
+ currency,
+ onClose,
+}: {
+ benchmarkId: string;
+ evaluation: BenchmarkEvaluation;
+ caseTitles: ReadonlyMap<string, string>;
+ onOpenCase: (caseId: string) => void;
+ currency: Currency;
+ onClose: () => void;
+}) {
+ const [asking, setAsking] = useState(false);
+ const label = evaluationLabel(evaluation);
+ const labelText = label.unlabeled ? S.benchmark.unlabeled : label.text;
+
+ return (
+ <>
+ <Modal
+ open
+ title={S.benchmark.evaluationDetailTitle(formatDateTime(evaluation.time))}
+ widthClass="sm:max-w-3xl"
+ onClose={onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose}>
+ {S.common.close}
+ </Button>
+ <Button size="sm" variant="secondary" onClick={() => setAsking(true)}>
+ <GlyphIcon d={MAGIC_WAND_ICON} />
+ {S.benchmark.askAi}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {/* Which series this point sits on, and the version it tested: the series label no
+ longer carries the version, so this line is where a reader reads it. */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <span className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
+ {evaluation.agentId && (
+ <AgentAvatar
+ id={evaluation.agentId}
+ size={ICON_SIZE.rowLead}
+ className="shrink-0 rounded"
+ />
+ )}
+ <span className="min-w-0 truncate font-mono text-xs text-gray-600 dark:text-gray-300">
+ {labelText}
+ </span>
+ </span>
+ <span className="font-mono text-xs text-gray-500 dark:text-gray-400">
+ v{evaluation.version}
+ </span>
+ </div>
+
+ <div className="flex flex-wrap gap-x-6 gap-y-2 rounded-md border border-gray-200 bg-gray-50/80 px-3 py-2 dark:border-gray-800 dark:bg-gray-950/40">
+ <Metric label={S.benchmark.colScore} value={formatScore(evaluation.score)} strong />
+ <Metric label={S.common.cost} value={formatMoney(evaluation.cost, currency)} />
+ <Metric
+ label={S.benchmark.colDuration}
+ value={humanizeDuration(evaluation.durationMs)}
+ />
+ </div>
+
+ {/* Evaluation summary title and body are displayed separately when present. */}
+ {(evaluation.summaryTitle || evaluation.summary) && (
+ <div>
+ {evaluation.summaryTitle ? (
+ <p className="text-xs font-semibold text-gray-700 dark:text-gray-200">
+ {evaluation.summaryTitle}
+ </p>
+ ) : (
+ <p className="text-xs font-semibold text-gray-500">{S.benchmark.summaryLabel}</p>
+ )}
+ {evaluation.summary && (
+ <p className="mt-0.5 whitespace-pre-wrap text-xs text-gray-600 dark:text-gray-300">
+ {evaluation.summary}
+ </p>
+ )}
+ </div>
+ )}
+
+ <div>
+ <p className="mb-1 text-xs font-semibold text-gray-500">{S.benchmark.cases}</p>
+ <div className="overflow-x-auto rounded-md border border-gray-200 dark:border-gray-800">
+ <table className="w-full min-w-[520px] text-left">
+ <thead>
+ <tr className="border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900">
+ <th className="px-2 py-1.5 font-medium">{S.benchmark.colCase}</th>
+ <th className="px-2 py-1.5 font-medium">{S.benchmark.colScore}</th>
+ <th className="px-2 py-1.5 font-medium">{S.common.cost}</th>
+ <th className="px-2 py-1.5 font-medium">{S.benchmark.colDuration}</th>
+ <th className="px-2 py-1.5 font-medium">{S.benchmark.colSession}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {evaluation.cases.map((c) => (
+ <CaseRow
+ key={c.case}
+ caseScore={c}
+ title={caseTitles.get(c.case)}
+ onOpenCase={caseTitles.has(c.case) ? onOpenCase : undefined}
+ currency={currency}
+ />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ </Modal>
+
+ {asking && (
+ <AskAiModal
+ open
+ onClose={() => setAsking(false)}
+ title={S.benchmark.askEvaluationTitle}
+ description={S.benchmark.askEvaluationDescription}
+ question={S.benchmark.askEvaluationDefault}
+ examples={askEvaluationExamples()}
+ tail={askEvaluationTail(askParams(benchmarkId, evaluation, labelText, currency))}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/web/src/features/benchmark/score-sparkline.tsx b/packages/web/src/features/benchmark/score-sparkline.tsx
new file mode 100644
index 00000000..b4b0b750
--- /dev/null
+++ b/packages/web/src/features/benchmark/score-sparkline.tsx
@@ -0,0 +1,55 @@
+/**
+ * Score sparkline of a Benchmark row: the scoreboard's Scores in order as one polyline, the
+ * newest point marked. Normalized to the observed range with a small floor, so a series that
+ * moved from 60 to 90 fills the box and a flat one draws a level line through its middle
+ * instead of collapsing onto an edge; there are no ticks — the number beside it is the value.
+ * A single score is a lone point. Pure SVG, its own geometry (outside the icon family).
+ */
+const W = 72;
+const H = 22;
+const PAD = 2.5;
+/** The smallest range the box stands for: below this, differences are noise at 72px wide. */
+const MIN_SPAN = 5;
+
+export function ScoreSparkline({
+ values,
+ label,
+ className = "",
+}: {
+ values: readonly number[];
+ label: string;
+ className?: string;
+}) {
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const span = Math.max(max - min, MIN_SPAN);
+ const low = (min + max) / 2 - span / 2;
+ const step = values.length > 1 ? (W - 2 * PAD) / (values.length - 1) : 0;
+ const points = values.map(
+ (v, i) => [PAD + i * step, H - PAD - ((v - low) / span) * (H - 2 * PAD)] as const,
+ );
+ const last = points[points.length - 1];
+ return (
+ <svg
+ width={W}
+ height={H}
+ viewBox={`0 0 ${W} ${H}`}
+ role="img"
+ aria-label={label}
+ className={`text-gray-500 dark:text-gray-400 ${className}`}
+ >
+ <title>{label}</title>
+ {points.length > 1 && (
+ <polyline
+ points={points.map(([x, y]) => `${x},${y}`).join(" ")}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ )}
+ {last !== undefined && <circle cx={last[0]} cy={last[1]} r={2} fill="currentColor" />}
+ </svg>
+ );
+}
diff --git a/packages/web/src/features/benchmark/use-benchmark-modal.tsx b/packages/web/src/features/benchmark/use-benchmark-modal.tsx
new file mode 100644
index 00000000..956990d8
--- /dev/null
+++ b/packages/web/src/features/benchmark/use-benchmark-modal.tsx
@@ -0,0 +1,360 @@
+/**
+ * Use one Benchmark: the single dialog behind the "Use" button on a card and on the Benchmark's
+ * own page. A segmented control at the top picks what to use it for — Evaluate, which puts an
+ * agent on the frozen cases and appends one labelled evaluation to the scoreboard, or Optimize,
+ * which improves an agent against those scores. Both tabs are forms over a fixed parameter tail
+ * for their Skill, both preview the assembled prompt, and both leave the same way: the prompt is
+ * prefilled into a new conversation with the agent that will carry the work out, and pressing
+ * Send stays the user's move. A Benchmark can score several agents, so which one is under test
+ * is a choice here; the baseline and the default target follow that choice. The model of the
+ * conversation that carries the work out is picked with the Project settings' own model picker
+ * (ModelSelect in its form variant, the one the new-chat defaults and the schedule form use),
+ * preset to the Project's default model. The evaluation runtime is never picked in this dialog —
+ * Evaluate takes the tested agent's own configured model and thinking level, and Optimize reuses
+ * what that agent's baseline recorded, so scores stay comparable. Mounted fresh per Benchmark.
+ */
+import { useEffect, useState } from "react";
+import type {
+ AgentSummary,
+ BenchmarkSummary,
+ ModelRefDto,
+ ModelsResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { formatScore } from "../../lib/format";
+import { toneStrip } from "../../lib/tone";
+import { agentDisplayName, useProject } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { FieldHint, FieldLabel } from "../../components/ui/field";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { MAGIC_WAND_ICON } from "../../components/ui/icons";
+import { Input, Textarea } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
+import { Segmented } from "../../components/ui/segmented";
+import { Select } from "../../components/ui/select";
+import { PromptFold, composeAiPrompt, pickDefaultAgent, useAiBridge } from "../ai-create";
+import { ModelSelect } from "../chat/model-select";
+import { defaultTargetScore, latestScoreOfAgent } from "./benchmark-metrics";
+import { MAX_RUNS, evaluateTail, optimizeTail } from "./benchmark-prompts";
+import type { EvaluateParams, OptimizeParams } from "./benchmark-prompts";
+
+/** The Skill the evaluator agent must carry; the dialog warns when the chosen agent lacks it. */
+const EVALUATION_SKILL = "agent-evaluation";
+/** The Skill the optimizer agent must carry; the dialog warns when the chosen agent lacks it. */
+const OPTIMIZATION_SKILL = "agent-optimization";
+
+/** Which half of the dialog is on screen. */
+export type UseTab = "evaluate" | "optimize";
+
+const digits = (v: string) => v.replace(/[^\d]/g, "");
+const errorProp = (message: string | undefined) =>
+ message !== undefined ? { error: message } : {};
+
+/** A digits-only field as an integer within [min, max], or null when it is empty or out of range. */
+function intIn(raw: string, min: number, max: number): number | null {
+ if (!/^\d+$/.test(raw)) return null;
+ const n = Number.parseInt(raw, 10);
+ return Number.isSafeInteger(n) && n >= min && n <= max ? n : null;
+}
+
+export function UseBenchmarkModal({
+ open,
+ onClose,
+ projectId,
+ benchmark,
+ agents,
+ models,
+ initialTab = "evaluate",
+}: {
+ open: boolean;
+ onClose: () => void;
+ projectId: string;
+ benchmark: BenchmarkSummary;
+ agents: readonly AgentSummary[];
+ /** The Project's models, for each tab's conversation-model picker; null while unknown. */
+ models: ModelsResponse | null;
+ /** Which tab opens first; the other is one click away. */
+ initialTab?: UseTab;
+}) {
+ const { openAiChat } = useAiBridge();
+ const { currentAgent } = useProject();
+ const [tab, setTab] = useState<UseTab>(initialTab);
+ // Who was tested last here is the likeliest subject of the next round; with no evaluation at
+ // all, the Agent the user came from, and failing that the Project's default. Both tabs act on
+ // the same tested agent, so the pick survives a tab switch.
+ const lastTested =
+ [...benchmark.evaluations].reverse().find((e) => (e.agentId ?? "") !== "")?.agentId ?? null;
+ const [testAgentId, setTestAgentId] = useState(
+ lastTested ?? currentAgent?.agentId ?? pickDefaultAgent(agents)?.agentId ?? "",
+ );
+ const baseline = latestScoreOfAgent(benchmark.evaluations, testAgentId);
+ const defaultTarget = defaultTargetScore(baseline?.score ?? null);
+ const [evaluatorId, setEvaluatorId] = useState<string | null>(
+ pickDefaultAgent(agents)?.agentId ?? null,
+ );
+ const [optimizerId, setOptimizerId] = useState<string | null>(
+ pickDefaultAgent(agents)?.agentId ?? null,
+ );
+ // The conversation's model, preset to the Project's default; null only while the model list
+ // has not arrived yet (the dialog usually opens after the page fetched it).
+ const [modelRef, setModelRef] = useState<ModelRefDto | null>(models?.defaultModel ?? null);
+ // Clamped: benchmark_config.toml is hand-editable, and a larger count there would open the
+ // dialog on a field its own bound rejects, with Send disabled until the number is retyped.
+ const [runs, setRuns] = useState(String(Math.min(benchmark.runs ?? 1, MAX_RUNS)));
+ const [note, setNote] = useState("");
+ const [roundLimit, setRoundLimit] = useState("3");
+ const [targetScore, setTargetScore] = useState(String(defaultTarget));
+ /** The target follows the tested agent's baseline until the field is edited by hand. */
+ const [targetTouched, setTargetTouched] = useState(false);
+ const [focus, setFocus] = useState("");
+ const [skillsByAgent, setSkillsByAgent] = useState<Record<string, string[]>>({});
+
+ // The installed Skills of the agents that could carry the work out, fetched once per agent,
+ // for the missing-skill hint. A failed fetch leaves the hint off: the send still goes through.
+ // Each result is stored under the agent it was fetched for, so it stays wanted even when the
+ // pick moved on meanwhile — dropping it would only make switching away and back refetch.
+ useEffect(() => {
+ for (const id of [evaluatorId, optimizerId]) {
+ if (id === null || skillsByAgent[id] !== undefined) continue;
+ api
+ .getAgentSkills(projectId, id)
+ .then((res) =>
+ setSkillsByAgent((prev) => ({ ...prev, [id]: res.skills.map((s) => s.name) })),
+ )
+ .catch(() => {});
+ }
+ }, [projectId, evaluatorId, optimizerId, skillsByAgent]);
+
+ useEffect(() => {
+ if (!targetTouched) setTargetScore(String(defaultTarget));
+ }, [defaultTarget, targetTouched]);
+
+ // A model list that arrives after the dialog opened seeds the picker the same way the
+ // initial state does; a pick already made is never overwritten.
+ const defaultModel = models?.defaultModel;
+ useEffect(() => {
+ if (defaultModel !== undefined) setModelRef((current) => current ?? defaultModel);
+ }, [defaultModel]);
+
+ const lacksSkill = (agentId: string | null, skill: string): boolean => {
+ const installed = agentId === null ? undefined : skillsByAgent[agentId];
+ return installed !== undefined && !installed.includes(skill);
+ };
+ const evaluatorMissingSkill = lacksSkill(evaluatorId, EVALUATION_SKILL);
+ const optimizerMissingSkill = lacksSkill(optimizerId, OPTIMIZATION_SKILL);
+
+ const runsValue = intIn(runs, 1, MAX_RUNS);
+ const roundsValue = intIn(roundLimit, 1, MAX_RUNS);
+ const targetValue = intIn(targetScore, 1, 100);
+ const evaluateParams: EvaluateParams = {
+ targetAgentId: testAgentId,
+ benchmarkId: benchmark.id,
+ runs: runsValue ?? benchmark.runs ?? 1,
+ };
+ const optimizeParams: OptimizeParams = {
+ ...evaluateParams,
+ roundLimit: roundsValue ?? 3,
+ targetScore: targetValue ?? defaultTarget,
+ };
+ const text =
+ tab === "evaluate"
+ ? composeAiPrompt(note, evaluateTail(evaluateParams))
+ : composeAiPrompt(focus, optimizeTail(optimizeParams));
+ const runnerId = tab === "evaluate" ? evaluatorId : optimizerId;
+ const ready =
+ runnerId !== null &&
+ testAgentId !== "" &&
+ runsValue !== null &&
+ (tab === "evaluate" || (roundsValue !== null && targetValue !== null));
+
+ const go = () => {
+ if (runnerId === null) return;
+ const ref = modelRef ?? defaultModel;
+ openAiChat({
+ agentId: runnerId,
+ text,
+ ...(ref !== undefined ? { modelRef: ref } : {}),
+ // An evaluation / optimization run, not a conversation of the user's own: the session
+ // list files it, and the Test Sessions it launches, under the Evaluations folder.
+ source: "benchmark",
+ });
+ onClose();
+ };
+
+ const agentOptions = agents.map((a) => (
+ <option key={a.agentId} value={a.agentId}>
+ {agentDisplayName(a)}
+ </option>
+ ));
+ // The Project settings' model picker (provider logo, searchable grouped panel, the default
+ // row marked), disabled until the list is known; an empty list reads as the models page's
+ // own empty line rather than as a picker with nothing in it.
+ const modelField = (label: string, hint: string) => (
+ <div>
+ <FieldLabel>{label}</FieldLabel>
+ {models !== null && models.models.length === 0 ? (
+ <p className="text-xs text-gray-400">{S.models.empty}</p>
+ ) : (
+ <ModelSelect
+ models={models?.models ?? []}
+ value={modelRef}
+ {...(defaultModel !== undefined ? { defaultModel } : {})}
+ onChange={setModelRef}
+ disabled={models === null}
+ variant="form"
+ />
+ )}
+ <FieldHint>{hint}</FieldHint>
+ </div>
+ );
+ const missingSkillStrip = (missing: boolean, message: string) =>
+ missing ? (
+ <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>{message}</div>
+ ) : null;
+ const testedAgentSelect = (hint: string) => (
+ <Select
+ label={S.benchmark.testedAgent}
+ hint={hint}
+ value={testAgentId}
+ onChange={(e) => setTestAgentId(e.target.value)}
+ >
+ {agentOptions}
+ </Select>
+ );
+ const runsInput = (hint: string) => (
+ <Input
+ label={S.benchmark.runsField}
+ hint={hint}
+ inputMode="numeric"
+ value={runs}
+ onChange={(e) => setRuns(digits(e.target.value))}
+ {...errorProp(runsValue === null ? S.benchmark.invalidRuns : undefined)}
+ />
+ );
+
+ return (
+ <Modal
+ open={open}
+ title={S.benchmark.useTitle(benchmark.title)}
+ onClose={onClose}
+ widthClass="sm:max-w-2xl"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose}>
+ {S.common.cancel}
+ </Button>
+ {/*
+ One exit for both tabs, and it hands the assembled prompt to a new conversation
+ instead of sending it: the work starts only when the user presses Send there, on
+ text they have read. Disabled until there is an agent to carry it out and every
+ parameter of the open tab is in range.
+ */}
+ <Button size="sm" variant="primary" disabled={!ready} onClick={go}>
+ <GlyphIcon d={MAGIC_WAND_ICON} />
+ {S.aiCreate.editInChat}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Segmented
+ cols={2}
+ value={tab}
+ onChange={setTab}
+ options={[
+ { value: "evaluate" as UseTab, label: S.benchmark.evaluate },
+ { value: "optimize" as UseTab, label: S.benchmark.optimize },
+ ]}
+ />
+ {tab === "evaluate" ? (
+ <>
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.benchmark.evaluateDescription}
+ </p>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {testedAgentSelect(S.benchmark.evaluateTestedAgentHint)}
+ <Select
+ label={S.benchmark.evaluatorAgent}
+ hint={S.benchmark.evaluatorAgentHint}
+ value={evaluatorId ?? ""}
+ onChange={(e) => setEvaluatorId(e.target.value)}
+ >
+ {agentOptions}
+ </Select>
+ {modelField(S.benchmark.evaluateSessionModel, S.benchmark.evaluateSessionModelHint)}
+ {runsInput(S.benchmark.evaluateRunsHint)}
+ </div>
+ {missingSkillStrip(evaluatorMissingSkill, S.benchmark.evaluatorMissingSkill)}
+ <Textarea
+ label={S.benchmark.evaluateNoteField}
+ placeholder={S.benchmark.evaluateNotePlaceholder}
+ rows={3}
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ />
+ <PromptFold text={text} />
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.benchmark.optimizeDescription}
+ </p>
+ {baseline === null ? (
+ <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}>
+ {S.benchmark.noBaseline}
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {S.benchmark.baselineLine(formatScore(baseline.score), optimizeParams.targetScore)}
+ </p>
+ )}
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {testedAgentSelect(S.benchmark.testedAgentHint)}
+ <Select
+ label={S.benchmark.optimizerAgent}
+ hint={S.benchmark.optimizerAgentHint}
+ value={optimizerId ?? ""}
+ onChange={(e) => setOptimizerId(e.target.value)}
+ >
+ {agentOptions}
+ </Select>
+ {modelField(S.benchmark.sessionModel, S.benchmark.sessionModelHint)}
+ </div>
+ {missingSkillStrip(optimizerMissingSkill, S.benchmark.optimizerMissingSkill)}
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ {runsInput(S.benchmark.optimizeRunsHint)}
+ <Input
+ label={S.benchmark.roundLimitField}
+ hint={S.benchmark.roundLimitHint}
+ inputMode="numeric"
+ value={roundLimit}
+ onChange={(e) => setRoundLimit(digits(e.target.value))}
+ {...errorProp(roundsValue === null ? S.benchmark.invalidRuns : undefined)}
+ />
+ <Input
+ label={S.benchmark.targetScoreField}
+ hint={S.benchmark.targetScoreHint}
+ inputMode="numeric"
+ value={targetScore}
+ onChange={(e) => {
+ setTargetTouched(true);
+ setTargetScore(digits(e.target.value));
+ }}
+ {...errorProp(targetValue === null ? S.benchmark.invalidScore : undefined)}
+ />
+ </div>
+ <Textarea
+ label={S.benchmark.focusField}
+ placeholder={S.benchmark.focusPlaceholder}
+ rows={3}
+ value={focus}
+ onChange={(e) => setFocus(e.target.value)}
+ />
+ <PromptFold text={text} />
+ </>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/chat/draft-cache.ts b/packages/web/src/features/chat/draft-cache.ts
index f1b39a01..91be0b98 100644
--- a/packages/web/src/features/chat/draft-cache.ts
+++ b/packages/web/src/features/chat/draft-cache.ts
@@ -51,6 +51,13 @@ export interface DraftCache {
* Dropped by the first edit: from then on the text is the user's and is cached like any other.
*/
aiPrefill?: true;
+ /**
+ * The conversation this draft creates is a Benchmark evaluation / optimization run (the
+ * Evaluation Center's Use dialog): written by the same bridge as aiPrefill and sent on as
+ * `SessionCreateRequest.source`, which files the Session under the sidebar's Evaluations
+ * folder. Like aiPrefill it lives and dies with the draft it seeds — nothing else sets it.
+ */
+ source?: "benchmark";
}
/** Minimal storage interface (a subset of localStorage). */
@@ -110,6 +117,7 @@ export function draftFromUnknown(parsed: unknown): DraftCache {
if (skills.length > 0) out.skills = skills;
}
if (o.aiPrefill === true) out.aiPrefill = true;
+ if (o.source === "benchmark") out.source = "benchmark";
if (
typeof o.approvalMode === "string" &&
APPROVAL_MODES.includes(o.approvalMode as ApprovalMode)
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 8c50446b..4df1c9e6 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -523,10 +523,23 @@ export function DraftView({
// Carried through every write, so a reload finds the prefill still marked as composed
// rather than resuming it as if it had been typed here.
if (aiPrefillRef.current) data.aiPrefill = true;
+ // The evaluation mark the Evaluation Center's Use dialog set on this draft rides along for
+ // the same reason: after a reload the Session must still be created as an evaluation run.
+ if (cached.source !== undefined) data.source = cached.source;
// A parked draft writes back into its own list entry; the active draft into its slot.
if (draftId !== undefined) saveDraftSession(userId, projectId, draftId, data);
else saveDraft(draftKey(userId, projectId), data);
- }, [cancelPendingSave, userId, projectId, draftId, agentId, workspace, approvalMode, modelRef]);
+ }, [
+ cancelPendingSave,
+ userId,
+ projectId,
+ draftId,
+ agentId,
+ workspace,
+ approvalMode,
+ modelRef,
+ cached.source,
+ ]);
// The timer and unmount cleanup read persistNow via a ref to always get the **latest version**: a stale closure would write back outdated options.
const persistRef = useRef(persistNow);
@@ -673,6 +686,9 @@ export function DraftView({
body.provider = modelRef.provider;
}
if (workspace.trim()) body.workspace = workspace.trim();
+ // A draft the Evaluation Center's Use dialog composed creates its Session as an
+ // evaluation run, which the sidebar files under the Evaluations folder.
+ if (cached.source !== undefined) body.source = cached.source;
const created = await api.createSession(projectId, agentId, body);
createdId = created.session.sessionId;
const res = await api.postTask(createdId, { input, ...(goal ? { goal } : {}) });
@@ -700,7 +716,17 @@ export function DraftView({
sendingRef.current = false;
}
},
- [projectId, agentId, approvalMode, modelRef, workspace, add, discardDraft, navigate],
+ [
+ projectId,
+ agentId,
+ approvalMode,
+ modelRef,
+ workspace,
+ cached.source,
+ add,
+ discardDraft,
+ navigate,
+ ],
);
/**
diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsx
index 38e3920c..c09b63b6 100644
--- a/packages/web/src/features/chat/md.tsx
+++ b/packages/web/src/features/chat/md.tsx
@@ -96,6 +96,12 @@ const SETTLED_COMPONENTS: Components = {
a: MdLink,
};
+/**
+ * The settled map, for the read-only Markdown surfaces outside the chat (the shared file
+ * browser) that keep the code-block chrome and swap only the link and image adapters.
+ */
+export const SETTLED_MD_COMPONENTS: Components = SETTLED_COMPONENTS;
+
export const Md = memo(function Md({
text,
streaming = false,
diff --git a/packages/web/src/features/plugins/plugin-detail.tsx b/packages/web/src/features/plugins/plugin-detail.tsx
index 4a1297d6..b7a30826 100644
--- a/packages/web/src/features/plugins/plugin-detail.tsx
+++ b/packages/web/src/features/plugins/plugin-detail.tsx
@@ -1,29 +1,27 @@
/**
* Plugin detail Modal — opened by clicking a library card (the model library's card-detail
- * pattern): the plugin's icon, full description, metadata line and hook points, then a file
- * browser over everything it ships — the shared `FileTree` on the left (one directory per
- * skill and one for the hook package, any number open at once) and a preview on the right.
- * The header and the tree never leave: opening a file fills the preview pane instead of
- * replacing the view, so the summary and the other files stay in sight while reading. The
- * files arrive in one request (GET /api/plugins/:plugin/files) when the Modal opens; a
- * markdown file renders through the chat markdown component with its frontmatter stripped,
- * anything else as a code block.
+ * pattern): the plugin's icon, full description, metadata line and hook points, then the
+ * shared read-only file browser over everything the plugin ships — one directory per skill
+ * and one for the hook package, any number open at once, and a preview on the right. The
+ * header and the tree never leave: opening a file fills the preview pane instead of replacing
+ * the view, so the summary and the other files stay in sight while reading. The files arrive
+ * in one request (GET /api/plugins/:plugin/files) when the Modal opens, so the whole tree is
+ * on hand at once and nothing here is fetched per directory.
*/
import { useEffect, useState } from "react";
import { Modal } from "../../components/ui/modal";
import { Badge } from "../../components/ui/badge";
-import { FileTree } from "../../components/ui/file-tree";
+import { FileBrowser } from "../../components/ui/file-browser";
+import type { FileBrowserPreview } from "../../components/ui/file-browser";
import type { TreeToggle } from "../../components/ui/file-tree";
import type { FileTreeRow } from "../../lib/file-tree";
import { PLUGIN_ICON } from "../../components/ui/icons";
-import { SkeletonList } from "../../components/ui/skeleton";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
+import { baseName } from "../../lib/workspace-tree";
import { useLocale } from "../../state/locale";
import { getPluginFiles } from "../../api/endpoints";
import type { PluginItem } from "@prismshadow/penguin-server/api";
-import { CodeBlock } from "../chat/code-block";
-import { Md } from "../chat/md";
import { SkillTile } from "../skills/skill-icon-view";
import { localizedText } from "../chat/skill-use";
@@ -35,32 +33,16 @@ interface FileGroup {
paths: string[];
}
-/** SKILL.md carries its frontmatter; the reader shows the body only. */
-function stripFrontmatter(content: string): string {
- return content.replace(/^?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim();
-}
-
-/** Highlighter language for a non-markdown file, by extension; plain text for the rest. */
-function languageFor(path: string): string {
- const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
- return (
- {
- js: "javascript",
- mjs: "javascript",
- cjs: "javascript",
- ts: "typescript",
- json: "json",
- yaml: "yaml",
- yml: "yaml",
- toml: "toml",
- sh: "shellscript",
- py: "python",
- html: "html",
- css: "css",
- svg: "xml",
- xml: "xml",
- }[ext] ?? "text"
- );
+/** The preview of one file, whose text the files response already carries. */
+function filePreview(path: string, text: string): FileBrowserPreview {
+ return {
+ path,
+ name: baseName(path),
+ // Everything a plugin ships is text here — the response is a path-to-content map — so the
+ // only question is whether it reads as a document or as source.
+ kind: path.endsWith(".md") ? "md" : "text",
+ content: text,
+ };
}
/**
@@ -209,6 +191,7 @@ export function PluginDetailModal({
// auto-preview), so the pane is never empty while there is something to read.
const current = selected ?? groups[0]?.paths[0] ?? null;
const text = current !== null && files !== null ? files[current] : undefined;
+ const preview = current !== null && text !== undefined ? filePreview(current, text) : null;
const toggleDir = (dir: string): void => {
const open = collapsed.has(dir);
@@ -249,48 +232,24 @@ export function PluginDetailModal({
</div>
</div>
- {/* The browser: tree left, preview right (stacked on narrow screens). Both panes scroll on
- their own inside fixed heights, so the header above stays put. */}
- <div className="mt-4 grid grid-cols-1 overflow-hidden rounded-md border border-gray-200 md:grid-cols-[220px_minmax(0,1fr)] dark:border-gray-800">
- <aside className="border-b border-gray-200 bg-gray-50/60 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-950/30">
- <div className="max-h-40 overflow-y-auto md:max-h-[50vh]">
- {error && <p className="px-3 py-2 text-xs text-red-500">{error}</p>}
- {files === null && !error && <SkeletonList rows={3} />}
- {/* A `tree` with no `treeitem` in it is not one: while the listing is in flight, or
- when it failed or held nothing, the aside carries the skeleton or the error and
- no tree at all. */}
- {rows.length > 0 && (
- <FileTree
- rows={rows}
- label={S.files.treeLabel}
- selectedPath={current}
- toggled={toggled}
- onToggleDir={toggleDir}
- onOpenFile={setSelected}
- />
- )}
- </div>
- </aside>
-
- <section className="min-w-0">
- <div className="flex min-h-9 items-center border-b border-gray-200 px-3 py-1.5 dark:border-gray-800">
- <p className="truncate font-mono text-xs text-gray-500">{current ?? plugin.name}</p>
- </div>
- <div className="max-h-[50vh] min-h-[50vh] overflow-auto p-3">
- {files === null && !error ? (
- <SkeletonList rows={8} />
- ) : current === null || text === undefined ? (
- <p className="text-sm text-gray-400">{error ?? S.common.none}</p>
- ) : current.endsWith(".md") ? (
- <div className="md-body text-sm text-gray-800 dark:text-gray-100">
- <Md text={stripFrontmatter(text)} />
- </div>
- ) : (
- <CodeBlock language={languageFor(current)} code={text} />
- )}
- </div>
- </section>
- </div>
+ {/* The browser: tree left, preview right (stacked on narrow screens) — the same one the
+ Benchmark case dialog draws. SKILL.md shows its body, with the frontmatter the card
+ above already states dropped. */}
+ <FileBrowser
+ className="mt-4"
+ rows={rows}
+ treeLabel={S.files.treeLabel}
+ selectedPath={current}
+ toggled={toggled}
+ treeLoading={files === null}
+ treeError={error}
+ headerFallback={plugin.name}
+ preview={preview}
+ emptyPreview={error ?? S.common.none}
+ stripFrontmatter
+ onToggleDir={toggleDir}
+ onOpenFile={setSelected}
+ />
</Modal>
);
}
diff --git a/packages/web/src/lib/group-order.ts b/packages/web/src/lib/group-order.ts
index 3cc687ae..a7261028 100644
--- a/packages/web/src/lib/group-order.ts
+++ b/packages/web/src/lib/group-order.ts
@@ -121,17 +121,40 @@ export function saveGroupOrder(
* nothing is stored;
* 2. the pinned cluster first, then the stored order within the pinned cluster and
* within the rest independently (orderWithinPinPartitions), so a drag can never move
- * a group across the pin boundary.
+ * a group across the pin boundary;
+ * 3. `demote`, when the caller passes one: a stable partition applied LAST and within the
+ * unpinned cluster only, moving the groups it picks behind the rest.
*
* An empty `order` returns the pinned-first list unchanged, which is exactly what the
* sidebar rendered before any group was ever dragged.
+ *
+ * Demotion is the sidebar's folder-only groups — the ones holding nothing but folded
+ * conversations, which a single evaluation creates by the dozen. It runs after the manual
+ * order rather than instead of it, so the arrangement still reads inside each of the two
+ * resulting blocks: the demoted groups keep their relative order and so do the kept ones,
+ * and a group that gains an active row simply rejoins the others where it was all along.
+ * Pinned groups are never demoted — a pin is the user saying where a group goes, and it is
+ * how someone who wants a folder-only group at the top of the list says so.
*/
export function orderGroups<T>(
groups: readonly T[],
keyOf: (group: T) => string,
- opts: { pinned: ReadonlySet<string>; order: readonly string[] },
+ opts: {
+ pinned: ReadonlySet<string>;
+ order: readonly string[];
+ /** Groups to send behind the rest of the unpinned cluster; absent = nothing is demoted. */
+ demote?: (group: T) => boolean;
+ },
): T[] {
- return orderWithinPinPartitions(groups, keyOf, opts.pinned, opts.order);
+ const ordered = orderWithinPinPartitions(groups, keyOf, opts.pinned, opts.order);
+ const demote = opts.demote;
+ if (demote === undefined) return ordered;
+ const kept: T[] = [];
+ const last: T[] = [];
+ for (const group of ordered) {
+ (!opts.pinned.has(keyOf(group)) && demote(group) ? last : kept).push(group);
+ }
+ return last.length === 0 ? ordered : [...kept, ...last];
}
/**
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 5f3a9ea6..acee02a5 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -253,6 +253,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "install",
why: "Collapsed sidebar groups, keyed by those same Agent ids and Workspace paths.",
},
+ {
+ kind: "family",
+ key: "penguin.sidebarExpandedFolderGroups.",
+ scope: "install",
+ why: "Folder-only sidebar groups the user opened, keyed by those same Agent ids and Workspace paths.",
+ },
{
kind: "family",
key: "penguin.sidebarPinnedGroups.",
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index a072885b..9dc3d99e 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -463,8 +463,8 @@ export interface NestedSessionMeta {
agentId: string | null;
provider: string;
modelId: string;
- /** Session origin as recorded by core (subagent / schedule); absent = user-created. */
- source?: "subagent" | "schedule";
+ /** Session origin as recorded by core (subagent / schedule / benchmark); absent = user-created. */
+ source?: "subagent" | "schedule" | "benchmark";
}
export interface StreamModel {
diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.ts
index f4b5085c..32395d9c 100644
--- a/packages/web/src/lib/session-grouping.ts
+++ b/packages/web/src/lib/session-grouping.ts
@@ -185,7 +185,9 @@ export function splitPage<T>(fetched: T[], pageSize: number): { items: T[]; hasM
*/
export function sessionCategory(s: SessionInfo): SessionCategory {
if (s.archived) return "archived";
- return s.source === "subagent" || s.source === "schedule" ? s.source : "active";
+ return s.source === "subagent" || s.source === "schedule" || s.source === "benchmark"
+ ? s.source
+ : "active";
}
/**
@@ -200,23 +202,56 @@ export function matchesSessionQuery(s: SessionInfo, query: string): boolean {
}
/** The collapsed-folder categories of a group, in render order (below the active user rows). */
-export const FOLDER_CATEGORIES = ["subagent", "schedule", "archived"] as const;
+export const FOLDER_CATEGORIES = ["subagent", "schedule", "benchmark", "archived"] as const;
export type FolderCategory = (typeof FOLDER_CATEGORIES)[number];
/**
- * Four-way split of one sidebar group's Sessions by sessionCategory (rendered top to
+ * Five-way split of one sidebar group's Sessions by sessionCategory (rendered top to
* bottom in this order): active user rows in the group body, then the collapsed
- * Subagents / Scheduled / Archived folders.
+ * Subagents / Scheduled / Evaluations / Archived folders.
*/
export type SessionPartition = Record<SessionCategory, SessionInfo[]>;
/** Partitions a group's Sessions for rendering. Input order is preserved within each part. */
export function partitionSessions(sessions: SessionInfo[]): SessionPartition {
- const parts: SessionPartition = { active: [], subagent: [], schedule: [], archived: [] };
+ const parts: SessionPartition = {
+ active: [],
+ subagent: [],
+ schedule: [],
+ benchmark: [],
+ archived: [],
+ };
for (const s of sessions) parts[sessionCategory(s)].push(s);
return parts;
}
+/**
+ * A group's FOLDED share: the conversations its collapsed folders hold (Subagents /
+ * Scheduled / Evaluations / Archived), summed from one set of category counts. Missing
+ * keys count as zero rather than poisoning the sum with NaN — the guard
+ * aggregateWorkspaceCounts applies to the same numbers.
+ */
+export function foldedShare(counts: SessionCategoryCounts): number {
+ let total = 0;
+ for (const category of FOLDER_CATEGORIES) {
+ const n = counts[category];
+ if (n > 0) total += n;
+ }
+ return total;
+}
+
+/**
+ * Whether a group holds nothing but folded conversations: no active row of its own, and at
+ * least one row inside its folders. That is the shape an evaluation leaves behind — one
+ * Workspace per Case × Run, each holding a single Test Session — and the shape of an Agent
+ * that has only ever been evaluated; the sidebar folds such a group up and sorts it behind
+ * the others. A group with both shares at zero (a registered but still unused Workspace) is
+ * NOT folder-only: it has nothing folded away to fold up.
+ */
+export function isFolderOnly(activeShare: number, folded: number): boolean {
+ return activeShare === 0 && folded > 0;
+}
+
const ALL_CATEGORIES: readonly SessionCategory[] = ["active", ...FOLDER_CATEGORIES];
/** One workspace-mode group's aggregated server counts: exact totals plus which Agents hold rows of each category. */
@@ -243,8 +278,8 @@ export function aggregateWorkspaceCounts(
let group = out.get(key);
if (!group) {
group = {
- totals: { active: 0, subagent: 0, schedule: 0, archived: 0 },
- agents: { active: [], subagent: [], schedule: [], archived: [] },
+ totals: { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 },
+ agents: { active: [], subagent: [], schedule: [], benchmark: [], archived: [] },
};
out.set(key, group);
}
@@ -265,7 +300,9 @@ export function aggregateWorkspaceCounts(
* The Session the UI opens as "the last conversation" (the chat home's auto-select and
* the collapsed rail's entry): the loaded row the user was last IN — not the one created
* last, which on a revisited conversation is a different row. Archived rows are hidden by
- * choice and a subagent Session is a child of some other conversation, so neither is ever
+ * choice, a subagent Session is a child of some other conversation, and a benchmark Session is
+ * an evaluator's Test Session rather than a conversation of the user's (the evaluate / optimize
+ * conversation they just sent is already the one on screen), so none of the three is ever
* auto-opened; schedule-created runs are the user's conversations and qualify. Newest by
* lastActiveAt (stamped from `Date#toISOString`, so uniform ISO-8601 UTC like createdAt and
* comparable as a string), ties broken by sessionId — the list's ordering convention. Input
@@ -427,10 +464,10 @@ const MONTH_MS = 30 * DAY_MS;
export const timeGroupKey = (bucket: TimeBucket): string => `\0time-${bucket}`;
/**
- * Group key the folders (Subagents / Scheduled / Archived) hang off in time mode. They are
- * NOT bucketed: their rows load only when a folder is first expanded, so an unloaded
- * Session's bucket is unknown and no bucket could honestly advertise a share of them. One
- * shared, Project-wide set below the buckets is what the sidebar renders instead.
+ * Group key the folders (Subagents / Scheduled / Evaluations / Archived) hang off in time
+ * mode. They are NOT bucketed: their rows load only when a folder is first expanded, so an
+ * unloaded Session's bucket is unknown and no bucket could honestly advertise a share of
+ * them. One shared, Project-wide set below the buckets is what the sidebar renders instead.
*/
export const TIME_FOLDERS_GROUP_KEY = "\0time-folders";
@@ -485,7 +522,13 @@ export function groupSessionsByTime<T extends { lastActiveAt: string }>(
export function totalCategoryCounts(
byAgent: ReadonlyMap<string, SessionCategoryCounts>,
): SessionCategoryCounts {
- const totals: SessionCategoryCounts = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const totals: SessionCategoryCounts = {
+ active: 0,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ };
for (const counts of byAgent.values()) {
for (const category of ALL_CATEGORIES) {
const n = counts[category];
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index c99c3eea..eb2b4a77 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2318,8 +2318,12 @@ Scenarios:
folderGroups: {
subagent: (n: number) => `Subagents (${n})`,
schedule: (n: number) => `Scheduled (${n})`,
+ benchmark: (n: number) => `Evaluations (${n})`,
archived: (n: number) => `Archived (${n})`,
},
+ /** Tooltip of a folder-only group's header (nothing active of its own): what its folders hold, plus the Workspace path where the header has one. */
+ folderOnlyGroup: (n: number, path?: string) =>
+ `Folded tasks only: ${n} conversation${n === 1 ? "" : "s"}${path ? ` (${path})` : ""}`,
skillsBanner: (names: string[]): string =>
`Using skill${names.length === 1 ? "" : "s"}: ${names.join(", ")}`,
attachedFilesBanner: (names: string[]): string =>
@@ -2892,9 +2896,60 @@ Scenarios:
benchmark: {
title: "Evaluation Center",
- selectBenchmark: "Select a Benchmark on the left",
- emptyAgent: "No Benchmarks for this agent",
+ guideFlow: [
+ {
+ title: "Create",
+ text: "Press Create with AI at the top right to have AI write a set of cases for an agent and take its baseline score, or Create manually to write the cases yourself.",
+ },
+ {
+ title: "Evaluate",
+ text: "Pick a Benchmark, press Use → Evaluate, choose the agent under test and send the prefilled conversation to get one labelled score.",
+ },
+ {
+ title: "Optimize",
+ text: "Pick a Benchmark, press Use → Optimize, set a target score and send; a new version is kept only when the score strictly improves.",
+ },
+ ],
+ searchPlaceholder: "Search titles, descriptions or tested agents",
+ noMatches: "No Benchmark matches",
+ filterByAgent: (agentId: string): string => `Benchmarks that evaluated ${agentId}`,
+ clearFilter: "Show all",
+ emptyTitle: "No Benchmarks yet",
+ emptyDescription:
+ "Start by letting AI write cases for an agent and take a baseline. Score curves and per-case detail appear here afterwards, with optimization one click away.",
caseCount: (n: number): string => `${n} case${n === 1 ? "" : "s"}`,
+ runsPerCase: (n: number): string => `${n} run${n === 1 ? "" : "s"} per case`,
+ notEvaluated: "Not evaluated yet",
+ /** A draft Benchmark: the agent is still writing its cases, so card and page are masked. */
+ building: "Being built",
+ buildingHint:
+ "The agent is still writing the cases and calibrating their difficulty; the Benchmark opens once that is done",
+ buildingDetail:
+ "Once it is built, the cases, the score chart and the evaluation table appear here.",
+ /** A Benchmark whose calibration never finished: unusable, so the card and page are masked. */
+ creationFailed: "Creation failed",
+ creationFailedHint:
+ "The cases' difficulty could not be calibrated; delete this Benchmark and create it again",
+ creationFailedDetail:
+ "Calibration of this Benchmark never completed, so it cannot be evaluated or optimized; delete it and create it again.",
+ testedAgents: "Tested agents",
+ lastEvaluated: (when: string): string => `last evaluated ${when}`,
+ sparklineLabel: (n: number): string => `Score trend over ${n} evaluation${n === 1 ? "" : "s"}`,
+ latestScoreLabel: "Latest score",
+ firstEvaluation: "first evaluation",
+ use: "Use",
+ evaluate: "Evaluate",
+ optimize: "Optimize",
+ view: "View",
+ copyPath: "Copy directory path",
+ deleteBenchmark: "Delete Benchmark",
+ deleteConfirm: (title: string): string =>
+ `Delete "${title}"? All of its cases and evaluation records will be removed; this cannot be undone.`,
+ deleted: "Benchmark deleted",
+ backToList: "Back to list",
+ /** The Benchmark's own page when the id in the address resolves to nothing. */
+ notFound: "This Benchmark was not found",
+ notFoundHint: "It may have been deleted, or the link carries an id that no longer exists.",
trendTitle: (metric: string): string => `${metric} over time`,
cases: "Cases",
viewCase: "View details",
@@ -2904,8 +2959,11 @@ Scenarios:
caseFileUnavailable: "Case files are unavailable",
evaluations: "Evaluations",
noEvaluations: "No evaluations yet",
+ noEvaluationsHint:
+ "The score curve and evaluation detail appear here once a baseline is taken.",
summaryLabel: "Summary",
- legendUnlabeled: "unlabeled model",
+ unlabeled: "Unlabeled",
+ agentColumn: "Tested agent",
colVersion: "Version",
colModel: "Model ID",
colThinkingLevel: "Thinking level",
@@ -2914,6 +2972,293 @@ Scenarios:
colCase: "Case",
colRun: "Run",
colSession: "Session",
+ askAi: "Ask AI",
+ evaluationDetailTitle: (time: string): string => `Evaluation · ${time}`,
+ askEvaluationTitle: "Ask AI about this evaluation",
+ askEvaluationDescription:
+ "The total score, the per-case results and every run's Session id go along with your question; the agent reads the scoreboard and the matching Traces before answering. The prompt stays editable.",
+ askEvaluationDefault: "Explain this evaluation's result.",
+ /** The default question leads the examples (it is what the box opens with), so a reader who tried another can bring it back. Keep `explain.prompt` equal to askEvaluationDefault. */
+ askEvaluationExamples: {
+ explain: {
+ label: "Explain this evaluation's result",
+ prompt: "Explain this evaluation's result.",
+ },
+ whyLow: {
+ label: "Why is the score low?",
+ prompt:
+ "Why did this evaluation score so low? Use the per-case scores and the runs to say where the points were actually lost.",
+ },
+ weakest: {
+ label: "Which cases are weakest, and what should change?",
+ prompt:
+ "Which cases scored worst? For each, what caused it, and what single change to the tested agent has a chance of lifting it?",
+ },
+ againstPrevious: {
+ label: "What changed against the previous evaluation?",
+ prompt:
+ "Compared with this series' previous evaluation, which cases went up and which went down? What most likely caused those changes?",
+ },
+ },
+ askEvaluationTail: (p: {
+ benchmarkId: string;
+ time: string;
+ label: string;
+ version: number;
+ provider: string;
+ modelId: string;
+ thinkingLevel: string;
+ score: string;
+ cost: string;
+ duration: string;
+ summaryTitle: string;
+ summary: string;
+ cases: { id: string; score: string; cost: string; duration: string; sessionIds: string[] }[];
+ }): string =>
+ "Explain the result of the Benchmark evaluation below. Read and analyze only: change neither this Benchmark nor the tested agent.\n\n" +
+ `- benchmark_id: \`${p.benchmarkId}\` (the Project's \`benchmarks/${p.benchmarkId}/\`; the scoreboard is \`benchmarks/${p.benchmarkId}/scoreboard.yaml\`)\n` +
+ `- Evaluated at: ${p.time}\n` +
+ `- Series label: ${p.label}\n` +
+ `- Tested version: v${p.version}\n` +
+ `- Evaluation runtime: provider \`${p.provider}\` / model_id \`${p.modelId}\` / thinking_level \`${p.thinkingLevel}\`\n` +
+ `- Total score ${p.score}; cost ${p.cost}; duration ${p.duration}\n` +
+ (p.summaryTitle !== "" ? `- Summary title: ${p.summaryTitle}\n` : "") +
+ (p.summary !== "" ? `- Summary: ${p.summary}\n` : "") +
+ "- Per-case scores (score, cost, duration, and the Session id of every run):\n" +
+ p.cases
+ .map(
+ (c) =>
+ ` - \`${c.id}\`: ${c.score}; ${c.cost}; ${c.duration}; Session ` +
+ (c.sessionIds.length > 0
+ ? c.sessionIds.map((id) => `\`${id}\``).join(", ")
+ : "not recorded"),
+ )
+ .join("\n") +
+ "\n\nRead this record in scoreboard.yaml, and the Traces of the Sessions listed above as far as you need them. Then say how these scores came about, " +
+ "which cases are weakest and exactly why, and what to do next (which part of the tested agent to change, or which evidence to gather first).",
+ askCaseTitle: "Ask AI about this case",
+ askCaseDescription:
+ "The paths to the statement and the rubric go along with your question, so the agent can say what this case tests and what answering it well takes. The case is frozen: it reads, it does not edit.",
+ askCaseDefault: "Explain what this case tests and what a strong answer looks like.",
+ /** As for the evaluation dialog: the default question leads, equal to askCaseDefault. */
+ askCaseExamples: {
+ explain: {
+ label: "Explain what this case tests and what a strong answer looks like",
+ prompt: "Explain what this case tests and what a strong answer looks like.",
+ },
+ rubricRewards: {
+ label: "What does the rubric reward?",
+ prompt:
+ "Where does this case's rubric put its points? Which items do the most to separate excellent work from merely passing work?",
+ },
+ whyRunLow: {
+ label: "Why did a run score low here?",
+ prompt:
+ "The latest evaluation did not score well on this case. Which step is the tested agent most likely losing it at?",
+ },
+ clearerStatement: {
+ label: "How could the statement be clearer?",
+ prompt:
+ "Is anything in this statement ambiguous or easy to misread? The case is frozen and cannot be edited, so say how to write it more clearly in the next Benchmark instead.",
+ },
+ },
+ askCaseTail: (p: {
+ benchmarkId: string;
+ caseId: string;
+ latest: { time: string; score: string; runs: { score: string; sessionId: string }[] } | null;
+ }): string =>
+ "Explain what the Benchmark case below tests and what a strong answer looks like. A case is frozen once it exists: read and analyze only, and do not change this Benchmark.\n\n" +
+ `- benchmark_id: \`${p.benchmarkId}\` (the Project's \`benchmarks/${p.benchmarkId}/\`)\n` +
+ `- case_id: \`${p.caseId}\`\n` +
+ `- Statement: \`benchmarks/${p.benchmarkId}/${p.caseId}/statement/README.md\`\n` +
+ `- Rubric: \`benchmarks/${p.benchmarkId}/${p.caseId}/rubric/README.md\`\n` +
+ (p.latest === null
+ ? "- This Benchmark has no evaluations yet.\n"
+ : `- The latest evaluation (${p.latest.time}) averaged ${p.latest.score} on this case\n` +
+ p.latest.runs
+ .map((r, i) => ` - Run #${i + 1}: ${r.score}; Session \`${r.sessionId}\`\n`)
+ .join("")) +
+ "\nRead both READMEs above (and the Traces of the Sessions listed, if there are any). Then say what capability this case actually tests, " +
+ "what a strong answer looks like (the decisions and the artifact it takes), and which rubric items separate excellent work from merely passing work.",
+ aiCreateTitle: "Create a Benchmark with AI",
+ aiCreateDescription:
+ "Describe the capability and the scenarios to test. AI writes the cases for the Test Agent, trial-runs each one to calibrate difficulty, and takes a baseline score.",
+ targetAgent: "Test Agent",
+ targetAgentHint:
+ "The agent the cases are written for and scored under; the writing itself is done by the agent named below, in a new conversation",
+ aiCreateExamples: {
+ reportWriter: {
+ label: "Report writing: 3 cases with contradicting sources",
+ description:
+ "3 cases: conflicting material, unstated conventions, strict length and citations",
+ prompt: `Write a small, hard Benchmark for the report-writing agent — few cases, a low baseline.
+
+- benchmark_id: \`report-conflicting-sources\`
+- capability: still deliver a report with traceable conclusions and one consistent set of conventions when the sources contradict each other, key conventions are unstated, and length and citations are constrained
+- case count: 3
+- techniques: each case gives 2–3 sources that contradict one another, one of them newer but dated only in a footer; currency, time zone and counting conventions are deliberately left incomplete, and the right move is to name the gap, make a conservative assumption and mark it; a strict length cap and citation format, where overrunning or a missing citation costs points outright
+- desired_baseline_score: \`<50\`
+- pilot_iteration_limit: \`4\``,
+ },
+ customerService: {
+ label: "Support: 3 conversations with a hidden policy condition",
+ description:
+ "3 cases: incomplete users, policy conditions buried in an appendix, an over-promise trap",
+ prompt: `Write a small, hard multi-turn Benchmark for the customer-support agent — few cases, a low baseline.
+
+- benchmark_id: \`support-hidden-policy\`
+- capability: verify before answering, never over-promise, and stay consistent with the policy when the user's information is incomplete, the policy condition is buried deep in the material, and an emotional message invites a promise the agent cannot make
+- case count: 3
+- techniques: the policy's exceptions and effective dates appear only in an appendix; the user's description is vague and the key facts come out only when asked; in at least one case the most natural reply is exactly the forbidden promise; scoring looks at verification, over-promising, tone and accuracy
+- desired_baseline_score: \`<50\`
+- pilot_iteration_limit: \`4\``,
+ },
+ codeReview: {
+ label: "Code review: 3 cases whose defects hide in the contracts",
+ description:
+ "3 cases: unstated calling and concurrency assumptions, misleading comments and tests",
+ prompt: `Write a small, hard Benchmark for the code-review agent — few cases, a low baseline.
+
+- benchmark_id: \`review-hidden-contracts\`
+- capability: find every real defect without false positives, and say how to verify each, when the defects hide in calling conventions, concurrency assumptions and data shapes and the comments and tests mislead
+- case count: 3
+- techniques: each case is a small multi-file repository with 2–3 real defects that depend on an unstated call order, a time-zone or encoding assumption, or a concurrency precondition; add one or two stale comments and a test that passes without covering the defects; scoring looks at recall, false positives and whether reproducible verification steps are given
+- desired_baseline_score: \`<50\`
+- pilot_iteration_limit: \`4\``,
+ },
+ dataAnalysis: {
+ label: "Data analysis: 3 cases with a vague ask and a booby-trapped dataset",
+ description: "3 cases: dirty data, unstated conventions, assumptions to clarify first",
+ prompt: `Write a small, hard Benchmark for the data-analysis agent — few cases, a low baseline.
+
+- benchmark_id: \`analysis-ambiguous-asks\`
+- capability: clarify assumptions before analysing, then reach a correct conclusion with verifiable conventions, when the business question is vague and the data carries dirty values and unstated conventions
+- case count: 3
+- techniques: each case ships a CSV with duplicate rows, mixed units and missing values, and a data dictionary that explains only some of the fields; the business question has two reasonable readings, and the right move is to name the split and answer under each stated assumption; scoring looks at the conclusion, the stated conventions and whether the charts agree with the conclusion
+- desired_baseline_score: \`<50\`
+- pilot_iteration_limit: \`4\``,
+ },
+ },
+ aiCreateTail: (targetAgentId: string): string =>
+ "Use the `benchmark-design` Skill: as the Builder, design and calibrate a Benchmark for the Test Agent below without changing that agent itself.\n\n" +
+ `- test_agent_id: \`${targetAgentId}\`\n` +
+ "- benchmark_id: keep the one named above if any; otherwise derive a short semantic id (letters, digits, `_` and `-` only)\n" +
+ "- desired_baseline_score: `<70` (unless the text above says otherwise)\n" +
+ "- pilot_iteration_limit: `3` (the draft above wins when it names one)\n\n" +
+ "A Benchmark sits beside agents, not under one: create `benchmarks/<benchmark_id>/` under the Project (never inside the tested agent's directory) with " +
+ "`benchmark_config.toml` (title, description, runs = 1; it records no agent), " +
+ "one `CASE-NNN-<slug>/` per case (`statement/README.md` is the statement, `rubric/README.md` the scoring rubric, 100 points per case, nothing from the rubric leaking into the statement) " +
+ "and `scoreboard.yaml` (initially `evaluations: []`; every evaluation records the tested `agent_id`, its `version`, the paired `provider` / `model_id` and the `thinking_level`). " +
+ "Delegate one `agent-evaluation` run per case through `run_subagent` to calibrate difficulty, " +
+ "freeze the final revision, append the Formal Baseline to scoreboard.yaml, and finish by reporting the Benchmark id, the baseline score and the per-case scores.",
+ manualCreateTitle: "Create a Benchmark manually",
+ manualCreateIntro:
+ "Fill in the title, the statements and the rubrics; the directory layout the Skills expect is written under the Project's benchmarks/. A Benchmark sits beside agents, so it can then evaluate any of them.",
+ idField: "Benchmark id",
+ idHint:
+ "The directory name is the identifier: letters, digits, _ and - only, e.g. report-writing-v1",
+ idExists: "A Benchmark with this id already exists; pick another",
+ titleField: "Title",
+ descriptionField: "Description",
+ descriptionHint: "One line on what capability is tested and what makes the cases hard",
+ runsField: "Runs per case",
+ runsHint:
+ "An integer from 1 to 1000; optimization runs every case this many times and averages",
+ runsInfo:
+ "Repeated runs separate a stable capability gap from chance, at a cost that scales with the count. AI calibration always uses one run per case; this value is for the optimization that follows.",
+ casesTitle: "Cases",
+ casesInfo:
+ "Every case has two halves: the statement goes to the Test Agent; the rubric is seen only by the evaluator and never enters the Test Agent's Workspace.",
+ rubricInfo:
+ "A discriminating rubric has observable items totalling 100 points, and puts most of the points on decisions or artifacts where doing it right and merely looking right diverge — never a high floor for format compliance.",
+ caseHeading: (n: number): string => `Case ${n}`,
+ caseSlugField: "Directory suffix",
+ caseSlugHint: (id: string): string => `Directory ${id}: letters, digits, _ and - only`,
+ caseTitleField: "Case title",
+ caseStatementField: "Statement",
+ caseStatementHint:
+ "Markdown; state the objective, the given materials, the required artifact and its format — never hint at the solution or the scoring",
+ caseRubricField: "Scoring rubric",
+ caseRubricHint:
+ 'Markdown; one item per line with its points, totalling 100, e.g. "- 40 pts: …"',
+ addCase: "Add case",
+ removeCase: "Remove this case",
+ createSubmit: "Create Benchmark",
+ created: "Benchmark created",
+ invalidId: "Letters, digits, _ and - only",
+ invalidRuns: "Must be an integer from 1 to 1000",
+ invalidScore: "Must be an integer from 1 to 100",
+ useTitle: (title: string): string => `Use: ${title}`,
+ testedAgent: "Tested agent",
+ evaluateDescription:
+ "AI puts the tested agent on this Benchmark for the full Case × runs matrix and appends the result to the scoreboard as one labelled evaluation.",
+ evaluateTestedAgentHint:
+ "Evaluated as its Agent State stands right now; the score is recorded under it, labelled with its version, model and thinking level",
+ evaluatorAgent: "Evaluator agent",
+ evaluatorAgentHint:
+ "The one that spawns the evaluation subagents, scores against the rubric and writes the scoreboard; needs the agent-evaluation Skill",
+ evaluatorMissingSkill:
+ "This agent does not have the agent-evaluation Skill installed and will most likely not complete the evaluation — switch to the default agent, or install the agent-tuning plugin on it first.",
+ evaluateSessionModel: "Model of the evaluation conversation",
+ evaluateSessionModelHint:
+ "The model that dispatches and totals the runs, the Project's default model unless changed; the tested agent uses the model it is configured with, which is not changed here",
+ evaluateRunsHint:
+ "How many times every case runs, averaged; defaults to the Benchmark's configured count",
+ evaluateNoteField: "Note",
+ evaluateNotePlaceholder:
+ "e.g. This round checks what the last optimization actually changed; watch the two citation cases",
+ evaluateTail: (p: { targetAgentId: string; benchmarkId: string; runs: number }): string =>
+ "Use the `agent-evaluation` Skill to evaluate the Test Agent on this frozen Benchmark.\n\n" +
+ `- test_agent_id: \`${p.targetAgentId}\`\n` +
+ `- benchmark_id: \`${p.benchmarkId}\` (the Project's \`benchmarks/${p.benchmarkId}/\`, beside the agents)\n` +
+ `- runs: \`${p.runs}\`\n\n` +
+ "Evaluate the full Case × runs matrix through `run_subagent`, one self-spawned `agent-evaluation` subagent per matrix cell (omit `agent_id`); " +
+ "the evaluation runtime is the model and thinking level that tested agent is configured with right now. Require every returned result to agree on " +
+ "`agent_id`, `provider`, `model_id` and `thinking_level`, and stop rather than merge two labels into one record. Average the runs per case and the cases " +
+ "per evaluation as the scoreboard contract specifies, then append exactly ONE evaluation to `scoreboard.yaml`, labelled with `agent_id`, `version`, " +
+ "`provider` / `model_id` and `thinking_level`. Change neither the tested agent nor the Benchmark. " +
+ "Finish by reporting the total score, the per-case scores and the label the evaluation was recorded under.",
+ optimizeDescription:
+ "AI changes the Test Agent under a falsifiable hypothesis and re-evaluates; a new version is kept only when the score strictly improves.",
+ optimizerAgent: "Optimizer agent",
+ optimizerAgentHint:
+ "The one that reads the scores and Traces and edits the Test Agent; needs the agent-optimization Skill",
+ optimizerMissingSkill:
+ "This agent does not have the agent-optimization Skill installed and will most likely not complete the optimization — switch to the default agent, or install the agent-tuning plugin on it first.",
+ testedAgentHint:
+ "The agent whose Agent State is edited; its scores are recorded under it and compared only against its own same-label history",
+ sessionModel: "Model of the optimizer's conversation",
+ sessionModelHint:
+ "The model that analyzes and edits, the Project's default model unless changed; evaluations of the Test Agent keep the model the baseline recorded, which is not changed here",
+ optimizeRunsHint: "How many times every case runs per candidate version, averaged",
+ roundLimitField: "Round limit",
+ roundLimitHint: "One change per round; a round counts once its evaluation is complete",
+ targetScoreField: "Target score",
+ targetScoreHint: "Reaching it ends the loop early; defaults to ten points above the baseline",
+ focusField: "Focus",
+ focusPlaceholder:
+ "e.g. Focus on citation rules and format compliance; leave the writing style alone",
+ noBaseline:
+ "The selected tested agent has no baseline score in this Benchmark yet. Optimization needs one complete baseline evaluation to compare against — take it on the Evaluate tab first.",
+ baselineLine: (score: string, target: number): string =>
+ `Current baseline ${score} · target ${target}`,
+ optimizeTail: (p: {
+ targetAgentId: string;
+ benchmarkId: string;
+ runs: number;
+ roundLimit: number;
+ targetScore: number;
+ }): string =>
+ "Use the `agent-optimization` Skill to improve the Test Agent against its frozen Benchmark.\n\n" +
+ `- test_agent_id: \`${p.targetAgentId}\`\n` +
+ `- benchmark_id: \`${p.benchmarkId}\` (the Project's \`benchmarks/${p.benchmarkId}/\`, beside the agents)\n` +
+ `- runs: \`${p.runs}\`\n` +
+ `- desired_score: \`>=${p.targetScore}\`\n` +
+ `- candidate_round_limit: \`${p.roundLimit}\`\n\n` +
+ "Each round, state one falsifiable hypothesis from the current Reference and make one bounded change; evaluate the full Case × runs matrix through `run_subagent` with `agent-evaluation`, " +
+ "keeping the provider / model_id / thinking_level that tested agent's baseline recorded; keep the version and append an evaluation carrying `agent_id`, `version`, `provider` / `model_id` and `thinking_level` " +
+ "to scoreboard.yaml only when the total score is strictly higher than the Reference, otherwise roll back. " +
+ "Finish by reporting the scores before and after, the retained version, and each round's change and decision.",
},
errors: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 3fd027bb..3d7a78ea 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2314,8 +2314,17 @@ Benchmark:
folderGroups: {
subagent: (n: number) => `子智能体(${n})`,
schedule: (n: number) => `定时任务(${n})`,
+ benchmark: (n: number) => `评估任务(${n})`,
archived: (n: number) => `已归档(${n})`,
},
+ /**
+ * Tooltip of a folder-only group's header — a group with no active conversation of its
+ * own, only rows inside its folders (it renders collapsed and sorts last). `n` is what
+ * those folders hold, which is also the count the dimmed header shows; the Workspace path
+ * follows where the header has one, since this sentence replaces the tooltip that carried it.
+ */
+ folderOnlyGroup: (n: number, path?: string) =>
+ `仅有折叠任务:${n} 个会话${path ? `(${path})` : ""}`,
skillsBanner: (names: string[]): string => `使用技能:${names.join("、")}`,
/** Attached-file notice above a user message (file names only; the paths stay in the Trace). */
attachedFilesBanner: (names: string[]): string => `附加文件:${names.join("、")}`,
@@ -2869,9 +2878,64 @@ Benchmark:
benchmark: {
title: "评估中心",
- selectBenchmark: "在左侧选择一个 Benchmark",
- emptyAgent: "该 Agent 暂无 Benchmark",
+ /** The three step cards under the title: each says where on this page to do that step. */
+ guideFlow: [
+ {
+ title: "出题",
+ text: "点右上角「用 AI 创建」,让 AI 为某个智能体出一套题并取得基线分;也可以「手动创建」自己写题。",
+ },
+ {
+ title: "评估",
+ text: "选一个 Benchmark,点「使用」→「评估」,选好被测智能体后在新对话中发送,即得到一条带标签的分数。",
+ },
+ {
+ title: "优化",
+ text: "选一个 Benchmark,点「使用」→「优化」,设定目标分数后在新对话中发送;分数严格提升才保留新版本。",
+ },
+ ],
+ searchPlaceholder: "搜索标题、描述或被测智能体",
+ noMatches: "没有匹配的 Benchmark",
+ /** The chip shown when the address filters the list to one Agent's Benchmarks. */
+ filterByAgent: (agentId: string): string => `只看评测过 ${agentId} 的 Benchmark`,
+ clearFilter: "显示全部",
+ emptyTitle: "还没有 Benchmark",
+ emptyDescription:
+ "先让 AI 为一个智能体出题并取得基线分;之后这里会显示分数曲线与逐题明细,并可一键发起优化。",
caseCount: (n: number): string => `${n} 题`,
+ runsPerCase: (n: number): string => `每题 ${n} 次运行`,
+ notEvaluated: "尚未评测",
+ /** A draft Benchmark: the agent is still writing its cases, so card and page are masked. */
+ building: "构建中",
+ buildingHint: "智能体还在出题与校准难度,构建完成后即可使用",
+ buildingDetail: "构建完成后,这里会显示题目、分数曲线与评估明细。",
+ /** A Benchmark whose calibration never finished: unusable, so the card and page are masked. */
+ creationFailed: "创建失败",
+ creationFailedHint: "题目难度未能校准完成,请删除后重新创建",
+ creationFailedDetail:
+ "这套题的难度校准没有完成,无法评估或优化;请删除这个 Benchmark,然后重新创建。",
+ /** The avatars on a card: which Agents this Benchmark has scored so far. */
+ testedAgents: "被测过的智能体",
+ lastEvaluated: (when: string): string => `最近评估 ${when}`,
+ /** Accessible name of the row sparkline. */
+ sparklineLabel: (n: number): string => `${n} 次评估的分数走势`,
+ latestScoreLabel: "最新分数",
+ /** The change column when there is nothing earlier to compare against. */
+ firstEvaluation: "首次评估",
+ /** Card and Benchmark-page action: opens the Use dialog. */
+ use: "使用",
+ /** The Use dialog's two tabs. */
+ evaluate: "评估",
+ optimize: "优化",
+ view: "查看",
+ copyPath: "复制目录路径",
+ deleteBenchmark: "删除 Benchmark",
+ deleteConfirm: (title: string): string =>
+ `确定删除「${title}」吗?它的全部题目与评估记录都会被删除,无法恢复。`,
+ deleted: "Benchmark 已删除",
+ backToList: "返回列表",
+ /** The Benchmark's own page when the id in the address resolves to nothing. */
+ notFound: "找不到这个 Benchmark",
+ notFoundHint: "它可能已被删除,或者链接里的 id 不对。",
/** Score-only chart title. */
trendTitle: (metric: string): string => `${metric}随时间变化`,
cases: "题目",
@@ -2882,10 +2946,12 @@ Benchmark:
caseFileUnavailable: "案例文件暂时无法读取",
evaluations: "评估明细",
noEvaluations: "暂无评估记录",
+ noEvaluationsHint: "取得基线分后,这里会出现分数曲线与评估明细。",
/** Evaluation notes (scoreboard's summary: score source and notes on this round's changes). */
summaryLabel: "评估说明",
- /** Chart legend: older evaluation records with no model label (gray series). */
- legendUnlabeled: "未标注模型",
+ /** Chart legend: evaluation records missing the tested Agent or the model (gray series). */
+ unlabeled: "未标注",
+ agentColumn: "被测 Agent",
colVersion: "版本",
colModel: "模型 ID",
colThinkingLevel: "推理强度",
@@ -2894,6 +2960,282 @@ Benchmark:
colCase: "题目",
colRun: "运行",
colSession: "Session",
+ // The evaluation detail dialog, and the Ask AI dialog both detail dialogs open.
+ askAi: "问 AI",
+ evaluationDetailTitle: (time: string): string => `评估 · ${time}`,
+ askEvaluationTitle: "问 AI:这次评估",
+ askEvaluationDescription:
+ "这次评估的总分、逐题得分与逐次运行的 Session id 会一起交给智能体,它读过记分板与相关 Trace 后作答;提示词可以改。",
+ askEvaluationDefault: "解释这次评估的结果。",
+ /** The default question leads the examples (it is what the box opens with), so a reader who tried another can bring it back. Keep `explain.prompt` equal to askEvaluationDefault. */
+ askEvaluationExamples: {
+ explain: {
+ label: "解释这次评估的结果",
+ prompt: "解释这次评估的结果。",
+ },
+ whyLow: {
+ label: "为什么这次分数低?",
+ prompt: "为什么这次评估的分数偏低?请结合逐题得分与运行记录说明主要失分在哪里。",
+ },
+ weakest: {
+ label: "哪些题最弱、该改什么?",
+ prompt: "哪几道题得分最弱?分别是什么原因,被测智能体改哪一处才有机会提上去?",
+ },
+ againstPrevious: {
+ label: "与上一次评估相比变化在哪?",
+ prompt: "与这个系列上一次评估相比,哪些题涨了、哪些题掉了?这些变化最可能来自什么?",
+ },
+ },
+ /** The evaluation dialog's Ask AI tail: this evaluation's facts, and what to read before answering. */
+ askEvaluationTail: (p: {
+ benchmarkId: string;
+ time: string;
+ label: string;
+ version: number;
+ provider: string;
+ modelId: string;
+ thinkingLevel: string;
+ score: string;
+ cost: string;
+ duration: string;
+ summaryTitle: string;
+ summary: string;
+ cases: { id: string; score: string; cost: string; duration: string; sessionIds: string[] }[];
+ }): string =>
+ "请解释下面这次 Benchmark 评估的结果。只做阅读与分析:不要修改这套 Benchmark,也不要修改被测智能体。\n\n" +
+ `- benchmark_id:\`${p.benchmarkId}\`(Project 的 \`benchmarks/${p.benchmarkId}/\`,记分板为 \`benchmarks/${p.benchmarkId}/scoreboard.yaml\`)\n` +
+ `- 评估时间:${p.time}\n` +
+ `- 系列标签:${p.label}\n` +
+ `- 被测版本:v${p.version}\n` +
+ `- 评测 Runtime:provider \`${p.provider}\` / model_id \`${p.modelId}\` / thinking_level \`${p.thinkingLevel}\`\n` +
+ `- 总分 ${p.score};成本 ${p.cost};耗时 ${p.duration}\n` +
+ (p.summaryTitle !== "" ? `- 评估说明标题:${p.summaryTitle}\n` : "") +
+ (p.summary !== "" ? `- 评估说明:${p.summary}\n` : "") +
+ "- 逐题得分(分数、成本、耗时,以及逐次运行的 Session id):\n" +
+ p.cases
+ .map(
+ (c) =>
+ ` - \`${c.id}\`:${c.score};${c.cost};${c.duration};Session ` +
+ (c.sessionIds.length > 0 ? c.sessionIds.map((id) => `\`${id}\``).join("、") : "未记录"),
+ )
+ .join("\n") +
+ "\n\n请读取 scoreboard.yaml 里这条记录,并按需读取上列 Session 的 Trace,然后说明:这些分数是怎么来的、" +
+ "哪几道题最薄弱及其具体原因,以及下一步建议(改被测智能体的哪一处,或先补哪一类证据)。",
+ askCaseTitle: "问 AI:这道题",
+ askCaseDescription:
+ "题干与评分细则的路径会交给智能体,请它讲清这道题考什么、怎样才算答好;题目已冻结,它只读不改。",
+ askCaseDefault: "解释这道题考什么、怎样才算答好。",
+ /** As for the evaluation dialog: the default question leads, equal to askCaseDefault. */
+ askCaseExamples: {
+ explain: {
+ label: "解释这道题考什么、怎样才算答好",
+ prompt: "解释这道题考什么、怎样才算答好。",
+ },
+ rubricRewards: {
+ label: "评分细则在奖励什么?",
+ prompt: "这道题的评分细则把分数主要放在哪些地方?哪些条目最能把优秀与及格区分开?",
+ },
+ whyRunLow: {
+ label: "为什么有的运行在这道题上得分低?",
+ prompt: "最近一次评估在这道题上得分不高,可能是被测智能体在哪一步做丢了?",
+ },
+ clearerStatement: {
+ label: "题干怎样才能更清楚?",
+ prompt:
+ "这道题的题干有没有含糊或容易误读的地方?题目已冻结不能改,请说明如果下次新建 Benchmark 该怎么写得更清楚。",
+ },
+ },
+ /** The case dialog's Ask AI tail: the two READMEs to read, and this case's latest run results. */
+ askCaseTail: (p: {
+ benchmarkId: string;
+ caseId: string;
+ latest: { time: string; score: string; runs: { score: string; sessionId: string }[] } | null;
+ }): string =>
+ "请解释下面这道 Benchmark 题目考的是什么、怎样才算答好。题目创建即冻结,只做阅读与分析,不要修改这套 Benchmark。\n\n" +
+ `- benchmark_id:\`${p.benchmarkId}\`(Project 的 \`benchmarks/${p.benchmarkId}/\`)\n` +
+ `- case_id:\`${p.caseId}\`\n` +
+ `- 题干:\`benchmarks/${p.benchmarkId}/${p.caseId}/statement/README.md\`\n` +
+ `- 评分细则:\`benchmarks/${p.benchmarkId}/${p.caseId}/rubric/README.md\`\n` +
+ (p.latest === null
+ ? "- 这套 Benchmark 还没有评估记录。\n"
+ : `- 最近一次评估(${p.latest.time})在这道题上的平均分 ${p.latest.score}\n` +
+ p.latest.runs
+ .map((r, i) => ` - 第 ${i + 1} 次运行:${r.score};Session \`${r.sessionId}\`\n`)
+ .join("")) +
+ "\n请读取上面两个 README(以及上列 Session 的 Trace,如果有),然后说明:这道题实际考察什么能力、" +
+ "一份好答案长什么样(关键决定与产物),以及评分细则靠哪些条目把优秀与及格区分开。",
+ // New Benchmark, AI mode: the target picker, the examples and the fixed tail.
+ aiCreateTitle: "让 AI 创建 Benchmark",
+ aiCreateDescription:
+ "描述要考察的能力与场景,AI 会为被测智能体出题、逐题试测以校准难度,并取得基线分。",
+ targetAgent: "被测智能体",
+ targetAgentHint: "题目为它而出、分数记在它名下;出题本身由下方所示的智能体在新对话里完成",
+ aiCreateExamples: {
+ reportWriter: {
+ label: "报告写作:材料互相矛盾的 3 道题",
+ description: "3 道题:冲突材料、缺失口径、严格篇幅与引用",
+ prompt: `为报告写作智能体出一套题量少而难的 Benchmark,把基线分压低。
+
+- benchmark_id:\`report-conflicting-sources\`
+- capability:在材料互相矛盾、关键口径没有写明、篇幅与引用受限时,仍能交出结论可追溯、口径一致的报告
+- 题量:3 道
+- 出题手法:每题给 2–3 份彼此冲突的材料,其中一份日期更新但只在页脚标注;币种、时区、统计口径等关键前提刻意不写全,正确做法是先指出缺口、再做保守假设并标明;篇幅上限与引用格式严格,超限或漏引直接失分
+- desired_baseline_score:\`<50\`
+- pilot_iteration_limit:\`4\``,
+ },
+ customerService: {
+ label: "客服:隐藏政策前提的 3 道对话题",
+ description: "3 道题:信息不全的用户、藏在附录的政策条件、越权承诺陷阱",
+ prompt: `为客服智能体出一套题量少而难的多轮对话 Benchmark,把基线分压低。
+
+- benchmark_id:\`support-hidden-policy\`
+- capability:在用户信息不全、政策条件藏在资料深处、情绪化表达诱导越权承诺时,仍能先核实再答复、不越权、口径与政策一致
+- 题量:3 道
+- 出题手法:政策文件的例外条款与生效日期只出现在附录;用户描述模糊,关键事实要追问才给;至少一题里最顺手的答复正是越权承诺;评分看是否核实、是否越权、语气与准确性
+- desired_baseline_score:\`<50\`
+- pilot_iteration_limit:\`4\``,
+ },
+ codeReview: {
+ label: "代码审查:缺陷藏在约定里的 3 道题",
+ description: "3 道题:调用约定与并发前提未写明,注释与测试会误导",
+ prompt: `为代码审查智能体出一套题量少而难的 Benchmark,把基线分压低。
+
+- benchmark_id:\`review-hidden-contracts\`
+- capability:在缺陷藏在调用约定、并发前提与数据形态里、注释与测试反而误导时,仍能查全真实缺陷、不误报、并说明如何验证
+- 题量:3 道
+- 出题手法:每题一个小型多文件仓库,2–3 个真实缺陷分别依赖未写明的调用顺序、时区或编码假设、并发前提;附带一两条过时注释和一份能通过却覆盖不到缺陷的测试;评分看查全、误报与是否给出可复现的验证步骤
+- desired_baseline_score:\`<50\`
+- pilot_iteration_limit:\`4\``,
+ },
+ dataAnalysis: {
+ label: "数据分析:问题模糊、数据带坑的 3 道题",
+ description: "3 道题:脏数据、未说明的口径、需要先澄清假设",
+ prompt: `为数据分析智能体出一套题量少而难的 Benchmark,把基线分压低。
+
+- benchmark_id:\`analysis-ambiguous-asks\`
+- capability:在业务问题表述模糊、数据带脏值与未说明的口径时,先澄清假设再分析,结论正确且口径可核对
+- 题量:3 道
+- 出题手法:每题附一份带重复行、混合单位与缺失值的 CSV,字段含义只有一部分写在数据字典里;业务问题本身有两种合理解读,正确做法是指出分歧、按标明的假设分别作答;评分看结论、口径说明与图表是否与结论一致
+- desired_baseline_score:\`<50\`
+- pilot_iteration_limit:\`4\``,
+ },
+ },
+ /** The fixed tail after the draft: the `benchmark-design` inputs and the layout it writes. */
+ aiCreateTail: (targetAgentId: string): string =>
+ "请使用 `benchmark-design` Skill,作为 Builder 为下面的被测智能体设计并校准一套 Benchmark,不要修改被测智能体本身。\n\n" +
+ `- test_agent_id:\`${targetAgentId}\`\n` +
+ "- benchmark_id:上文已指定则沿用,否则按场景取一个简短的语义化 id(仅字母、数字、`_` 和 `-`)\n" +
+ "- desired_baseline_score:`<70`(上文另有要求时以上文为准)\n" +
+ "- pilot_iteration_limit:`3`(上文另有要求时以上文为准)\n\n" +
+ "Benchmark 与 Agent 平级:在 Project 的 `benchmarks/<benchmark_id>/` 下(不在被测智能体目录内)创建 `benchmark_config.toml`" +
+ "(title、description、runs = 1;不记录被测智能体)、" +
+ "每题一个 `CASE-NNN-<slug>/`(`statement/README.md` 为题干,`rubric/README.md` 为评分细则,每题满分 100 分,细则不得泄露到题干)" +
+ "以及 `scoreboard.yaml`(初始为 `evaluations: []`;每条 evaluation 记录被测的 `agent_id`、`version`、成对的 `provider` / `model_id` 与 `thinking_level`)。" +
+ "通过 `run_subagent` 委派 `agent-evaluation` 逐题试测以校准难度," +
+ "定稿后冻结并把 Formal Baseline 追加进 scoreboard.yaml,最后报告 Benchmark id、基线分数与各题得分。",
+ // New Benchmark, manual mode: the form.
+ manualCreateTitle: "手动创建 Benchmark",
+ manualCreateIntro:
+ "填好标题、题干与评分细则后,目录结构会按技能约定写入 Project 的 benchmarks/ 下;Benchmark 与 Agent 平级,之后可以用它评测任意智能体。",
+ idField: "Benchmark id",
+ idHint: "目录名即标识:仅字母、数字、_ 和 -,例如 report-writing-v1",
+ idExists: "已有同名 Benchmark,请换一个 id",
+ titleField: "标题",
+ descriptionField: "描述",
+ descriptionHint: "一句话说明考察什么能力、题目难在哪里",
+ runsField: "每题运行次数",
+ runsHint: "1–1000 的整数;优化时每道题跑这么多次取平均",
+ runsInfo:
+ "多次运行能把稳定的能力差距和偶然波动分开,但评测成本按次数倍增。AI 出题校准时固定每题 1 次;这里的值给之后的优化用。",
+ casesTitle: "题目",
+ casesInfo:
+ "每道题分两部分:题干交给被测智能体;评分细则只有评测方能看到,永远不进被测智能体的 Workspace。",
+ rubricInfo:
+ "有区分度的评分细则:条目可观察、合计 100 分,把分数主要放在「真正做对」和「看起来做对」会产生不同结果的决定或产物上,不要给格式合规太高的保底分。",
+ caseHeading: (n: number): string => `第 ${n} 题`,
+ caseSlugField: "目录名后缀",
+ caseSlugHint: (id: string): string => `目录名 ${id}:仅字母、数字、_ 和 -`,
+ caseTitleField: "题目标题",
+ caseStatementField: "题干",
+ caseStatementHint: "Markdown;写明目标、给定材料、要求的产物与格式,不要暗示解法或评分点",
+ caseRubricField: "评分细则",
+ caseRubricHint: "Markdown;逐条给分并合计 100 分,如「- 40 分:……」",
+ addCase: "添加题目",
+ removeCase: "删除此题",
+ createSubmit: "创建 Benchmark",
+ created: "Benchmark 已创建",
+ invalidId: "仅允许字母、数字、_ 和 -",
+ invalidRuns: "必须是 1–1000 的整数",
+ invalidScore: "必须是 1–100 的整数",
+ // Use: one dialog with an Evaluate tab and an Optimize tab, over a single exit.
+ useTitle: (title: string): string => `使用:${title}`,
+ // Shared by both tabs.
+ testedAgent: "被测智能体",
+ // Evaluate tab.
+ evaluateDescription:
+ "AI 会把被测智能体放到这套 Benchmark 上跑完整的 Case × runs 矩阵,并把结果作为一条带标签的评估追加进记分。",
+ evaluateTestedAgentHint:
+ "评估的是它当下的 Agent State;分数记在它名下,标签含其版本号、模型与思考等级",
+ evaluatorAgent: "执行评估的智能体",
+ evaluatorAgentHint:
+ "派发评测子会话、按评分细则打分并写入记分的一方;需要装有 agent-evaluation 技能",
+ evaluatorMissingSkill:
+ "该智能体没有安装 agent-evaluation 技能,多半无法完成评估——建议换用默认智能体,或先为它安装 agent-tuning 插件。",
+ evaluateSessionModel: "评估会话使用的模型",
+ evaluateSessionModelHint:
+ "派发与汇总评测的模型,缺省为 Project 默认模型;被测智能体用的是它自己配置的模型,不在这里改",
+ evaluateRunsHint: "每道题跑几次取平均;缺省为 Benchmark 配置的次数",
+ evaluateNoteField: "说明",
+ evaluateNotePlaceholder: "例如:这一轮用来确认上次优化的效果,重点看引用规范那两道题",
+ /** The fixed tail: the `agent-evaluation` inputs, the label check and the single append. */
+ evaluateTail: (p: { targetAgentId: string; benchmarkId: string; runs: number }): string =>
+ "请使用 `agent-evaluation` Skill,在这套已冻结的 Benchmark 上评估被测智能体。\n\n" +
+ `- test_agent_id:\`${p.targetAgentId}\`\n` +
+ `- benchmark_id:\`${p.benchmarkId}\`(Project 的 \`benchmarks/${p.benchmarkId}/\`,与 Agent 平级)\n` +
+ `- runs:\`${p.runs}\`\n\n` +
+ "通过 `run_subagent` 按完整的 Case × runs 矩阵评测,每个矩阵单元一个自调用的 `agent-evaluation` 子会话(省略 `agent_id`);" +
+ "评测 Runtime 取被测智能体当前配置的模型与思考等级。校验每条返回结果的 `agent_id`、`provider`、`model_id` 与 `thinking_level` 完全一致," +
+ "不一致就停下、不要把不同标签混成一条。按记分契约求各题(runs 平均)与整体(各题平均)的分数," +
+ "然后只向 `scoreboard.yaml` 追加一条 evaluation,记上 `agent_id`、`version`、`provider` / `model_id` 与 `thinking_level` 作为标签。" +
+ "不修改被测智能体,也不修改 Benchmark。结束时报告总分、各题得分与本条记录的标签。",
+ // Optimize tab.
+ optimizeDescription: "AI 会按可证伪的假设修改被测智能体并重新评测,分数严格提升才保留新版本。",
+ optimizerAgent: "执行优化的智能体",
+ optimizerAgentHint: "读分数与 Trace、修改被测智能体的一方;需要装有 agent-optimization 技能",
+ optimizerMissingSkill:
+ "该智能体没有安装 agent-optimization 技能,多半无法完成优化——建议换用默认智能体,或先为它安装 agent-tuning 插件。",
+ testedAgentHint: "优化改的是它的 Agent State;分数记在它名下,只与它自己同标签的历史分数比较",
+ sessionModel: "优化会话使用的模型",
+ sessionModelHint:
+ "做分析与改动的模型,缺省为 Project 默认模型;评测被测智能体时沿用基线记录的模型,不在这里改",
+ optimizeRunsHint: "每个候选版本每道题跑几次取平均",
+ roundLimitField: "最多轮数",
+ roundLimitHint: "每轮一个改动;评测完整才算一轮",
+ targetScoreField: "目标分数",
+ targetScoreHint: "达到即提前结束;默认比当前基线高 10 分",
+ focusField: "优化重点",
+ focusPlaceholder: "例如:重点优化引用规范与格式合规,不要改动写作风格",
+ noBaseline:
+ "所选被测智能体在这套 Benchmark 上还没有基线分。优化需要一条完整的基线评估作为比较起点——先到「评估」跑一次完整评测取得基线。",
+ baselineLine: (score: string, target: number): string => `当前基线 ${score} · 目标 ${target}`,
+ /** The fixed tail: the `agent-optimization` inputs, the acceptance rule and the report. */
+ optimizeTail: (p: {
+ targetAgentId: string;
+ benchmarkId: string;
+ runs: number;
+ roundLimit: number;
+ targetScore: number;
+ }): string =>
+ "请使用 `agent-optimization` Skill,针对已冻结的 Benchmark 优化被测智能体。\n\n" +
+ `- test_agent_id:\`${p.targetAgentId}\`\n` +
+ `- benchmark_id:\`${p.benchmarkId}\`(Project 的 \`benchmarks/${p.benchmarkId}/\`,与 Agent 平级)\n` +
+ `- runs:\`${p.runs}\`\n` +
+ `- desired_score:\`>=${p.targetScore}\`\n` +
+ `- candidate_round_limit:\`${p.roundLimit}\`\n\n` +
+ "每轮从当前 Reference 出发提出一个可证伪的假设、只做一个有界改动;通过 `run_subagent` 委派 `agent-evaluation` 评测完整的 Case × runs 矩阵," +
+ "评测沿用该被测智能体基线记录的 provider / model_id / thinking_level;仅当总分严格高于 Reference 时保留该版本," +
+ "并把记有 `agent_id`、`version`、`provider` / `model_id` 与 `thinking_level` 的 evaluation 追加到 scoreboard.yaml,否则回滚。" +
+ "结束时报告优化前后的分数、保留的版本号,以及每轮的改动与取舍。",
},
// Server error code → localized copy (the server's message is hardcoded Chinese; this is only a fallback for unknown codes).
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index fae06ede..de2d3259 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -16,6 +16,7 @@ import { PluginsPage } from "./features/plugins/plugins-page";
import { ModelsPage } from "./features/models/models-page";
import { UsagePage } from "./features/usage/usage-page";
import { BenchmarkPage } from "./features/benchmark/benchmark-page";
+import { BenchmarkDetailPage } from "./features/benchmark/benchmark-detail-page";
import { TerminalPage } from "./features/terminal/terminal-page";
/** Route guard: shows blank while initializing, redirects to /login when not authenticated. */
@@ -75,6 +76,7 @@ export function AppRouter() {
everyone else, so a member only ever reaches this by typing the URL. */}
<Route path="/usage" element={<UsagePage />} />
<Route path="/benchmark" element={<BenchmarkPage />} />
+ <Route path="/benchmark/:benchmarkId" element={<BenchmarkDetailPage />} />
{/* System settings and user management live in the settings dialog now (see
SettingsDialog); their old routes fall through to the catch-all. */}
<Route path="*" element={<Navigate to="/chat" replace />} />
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index c3e9d411..03e1164f 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -4,8 +4,8 @@
* the chat page shares this same data for status sync / title events / self-healing reload.
*
* **Paged per (Agent, category)**: the default load fetches only the **active** category
- * (user-created, non-archived) plus per-category totals — archived / subagent / schedule
- * Sessions are not loaded until their collapsed folder is opened. Each pair fetches
+ * (user-created, non-archived) plus per-category totals — archived / subagent / schedule /
+ * benchmark Sessions are not loaded until their collapsed folder is opened. Each pair fetches
* SIDEBAR_PAGE_SIZE sessions per page (requesting one extra to detect "has more" — see
* splitPage); `loadMoreFor` fetches a pair's first page when unloaded and the next page
* otherwise (deduplicated by sessionId — new sessions shift server offsets), so every
@@ -229,7 +229,13 @@ export function createSessionsStore() {
const workspaceCounts = get().workspaceCountsByAgent;
const wsCur = workspaceCounts.get(agentId);
if (wsCur) {
- const ws = wsCur[workspace] ?? { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const ws = wsCur[workspace] ?? {
+ active: 0,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ };
const next = new Map(workspaceCounts);
next.set(agentId, {
...wsCur,
diff --git a/packages/web/test/ai-bridge.test.ts b/packages/web/test/ai-bridge.test.ts
index a5db25f1..7632fc28 100644
--- a/packages/web/test/ai-bridge.test.ts
+++ b/packages/web/test/ai-bridge.test.ts
@@ -17,6 +17,15 @@ describe("buildAiDraft", () => {
expect(draft.text).toBe("prompt");
});
+ it("replaces the cached model only when the request pins one", () => {
+ const cached = { modelRef: { provider: "p", modelId: "m" } };
+ expect(buildAiDraft(cached, { agentId: "a", text: "t" }).modelRef).toEqual(cached.modelRef);
+ expect(
+ buildAiDraft(cached, { agentId: "a", text: "t", modelRef: { provider: "q", modelId: "n" } })
+ .modelRef,
+ ).toEqual({ provider: "q", modelId: "n" });
+ });
+
it("resets the skill selection unless the request pins one", () => {
expect(buildAiDraft({ skills: ["old"] }, { agentId: "a", text: "t" }).skills).toEqual([]);
expect(buildAiDraft({}, { agentId: "a", text: "t", skills: ["s"] }).skills).toEqual(["s"]);
diff --git a/packages/web/test/benchmark-case-tree.test.ts b/packages/web/test/benchmark-case-tree.test.ts
new file mode 100644
index 00000000..e7674901
--- /dev/null
+++ b/packages/web/test/benchmark-case-tree.test.ts
@@ -0,0 +1,89 @@
+/**
+ * The Benchmark case browser's tree rows: two top-level directories, one per material, over
+ * listings fetched one directory per level — a closed material holds its children back, a
+ * directory whose listing has not arrived reports itself unloaded, and every path names the
+ * material it came from so the two file spaces cannot collide.
+ */
+import { describe, expect, it } from "vitest";
+import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";
+import { caseTreeRows } from "../src/features/benchmark/benchmark-case-browser";
+import type { CaseMaterialSpec } from "../src/features/benchmark/benchmark-case-browser";
+
+const MTIME = "2026-09-12T00:00:00.000Z";
+
+const dir = (name: string): WorkspaceFileEntry => ({
+ name,
+ kind: "dir",
+ sizeBytes: 0,
+ mtime: MTIME,
+});
+const file = (name: string, sizeBytes = 12): WorkspaceFileEntry => ({
+ name,
+ kind: "file",
+ sizeBytes,
+ mtime: MTIME,
+});
+
+const MATERIALS: CaseMaterialSpec[] = [
+ { material: "statement", label: "Task materials" },
+ { material: "rubric", label: "Scoring rubric" },
+];
+
+const LISTINGS = new Map<string, WorkspaceFileEntry[]>([
+ ["statement", [dir("assets"), file("README.md")]],
+ ["statement/assets", [file("chart.png", 2048)]],
+ ["rubric", [file("README.md")]],
+]);
+
+describe("caseTreeRows", () => {
+ it("walks every open directory and prefixes each path with its material", () => {
+ const expanded = new Set(["statement", "statement/assets", "rubric"]);
+ expect(
+ caseTreeRows(MATERIALS, LISTINGS, expanded).map((r) => [r.path, r.kind, r.depth, r.material]),
+ ).toEqual([
+ ["statement", "dir", 0, "statement"],
+ ["statement/assets", "dir", 1, "statement"],
+ ["statement/assets/chart.png", "file", 2, "statement"],
+ ["statement/README.md", "file", 1, "statement"],
+ ["rubric", "dir", 0, "rubric"],
+ ["rubric/README.md", "file", 1, "rubric"],
+ ]);
+ });
+
+ it("keeps a closed material's row and none of its children", () => {
+ const rows = caseTreeRows(MATERIALS, LISTINGS, new Set(["rubric"]));
+ expect(rows.map((r) => r.path)).toEqual(["statement", "rubric", "rubric/README.md"]);
+ expect(rows[0]).toMatchObject({ expanded: false, loaded: true, empty: false });
+ });
+
+ it("reports a directory whose listing has not arrived as unloaded", () => {
+ const expanded = new Set(["statement", "statement/assets", "rubric"]);
+ const rows = caseTreeRows(MATERIALS, new Map([["statement", [dir("assets")]]]), expanded);
+ expect(rows.map((r) => [r.path, r.loaded, r.expanded])).toEqual([
+ ["statement", true, true],
+ // Open, and waiting for its own listing: no children, and the tree draws no group for it.
+ ["statement/assets", false, true],
+ ["rubric", false, true],
+ ]);
+ });
+
+ it("marks a listed directory holding nothing as empty", () => {
+ const rows = caseTreeRows(MATERIALS, new Map([["statement", []]]), new Set(["statement"]));
+ expect(rows[0]).toMatchObject({ path: "statement", loaded: true, empty: true });
+ });
+
+ it("states each row's own position among its siblings, for the flat list to announce", () => {
+ const expanded = new Set(["statement", "statement/assets", "rubric"]);
+ expect(
+ caseTreeRows(MATERIALS, LISTINGS, expanded).map((r) => `${r.posInSet}/${r.setSize}`),
+ ).toEqual(["1/2", "1/2", "1/1", "2/2", "2/2", "1/1"]);
+ });
+
+ it("carries a file's size for the row to show, and none for a directory", () => {
+ const rows = caseTreeRows(MATERIALS, LISTINGS, new Set(["statement", "statement/assets"]));
+ const sizes = new Map(rows.map((r) => [r.path, r.sizeBytes] as const));
+ expect(sizes.get("statement/assets/chart.png")).toBe(2048);
+ expect(sizes.get("statement/assets")).toBe(0);
+ expect(sizes.get("statement")).toBe(0);
+ });
+});
diff --git a/packages/web/test/benchmark-metrics.test.ts b/packages/web/test/benchmark-metrics.test.ts
index 4a4d7630..2c117990 100644
--- a/packages/web/test/benchmark-metrics.test.ts
+++ b/packages/web/test/benchmark-metrics.test.ts
@@ -1,15 +1,25 @@
/**
* Unit tests for the Evaluation center's Score-only chart helpers: Score extraction,
- * dynamic y-axis range, and runtime grouping. The gap segmentation these series are drawn
- * with is shared chart geometry (chart-geom's lineSegments, covered in usage-charts.test.ts).
+ * dynamic y-axis range, and label grouping — the tested Agent, the model and the thinking
+ * level, which is also what a score change is measured within. The Agent State version and the
+ * provider are on the record and outside the key, so successive versions of one agent stay on
+ * one line. The gap segmentation these series are drawn with is shared chart geometry
+ * (chart-geom's lineSegments, covered in usage-charts.test.ts).
*/
import { describe, expect, it } from "vitest";
import {
- modelSeries,
+ defaultTargetScore,
+ evaluationLabel,
+ labelSeries,
+ latestScoreOfAgent,
+ latestWithDelta,
+ matchesBenchmarkQuery,
scoreScale,
scoreValues,
seriesValues,
+ sparklineSeries,
} from "../src/features/benchmark/benchmark-metrics";
+import type { EvaluationLabelLike } from "../src/features/benchmark/benchmark-metrics";
const evaluations = [{ score: 60 }, { score: 75.25 }, { score: 85.5 }];
@@ -61,81 +71,209 @@ describe("scoreScale (dynamic padded Score axis)", () => {
});
});
-describe("modelSeries / seriesValues (curves split by model ID and thinking level)", () => {
- const mixed = [
- {
- score: 6,
- provider: "deepseek",
- modelId: "deepseek-v4-flash",
- thinkingLevel: "medium",
- },
+describe("evaluationLabel", () => {
+ const full = {
+ agentId: "report-writer",
+ version: 3,
+ provider: "deepseek",
+ modelId: "deepseek-v4-pro",
+ thinkingLevel: "xhigh",
+ };
+
+ it("spells the three parts a reader compares scores across", () => {
+ const label = evaluationLabel(full);
+ expect(label.text).toBe("report-writer · deepseek-v4-pro · xhigh");
+ expect(label.unlabeled).toBe(false);
+ expect(label.key).not.toBe("");
+ });
+
+ it("omits an empty part from the text", () => {
+ expect(evaluationLabel({ ...full, thinkingLevel: "" }).text).toBe(
+ "report-writer · deepseek-v4-pro",
+ );
+ });
+
+ it("the Agent State version is outside the key: a new version of one agent keeps its label", () => {
+ expect(evaluationLabel({ ...full, version: 4 }).key).toBe(evaluationLabel(full).key);
+ expect(evaluationLabel({ ...full, version: 4 }).text).toBe(evaluationLabel(full).text);
+ });
+
+ it("the provider is outside the key too: a series has to be readable from its legend text", () => {
+ expect(evaluationLabel({ ...full, provider: "siliconflow" }).key).toBe(
+ evaluationLabel(full).key,
+ );
+ });
+
+ it("separates tested Agents, models and thinking levels", () => {
+ expect(evaluationLabel({ ...full, agentId: "support" }).key).not.toBe(
+ evaluationLabel(full).key,
+ );
+ expect(evaluationLabel({ ...full, modelId: "kimi-k2.6" }).key).not.toBe(
+ evaluationLabel(full).key,
+ );
+ expect(evaluationLabel({ ...full, thinkingLevel: "medium" }).key).not.toBe(
+ evaluationLabel(full).key,
+ );
+ });
+
+ it("a record missing the tested Agent or the model is unlabeled", () => {
+ expect(evaluationLabel({ ...full, agentId: null })).toEqual({
+ key: "",
+ text: "",
+ unlabeled: true,
+ });
+ expect(evaluationLabel({ ...full, modelId: "" }).unlabeled).toBe(true);
+ expect(evaluationLabel({}).unlabeled).toBe(true);
+ });
+});
+
+describe("labelSeries / seriesValues (curves split by label)", () => {
+ const runtime = { provider: "deepseek", modelId: "deepseek-v4-pro", thinkingLevel: "xhigh" };
+ // Annotated: an untagged `{ score }` shares no property with the all-optional label type,
+ // so the inferred union would trip the weak-type check when handed to labelSeries.
+ const mixed: Array<{ score: number } & EvaluationLabelLike> = [
+ { score: 6, agentId: "report-writer", version: 1, ...runtime },
{ score: 7 }, // Defensive untagged input -> trailing gray series.
- {
- score: 7.5,
- provider: "deepseek",
- modelId: "deepseek-v4-pro",
- thinkingLevel: "xhigh",
- },
- {
- score: 8.5,
- provider: "deepseek",
- modelId: "deepseek-v4-pro",
- thinkingLevel: "xhigh",
- },
+ { score: 7.5, agentId: "report-writer", version: 2, ...runtime },
+ { score: 8.5, agentId: "report-writer", version: 3, ...runtime },
+ { score: 5, agentId: "report-writer", version: 3, ...runtime, thinkingLevel: "medium" },
];
- it("groups by (modelId, thinkingLevel) in first-appearance order; untagged records go to a trailing unnamed series", () => {
- const series = modelSeries(mixed);
- expect(series.map((s) => s.modelId)).toEqual([
- "deepseek-v4-flash",
- "deepseek-v4-pro",
- undefined,
+ it("one agent's successive versions on one runtime are a single series; unlabeled records trail it", () => {
+ const series = labelSeries(mixed);
+ expect(series.map((x) => x.text)).toEqual([
+ "report-writer · deepseek-v4-pro · xhigh",
+ "report-writer · deepseek-v4-pro · medium",
+ "",
]);
- expect(series.map((s) => s.thinkingLevel)).toEqual(["medium", "xhigh", undefined]);
- expect(series.map((s) => s.indices)).toEqual([[0], [2, 3], [1]]);
+ expect(series.map((x) => x.indices)).toEqual([[0, 2, 3], [4], [1]]);
+ expect(series.map((x) => x.unlabeled)).toEqual([false, false, true]);
expect(series[2]!.key).toBe("");
});
- it("the same model ID and thinking level across providers stays in one series", () => {
- const sameRuntime = [
- {
- score: 1,
- provider: "moonshot",
- modelId: "kimi-k2.6",
- thinkingLevel: "medium",
- },
+ it("the same runtime under two tested Agents forms separate series", () => {
+ const series = labelSeries([
+ { agentId: "report-writer", version: 1, modelId: "kimi-k2.6" },
+ { agentId: "support", version: 1, modelId: "kimi-k2.6" },
+ ]);
+ expect(series).toHaveLength(2);
+ expect(series.map((x) => x.indices)).toEqual([[0], [1]]);
+ });
+
+ it("the provider a model is served from does not start a second series", () => {
+ const series = labelSeries([
+ { agentId: "report-writer", version: 1, provider: "deepseek", modelId: "deepseek-v4-pro" },
{
- score: 2,
+ agentId: "report-writer",
+ version: 2,
provider: "siliconflow",
- modelId: "kimi-k2.6",
- thinkingLevel: "medium",
+ modelId: "deepseek-v4-pro",
},
- ];
- const series = modelSeries(sameRuntime);
+ ]);
expect(series).toHaveLength(1);
expect(series[0]!.indices).toEqual([0, 1]);
});
- it("the same model ID at different thinking levels forms separate series", () => {
- const levels = [
- { score: 1, modelId: "deepseek-v4-pro", thinkingLevel: "medium" },
- { score: 2, modelId: "deepseek-v4-pro", thinkingLevel: "xhigh" },
- ];
- const series = modelSeries(levels);
- expect(series).toHaveLength(2);
- expect(series.map((s) => s.thinkingLevel)).toEqual(["medium", "xhigh"]);
- });
-
it("seriesValues: indexes outside the series are null (skipped points), keeping the global time axis", () => {
- const series = modelSeries(mixed);
- expect(seriesValues(mixed, series[1]!)).toEqual([null, null, 7.5, 8.5]);
- expect(seriesValues(mixed, series[2]!)).toEqual([null, 7, null, null]);
+ const series = labelSeries(mixed);
+ expect(seriesValues(mixed, series[0]!)).toEqual([6, null, 7.5, 8.5, null]);
+ expect(seriesValues(mixed, series[2]!)).toEqual([null, 7, null, null, null]);
});
it("all untagged defensive input forms one unnamed series", () => {
- const series = modelSeries([{}, {}]);
+ const series = labelSeries([{}, {}]);
expect(series).toHaveLength(1);
expect(series[0]!.key).toBe("");
expect(series[0]!.indices).toEqual([0, 1]);
});
});
+
+describe("row helpers: latestWithDelta / latestScoreOfAgent / sparklineSeries / defaultTargetScore", () => {
+ const label = { agentId: "report-writer", version: 1, provider: "deepseek", modelId: "m" };
+ const timed = [
+ { time: "2026-07-14T09:30:00Z", score: 60, ...label },
+ { time: "2026-07-15T09:30:00Z", score: Number.NaN, ...label },
+ { time: "2026-07-16T09:30:00Z", score: 72.35, ...label },
+ ];
+
+ it("latestWithDelta reports the newest finite Score, its change from the previous finite one of the same label, and its time", () => {
+ expect(latestWithDelta(timed)).toEqual({
+ score: 72.35,
+ delta: 72.35 - 60,
+ time: timed[2]!.time,
+ });
+ expect(latestWithDelta([timed[0]!])).toEqual({ score: 60, delta: null, time: timed[0]!.time });
+ expect(latestWithDelta([])).toBeNull();
+ expect(latestWithDelta([timed[1]!])).toBeNull();
+ });
+
+ it("a newest record whose label appears for the first time reports no change", () => {
+ const switched = [timed[0]!, { ...timed[2]!, modelId: "n" }];
+ expect(latestWithDelta(switched)!.delta).toBeNull();
+ // The label from two records back is the one it is comparable to.
+ const back = [timed[0]!, { ...timed[2]!, agentId: "support" }, timed[2]!];
+ expect(latestWithDelta(back)!.delta).toBe(72.35 - 60);
+ });
+
+ it("a new Agent State version is the comparison, not a new label", () => {
+ const nextVersion = [timed[0]!, { ...timed[2]!, version: 2 }];
+ expect(latestWithDelta(nextVersion)!.delta).toBe(72.35 - 60);
+ });
+
+ it("latestScoreOfAgent narrows to one tested Agent, and reports nothing when it has no score here", () => {
+ const twoAgents = [timed[0]!, { ...timed[2]!, agentId: "support", score: 90 }];
+ expect(latestScoreOfAgent(twoAgents, "report-writer")).toEqual({
+ score: 60,
+ delta: null,
+ time: timed[0]!.time,
+ });
+ expect(latestScoreOfAgent(twoAgents, "support")!.score).toBe(90);
+ expect(latestScoreOfAgent(twoAgents, "reviewer")).toBeNull();
+ expect(latestScoreOfAgent(twoAgents, "")).toBeNull();
+ });
+
+ it("sparklineSeries keeps finite Scores in scoreboard order and skips malformed ones", () => {
+ expect(sparklineSeries(timed)).toEqual([60, 72.35]);
+ expect(sparklineSeries([])).toEqual([]);
+ });
+
+ it("defaultTargetScore is ten above the baseline as a whole number, capped at 100, and 80 without one", () => {
+ expect(defaultTargetScore(72.35)).toBe(83);
+ expect(defaultTargetScore(95)).toBe(100);
+ expect(defaultTargetScore(null)).toBe(80);
+ });
+});
+
+describe("matchesBenchmarkQuery", () => {
+ const benchmark = {
+ id: "report-writing-v1",
+ title: "Report writing",
+ description: "Hard cases",
+ agentIds: ["report-writer", "support"],
+ };
+ const agents = [
+ { agentId: "report-writer", name: "Report Writer" },
+ { agentId: "support", name: "Support" },
+ { agentId: "reviewer", name: "Reviewer" },
+ ];
+
+ it("matches case-insensitively on the title, description, id, and any tested agent's name or id", () => {
+ expect(matchesBenchmarkQuery(benchmark, agents, "WRITING")).toBe(true);
+ expect(matchesBenchmarkQuery(benchmark, agents, "hard")).toBe(true);
+ expect(matchesBenchmarkQuery(benchmark, agents, "-v1")).toBe(true);
+ expect(matchesBenchmarkQuery(benchmark, agents, "report writer")).toBe(true);
+ expect(matchesBenchmarkQuery(benchmark, agents, "support")).toBe(true);
+ // An agent that never ran this Benchmark is not a match, even though the Project has it.
+ expect(matchesBenchmarkQuery(benchmark, agents, "reviewer")).toBe(false);
+ });
+
+ it("an id evaluated by a since-deleted agent still matches on the id itself", () => {
+ expect(matchesBenchmarkQuery({ ...benchmark, agentIds: ["gone-agent"] }, agents, "gone")).toBe(
+ true,
+ );
+ });
+
+ it("a blank query matches everything", () => {
+ expect(matchesBenchmarkQuery({ id: "x", title: "x" }, agents, " ")).toBe(true);
+ });
+});
diff --git a/packages/web/test/benchmark-prompts.test.ts b/packages/web/test/benchmark-prompts.test.ts
new file mode 100644
index 00000000..58828999
--- /dev/null
+++ b/packages/web/test/benchmark-prompts.test.ts
@@ -0,0 +1,296 @@
+/**
+ * The Evaluation Center's prompts and id helpers (src/features/benchmark/benchmark-prompts.ts):
+ * the Create-with-AI tail hands the benchmark-design Skill its tested Agent and the Project-level
+ * layout, the Evaluate and Optimize tails carry every input the agent-evaluation and
+ * agent-optimization Skills require, the two Ask AI tails carry the facts on screen and the
+ * files they were read from, and the manual form's directory names follow the id alphabet.
+ * Assertions on a tail's wording are language-agnostic: the ids, paths and Session ids it must
+ * name, never the sentences around them, which differ per dictionary.
+ */
+import { describe, expect, it } from "vitest";
+import { S } from "../src/lib/strings";
+import {
+ MAX_RUNS,
+ askCaseExamples,
+ askCaseTail,
+ askEvaluationExamples,
+ askEvaluationTail,
+ benchmarkCreateExamples,
+ benchmarkCreateTail,
+ benchmarkPath,
+ buildEvaluatePrompt,
+ buildOptimizePrompt,
+ caseId,
+ evaluateTail,
+ isValidRuns,
+ optimizeTail,
+ slugFromTitle,
+} from "../src/features/benchmark/benchmark-prompts";
+
+describe("benchmarkCreateTail", () => {
+ it("names the Skill, the tested Agent and the layout the Skill writes", () => {
+ const tail = benchmarkCreateTail("report-writer");
+ expect(tail).toContain("`benchmark-design`");
+ expect(tail).toContain("`report-writer`");
+ expect(tail).toContain("`agent-evaluation`");
+ expect(tail).toContain("benchmark_config.toml");
+ expect(tail).toContain("scoreboard.yaml");
+ // Benchmark design calibrates with one run per case; the tail never asks for another count.
+ expect(tail).toContain("runs = 1");
+ expect(tail).toContain("pilot_iteration_limit");
+ });
+
+ it("places the Benchmark at the Project level and has every evaluation record its tested Agent", () => {
+ const tail = benchmarkCreateTail("report-writer");
+ expect(tail).toContain("`benchmarks/<benchmark_id>/`");
+ expect(tail).not.toContain("agents/report-writer");
+ expect(tail).toContain("`agent_id`");
+ });
+
+ it("offers examples with unique keys and non-empty prompts", () => {
+ const examples = benchmarkCreateExamples();
+ expect(examples.length).toBeGreaterThanOrEqual(4);
+ expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);
+ for (const e of examples) {
+ expect(e.label).not.toBe("");
+ expect(e.prompt.trim()).not.toBe("");
+ }
+ });
+});
+
+describe("evaluateTail / buildEvaluatePrompt", () => {
+ const params = {
+ targetAgentId: "report-writer",
+ benchmarkId: "report-writing-v1",
+ runs: 2,
+ };
+
+ it("carries every input the agent-evaluation Skill requires", () => {
+ const tail = evaluateTail(params);
+ expect(tail).toContain("`agent-evaluation`");
+ expect(tail).toContain("`report-writer`");
+ expect(tail).toContain("`report-writing-v1`");
+ expect(tail).toMatch(/runs[::] ?`2`/);
+ // The Benchmark sits beside the agents, and the appended evaluation names the tested one
+ // together with the rest of its label.
+ expect(tail).toContain("`benchmarks/report-writing-v1/`");
+ expect(tail).toContain("scoreboard.yaml");
+ for (const field of ["`agent_id`", "`version`", "`provider`", "`model_id`", "`thinking_level`"])
+ expect(tail).toContain(field);
+ });
+
+ it("asks for the full matrix through self-spawned subagents and a single appended record", () => {
+ const tail = evaluateTail(params);
+ expect(tail).toContain("run_subagent");
+ expect(tail).toContain("Case × runs");
+ // The tail must not offer an optimization: this request only measures.
+ expect(tail).not.toContain("agent-optimization");
+ expect(tail).not.toContain("desired_score");
+ });
+
+ it("puts the note before the tail, and sends the tail alone when the note is blank", () => {
+ expect(buildEvaluatePrompt("Watch the citation cases.", params)).toBe(
+ `Watch the citation cases.\n\n${evaluateTail(params)}`,
+ );
+ expect(buildEvaluatePrompt(" ", params)).toBe(evaluateTail(params));
+ });
+});
+
+describe("optimizeTail / buildOptimizePrompt", () => {
+ const params = {
+ targetAgentId: "report-writer",
+ benchmarkId: "report-writing-v1",
+ runs: 2,
+ roundLimit: 3,
+ targetScore: 85,
+ };
+
+ it("carries every input the agent-optimization Skill requires", () => {
+ const tail = optimizeTail(params);
+ expect(tail).toContain("`agent-optimization`");
+ expect(tail).toContain("`report-writer`");
+ expect(tail).toContain("`report-writing-v1`");
+ expect(tail).toMatch(/runs[::] ?`2`/);
+ expect(tail).toMatch(/desired_score[::] ?`>=85`/);
+ expect(tail).toMatch(/candidate_round_limit[::] ?`3`/);
+ expect(tail).toContain("scoreboard.yaml");
+ // The Benchmark sits beside the agents, and the appended evaluation names the tested one.
+ expect(tail).toContain("`benchmarks/report-writing-v1/`");
+ expect(tail).toContain("`agent_id`");
+ });
+
+ it("puts the focus text before the tail, and sends the tail alone when the focus is blank", () => {
+ expect(buildOptimizePrompt("Focus on citations.", params)).toBe(
+ `Focus on citations.\n\n${optimizeTail(params)}`,
+ );
+ expect(buildOptimizePrompt(" ", params)).toBe(optimizeTail(params));
+ });
+});
+
+describe("askEvaluationTail (the evaluation dialog's Ask AI question)", () => {
+ const params = {
+ benchmarkId: "report-writing-v1",
+ time: "2026-07-16 09:30",
+ label: "report-writer · deepseek-v4-pro · xhigh",
+ version: 3,
+ provider: "deepseek",
+ modelId: "deepseek-v4-pro",
+ thinkingLevel: "xhigh",
+ score: "72.35",
+ cost: "$0.42",
+ duration: "3m20s",
+ summaryTitle: "Citations still weak",
+ summary: "Two cases lost points on citation format.",
+ cases: [
+ {
+ id: "CASE-001-contradictions",
+ score: "80",
+ cost: "$0.21",
+ duration: "1m40s",
+ sessionIds: ["ses-a1", "ses-a2"],
+ },
+ {
+ id: "CASE-002-citations",
+ score: "64.7",
+ cost: "$0.21",
+ duration: "1m40s",
+ sessionIds: ["ses-b1"],
+ },
+ ],
+ };
+
+ it("names the Benchmark, its scoreboard and the label facts of this record", () => {
+ const tail = askEvaluationTail(params);
+ expect(tail).toContain("`report-writing-v1`");
+ expect(tail).toContain("`benchmarks/report-writing-v1/`");
+ expect(tail).toContain("`benchmarks/report-writing-v1/scoreboard.yaml`");
+ expect(tail).toContain("2026-07-16 09:30");
+ expect(tail).toContain("report-writer · deepseek-v4-pro · xhigh");
+ expect(tail).toContain("v3");
+ expect(tail).toContain("`deepseek`");
+ expect(tail).toContain("`deepseek-v4-pro`");
+ expect(tail).toContain("`xhigh`");
+ expect(tail).toContain("72.35");
+ expect(tail).toContain("$0.42");
+ expect(tail).toContain("3m20s");
+ expect(tail).toContain("Citations still weak");
+ expect(tail).toContain("Two cases lost points on citation format.");
+ });
+
+ it("lists every case with its score and the Session id of every run", () => {
+ const tail = askEvaluationTail(params);
+ for (const c of params.cases) {
+ expect(tail).toContain(`\`${c.id}\``);
+ expect(tail).toContain(c.score);
+ for (const sessionId of c.sessionIds) expect(tail).toContain(`\`${sessionId}\``);
+ }
+ });
+
+ it("omits a summary the record does not carry, and says so when no run recorded a Session", () => {
+ const tail = askEvaluationTail({
+ ...params,
+ summaryTitle: "",
+ summary: "",
+ cases: [{ ...params.cases[0]!, sessionIds: [] }],
+ });
+ expect(tail).not.toContain("Citations still weak");
+ expect(tail).not.toContain("Two cases lost points on citation format.");
+ expect(tail).toContain("`CASE-001-contradictions`");
+ expect(tail).not.toContain("ses-a1");
+ });
+
+ // It asks for an explanation of scores already recorded: no Skill to run, nothing to change.
+ it("names no Skill and no subagent to spawn", () => {
+ const tail = askEvaluationTail(params);
+ expect(tail).not.toContain("agent-evaluation");
+ expect(tail).not.toContain("agent-optimization");
+ expect(tail).not.toContain("run_subagent");
+ });
+
+ it("offers examples with unique keys and non-empty prompts, the default question first", () => {
+ const examples = askEvaluationExamples();
+ expect(examples).toHaveLength(4);
+ expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);
+ for (const e of examples) {
+ expect(e.label).not.toBe("");
+ expect(e.prompt.trim()).not.toBe("");
+ }
+ // The box opens on the default question; the leading example IS that question, so a
+ // reader who tried another example can bring it back with one click.
+ expect(examples[0]?.prompt).toBe(S.benchmark.askEvaluationDefault);
+ });
+});
+
+describe("askCaseTail (the case dialog's Ask AI question)", () => {
+ const params = {
+ benchmarkId: "report-writing-v1",
+ caseId: "CASE-002-citations",
+ latest: {
+ time: "2026-07-16 09:30",
+ score: "64.7",
+ runs: [
+ { score: "70", sessionId: "ses-b1" },
+ { score: "59.4", sessionId: "ses-b2" },
+ ],
+ },
+ };
+
+ it("names both material paths and the latest evaluation's runs with their Sessions", () => {
+ const tail = askCaseTail(params);
+ expect(tail).toContain("`report-writing-v1`");
+ expect(tail).toContain("`CASE-002-citations`");
+ expect(tail).toContain("`benchmarks/report-writing-v1/CASE-002-citations/statement/README.md`");
+ expect(tail).toContain("`benchmarks/report-writing-v1/CASE-002-citations/rubric/README.md`");
+ expect(tail).toContain("2026-07-16 09:30");
+ expect(tail).toContain("64.7");
+ expect(tail).toContain("`ses-b1`");
+ expect(tail).toContain("`ses-b2`");
+ });
+
+ it("keeps the paths and carries no run results when the Benchmark has no evaluations", () => {
+ const tail = askCaseTail({ ...params, latest: null });
+ expect(tail).toContain("`benchmarks/report-writing-v1/CASE-002-citations/statement/README.md`");
+ expect(tail).toContain("`benchmarks/report-writing-v1/CASE-002-citations/rubric/README.md`");
+ expect(tail).not.toContain("ses-b1");
+ expect(tail).not.toContain("64.7");
+ });
+
+ it("offers examples with unique keys and non-empty prompts, the default question first", () => {
+ const examples = askCaseExamples();
+ expect(examples).toHaveLength(4);
+ expect(examples[0]?.prompt).toBe(S.benchmark.askCaseDefault);
+ expect(new Set(examples.map((e) => e.key)).size).toBe(examples.length);
+ for (const e of examples) {
+ expect(e.label).not.toBe("");
+ expect(e.prompt.trim()).not.toBe("");
+ }
+ });
+});
+
+describe("id helpers", () => {
+ it("slugFromTitle keeps ASCII words, folds separators, and yields nothing for a CJK title", () => {
+ expect(slugFromTitle("Report Writing (hard) v1")).toBe("report-writing-hard-v1");
+ expect(slugFromTitle(" 报告写作 ")).toBe("");
+ expect(slugFromTitle("--a__b--")).toBe("a-b");
+ });
+
+ it("caseId pads the position to three digits", () => {
+ expect(caseId(1, "contradictions")).toBe("CASE-001-contradictions");
+ expect(caseId(12, "x")).toBe("CASE-012-x");
+ });
+
+ it("benchmarkPath is the Project-level directory relative to the App Data Dir", () => {
+ expect(benchmarkPath("v1")).toBe("benchmarks/v1");
+ });
+
+ // The create route enforces the same bound, so a Benchmark can never be created with a runs
+ // count the Optimize dialog would then refuse.
+ it("isValidRuns accepts 1..MAX_RUNS and nothing else", () => {
+ expect(isValidRuns("1")).toBe(true);
+ expect(isValidRuns(String(MAX_RUNS))).toBe(true);
+ expect(isValidRuns(String(MAX_RUNS + 1))).toBe(false);
+ expect(isValidRuns("0")).toBe(false);
+ expect(isValidRuns("")).toBe(false);
+ expect(isValidRuns("1.5")).toBe(false);
+ });
+});
diff --git a/packages/web/test/group-order.test.ts b/packages/web/test/group-order.test.ts
index 22d41059..12e1c78e 100644
--- a/packages/web/test/group-order.test.ts
+++ b/packages/web/test/group-order.test.ts
@@ -8,6 +8,8 @@
* store because its buckets are a fixed chronological ladder, groups with no stored
* place surfacing at the TOP (including the merged temporary-workspace group, which is
* otherwise forced last), stale keys inert, and pruning gated on a complete live set.
+ * Beside the stored order stands the demotion of folder-only groups — applied last, inside
+ * the unpinned cluster only, over the two pure predicates session-grouping.ts exports for it.
*/
import { describe, expect, it } from "vitest";
import {
@@ -23,8 +25,10 @@ import type { GroupOrderStorage } from "../src/lib/group-order";
import { moveInSequence } from "../src/lib/session-order";
import {
TEMP_WORKSPACE_GROUP_KEY,
+ foldedShare,
groupSessionsByWorkspace,
groupSessionsByTime,
+ isFolderOnly,
timeGroupKey,
} from "../src/lib/session-grouping";
@@ -394,3 +398,55 @@ describe("group order and row order are independent axes", () => {
]);
});
});
+
+describe("folder-only groups sort last (demote)", () => {
+ /** Stands in for the sidebar's own predicate: these keys are the groups holding only folded rows. */
+ const isFolded = (key: string) => key.startsWith("f");
+
+ it("sends the demoted groups behind the rest, each block keeping its order", () => {
+ const out = orderGroups(["a", "f1", "b", "f2", "c"], id, {
+ ...noPins,
+ order: [],
+ demote: isFolded,
+ });
+ expect(out).toEqual(["a", "b", "c", "f1", "f2"]);
+ // Demoting nothing is the identity — what a Project with no evaluations still renders.
+ const plain = { ...noPins, order: [], demote: () => false };
+ expect(orderGroups(["a", "b", "c"], id, plain)).toEqual(["a", "b", "c"]);
+ });
+
+ it("never demotes a pinned group — a pin is how a folder-only group is kept up top", () => {
+ const out = orderGroups(["a", "f1", "pf", "b"], id, {
+ pinned: new Set(["pf"]),
+ order: [],
+ // "pf" is folder-only AND pinned: the pin wins, as it does over every other sort.
+ demote: isFolded,
+ });
+ expect(out).toEqual(["pf", "a", "b", "f1"]);
+ });
+
+ it("the manual order still applies inside each of the two blocks", () => {
+ // Stored: f2, b, f1, a. The demotion splits that sequence without reshuffling either
+ // half, so a drag survives a group becoming — or ceasing to be — folder-only.
+ const out = orderGroups(["a", "f1", "b", "f2"], id, {
+ ...noPins,
+ order: ["f2", "b", "f1", "a"],
+ demote: isFolded,
+ });
+ expect(out).toEqual(["b", "a", "f2", "f1"]);
+ });
+
+ it("is folder-only when the active share is zero and something is folded away", () => {
+ // One Workspace of an evaluation: a single Test Session, inside the Evaluations folder.
+ const evaluation = { active: 0, subagent: 0, schedule: 0, benchmark: 1, archived: 0 };
+ expect(foldedShare(evaluation)).toBe(1);
+ expect(isFolderOnly(0, foldedShare(evaluation))).toBe(true);
+ // Every folded category counts; the active one never does.
+ const mixed = { active: 7, subagent: 2, schedule: 1, benchmark: 3, archived: 4 };
+ expect(foldedShare(mixed)).toBe(10);
+ // A registered but still unused Workspace has nothing folded away to fold up …
+ expect(isFolderOnly(0, 0)).toBe(false);
+ // … and one active conversation makes a group an ordinary one again.
+ expect(isFolderOnly(1, 9)).toBe(false);
+ });
+});
diff --git a/packages/web/test/markdown-math.test.ts b/packages/web/test/markdown-math.test.ts
index 8af22725..04962078 100644
--- a/packages/web/test/markdown-math.test.ts
+++ b/packages/web/test/markdown-math.test.ts
@@ -330,7 +330,7 @@ describe("the pipeline every renderer shares", () => {
const RENDERERS = [
"../src/features/chat/md.tsx",
"../src/features/chat/workspace-browser.tsx",
- "../src/features/benchmark/benchmark-case-browser.tsx",
+ "../src/components/ui/file-browser.tsx",
"../src/features/traces/trace-event-row.tsx",
];
@@ -355,7 +355,7 @@ describe("the pipeline every renderer shares", () => {
}
expect(source, relative).toContain('from "../../lib/markdown-plugins"');
}
- expect(total).toBe(5); // md.tsx, workspace, benchmark, and two in trace-event-row
+ expect(total).toBe(5); // md.tsx, workspace, the shared file browser, and two in trace-event-row
});
it("no renderer assembles its own pipeline out of the underlying plugins", () => {
diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.ts
index 89e068f1..098e2bc7 100644
--- a/packages/web/test/session-grouping.test.ts
+++ b/packages/web/test/session-grouping.test.ts
@@ -13,6 +13,7 @@
import { describe, expect, it } from "vitest";
import type { SessionCategoryCounts, SessionInfo } from "@prismshadow/penguin-server/api";
import {
+ FOLDER_CATEGORIES,
SIDEBAR_PAGE_SIZE,
TEMP_WORKSPACE_GROUP_KEY,
TIME_BUCKETS,
@@ -44,7 +45,7 @@ function session(
sessionId?: string;
agentId?: string;
archived?: boolean;
- source?: "schedule" | "subagent";
+ source?: "schedule" | "subagent" | "benchmark";
lastActiveAt?: string;
} = {},
): SessionInfo {
@@ -177,7 +178,7 @@ describe("sessionCategory (the bucket a Session renders under = the server's lis
});
});
-describe("partitionSessions (per-group user / subagent / scheduled / archived split)", () => {
+describe("partitionSessions (per-group user / subagent / scheduled / evaluations / archived split)", () => {
it("splits user rows and one bucket per origin, preserving order within each part", () => {
const user1 = session("/srv/alpha", "2026-07-06T10:00:00.000Z");
const sched1 = session("/srv/alpha", "2026-07-05T10:00:00.000Z", { source: "schedule" });
@@ -208,11 +209,12 @@ describe("partitionSessions (per-group user / subagent / scheduled / archived sp
expect(parts.active).toEqual([]);
});
- it("empty input yields four empty parts", () => {
+ it("empty input yields five empty parts", () => {
expect(partitionSessions([])).toEqual({
active: [],
subagent: [],
schedule: [],
+ benchmark: [],
archived: [],
});
});
@@ -250,6 +252,22 @@ describe("latestConversation (the auto-opened 'last conversation')", () => {
});
});
+describe("benchmark Sessions (the Evaluation Center's runs)", () => {
+ it("files a benchmark Session into its own folder and never auto-opens it", () => {
+ // The Test Session an evaluation launches for a Case × Run, active more recently than
+ // anything the user opened themselves.
+ const run = session("/srv/a", "2026-07-08T10:00:00.000Z", { source: "benchmark" });
+ const user = session("/srv/a", "2026-07-02T10:00:00.000Z");
+ const parts = partitionSessions([run, user]);
+ expect(parts.benchmark.map((s) => s.sessionId)).toEqual([run.sessionId]);
+ expect(parts.active.map((s) => s.sessionId)).toEqual([user.sessionId]);
+ // Its own collapsed folder, rendered between Scheduled and Archived.
+ expect(FOLDER_CATEGORIES).toEqual(["subagent", "schedule", "benchmark", "archived"]);
+ // The evaluator's run is not the conversation the user was last in.
+ expect(latestConversation([run, user])).toBe(user);
+ });
+});
+
describe("splitPage (limit+1 fetch trick)", () => {
it("an overflow row proves the server has more and is never shown", () => {
const fetched = [1, 2, 3, 4];
@@ -264,7 +282,7 @@ describe("splitPage (limit+1 fetch trick)", () => {
});
describe("aggregateWorkspaceCounts (per-group exact server share)", () => {
- const zero = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const zero = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
it("sums each Workspace path across Agents and records which Agents hold each category", () => {
const byAgent = new Map<string, Record<string, SessionCategoryCounts>>([
@@ -279,17 +297,24 @@ describe("aggregateWorkspaceCounts (per-group exact server share)", () => {
]);
const groups = aggregateWorkspaceCounts(byAgent);
expect(groups.get("/srv/alpha")).toEqual({
- totals: { active: 3, subagent: 1, schedule: 2, archived: 0 },
+ totals: { active: 3, subagent: 1, schedule: 2, benchmark: 0, archived: 0 },
agents: {
active: ["agent_a", "agent_b"],
subagent: ["agent_a"],
schedule: ["agent_b"],
+ benchmark: [],
archived: [],
},
});
expect(groups.get("/srv/beta")).toEqual({
totals: { ...zero, archived: 3 },
- agents: { active: [], subagent: [], schedule: [], archived: ["agent_a"] },
+ agents: {
+ active: [],
+ subagent: [],
+ schedule: [],
+ benchmark: [],
+ archived: ["agent_a"],
+ },
});
// A group only in another Workspace never appears — its content can't surface elsewhere.
expect(groups.has("/srv/gamma")).toBe(false);
@@ -310,7 +335,13 @@ describe("aggregateWorkspaceCounts (per-group exact server share)", () => {
expect(groups.size).toBe(1);
expect(groups.get(TEMP_WORKSPACE_GROUP_KEY)).toEqual({
totals: { ...zero, active: 3, archived: 1 },
- agents: { active: ["agent_a"], subagent: [], schedule: [], archived: ["agent_a"] },
+ agents: {
+ active: ["agent_a"],
+ subagent: [],
+ schedule: [],
+ benchmark: [],
+ archived: ["agent_a"],
+ },
});
});
});
@@ -468,6 +499,7 @@ describe("totalCategoryCounts", () => {
active: 0,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
...over,
});
@@ -480,7 +512,7 @@ describe("totalCategoryCounts", () => {
["b", counts({ active: 4, subagent: 1 })],
]),
),
- ).toEqual({ active: 7, subagent: 1, schedule: 0, archived: 2 });
+ ).toEqual({ active: 7, subagent: 1, schedule: 0, benchmark: 0, archived: 2 });
});
it("reports zeros for an empty map rather than leaving fields undefined", () => {
@@ -488,6 +520,7 @@ describe("totalCategoryCounts", () => {
active: 0,
subagent: 0,
schedule: 0,
+ benchmark: 0,
archived: 0,
});
});
@@ -522,10 +555,10 @@ describe("aggregateWorkspaceLatest (per-group newest-Session stamp)", () => {
});
describe("completeWorkspaceGroups (every counted Workspace is a group, placed by recency)", () => {
- const zero = { active: 0, subagent: 0, schedule: 0, archived: 0 };
+ const zero = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
const counted = (totals: Partial<SessionCategoryCounts>) => ({
totals: { ...zero, ...totals },
- agents: { active: [], subagent: [], schedule: [], archived: [] },
+ agents: { active: [], subagent: [], schedule: [], benchmark: [], archived: [] },
});
it("adds an empty group for a counted Workspace the loaded rows never touched, and orders every group by its newest stamp", () => {
diff --git a/plugins/agent-tuning/plugin.json b/plugins/agent-tuning/plugin.json
index dbc329b7..5aea0219 100644
--- a/plugins/agent-tuning/plugin.json
+++ b/plugins/agent-tuning/plugin.json
@@ -3,6 +3,6 @@
"description_zh": "闭环的 Agent 调优:依据需求初始化 Agent、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。",
"short_description": "Initialize, benchmark, evaluate and improve agents.",
"short_description_zh": "初始化、评测、评分与改进 Agent。",
- "version": "2026.09.02.1",
+ "version": "2026.09.14.3",
"category": "ai-app-development"
}
diff --git a/plugins/agent-tuning/skills/agent-evaluation/SKILL.md b/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
index b2356a30..fb7625e3 100644
--- a/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
+++ b/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
@@ -34,7 +34,7 @@ One request represents one Test Agent execution. The `run` value identifies that
Return a **scored result** when the Test Agent ran and the Rubric could be applied. Wrong, malformed, or missing Test Agent output is still a scored result. Return an **evaluation failure** when the request, Benchmark, launch, version check, Trace binding, or scoring process prevents a valid score.
-Resolve the Project, Test Agent, Benchmark, and Case only from the explicit request and Environment App Data Dir. Reject traversal, symlink escape, or any path outside the requested Test Agent. Never read a Project configuration file, credential, or vault.
+Resolve the Project, Test Agent, Benchmark, and Case only from the explicit request and Environment App Data Dir. Reject traversal, symlink escape, or any path outside the requested Test Agent and Benchmark. Never read a Project configuration file, credential, or vault.
## Prepare
@@ -42,12 +42,14 @@ Use the `App Data Dir` from the Environment:
```text
TEST_AGENT_DIR = <app_data_dir>/agents/<test_agent_id>
-BENCHMARK_DIR = <test_agent_dir>/benchmarks/<benchmark_id>
+BENCHMARK_DIR = <app_data_dir>/benchmarks/<benchmark_id>
```
-Reject path traversal, symlink escape, or any resolved path outside the requested Test Agent. Inspect only the requested Agent State, Benchmark config and Case, isolated Test Workspace, and Traces needed to verify this execution. Do not inspect another Agent, Project secrets, hidden configuration, or unrelated Workspaces or Traces.
+The Benchmark is Project-level and is not owned by the Test Agent: it sits beside `agents/` and may evaluate several Agents. `test_agent_id` names the Agent this request evaluates; return it as `agent_id`.
-Require `agent_state/system_config.yaml`, `benchmark_config.toml`, `<case_id>/statement/README.md`, and `<case_id>/rubric/README.md`. Treat `run` only as the caller-owned label for this evaluation and return it unchanged; do not read or validate the total Run count. The top-level Agent State `version`, defaulting to 1, must equal `expected_version`; otherwise return `version_changed`. Read and snapshot `model.thinking_level` from this Target Agent config, using the normal Agent-config default `medium` only when the field is absent. This configured value is the evaluation `thinking_level`; do not require or read thinking metadata from a Trace.
+Reject path traversal, symlink escape, or any resolved path outside the requested Test Agent and Benchmark. Inspect only the requested Agent State, Benchmark config and Case, isolated Test Workspace, and Traces needed to verify this execution. Do not inspect another Agent, Project secrets, hidden configuration, or unrelated Workspaces or Traces.
+
+Require `agent_state/system_config.yaml`, `benchmark_config.toml`, `<case_id>/statement/README.md`, and `<case_id>/rubric/README.md`. Return `benchmark_invalid` when `benchmark_config.toml` says `status = "failed"`: a Benchmark whose calibration failed is not evaluated. Treat `run` only as the caller-owned label for this evaluation and return it unchanged; do not read or validate the total Run count. The top-level Agent State `version`, defaulting to 1, must equal `expected_version`; otherwise return `version_changed`. Read and snapshot `model.thinking_level` from this Target Agent config, using the normal Agent-config default `medium` only when the field is absent. This configured value is the evaluation `thinking_level`; do not require or read thinking metadata from a Trace.
Before launch, snapshot every file under the Case's `statement/` and `rubric/` directories. Require a usable Rubric whose scoring items total exactly 100 points. Create a unique Workspace under `<test_agent_dir>/workspaces/`, resolve it to an absolute canonical path, and verify that the resolved path remains under that directory. Copy only `statement/` into it. The Test Agent may see the Statement and its own State, but never the Rubric, Gold answers, scoring rules, or Evaluator reasoning.
@@ -67,9 +69,12 @@ export PENGUIN_HOME
penguin run \
--message "Read README.md in the current Workspace and complete the task exactly as specified there." \
--provider "<provider>" --model-id "<model_id>" --project-id "$PROJECT_ID" \
- --agent-id "<test_agent_id>" --workspace "<absolute_unique_workspace_path>" --approve allow-all
+ --agent-id "<test_agent_id>" --workspace "<absolute_unique_workspace_path>" \
+ --approve allow-all --source benchmark
```
+`--source benchmark` files the Test Session under the Evaluations folder of the Web App's session list rather than the Test Agent's active conversations; never omit it.
+
Use the exact requested Agent, Project, absolute Workspace path, and model pair. Never omit either model flag and never fall back to a Project default. If a launch fails, retry only when unchanged Workspace and Trace evidence proves that the Test Agent did not start. Every retry must follow a new diagnosis and apply a specific correction; never repeat an unchanged launch. Do not impose a numeric retry limit while distinct safe repairs remain. Return `evaluation_failed` when no new repair remains, external configuration is required, or it is unclear whether the Test Agent started.
Verify after the run that the State version, configured `model.thinking_level`, and both directory snapshots are unchanged. Return `version_changed` when the State version or configured thinking level differs and `benchmark_invalid` when the Statement or Rubric differs.
@@ -99,6 +104,7 @@ protocol_version: 1
status: ok
case_id: <case_id>
run: <run>
+agent_id: <test_agent_id>
expected_version: <version>
provider: <actual_provider>
model_id: <actual_model_id>
@@ -116,6 +122,7 @@ protocol_version: 1
status: failed
case_id: <case_id_or_null>
run: <run_or_null>
+agent_id: <test_agent_id_or_null>
expected_version: <version_or_null>
provider: <provider_or_null>
model_id: <model_id_or_null>
diff --git a/plugins/agent-tuning/skills/agent-optimization/SKILL.md b/plugins/agent-tuning/skills/agent-optimization/SKILL.md
index 70214c48..e428f1ad 100644
--- a/plugins/agent-tuning/skills/agent-optimization/SKILL.md
+++ b/plugins/agent-tuning/skills/agent-optimization/SKILL.md
@@ -13,7 +13,7 @@ If the request does not identify the Test Agent, frozen Benchmark, desired targe
## Goal and contract
-Require an explicit Test Agent, a frozen Benchmark with a complete valid Formal Baseline, a desired target score, a positive `runs` value, and a positive round limit. `runs` is the number of Runs per Case for every Candidate in this optimization Session. Freeze it for the Session; do not infer it from `benchmark_config.toml` or the Formal Baseline. Read the evaluation `(provider, model_id, thinking_level)` from the complete Evaluation that matches the current Agent State; do not require the user to repeat it. An Evaluation without any part of this runtime is incomplete and cannot be used as a Reference. The top-level Session must provide `run_subagent`, and the current Agent must have the `agent-evaluation` Skill. If a prerequisite is missing, stop and explain what is needed. Do not create the missing Agent, Benchmark, or Baseline, and do not evaluate the Test Agent directly.
+Require an explicit Test Agent, a frozen Benchmark with a complete valid Formal Baseline, a desired target score, a positive `runs` value, and a positive round limit. The Benchmark's `benchmark_config.toml` must say `status = "published"`; a `draft` Benchmark is still being built and is not frozen, and a `failed` one never finished calibrating, so stop and explain in either case. `runs` is the number of Runs per Case for every Candidate in this optimization Session. Freeze it for the Session; do not infer it from `benchmark_config.toml` or the Formal Baseline. Read the evaluation `(provider, model_id, thinking_level)` from the complete Evaluation that matches the current Agent State; do not require the user to repeat it. An Evaluation without any part of this runtime is incomplete and cannot be used as a Reference. The top-level Session must provide `run_subagent`, and the current Agent must have the `agent-evaluation` Skill. If a prerequisite is missing, stop and explain what is needed. Do not create the missing Agent, Benchmark, or Baseline, and do not evaluate the Test Agent directly.
A **Reference** is the Agent State currently kept as best, together with its complete Evaluation on the frozen Benchmark.
@@ -30,11 +30,13 @@ PENGUIN_HOME = <parent_of_project_dir>
TARGET = <app_data_dir>/agents/<test_agent_id>
STATE = <target>/agent_state
TRACES = <target>/traces
-BENCHMARK = <target>/benchmarks/<benchmark_id>
+BENCHMARK = <app_data_dir>/benchmarks/<benchmark_id>
SCOREBOARD = <benchmark>/scoreboard.yaml
SNAPSHOTS = <target>/snapshots
```
+The Benchmark is Project-level rather than owned by the Test Agent: it sits beside `agents/` and may evaluate several Agents. `test_agent_id` names the one this Session optimizes, and every Evaluation records it. Use only the Evaluations whose `agent_id` is that Agent as a Reference or for diagnosis.
+
Inspect only the requested Test Agent and Benchmark: the Agent State, public Statements, Scoreboard, and score-linked Test Traces or artifacts from the Baseline and this optimization, including rejected Candidates.
Do not inspect Rubrics, Gold answers, private scoring conditions, Evaluator State, Workspace, or Trace, other Agents, or Project secrets. If private evaluation information enters the Optimizer context, restore the active Candidate and stop as contaminated.
@@ -86,7 +88,7 @@ model_id: <model_id>
Inspect the complete streamed and final worker response. Before reading `status`, `score`, or any other protocol field, verify that the worker-authored text is exactly one plain protocol YAML document. Narration, headings, code fences, summaries, or scoring details are not valid protocol. Ask the same Evaluator to resend only the clean YAML from its existing result; do not rerun the Test Agent for a formatting repair and do not extract YAML from the invalid response yourself. Transport metadata added by `run_subagent` is not worker-authored text. If private evaluation information appears, follow the contamination rule above.
-For every scored result, require its actual `provider`, `model_id`, and `thinking_level` to equal the Reference runtime. A mismatch invalidates the Candidate matrix and stops optimization; never compare or record scores produced under a different runtime.
+For every scored result, require its `agent_id` to equal the requested Test Agent and its actual `provider`, `model_id`, and `thinking_level` to equal the Reference runtime. A mismatch invalidates the Candidate matrix and stops optimization; never compare or record scores produced under a different runtime.
Correct and resend an `invalid_request`. Stop on `version_changed` or `benchmark_invalid`.
@@ -94,10 +96,11 @@ For `evaluation_failed`, keep the same Candidate and incomplete matrix. Ask the
## Record and report
-Append each complete accepted Candidate Evaluation to `scoreboard.yaml` immediately after acceptance and verify the stored version, score, matrix, and Session ids before continuing. Obtain the current UTC timestamp from the environment, for example with `date -u +"%Y-%m-%dT%H:%M:%SZ"`, rather than inferring UTC from a displayed local time. Use the same field names as the Baseline:
+Append each complete accepted Candidate Evaluation to `scoreboard.yaml` immediately after acceptance and verify the stored Agent id, version, score, matrix, and Session ids before continuing. Obtain the current UTC timestamp from the environment, for example with `date -u +"%Y-%m-%dT%H:%M:%SZ"`, rather than inferring UTC from a displayed local time. Use the same field names as the Baseline:
```yaml
- time: <ISO-8601 timestamp>
+ agent_id: <test_agent_id>
version: <Candidate version>
provider: <provider>
model_id: <model_id>
@@ -121,7 +124,7 @@ Append each complete accepted Candidate Evaluation to `scoreboard.yaml` immediat
session_id: <Test Session id>
```
-After writing, parse the complete `scoreboard.yaml` and verify the appended Evaluation before reporting success or continuing.
+After writing, parse the complete `scoreboard.yaml` and verify the appended Evaluation, including its `agent_id`, before reporting success or continuing.
Every Run and Case score is on the fixed `0..100` scale. Do not write `max_score`. Calculate and write every Case and Evaluation average directly in the Scoreboard: ignore `null` values when averaging cost and write `null` only when all contributing costs are unknown; round `score` averages to two decimal places, `cost` averages to six decimal places, and `duration_ms` averages to the nearest integer. These stored values are authoritative—do not add a server, frontend, script, or consistency check that recomputes or validates them. Do not add an `aggregate` object or use `case_id`, `mean_score`, `mean_cost`, or `mean_duration_ms`. Do not record rejected Candidates in the Scoreboard.
diff --git a/plugins/agent-tuning/skills/benchmark-design/SKILL.md b/plugins/agent-tuning/skills/benchmark-design/SKILL.md
index f73e78a6..fd0bed5b 100644
--- a/plugins/agent-tuning/skills/benchmark-design/SKILL.md
+++ b/plugins/agent-tuning/skills/benchmark-design/SKILL.md
@@ -39,10 +39,12 @@ Use the Environment's `App Data Dir` and the explicit Test Agent id:
```text
TEST_AGENT_DIR = <app_data_dir>/agents/<test_agent_id>
-BENCHMARK_DIR = <app_data_dir>/agents/<test_agent_id>/benchmarks/<benchmark_id>
+BENCHMARK_DIR = <app_data_dir>/benchmarks/<benchmark_id>
SCOREBOARD = <benchmark_dir>/scoreboard.yaml
```
+A Benchmark lives beside `agents/`, not inside one: it belongs to the Project and may evaluate several Agents. `test_agent_id` names the one this request evaluates, and every Evaluation records it.
+
Access only the specified Test Agent and Benchmark: the Agent State, complete Benchmark, and Test Traces or artifacts from valid evaluations. Do not access other Agents, Project secrets, or Evaluator State, Workspace, or Trace.
Read the Agent State version from the top-level `version` in `agent_state/system_config.yaml`; use 1 only when it is absent.
@@ -68,7 +70,7 @@ Each Case contains:
Both directories require a `README.md` and may contain supporting files. Do not put Gold answers for evaluated instances, hidden mappings, or private scoring conditions in `statement/`.
-Create `benchmark_config.toml` with `title`, `description`, and `runs = 1`. Benchmark design always uses one Run per Case; do not ask for or accept another Run count. Initialize `scoreboard.yaml` with `evaluations: []`.
+Create `benchmark_config.toml` with `title`, `description`, `runs = 1`, and `status = "draft"`. Benchmark design always uses one Run per Case; do not ask for or accept another Run count. `status = "draft"` tells the Web App that the Benchmark is still being built — it shows the Benchmark masked, and nobody can use or open it until the status is `published`. A draft ends in one of two states: `published` once the Formal Baseline is recorded, or `failed` when calibration produces no valid Pilot result to freeze. Initialize `scoreboard.yaml` with `evaluations: []`.
Pass the resolved `(provider, model_id)` explicitly in every Pilot Evaluator request, starting with the first cell. Freeze that pair and the Test Agent's configured `thinking_level` for the complete Benchmark workflow. Every scored Evaluator result must report the requested pair and the same configured thinking level. A mismatch invalidates the matrix.
@@ -117,7 +119,7 @@ model_id: <model_id>
Inspect the complete streamed and final worker response. Before reading `status`, `score`, or any other protocol field, verify that the worker-authored text is exactly one plain protocol YAML document. Narration, headings, code fences, summaries, or scoring details are not valid protocol. Ask the same Evaluator to resend only the clean YAML from its existing result; do not rerun the Test Agent for a formatting repair and do not extract YAML from the invalid response yourself. Transport metadata added by `run_subagent` is not worker-authored text. A wrong or missing Test Agent artifact is a valid scored result and must not be retried.
-For every scored result, require non-empty `provider`, `model_id`, and `thinking_level`. Require the model pair to equal the explicitly resolved pair and the thinking level to equal the Test Agent configuration read before dispatch. Reject a Pilot result whose cells report mixed or mismatched runtimes. The Evaluator verifies provider/model from the root Trace and reports thinking from the unchanged Target Agent configuration; it does not require Trace metadata for thinking.
+For every scored result, require non-empty `agent_id`, `provider`, `model_id`, and `thinking_level`. Require `agent_id` to equal the requested Test Agent. Require the model pair to equal the explicitly resolved pair and the thinking level to equal the Test Agent configuration read before dispatch. Reject a Pilot result whose cells report mixed or mismatched runtimes. The Evaluator verifies provider/model from the root Trace and reports thinking from the unchanged Target Agent configuration; it does not require Trace metadata for thinking.
Correct and resend an `invalid_request`. For `benchmark_invalid`, repair and rerun the affected Case during Pilot. For `version_changed`, discard the current Pilot result and restart after the Agent version is stable.
@@ -127,7 +129,7 @@ For `evaluation_failed`, keep the same Benchmark revision and cell. Diagnose the
Treat the first draft as a hypothesis. The first valid result from every planned Case together forms Pilot iteration 1. A later iteration starts after a difficulty refinement and completes when every affected Case has a valid new result. Request corrections, validity repairs, and evaluation reruns stay in the current iteration and do not consume the requested iteration budget. Use the recorded Agent State version and fixed evaluation runtime.
-Keep unselected Pilot results out of the Scoreboard. During calibration, retain only one temporary restorable copy: the lowest-scoring complete valid revision seen so far, including its one-Run-per-Case result. Store it outside `benchmarks/`, replace it only when a lower valid revision completes, and never retain invalid revisions.
+Keep unselected Pilot results out of the Scoreboard. During calibration, retain only one temporary restorable copy: the lowest-scoring complete valid revision seen so far, including its one-Run-per-Case result. Store it outside the Project's `benchmarks/`, replace it only when a lower valid revision completes, and never retain invalid revisions.
Use the Pilot to find the current Test Agent's capability boundary.
@@ -167,6 +169,7 @@ After validation, obtain the current UTC timestamp from the environment, for exa
```yaml
evaluations:
- time: <ISO-8601 timestamp>
+ agent_id: <test_agent_id>
version: <Agent State version>
provider: <provider>
model_id: <model_id>
@@ -190,7 +193,9 @@ evaluations:
session_id: <Test Session id>
```
-After writing, parse the complete `scoreboard.yaml` and verify the appended Evaluation before reporting success or continuing.
+After writing, parse the complete `scoreboard.yaml` and verify the appended Evaluation, including its `agent_id`, before reporting success or continuing.
+
+Once the Formal Baseline is verified, set `status = "published"` in `benchmark_config.toml`. Change only that line, keep `title`, `description` and `runs` as they are, and parse the file again to confirm it is valid TOML. When the run ends in `calibration_failed`, set `status = "failed"` the same way — change only that line, keep the other fields, and parse the file again — so the Web App tells the user that this Benchmark failed to calibrate and has to be deleted and created again. Never leave a failed Benchmark on `draft`.
Every Run and Case score is on the fixed `0..100` scale. Do not write `max_score`. Calculate and write every Case and Evaluation average directly in the Scoreboard: ignore `null` values when averaging cost and write `null` only when all contributing costs are unknown; round `score` averages to two decimal places, `cost` averages to six decimal places, and `duration_ms` averages to the nearest integer. These stored values are authoritative—do not add a server, frontend, script, or consistency check that recomputes or validates them. Do not add an `aggregate` object or use `case_id`, `mean_score`, `mean_cost`, or `mean_duration_ms`.