Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(lobe-bench): add Lobe Bench workspace pages for benchmarks, datasets and experiments (#22483)

Robin Zhangc6af50c08d78
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.md
index 31988a0be44..666a334d559 100644
--- a/.agents/ux/lobe-design-rules.md
+++ b/.agents/ux/lobe-design-rules.md
@@ -138,6 +138,8 @@ Reply is the primary Channel message action. Replying to a person only posts a q
Source: user correction of the proposed in-channel reply semantics (2026-10-31).
+- Long-running experiment startup belongs to the experiment page. Do not trap users in a blocking modal; route navigation must not own or cancel launch orchestration. A short pre-launch cost confirmation may remain.
+
## LOBE-UX-020 — Conversation day dividers follow WeChat, time included
A Channel day divider stamps the first message of the day the way WeChat does: today is the time alone ("10:17"), not "今天"; earlier days are the day followed by the time ("昨天 01:36", "星期五 10:15", "11 月 7 日 10:15", "2025 年 11 月 7 日 10:15"). Days are calendar days in local time, not 24-hour spans. The full date stays in the hover title and the separator's accessible label.
diff --git a/locales/en-US/eval.json b/locales/en-US/eval.json
index 545e8a40440..0788a9cc401 100644
--- a/locales/en-US/eval.json
+++ b/locales/en-US/eval.json
@@ -1,5 +1,6 @@
{
"benchmark.actions.delete": "Delete Benchmark",
+ "benchmark.actions.delete.builtIn": "Built-in benchmark · cannot be deleted",
"benchmark.actions.delete.confirm": "Are you sure you want to delete this benchmark? Related datasets and evaluation records will also be deleted.",
"benchmark.actions.edit": "Edit Benchmark",
"benchmark.actions.export": "Export",
@@ -35,6 +36,7 @@
"benchmark.create.tags.label": "Tags",
"benchmark.create.tags.placeholder": "Add tags, separate with comma or space",
"benchmark.create.title": "Create Benchmark",
+ "benchmark.delete.error": "Failed to delete benchmark",
"benchmark.detail.backToOverview": "Back to Overview",
"benchmark.detail.datasetCount": "{{count}} dataset{{count, plural, one {} other {s}}} in this benchmark",
"benchmark.detail.runCount": "{{count}} evaluation run{{count, plural, one {} other {s}}} on this benchmark",
@@ -54,6 +56,7 @@
"benchmark.detail.stats.runs": "Runs",
"benchmark.detail.stats.tags": "Tags",
"benchmark.detail.stats.topAgents": "Top Agents",
+ "benchmark.detail.stats.topModels": "Top Models",
"benchmark.detail.stats.totalCases": "Total Cases",
"benchmark.detail.stats.waiting": "Waiting...",
"benchmark.detail.tabs.data": "Data",
@@ -99,9 +102,16 @@
"caseDetail.failureReason": "Failure Reason",
"caseDetail.input": "Input",
"caseDetail.judgeComment": "Judge Comment",
+ "caseDetail.judgeError.regradeHint": "The original answer is kept. On the experiment page, Rerun runs this case again and grades the new attempts.",
+ "caseDetail.memory.agent": "written during the attempt",
+ "caseDetail.memory.empty": "No memory entries.",
+ "caseDetail.memory.removed": "removed",
+ "caseDetail.memory.seed": "seed",
"caseDetail.resources": "Resources",
"caseDetail.score": "Score",
"caseDetail.section.externalResult": "External Result",
+ "caseDetail.section.memory": "Memory at the end",
+ "caseDetail.section.rules": "Rules",
"caseDetail.section.runtime": "Runtime",
"caseDetail.section.scoring": "Scoring Details",
"caseDetail.section.testCase": "Test Case",
@@ -117,6 +127,59 @@
"common.save": "Save",
"common.unknown": "Unknown",
"common.update": "Update",
+ "connections.adapter": "LobeBench mock adapter",
+ "connections.authIncluded": "Access credentials included",
+ "connections.authNone": "No authentication",
+ "connections.authSaved": "Authentication saved",
+ "connections.authentication": "Authentication",
+ "connections.autoImport": "These connections will be created and bound automatically when you import. You do not need to enter an address or token.",
+ "connections.bearerAuth": "Bearer token",
+ "connections.cancel": "Cancel",
+ "connections.case": "Case override",
+ "connections.checking": "Checking connection availability…",
+ "connections.clearAuth": "No authentication (clear saved credentials)",
+ "connections.completeScope": "Choose every service in an edited environment or case, or clear your changes to configure it later.",
+ "connections.configureLater": "Configure later",
+ "connections.configured": "All required services have a connection.",
+ "connections.create": "Create connection",
+ "connections.datasetHint": "Connections are shared by cases using the same environment. Availability here confirms the saved binding; the service is checked when a run starts.",
+ "connections.datasetOnly": "Manage connections in the Dataset that uses this environment. Import a new Dataset before configuring its connections.",
+ "connections.disabled": "Disabled",
+ "connections.edit": "Edit connection",
+ "connections.editHint": "Changes affect every environment using this connection. Saved credentials are kept private; enter new credentials to replace them.",
+ "connections.empty": "No available HTTP connections yet. Create one here, then choose it above.",
+ "connections.enabled": "Enable connection",
+ "connections.environment": "Environment",
+ "connections.fromPackage": "Use the connection included in the ZIP",
+ "connections.headerAuth": "Custom headers",
+ "connections.hideDetails": "Hide connections",
+ "connections.hint": "Choose a connection for each service. Each connection manages its own address and authentication. The same connection can serve several services.",
+ "connections.importLater": "Some services have no connection included. You can import now and configure them in the dataset before running.",
+ "connections.included": "Connections included in this ZIP",
+ "connections.keepAuth": "Keep saved authentication",
+ "connections.manage": "Configure connections",
+ "connections.missing": "{{count}} service bindings need a connection before running.",
+ "connections.name": "Connection name",
+ "connections.noAuth": "No access credentials included",
+ "connections.openManager": "Manage Dataset connection addresses and authentication",
+ "connections.optional": "Choose existing connections (optional)",
+ "connections.refresh": "Refresh connections",
+ "connections.replaceAuth": "Replace or clear authentication when changing the server address.",
+ "connections.save": "Save connections",
+ "connections.saveAndTest": "Save and test",
+ "connections.saved": "Connections saved",
+ "connections.settingsHint": "Mock services use the connections bound to each dataset’s environments and cases. ZIP imports can configure them automatically. Open a dataset to change its bindings.",
+ "connections.showDetails": "Show connections",
+ "connections.standard": "Standard MCP",
+ "connections.statusConnected": "Last check succeeded",
+ "connections.statusDisconnected": "Not checked",
+ "connections.statusError": "Last check failed",
+ "connections.tested": "Connected · {{count}} tools available",
+ "connections.title": "Mock MCP connections",
+ "connections.transport": "Protocol for {{service}}",
+ "connections.unavailable": "Connection unavailable — choose another",
+ "connections.unbound": "Not bound to an environment or case",
+ "connections.url": "MCP server URL",
"dataset.actions.addDataset": "Add Dataset",
"dataset.actions.import": "Import Data",
"dataset.actions.importDataset": "Import Dataset",
@@ -190,6 +253,25 @@
"dataset.import.metadata": "Metadata",
"dataset.import.metadataDesc": "Extra info, stored as-is",
"dataset.import.next": "Next",
+ "dataset.import.package.asNew": "Import as new dataset",
+ "dataset.import.package.benchmark": "Benchmark",
+ "dataset.import.package.benchmarkName": "New benchmark name",
+ "dataset.import.package.cases": "{{count}} cases",
+ "dataset.import.package.environments": "{{count}} environments",
+ "dataset.import.package.hint": "Dataset ZIP package · up to 10 MiB",
+ "dataset.import.package.history": "The imported cases are fixed. Import updated packages as a new dataset to keep past results comparable.",
+ "dataset.import.package.instructions": "Upload your dataset ZIP. The ZIP must contain dataset.json at its root.",
+ "dataset.import.package.judge": "Judge model",
+ "dataset.import.package.judge.hint": "Every run on this benchmark is graded by this model, so its scores stay comparable. It cannot be changed later.",
+ "dataset.import.package.judge.placeholder": "Choose the judge model",
+ "dataset.import.package.mockServices": "Mock services used: {{services}}. Each service uses its bound connection.",
+ "dataset.import.package.name": "Dataset name",
+ "dataset.import.package.newBenchmark": "Create a new benchmark",
+ "dataset.import.package.preserved": "Case content, grading rules and environment settings are imported together. This creates a private dataset in your account.",
+ "dataset.import.package.preview": "Confirm dataset package",
+ "dataset.import.package.refreshError": "The dataset was imported, but the list could not refresh. Reload the page to see it; you do not need to import again.",
+ "dataset.import.package.tooLarge": "The ZIP is too large. Choose a package smaller than 10 MiB.",
+ "dataset.import.package.zipRequired": "Choose a dataset ZIP package.",
"dataset.import.parseError": "Failed to parse file",
"dataset.import.parsing": "Parsing file...",
"dataset.import.prev": "Previous",
@@ -203,7 +285,7 @@
"dataset.import.step.upload": "Upload File",
"dataset.import.success": "Successfully imported {{count}} test cases",
"dataset.import.title": "Import Dataset",
- "dataset.import.upload.hint": "Supports CSV, XLSX, JSON, JSONL",
+ "dataset.import.upload.hint": "Supports CSV, XLSX, JSON, JSONL and dataset ZIP packages (up to 10 MiB)",
"dataset.import.upload.text": "Click or drag file here to upload",
"dataset.import.uploading": "Uploading...",
"dataset.switchDataset": "Switch Dataset",
@@ -232,6 +314,8 @@
"evalMode.provider.placeholder": "LLM provider (e.g. openai, azure)",
"evalMode.rubric": "Rubric Scoring",
"evalMode.rubric.desc": "Score output using benchmark rubrics with weighted criteria",
+ "evalMode.rule-checklist": "Rule Checklist",
+ "evalMode.rule-checklist.desc": "The LLM judge decides each Must / Must not rule on its own; the case passes only when every rule is satisfied",
"evalMode.systemRole.label": "System Prompt",
"evalMode.systemRole.placeholder": "Optional system prompt for the LLM judge",
"experiment.actions.create": "Create Experiment",
@@ -277,6 +361,497 @@
"experiment.list.title": "Experiments",
"experiment.overview.emptyHint": "Run activity and scoped datasets will appear here.",
"experiment.run.parent": "Forked from {{name}}",
+ "lobeBench.attempt.backToExperiment": "Back to experiment",
+ "lobeBench.benchmark.best": "best {{value}} over {{count}} full runs",
+ "lobeBench.benchmark.cases": "{{count}} cases",
+ "lobeBench.benchmark.create.datasets": "Datasets",
+ "lobeBench.benchmark.create.datasets.empty": "No dataset to build it from yet. Import a dataset ZIP first; it stays on its own until a benchmark is made of it.",
+ "lobeBench.benchmark.create.datasets.hint": "A benchmark runs the datasets it is made of. Choose at least one.",
+ "lobeBench.benchmark.create.datasets.placeholder": "Choose datasets",
+ "lobeBench.benchmark.create.description": "Description",
+ "lobeBench.benchmark.create.description.placeholder": "Optional: what this benchmark measures",
+ "lobeBench.benchmark.create.failed": "Could not create the benchmark",
+ "lobeBench.benchmark.create.judge": "Judge model",
+ "lobeBench.benchmark.create.judge.hint": "Every run on this benchmark is graded by this model, so its scores stay comparable. It cannot be changed later.",
+ "lobeBench.benchmark.create.judge.placeholder": "Choose the judge model",
+ "lobeBench.benchmark.create.name": "Name",
+ "lobeBench.benchmark.create.name.placeholder": "e.g. Finance agents",
+ "lobeBench.benchmark.create.submit": "Create benchmark",
+ "lobeBench.benchmark.create.title": "New benchmark",
+ "lobeBench.benchmark.custom": "My cases",
+ "lobeBench.benchmark.datasets": "Datasets",
+ "lobeBench.benchmark.datasets.add": "Add dataset",
+ "lobeBench.benchmark.datasets.empty": "No datasets. A benchmark's datasets are chosen when it is created; to use others, create a new benchmark.",
+ "lobeBench.benchmark.datasets.hint": "The datasets this benchmark is made of. A run counts on the leaderboard when it ran all of a dataset's cases.",
+ "lobeBench.benchmark.datasets.noneLoose": "No dataset to add yet: make one in the Case library",
+ "lobeBench.benchmark.datasets.remove": "Remove from this benchmark",
+ "lobeBench.benchmark.delete.confirm": "Delete {{name}}? Its runs and results are deleted with it. Its datasets are kept, free to make another benchmark of.",
+ "lobeBench.benchmark.newExperiment": "New experiment",
+ "lobeBench.benchmark.noRuns": "No full run yet",
+ "lobeBench.benchmark.noRunsYet": "No run on this benchmark yet. Start an experiment to compare contenders on a case set.",
+ "lobeBench.benchmark.notFound": "Benchmark not found",
+ "lobeBench.benchmark.outdatedRun": "Earlier case version · not ranked",
+ "lobeBench.benchmark.rank.active_one": "{{count}} run in progress",
+ "lobeBench.benchmark.rank.active_other": "{{count}} runs in progress",
+ "lobeBench.benchmark.rank.anyRate": "any of {{k}}: {{value}}",
+ "lobeBench.benchmark.rank.broken_one": "{{count}} run has incomplete or errored attempts and is not ranked",
+ "lobeBench.benchmark.rank.broken_other": "{{count}} runs have incomplete or errored attempts and are not ranked",
+ "lobeBench.benchmark.rank.compare.all": "Compare: all models",
+ "lobeBench.benchmark.rank.compare.reset": "Show all models",
+ "lobeBench.benchmark.rank.compare.some_one": "Compare: {{count}} model",
+ "lobeBench.benchmark.rank.compare.some_other": "Compare: {{count}} models",
+ "lobeBench.benchmark.rank.cost": "${{cost}}/case",
+ "lobeBench.benchmark.rank.empty": "No completed run on all of {{set}} yet. Start an experiment on it and the models rank here.",
+ "lobeBench.benchmark.rank.estimated": "estimated from {{attempts}} attempts",
+ "lobeBench.benchmark.rank.fewAttempts_one": "{{count}} run has no comparable score for {{k}} attempts and is not ranked",
+ "lobeBench.benchmark.rank.fewAttempts_other": "{{count}} runs have no comparable score for {{k}} attempts and are not ranked",
+ "lobeBench.benchmark.rank.hint": "Each contender's best completed run on the whole set, ranked by cases that passed all {{k}} attempts. A run of more attempts per case is scored on {{k}} (estimated); one of fewer is not ranked.",
+ "lobeBench.benchmark.rank.legend.rate": "Passed all {{k}} attempts (ranked by this)",
+ "lobeBench.benchmark.rank.legend.reach": "Passed at least 1 of {{k}}",
+ "lobeBench.benchmark.rank.outdated_one": "{{count}} run on an earlier version of the cases is not ranked",
+ "lobeBench.benchmark.rank.outdated_other": "{{count}} runs on an earlier version of the cases are not ranked",
+ "lobeBench.benchmark.rank.setOption_one": "{{name}} · {{count}} contender",
+ "lobeBench.benchmark.rank.setOption_other": "{{name}} · {{count}} contenders",
+ "lobeBench.benchmark.rank.summary_one": "{{count}} contender · {{runs}} completed full runs",
+ "lobeBench.benchmark.rank.summary_other": "{{count}} contenders · {{runs}} completed full runs",
+ "lobeBench.benchmark.rank.title": "Leaderboard",
+ "lobeBench.benchmark.rank.unjudged_one": "{{count}} completed run awaiting judging",
+ "lobeBench.benchmark.rank.unjudged_other": "{{count}} completed runs awaiting judging",
+ "lobeBench.benchmark.runCases": "{{selected}} of {{total}} cases",
+ "lobeBench.benchmark.runCount_one": "{{count}} evaluation run on this benchmark",
+ "lobeBench.benchmark.runCount_other": "{{count}} evaluation runs on this benchmark",
+ "lobeBench.benchmark.runs": "Runs",
+ "lobeBench.benchmark.standard.hint": "Every run on this benchmark uses this judge model and these rules, so its scores stay comparable. They cannot be changed later or per experiment.",
+ "lobeBench.benchmark.standard.k": "Attempts per case",
+ "lobeBench.benchmark.standard.title": "Grading and run rules",
+ "lobeBench.builtIn": "Built-in",
+ "lobeBench.case.delete": "Delete",
+ "lobeBench.case.delete.confirm": "Delete this case? Past results keep their own copy of it.",
+ "lobeBench.case.difficulty.why": "Why this level: {{signals}}.",
+ "lobeBench.case.edit": "Edit",
+ "lobeBench.case.editor.category": "Category",
+ "lobeBench.case.editor.edit": "Edit case",
+ "lobeBench.case.editor.environment": "Environment",
+ "lobeBench.case.editor.environment.none": "None — this case carries its own setup",
+ "lobeBench.case.editor.environment.usedBy": "used by {{count}} cases",
+ "lobeBench.case.editor.input": "User request",
+ "lobeBench.case.editor.input.placeholder": "What the user asks the Agent to do.",
+ "lobeBench.case.editor.invalidDate": "The clock must be an ISO date, e.g. 2026-07-20 or 2026-07-20T09:00:00Z",
+ "lobeBench.case.editor.mock": "Mocked connectors (comma separated)",
+ "lobeBench.case.editor.new": "New case",
+ "lobeBench.case.editor.overrides": "This case only",
+ "lobeBench.case.editor.overrides.hint": "Laid over the shared environment; leave a field empty to inherit it.",
+ "lobeBench.case.editor.persona": "Persona (system role)",
+ "lobeBench.case.editor.plugins": "Tool allowlist (plugin identifiers, comma separated)",
+ "lobeBench.case.editor.rules": "Rules",
+ "lobeBench.case.editor.rules.hint": "One per line, starting with \"Must:\" or \"Must not:\". The judge checks each one and explains every miss.",
+ "lobeBench.case.editor.save": "Save",
+ "lobeBench.case.editor.saved": "Case saved",
+ "lobeBench.case.editor.sessionDate": "Clock (ISO date or instant)",
+ "lobeBench.case.editor.timezone": "Timezone",
+ "lobeBench.case.editor.title": "Title",
+ "lobeBench.case.editor.turns": "Earlier turns",
+ "lobeBench.case.editor.turns.add": "Add turn",
+ "lobeBench.case.editor.turns.hint": "Replayed before the request, so the Agent has the context the user had.",
+ "lobeBench.case.fromConversation": "From a conversation",
+ "lobeBench.case.fromConversation.drafting": "Drafting the case from the conversation…",
+ "lobeBench.case.fromConversation.empty": "No conversations found.",
+ "lobeBench.case.fromConversation.hint": "Pick one of your conversations: its last request becomes the case, the earlier turns its context, and the judge drafts the rules. Nothing is saved until you do.",
+ "lobeBench.case.fromConversation.rulesFailed": "The judge could not draft rules ({{error}}). Write them yourself, or pick a judge model in Settings.",
+ "lobeBench.case.fromConversation.search": "Search conversations, then press Enter",
+ "lobeBench.case.level.L1": "L1",
+ "lobeBench.case.level.L2": "L2",
+ "lobeBench.case.level.L3": "L3",
+ "lobeBench.case.level.L4": "L4",
+ "lobeBench.case.new": "New case",
+ "lobeBench.case.persona": "Persona for this case",
+ "lobeBench.case.prompt": "What the user asks",
+ "lobeBench.case.readOnly": "read-only",
+ "lobeBench.case.rules": "Grading rules",
+ "lobeBench.case.runsWith": "Runs with",
+ "lobeBench.case.runsWith.clock": "Clock",
+ "lobeBench.case.runsWith.clockPinned": "Every \"today\" the model sees is {{date}}",
+ "lobeBench.case.runsWith.clockWall": "Real time",
+ "lobeBench.case.runsWith.connectors": "Simulated connectors",
+ "lobeBench.case.runsWith.memory": "Memory",
+ "lobeBench.case.runsWith.memoryEmpty": "starts empty",
+ "lobeBench.case.runsWith.memoryMode": "Memory {{permission}} · effort {{effort}}",
+ "lobeBench.case.runsWith.memoryOff": "Memory off",
+ "lobeBench.case.runsWith.memoryRecords_one": "starts with {{count}} preset record",
+ "lobeBench.case.runsWith.memoryRecords_other": "starts with {{count}} preset records",
+ "lobeBench.case.runsWith.noConnectors": "No connectors",
+ "lobeBench.case.testRun": "Test run",
+ "lobeBench.case.testRun.go": "Run once",
+ "lobeBench.case.testRun.hint": "Runs this case once with one contender and opens the attempt. Model tokens are billed to your providers.",
+ "lobeBench.compare.attempt": "Attempt {{n}}",
+ "lobeBench.compare.error": "Error",
+ "lobeBench.compare.filter.judgeErrors": "Grading errors",
+ "lobeBench.compare.judgeError": "Grading error",
+ "lobeBench.compare.noReason": "No judge reason recorded.",
+ "lobeBench.compare.open": "Open conversation",
+ "lobeBench.compare.passes": "{{passed}}/{{total}} passed",
+ "lobeBench.compare.pending": "Not finished yet",
+ "lobeBench.compare.reason": "Judge reason",
+ "lobeBench.compare.timeCost": "Time · cost",
+ "lobeBench.compare.toolCalls": "Tool calls",
+ "lobeBench.contender.model": "Model",
+ "lobeBench.contender.model.placeholder": "Pick a model that supports tool calls",
+ "lobeBench.contender.modelDefault": "Model default",
+ "lobeBench.contender.modelSettings": "Model settings",
+ "lobeBench.contender.name": "Name",
+ "lobeBench.contender.name.placeholder": "Optional — model name plus settings if empty",
+ "lobeBench.contender.save": "Add to experiment",
+ "lobeBench.contender.save.list": "Save",
+ "lobeBench.contender.settings.default": "Default settings",
+ "lobeBench.contender.settings.reasoning": "reasoning",
+ "lobeBench.contender.settings.temperature": "temperature",
+ "lobeBench.contender.settings.topP": "top_p",
+ "lobeBench.contender.subtitle": "The same model list and settings as in chat. Add providers under Settings → AI providers.",
+ "lobeBench.contender.temperature": "Temperature",
+ "lobeBench.contender.title": "New contender",
+ "lobeBench.contender.topP": "Top P",
+ "lobeBench.contenders.builtIn": "Contenders you ran in past experiments. The built-in benchmark keeps no saved list; add one on the New experiment page.",
+ "lobeBench.contenders.col.best": "Best full run",
+ "lobeBench.contenders.col.experiments": "Experiments",
+ "lobeBench.contenders.col.model": "Model",
+ "lobeBench.contenders.col.name": "Contender",
+ "lobeBench.contenders.delete.confirm": "Remove this contender from the saved list? Past experiments keep their results.",
+ "lobeBench.contenders.edit": "Edit",
+ "lobeBench.contenders.empty": "No contenders yet. Start an experiment, or add one here.",
+ "lobeBench.contenders.new": "New contender",
+ "lobeBench.contenders.saved": "Contender saved",
+ "lobeBench.contenders.subtitle": "A contender is a model with the settings it runs with. Every contender that ran is kept here; add one ahead of time or tidy the list.",
+ "lobeBench.contenders.title": "Contenders",
+ "lobeBench.dashboard.abort": "Stop",
+ "lobeBench.dashboard.abort.confirm": "Stop the running contenders? Finished cases keep their results; the rest stay unfinished.",
+ "lobeBench.dashboard.action.failed": "Could not complete the action for {{models}}. Reload and inspect these runs.",
+ "lobeBench.dashboard.action.rerunFailed": "Could not start the rerun for {{models}}. Reload and inspect the runs.",
+ "lobeBench.dashboard.action.rerunSuccess": "{{models}}: {{count}} cases are running again.",
+ "lobeBench.dashboard.action.stillRunning": "{{models}} are still running. Wait for them to finish before trying again.",
+ "lobeBench.dashboard.action.stopSuccess": "Stopped {{models}}.",
+ "lobeBench.dashboard.awaitingExternal": "{{name}}: {{count}} attempts are waiting for external grading.",
+ "lobeBench.dashboard.byCategory": "By category",
+ "lobeBench.dashboard.byCategory.hint": "Colour is the pass rate. Click a cell to see only that category by case.",
+ "lobeBench.dashboard.byLevel": "By difficulty",
+ "lobeBench.dashboard.byLevel.hint": "Pass rate per difficulty level. Levels come from the case contract (calls in order, services spanned, failures injected, rules to satisfy), not from any model.",
+ "lobeBench.dashboard.caseProgress": "{{evaluated}}/{{total}} cases evaluated · {{errors}} with errors · {{pending}} awaiting completion",
+ "lobeBench.dashboard.caseUnavailable": "Result unavailable",
+ "lobeBench.dashboard.cases.count": "{{count}} cases · cells are passes out of {{k}}; click a row to compare",
+ "lobeBench.dashboard.cases.empty": "No cases under this filter.",
+ "lobeBench.dashboard.cases.unavailable": "No selected cases are available. Return to the case library to inspect this case set.",
+ "lobeBench.dashboard.col.anyK": "Any of {{k}}",
+ "lobeBench.dashboard.col.contender": "Contender",
+ "lobeBench.dashboard.col.cost": "Cost per case · time",
+ "lobeBench.dashboard.col.errors": "{{count}} errors",
+ "lobeBench.dashboard.col.passRate": "Pass rate",
+ "lobeBench.dashboard.col.passRateAllK": "Pass rate · all {{k}} attempts",
+ "lobeBench.dashboard.col.passed": "Passed",
+ "lobeBench.dashboard.col.passedAllK": "All {{k}} passed",
+ "lobeBench.dashboard.coverageGap": "{{name}}: {{available}} of {{expected}} case results are available; {{missing}} are missing. Saved summary scores are unchanged. Breakdowns and CSV include only available evidence.",
+ "lobeBench.dashboard.errors": "{{count}} cases have execution errors. Their results are incomplete; rerun these cases to finish the evaluation.",
+ "lobeBench.dashboard.export": "Export CSV",
+ "lobeBench.dashboard.filter.all": "All",
+ "lobeBench.dashboard.filter.allFail": "Everyone failed",
+ "lobeBench.dashboard.filter.category": "Category: {{category}}",
+ "lobeBench.dashboard.filter.clear": "Clear",
+ "lobeBench.dashboard.filter.diff": "Cases with disagreement",
+ "lobeBench.dashboard.filter.errors": "With errors",
+ "lobeBench.dashboard.filter.level": "Level: {{level}}",
+ "lobeBench.dashboard.gradingGap": "{{name}}: {{count}} attempts have unfinished grading. Saved summary scores are unchanged.",
+ "lobeBench.dashboard.insight.gap": "Gap to second",
+ "lobeBench.dashboard.insight.gapLine": "{{gap}} cases",
+ "lobeBench.dashboard.insight.leader": "Leader",
+ "lobeBench.dashboard.insight.leaderLine": "{{passed}}/{{total}} passed all {{k}} attempts · any of {{k}}: {{anyK}}",
+ "lobeBench.dashboard.insight.lowest": "Lowest pass rate",
+ "lobeBench.dashboard.insight.weakest": "Shared weak spot",
+ "lobeBench.dashboard.insight.weakestLine": "{{rate}} average pass rate",
+ "lobeBench.dashboard.judgeErrors": "{{name}}: {{count}} attempts got no verdict. Rerun runs those cases again.",
+ "lobeBench.dashboard.loadError": "Could not load experiment results",
+ "lobeBench.dashboard.loading": "Loading experiment results…",
+ "lobeBench.dashboard.missingCases": "{{count}} selected cases are no longer available in this case set. The breakdown and CSV include only available selected cases.",
+ "lobeBench.dashboard.missingRuns": "Some experiment runs are unavailable. Results cannot be compared until all contender runs are available.",
+ "lobeBench.dashboard.notFound": "This experiment does not exist or is not a Lobe Bench experiment.",
+ "lobeBench.dashboard.partialCounts": "Counts show confirmed passes so far. Final pass rates and ranking are available once every case is fully evaluated.",
+ "lobeBench.dashboard.progress": "{{done}}/{{total}} attempts done. Results below are partial and refresh automatically.",
+ "lobeBench.dashboard.ranking": "Contender ranking",
+ "lobeBench.dashboard.rerun": "Rerun",
+ "lobeBench.dashboard.rerun.confirm_one": "{{count}} case will run again (all of its attempts) with the same models and settings. This costs model calls.",
+ "lobeBench.dashboard.rerun.confirm_other": "{{count}} cases will run again (all of their attempts) with the same models and settings. This costs model calls.",
+ "lobeBench.dashboard.rerun.hint": "Runs again every case with an attempt that has no verdict (error, timeout, or ungraded), with the same models and settings. Cases with verdicts stay.",
+ "lobeBench.dashboard.rerun.none": "Every attempt has a verdict; nothing to rerun.",
+ "lobeBench.dashboard.setup.col.cases": "Cases",
+ "lobeBench.dashboard.setup.col.cost": "Cost",
+ "lobeBench.dashboard.setup.col.k": "Per case",
+ "lobeBench.dashboard.setup.col.model": "Model",
+ "lobeBench.dashboard.setup.col.settings": "Settings",
+ "lobeBench.dashboard.setup.col.steps": "Max steps",
+ "lobeBench.dashboard.setup.hint": "Saved when the experiment started: the selected models and run settings. Cases and grading rules come from the current library.",
+ "lobeBench.dashboard.spent": "Spent {{cost}}",
+ "lobeBench.dashboard.statusIncomplete": "Incomplete",
+ "lobeBench.dashboard.tabs.cases": "By case",
+ "lobeBench.dashboard.tabs.results": "Results",
+ "lobeBench.dashboard.tabs.setup": "Setup",
+ "lobeBench.dataset.custom": "My dataset",
+ "lobeBench.dataset.deleteInBenchmark": "This dataset is part of a benchmark. Delete the benchmark first; its datasets are kept.",
+ "lobeBench.dataset.noRuns": "No run on this dataset yet. Run an experiment on it.",
+ "lobeBench.dataset.notFound": "Case set not found",
+ "lobeBench.dataset.own.subtitle_one": "{{count}} case. The cases are fixed; import an updated package as a new dataset.",
+ "lobeBench.dataset.own.subtitle_other": "{{count}} cases. The cases are fixed; import an updated package as a new dataset.",
+ "lobeBench.dataset.release": "Release {{release}}",
+ "lobeBench.dataset.runCount_one": "{{count}} run on this dataset",
+ "lobeBench.dataset.runCount_other": "{{count}} runs on this dataset",
+ "lobeBench.environments.col.cases": "Cases",
+ "lobeBench.environments.col.name": "Environment",
+ "lobeBench.environments.col.setup": "Setup",
+ "lobeBench.environments.delete.confirm": "Delete this environment? Its {{count}} cases keep running on their own settings, without it.",
+ "lobeBench.environments.editor.agentName": "Agent name the user knows it by (optional)",
+ "lobeBench.environments.editor.builtIn": "Built-in environment: shown as is. Duplicate it to make an editable copy for your own cases.",
+ "lobeBench.environments.editor.description": "Description",
+ "lobeBench.environments.editor.duplicate": "Duplicate",
+ "lobeBench.environments.editor.edit": "Edit environment",
+ "lobeBench.environments.editor.envPrompt": "Extra system context (optional)",
+ "lobeBench.environments.editor.impact": "Used by {{count}} cases — saving changes them all",
+ "lobeBench.environments.editor.memory": "Memory",
+ "lobeBench.environments.editor.memory.effort": "Effort",
+ "lobeBench.environments.editor.memory.hint": "When on, each attempt gets its own Memory seeded from the entries below; the model can read it, or read and write it.",
+ "lobeBench.environments.editor.memory.invalid": "The seed entries must be a JSON object.",
+ "lobeBench.environments.editor.memory.permission": "Tool permission",
+ "lobeBench.environments.editor.memory.placeholder": "{ \"persona\": { \"narrative\": \"…\" }, \"preferences\": [ … ], \"contexts\": [ … ], \"seededAt\": \"2026-07-20T09:00:00Z\" }",
+ "lobeBench.environments.editor.memory.seeds": "Seed entries (JSON)",
+ "lobeBench.environments.editor.memory.template": "Insert an example",
+ "lobeBench.environments.editor.name": "Name",
+ "lobeBench.environments.editor.new": "New environment",
+ "lobeBench.environments.editor.saved": "Environment saved",
+ "lobeBench.environments.empty": "No environments yet.",
+ "lobeBench.environments.new": "New environment",
+ "lobeBench.environments.setup.clock": "clock {{date}}",
+ "lobeBench.environments.setup.memory": "Memory {{permission}}",
+ "lobeBench.environments.setup.mock": "{{count}} mocked",
+ "lobeBench.environments.setup.none": "product defaults",
+ "lobeBench.environments.setup.tools": "{{count}} tools",
+ "lobeBench.environments.subtitle": "The persona, tools, Memory, clock and mocked connectors cases run in. Many cases share one; change it once and they all follow.",
+ "lobeBench.environments.title": "Environments",
+ "lobeBench.experiment.delete": "Delete experiment",
+ "lobeBench.experiment.delete.active": "Stop the experiment before deleting it",
+ "lobeBench.experiment.delete.confirm": "Delete \"{{name}}\"? Its runs, per-case results and Judge verdicts are removed with it, and the leaderboard no longer counts them. This cannot be undone.",
+ "lobeBench.experiment.delete.done": "Experiment deleted",
+ "lobeBench.experiment.delete.failed": "Could not delete the experiment",
+ "lobeBench.experiment.edit.failed": "Could not update the experiment",
+ "lobeBench.experiment.edit.saved": "Experiment updated",
+ "lobeBench.experiment.edit.title": "Edit experiment",
+ "lobeBench.experiment.line_one": "{{count}} contender · {{dataset}} · {{k}}× per case",
+ "lobeBench.experiment.line_other": "{{count}} contenders · {{dataset}} · {{k}}× per case",
+ "lobeBench.experiment.more": "More actions",
+ "lobeBench.experiment.noRuns": "No run in this experiment yet.",
+ "lobeBench.experiment.outdated": "Earlier case version: not on any leaderboard",
+ "lobeBench.experiment.runCount_one": "{{count}} run in this experiment",
+ "lobeBench.experiment.runCount_other": "{{count}} runs in this experiment",
+ "lobeBench.experiment.unnamed": "Untitled experiment",
+ "lobeBench.library.badge.broken": "Possibly broken",
+ "lobeBench.library.badge.easy": "Low discrimination",
+ "lobeBench.library.cases": "{{count}} cases",
+ "lobeBench.library.col.case": "Case",
+ "lobeBench.library.col.category": "Category",
+ "lobeBench.library.col.level": "Level",
+ "lobeBench.library.col.tools": "Tools",
+ "lobeBench.library.empty": "No shared case library is installed. You can import a dataset ZIP without one.",
+ "lobeBench.library.filter.category": "Category",
+ "lobeBench.library.filter.count": "{{shown}} of {{total}} cases",
+ "lobeBench.library.filter.level": "Level",
+ "lobeBench.library.filter.search": "Search cases",
+ "lobeBench.library.levels": "{{l1}} L1 · {{l2}} L2 · {{l3}} L3 · {{l4}} L4",
+ "lobeBench.library.subtitle": "Previously installed shared cases. Select cases to make a dataset, or import a dataset ZIP directly.",
+ "lobeBench.library.title": "Case library",
+ "lobeBench.new.advanced": "Advanced",
+ "lobeBench.new.cancel": "Cancel",
+ "lobeBench.new.cases.selected": "{{selected}} of {{total}} cases",
+ "lobeBench.new.confirm.billing": "Model and judge tokens are billed to your providers.",
+ "lobeBench.new.confirm.cost": "Estimated cost {{cost}}, from your recent runs of the same models.",
+ "lobeBench.new.confirm.costUnknown": "No cost history for these models yet; the dashboard shows the cost as it runs.",
+ "lobeBench.new.confirm.judge": "Judge: {{model}}",
+ "lobeBench.new.confirm.judgeDefault": "Judge: system default (pick one in Settings)",
+ "lobeBench.new.confirm.judgeOf": "{{benchmark}} judged by {{model}}",
+ "lobeBench.new.confirm.line": "{{cases}} cases × {{contenders}} contenders × {{k}} attempts each = {{attempts}} attempts.",
+ "lobeBench.new.confirm.ok": "Start",
+ "lobeBench.new.confirm.standardOf": "{{benchmark}}: judged by {{model}}, {{k}} attempts per case, up to {{maxSteps}} steps, {{timeout}} min per attempt",
+ "lobeBench.new.confirm.title": "Start this experiment?",
+ "lobeBench.new.contenders.add": "Add contender",
+ "lobeBench.new.contenders.empty": "Add at least one contender.",
+ "lobeBench.new.contenders.hint": "The same model with other settings is another contender; they compare side by side.",
+ "lobeBench.new.contenders.remove": "Remove contender",
+ "lobeBench.new.contenders.saved": "Saved contenders — click to add",
+ "lobeBench.new.dataset.cases": "{{count}} cases",
+ "lobeBench.new.draft.datasetUnavailable": "This case set is no longer available. Choose another case set.",
+ "lobeBench.new.draft.discard": "Discard draft",
+ "lobeBench.new.draft.modelsUnavailable": "A selected model or judge is no longer available. Remove it or select an available model.",
+ "lobeBench.new.draft.restored": "Your unfinished experiment has been restored.",
+ "lobeBench.new.draft.storageError": "This browser could not save your draft. Keep this page open until you start the experiment.",
+ "lobeBench.new.error": "Could not start the experiment",
+ "lobeBench.new.estimate": "{{attempts}} attempts. Each attempt uses separate memory and a mock environment. Runs with incomplete or errored attempts are not ranked.",
+ "lobeBench.new.group.benchmarks": "Benchmarks",
+ "lobeBench.new.group.datasets": "My datasets",
+ "lobeBench.new.judge": "Judge model",
+ "lobeBench.new.judge.hint": "Grades every attempt of this experiment. Leave empty to use the benchmark default.",
+ "lobeBench.new.judge.missing": "{{name}} has no judge model, so it cannot be run. Import it again as a new benchmark and choose a judge.",
+ "lobeBench.new.k.hint": "Leaderboards rank runs with at least {{k}} attempts per case.",
+ "lobeBench.new.k.once": "once",
+ "lobeBench.new.k.ranked": "{{k}}× (leaderboard)",
+ "lobeBench.new.k.times": "{{k}}×",
+ "lobeBench.new.launch.abandon": "Stop recovery",
+ "lobeBench.new.launch.abandon.confirm": "Runs already started keep running in the experiment. The form unlocks; starting again creates a new experiment and may incur additional costs.",
+ "lobeBench.new.launch.abandon.title": "Stop recovering this launch?",
+ "lobeBench.new.launch.back": "Back to experiments",
+ "lobeBench.new.launch.busy": "Another tab is starting this experiment. Check again shortly.",
+ "lobeBench.new.launch.close": "Close",
+ "lobeBench.new.launch.continue": "Continue launching",
+ "lobeBench.new.launch.currentRun": "Run {{index}} of {{total}} · {{name}}",
+ "lobeBench.new.launch.elapsed": "Since first start: {{elapsed}}",
+ "lobeBench.new.launch.failed": "Stopped at “{{name}}”: {{error}}. Continue to check progress and finish launching.",
+ "lobeBench.new.launch.interrupted": "Launch not finished",
+ "lobeBench.new.launch.legacy": "A launch record from an earlier version was found.",
+ "lobeBench.new.launch.legacy.hint": "This record cannot be resumed here. Open the experiment to inspect its runs, or stop recovery.",
+ "lobeBench.new.launch.metadataFailed": "Saving the experiment setup failed: {{error}}. Continue to retry saving it.",
+ "lobeBench.new.launch.occupied": "Another tab has started a launch for this benchmark. Its saved record is shown above.",
+ "lobeBench.new.launch.open": "Open experiment",
+ "lobeBench.new.launch.pending": "An experiment launch is unfinished. Settings are locked while it is being recovered.",
+ "lobeBench.new.launch.perBenchmark": "Launch records are saved separately for each benchmark. Return to its form to recover an unfinished launch.",
+ "lobeBench.new.launch.progress": "{{started}} of {{total}} contenders have been accepted for execution.",
+ "lobeBench.new.launch.recheck": "Check again",
+ "lobeBench.new.launch.recovery": "Startup has not been confirmed. Check and continue from the saved checkpoint; existing runs will not be started again.",
+ "lobeBench.new.launch.stage.check": "Checking saved runs",
+ "lobeBench.new.launch.stage.complete": "All runs submitted. Opening the experiment…",
+ "lobeBench.new.launch.stage.experiment": "Creating experiment",
+ "lobeBench.new.launch.stage.metadata": "Saving experiment setup",
+ "lobeBench.new.launch.stage.run": "Preparing run and checking connections",
+ "lobeBench.new.launch.stage.start": "Checking connections and submitting run",
+ "lobeBench.new.launch.steps": "{{completed}} of {{total}} launch steps complete",
+ "lobeBench.new.launch.storageError": "This browser could not save the launch record. No new launch was started.",
+ "lobeBench.new.launch.title": "Starting experiment",
+ "lobeBench.new.launch.unconfirmed": "{{count}} contenders are awaiting server confirmation: {{names}}. Check again shortly or open the experiment.",
+ "lobeBench.new.launch.unknown": "The last launch did not finish. Continue to check its saved progress.",
+ "lobeBench.new.launch.waiting": "You can visit other pages while startup continues in this browser tab. Return to this experiment to check progress.",
+ "lobeBench.new.maxConcurrency": "Cases at once",
+ "lobeBench.new.maxConcurrency.hint_one": "How many cases each contender runs at the same time, each with its single attempt. Lower it if a provider rate-limits you. Leave empty to start every case together.",
+ "lobeBench.new.maxConcurrency.hint_other": "How many cases each contender runs at the same time, each with its {{count}} attempts. Lower it if a provider rate-limits you. Leave empty to start every case together.",
+ "lobeBench.new.maxConcurrency.placeholder": "No limit",
+ "lobeBench.new.maxSteps": "Max steps per attempt",
+ "lobeBench.new.name": "Experiment name",
+ "lobeBench.new.name.placeholder": "Optional — named after the contenders if empty",
+ "lobeBench.new.providerCheckFailed": "Could not check the model providers. Try again.",
+ "lobeBench.new.providerKeyMissing": "No API key for {{provider}} on this server. Add one under Settings → AI providers, or pick a model from another provider.",
+ "lobeBench.new.question": "Question you want answered",
+ "lobeBench.new.question.placeholder": "Optional, e.g. \"Does deep thinking help on finance cases?\"",
+ "lobeBench.new.standard.missing": "{{name}} has no judge model or run rules, so it cannot be run.",
+ "lobeBench.new.standard.mixed": "The chosen benchmarks use different run rules (attempts, steps or timeout). Start a separate experiment for each.",
+ "lobeBench.new.start": "Start experiment",
+ "lobeBench.new.step.contenders": "2 · Contenders · model + settings",
+ "lobeBench.new.step.dataset": "1 · Benchmarks · choose one or more",
+ "lobeBench.new.step.k": "3 · Attempts per case",
+ "lobeBench.new.subtitle": "Two steps: benchmarks and contenders. Each benchmark sets its own judge, attempts per case, step limit and timeout.",
+ "lobeBench.new.timeout": "Timeout per attempt (minutes)",
+ "lobeBench.new.title": "New experiment",
+ "lobeBench.overview.attention.errors": "{{count}} cases with execution errors",
+ "lobeBench.overview.attention.external": "{{count}} cases awaiting external grading",
+ "lobeBench.overview.attention.judgeErrors": "{{count}} cases could not be graded",
+ "lobeBench.overview.attention.ungraded": "Grading unfinished for {{count}} cases",
+ "lobeBench.overview.card.contenders": "Contenders",
+ "lobeBench.overview.card.noDataset": "No datasets yet",
+ "lobeBench.overview.card.noDatasetHint": "Datasets are chosen when a benchmark is created",
+ "lobeBench.overview.card.noRun": "No full run yet",
+ "lobeBench.overview.card.noRunHint": "Run every case of a dataset to rank here",
+ "lobeBench.overview.card.on": "on {{dataset}}",
+ "lobeBench.overview.card.openBenchmark": "Open benchmark",
+ "lobeBench.overview.card.runs": "Runs",
+ "lobeBench.overview.card.top": "Leader · {{name}}",
+ "lobeBench.overview.createBenchmark": "New benchmark",
+ "lobeBench.overview.experiments.empty": "No experiments yet. Start one to compare models on a dataset.",
+ "lobeBench.overview.newExperiment": "New experiment",
+ "lobeBench.overview.notInstalled": "Start by importing a dataset ZIP. You can use a shared package or create your own from the example.",
+ "lobeBench.overview.passedOf": "{{passed}}/{{total}}",
+ "lobeBench.overview.running": "Running",
+ "lobeBench.overview.runningLine": "{{done}}/{{total}} cases · {{cost}} so far",
+ "lobeBench.picks.clear": "Clear",
+ "lobeBench.picks.create": "Create dataset",
+ "lobeBench.picks.created_one": "Made {{dataset}} with {{count}} case",
+ "lobeBench.picks.created_other": "Made {{dataset}} with {{count}} cases",
+ "lobeBench.picks.defaultName": "My dataset",
+ "lobeBench.picks.delete": "Delete dataset",
+ "lobeBench.picks.delete.confirm": "Delete \"{{name}}\"? The runs on it and their results are deleted too, and leave every leaderboard. This cannot be undone.",
+ "lobeBench.picks.failed": "The dataset was not saved. Try again.",
+ "lobeBench.picks.fixed": "Its cases are fixed once it is made, so its runs always mean the same cases. For other cases, make another dataset.",
+ "lobeBench.picks.hint.library": "Check cases to make a dataset of your own.",
+ "lobeBench.picks.name": "Dataset name",
+ "lobeBench.picks.name.placeholder": "e.g. Finance L2",
+ "lobeBench.picks.rename": "Rename",
+ "lobeBench.picks.run": "Run experiment",
+ "lobeBench.picks.selected": "{{count}} selected",
+ "lobeBench.picks.title_one": "Make a dataset of {{count}} case",
+ "lobeBench.picks.title_other": "Make a dataset of {{count}} cases",
+ "lobeBench.settings.benchmark": "Benchmark",
+ "lobeBench.settings.defaults": "New experiment defaults",
+ "lobeBench.settings.defaults.hint": "What the New experiment form starts with; every value can still be changed per experiment.",
+ "lobeBench.settings.defaults.k": "Attempts per case",
+ "lobeBench.settings.defaults.maxSteps": "Max steps per attempt",
+ "lobeBench.settings.defaults.timeout": "Timeout per attempt (minutes)",
+ "lobeBench.settings.grading.hint": "Comes with Lobe Bench. Any experiment can choose a different grader when you start it.",
+ "lobeBench.settings.grading.line": "Attempts are graded by {{model}}.",
+ "lobeBench.settings.grading.title": "Grading",
+ "lobeBench.settings.grading.unset": "Attempts are graded by the system default model.",
+ "lobeBench.settings.judge": "Judge model",
+ "lobeBench.settings.judge.clear": "Use system default",
+ "lobeBench.settings.judge.hint": "Grades every attempt. Pick a model that is not one of the contenders; a case set or a case can still name its own judge.",
+ "lobeBench.settings.judge.placeholder": "System default (the topic model of your assistant)",
+ "lobeBench.settings.mine.hint": "Only you see these; every experiment can still change them.",
+ "lobeBench.settings.mine.reset": "Reset",
+ "lobeBench.settings.mine.reset.done": "Back to the Lobe Bench defaults",
+ "lobeBench.settings.mine.saved": "Saved for you",
+ "lobeBench.settings.mine.title": "Your defaults for new experiments",
+ "lobeBench.settings.notInstalled": "No Lobe Bench benchmark in this account yet.",
+ "lobeBench.settings.save": "Save",
+ "lobeBench.settings.saved": "Saved",
+ "lobeBench.settings.subtitle": "Where mock tool connections are managed. Each benchmark fixes its own judge and run rules when it is made.",
+ "lobeBench.settings.title": "Settings",
+ "lobeBench.sidebar.benchmarks": "Benchmarks",
+ "lobeBench.sidebar.benchmarks.empty": "No benchmarks yet. Import a dataset or create one.",
+ "lobeBench.sidebar.contenders": "Contenders",
+ "lobeBench.sidebar.datasets": "Datasets",
+ "lobeBench.sidebar.datasets.empty": "No datasets yet. Import a dataset ZIP to start.",
+ "lobeBench.sidebar.draft": "New experiment (not started)",
+ "lobeBench.sidebar.empty": "No experiments yet",
+ "lobeBench.sidebar.experiments": "Experiments",
+ "lobeBench.sidebar.library": "Case library",
+ "lobeBench.sidebar.newBenchmark": "New benchmark",
+ "lobeBench.sidebar.newExperiment": "New experiment",
+ "lobeBench.sidebar.overview": "Dashboard",
+ "lobeBench.sidebar.settings": "Settings",
+ "lobeBench.status.aborted": "Aborted",
+ "lobeBench.status.done": "Done",
+ "lobeBench.status.failed": "Failed",
+ "lobeBench.status.pending": "Pending",
+ "lobeBench.status.running": "Running {{done}}/{{total}}",
+ "lobeBench.subtitle": "LobeHub's standard cases. Run experiments to compare models, settings and harnesses.",
+ "lobeBench.switch.agent": "Evaluation Lab",
+ "lobeBench.switch.bench": "Lobe Bench",
+ "lobeBench.title": "Lobe Bench",
+ "lobeBench.topicCase.agent": "Agent",
+ "lobeBench.topicCase.answer": "Recorded answer",
+ "lobeBench.topicCase.context": "{{count}} earlier messages replay before the request",
+ "lobeBench.topicCase.input": "Request under test",
+ "lobeBench.topicCase.intro": "Paste a conversation id. Its last request becomes the case, the earlier messages replay as context, and the Agent that answered it (persona, tools) is kept with the case.",
+ "lobeBench.topicCase.load": "Load",
+ "lobeBench.topicCase.loadError": "Could not load that conversation",
+ "lobeBench.topicCase.noAgent": "No Agent setup captured; the case runs on the contender’s default setup.",
+ "lobeBench.topicCase.rules": "Rules",
+ "lobeBench.topicCase.rules.hint": "One per line, starting with Must: or Must not:. Drafted from the conversation; check them before saving.",
+ "lobeBench.topicCase.rulesRequired": "Add at least one rule",
+ "lobeBench.topicCase.save": "Save to My cases",
+ "lobeBench.topicCase.saveError": "Could not save the case",
+ "lobeBench.topicCase.saved": "Case saved to My cases",
+ "lobeBench.topicCase.title": "Case from a conversation",
+ "lobeBench.topicCase.tools": "Tools",
+ "lobeBench.topicCase.topicId": "Conversation id",
+ "lobeBench.topicCase.topicId.placeholder": "tpc_… (the topic in the chat URL)",
+ "lobeBench.unit.min": "{{value}} min",
"overview.createBenchmark": "Create Benchmark",
"overview.createExperiment": "Create Experiment",
"overview.importDataset": "Import Dataset",
@@ -387,8 +962,11 @@
"run.metrics.duration": "Duration",
"run.metrics.errorCases": "Error",
"run.metrics.evaluated": "{{count}} evaluated",
+ "run.metrics.passAllK": "All {{k}} attempts passed (pass^{{k}})",
"run.metrics.passRate": "Pass Rate",
+ "run.metrics.passRate.anyK": "Pass Rate · passed at least 1 of {{k}} attempts (pass@{{k}})",
"run.metrics.passRate.short": "pass rate",
+ "run.metrics.perAttempt": "Per attempt (pass@1)",
"run.metrics.perCase": "/ case",
"run.metrics.tokens": "Tokens",
"run.metrics.totalDuration": "Cumulative",
diff --git a/locales/zh-CN/eval.json b/locales/zh-CN/eval.json
index dde28209cb1..39050c4ebd1 100644
--- a/locales/zh-CN/eval.json
+++ b/locales/zh-CN/eval.json
@@ -1,5 +1,6 @@
{
"benchmark.actions.delete": "删除基准",
+ "benchmark.actions.delete.builtIn": "内置基准 · 不可删除",
"benchmark.actions.delete.confirm": "确定要删除此基准吗?相关数据集和评测记录也会被删除。",
"benchmark.actions.edit": "编辑基准",
"benchmark.actions.export": "导出",
@@ -35,6 +36,7 @@
"benchmark.create.tags.label": "标签",
"benchmark.create.tags.placeholder": "添加标签,用逗号或空格分隔",
"benchmark.create.title": "创建基准",
+ "benchmark.delete.error": "删除基准失败",
"benchmark.detail.backToOverview": "返回总览",
"benchmark.detail.datasetCount": "此基准包含 {{count}} 个数据集",
"benchmark.detail.runCount": "此基准有 {{count}} 次评测",
@@ -54,6 +56,7 @@
"benchmark.detail.stats.runs": "评测",
"benchmark.detail.stats.tags": "标签",
"benchmark.detail.stats.topAgents": "Top Agents",
+ "benchmark.detail.stats.topModels": "Top Models",
"benchmark.detail.stats.totalCases": "总用例数",
"benchmark.detail.stats.waiting": "Waiting...",
"benchmark.detail.tabs.data": "数据",
@@ -99,9 +102,16 @@
"caseDetail.failureReason": "失败原因",
"caseDetail.input": "输入",
"caseDetail.judgeComment": "裁判评语",
+ "caseDetail.judgeError.regradeHint": "原答案已保留。在实验页点「重跑」,会把这道题重新跑一遍并评分。",
+ "caseDetail.memory.agent": "作答中写入",
+ "caseDetail.memory.empty": "没有记忆条目。",
+ "caseDetail.memory.removed": "已删除",
+ "caseDetail.memory.seed": "题目给的",
"caseDetail.resources": "资源",
"caseDetail.score": "评分",
"caseDetail.section.externalResult": "外部结果",
+ "caseDetail.section.memory": "结束时的记忆",
+ "caseDetail.section.rules": "规则",
"caseDetail.section.runtime": "执行信息",
"caseDetail.section.scoring": "评分详情",
"caseDetail.section.testCase": "测试用例",
@@ -117,6 +127,59 @@
"common.save": "保存",
"common.unknown": "未知",
"common.update": "更新",
+ "connections.adapter": "LobeBench Mock 适配器",
+ "connections.authIncluded": "包内已包含访问凭证",
+ "connections.authNone": "无鉴权",
+ "connections.authSaved": "已保存鉴权",
+ "connections.authentication": "鉴权",
+ "connections.autoImport": "导入时会自动创建并绑定这些连接,无需手动填写地址或 Token。",
+ "connections.bearerAuth": "Bearer 令牌",
+ "connections.cancel": "取消",
+ "connections.case": "题目覆盖配置",
+ "connections.checking": "正在检查连接是否可用…",
+ "connections.clearAuth": "不使用鉴权(清除已保存的凭据)",
+ "connections.completeScope": "请为正在修改的环境或题目选齐所有服务,或清空本次选择后稍后配置。",
+ "connections.configureLater": "稍后配置",
+ "connections.configured": "所有需要的服务均已配置连接。",
+ "connections.create": "创建连接",
+ "connections.datasetHint": "使用同一环境的题目会复用连接。此处检查已保存的绑定,运行开始时会检查服务本身。",
+ "connections.datasetOnly": "请在使用此环境的数据集中管理连接。新数据集需先导入,再配置连接。",
+ "connections.disabled": "已停用",
+ "connections.edit": "编辑连接",
+ "connections.editHint": "更改将影响使用此连接的所有环境。已保存的凭据不会显示;输入新凭据即可替换。",
+ "connections.empty": "还没有可用的 HTTP 连接。在此创建后,再在上方选择。",
+ "connections.enabled": "启用连接",
+ "connections.environment": "环境",
+ "connections.fromPackage": "使用 ZIP 内附的连接",
+ "connections.headerAuth": "自定义请求头",
+ "connections.hideDetails": "收起连接",
+ "connections.hint": "为每个服务选择连接。每个连接单独管理地址和鉴权,同一个连接可以供多个服务复用。",
+ "connections.importLater": "部分服务未附带连接,可以先导入,再到题集内配置,配置完成后即可运行。",
+ "connections.included": "ZIP 内附的连接",
+ "connections.keepAuth": "保留已保存的鉴权",
+ "connections.manage": "配置连接",
+ "connections.missing": "还有 {{count}} 个服务需要配置连接,完成后才能运行。",
+ "connections.name": "连接名称",
+ "connections.noAuth": "包内未包含访问凭证",
+ "connections.openManager": "管理数据集连接地址和鉴权",
+ "connections.optional": "选择已有连接(可选)",
+ "connections.refresh": "刷新连接",
+ "connections.replaceAuth": "更改服务地址时,请替换或清除鉴权信息。",
+ "connections.save": "保存连接",
+ "connections.saveAndTest": "保存并测试",
+ "connections.saved": "连接已保存",
+ "connections.settingsHint": "Mock 服务使用各题集的环境和题目所绑定的连接。ZIP 导入可以自动配置,到对应题集即可修改绑定。",
+ "connections.showDetails": "展开连接",
+ "connections.standard": "标准 MCP",
+ "connections.statusConnected": "最近检查成功",
+ "connections.statusDisconnected": "尚未检查",
+ "connections.statusError": "最近检查失败",
+ "connections.tested": "已连接 · {{count}} 个可用工具",
+ "connections.title": "Mock MCP 连接",
+ "connections.transport": "{{service}} 的协议",
+ "connections.unavailable": "连接不可用,请重新选择",
+ "connections.unbound": "尚未绑定环境或用例",
+ "connections.url": "MCP 服务地址",
"dataset.actions.addDataset": "添加数据集",
"dataset.actions.import": "导入数据",
"dataset.actions.importDataset": "导入数据集",
@@ -190,6 +253,25 @@
"dataset.import.metadata": "元数据",
"dataset.import.metadataDesc": "额外信息,原样存储",
"dataset.import.next": "下一步",
+ "dataset.import.package.asNew": "导入为新 Dataset",
+ "dataset.import.package.benchmark": "所属 Benchmark",
+ "dataset.import.package.benchmarkName": "新 Benchmark 名称",
+ "dataset.import.package.cases": "{{count}} 道题",
+ "dataset.import.package.environments": "{{count}} 个环境",
+ "dataset.import.package.hint": "Dataset ZIP 题包 · 最大 10 MiB",
+ "dataset.import.package.history": "导入后题目保持固定。更新题包请导入为新的 Dataset,确保历史成绩仍对应原来的题目。",
+ "dataset.import.package.instructions": "上传你的 ZIP 题包。ZIP 根目录需包含 dataset.json。",
+ "dataset.import.package.judge": "评审模型",
+ "dataset.import.package.judge.hint": "这个 Benchmark 下的所有运行都用这个模型判分,分数才能互相比较。创建后不能修改。",
+ "dataset.import.package.judge.placeholder": "选择评审模型",
+ "dataset.import.package.mockServices": "使用的 Mock 服务:{{services}}。运行时通过各自绑定的连接调用。",
+ "dataset.import.package.name": "Dataset 名称",
+ "dataset.import.package.newBenchmark": "创建新的 Benchmark",
+ "dataset.import.package.preserved": "题目内容、评分规则和环境配置会一起导入,保存为你账号下的私有 Dataset。",
+ "dataset.import.package.preview": "确认题包内容",
+ "dataset.import.package.refreshError": "Dataset 已导入,但列表刷新失败。请刷新页面查看,无需重复导入。",
+ "dataset.import.package.tooLarge": "ZIP 题包过大,请选择不超过 10 MiB 的文件。",
+ "dataset.import.package.zipRequired": "请选择 Dataset ZIP 题包。",
"dataset.import.parseError": "文件解析失败",
"dataset.import.parsing": "正在解析文件...",
"dataset.import.prev": "上一步",
@@ -203,7 +285,7 @@
"dataset.import.step.upload": "上传文件",
"dataset.import.success": "成功导入 {{count}} 个数据用例",
"dataset.import.title": "导入数据集",
- "dataset.import.upload.hint": "支持 CSV、XLSX、JSON、JSONL",
+ "dataset.import.upload.hint": "支持 CSV、XLSX、JSON、JSONL 和 Dataset ZIP 题包(最大 10 MiB)",
"dataset.import.upload.text": "点击或拖拽文件到此处",
"dataset.import.uploading": "上传中...",
"dataset.switchDataset": "切换数据集",
@@ -232,6 +314,8 @@
"evalMode.provider.placeholder": "LLM 服务商(如 openai、azure)",
"evalMode.rubric": "混合指标评分",
"evalMode.rubric.desc": "使用基准的加权指标进行混合评分",
+ "evalMode.rule-checklist": "规则清单",
+ "evalMode.rule-checklist.desc": "LLM 逐条判定 Must / Must not 规则,全部满足才算通过",
"evalMode.systemRole.label": "系统提示词",
"evalMode.systemRole.placeholder": "LLM 评判的系统提示词(可选)",
"experiment.actions.create": "创建实验",
@@ -277,6 +361,497 @@
"experiment.list.title": "实验",
"experiment.overview.emptyHint": "运行活动与作用域数据集将显示在这里。",
"experiment.run.parent": "派生自 {{name}}",
+ "lobeBench.attempt.backToExperiment": "返回实验",
+ "lobeBench.benchmark.best": "{{count}} 次完整运行中最好 {{value}}",
+ "lobeBench.benchmark.cases": "{{count}} 道题",
+ "lobeBench.benchmark.create.datasets": "数据集",
+ "lobeBench.benchmark.create.datasets.empty": "还没有可用的数据集。请先导入一个数据集 ZIP;导入后它不属于任何 Benchmark,直到你用它建一个 Benchmark。",
+ "lobeBench.benchmark.create.datasets.hint": "Benchmark 跑的就是它包含的数据集,至少选一个。",
+ "lobeBench.benchmark.create.datasets.placeholder": "选择数据集",
+ "lobeBench.benchmark.create.description": "描述",
+ "lobeBench.benchmark.create.description.placeholder": "可选:这个基准衡量什么",
+ "lobeBench.benchmark.create.failed": "基准创建失败",
+ "lobeBench.benchmark.create.judge": "评审模型",
+ "lobeBench.benchmark.create.judge.hint": "这个 Benchmark 下的所有运行都用这个模型判分,分数才能互相比较。创建后不能修改。",
+ "lobeBench.benchmark.create.judge.placeholder": "选择评审模型",
+ "lobeBench.benchmark.create.name": "名称",
+ "lobeBench.benchmark.create.name.placeholder": "例如:金融类 Agent",
+ "lobeBench.benchmark.create.submit": "创建基准",
+ "lobeBench.benchmark.create.title": "新建基准",
+ "lobeBench.benchmark.custom": "我的题目",
+ "lobeBench.benchmark.datasets": "数据集",
+ "lobeBench.benchmark.datasets.add": "添加数据集",
+ "lobeBench.benchmark.datasets.empty": "没有数据集。基准的数据集在创建时选定;要用别的数据集,请新建一个基准。",
+ "lobeBench.benchmark.datasets.hint": "这个基准由以下数据集组成。一次运行跑完某个数据集的全部题目,才计入排行榜。",
+ "lobeBench.benchmark.datasets.noneLoose": "还没有可添加的数据集:去题库里建一个",
+ "lobeBench.benchmark.datasets.remove": "移出这个基准",
+ "lobeBench.benchmark.delete.confirm": "删除 {{name}}?它的运行和结果会一起删除;其中的数据集保留,可以再用来建新的 Benchmark。",
+ "lobeBench.benchmark.newExperiment": "新建实验",
+ "lobeBench.benchmark.noRuns": "还没有完整运行",
+ "lobeBench.benchmark.noRunsYet": "这个基准还没有运行。新建实验,在某个题集上比较参赛者。",
+ "lobeBench.benchmark.notFound": "找不到该基准",
+ "lobeBench.benchmark.outdatedRun": "旧版题目 · 不计入排名",
+ "lobeBench.benchmark.rank.active_one": "{{count}} 次运行进行中",
+ "lobeBench.benchmark.rank.active_other": "{{count}} 次运行进行中",
+ "lobeBench.benchmark.rank.anyRate": "{{k}} 次中过一次:{{value}}",
+ "lobeBench.benchmark.rank.broken_one": "{{count}} 场运行含未完成或出错的作答,未参与排名",
+ "lobeBench.benchmark.rank.broken_other": "{{count}} 场运行含未完成或出错的作答,未参与排名",
+ "lobeBench.benchmark.rank.compare.all": "对比:全部模型",
+ "lobeBench.benchmark.rank.compare.reset": "显示全部模型",
+ "lobeBench.benchmark.rank.compare.some_one": "对比:{{count}} 个模型",
+ "lobeBench.benchmark.rank.compare.some_other": "对比:{{count}} 个模型",
+ "lobeBench.benchmark.rank.cost": "${{cost}}/题",
+ "lobeBench.benchmark.rank.empty": "{{set}} 上还没有跑完全部题目的运行。在它上面新建实验,模型排名就会出现在这里。",
+ "lobeBench.benchmark.rank.estimated": "由 {{attempts}} 次换算",
+ "lobeBench.benchmark.rank.fewAttempts_one": "{{count}} 场运行缺少可比较的 {{k}} 次作答成绩,未参与排名",
+ "lobeBench.benchmark.rank.fewAttempts_other": "{{count}} 场运行缺少可比较的 {{k}} 次作答成绩,未参与排名",
+ "lobeBench.benchmark.rank.hint": "每个参赛者在整个题集上最好的一次完整运行,按“{{k}} 次全过”的题数排名。每题跑了更多次的按 {{k}} 次换算;少于 {{k}} 次的不参与排名。",
+ "lobeBench.benchmark.rank.legend.rate": "{{k}} 次全过(按此排名)",
+ "lobeBench.benchmark.rank.legend.reach": "{{k}} 次中至少过 1 次",
+ "lobeBench.benchmark.rank.outdated_one": "{{count}} 次运行用的是旧版题目,不计入排名",
+ "lobeBench.benchmark.rank.outdated_other": "{{count}} 次运行用的是旧版题目,不计入排名",
+ "lobeBench.benchmark.rank.setOption_one": "{{name}} · {{count}} 个参赛者",
+ "lobeBench.benchmark.rank.setOption_other": "{{name}} · {{count}} 个参赛者",
+ "lobeBench.benchmark.rank.summary_one": "{{count}} 个参赛者 · 来自 {{runs}} 次完整运行",
+ "lobeBench.benchmark.rank.summary_other": "{{count}} 个参赛者 · 来自 {{runs}} 次完整运行",
+ "lobeBench.benchmark.rank.title": "排行榜",
+ "lobeBench.benchmark.rank.unjudged_one": "{{count}} 次完整运行等待评审",
+ "lobeBench.benchmark.rank.unjudged_other": "{{count}} 次完整运行等待评审",
+ "lobeBench.benchmark.runCases": "{{total}} 题中的 {{selected}} 题",
+ "lobeBench.benchmark.runCount_one": "本基准上共 {{count}} 次评测运行",
+ "lobeBench.benchmark.runCount_other": "本基准上共 {{count}} 次评测运行",
+ "lobeBench.benchmark.runs": "运行",
+ "lobeBench.benchmark.standard.hint": "这个 Benchmark 下的所有运行都用这个评审模型和这些规则,分数才能互相比较。创建后不能修改,建实验时也不能另选。",
+ "lobeBench.benchmark.standard.k": "每题跑几次",
+ "lobeBench.benchmark.standard.title": "判分与运行规则",
+ "lobeBench.builtIn": "内置",
+ "lobeBench.case.delete": "删除",
+ "lobeBench.case.delete.confirm": "删除这道题?历史结果保留它的副本。",
+ "lobeBench.case.difficulty.why": "判为该难度的依据:{{signals}}。",
+ "lobeBench.case.edit": "编辑",
+ "lobeBench.case.editor.category": "分类",
+ "lobeBench.case.editor.edit": "编辑题目",
+ "lobeBench.case.editor.environment": "环境",
+ "lobeBench.case.editor.environment.none": "不共享,只用本题自己的设置",
+ "lobeBench.case.editor.environment.usedBy": "{{count}} 道题在用",
+ "lobeBench.case.editor.input": "用户请求",
+ "lobeBench.case.editor.input.placeholder": "用户让 Agent 做什么。",
+ "lobeBench.case.editor.invalidDate": "时钟要是 ISO 日期,例如 2026-07-20 或 2026-07-20T09:00:00Z",
+ "lobeBench.case.editor.mock": "mock 连接器(逗号分隔)",
+ "lobeBench.case.editor.new": "新建题",
+ "lobeBench.case.editor.overrides": "本题覆盖",
+ "lobeBench.case.editor.overrides.hint": "盖在共享环境之上,留空则沿用共享环境。",
+ "lobeBench.case.editor.persona": "人设(系统提示)",
+ "lobeBench.case.editor.plugins": "工具白名单(插件标识,逗号分隔)",
+ "lobeBench.case.editor.rules": "评审规则",
+ "lobeBench.case.editor.rules.hint": "一行一条,以 \"Must:\" 或 \"Must not:\" 开头。评审逐条判定并说明每一条未达项。",
+ "lobeBench.case.editor.save": "保存",
+ "lobeBench.case.editor.saved": "题目已保存",
+ "lobeBench.case.editor.sessionDate": "时钟(ISO 日期或时刻)",
+ "lobeBench.case.editor.timezone": "时区",
+ "lobeBench.case.editor.title": "标题",
+ "lobeBench.case.editor.turns": "前文对话",
+ "lobeBench.case.editor.turns.add": "加一轮",
+ "lobeBench.case.editor.turns.hint": "在请求之前回放,让 Agent 拿到和用户一样的上下文。",
+ "lobeBench.case.fromConversation": "从对话起草",
+ "lobeBench.case.fromConversation.drafting": "正在从对话起草题目…",
+ "lobeBench.case.fromConversation.empty": "没有找到对话。",
+ "lobeBench.case.fromConversation.hint": "选一段你的对话:最后一条请求成为题目,前文作为上下文,评审模型起草规则。你保存前什么都不会写入。",
+ "lobeBench.case.fromConversation.rulesFailed": "评审模型没能起草规则({{error}})。请自己写,或在设置里指定评审模型。",
+ "lobeBench.case.fromConversation.search": "搜索对话,回车确认",
+ "lobeBench.case.level.L1": "L1",
+ "lobeBench.case.level.L2": "L2",
+ "lobeBench.case.level.L3": "L3",
+ "lobeBench.case.level.L4": "L4",
+ "lobeBench.case.new": "新建题",
+ "lobeBench.case.persona": "这道题的人设",
+ "lobeBench.case.prompt": "用户会怎么问",
+ "lobeBench.case.readOnly": "只读",
+ "lobeBench.case.rules": "评分清单",
+ "lobeBench.case.runsWith": "运行环境",
+ "lobeBench.case.runsWith.clock": "时钟",
+ "lobeBench.case.runsWith.clockPinned": "模型看到的\"今天\"固定为 {{date}}",
+ "lobeBench.case.runsWith.clockWall": "实时时间",
+ "lobeBench.case.runsWith.connectors": "模拟的连接器",
+ "lobeBench.case.runsWith.memory": "记忆",
+ "lobeBench.case.runsWith.memoryEmpty": "从空记忆开始",
+ "lobeBench.case.runsWith.memoryMode": "记忆 {{permission}} · 强度 {{effort}}",
+ "lobeBench.case.runsWith.memoryOff": "记忆关闭",
+ "lobeBench.case.runsWith.memoryRecords_one": "预置 {{count}} 条记忆",
+ "lobeBench.case.runsWith.memoryRecords_other": "预置 {{count}} 条记忆",
+ "lobeBench.case.runsWith.noConnectors": "没有连接器",
+ "lobeBench.case.testRun": "试跑",
+ "lobeBench.case.testRun.go": "跑一次",
+ "lobeBench.case.testRun.hint": "用一个参赛者把这道题跑一次并打开作答。模型 token 由你的服务商计费。",
+ "lobeBench.compare.attempt": "第 {{n}} 次",
+ "lobeBench.compare.error": "报错",
+ "lobeBench.compare.filter.judgeErrors": "评分出错",
+ "lobeBench.compare.judgeError": "评分出错",
+ "lobeBench.compare.noReason": "没有记录评分理由。",
+ "lobeBench.compare.open": "打开对话",
+ "lobeBench.compare.passes": "{{passed}}/{{total}} 通过",
+ "lobeBench.compare.pending": "还没跑完",
+ "lobeBench.compare.reason": "评分理由",
+ "lobeBench.compare.timeCost": "用时 · 费用",
+ "lobeBench.compare.toolCalls": "工具调用",
+ "lobeBench.contender.model": "模型",
+ "lobeBench.contender.model.placeholder": "选一个支持工具调用的模型",
+ "lobeBench.contender.modelDefault": "模型默认",
+ "lobeBench.contender.modelSettings": "模型设置",
+ "lobeBench.contender.name": "名称",
+ "lobeBench.contender.name.placeholder": "可选,不填就用模型名加参数",
+ "lobeBench.contender.save": "加入实验",
+ "lobeBench.contender.save.list": "保存",
+ "lobeBench.contender.settings.default": "默认参数",
+ "lobeBench.contender.settings.reasoning": "推理",
+ "lobeBench.contender.settings.temperature": "创造力",
+ "lobeBench.contender.settings.topP": "开放性",
+ "lobeBench.contender.subtitle": "和聊天里用的是同一份模型列表和参数。在 设置 → AI 服务商 里可以接入更多。",
+ "lobeBench.contender.temperature": "创造力",
+ "lobeBench.contender.title": "新参赛者",
+ "lobeBench.contender.topP": "开放性",
+ "lobeBench.contenders.builtIn": "你在过往实验里跑过的参赛者。内置基准不保存自定义列表,请在\"新实验\"页添加。",
+ "lobeBench.contenders.col.best": "最佳完整跑",
+ "lobeBench.contenders.col.experiments": "实验数",
+ "lobeBench.contenders.col.model": "模型",
+ "lobeBench.contenders.col.name": "参赛者",
+ "lobeBench.contenders.delete.confirm": "从保存列表移除这个参赛者?历史实验结果保留。",
+ "lobeBench.contenders.edit": "编辑",
+ "lobeBench.contenders.empty": "还没有参赛者。开一场实验,或在这里添加。",
+ "lobeBench.contenders.new": "新建参赛者",
+ "lobeBench.contenders.saved": "参赛者已保存",
+ "lobeBench.contenders.subtitle": "参赛者 = 模型 + 它运行时的参数。跑过的参赛者都留在这里;可以提前加,也可以整理。",
+ "lobeBench.contenders.title": "参赛者",
+ "lobeBench.dashboard.abort": "停止",
+ "lobeBench.dashboard.abort.confirm": "停止正在跑的参赛者?已完成的题保留结果,其余保持未完成。",
+ "lobeBench.dashboard.action.failed": "未能完成 {{models}} 的操作,请刷新并检查这些运行。",
+ "lobeBench.dashboard.action.rerunFailed": "未能为 {{models}} 发起重跑,请刷新并检查这些运行。",
+ "lobeBench.dashboard.action.rerunSuccess": "{{models}}:{{count}} 道题正在重跑。",
+ "lobeBench.dashboard.action.stillRunning": "{{models}} 仍在运行,请等待结束后再试。",
+ "lobeBench.dashboard.action.stopSuccess": "已停止 {{models}}。",
+ "lobeBench.dashboard.awaitingExternal": "{{name}}:{{count}} 次作答正在等待外部评分。",
+ "lobeBench.dashboard.byCategory": "按类别",
+ "lobeBench.dashboard.byCategory.hint": "颜色是通过率。点一格,逐题里只看这个类别。",
+ "lobeBench.dashboard.byLevel": "按难度",
+ "lobeBench.dashboard.byLevel.hint": "各难度等级的通过率。难度来自题目契约(顺序调用数、跨服务、注入的故障、规则数),与模型无关。",
+ "lobeBench.dashboard.caseProgress": "已完成评判 {{evaluated}}/{{total}} 题 · {{errors}} 题异常 · {{pending}} 题待完成",
+ "lobeBench.dashboard.caseUnavailable": "结果不可用",
+ "lobeBench.dashboard.cases.count": "{{count}} 题 · 格子里是通过次数/{{k}},点一行横向对比",
+ "lobeBench.dashboard.cases.empty": "这个筛选下没有题。",
+ "lobeBench.dashboard.cases.unavailable": "当前没有可用的已选题,请返回题库检查该题集。",
+ "lobeBench.dashboard.col.anyK": "{{k}} 次中至少 1 次",
+ "lobeBench.dashboard.col.contender": "参赛者",
+ "lobeBench.dashboard.col.cost": "每题费用 · 用时",
+ "lobeBench.dashboard.col.errors": "{{count}} 次报错",
+ "lobeBench.dashboard.col.passRate": "通过率",
+ "lobeBench.dashboard.col.passRateAllK": "通过率 · {{k}} 次全过",
+ "lobeBench.dashboard.col.passed": "通过",
+ "lobeBench.dashboard.col.passedAllK": "全 {{k}} 次通过",
+ "lobeBench.dashboard.coverageGap": "{{name}}:应有 {{expected}} 条逐题结果,现可用 {{available}} 条,缺少 {{missing}} 条。汇总保留原始成绩,分类明细与 CSV 仅包含现存证据。",
+ "lobeBench.dashboard.errors": "{{count}} 题存在运行异常,成绩尚不完整。重新运行这些题目可补齐评测。",
+ "lobeBench.dashboard.export": "导出 CSV",
+ "lobeBench.dashboard.filter.all": "全部",
+ "lobeBench.dashboard.filter.allFail": "全都没过",
+ "lobeBench.dashboard.filter.category": "类别:{{category}}",
+ "lobeBench.dashboard.filter.clear": "清除",
+ "lobeBench.dashboard.filter.diff": "有分歧的题",
+ "lobeBench.dashboard.filter.errors": "有报错",
+ "lobeBench.dashboard.filter.level": "难度:{{level}}",
+ "lobeBench.dashboard.gradingGap": "{{name}}:{{count}} 次作答尚未完成评分;汇总保留原有成绩。",
+ "lobeBench.dashboard.insight.gap": "和第二名的差距",
+ "lobeBench.dashboard.insight.gapLine": "{{gap}} 题",
+ "lobeBench.dashboard.insight.leader": "第一",
+ "lobeBench.dashboard.insight.leaderLine": "{{passed}}/{{total}} 题 {{k}} 次全过 · 至少过 1 次:{{anyK}}",
+ "lobeBench.dashboard.insight.lowest": "通过率最低的分类",
+ "lobeBench.dashboard.insight.weakest": "共同短板",
+ "lobeBench.dashboard.insight.weakestLine": "平均通过率 {{rate}}",
+ "lobeBench.dashboard.judgeErrors": "{{name}}:{{count}} 次作答没有评出结果。点「重跑」会把这些题重新跑一遍。",
+ "lobeBench.dashboard.loadError": "无法加载实验结果",
+ "lobeBench.dashboard.loading": "正在加载实验结果…",
+ "lobeBench.dashboard.missingCases": "有 {{count}} 道已选题在当前题集中不可用;逐题明细与 CSV 仅包含仍可用的已选题。",
+ "lobeBench.dashboard.missingRuns": "部分实验运行记录不可用,暂时无法比较所有模型的结果。",
+ "lobeBench.dashboard.notFound": "这个实验不存在,或者不是 Lobe Bench 实验。",
+ "lobeBench.dashboard.partialCounts": "下方显示已确认的通过题数。全部题目完成评判后,再显示最终通过率和排名。",
+ "lobeBench.dashboard.progress": "{{done}}/{{total}} 次作答完成。下面是已完成部分的结果,会自动更新。",
+ "lobeBench.dashboard.ranking": "参赛者排行",
+ "lobeBench.dashboard.rerun": "重跑",
+ "lobeBench.dashboard.rerun.confirm_one": "{{count}} 道题会重新跑一遍(每题的全部尝试),用同样的模型和设置,会产生模型调用费用。",
+ "lobeBench.dashboard.rerun.confirm_other": "{{count}} 道题会重新跑一遍(每题的全部尝试),用同样的模型和设置,会产生模型调用费用。",
+ "lobeBench.dashboard.rerun.hint": "把有一次作答没出结果(报错、超时、没评出分)的题,用同样的模型和设置重新跑一遍;有结果的题不动。",
+ "lobeBench.dashboard.rerun.none": "每次作答都有结果,没有需要重跑的题。",
+ "lobeBench.dashboard.setup.col.cases": "题目",
+ "lobeBench.dashboard.setup.col.cost": "费用",
+ "lobeBench.dashboard.setup.col.k": "每题",
+ "lobeBench.dashboard.setup.col.model": "模型",
+ "lobeBench.dashboard.setup.col.settings": "参数",
+ "lobeBench.dashboard.setup.col.steps": "最多步数",
+ "lobeBench.dashboard.setup.hint": "实验启动时已保存所选模型与运行参数;题目与判分规则使用题库当前数据。",
+ "lobeBench.dashboard.spent": "已花费 {{cost}}",
+ "lobeBench.dashboard.statusIncomplete": "未完成",
+ "lobeBench.dashboard.tabs.cases": "逐题",
+ "lobeBench.dashboard.tabs.results": "结果",
+ "lobeBench.dashboard.tabs.setup": "设置",
+ "lobeBench.dataset.custom": "我的数据集",
+ "lobeBench.dataset.deleteInBenchmark": "这个数据集属于某个 Benchmark。请先删除 Benchmark,删除后数据集会保留。",
+ "lobeBench.dataset.noRuns": "这个数据集还没有运行。用它跑个实验吧。",
+ "lobeBench.dataset.notFound": "找不到该题集",
+ "lobeBench.dataset.own.subtitle_one": "{{count}} 道题。题目保持固定,更新题包请导入为新的 Dataset。",
+ "lobeBench.dataset.own.subtitle_other": "{{count}} 道题。题目保持固定,更新题包请导入为新的 Dataset。",
+ "lobeBench.dataset.release": "发布 {{release}}",
+ "lobeBench.dataset.runCount_one": "这个数据集上有 {{count}} 次运行",
+ "lobeBench.dataset.runCount_other": "这个数据集上有 {{count}} 次运行",
+ "lobeBench.environments.col.cases": "题数",
+ "lobeBench.environments.col.name": "环境",
+ "lobeBench.environments.col.setup": "设置",
+ "lobeBench.environments.delete.confirm": "删除这个环境?它的 {{count}} 道题会脱离它,按各自的设置继续运行。",
+ "lobeBench.environments.editor.agentName": "用户所知的 Agent 名字(可选)",
+ "lobeBench.environments.editor.builtIn": "内置环境:只读展示。复制一份即可为你自己的题目修改。",
+ "lobeBench.environments.editor.description": "描述",
+ "lobeBench.environments.editor.duplicate": "复制一份",
+ "lobeBench.environments.editor.edit": "编辑环境",
+ "lobeBench.environments.editor.envPrompt": "额外系统上下文(可选)",
+ "lobeBench.environments.editor.impact": "{{count}} 道题在用,保存后全部跟着变",
+ "lobeBench.environments.editor.memory": "记忆",
+ "lobeBench.environments.editor.memory.effort": "强度",
+ "lobeBench.environments.editor.memory.hint": "开启后每次作答有自己的一份记忆,用下面的种子初始化;模型可以只读,或读写。",
+ "lobeBench.environments.editor.memory.invalid": "种子条目必须是一个 JSON 对象。",
+ "lobeBench.environments.editor.memory.permission": "工具权限",
+ "lobeBench.environments.editor.memory.placeholder": "{ \"persona\": { \"narrative\": \"…\" }, \"preferences\": [ … ], \"contexts\": [ … ], \"seededAt\": \"2026-07-20T09:00:00Z\" }",
+ "lobeBench.environments.editor.memory.seeds": "种子条目(JSON)",
+ "lobeBench.environments.editor.memory.template": "插入示例",
+ "lobeBench.environments.editor.name": "名称",
+ "lobeBench.environments.editor.new": "新建环境",
+ "lobeBench.environments.editor.saved": "环境已保存",
+ "lobeBench.environments.empty": "还没有环境。",
+ "lobeBench.environments.new": "新建环境",
+ "lobeBench.environments.setup.clock": "时钟 {{date}}",
+ "lobeBench.environments.setup.memory": "记忆 {{permission}}",
+ "lobeBench.environments.setup.mock": "{{count}} 个 mock",
+ "lobeBench.environments.setup.none": "产品默认",
+ "lobeBench.environments.setup.tools": "{{count}} 个工具",
+ "lobeBench.environments.subtitle": "题目运行时的人设、工具、记忆、时钟和 mock 连接器。多道题共用一个环境,改一处全部跟着变。",
+ "lobeBench.environments.title": "环境",
+ "lobeBench.experiment.delete": "删除实验",
+ "lobeBench.experiment.delete.active": "请先停止实验再删除",
+ "lobeBench.experiment.delete.confirm": "确定删除“{{name}}”?它的运行、逐题结果和 Judge 判定会一并删除,排行榜不再计入。此操作不可撤销。",
+ "lobeBench.experiment.delete.done": "实验已删除",
+ "lobeBench.experiment.delete.failed": "删除实验失败",
+ "lobeBench.experiment.edit.failed": "实验更新失败",
+ "lobeBench.experiment.edit.saved": "实验已更新",
+ "lobeBench.experiment.edit.title": "编辑实验",
+ "lobeBench.experiment.line_one": "{{count}} 个参赛者 · {{dataset}} · 每题 {{k}} 次",
+ "lobeBench.experiment.line_other": "{{count}} 个参赛者 · {{dataset}} · 每题 {{k}} 次",
+ "lobeBench.experiment.more": "更多操作",
+ "lobeBench.experiment.noRuns": "这个实验还没有运行。",
+ "lobeBench.experiment.outdated": "旧版题目:不计入任何排行榜",
+ "lobeBench.experiment.runCount_one": "本实验共 {{count}} 次运行",
+ "lobeBench.experiment.runCount_other": "本实验共 {{count}} 次运行",
+ "lobeBench.experiment.unnamed": "未命名实验",
+ "lobeBench.library.badge.broken": "疑似坏题",
+ "lobeBench.library.badge.easy": "区分度低",
+ "lobeBench.library.cases": "{{count}} 题",
+ "lobeBench.library.col.case": "题目",
+ "lobeBench.library.col.category": "类别",
+ "lobeBench.library.col.level": "难度",
+ "lobeBench.library.col.tools": "工具",
+ "lobeBench.library.empty": "当前没有共享题库,你可以直接导入 Dataset ZIP 题包。",
+ "lobeBench.library.filter.category": "分类",
+ "lobeBench.library.filter.count": "{{total}} 题中的 {{shown}} 题",
+ "lobeBench.library.filter.level": "难度",
+ "lobeBench.library.filter.search": "搜索题目",
+ "lobeBench.library.levels": "{{l1}} L1 · {{l2}} L2 · {{l3}} L3 · {{l4}} L4",
+ "lobeBench.library.subtitle": "这里展示此前安装的共享题目。你可以选题创建 Dataset,也可以直接导入 Dataset ZIP 题包。",
+ "lobeBench.library.title": "题目库",
+ "lobeBench.new.advanced": "高级",
+ "lobeBench.new.cancel": "取消",
+ "lobeBench.new.cases.selected": "{{total}} 题中的 {{selected}} 题",
+ "lobeBench.new.confirm.billing": "模型和评审的 token 由你的服务商计费。",
+ "lobeBench.new.confirm.cost": "预估费用 {{cost}},按你最近跑同样模型的均价估算。",
+ "lobeBench.new.confirm.costUnknown": "这些模型还没有费用记录;看板会在跑的过程中显示实际费用。",
+ "lobeBench.new.confirm.judge": "评审模型:{{model}}",
+ "lobeBench.new.confirm.judgeDefault": "评审模型:系统默认(可在设置里指定)",
+ "lobeBench.new.confirm.judgeOf": "{{benchmark}} 由 {{model}} 判分",
+ "lobeBench.new.confirm.line": "{{cases}} 题 × {{contenders}} 个参赛者 × 每题 {{k}} 次 = {{attempts}} 次作答。",
+ "lobeBench.new.confirm.ok": "开始",
+ "lobeBench.new.confirm.standardOf": "{{benchmark}}:由 {{model}} 判分,每题跑 {{k}} 次,最多 {{maxSteps}} 步,每次 {{timeout}} 分钟",
+ "lobeBench.new.confirm.title": "开始这次实验?",
+ "lobeBench.new.contenders.add": "添加参赛者",
+ "lobeBench.new.contenders.empty": "至少添加一个参赛者。",
+ "lobeBench.new.contenders.hint": "同一个模型换一组参数就是另一个参赛者,可以并排比。",
+ "lobeBench.new.contenders.remove": "移除参赛模型",
+ "lobeBench.new.contenders.saved": "保存过的参赛者,点一下加入",
+ "lobeBench.new.dataset.cases": "{{count}} 题",
+ "lobeBench.new.draft.datasetUnavailable": "此题集已不可用,请重新选择题集。",
+ "lobeBench.new.draft.discard": "丢弃草稿",
+ "lobeBench.new.draft.modelsUnavailable": "所选模型或评分模型已不可用,请移除或重新选择可用模型。",
+ "lobeBench.new.draft.restored": "已恢复上次未完成的实验。",
+ "lobeBench.new.draft.storageError": "浏览器未能保存草稿,请保留此页直至实验启动。",
+ "lobeBench.new.error": "实验没能开始",
+ "lobeBench.new.estimate": "共 {{attempts}} 次作答。每次使用独立的记忆和模拟环境。运行中有未完成或报错的作答时,不参与排名。",
+ "lobeBench.new.group.benchmarks": "基准",
+ "lobeBench.new.group.datasets": "我的 dataset",
+ "lobeBench.new.judge": "评审模型",
+ "lobeBench.new.judge.hint": "给本次实验的每次作答打分。留空则用基准默认。",
+ "lobeBench.new.judge.missing": "{{name}} 没有设置评审模型,不能运行。请重新导入为新的 Benchmark 并选择评审模型。",
+ "lobeBench.new.k.hint": "每题至少跑 {{k}} 次的运行才进排行榜。",
+ "lobeBench.new.k.once": "1 次",
+ "lobeBench.new.k.ranked": "{{k}} 次(上榜)",
+ "lobeBench.new.k.times": "{{k}} 次",
+ "lobeBench.new.launch.abandon": "停止恢复",
+ "lobeBench.new.launch.abandon.confirm": "已经启动的运行会在该实验中继续。表单将解锁;再次开始会创建新实验,可能产生额外费用。",
+ "lobeBench.new.launch.abandon.title": "停止恢复这次启动?",
+ "lobeBench.new.launch.back": "返回实验列表",
+ "lobeBench.new.launch.busy": "此实验正在其他页面启动,请稍后重新检查。",
+ "lobeBench.new.launch.close": "关闭",
+ "lobeBench.new.launch.continue": "继续启动",
+ "lobeBench.new.launch.currentRun": "第 {{index}} / {{total}} 个运行 · {{name}}",
+ "lobeBench.new.launch.elapsed": "距首次启动:{{elapsed}}",
+ "lobeBench.new.launch.failed": "在“{{name}}”处中断:{{error}}。继续以检查进度并完成启动。",
+ "lobeBench.new.launch.interrupted": "启动尚未完成",
+ "lobeBench.new.launch.legacy": "发现旧版本的启动记录。",
+ "lobeBench.new.launch.legacy.hint": "无法在此恢复旧记录。请打开实验检查运行状态,或停止恢复。",
+ "lobeBench.new.launch.metadataFailed": "保存实验配置失败:{{error}}。继续以重试保存。",
+ "lobeBench.new.launch.occupied": "另一个标签页已为这个基准发起启动,上方显示了它的启动记录。",
+ "lobeBench.new.launch.open": "打开实验",
+ "lobeBench.new.launch.pending": "有一项实验尚未完成启动。恢复启动期间,设置已锁定。",
+ "lobeBench.new.launch.perBenchmark": "每个基准分别保存启动记录。要恢复未完成的启动,请回到对应基准的表单。",
+ "lobeBench.new.launch.progress": "{{total}} 个参赛者中,已有 {{started}} 个确认启动。",
+ "lobeBench.new.launch.recheck": "重新检查",
+ "lobeBench.new.launch.recovery": "启动尚未确认。可检查状态并从保存的位置继续,已启动的运行不会重复提交。",
+ "lobeBench.new.launch.stage.check": "正在检查已保存的运行",
+ "lobeBench.new.launch.stage.complete": "所有运行已提交,正在打开实验…",
+ "lobeBench.new.launch.stage.experiment": "正在创建实验",
+ "lobeBench.new.launch.stage.metadata": "正在保存实验配置",
+ "lobeBench.new.launch.stage.run": "正在准备运行并检查连接",
+ "lobeBench.new.launch.stage.start": "正在检查连接并提交运行",
+ "lobeBench.new.launch.steps": "已完成 {{completed}} / {{total}} 个启动步骤",
+ "lobeBench.new.launch.storageError": "浏览器无法保存启动记录,未开始新的启动请求。",
+ "lobeBench.new.launch.title": "正在启动实验",
+ "lobeBench.new.launch.unconfirmed": "{{count}} 个参赛者尚未得到服务器确认:{{names}}。请稍后重新检查,或打开实验查看。",
+ "lobeBench.new.launch.unknown": "上次启动尚未完成,继续以检查已保存的进度。",
+ "lobeBench.new.launch.waiting": "启动期间可以浏览其他页面,再回到此实验查看进度。启动流程在当前浏览器标签页内继续。",
+ "lobeBench.new.maxConcurrency": "同时运行的题数",
+ "lobeBench.new.maxConcurrency.hint_one": "每个参赛模型同时跑几道题,每题各作答 {{count}} 次。遇到供应商限流时调低。留空则所有题一起开始。",
+ "lobeBench.new.maxConcurrency.hint_other": "每个参赛模型同时跑几道题,每题各作答 {{count}} 次。遇到供应商限流时调低。留空则所有题一起开始。",
+ "lobeBench.new.maxConcurrency.placeholder": "不限",
+ "lobeBench.new.maxSteps": "每次作答最多步数",
+ "lobeBench.new.name": "实验名称",
+ "lobeBench.new.name.placeholder": "可选,不填就按参赛者自动起名",
+ "lobeBench.new.providerCheckFailed": "无法检查模型服务商,请重试。",
+ "lobeBench.new.providerKeyMissing": "服务器上没有 {{provider}} 的 API key。请在\"设置 → AI 服务商\"里添加,或换一个服务商的模型。",
+ "lobeBench.new.question": "想回答的问题",
+ "lobeBench.new.question.placeholder": "可选,例如“深度思考对金融类题目有帮助吗?”",
+ "lobeBench.new.standard.missing": "{{name}} 没有设置评审模型或运行规则,不能运行。",
+ "lobeBench.new.standard.mixed": "所选 Benchmark 的运行规则不同(每题次数、步数或超时),请分开建实验。",
+ "lobeBench.new.start": "开始实验",
+ "lobeBench.new.step.contenders": "2 · 参赛者 · 模型 + 参数",
+ "lobeBench.new.step.dataset": "1 · 基准 · 选一个或多个",
+ "lobeBench.new.step.k": "3 · 每题跑几次",
+ "lobeBench.new.subtitle": "两步:选 Benchmark、选参赛者。评审模型、每题次数、步数和超时都由各 Benchmark 自己决定。",
+ "lobeBench.new.timeout": "每次作答超时(分钟)",
+ "lobeBench.new.title": "新建实验",
+ "lobeBench.overview.attention.errors": "{{count}} 道题执行出错",
+ "lobeBench.overview.attention.external": "{{count}} 道题等待外部评分",
+ "lobeBench.overview.attention.judgeErrors": "{{count}} 道题评分出错",
+ "lobeBench.overview.attention.ungraded": "{{count}} 道题评分未完成",
+ "lobeBench.overview.card.contenders": "参赛者",
+ "lobeBench.overview.card.noDataset": "还没有数据集",
+ "lobeBench.overview.card.noDatasetHint": "数据集在创建基准时选定",
+ "lobeBench.overview.card.noRun": "还没有完整运行",
+ "lobeBench.overview.card.noRunHint": "跑完一个数据集的全部题目即可上榜",
+ "lobeBench.overview.card.on": "数据集 {{dataset}}",
+ "lobeBench.overview.card.openBenchmark": "打开基准",
+ "lobeBench.overview.card.runs": "运行",
+ "lobeBench.overview.card.top": "第一名 · {{name}}",
+ "lobeBench.overview.createBenchmark": "新建基准",
+ "lobeBench.overview.experiments.empty": "还没有实验。新建一个,在数据集上比较模型。",
+ "lobeBench.overview.newExperiment": "新建实验",
+ "lobeBench.overview.notInstalled": "导入一个 Dataset ZIP 题包即可开始。你可以使用他人分享的题包,也可以从示例创建自己的题包。",
+ "lobeBench.overview.passedOf": "{{passed}}/{{total}}",
+ "lobeBench.overview.running": "进行中",
+ "lobeBench.overview.runningLine": "{{done}}/{{total}} 题 · 已花费 {{cost}}",
+ "lobeBench.picks.clear": "清空",
+ "lobeBench.picks.create": "新建 dataset",
+ "lobeBench.picks.created_one": "已建好 {{dataset}},共 {{count}} 道题",
+ "lobeBench.picks.created_other": "已建好 {{dataset}},共 {{count}} 道题",
+ "lobeBench.picks.defaultName": "我的 dataset",
+ "lobeBench.picks.delete": "删除 dataset",
+ "lobeBench.picks.delete.confirm": "删除“{{name}}”?它上面的运行和结果会一起删除,并从所有排行榜中移除。此操作无法撤销。",
+ "lobeBench.picks.failed": "Dataset 没有保存成功,请重试。",
+ "lobeBench.picks.fixed": "数据集建好后题目就固定了,它的运行结果始终对应同一组题。想用别的题,就再建一个数据集。",
+ "lobeBench.picks.hint.library": "勾选题目,建成你自己的数据集。",
+ "lobeBench.picks.name": "Dataset 名称",
+ "lobeBench.picks.name.placeholder": "例如:金融 L2",
+ "lobeBench.picks.rename": "重命名",
+ "lobeBench.picks.run": "跑实验",
+ "lobeBench.picks.selected": "已选 {{count}} 道",
+ "lobeBench.picks.title_one": "用 {{count}} 道题建数据集",
+ "lobeBench.picks.title_other": "用 {{count}} 道题建数据集",
+ "lobeBench.settings.benchmark": "基准",
+ "lobeBench.settings.defaults": "新实验默认值",
+ "lobeBench.settings.defaults.hint": "新建实验表单的初始值,每次实验仍可改。",
+ "lobeBench.settings.defaults.k": "每题次数",
+ "lobeBench.settings.defaults.maxSteps": "每次作答最大步数",
+ "lobeBench.settings.defaults.timeout": "每次作答超时(分钟)",
+ "lobeBench.settings.grading.hint": "Lobe Bench 自带。每个实验开始时都可以另选评分模型。",
+ "lobeBench.settings.grading.line": "每次作答由 {{model}} 评分。",
+ "lobeBench.settings.grading.title": "评分",
+ "lobeBench.settings.grading.unset": "每次作答由系统默认模型评分。",
+ "lobeBench.settings.judge": "评审模型",
+ "lobeBench.settings.judge.clear": "用系统默认",
+ "lobeBench.settings.judge.hint": "给每次作答打分。选一个不参赛的模型;题集或题目仍可指定自己的评审。",
+ "lobeBench.settings.judge.placeholder": "系统默认(助手的话题模型)",
+ "lobeBench.settings.mine.hint": "只对你生效;每个实验仍可单独修改。",
+ "lobeBench.settings.mine.reset": "恢复默认",
+ "lobeBench.settings.mine.reset.done": "已恢复为 Lobe Bench 默认值",
+ "lobeBench.settings.mine.saved": "已保存",
+ "lobeBench.settings.mine.title": "你的新实验默认值",
+ "lobeBench.settings.notInstalled": "这个账号里还没有 Lobe Bench 基准。",
+ "lobeBench.settings.save": "保存",
+ "lobeBench.settings.saved": "已保存",
+ "lobeBench.settings.subtitle": "在这里管理 Mock 工具连接。评审模型和运行规则在创建 Benchmark 时就已固定。",
+ "lobeBench.settings.title": "设置",
+ "lobeBench.sidebar.benchmarks": "基准",
+ "lobeBench.sidebar.benchmarks.empty": "还没有 Benchmark,导入 Dataset 或创建一个即可。",
+ "lobeBench.sidebar.contenders": "参赛者",
+ "lobeBench.sidebar.datasets": "数据集",
+ "lobeBench.sidebar.datasets.empty": "还没有 Dataset,导入 ZIP 题包即可开始。",
+ "lobeBench.sidebar.draft": "新实验(未开始)",
+ "lobeBench.sidebar.empty": "还没有实验",
+ "lobeBench.sidebar.experiments": "实验",
+ "lobeBench.sidebar.library": "题目库",
+ "lobeBench.sidebar.newBenchmark": "新建基准",
+ "lobeBench.sidebar.newExperiment": "新建实验",
+ "lobeBench.sidebar.overview": "总览",
+ "lobeBench.sidebar.settings": "设置",
+ "lobeBench.status.aborted": "已中止",
+ "lobeBench.status.done": "已完成",
+ "lobeBench.status.failed": "失败",
+ "lobeBench.status.pending": "待开始",
+ "lobeBench.status.running": "进行中 {{done}}/{{total}}",
+ "lobeBench.subtitle": "LobeHub 的标准题。用实验比较模型、参数和 harness。",
+ "lobeBench.switch.agent": "评测实验室",
+ "lobeBench.switch.bench": "Lobe Bench",
+ "lobeBench.title": "Lobe Bench",
+ "lobeBench.topicCase.agent": "Agent",
+ "lobeBench.topicCase.answer": "当时的回答",
+ "lobeBench.topicCase.context": "提问前回放 {{count}} 条消息",
+ "lobeBench.topicCase.input": "被测提问",
+ "lobeBench.topicCase.intro": "粘贴对话 id。最后一次提问作为题目,之前的消息作为上下文回放,回答它的 Agent(人设、工具)随题目一并记录。",
+ "lobeBench.topicCase.load": "载入",
+ "lobeBench.topicCase.loadError": "无法载入该对话",
+ "lobeBench.topicCase.noAgent": "未捕获到 Agent 配置,题目将用参赛者的默认配置作答。",
+ "lobeBench.topicCase.rules": "规则",
+ "lobeBench.topicCase.rules.hint": "每行一条,以 Must: 或 Must not: 开头。由对话草拟,保存前请检查。",
+ "lobeBench.topicCase.rulesRequired": "至少写一条规则",
+ "lobeBench.topicCase.save": "保存到我的题目",
+ "lobeBench.topicCase.saveError": "保存失败",
+ "lobeBench.topicCase.saved": "已保存到我的题目",
+ "lobeBench.topicCase.title": "从对话生成题目",
+ "lobeBench.topicCase.tools": "工具",
+ "lobeBench.topicCase.topicId": "对话 id",
+ "lobeBench.topicCase.topicId.placeholder": "tpc_…(聊天地址里的 topic)",
+ "lobeBench.unit.min": "{{value}} 分",
"overview.createBenchmark": "创建基准",
"overview.createExperiment": "创建实验",
"overview.importDataset": "导入数据集",
@@ -387,8 +962,11 @@
"run.metrics.duration": "耗时",
"run.metrics.errorCases": "出错",
"run.metrics.evaluated": "{{count}} 个已评测",
+ "run.metrics.passAllK": "{{k}} 次全部通过(pass^{{k}})",
"run.metrics.passRate": "通过率",
+ "run.metrics.passRate.anyK": "通过率 · {{k}} 次中至少通过 1 次(pass@{{k}})",
"run.metrics.passRate.short": "通过率",
+ "run.metrics.perAttempt": "单次作答通过率(pass@1)",
"run.metrics.perCase": "/用例",
"run.metrics.tokens": "Tokens",
"run.metrics.totalDuration": "累计",
diff --git a/packages/locales/src/default/eval.ts b/packages/locales/src/default/eval.ts
index 85bee5c3962..b72901cc9f3 100644
--- a/packages/locales/src/default/eval.ts
+++ b/packages/locales/src/default/eval.ts
@@ -1,5 +1,7 @@
export default {
'benchmark.actions.delete': 'Delete Benchmark',
+ 'benchmark.actions.delete.builtIn': 'Built-in benchmark · cannot be deleted',
+ 'benchmark.delete.error': 'Failed to delete benchmark',
'benchmark.actions.delete.confirm':
'Are you sure you want to delete this benchmark? Related datasets and evaluation records will also be deleted.',
'benchmark.actions.edit': 'Edit Benchmark',
@@ -62,6 +64,7 @@ export default {
'benchmark.detail.stats.perRun': '/ Run',
'benchmark.detail.stats.p99Duration': 'P99: {{duration}}',
'benchmark.detail.stats.topAgents': 'Top Agents',
+ 'benchmark.detail.stats.topModels': 'Top Models',
'benchmark.detail.stats.totalCases': 'Total Cases',
'benchmark.detail.stats.waiting': 'Waiting...',
'benchmark.detail.tabs.data': 'Data',
@@ -180,9 +183,35 @@ export default {
'dataset.import.step.upload': 'Upload File',
'dataset.import.success': 'Successfully imported {{count}} test cases',
'dataset.import.title': 'Import Dataset',
- 'dataset.import.upload.hint': 'Supports CSV, XLSX, JSON, JSONL',
+ 'dataset.import.upload.hint':
+ 'Supports CSV, XLSX, JSON, JSONL and dataset ZIP packages (up to 10 MiB)',
'dataset.import.upload.text': 'Click or drag file here to upload',
'dataset.import.uploading': 'Uploading...',
+ 'dataset.import.package.asNew': 'Import as new dataset',
+ 'dataset.import.package.benchmark': 'Benchmark',
+ 'dataset.import.package.benchmarkName': 'New benchmark name',
+ 'dataset.import.package.judge': 'Judge model',
+ 'dataset.import.package.judge.hint':
+ 'Every run on this benchmark is graded by this model, so its scores stay comparable. It cannot be changed later.',
+ 'dataset.import.package.judge.placeholder': 'Choose the judge model',
+ 'dataset.import.package.cases': '{{count}} cases',
+ 'dataset.import.package.environments': '{{count}} environments',
+ 'dataset.import.package.hint': 'Dataset ZIP package · up to 10 MiB',
+ 'dataset.import.package.history':
+ 'The imported cases are fixed. Import updated packages as a new dataset to keep past results comparable.',
+ 'dataset.import.package.instructions':
+ 'Upload your dataset ZIP. The ZIP must contain dataset.json at its root.',
+ 'dataset.import.package.mockServices':
+ 'Mock services used: {{services}}. Each service uses its bound connection.',
+ 'dataset.import.package.name': 'Dataset name',
+ 'dataset.import.package.newBenchmark': 'Create a new benchmark',
+ 'dataset.import.package.preserved':
+ 'Case content, grading rules and environment settings are imported together. This creates a private dataset in your account.',
+ 'dataset.import.package.preview': 'Confirm dataset package',
+ 'dataset.import.package.refreshError':
+ 'The dataset was imported, but the list could not refresh. Reload the page to see it; you do not need to import again.',
+ 'dataset.import.package.tooLarge': 'The ZIP is too large. Choose a package smaller than 10 MiB.',
+ 'dataset.import.package.zipRequired': 'Choose a dataset ZIP package.',
'dataset.detail.backToEval': 'Back to Eval',
'capture.actual': 'What it answered',
'capture.captured': 'Captured content',
@@ -285,6 +314,9 @@ export default {
'evalMode.llm-rubric': 'LLM Judge',
'evalMode.llm-rubric.desc':
'Use LLM to evaluate output quality based on custom criteria (0.0 to 1.0)',
+ 'evalMode.rule-checklist': 'Rule Checklist',
+ 'evalMode.rule-checklist.desc':
+ 'The LLM judge decides each Must / Must not rule on its own; the case passes only when every rule is satisfied',
'evalMode.answer-relevance': 'LLM Relevance',
'evalMode.answer-relevance.desc': 'Use LLM to evaluate answer relevance (yes or no)',
'evalMode.criteria.label': 'Eval Prompt',
@@ -420,8 +452,11 @@ export default {
'run.metrics.duration': 'Duration',
'run.metrics.errorCases': 'Error',
'run.metrics.evaluated': '{{count}} evaluated',
+ 'run.metrics.passAllK': 'All {{k}} attempts passed (pass^{{k}})',
'run.metrics.passRate': 'Pass Rate',
+ 'run.metrics.passRate.anyK': 'Pass Rate · passed at least 1 of {{k}} attempts (pass@{{k}})',
'run.metrics.passRate.short': 'pass rate',
+ 'run.metrics.perAttempt': 'Per attempt (pass@1)',
'run.metrics.perCase': '/ case',
'run.metrics.tokens': 'Tokens',
'run.metrics.totalDuration': 'Cumulative',
@@ -521,4 +556,669 @@ export default {
'testCaseDetail.role.tool': 'Tool',
'testCaseDetail.role.user': 'User',
'testCaseDetail.title': 'Test case',
+ 'lobeBench.switch.agent': 'Evaluation Lab',
+ 'lobeBench.switch.bench': 'Lobe Bench',
+ 'lobeBench.title': 'Lobe Bench',
+ 'lobeBench.subtitle':
+ "LobeHub's standard cases. Run experiments to compare models, settings and harnesses.",
+ 'lobeBench.sidebar.overview': 'Dashboard',
+ 'lobeBench.sidebar.experiments': 'Experiments',
+ 'lobeBench.sidebar.newBenchmark': 'New benchmark',
+ 'lobeBench.sidebar.newExperiment': 'New experiment',
+ 'lobeBench.sidebar.draft': 'New experiment (not started)',
+ 'lobeBench.sidebar.library': 'Case library',
+ 'lobeBench.sidebar.empty': 'No experiments yet',
+ 'lobeBench.overview.createBenchmark': 'New benchmark',
+ 'lobeBench.overview.experiments.empty':
+ 'No experiments yet. Start one to compare models on a dataset.',
+ 'lobeBench.overview.card.top': 'Leader · {{name}}',
+ 'lobeBench.overview.card.on': 'on {{dataset}}',
+ 'lobeBench.overview.card.noRun': 'No full run yet',
+ 'lobeBench.overview.card.noRunHint': 'Run every case of a dataset to rank here',
+ 'lobeBench.overview.card.noDataset': 'No datasets yet',
+ 'lobeBench.overview.card.noDatasetHint': 'Datasets are chosen when a benchmark is created',
+ 'lobeBench.overview.card.openBenchmark': 'Open benchmark',
+ 'lobeBench.overview.card.runs': 'Runs',
+ 'lobeBench.overview.card.contenders': 'Contenders',
+ 'lobeBench.overview.newExperiment': 'New experiment',
+ 'lobeBench.overview.notInstalled':
+ 'Start by importing a dataset ZIP. You can use a shared package or create your own from the example.',
+ 'lobeBench.overview.running': 'Running',
+ 'lobeBench.overview.runningLine': '{{done}}/{{total}} cases · {{cost}} so far',
+ 'lobeBench.overview.passedOf': '{{passed}}/{{total}}',
+ 'lobeBench.overview.attention.errors': '{{count}} cases with execution errors',
+ 'lobeBench.experiment.line_one': '{{count}} contender · {{dataset}} · {{k}}× per case',
+ 'lobeBench.experiment.line_other': '{{count}} contenders · {{dataset}} · {{k}}× per case',
+ 'lobeBench.experiment.unnamed': 'Untitled experiment',
+ 'lobeBench.experiment.runCount_one': '{{count}} run in this experiment',
+ 'lobeBench.experiment.runCount_other': '{{count}} runs in this experiment',
+ 'lobeBench.experiment.noRuns': 'No run in this experiment yet.',
+ 'lobeBench.experiment.more': 'More actions',
+ 'lobeBench.experiment.edit.title': 'Edit experiment',
+ 'lobeBench.experiment.edit.saved': 'Experiment updated',
+ 'lobeBench.experiment.edit.failed': 'Could not update the experiment',
+ 'lobeBench.experiment.delete': 'Delete experiment',
+ 'lobeBench.experiment.delete.confirm':
+ 'Delete "{{name}}"? Its runs, per-case results and Judge verdicts are removed with it, and the leaderboard no longer counts them. This cannot be undone.',
+ 'lobeBench.experiment.delete.active': 'Stop the experiment before deleting it',
+ 'lobeBench.experiment.delete.done': 'Experiment deleted',
+ 'lobeBench.experiment.delete.failed': 'Could not delete the experiment',
+ 'lobeBench.status.done': 'Done',
+ 'lobeBench.status.running': 'Running {{done}}/{{total}}',
+ 'lobeBench.status.pending': 'Pending',
+ 'lobeBench.status.failed': 'Failed',
+ 'lobeBench.status.aborted': 'Aborted',
+ 'lobeBench.new.title': 'New experiment',
+ 'lobeBench.new.subtitle':
+ 'Two steps: benchmarks and contenders. Each benchmark sets its own judge, attempts per case, step limit and timeout.',
+ 'lobeBench.new.name': 'Experiment name',
+ 'lobeBench.new.name.placeholder': 'Optional — named after the contenders if empty',
+ 'lobeBench.new.question': 'Question you want answered',
+ 'lobeBench.new.question.placeholder':
+ 'Optional, e.g. "Does deep thinking help on finance cases?"',
+ 'lobeBench.new.step.dataset': '1 · Benchmarks · choose one or more',
+ 'lobeBench.new.step.contenders': '2 · Contenders · model + settings',
+ 'lobeBench.new.step.k': '3 · Attempts per case',
+ 'lobeBench.new.dataset.cases': '{{count}} cases',
+ 'lobeBench.new.group.benchmarks': 'Benchmarks',
+ 'lobeBench.new.group.datasets': 'My datasets',
+ 'lobeBench.new.cases.selected': '{{selected}} of {{total}} cases',
+ 'lobeBench.new.k.once': 'once',
+ 'lobeBench.new.k.times': '{{k}}×',
+ 'lobeBench.new.contenders.add': 'Add contender',
+ 'lobeBench.new.contenders.remove': 'Remove contender',
+ 'lobeBench.new.providerKeyMissing':
+ 'No API key for {{provider}} on this server. Add one under Settings → AI providers, or pick a model from another provider.',
+ 'lobeBench.new.providerCheckFailed': 'Could not check the model providers. Try again.',
+ 'lobeBench.new.contenders.hint':
+ 'The same model with other settings is another contender; they compare side by side.',
+ 'lobeBench.new.contenders.empty': 'Add at least one contender.',
+ 'lobeBench.new.advanced': 'Advanced',
+ 'lobeBench.new.maxConcurrency': 'Cases at once',
+ 'lobeBench.new.maxConcurrency.hint_one':
+ 'How many cases each contender runs at the same time, each with its single attempt. Lower it if a provider rate-limits you. Leave empty to start every case together.',
+ 'lobeBench.new.maxConcurrency.hint_other':
+ 'How many cases each contender runs at the same time, each with its {{count}} attempts. Lower it if a provider rate-limits you. Leave empty to start every case together.',
+ 'lobeBench.new.maxConcurrency.placeholder': 'No limit',
+ 'lobeBench.new.maxSteps': 'Max steps per attempt',
+ 'lobeBench.new.timeout': 'Timeout per attempt (minutes)',
+ 'lobeBench.new.draft.restored': 'Your unfinished experiment has been restored.',
+ 'lobeBench.new.draft.discard': 'Discard draft',
+ 'lobeBench.new.draft.storageError':
+ 'This browser could not save your draft. Keep this page open until you start the experiment.',
+ 'lobeBench.new.draft.datasetUnavailable':
+ 'This case set is no longer available. Choose another case set.',
+ 'lobeBench.new.draft.modelsUnavailable':
+ 'A selected model or judge is no longer available. Remove it or select an available model.',
+ 'lobeBench.new.estimate':
+ '{{attempts}} attempts. Each attempt uses separate memory and a mock environment. Runs with incomplete or errored attempts are not ranked.',
+ 'lobeBench.new.start': 'Start experiment',
+ 'lobeBench.new.cancel': 'Cancel',
+ 'lobeBench.new.error': 'Could not start the experiment',
+ 'lobeBench.contender.title': 'New contender',
+ 'lobeBench.contender.subtitle':
+ 'The same model list and settings as in chat. Add providers under Settings → AI providers.',
+ 'lobeBench.contender.model': 'Model',
+ 'lobeBench.contender.model.placeholder': 'Pick a model that supports tool calls',
+ 'lobeBench.contender.name': 'Name',
+ 'lobeBench.contender.name.placeholder': 'Optional — model name plus settings if empty',
+ 'lobeBench.contender.temperature': 'Temperature',
+ 'lobeBench.contender.topP': 'Top P',
+ 'lobeBench.contender.modelSettings': 'Model settings',
+ 'lobeBench.contender.modelDefault': 'Model default',
+ 'lobeBench.contender.save': 'Add to experiment',
+ 'lobeBench.contender.settings.default': 'Default settings',
+ 'lobeBench.contender.settings.temperature': 'temperature',
+ 'lobeBench.contender.settings.topP': 'top_p',
+ 'lobeBench.contender.settings.reasoning': 'reasoning',
+ 'lobeBench.dashboard.tabs.results': 'Results',
+ 'lobeBench.dashboard.tabs.cases': 'By case',
+ 'lobeBench.dashboard.tabs.setup': 'Setup',
+ 'lobeBench.dashboard.progress':
+ '{{done}}/{{total}} attempts done. Results below are partial and refresh automatically.',
+ 'lobeBench.dashboard.filter.clear': 'Clear filters',
+ 'lobeBench.dashboard.loading': 'Loading experiment results…',
+ 'lobeBench.dashboard.loadError': 'Could not load experiment results',
+ 'lobeBench.dashboard.missingRuns':
+ 'Some experiment runs are unavailable. Results cannot be compared until all contender runs are available.',
+ 'lobeBench.dashboard.missingCases':
+ '{{count}} selected cases are no longer available in this case set. The breakdown and CSV include only available selected cases.',
+ 'lobeBench.dashboard.coverageGap':
+ '{{name}}: {{available}} of {{expected}} case results are available; {{missing}} are missing. Saved summary scores are unchanged. Breakdowns and CSV include only available evidence.',
+ 'lobeBench.dashboard.statusIncomplete': 'Incomplete',
+ 'lobeBench.dashboard.partialCounts':
+ 'Counts show confirmed passes so far. Final pass rates and ranking are available once every case is fully evaluated.',
+ 'lobeBench.dashboard.caseProgress':
+ '{{evaluated}}/{{total}} cases evaluated · {{errors}} with errors · {{pending}} awaiting completion',
+ 'lobeBench.dashboard.col.passedAllK': 'All {{k}} passed',
+ 'lobeBench.dashboard.cases.unavailable':
+ 'No selected cases are available. Return to the case library to inspect this case set.',
+ 'lobeBench.dashboard.caseUnavailable': 'Result unavailable',
+ 'lobeBench.dashboard.errors':
+ '{{count}} cases have execution errors. Their results are incomplete; rerun these cases to finish the evaluation.',
+ 'lobeBench.dashboard.rerun': 'Rerun',
+ 'lobeBench.dashboard.rerun.hint':
+ 'Runs again every case with an attempt that has no verdict (error, timeout, or ungraded), with the same models and settings. Cases with verdicts stay.',
+ 'lobeBench.dashboard.rerun.none': 'Every attempt has a verdict; nothing to rerun.',
+ 'lobeBench.dashboard.rerun.confirm_one':
+ '{{count}} case will run again (all of its attempts) with the same models and settings. This costs model calls.',
+ 'lobeBench.dashboard.rerun.confirm_other':
+ '{{count}} cases will run again (all of their attempts) with the same models and settings. This costs model calls.',
+ 'lobeBench.dashboard.action.rerunSuccess': '{{models}}: {{count}} cases are running again.',
+ 'lobeBench.dashboard.action.rerunFailed':
+ 'Could not start the rerun for {{models}}. Reload and inspect the runs.',
+ 'lobeBench.dashboard.insight.leader': 'Leader',
+ 'lobeBench.dashboard.insight.leaderLine':
+ '{{passed}}/{{total}} passed all {{k}} attempts · any of {{k}}: {{anyK}}',
+ 'lobeBench.dashboard.insight.gap': 'Gap to second',
+ 'lobeBench.dashboard.insight.gapLine': '{{gap}} cases',
+ 'lobeBench.dashboard.insight.weakest': 'Shared weak spot',
+ 'lobeBench.dashboard.insight.weakestLine': '{{rate}} average pass rate',
+ 'lobeBench.dashboard.ranking': 'Contender ranking',
+ 'lobeBench.dashboard.col.contender': 'Contender',
+ 'lobeBench.dashboard.col.passRate': 'Pass rate',
+ 'lobeBench.dashboard.col.passRateAllK': 'Pass rate · all {{k}} attempts',
+ 'lobeBench.dashboard.col.passed': 'Passed',
+ 'lobeBench.dashboard.col.anyK': 'Any of {{k}}',
+ 'lobeBench.dashboard.col.cost': 'Cost per case · time',
+ 'lobeBench.dashboard.col.errors': '{{count}} errors',
+ 'lobeBench.dashboard.byCategory': 'By category',
+ 'lobeBench.dashboard.byCategory.hint':
+ 'Colour is the pass rate. Click a cell to see only that category by case.',
+ 'lobeBench.dashboard.filter.diff': 'Cases with disagreement',
+ 'lobeBench.dashboard.filter.all': 'All',
+ 'lobeBench.dashboard.filter.allFail': 'Everyone failed',
+ 'lobeBench.dashboard.filter.errors': 'With errors',
+ 'lobeBench.dashboard.filter.category': 'Category: {{category}}',
+ 'lobeBench.dashboard.cases.count':
+ '{{count}} cases · cells are passes out of {{k}}; click a row to compare',
+ 'lobeBench.dashboard.cases.empty': 'No cases under this filter.',
+ 'lobeBench.dashboard.setup.col.model': 'Model',
+ 'lobeBench.dashboard.setup.col.settings': 'Settings',
+ 'lobeBench.dashboard.setup.col.cases': 'Cases',
+ 'lobeBench.dashboard.setup.col.k': 'Per case',
+ 'lobeBench.dashboard.setup.col.steps': 'Max steps',
+ 'lobeBench.dashboard.setup.col.cost': 'Cost',
+ 'lobeBench.dashboard.notFound':
+ 'This experiment does not exist or is not a Lobe Bench experiment.',
+ 'lobeBench.dashboard.spent': 'Spent {{cost}}',
+ 'lobeBench.compare.attempt': 'Attempt {{n}}',
+ 'lobeBench.compare.toolCalls': 'Tool calls',
+ 'lobeBench.compare.timeCost': 'Time · cost',
+ 'lobeBench.compare.reason': 'Judge reason',
+ 'lobeBench.compare.open': 'Open conversation',
+ 'lobeBench.compare.error': 'Error',
+ 'lobeBench.compare.pending': 'Not finished yet',
+ 'lobeBench.compare.noReason': 'No judge reason recorded.',
+ 'lobeBench.compare.passes': '{{passed}}/{{total}} passed',
+ 'lobeBench.library.title': 'Case library',
+ 'lobeBench.library.subtitle':
+ 'Previously installed shared cases. Select cases to make a dataset, or import a dataset ZIP directly.',
+ 'lobeBench.library.empty':
+ 'No shared case library is installed. You can import a dataset ZIP without one.',
+ 'lobeBench.sidebar.benchmarks': 'Benchmarks',
+ 'lobeBench.sidebar.datasets': 'Datasets',
+ 'lobeBench.benchmark.notFound': 'Benchmark not found',
+ 'lobeBench.benchmark.rank.title': 'Leaderboard',
+ 'lobeBench.benchmark.rank.hint':
+ "Each contender's best completed run on the whole set, ranked by cases that passed all {{k}} attempts. A run of more attempts per case is scored on {{k}} (estimated); one of fewer is not ranked.",
+ 'lobeBench.benchmark.rank.anyRate': 'any of {{k}}: {{value}}',
+ 'lobeBench.benchmark.rank.legend.rate': 'Passed all {{k}} attempts (ranked by this)',
+ 'lobeBench.benchmark.rank.legend.reach': 'Passed at least 1 of {{k}}',
+ 'lobeBench.benchmark.rank.estimated': 'estimated from {{attempts}} attempts',
+ 'lobeBench.benchmark.rank.fewAttempts_one':
+ '{{count}} run has no comparable score for {{k}} attempts and is not ranked',
+ 'lobeBench.benchmark.rank.fewAttempts_other':
+ '{{count}} runs have no comparable score for {{k}} attempts and are not ranked',
+ 'lobeBench.new.k.ranked': '{{k}}× (leaderboard)',
+ 'lobeBench.new.k.hint': 'Leaderboards rank runs with at least {{k}} attempts per case.',
+ 'lobeBench.benchmark.rank.cost': '${{cost}}/case',
+ 'lobeBench.benchmark.rank.compare.all': 'Compare: all models',
+ 'lobeBench.benchmark.rank.compare.reset': 'Show all models',
+ 'lobeBench.benchmark.rank.compare.some_one': 'Compare: {{count}} model',
+ 'lobeBench.benchmark.rank.compare.some_other': 'Compare: {{count}} models',
+ 'lobeBench.benchmark.rank.setOption_one': '{{name}} · {{count}} contender',
+ 'lobeBench.benchmark.rank.setOption_other': '{{name}} · {{count}} contenders',
+ 'lobeBench.benchmark.rank.summary_one': '{{count}} contender · {{runs}} completed full runs',
+ 'lobeBench.benchmark.rank.summary_other': '{{count}} contenders · {{runs}} completed full runs',
+ 'lobeBench.benchmark.rank.active_one': '{{count}} run in progress',
+ 'lobeBench.benchmark.rank.active_other': '{{count}} runs in progress',
+ 'lobeBench.benchmark.rank.unjudged_one': '{{count}} completed run awaiting judging',
+ 'lobeBench.benchmark.rank.unjudged_other': '{{count}} completed runs awaiting judging',
+ 'lobeBench.benchmark.rank.outdated_one':
+ '{{count}} run on an earlier version of the cases is not ranked',
+ 'lobeBench.benchmark.rank.outdated_other':
+ '{{count}} runs on an earlier version of the cases are not ranked',
+ 'lobeBench.benchmark.outdatedRun': 'Earlier case version · not ranked',
+ 'lobeBench.experiment.outdated': 'Earlier case version: not on any leaderboard',
+ 'lobeBench.benchmark.rank.broken_one':
+ '{{count}} run has incomplete or errored attempts and is not ranked',
+ 'lobeBench.benchmark.rank.broken_other':
+ '{{count}} runs have incomplete or errored attempts and are not ranked',
+ 'lobeBench.benchmark.rank.empty':
+ 'No completed run on all of {{set}} yet. Start an experiment on it and the models rank here.',
+ 'lobeBench.benchmark.datasets': 'Datasets',
+ 'lobeBench.benchmark.datasets.hint':
+ "The datasets this benchmark is made of. A run counts on the leaderboard when it ran all of a dataset's cases.",
+ 'lobeBench.benchmark.standard.title': 'Grading and run rules',
+ 'lobeBench.benchmark.standard.hint':
+ 'Every run on this benchmark uses this judge model and these rules, so its scores stay comparable. They cannot be changed later or per experiment.',
+ 'lobeBench.benchmark.standard.k': 'Attempts per case',
+ 'lobeBench.new.standard.missing':
+ '{{name}} has no judge model or run rules, so it cannot be run.',
+ 'lobeBench.new.standard.mixed':
+ 'The chosen benchmarks use different run rules (attempts, steps or timeout). Start a separate experiment for each.',
+ 'lobeBench.new.confirm.standardOf':
+ '{{benchmark}}: judged by {{model}}, {{k}} attempts per case, up to {{maxSteps}} steps, {{timeout}} min per attempt',
+ 'lobeBench.benchmark.create.judge': 'Judge model',
+ 'lobeBench.benchmark.create.judge.hint':
+ 'Every run on this benchmark is graded by this model, so its scores stay comparable. It cannot be changed later.',
+ 'lobeBench.benchmark.create.judge.placeholder': 'Choose the judge model',
+ 'lobeBench.benchmark.create.datasets': 'Datasets',
+ 'lobeBench.benchmark.create.datasets.empty':
+ 'No dataset to build it from yet. Import a dataset ZIP first; it stays on its own until a benchmark is made of it.',
+ 'lobeBench.benchmark.create.datasets.hint':
+ 'A benchmark runs the datasets it is made of. Choose at least one.',
+ 'lobeBench.benchmark.create.datasets.placeholder': 'Choose datasets',
+ 'lobeBench.benchmark.create.description': 'Description',
+ 'lobeBench.benchmark.create.description.placeholder': 'Optional: what this benchmark measures',
+ 'lobeBench.benchmark.create.failed': 'Could not create the benchmark',
+ 'lobeBench.benchmark.create.name': 'Name',
+ 'lobeBench.benchmark.create.name.placeholder': 'e.g. Finance agents',
+ 'lobeBench.benchmark.create.submit': 'Create benchmark',
+ 'lobeBench.benchmark.create.title': 'New benchmark',
+ 'lobeBench.benchmark.datasets.add': 'Add dataset',
+ 'lobeBench.benchmark.datasets.empty':
+ "No datasets. A benchmark's datasets are chosen when it is created; to use others, create a new benchmark.",
+ 'lobeBench.benchmark.datasets.remove': 'Remove from this benchmark',
+ 'lobeBench.benchmark.delete.confirm':
+ 'Delete {{name}}? Its runs and results are deleted with it. Its datasets are kept, free to make another benchmark of.',
+ 'lobeBench.benchmark.runs': 'Runs',
+ 'lobeBench.benchmark.runCount_one': '{{count}} evaluation run on this benchmark',
+ 'lobeBench.benchmark.runCount_other': '{{count}} evaluation runs on this benchmark',
+ 'lobeBench.benchmark.noRunsYet':
+ 'No run on this benchmark yet. Start an experiment to compare contenders on a case set.',
+ 'lobeBench.benchmark.newExperiment': 'New experiment',
+ 'lobeBench.benchmark.custom': 'My cases',
+ 'lobeBench.benchmark.cases': '{{count}} cases',
+ 'lobeBench.benchmark.best': 'best {{value}} over {{count}} full runs',
+ 'lobeBench.benchmark.noRuns': 'No full run yet',
+ 'lobeBench.dataset.deleteInBenchmark':
+ 'This dataset is part of a benchmark. Delete the benchmark first; its datasets are kept.',
+ 'lobeBench.dataset.noRuns': 'No run on this dataset yet. Run an experiment on it.',
+ 'lobeBench.dataset.own.subtitle_one':
+ '{{count}} case. The cases are fixed; import an updated package as a new dataset.',
+ 'lobeBench.dataset.own.subtitle_other':
+ '{{count}} cases. The cases are fixed; import an updated package as a new dataset.',
+ 'lobeBench.dataset.runCount_one': '{{count}} run on this dataset',
+ 'lobeBench.dataset.runCount_other': '{{count}} runs on this dataset',
+ 'lobeBench.dataset.notFound': 'Case set not found',
+ 'lobeBench.dataset.custom': 'My dataset',
+ 'lobeBench.dataset.release': 'Release {{release}}',
+ 'lobeBench.topicCase.title': 'Case from a conversation',
+ 'lobeBench.topicCase.intro':
+ 'Paste a conversation id. Its last request becomes the case, the earlier messages replay as context, and the Agent that answered it (persona, tools) is kept with the case.',
+ 'lobeBench.topicCase.topicId': 'Conversation id',
+ 'lobeBench.topicCase.topicId.placeholder': 'tpc_\u2026 (the topic in the chat URL)',
+ 'lobeBench.topicCase.load': 'Load',
+ 'lobeBench.topicCase.agent': 'Agent',
+ 'lobeBench.topicCase.noAgent':
+ 'No Agent setup captured; the case runs on the contender\u2019s default setup.',
+ 'lobeBench.topicCase.tools': 'Tools',
+ 'lobeBench.topicCase.context': '{{count}} earlier messages replay before the request',
+ 'lobeBench.topicCase.input': 'Request under test',
+ 'lobeBench.topicCase.answer': 'Recorded answer',
+ 'lobeBench.topicCase.rules': 'Rules',
+ 'lobeBench.topicCase.rules.hint':
+ 'One per line, starting with Must: or Must not:. Drafted from the conversation; check them before saving.',
+ 'lobeBench.topicCase.rulesRequired': 'Add at least one rule',
+ 'lobeBench.topicCase.save': 'Save to My cases',
+ 'lobeBench.topicCase.saved': 'Case saved to My cases',
+ 'lobeBench.topicCase.loadError': 'Could not load that conversation',
+ 'lobeBench.topicCase.saveError': 'Could not save the case',
+ 'lobeBench.library.cases': '{{count}} cases',
+ 'lobeBench.library.col.case': 'Case',
+ 'lobeBench.library.col.category': 'Category',
+ 'lobeBench.library.col.tools': 'Tools',
+ 'lobeBench.dashboard.insight.lowest': 'Lowest pass rate',
+ 'lobeBench.library.badge.broken': 'Possibly broken',
+ 'lobeBench.library.badge.easy': 'Low discrimination',
+ 'lobeBench.sidebar.datasets.empty': 'No datasets yet. Import a dataset ZIP to start.',
+ 'lobeBench.sidebar.benchmarks.empty': 'No benchmarks yet. Import a dataset or create one.',
+ 'lobeBench.picks.title_one': 'Make a dataset of {{count}} case',
+ 'lobeBench.picks.title_other': 'Make a dataset of {{count}} cases',
+ 'lobeBench.picks.fixed':
+ 'Its cases are fixed once it is made, so its runs always mean the same cases. For other cases, make another dataset.',
+ 'lobeBench.picks.created_one': 'Made {{dataset}} with {{count}} case',
+ 'lobeBench.picks.created_other': 'Made {{dataset}} with {{count}} cases',
+ 'lobeBench.benchmark.datasets.noneLoose': 'No dataset to add yet: make one in the Case library',
+ 'lobeBench.picks.name': 'Dataset name',
+ 'lobeBench.picks.name.placeholder': 'e.g. Finance L2',
+ 'lobeBench.picks.defaultName': 'My dataset',
+ 'lobeBench.picks.create': 'Create dataset',
+ 'lobeBench.picks.failed': 'The dataset was not saved. Try again.',
+ 'lobeBench.picks.selected': '{{count}} selected',
+ 'lobeBench.picks.clear': 'Clear',
+ 'lobeBench.picks.hint.library': 'Check cases to make a dataset of your own.',
+ 'lobeBench.picks.run': 'Run experiment',
+ 'lobeBench.picks.rename': 'Rename',
+ 'lobeBench.picks.delete': 'Delete dataset',
+ 'lobeBench.picks.delete.confirm':
+ 'Delete "{{name}}"? The runs on it and their results are deleted too, and leave every leaderboard. This cannot be undone.',
+ 'lobeBench.case.prompt': 'What the user asks',
+ 'lobeBench.case.persona': 'Persona for this case',
+ 'lobeBench.case.rules': 'Grading rules',
+ 'lobeBench.case.readOnly': 'read-only',
+ 'lobeBench.unit.min': '{{value}} min',
+ 'lobeBench.benchmark.runCases': '{{selected}} of {{total}} cases',
+ 'lobeBench.new.confirm.title': 'Start this experiment?',
+ 'lobeBench.new.confirm.line':
+ '{{cases}} cases × {{contenders}} contenders × {{k}} attempts each = {{attempts}} attempts.',
+ 'lobeBench.new.confirm.cost':
+ 'Estimated cost {{cost}}, from your recent runs of the same models.',
+ 'lobeBench.new.confirm.costUnknown':
+ 'No cost history for these models yet; the dashboard shows the cost as it runs.',
+ 'lobeBench.new.confirm.billing': 'Model and judge tokens are billed to your providers.',
+ 'lobeBench.new.confirm.ok': 'Start',
+ 'lobeBench.dashboard.abort': 'Stop',
+ 'lobeBench.dashboard.abort.confirm':
+ 'Stop the running contenders? Finished cases keep their results; the rest stay unfinished.',
+ 'lobeBench.dashboard.export': 'Export CSV',
+ 'lobeBench.attempt.backToExperiment': 'Back to experiment',
+ 'caseDetail.section.rules': 'Rules',
+ 'caseDetail.section.memory': 'Memory at the end',
+ 'caseDetail.memory.seed': 'seed',
+ 'caseDetail.memory.agent': 'written during the attempt',
+ 'caseDetail.memory.removed': 'removed',
+ 'caseDetail.memory.empty': 'No memory entries.',
+ 'lobeBench.sidebar.settings': 'Settings',
+ 'lobeBench.settings.title': 'Settings',
+ 'lobeBench.settings.subtitle':
+ 'Where mock tool connections are managed. Each benchmark fixes its own judge and run rules when it is made.',
+ 'lobeBench.settings.benchmark': 'Benchmark',
+ 'lobeBench.settings.judge': 'Judge model',
+ 'lobeBench.settings.judge.hint':
+ 'Grades every attempt. Pick a model that is not one of the contenders; a case set or a case can still name its own judge.',
+ 'lobeBench.settings.judge.placeholder': 'System default (the topic model of your assistant)',
+ 'lobeBench.settings.judge.clear': 'Use system default',
+ 'lobeBench.settings.grading.title': 'Grading',
+ 'lobeBench.settings.grading.line': 'Attempts are graded by {{model}}.',
+ 'lobeBench.settings.grading.unset': 'Attempts are graded by the system default model.',
+ 'lobeBench.settings.grading.hint':
+ 'Comes with Lobe Bench. Any experiment can choose a different grader when you start it.',
+ 'lobeBench.settings.mine.title': 'Your defaults for new experiments',
+ 'lobeBench.settings.mine.hint': 'Only you see these; every experiment can still change them.',
+ 'lobeBench.settings.mine.reset': 'Reset',
+ 'lobeBench.settings.mine.reset.done': 'Back to the Lobe Bench defaults',
+ 'lobeBench.settings.mine.saved': 'Saved for you',
+ 'lobeBench.library.col.level': 'Level',
+ 'lobeBench.library.filter.level': 'Level',
+ 'lobeBench.library.levels': '{{l1}} L1 · {{l2}} L2 · {{l3}} L3 · {{l4}} L4',
+ 'lobeBench.case.level.L1': 'L1',
+ 'lobeBench.case.level.L2': 'L2',
+ 'lobeBench.case.level.L3': 'L3',
+ 'lobeBench.case.level.L4': 'L4',
+ 'lobeBench.case.difficulty.why': 'Why this level: {{signals}}.',
+ 'lobeBench.dashboard.byLevel': 'By difficulty',
+ 'lobeBench.dashboard.byLevel.hint':
+ 'Pass rate per difficulty level. Levels come from the case contract (calls in order, services spanned, failures injected, rules to satisfy), not from any model.',
+ 'lobeBench.dashboard.filter.level': 'Level: {{level}}',
+ 'lobeBench.builtIn': 'Built-in',
+ 'lobeBench.contenders.builtIn':
+ 'Contenders you ran in past experiments. The built-in benchmark keeps no saved list; add one on the New experiment page.',
+ 'lobeBench.environments.editor.builtIn':
+ 'Built-in environment: shown as is. Duplicate it to make an editable copy for your own cases.',
+ 'lobeBench.new.judge': 'Judge model',
+ 'lobeBench.new.judge.hint':
+ 'Grades every attempt of this experiment. Leave empty to use the benchmark default.',
+ 'lobeBench.settings.defaults': 'New experiment defaults',
+ 'lobeBench.settings.defaults.hint':
+ 'What the New experiment form starts with; every value can still be changed per experiment.',
+ 'lobeBench.settings.defaults.k': 'Attempts per case',
+ 'lobeBench.settings.defaults.maxSteps': 'Max steps per attempt',
+ 'lobeBench.settings.defaults.timeout': 'Timeout per attempt (minutes)',
+ 'lobeBench.settings.save': 'Save',
+ 'lobeBench.settings.saved': 'Saved',
+ 'lobeBench.settings.notInstalled': 'No Lobe Bench benchmark in this account yet.',
+ 'lobeBench.new.confirm.judge': 'Judge: {{model}}',
+ 'lobeBench.new.confirm.judgeDefault': 'Judge: system default (pick one in Settings)',
+ 'lobeBench.new.confirm.judgeOf': '{{benchmark}} judged by {{model}}',
+ 'lobeBench.new.judge.missing':
+ '{{name}} has no judge model, so it cannot be run. Import it again as a new benchmark and choose a judge.',
+ 'lobeBench.case.new': 'New case',
+ 'lobeBench.case.fromConversation': 'From a conversation',
+ 'lobeBench.case.fromConversation.hint':
+ 'Pick one of your conversations: its last request becomes the case, the earlier turns its context, and the judge drafts the rules. Nothing is saved until you do.',
+ 'lobeBench.case.fromConversation.search': 'Search conversations, then press Enter',
+ 'lobeBench.case.fromConversation.empty': 'No conversations found.',
+ 'lobeBench.case.fromConversation.drafting': 'Drafting the case from the conversation…',
+ 'lobeBench.case.edit': 'Edit',
+ 'lobeBench.case.delete': 'Delete',
+ 'lobeBench.case.runsWith': 'Runs with',
+ 'lobeBench.case.runsWith.connectors': 'Simulated connectors',
+ 'lobeBench.case.runsWith.noConnectors': 'No connectors',
+ 'lobeBench.case.runsWith.memory': 'Memory',
+ 'lobeBench.case.runsWith.memoryOff': 'Memory off',
+ 'lobeBench.case.runsWith.memoryMode': 'Memory {{permission}} · effort {{effort}}',
+ 'lobeBench.case.runsWith.memoryEmpty': 'starts empty',
+ 'lobeBench.case.runsWith.memoryRecords_one': 'starts with {{count}} preset record',
+ 'lobeBench.case.runsWith.memoryRecords_other': 'starts with {{count}} preset records',
+ 'lobeBench.case.runsWith.clock': 'Clock',
+ 'lobeBench.case.runsWith.clockPinned': 'Every "today" the model sees is {{date}}',
+ 'lobeBench.case.runsWith.clockWall': 'Real time',
+ 'lobeBench.case.delete.confirm': 'Delete this case? Past results keep their own copy of it.',
+ 'lobeBench.case.testRun': 'Test run',
+ 'lobeBench.case.testRun.hint':
+ 'Runs this case once with one contender and opens the attempt. Model tokens are billed to your providers.',
+ 'lobeBench.case.editor.new': 'New case',
+ 'lobeBench.case.editor.edit': 'Edit case',
+ 'lobeBench.case.editor.title': 'Title',
+ 'lobeBench.case.editor.input': 'User request',
+ 'lobeBench.case.editor.input.placeholder': 'What the user asks the Agent to do.',
+ 'lobeBench.case.editor.turns': 'Earlier turns',
+ 'lobeBench.case.editor.turns.hint':
+ 'Replayed before the request, so the Agent has the context the user had.',
+ 'lobeBench.case.editor.turns.add': 'Add turn',
+ 'lobeBench.case.editor.category': 'Category',
+ 'lobeBench.case.editor.rules': 'Rules',
+ 'lobeBench.case.editor.rules.hint':
+ 'One per line, starting with "Must:" or "Must not:". The judge checks each one and explains every miss.',
+ 'lobeBench.case.editor.environment': 'Environment',
+ 'lobeBench.case.editor.environment.none': 'None — this case carries its own setup',
+ 'lobeBench.case.editor.environment.usedBy': 'used by {{count}} cases',
+ 'lobeBench.case.editor.overrides': 'This case only',
+ 'lobeBench.case.editor.overrides.hint':
+ 'Laid over the shared environment; leave a field empty to inherit it.',
+ 'lobeBench.case.editor.sessionDate': 'Clock (ISO date or instant)',
+ 'lobeBench.case.editor.timezone': 'Timezone',
+ 'lobeBench.case.editor.persona': 'Persona (system role)',
+ 'lobeBench.case.editor.plugins': 'Tool allowlist (plugin identifiers, comma separated)',
+ 'lobeBench.case.editor.mock': 'Mocked connectors (comma separated)',
+ 'lobeBench.case.editor.save': 'Save',
+ 'lobeBench.case.editor.saved': 'Case saved',
+ 'lobeBench.case.editor.invalidDate':
+ 'The clock must be an ISO date, e.g. 2026-07-20 or 2026-07-20T09:00:00Z',
+ 'lobeBench.case.fromConversation.rulesFailed':
+ 'The judge could not draft rules ({{error}}). Write them yourself, or pick a judge model in Settings.',
+ 'lobeBench.case.testRun.go': 'Run once',
+ 'lobeBench.environments.title': 'Environments',
+ 'lobeBench.environments.subtitle':
+ 'The persona, tools, Memory, clock and mocked connectors cases run in. Many cases share one; change it once and they all follow.',
+ 'lobeBench.environments.new': 'New environment',
+ 'lobeBench.environments.empty': 'No environments yet.',
+ 'lobeBench.environments.col.name': 'Environment',
+ 'lobeBench.environments.col.setup': 'Setup',
+ 'lobeBench.environments.col.cases': 'Cases',
+ 'lobeBench.environments.setup.tools': '{{count}} tools',
+ 'lobeBench.environments.setup.memory': 'Memory {{permission}}',
+ 'lobeBench.environments.setup.clock': 'clock {{date}}',
+ 'lobeBench.environments.setup.mock': '{{count}} mocked',
+ 'lobeBench.environments.setup.none': 'product defaults',
+ 'lobeBench.environments.editor.new': 'New environment',
+ 'lobeBench.environments.editor.edit': 'Edit environment',
+ 'lobeBench.environments.editor.impact': 'Used by {{count}} cases — saving changes them all',
+ 'lobeBench.environments.editor.name': 'Name',
+ 'lobeBench.environments.editor.description': 'Description',
+ 'lobeBench.environments.editor.agentName': 'Agent name the user knows it by (optional)',
+ 'lobeBench.environments.editor.memory': 'Memory',
+ 'lobeBench.environments.editor.memory.hint':
+ 'When on, each attempt gets its own Memory seeded from the entries below; the model can read it, or read and write it.',
+ 'lobeBench.environments.editor.memory.permission': 'Tool permission',
+ 'lobeBench.environments.editor.memory.effort': 'Effort',
+ 'lobeBench.environments.editor.memory.seeds': 'Seed entries (JSON)',
+ 'lobeBench.environments.editor.memory.template': 'Insert an example',
+ 'lobeBench.environments.editor.memory.placeholder':
+ '{ "persona": { "narrative": "…" }, "preferences": [ … ], "contexts": [ … ], "seededAt": "2026-07-20T09:00:00Z" }',
+ 'lobeBench.environments.editor.memory.invalid': 'The seed entries must be a JSON object.',
+ 'lobeBench.environments.editor.envPrompt': 'Extra system context (optional)',
+ 'lobeBench.environments.editor.duplicate': 'Duplicate',
+ 'lobeBench.environments.editor.saved': 'Environment saved',
+ 'lobeBench.environments.delete.confirm':
+ 'Delete this environment? Its {{count}} cases keep running on their own settings, without it.',
+ 'lobeBench.sidebar.contenders': 'Contenders',
+ 'lobeBench.new.contenders.saved': 'Saved contenders — click to add',
+ 'lobeBench.contenders.title': 'Contenders',
+ 'lobeBench.contenders.subtitle':
+ 'A contender is a model with the settings it runs with. Every contender that ran is kept here; add one ahead of time or tidy the list.',
+ 'lobeBench.contenders.new': 'New contender',
+ 'lobeBench.contenders.empty': 'No contenders yet. Start an experiment, or add one here.',
+ 'lobeBench.contenders.col.name': 'Contender',
+ 'lobeBench.contenders.col.model': 'Model',
+ 'lobeBench.contenders.col.experiments': 'Experiments',
+ 'lobeBench.contenders.col.best': 'Best full run',
+ 'lobeBench.contenders.edit': 'Edit',
+ 'lobeBench.contenders.delete.confirm':
+ 'Remove this contender from the saved list? Past experiments keep their results.',
+ 'lobeBench.contenders.saved': 'Contender saved',
+ 'lobeBench.contender.save.list': 'Save',
+ 'lobeBench.library.filter.search': 'Search cases',
+ 'lobeBench.library.filter.category': 'Category',
+ 'lobeBench.library.filter.count': '{{shown}} of {{total}} cases',
+ 'lobeBench.new.launch.close': 'Close',
+ 'lobeBench.new.launch.currentRun': 'Run {{index}} of {{total}} · {{name}}',
+ 'lobeBench.new.launch.elapsed': 'Since first start: {{elapsed}}',
+ 'lobeBench.new.launch.interrupted': 'Launch not finished',
+ 'lobeBench.new.launch.stage.check': 'Checking saved runs',
+ 'lobeBench.new.launch.stage.complete': 'All runs submitted. Opening the experiment…',
+ 'lobeBench.new.launch.stage.experiment': 'Creating experiment',
+ 'lobeBench.new.launch.stage.metadata': 'Saving experiment setup',
+ 'lobeBench.new.launch.stage.run': 'Preparing run and checking connections',
+ 'lobeBench.new.launch.stage.start': 'Checking connections and submitting run',
+ 'lobeBench.new.launch.steps': '{{completed}} of {{total}} launch steps complete',
+ 'lobeBench.new.launch.title': 'Starting experiment',
+ 'lobeBench.new.launch.waiting':
+ 'You can visit other pages while startup continues in this browser tab. Return to this experiment to check progress.',
+ 'lobeBench.new.launch.busy': 'Another tab is starting this experiment. Check again shortly.',
+ 'lobeBench.new.launch.back': 'Back to experiments',
+ 'lobeBench.new.launch.recovery':
+ 'Startup has not been confirmed. Check and continue from the saved checkpoint; existing runs will not be started again.',
+ 'lobeBench.new.launch.pending':
+ 'An experiment launch is unfinished. Settings are locked while it is being recovered.',
+ 'lobeBench.new.launch.unknown':
+ 'The last launch did not finish. Continue to check its saved progress.',
+ 'lobeBench.new.launch.progress':
+ '{{started}} of {{total}} contenders have been accepted for execution.',
+ 'lobeBench.new.launch.metadataFailed':
+ 'Saving the experiment setup failed: {{error}}. Continue to retry saving it.',
+ 'lobeBench.new.launch.failed':
+ 'Stopped at “{{name}}”: {{error}}. Continue to check progress and finish launching.',
+ 'lobeBench.new.launch.storageError':
+ 'This browser could not save the launch record. No new launch was started.',
+ 'lobeBench.new.launch.continue': 'Continue launching',
+ 'lobeBench.new.launch.open': 'Open experiment',
+ 'lobeBench.new.launch.abandon': 'Stop recovery',
+ 'lobeBench.new.launch.abandon.title': 'Stop recovering this launch?',
+ 'lobeBench.new.launch.abandon.confirm':
+ 'Runs already started keep running in the experiment. The form unlocks; starting again creates a new experiment and may incur additional costs.',
+ 'lobeBench.dashboard.gradingGap':
+ '{{name}}: {{count}} attempts have unfinished grading. Saved summary scores are unchanged.',
+ 'lobeBench.dashboard.awaitingExternal':
+ '{{name}}: {{count}} attempts are waiting for external grading.',
+ 'lobeBench.dashboard.setup.hint':
+ 'Saved when the experiment started: the selected models and run settings. Cases and grading rules come from the current library.',
+ 'lobeBench.new.launch.unconfirmed':
+ '{{count}} contenders are awaiting server confirmation: {{names}}. Check again shortly or open the experiment.',
+ 'lobeBench.new.launch.occupied':
+ 'Another tab has started a launch for this benchmark. Its saved record is shown above.',
+ 'lobeBench.new.launch.legacy': 'A launch record from an earlier version was found.',
+ 'lobeBench.new.launch.legacy.hint':
+ 'This record cannot be resumed here. Open the experiment to inspect its runs, or stop recovery.',
+ 'lobeBench.new.launch.perBenchmark':
+ 'Launch records are saved separately for each benchmark. Return to its form to recover an unfinished launch.',
+ 'lobeBench.new.launch.recheck': 'Check again',
+ 'lobeBench.dashboard.action.stopSuccess': 'Stopped {{models}}.',
+ 'lobeBench.dashboard.action.failed':
+ 'Could not complete the action for {{models}}. Reload and inspect these runs.',
+ 'lobeBench.dashboard.action.stillRunning':
+ '{{models}} are still running. Wait for them to finish before trying again.',
+ 'lobeBench.compare.judgeError': 'Grading error',
+ 'lobeBench.dashboard.judgeErrors':
+ '{{name}}: {{count}} attempts got no verdict. Rerun runs those cases again.',
+ 'lobeBench.compare.filter.judgeErrors': 'Grading errors',
+ 'lobeBench.overview.attention.judgeErrors': '{{count}} cases could not be graded',
+ 'lobeBench.overview.attention.ungraded': 'Grading unfinished for {{count}} cases',
+ 'lobeBench.overview.attention.external': '{{count}} cases awaiting external grading',
+ 'caseDetail.judgeError.regradeHint':
+ 'The original answer is kept. On the experiment page, Rerun runs this case again and grades the new attempts.',
+ 'connections.title': 'Mock MCP connections',
+ 'connections.hint':
+ 'Choose a connection for each service. Each connection manages its own address and authentication. The same connection can serve several services.',
+ 'connections.environment': 'Environment',
+ 'connections.case': 'Case override',
+ 'connections.fromPackage': 'Use the connection included in the ZIP',
+ 'connections.configureLater': 'Configure later',
+ 'connections.unavailable': 'Connection unavailable — choose another',
+ 'connections.transport': 'Protocol for {{service}}',
+ 'connections.standard': 'Standard MCP',
+ 'connections.adapter': 'LobeBench mock adapter',
+ 'connections.empty': 'No available HTTP connections yet. Create one here, then choose it above.',
+ 'connections.create': 'Create connection',
+ 'connections.refresh': 'Refresh connections',
+ 'connections.included': 'Connections included in this ZIP',
+ 'connections.autoImport':
+ 'These connections will be created and bound automatically when you import. You do not need to enter an address or token.',
+ 'connections.authIncluded': 'Access credentials included',
+ 'connections.noAuth': 'No access credentials included',
+ 'connections.importLater':
+ 'Some services have no connection included. You can import now and configure them in the dataset before running.',
+ 'connections.optional': 'Choose existing connections (optional)',
+ 'connections.completeScope':
+ 'Choose every service in an edited environment or case, or clear your changes to configure it later.',
+ 'connections.saved': 'Connections saved',
+ 'connections.cancel': 'Cancel',
+ 'connections.save': 'Save connections',
+ 'connections.editHint':
+ 'Changes affect every environment using this connection. Saved credentials are kept private; enter new credentials to replace them.',
+ 'connections.checking': 'Checking connection availability…',
+ 'connections.missing': '{{count}} service bindings need a connection before running.',
+ 'connections.configured': 'All required services have a connection.',
+ 'connections.manage': 'Configure connections',
+ 'connections.showDetails': 'Show connections',
+ 'connections.hideDetails': 'Hide connections',
+ 'connections.datasetHint':
+ 'Connections are shared by cases using the same environment. Availability here confirms the saved binding; the service is checked when a run starts.',
+ 'connections.settingsHint':
+ 'Mock services use the connections bound to each dataset’s environments and cases. ZIP imports can configure them automatically. Open a dataset to change its bindings.',
+ 'connections.openManager': 'Manage Dataset connection addresses and authentication',
+ 'connections.name': 'Connection name',
+ 'connections.url': 'MCP server URL',
+ 'connections.authentication': 'Authentication',
+ 'connections.keepAuth': 'Keep saved authentication',
+ 'connections.clearAuth': 'No authentication (clear saved credentials)',
+ 'connections.bearerAuth': 'Bearer token',
+ 'connections.headerAuth': 'Custom headers',
+ 'connections.replaceAuth': 'Replace or clear authentication when changing the server address.',
+ 'connections.saveAndTest': 'Save and test',
+ 'connections.tested': 'Connected \u00B7 {{count}} tools available',
+ 'connections.datasetOnly':
+ 'Manage connections in the Dataset that uses this environment. Import a new Dataset before configuring its connections.',
+ 'connections.unbound': 'Not bound to an environment or case',
+ 'connections.edit': 'Edit connection',
+ 'connections.enabled': 'Enable connection',
+ 'connections.disabled': 'Disabled',
+ 'connections.authSaved': 'Authentication saved',
+ 'connections.authNone': 'No authentication',
+ 'connections.statusConnected': 'Last check succeeded',
+ 'connections.statusError': 'Last check failed',
+ 'connections.statusDisconnected': 'Not checked',
};
diff --git a/src/features/AgentEval/ConnectorBindings/ConnectionEditor.tsx b/src/features/AgentEval/ConnectorBindings/ConnectionEditor.tsx
new file mode 100644
index 00000000000..ee60176a52b
--- /dev/null
+++ b/src/features/AgentEval/ConnectorBindings/ConnectionEditor.tsx
@@ -0,0 +1,219 @@
+'use client';
+
+import {
+ Button,
+ createModal,
+ Flexbox,
+ Input,
+ InputPassword,
+ Select,
+ Spin,
+ Switch,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { useId, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import KeyValueEditor from '@/components/KeyValueEditor';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+type Connection = Awaited<ReturnType<typeof agentEvalService.getEvalConnector>>;
+interface EditorProps {
+ datasetId: string;
+ id?: string;
+ onSaved: () => Promise<unknown>;
+}
+
+const ConnectionForm = ({
+ datasetId,
+ connection,
+ onSaved,
+}: Omit<EditorProps, 'id'> & { connection?: Connection }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const formId = useId();
+ const [connectionId, setConnectionId] = useState(connection?.id);
+ const [name, setName] = useState(connection?.name ?? '');
+ const [enabled, setEnabled] = useState(connection?.isEnabled ?? true);
+ const [url, setUrl] = useState(connection?.mcpServerUrl ?? '');
+ const [auth, setAuth] = useState(connection?.hasCredentials ? 'keep' : 'none');
+ const [token, setToken] = useState('');
+ const [headers, setHeaders] = useState<Record<string, string>>({});
+ const [pending, setPending] = useState<'save' | 'test'>();
+ const [error, setError] = useState<unknown>();
+ const [tested, setTested] = useState<number>();
+ const needsAuth = auth === 'keep' && url !== connection?.mcpServerUrl;
+ const invalid = !name.trim() || !url.trim() || needsAuth || (auth === 'bearer' && !token);
+
+ const save = async (test: boolean) => {
+ setPending(test ? 'test' : 'save');
+ setError(undefined);
+ setTested(undefined);
+ try {
+ const saved = await agentEvalService.saveEvalConnector({
+ credentials:
+ auth === 'keep'
+ ? undefined
+ : auth === 'none'
+ ? null
+ : auth === 'bearer'
+ ? { token, type: 'bearer' }
+ : { headers, type: 'header' },
+ datasetId,
+ id: connectionId,
+ isEnabled: enabled,
+ mcpServerUrl: url.trim(),
+ name: name.trim(),
+ });
+ setConnectionId(saved.id);
+ await onSaved();
+ if (test) {
+ const result = await agentEvalService.testEvalConnector(datasetId, saved.id);
+ setTested(result.toolCount);
+ await onSaved();
+ } else {
+ toast.success(t('connections.saved'));
+ close();
+ }
+ } catch (cause) {
+ setError(cause);
+ } finally {
+ setPending(undefined);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text type="secondary">{t('connections.editHint')}</Text>
+ <Flexbox horizontal align="center" gap={12} justify="space-between">
+ <label htmlFor={`${formId}-enabled`}>{t('connections.enabled')}</label>
+ <Switch
+ checked={enabled}
+ disabled={!!pending}
+ id={`${formId}-enabled`}
+ onChange={setEnabled}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <label htmlFor={`${formId}-name`}>{t('connections.name')}</label>
+ <Input
+ disabled={!!pending}
+ id={`${formId}-name`}
+ maxLength={255}
+ value={name}
+ onChange={(e) => {
+ setTested(undefined);
+ setName(e.target.value);
+ }}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <label htmlFor={`${formId}-url`}>{t('connections.url')}</label>
+ <Input
+ disabled={!!pending}
+ id={`${formId}-url`}
+ value={url}
+ onChange={(e) => {
+ setTested(undefined);
+ setUrl(e.target.value);
+ }}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <label htmlFor={`${formId}-auth`}>{t('connections.authentication')}</label>
+ <Select
+ disabled={!!pending}
+ id={`${formId}-auth`}
+ value={auth}
+ options={[
+ ...(connection?.hasCredentials
+ ? [{ label: t('connections.keepAuth'), value: 'keep' }]
+ : []),
+ { label: t('connections.clearAuth'), value: 'none' },
+ { label: t('connections.bearerAuth'), value: 'bearer' },
+ { label: t('connections.headerAuth'), value: 'header' },
+ ]}
+ onChange={(value) => {
+ setTested(undefined);
+ setAuth(String(value));
+ }}
+ />
+ {needsAuth && <Text type="danger">{t('connections.replaceAuth')}</Text>}
+ {auth === 'bearer' && (
+ <InputPassword
+ aria-label={t('connections.bearerAuth')}
+ autoComplete="new-password"
+ disabled={!!pending}
+ value={token}
+ onChange={(e) => {
+ setTested(undefined);
+ setToken(e.target.value);
+ }}
+ />
+ )}
+ {auth === 'header' && (
+ <KeyValueEditor
+ disabled={!!pending}
+ value={headers}
+ onChange={(value) => {
+ setTested(undefined);
+ setHeaders(value);
+ }}
+ />
+ )}
+ </Flexbox>
+ {!!error && <AsyncError error={error} variant="inline" />}
+ {tested !== undefined && <Text>{t('connections.tested', { count: tested })}</Text>}
+ <Flexbox horizontal gap={8} justify="flex-end" wrap="wrap">
+ <Button disabled={!!pending} onClick={close}>
+ {t('connections.cancel')}
+ </Button>
+ <Button
+ disabled={invalid || !!pending}
+ loading={pending === 'test'}
+ onClick={() => void save(true)}
+ >
+ {t('connections.saveAndTest')}
+ </Button>
+ <Button
+ disabled={invalid || !!pending}
+ loading={pending === 'save'}
+ type="primary"
+ onClick={() => void save(false)}
+ >
+ {t('connections.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+const ConnectionEditor = (props: EditorProps) => {
+ const fetchConnection = useEvalStore((s) => s.useFetchEvalConnector);
+ const { data, error, isLoading, mutate } = fetchConnection(props.datasetId, props.id);
+ if (props.id && isLoading) return <Spin />;
+ if (error) return <AsyncError error={error} onRetry={() => void mutate()} />;
+ if (props.id && !data) return null;
+ return (
+ <ConnectionForm
+ {...props}
+ connection={data}
+ onSaved={async () => {
+ await Promise.all([props.onSaved(), props.id ? mutate() : Promise.resolve()]);
+ }}
+ />
+ );
+};
+
+export const openConnectionEditor = (props: EditorProps & { title: string }) =>
+ createModal({
+ content: <ConnectionEditor {...props} />,
+ footer: null,
+ maskClosable: false,
+ title: props.title,
+ width: 640,
+ });
diff --git a/src/features/AgentEval/ConnectorBindings/DatasetConnections.tsx b/src/features/AgentEval/ConnectorBindings/DatasetConnections.tsx
new file mode 100644
index 00000000000..1644ec18249
--- /dev/null
+++ b/src/features/AgentEval/ConnectorBindings/DatasetConnections.tsx
@@ -0,0 +1,276 @@
+'use client';
+
+import type {
+ AgentEvalDatasetConnectorRequirement,
+ AgentEvalDatasetPackageBindings,
+} from '@lobechat/types';
+import { Block, Button, Flexbox, Modal, Spin, Text, toast } from '@lobehub/ui';
+import { useId, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+import { hasPartialConnectorBindings } from './bindings';
+import { openConnectionEditor } from './ConnectionEditor';
+import { ConnectorBindings } from './index';
+
+const DatasetConnectionsEditor = ({
+ datasetId,
+ onClose,
+ onSaved,
+ requirements,
+}: {
+ datasetId: string;
+ onClose: () => void;
+ onSaved: () => Promise<unknown>;
+ requirements: AgentEvalDatasetConnectorRequirement[];
+}) => {
+ const { t } = useTranslation('eval');
+ const [value, setValue] = useState<AgentEvalDatasetPackageBindings>(() => ({
+ caseBindings: Object.fromEntries(
+ requirements.filter((r) => r.scope === 'case').map((r) => [r.key, r.bindings]),
+ ),
+ environmentBindings: Object.fromEntries(
+ requirements.filter((r) => r.scope === 'environment').map((r) => [r.key, r.bindings]),
+ ),
+ }));
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const changes: AgentEvalDatasetPackageBindings = {};
+ for (const requirement of requirements) {
+ const scope = requirement.scope === 'environment' ? 'environmentBindings' : 'caseBindings';
+ const next = value[scope]?.[requirement.key] ?? {};
+ if (JSON.stringify(next) !== JSON.stringify(requirement.bindings)) {
+ changes[scope] = { ...changes[scope], [requirement.key]: next };
+ }
+ }
+ const partial = hasPartialConnectorBindings(requirements, changes);
+ const save = async () => {
+ setSaving(true);
+ setError(undefined);
+ try {
+ await agentEvalService.updateDatasetConnectorBindings({ datasetId, ...changes });
+ await onSaved();
+ toast.success(t('connections.saved'));
+ onClose();
+ } catch (cause) {
+ setError(cause);
+ } finally {
+ setSaving(false);
+ }
+ };
+ return (
+ <Modal
+ open
+ closable={!saving}
+ keyboard={!saving}
+ maskClosable={false}
+ title={t('connections.title')}
+ width={640}
+ footer={
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={saving} onClick={onClose}>
+ {t('connections.cancel')}
+ </Button>
+ <Button disabled={partial} loading={saving} type="primary" onClick={() => void save()}>
+ {t('connections.save')}
+ </Button>
+ </Flexbox>
+ }
+ onCancel={onClose}
+ >
+ <Flexbox gap={12}>
+ <Text type="secondary">{t('connections.editHint')}</Text>
+ {!!error && <AsyncError error={error} variant="inline" />}
+ {partial && <Text type="danger">{t('connections.completeScope')}</Text>}
+ <ConnectorBindings
+ datasetId={datasetId}
+ disabled={saving}
+ requirements={requirements}
+ value={value}
+ onChange={setValue}
+ />
+ </Flexbox>
+ </Modal>
+ );
+};
+
+export const DatasetConnections = ({
+ datasetId,
+ editable,
+}: {
+ datasetId: string;
+ editable: boolean;
+}) => {
+ const { t } = useTranslation('eval');
+ const detailsId = useId();
+ const [expanded, setExpanded] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [fetchBindings, fetchConnectors] = useEvalStore((s) => [
+ s.useFetchDatasetConnectorBindings,
+ s.useFetchEvalConnectors,
+ ]);
+ const { data, error, isLoading, mutate } = fetchBindings(datasetId);
+ const {
+ data: connectors,
+ error: connectorError,
+ mutate: refreshConnectors,
+ } = fetchConnectors(datasetId);
+ if (isLoading) return <Spin />;
+ if (error) return <AsyncError error={error} variant="inline" onRetry={() => void mutate()} />;
+ if (!data) return null;
+ // An older server may omit the field; treat it as a Dataset with no connector needs.
+ const requirements = data.requirements ?? [];
+ const missing =
+ connectors &&
+ requirements.reduce(
+ (count, requirement) =>
+ count +
+ requirement.services.filter(
+ (service) =>
+ !connectors.some(
+ (connection) =>
+ connection.id === requirement.bindings[service]?.connectorId &&
+ connection.isEnabled &&
+ connection.mcpConnectionType === 'http' &&
+ connection.mcpServerUrl,
+ ),
+ ).length,
+ 0,
+ );
+ return (
+ <Block padding={16} variant="outlined">
+ <Flexbox gap={8}>
+ <Flexbox horizontal align="center" gap={12} justify="space-between" wrap="wrap">
+ <Flexbox gap={4}>
+ <Text weight={600}>{t('connections.title')}</Text>
+ <Text type="secondary">
+ {missing === undefined
+ ? t('connections.checking')
+ : missing
+ ? t('connections.missing', { count: missing })
+ : t('connections.configured')}
+ </Text>
+ </Flexbox>
+ <Button
+ aria-controls={detailsId}
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {t(expanded ? 'connections.hideDetails' : 'connections.showDetails')}
+ </Button>
+ </Flexbox>
+ {!!connectorError && (
+ <AsyncError
+ error={connectorError}
+ variant="inline"
+ onRetry={() => void refreshConnectors()}
+ />
+ )}
+ {expanded && (
+ <Flexbox gap={12} id={detailsId}>
+ {editable && (
+ <Flexbox horizontal justify="flex-end">
+ <Button onClick={() => setEditing(true)}>{t('connections.manage')}</Button>
+ </Flexbox>
+ )}
+ {connectors?.length === 0 && <Text type="secondary">{t('connections.empty')}</Text>}
+ <Flexbox gap={16} style={{ maxHeight: 400, overflowY: 'auto' }}>
+ {(connectors ?? []).map((connection) => {
+ const usages = requirements.filter((requirement) =>
+ Object.values(requirement.bindings).some(
+ (binding) => binding.connectorId === connection.id,
+ ),
+ );
+ return (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={12}
+ justify="space-between"
+ key={connection.id}
+ wrap="wrap"
+ >
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflowWrap: 'anywhere' }}>
+ <Text>{connection.name}</Text>
+ {!connection.isEnabled && (
+ <Text type="secondary">{t('connections.disabled')}</Text>
+ )}
+ <Text fontSize={13} type="secondary">
+ {connection.mcpServerUrl ?? '--'}
+ </Text>
+ <Text fontSize={13} type="secondary">
+ {t(
+ connection.hasCredentials
+ ? 'connections.authSaved'
+ : 'connections.authNone',
+ )}
+ {' · '}
+ {t(
+ connection.status === 'connected'
+ ? 'connections.statusConnected'
+ : connection.status === 'error'
+ ? 'connections.statusError'
+ : 'connections.statusDisconnected',
+ )}
+ </Text>
+ <Text fontSize={13} type="secondary">
+ {usages.length
+ ? usages.map((item) => item.name).join(' · ')
+ : t('connections.unbound')}
+ </Text>
+ </Flexbox>
+ {editable && (
+ <Button
+ onClick={() =>
+ openConnectionEditor({
+ datasetId,
+ id: connection.id,
+ onSaved: async () => {
+ await Promise.all([mutate(), refreshConnectors()]);
+ },
+ title: connection.name,
+ })
+ }
+ >
+ {t('connections.edit')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ {editable && (
+ <Button
+ onClick={() =>
+ openConnectionEditor({
+ datasetId,
+ onSaved: refreshConnectors,
+ title: t('connections.create'),
+ })
+ }
+ >
+ {t('connections.create')}
+ </Button>
+ )}
+ <Text fontSize={13} type="secondary">
+ {t('connections.datasetHint')}
+ </Text>
+ </Flexbox>
+ )}
+ {editing && (
+ <DatasetConnectionsEditor
+ datasetId={datasetId}
+ requirements={requirements}
+ onClose={() => setEditing(false)}
+ onSaved={async () => {
+ await Promise.all([mutate(), refreshConnectors()]);
+ }}
+ />
+ )}
+ </Flexbox>
+ </Block>
+ );
+};
diff --git a/src/features/AgentEval/ConnectorBindings/bindings.test.ts b/src/features/AgentEval/ConnectorBindings/bindings.test.ts
new file mode 100644
index 00000000000..c7d35bc5866
--- /dev/null
+++ b/src/features/AgentEval/ConnectorBindings/bindings.test.ts
@@ -0,0 +1,45 @@
+import type { AgentEvalDatasetPackageConnectionRequirement } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { hasPartialConnectorBindings, setConnectorBinding } from './bindings';
+
+const environment: AgentEvalDatasetPackageConnectionRequirement = {
+ key: 'shared-key',
+ name: 'Mail and calendar',
+ scope: 'environment',
+ services: ['gmail', 'calendar'],
+};
+const testcase: AgentEvalDatasetPackageConnectionRequirement = { ...environment, scope: 'case' };
+const connection = { connectorId: 'connection-a', transport: 'mcp' as const };
+
+describe('dataset connector selection', () => {
+ it('leaves automatic or deferred package bindings untouched until the user selects a connection', () => {
+ expect(hasPartialConnectorBindings([environment], {})).toBe(false);
+ const partial = setConnectorBinding({}, environment, 'gmail', connection);
+ expect(hasPartialConnectorBindings([environment], partial)).toBe(true);
+ const complete = setConnectorBinding(partial, environment, 'calendar', connection);
+ expect(hasPartialConnectorBindings([environment], complete)).toBe(false);
+ });
+
+ it('isolates case and environment scopes even when their portable keys are identical', () => {
+ const original = {
+ environmentBindings: { 'shared-key': { gmail: connection, calendar: connection } },
+ };
+ const changed = setConnectorBinding(original, testcase, 'gmail', {
+ connectorId: 'connection-b',
+ });
+ expect(changed.environmentBindings).toEqual(original.environmentBindings);
+ expect(changed.caseBindings?.['shared-key'].gmail.connectorId).toBe('connection-b');
+ expect(original).not.toHaveProperty('caseBindings');
+ });
+
+ it('clearing the last selection restores omitted import scope instead of sending an incomplete replacement', () => {
+ const selected = setConnectorBinding({}, environment, 'gmail', connection);
+ const cleared = setConnectorBinding(selected, environment, 'gmail');
+ expect(cleared.environmentBindings).not.toHaveProperty('shared-key');
+ expect(hasPartialConnectorBindings([environment], cleared)).toBe(false);
+ expect(
+ hasPartialConnectorBindings([environment], { environmentBindings: { 'shared-key': {} } }),
+ ).toBe(true);
+ });
+});
diff --git a/src/features/AgentEval/ConnectorBindings/bindings.ts b/src/features/AgentEval/ConnectorBindings/bindings.ts
new file mode 100644
index 00000000000..75c6a361c88
--- /dev/null
+++ b/src/features/AgentEval/ConnectorBindings/bindings.ts
@@ -0,0 +1,34 @@
+import type {
+ AgentEvalDatasetPackageBindings,
+ AgentEvalDatasetPackageConnectionRequirement,
+ EvalConnectorBinding,
+} from '@lobechat/types';
+
+export const setConnectorBinding = (
+ value: AgentEvalDatasetPackageBindings,
+ requirement: AgentEvalDatasetPackageConnectionRequirement,
+ service: string,
+ binding?: EvalConnectorBinding,
+): AgentEvalDatasetPackageBindings => {
+ const scope = requirement.scope === 'environment' ? 'environmentBindings' : 'caseBindings';
+ const next = { ...value[scope]?.[requirement.key] };
+ if (binding) next[service] = binding;
+ else delete next[service];
+ const groups = { ...value[scope] };
+ if (Object.keys(next).length) groups[requirement.key] = next;
+ else delete groups[requirement.key];
+ return { ...value, [scope]: groups };
+};
+
+/** Import overrides replace one complete scope. An untouched scope uses the package or stays unbound. */
+export const hasPartialConnectorBindings = (
+ requirements: AgentEvalDatasetPackageConnectionRequirement[],
+ value: AgentEvalDatasetPackageBindings,
+) =>
+ requirements.some((requirement) => {
+ const bindings =
+ value[requirement.scope === 'environment' ? 'environmentBindings' : 'caseBindings']?.[
+ requirement.key
+ ];
+ return !!bindings && requirement.services.some((service) => !bindings[service]?.connectorId);
+ });
diff --git a/src/features/AgentEval/ConnectorBindings/index.tsx b/src/features/AgentEval/ConnectorBindings/index.tsx
new file mode 100644
index 00000000000..043d071977a
--- /dev/null
+++ b/src/features/AgentEval/ConnectorBindings/index.tsx
@@ -0,0 +1,169 @@
+'use client';
+
+import type {
+ AgentEvalDatasetPackageBindings,
+ AgentEvalDatasetPackageConnectionRequirement,
+} from '@lobechat/types';
+import { Button, Flexbox, Select, Spin, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { useId } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { useEvalStore } from '@/store/eval';
+
+import { setConnectorBinding } from './bindings';
+import { openConnectionEditor } from './ConnectionEditor';
+
+const styles = stylex.create({ groups: { maxHeight: 400, overflowY: 'auto' } });
+
+interface ConnectorBindingsProps {
+ datasetId?: string;
+ disabled?: boolean;
+ onChange: (bindings: AgentEvalDatasetPackageBindings) => void;
+ requirements: AgentEvalDatasetPackageConnectionRequirement[];
+ value: AgentEvalDatasetPackageBindings;
+}
+
+/** Only exact connection IDs cross this form. URL and credentials stay in the connection manager. */
+export const ConnectorBindings = ({
+ datasetId,
+ disabled,
+ onChange,
+ requirements,
+ value,
+}: ConnectorBindingsProps) => {
+ const { t } = useTranslation('eval');
+ const id = useId();
+ const fetchConnectors = useEvalStore((s) => s.useFetchEvalConnectors);
+ const { data, error, isLoading, isValidating, mutate } = fetchConnectors(datasetId);
+ const available = data?.filter(
+ (connection) =>
+ connection.isEnabled && connection.mcpConnectionType === 'http' && connection.mcpServerUrl,
+ );
+
+ if (!datasetId) return <Text type="secondary">{t('connections.datasetOnly')}</Text>;
+
+ return (
+ <Flexbox gap={12}>
+ <Text fontSize={13} type="secondary">
+ {t('connections.hint')}
+ </Text>
+ {!!error && (
+ <AsyncError
+ error={error}
+ retrying={isValidating}
+ variant="inline"
+ onRetry={() => void mutate()}
+ />
+ )}
+ {isLoading && !data ? (
+ <Spin />
+ ) : (
+ <Flexbox className={stylex.props(styles.groups).className} gap={20}>
+ {requirements.map((requirement, groupIndex) => {
+ const bindings =
+ value[requirement.scope === 'environment' ? 'environmentBindings' : 'caseBindings']?.[
+ requirement.key
+ ];
+ return (
+ <Flexbox gap={8} key={`${requirement.scope}:${requirement.key}`}>
+ <Text weight={500}>
+ {requirement.name} ·{' '}
+ {t(
+ requirement.scope === 'environment'
+ ? 'connections.environment'
+ : 'connections.case',
+ )}
+ </Text>
+ {requirement.services.map((service, index) => {
+ const binding = bindings?.[service];
+ const provided = requirement.providedServices?.includes(service);
+ const missing =
+ !!binding &&
+ !available?.some((connection) => connection.id === binding.connectorId);
+ const fieldId = `${id}-${groupIndex}-${index}`;
+ return (
+ <Flexbox gap={6} key={service}>
+ <label htmlFor={fieldId}>{service}</label>
+ <Select
+ disabled={disabled || (!data && !!error)}
+ id={fieldId}
+ value={binding?.connectorId ?? ''}
+ options={[
+ {
+ label: t(
+ provided ? 'connections.fromPackage' : 'connections.configureLater',
+ ),
+ value: '',
+ },
+ ...(missing
+ ? [{ label: t('connections.unavailable'), value: binding.connectorId }]
+ : []),
+ ...(available ?? []).map((connection) => ({
+ label: connection.name,
+ value: connection.id,
+ })),
+ ]}
+ onChange={(connectorId) =>
+ onChange(
+ setConnectorBinding(
+ value,
+ requirement,
+ service,
+ connectorId
+ ? {
+ connectorId: String(connectorId),
+ transport: binding?.transport ?? 'mcp',
+ }
+ : undefined,
+ ),
+ )
+ }
+ />
+ {binding && (
+ <Select
+ aria-label={t('connections.transport', { service })}
+ disabled={disabled}
+ value={binding.transport ?? 'mcp'}
+ options={[
+ { label: t('connections.standard'), value: 'mcp' },
+ { label: t('connections.adapter'), value: 'lobe-bench' },
+ ]}
+ onChange={(transport) =>
+ onChange(
+ setConnectorBinding(value, requirement, service, {
+ ...binding,
+ transport: transport as 'mcp' | 'lobe-bench',
+ }),
+ )
+ }
+ />
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ )}
+ {!isLoading && available?.length === 0 && (
+ <Text type="secondary">{t('connections.empty')}</Text>
+ )}
+ <Flexbox horizontal gap={8} wrap="wrap">
+ <Button
+ disabled={disabled}
+ onClick={() =>
+ openConnectionEditor({ datasetId, onSaved: mutate, title: t('connections.create') })
+ }
+ >
+ {t('connections.create')}
+ </Button>
+ <Button disabled={disabled} loading={isValidating} onClick={() => void mutate()}>
+ {t('connections.refresh')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/features/AgentEval/DatasetPackagePreview/importError.test.ts b/src/features/AgentEval/DatasetPackagePreview/importError.test.ts
new file mode 100644
index 00000000000..e4205af9b60
--- /dev/null
+++ b/src/features/AgentEval/DatasetPackagePreview/importError.test.ts
@@ -0,0 +1,22 @@
+import { TRPCClientError } from '@trpc/client';
+import { describe, expect, it } from 'vitest';
+
+import { datasetImportErrorMessage } from './importError';
+
+describe('dataset import feedback', () => {
+ it('keeps actionable package validation and permission messages', () => {
+ for (const code of ['BAD_REQUEST', 'FORBIDDEN']) {
+ const error = Object.assign(new TRPCClientError('Use a new dataset'), { data: { code } });
+ expect(datasetImportErrorMessage(error, 'Try again')).toBe('Use a new dataset');
+ }
+ });
+ it('hides internal database and transport details behind localized feedback', () => {
+ const error = Object.assign(new TRPCClientError('internal SQL detail'), {
+ data: { code: 'INTERNAL_SERVER_ERROR' },
+ });
+ expect(datasetImportErrorMessage(error, 'Try again')).toBe('Try again');
+ expect(datasetImportErrorMessage(new Error('private storage endpoint'), 'Try again')).toBe(
+ 'Try again',
+ );
+ });
+});
diff --git a/src/features/AgentEval/DatasetPackagePreview/importError.ts b/src/features/AgentEval/DatasetPackagePreview/importError.ts
new file mode 100644
index 00000000000..68b9d1e9c7b
--- /dev/null
+++ b/src/features/AgentEval/DatasetPackagePreview/importError.ts
@@ -0,0 +1,8 @@
+import { TRPCClientError } from '@trpc/client';
+
+/** Only intentional validation/permission messages are safe to show verbatim. */
+export const datasetImportErrorMessage = (error: unknown, fallback: string) =>
+ error instanceof TRPCClientError &&
+ (error.data?.code === 'BAD_REQUEST' || error.data?.code === 'FORBIDDEN')
+ ? error.message
+ : fallback;
diff --git a/src/features/AgentEval/DatasetPackagePreview/index.tsx b/src/features/AgentEval/DatasetPackagePreview/index.tsx
new file mode 100644
index 00000000000..0f4fcec3146
--- /dev/null
+++ b/src/features/AgentEval/DatasetPackagePreview/index.tsx
@@ -0,0 +1,157 @@
+'use client';
+
+import type {
+ AgentEvalDatasetPackageBindings,
+ AgentEvalDatasetPackagePreview,
+} from '@lobechat/types';
+import { Accordion, Flexbox, Input, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useId } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ConnectorBindings } from '@/features/AgentEval/ConnectorBindings';
+import { hasPartialConnectorBindings } from '@/features/AgentEval/ConnectorBindings/bindings';
+
+const styles = stylex.create({
+ sample: {
+ borderBlockStartWidth: 1,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ paddingBlockStart: 12,
+ whiteSpace: 'pre-wrap',
+ overflowWrap: 'anywhere',
+ },
+ samples: { maxHeight: 200, overflowY: 'auto' },
+});
+
+interface DatasetPackagePreviewProps {
+ bindings: AgentEvalDatasetPackageBindings;
+ datasetId?: string;
+ disabled?: boolean;
+ existingDataset?: boolean;
+ name: string;
+ onBindingsChange: (bindings: AgentEvalDatasetPackageBindings) => void;
+ onNameChange: (name: string) => void;
+ preview: AgentEvalDatasetPackagePreview;
+ samples: Array<{ input?: unknown }>;
+}
+
+/** A structured package already contains its case fields, rules and environments. */
+export const DatasetPackagePreview = ({
+ bindings,
+ onBindingsChange,
+ datasetId,
+ disabled,
+ existingDataset,
+ name,
+ onNameChange,
+ preview,
+ samples,
+}: DatasetPackagePreviewProps) => {
+ const { t } = useTranslation('eval');
+ const id = useId();
+
+ return (
+ <Flexbox gap={20}>
+ <Flexbox gap={8}>
+ <Text weight={600}>{t('dataset.import.package.preview')}</Text>
+ {preview.description && <Text type="secondary">{preview.description}</Text>}
+ <Flexbox horizontal gap={8} wrap="wrap">
+ <Tag>{t('dataset.import.package.cases', { count: preview.caseCount })}</Tag>
+ <Tag>{t('dataset.import.package.environments', { count: preview.environmentCount })}</Tag>
+ {preview.release && (
+ <Tag>{t('lobeBench.dataset.release', { release: preview.release })}</Tag>
+ )}
+ </Flexbox>
+ <Text fontSize={13} type="secondary">
+ {t('dataset.import.package.preserved')}
+ </Text>
+ {preview.mockServices.length > 0 && (
+ <Text fontSize={13} type="secondary">
+ {t('dataset.import.package.mockServices', {
+ services: preview.mockServices.join(', '),
+ })}
+ </Text>
+ )}
+ </Flexbox>
+
+ {!!preview.embeddedConnections?.length && (
+ <Flexbox gap={8}>
+ <Text weight={500}>{t('connections.included')}</Text>
+ <Text fontSize={13} type="secondary">
+ {t('connections.autoImport')}
+ </Text>
+ {preview.embeddedConnections.map((connection) => (
+ <Flexbox horizontal gap={8} key={connection.key} wrap="wrap">
+ <Text>{connection.name}</Text>
+ <Tag>
+ {t(connection.authConfigured ? 'connections.authIncluded' : 'connections.noAuth')}
+ </Tag>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ {preview.connectionRequirements.some((requirement) =>
+ requirement.services.some((service) => !requirement.providedServices?.includes(service)),
+ ) && <Text type="secondary">{t('connections.importLater')}</Text>}
+ {preview.connectionRequirements.some(
+ (requirement) => !requirement.providedServices?.length,
+ ) && (
+ <Flexbox gap={8}>
+ {hasPartialConnectorBindings(preview.connectionRequirements, bindings) && (
+ <Text type="danger">{t('connections.completeScope')}</Text>
+ )}
+ <Accordion
+ items={[
+ {
+ key: 'connections',
+ title: t('connections.optional'),
+ children: (
+ <ConnectorBindings
+ datasetId={datasetId}
+ disabled={disabled}
+ value={bindings}
+ requirements={preview.connectionRequirements.filter(
+ (requirement) => !requirement.providedServices?.length,
+ )}
+ onChange={onBindingsChange}
+ />
+ ),
+ },
+ ]}
+ />
+ </Flexbox>
+ )}
+
+ {!existingDataset && (
+ <>
+ <Flexbox gap={8}>
+ <label htmlFor={`${id}-name`}>{t('dataset.import.package.name')}</label>
+ <Input
+ disabled={disabled}
+ id={`${id}-name`}
+ maxLength={200}
+ value={name}
+ onChange={(e) => onNameChange(e.target.value)}
+ />
+ </Flexbox>
+ </>
+ )}
+
+ <Flexbox gap={12}>
+ <Text weight={500}>{t('dataset.import.preview')}</Text>
+ <Flexbox className={stylex.props(styles.samples).className} gap={12}>
+ {samples.slice(0, 3).map((sample, index) => (
+ <Text className={stylex.props(styles.sample).className} fontSize={13} key={index}>
+ {String(sample.input ?? '')}
+ </Text>
+ ))}
+ </Flexbox>
+ <Text fontSize={13} type="secondary">
+ {t('dataset.import.package.history')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/features/Eval/caseDifficulty.test.ts b/src/features/Eval/caseDifficulty.test.ts
new file mode 100644
index 00000000000..2f77d98325b
--- /dev/null
+++ b/src/features/Eval/caseDifficulty.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ CASE_LEVELS,
+ getCaseDifficulty,
+ getCaseLevel,
+ levelFromScore,
+ levelLabelKey,
+ levelTagColor,
+ resolveCaseDifficulty,
+} from './caseDifficulty';
+
+describe('levelFromScore', () => {
+ it.each([
+ [0, 'L1'],
+ [1, 'L1'],
+ [2, 'L2'],
+ [3, 'L2'],
+ [4, 'L3'],
+ [5, 'L3'],
+ [6, 'L4'],
+ [7, 'L4'],
+ [12, 'L4'],
+ ])('maps a release difficulty score of %i to %s', (score, level) => {
+ expect(levelFromScore(score)).toBe(level);
+ });
+});
+
+describe('resolveCaseDifficulty', () => {
+ it('reads the tier from the release difficulty score before any label', () => {
+ expect(
+ resolveCaseDifficulty({
+ difficulty: { level: 'Advanced', score: 7, signals: ['x'] },
+ level: 'Advanced',
+ }),
+ ).toEqual({ kind: 'level', level: 'L4' });
+ expect(resolveCaseDifficulty({ difficulty: { level: 'Advanced', score: 4 } })).toEqual({
+ kind: 'level',
+ level: 'L3',
+ });
+ });
+
+ it.each(CASE_LEVELS)('reads a top-level %s without requiring difficulty details', (level) => {
+ expect(resolveCaseDifficulty({ level })).toEqual({ kind: 'level', level });
+ });
+
+ it.each([
+ ['Starter', 'L1'],
+ ['Intermediate', 'L2'],
+ ['Advanced', 'L3'],
+ ])('maps the legacy release label %s to %s when there is no score', (legacy, level) => {
+ expect(resolveCaseDifficulty({ level: legacy })).toEqual({ kind: 'level', level });
+ expect(resolveCaseDifficulty({ difficulty: { level: legacy } })).toEqual({
+ kind: 'level',
+ level,
+ });
+ });
+
+ it.each(['easy', 'medium', 'hard'] as const)(
+ 'preserves the legacy %s classification',
+ (value) => {
+ expect(resolveCaseDifficulty({ difficulty: value })).toEqual({ kind: 'legacy', value });
+ },
+ );
+
+ it('falls back past an unknown top-level level to supported difficulty metadata', () => {
+ expect(resolveCaseDifficulty({ difficulty: { level: 'Advanced' }, level: 'unknown' })).toEqual({
+ kind: 'level',
+ level: 'L3',
+ });
+ expect(resolveCaseDifficulty({ difficulty: 'easy', level: 'unknown' })).toEqual({
+ kind: 'legacy',
+ value: 'easy',
+ });
+ });
+
+ it.each([
+ undefined,
+ null,
+ false,
+ 1,
+ 'easy',
+ [],
+ {},
+ { difficulty: null },
+ { difficulty: [] },
+ { difficulty: {} },
+ { difficulty: { level: {} } },
+ { difficulty: { level: 'starter' } },
+ { difficulty: { level: 'easy' } },
+ { difficulty: 'Starter' },
+ { difficulty: 'unknown' },
+ { level: 'advanced' },
+ ])('does not render a label for unsupported metadata: %j', (metadata) => {
+ expect(resolveCaseDifficulty(metadata)).toBeUndefined();
+ });
+});
+
+describe('shared release difficulty helpers', () => {
+ it('keeps level, detail and label behavior for LobeBench callers', () => {
+ const details = { level: 'Advanced', score: 4, signals: ['tool use'] };
+ const testCase = { metadata: { difficulty: details, level: 'Starter' } };
+ expect(getCaseLevel(testCase)).toBe('L3');
+ expect(getCaseDifficulty(testCase)).toEqual(details);
+ expect(getCaseLevel({ metadata: { level: 'Starter' } })).toBe('L1');
+ expect(levelLabelKey('L1')).toBe('lobeBench.case.level.L1');
+ expect(levelTagColor('L1')).toBe('success');
+ expect(levelTagColor('L2')).toBe('processing');
+ expect(levelTagColor('L3')).toBe('warning');
+ expect(levelTagColor('L4')).toBe('error');
+ expect(getCaseLevel({ metadata: { difficulty: { score: 4 } } })).toBe('L3');
+ expect(getCaseDifficulty({ metadata: { difficulty: 'easy' } })).toBeUndefined();
+ });
+});
diff --git a/src/features/Eval/caseDifficulty.ts b/src/features/Eval/caseDifficulty.ts
new file mode 100644
index 00000000000..7349f59e7d8
--- /dev/null
+++ b/src/features/Eval/caseDifficulty.ts
@@ -0,0 +1,78 @@
+/** Four tiers, L1 (easiest) to L4, read from the release's difficulty score. */
+export const CASE_LEVELS = ['L1', 'L2', 'L3', 'L4'] as const;
+export type CaseLevel = (typeof CASE_LEVELS)[number];
+
+/**
+ * The release grades a case by counting contract signals (calls in order,
+ * services spanned, injected failure, forbidden calls, conversation context,
+ * Memory fixture, rule count, procedure length). The score maps to a tier:
+ * L1 ≤ 1 · L2 2–3 · L3 4–5 · L4 ≥ 6.
+ */
+export const levelFromScore = (score: number): CaseLevel =>
+ score <= 1 ? 'L1' : score <= 3 ? 'L2' : score <= 5 ? 'L3' : 'L4';
+
+/** Labels older releases wrote; without a score an "Advanced" case cannot be split into L3/L4. */
+const LEGACY_LEVELS: Record<string, CaseLevel> = {
+ Advanced: 'L3',
+ Intermediate: 'L2',
+ Starter: 'L1',
+};
+
+interface CaseWithDifficulty {
+ metadata?: unknown;
+}
+
+interface CaseDifficultyDetails {
+ level?: string;
+ score?: number;
+ signals?: string[];
+}
+
+export type CaseDifficultyLabel =
+ { kind: 'level'; level: CaseLevel } | { kind: 'legacy'; value: 'easy' | 'hard' | 'medium' };
+
+const asRecord = (value: unknown): Record<string, unknown> | undefined =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+
+const isCaseLevel = (value: unknown): value is CaseLevel =>
+ CASE_LEVELS.includes(value as CaseLevel);
+
+const toLevel = (value: unknown): CaseLevel | undefined =>
+ isCaseLevel(value) ? value : typeof value === 'string' ? LEGACY_LEVELS[value] : undefined;
+
+/**
+ * The case's tier: from the release's difficulty score when it carries one,
+ * otherwise from the level label the release wrote (legacy names included).
+ */
+export const getCaseLevel = (testCase: CaseWithDifficulty): CaseLevel | undefined => {
+ const metadata = asRecord(testCase.metadata);
+ const details = asRecord(metadata?.difficulty);
+ if (typeof details?.score === 'number') return levelFromScore(details.score);
+ return toLevel(metadata?.level) ?? toLevel(details?.level);
+};
+
+/** Why the case got its level: the contract signals the release's rubric counted. */
+export const getCaseDifficulty = (
+ testCase: CaseWithDifficulty,
+): CaseDifficultyDetails | undefined =>
+ asRecord(asRecord(testCase.metadata)?.difficulty) as CaseDifficultyDetails | undefined;
+
+/** Keep release levels and legacy easy/medium/hard labels as distinct classifications. */
+export const resolveCaseDifficulty = (metadata: unknown): CaseDifficultyLabel | undefined => {
+ const level = getCaseLevel({ metadata });
+ if (level) return { kind: 'level', level };
+
+ const legacy = asRecord(metadata)?.difficulty;
+ if (legacy === 'easy' || legacy === 'medium' || legacy === 'hard') {
+ return { kind: 'legacy', value: legacy };
+ }
+ return undefined;
+};
+
+/** The translation key of a level's label (typed, so `t` accepts it). */
+export const levelLabelKey = (level: CaseLevel) => `lobeBench.case.level.${level}` as const;
+
+export const levelTagColor = (level: CaseLevel) =>
+ level === 'L1' ? 'success' : level === 'L2' ? 'processing' : level === 'L3' ? 'warning' : 'error';
diff --git a/src/features/Eval/judgeError.test.ts b/src/features/Eval/judgeError.test.ts
new file mode 100644
index 00000000000..fd991d55449
--- /dev/null
+++ b/src/features/Eval/judgeError.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { getJudgeFailure } from './judgeError';
+
+describe('trajectory Judge failure display', () => {
+ it('shows the dedicated grading diagnostic before an older execution error', () => {
+ expect(
+ getJudgeFailure('judge_error', { judgeError: 'Judge unavailable', error: 'Old error' }),
+ ).toEqual({ diagnostic: 'Judge unavailable' });
+ });
+
+ it('recognizes thread Judge errors without a topic errorPhase and does not need a reason to flag them', () => {
+ expect(getJudgeFailure('judge_error')).toEqual({ diagnostic: undefined });
+ expect(
+ getJudgeFailure('passed', { errorPhase: 'judge', judgeError: 'Protocol failure' }),
+ ).toEqual({ diagnostic: 'Protocol failure' });
+ });
+
+ it('does not replace genuine model failures or execution errors with grading failures', () => {
+ expect(getJudgeFailure('failed', { error: 'Step cap' })).toBeUndefined();
+ expect(getJudgeFailure('error', { error: 'Provider unavailable' })).toBeUndefined();
+ expect(getJudgeFailure('passed')).toBeUndefined();
+ });
+});
diff --git a/src/features/Eval/judgeError.ts b/src/features/Eval/judgeError.ts
new file mode 100644
index 00000000000..a86b672a235
--- /dev/null
+++ b/src/features/Eval/judgeError.ts
@@ -0,0 +1,11 @@
+interface JudgeResult {
+ error?: string;
+ errorPhase?: string;
+ judgeError?: string;
+}
+
+/** A Judge fault is a diagnostic about grading, not a zero-score candidate answer. */
+export const getJudgeFailure = (status: string | null | undefined, result?: JudgeResult | null) =>
+ status === 'judge_error' || result?.errorPhase === 'judge'
+ ? { diagnostic: result?.judgeError ?? result?.error }
+ : undefined;
diff --git a/src/features/LobeBench/AreaSwitch.tsx b/src/features/LobeBench/AreaSwitch.tsx
new file mode 100644
index 00000000000..eb0887ecc93
--- /dev/null
+++ b/src/features/LobeBench/AreaSwitch.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { Segmented } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { LOBE_BENCH_PATH } from '@/features/LobeBench/lobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+export type EvalArea = 'agent' | 'bench';
+
+/**
+ * The switch between the two eval areas: "Agent Eval" tests the user's own
+ * Agents on their own cases; "Lobe Bench" compares models on LobeHub's
+ * standard cases. Both live under `/eval`.
+ */
+const AreaSwitch = memo<{ active: EvalArea }>(({ active }) => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+
+ return (
+ <Segmented
+ size={'small'}
+ value={active}
+ options={[
+ { label: t('lobeBench.switch.agent'), value: 'agent' },
+ { label: t('lobeBench.switch.bench'), value: 'bench' },
+ ]}
+ onChange={(value) => navigate(value === 'bench' ? LOBE_BENCH_PATH : '/eval')}
+ />
+ );
+});
+
+AreaSwitch.displayName = 'EvalAreaSwitch';
+
+export default AreaSwitch;
diff --git a/src/features/LobeBench/Benchmark/index.tsx b/src/features/LobeBench/Benchmark/index.tsx
new file mode 100644
index 00000000000..71536a1d97c
--- /dev/null
+++ b/src/features/LobeBench/Benchmark/index.tsx
@@ -0,0 +1,243 @@
+'use client';
+
+import { Button, Empty, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Database, Plus } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { getBenchmarkIcon } from '@/features/LobeBench/benchmarkIcon';
+import ContenderRanking from '@/features/LobeBench/ContenderRanking';
+import {
+ benchmarkDatasetsOf,
+ caseCountOf,
+ getDatasetMeta,
+ isCustomBenchmark,
+ isRunActive,
+ LOBE_BENCH_PATH,
+ rankableSetsOf,
+ sortBenchmarks,
+} from '@/features/LobeBench/lobeBench';
+import RunsSection from '@/features/LobeBench/RunsSection';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchExperiments,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import BenchmarkTitleBar from '@/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/TitleBar';
+import { useEvalStore } from '@/store/eval';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ sectionTitle: {
+ margin: 0,
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+ datasetGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))',
+ gap: 12,
+ },
+ datasetCard: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 12,
+ paddingBlock: 12,
+ paddingInline: 16,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ color: cssVar.colorText,
+ backgroundColor: {
+ 'default': 'transparent',
+ ':hover': cssVar.colorFillQuaternary,
+ },
+ },
+ filterEmpty: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: 48,
+ paddingInline: 24,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+});
+
+/**
+ * One Lobe Bench benchmark. It opens on what the benchmark is for: the models
+ * ranked by their completed runs, under the same title row as the Evaluation
+ * Lab's page. The datasets it is made of follow (a benchmark is made of
+ * datasets), then its runs.
+ */
+const LobeBenchBenchmark = memo(() => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const { benchmarkId } = useParams<{ benchmarkId: string }>();
+ const systemIcon = useMemo(() => getBenchmarkIcon(benchmarkId ?? ''), [benchmarkId]);
+
+ const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);
+ const benchmark = useEvalStore((s) =>
+ benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
+ );
+ const { isLoading } = useFetchBenchmarkDetail(benchmarkId);
+ // Datasets and runs are read across all of Lobe Bench: the library (and the
+ // mock settings every dataset shares) sits under another benchmark than Hard 50.
+ const { benchmarks: benchmarkList } = useLobeBenchBenchmarks();
+ const benchmarks = useMemo(() => sortBenchmarks(benchmarkList), [benchmarkList]);
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets, mutate: refreshDatasets } = useLobeBenchDatasets(benchmarkIds);
+ const { experiments } = useLobeBenchExperiments();
+ const hasActive = experiments.some((e) => e.recentRuns?.some((r) => isRunActive(r.status)));
+ const { data: allRuns, mutate: refreshRuns } = useLobeBenchRuns(benchmarkIds, {
+ refreshInterval: hasActive ? 5000 : undefined,
+ });
+ const listed = benchmarks.find((b) => b.id === benchmarkId);
+ // One the account made: its datasets are fixed when it is made, and it can be deleted.
+ const custom = isCustomBenchmark(listed);
+ const madeOf = useMemo(
+ () => (listed ? benchmarkDatasetsOf(datasets, listed) : []),
+ [datasets, listed],
+ );
+ const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
+ const sets = useMemo(() => rankableSetsOf(benchmarks, datasets), [benchmarks, datasets]);
+ const rankedSets = useMemo(
+ () => sets.filter((set) => set.benchmarkId === benchmarkId),
+ [benchmarkId, sets],
+ );
+ // The runs on this benchmark: every run on a dataset it is made of, as the
+ // Evaluation Lab lists them (one on some of the cases says so).
+ const runList = useMemo(
+ () => (allRuns ?? []).filter((run) => madeOf.some((dataset) => dataset.id === run.datasetId)),
+ [allRuns, madeOf],
+ );
+
+ // Deleting one the account made deletes its runs and keeps its datasets, freed
+ // to make another benchmark of (the server does both).
+ const handleDelete = async () => {
+ if (!benchmarkId) return;
+ await deleteBenchmark(benchmarkId);
+ navigate(LOBE_BENCH_PATH);
+ };
+
+ const handleBenchmarkUpdate = useCallback(async () => {
+ await refreshDatasets();
+ }, [refreshDatasets]);
+
+ if (!benchmark) {
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
+ {!isLoading && <Empty description={t('lobeBench.benchmark.notFound')} />}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={24}>
+ <BenchmarkTitleBar
+ benchmark={benchmark}
+ systemIcon={systemIcon}
+ deleteConfirm={
+ custom ? t('lobeBench.benchmark.delete.confirm', { name: benchmark.name }) : undefined
+ }
+ onBenchmarkUpdate={handleBenchmarkUpdate}
+ onDelete={custom ? handleDelete : undefined}
+ />
+
+ {/* A benchmark the account made with no dataset yet has nothing to rank. */}
+ {rankedSets.length > 0 && (
+ <ContenderRanking benchmarkId={benchmarkId!} runs={runList} sets={rankedSets} />
+ )}
+
+ {(madeOf.length > 0 || custom) && (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'flex-end'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4}>
+ <h3 className={stylex.props(styles.sectionTitle).className}>
+ {t('lobeBench.benchmark.datasets')}
+ </h3>
+ <Text type={'secondary'}>{t('lobeBench.benchmark.datasets.hint')}</Text>
+ </Flexbox>
+ </Flexbox>
+ {madeOf.length === 0 && (
+ <Flexbox className={stylex.props(styles.filterEmpty).className}>
+ <Text type={'secondary'}>{t('lobeBench.benchmark.datasets.empty')}</Text>
+ </Flexbox>
+ )}
+ <div className={stylex.props(styles.datasetGrid).className}>
+ {madeOf.map((dataset) => {
+ const release = getDatasetMeta(dataset).release;
+ return (
+ <WorkspaceLink
+ className={stylex.props(styles.datasetCard).className}
+ key={dataset.id}
+ to={`${LOBE_BENCH_PATH}/datasets/${dataset.id}`}
+ >
+ <Database size={18} style={{ color: cssVar.colorTextSecondary, flex: 'none' }} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {dataset.name}
+ </Text>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {[
+ t('lobeBench.benchmark.cases', { count: caseCountOf(dataset) }),
+ release && t('lobeBench.dataset.release', { release }),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </Text>
+ </Flexbox>
+ </WorkspaceLink>
+ );
+ })}
+ </div>
+ </Flexbox>
+ )}
+
+ <RunsSection
+ benchmarkId={benchmarkId}
+ countLabel={(count) => t('lobeBench.benchmark.runCount', { count })}
+ datasets={datasets}
+ emptyLabel={t('lobeBench.benchmark.noRunsYet')}
+ rankedSets={rankedSets}
+ runs={runList}
+ action={
+ <Button
+ icon={Plus}
+ size={'small'}
+ type={'primary'}
+ onClick={() =>
+ navigate(
+ madeOf[0]
+ ? `${LOBE_BENCH_PATH}/experiments/new?dataset=${madeOf[0].id}`
+ : `${LOBE_BENCH_PATH}/experiments/new`,
+ )
+ }
+ >
+ {t('lobeBench.benchmark.newExperiment')}
+ </Button>
+ }
+ onRefresh={refreshRuns}
+ />
+ </Flexbox>
+ );
+});
+
+LobeBenchBenchmark.displayName = 'LobeBenchBenchmark';
+
+export default LobeBenchBenchmark;
diff --git a/src/features/LobeBench/BenchmarkLeaderboard.tsx b/src/features/LobeBench/BenchmarkLeaderboard.tsx
new file mode 100644
index 00000000000..c8470f9b1f0
--- /dev/null
+++ b/src/features/LobeBench/BenchmarkLeaderboard.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { memo, useMemo } from 'react';
+
+import ContenderRanking from '@/features/LobeBench/ContenderRanking';
+import {
+ benchmarkDatasetsOf,
+ rankableSetsOf,
+ sortBenchmarks,
+} from '@/features/LobeBench/lobeBench';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+
+/**
+ * A Lobe Bench benchmark's leaderboard, read on its own: for pages that show
+ * the benchmark without the Lobe Bench workspace around it (the Evaluation
+ * Lab's benchmark page). Renders nothing until the benchmark has a dataset.
+ */
+const BenchmarkLeaderboard = memo<{ benchmarkId: string }>(({ benchmarkId }) => {
+ const { benchmarks: benchmarkList } = useLobeBenchBenchmarks();
+ const benchmarks = useMemo(() => sortBenchmarks(benchmarkList), [benchmarkList]);
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ const { data: allRuns } = useLobeBenchRuns(benchmarkIds);
+
+ const listed = benchmarks.find((b) => b.id === benchmarkId);
+ const madeOf = useMemo(
+ () => (listed ? benchmarkDatasetsOf(datasets, listed) : []),
+ [datasets, listed],
+ );
+ const sets = useMemo(
+ () => rankableSetsOf(benchmarks, datasets).filter((set) => set.benchmarkId === benchmarkId),
+ [benchmarkId, benchmarks, datasets],
+ );
+ const runs = useMemo(
+ () => (allRuns ?? []).filter((run) => madeOf.some((dataset) => dataset.id === run.datasetId)),
+ [allRuns, madeOf],
+ );
+
+ if (sets.length === 0) return null;
+ return <ContenderRanking benchmarkId={benchmarkId} runs={runs} sets={sets} />;
+});
+
+BenchmarkLeaderboard.displayName = 'BenchmarkLeaderboard';
+
+export default BenchmarkLeaderboard;
diff --git a/src/features/LobeBench/BenchmarkModal.tsx b/src/features/LobeBench/BenchmarkModal.tsx
new file mode 100644
index 00000000000..09fe464b167
--- /dev/null
+++ b/src/features/LobeBench/BenchmarkModal.tsx
@@ -0,0 +1,160 @@
+'use client';
+
+import {
+ Button,
+ createModal,
+ Flexbox,
+ Input,
+ Select,
+ Text,
+ TextArea,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import BenchmarkStandardFields, {
+ type BenchmarkStandard,
+ isCompleteStandard,
+} from '@/features/LobeBench/BenchmarkStandardFields';
+import { moveDatasets } from '@/features/LobeBench/datasetCases';
+import { caseCountOf, DEFAULT_PROTOCOL, LOBE_BENCH_KIND } from '@/features/LobeBench/lobeBench';
+import { useEvalStore } from '@/store/eval';
+
+interface DatasetOption {
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ testCaseCount?: number | null;
+}
+
+interface CreateBenchmarkFormProps {
+ /** The account's datasets in no benchmark of its own, that the new one can be made of. */
+ datasets: DatasetOption[];
+ onCreated?: (benchmarkId: string) => void;
+}
+
+/**
+ * Makes a benchmark of the account's own datasets, with the judge and run rules
+ * every run on it follows (fixed from then on, so its scores stay comparable).
+ * Datasets are made first, in the Case library; a benchmark only chooses among them.
+ */
+const CreateBenchmarkForm = memo<CreateBenchmarkFormProps>(({ datasets, onCreated }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const createBenchmark = useEvalStore((s) => s.createBenchmark);
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [picked, setPicked] = useState<string[]>([]);
+ const [standard, setStandard] = useState<BenchmarkStandard>({ protocol: DEFAULT_PROTOCOL });
+ const [saving, setSaving] = useState(false);
+
+ const submit = async () => {
+ const trimmed = name.trim();
+ const { judge, protocol } = standard;
+ if (!trimmed || !judge || !isCompleteStandard(standard) || picked.length === 0) return;
+ setSaving(true);
+ try {
+ const created = (await createBenchmark({
+ description: description.trim() || undefined,
+ identifier: `lobe-bench-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
+ metadata: {
+ judge: { model: judge.model, provider: judge.provider },
+ kind: LOBE_BENCH_KIND,
+ protocol,
+ },
+ name: trimmed,
+ })) as { data?: { id?: string }; id?: string };
+ const id = created?.id ?? created?.data?.id;
+ if (!id) throw new Error(t('lobeBench.benchmark.create.failed'));
+ await moveDatasets(
+ datasets.filter((dataset) => picked.includes(dataset.id)),
+ id,
+ );
+ close();
+ onCreated?.(id);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('lobeBench.benchmark.create.failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.benchmark.create.name')}</Text>
+ <Input
+ autoFocus
+ id={'lobe-bench-benchmark-name'}
+ placeholder={t('lobeBench.benchmark.create.name.placeholder')}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onPressEnter={submit}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.benchmark.create.description')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ id={'lobe-bench-benchmark-description'}
+ placeholder={t('lobeBench.benchmark.create.description.placeholder')}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Flexbox>
+ <BenchmarkStandardFields value={standard} onChange={setStandard} />
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.benchmark.create.datasets')}</Text>
+ {datasets.length > 0 ? (
+ <>
+ <Select
+ id={'lobe-bench-benchmark-datasets'}
+ mode={'multiple'}
+ placeholder={t('lobeBench.benchmark.create.datasets.placeholder')}
+ value={picked}
+ options={datasets.map((dataset) => ({
+ label: `${dataset.name} · ${t('lobeBench.new.dataset.cases', {
+ count: caseCountOf(dataset),
+ })}`,
+ value: dataset.id,
+ }))}
+ onChange={(value) => setPicked(value as string[])}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.benchmark.create.datasets.hint')}
+ </Text>
+ </>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.benchmark.create.datasets.empty')}
+ </Text>
+ )}
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('common.cancel')}</Button>
+ <Button
+ disabled={!name.trim() || !isCompleteStandard(standard) || picked.length === 0}
+ loading={saving}
+ type={'primary'}
+ onClick={submit}
+ >
+ {t('lobeBench.benchmark.create.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CreateBenchmarkForm.displayName = 'LobeBenchCreateBenchmarkForm';
+
+/** Opens the dialog that makes a benchmark of the account's datasets. */
+export const openCreateBenchmarkModal = (props: CreateBenchmarkFormProps) =>
+ createModal({
+ content: <CreateBenchmarkForm {...props} />,
+ footer: null,
+ title: translate('lobeBench.benchmark.create.title', { ns: 'eval' }),
+ width: 480,
+ });
diff --git a/src/features/LobeBench/BenchmarkStandardFields.tsx b/src/features/LobeBench/BenchmarkStandardFields.tsx
new file mode 100644
index 00000000000..e07476164fc
--- /dev/null
+++ b/src/features/LobeBench/BenchmarkStandardFields.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { Flexbox, InputNumber, Segmented, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { K_OPTIONS, type LobeBenchProtocol } from '@/features/LobeBench/lobeBench';
+import ModelSelect from '@/features/ModelSelect';
+
+export interface BenchmarkStandard {
+ judge?: { model: string; provider: string };
+ protocol: LobeBenchProtocol;
+}
+
+/** Whether a new benchmark's judge and run rules are all set. */
+export const isCompleteStandard = (value: BenchmarkStandard) =>
+ !!value.judge &&
+ value.protocol.k >= 1 &&
+ value.protocol.maxSteps >= 1 &&
+ value.protocol.timeoutMinutes >= 1;
+
+interface BenchmarkStandardFieldsProps {
+ disabled?: boolean;
+ onChange: (value: BenchmarkStandard) => void;
+ value: BenchmarkStandard;
+}
+
+/**
+ * What a new benchmark fixes for every run on it, so its scores stay
+ * comparable: the judge model, attempts per case, step limit and timeout.
+ * None of them can be changed afterwards, nor chosen per experiment.
+ */
+const BenchmarkStandardFields = memo<BenchmarkStandardFieldsProps>(
+ ({ disabled, onChange, value }) => {
+ const { t } = useTranslation('eval');
+ const setProtocol = (patch: Partial<LobeBenchProtocol>) =>
+ onChange({ ...value, protocol: { ...value.protocol, ...patch } });
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('lobeBench.benchmark.standard.title')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.benchmark.standard.hint')}
+ </Text>
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.benchmark.create.judge')}</Text>
+ <ModelSelect
+ disabled={disabled}
+ placeholder={t('lobeBench.benchmark.create.judge.placeholder')}
+ value={value.judge}
+ onChange={(judge) => onChange({ ...value, judge })}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.benchmark.standard.k')}</Text>
+ <Segmented
+ disabled={disabled}
+ value={String(value.protocol.k)}
+ options={K_OPTIONS.map((option) => ({
+ label: t('lobeBench.new.k.times', { k: option }),
+ value: String(option),
+ }))}
+ onChange={(k) => setProtocol({ k: Number(k) })}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={12}>
+ <Flexbox flex={1} gap={6}>
+ <Text fontSize={13}>{t('lobeBench.new.maxSteps')}</Text>
+ <InputNumber
+ disabled={disabled}
+ max={500}
+ min={1}
+ precision={0}
+ style={{ width: '100%' }}
+ value={value.protocol.maxSteps}
+ onChange={(maxSteps) => setProtocol({ maxSteps: Number(maxSteps) || 0 })}
+ />
+ </Flexbox>
+ <Flexbox flex={1} gap={6}>
+ <Text fontSize={13}>{t('lobeBench.new.timeout')}</Text>
+ <InputNumber
+ disabled={disabled}
+ max={240}
+ min={1}
+ precision={0}
+ style={{ width: '100%' }}
+ value={value.protocol.timeoutMinutes}
+ onChange={(timeoutMinutes) =>
+ setProtocol({ timeoutMinutes: Number(timeoutMinutes) || 0 })
+ }
+ />
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+BenchmarkStandardFields.displayName = 'LobeBenchBenchmarkStandardFields';
+
+export default BenchmarkStandardFields;
diff --git a/src/features/LobeBench/CaseEditor.tsx b/src/features/LobeBench/CaseEditor.tsx
new file mode 100644
index 00000000000..c8eb015ea1a
--- /dev/null
+++ b/src/features/LobeBench/CaseEditor.tsx
@@ -0,0 +1,372 @@
+'use client';
+
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import {
+ ActionIcon,
+ Button,
+ Drawer,
+ Flexbox,
+ Input,
+ Segmented,
+ Select,
+ Text,
+ TextArea,
+ toast,
+} from '@lobehub/ui';
+import { X } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { buildCaseContent } from '@/features/LobeBench/caseEditorContent';
+import { getCaseRules, getCaseTitle } from '@/features/LobeBench/lobeBench';
+import { type LobeBenchCase, ownEnvironmentOf } from '@/features/LobeBench/useLobeBench';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+type Role = 'assistant' | 'user';
+interface Turn {
+ content: string;
+ role: Role;
+}
+
+/** What a conversation draft (or a copy) pre-fills the editor with. */
+export interface CaseDraft {
+ category?: string;
+ environment?: EvalCaseEnvironment;
+ input?: string;
+ messages?: Turn[];
+ rules?: string[];
+ sessionDate?: string;
+ sourceTopicId?: string;
+ title?: string;
+}
+
+interface CaseEditorProps {
+ datasetId: string;
+ /** Pre-fills a new case; ignored when `testCase` is set. */
+ draft?: CaseDraft;
+ onClose: () => void;
+ onSaved: (testCase: { id: string }) => void;
+ open: boolean;
+ /** The case to edit; absent when creating one. */
+ testCase?: LobeBenchCase;
+}
+
+const joinList = (list?: string[]) => (list ?? []).join(', ');
+const splitList = (value: string) =>
+ value
+ .split(',')
+ .map((item) => item.trim())
+ .filter(Boolean);
+
+/**
+ * Creates or edits one case: the request, the earlier turns, the rules the
+ * judge checks, the shared environment it runs in and the few fields this
+ * case overrides on top of it.
+ */
+const CaseEditor = memo<CaseEditorProps>(
+ ({ datasetId, draft, onClose, onSaved, open, testCase }) => {
+ const { t } = useTranslation('eval');
+ const { data: environments } = useEvalStore.getState().useFetchEvalEnvironments();
+
+ const [title, setTitle] = useState('');
+ const [input, setInput] = useState('');
+ const [turns, setTurns] = useState<Turn[]>([]);
+ const [category, setCategory] = useState('');
+ const [rules, setRules] = useState('');
+ const [environmentId, setEnvironmentId] = useState('');
+ const [sessionDate, setSessionDate] = useState('');
+ const [timezone, setTimezone] = useState('');
+ const [persona, setPersona] = useState('');
+ const [plugins, setPlugins] = useState('');
+ const [mockServices, setMockServices] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // Load the case (or the draft) every time the drawer opens.
+ useEffect(() => {
+ if (!open) return;
+ const own = ((testCase ? ownEnvironmentOf(testCase) : draft?.environment) ??
+ {}) as EvalCaseEnvironment;
+ const turnsOf = (list?: Array<{ content: string; role: string }>) =>
+ (list ?? [])
+ .filter((m): m is Turn => m.role === 'user' || m.role === 'assistant')
+ .map((m) => ({ content: m.content, role: m.role }));
+ setTitle(
+ testCase
+ ? typeof testCase.metadata?.title === 'string'
+ ? testCase.metadata.title
+ : ''
+ : (draft?.title ?? ''),
+ );
+ setInput(testCase ? (testCase.content?.input ?? '') : (draft?.input ?? ''));
+ setTurns(turnsOf(testCase ? testCase.content?.messages : draft?.messages));
+ setCategory(testCase ? (testCase.content?.category ?? '') : (draft?.category ?? ''));
+ setRules(testCase ? getCaseRules(testCase).join('\n') : (draft?.rules ?? []).join('\n'));
+ setEnvironmentId(testCase?.environmentId ?? testCase?.environment?.id ?? '');
+ setSessionDate(own.sessionDate ?? draft?.sessionDate ?? '');
+ setTimezone(own.timezone ?? '');
+ setPersona(own.agent?.systemRole ?? '');
+ setPlugins(joinList(own.agent?.plugins));
+ setMockServices(joinList(own.mock?.services));
+ }, [open, testCase, draft]);
+
+ const save = async () => {
+ if (!input.trim()) return;
+ if (sessionDate.trim() && Number.isNaN(Date.parse(sessionDate.trim()))) {
+ toast.error(t('lobeBench.case.editor.invalidDate'));
+ return;
+ }
+ setSaving(true);
+ try {
+ const pluginList = splitList(plugins);
+ const services = splitList(mockServices);
+ const agent = {
+ ...(persona.trim() && { systemRole: persona.trim() }),
+ ...(plugins.trim() && { plugins: pluginList }),
+ };
+ const environment: EvalCaseEnvironment = {
+ ...(Object.keys(agent).length > 0 && { agent }),
+ ...(services.length > 0 && { mock: { services } }),
+ ...(sessionDate.trim() && { sessionDate: sessionDate.trim() }),
+ ...(timezone.trim() && { timezone: timezone.trim() }),
+ };
+ const ruleLines = rules
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const content = buildCaseContent({
+ category,
+ environment,
+ expected: testCase?.content?.expected,
+ input,
+ originalEnvironment: testCase ? ownEnvironmentOf(testCase) : draft?.environment,
+ originalMessages: testCase ? testCase.content?.messages : draft?.messages,
+ turns,
+ });
+ const evalConfig = ruleLines.length > 0 ? { judgePrompt: ruleLines.join('\n') } : null;
+ const evalMode = ruleLines.length > 0 ? ('rule-checklist' as const) : null;
+ const metadata = {
+ ...testCase?.metadata,
+ ...(draft?.sourceTopicId && !testCase && { sourceTopicId: draft.sourceTopicId }),
+ title: title.trim() || undefined,
+ };
+ if (testCase) {
+ await agentEvalService.updateTestCase({
+ content,
+ environmentId: environmentId || null,
+ evalConfig,
+ evalMode,
+ id: testCase.id,
+ metadata,
+ });
+ onSaved({ id: testCase.id });
+ } else {
+ const created = (await agentEvalService.createTestCase({
+ content,
+ datasetId,
+ environmentId: environmentId || null,
+ ...(evalConfig && { evalConfig }),
+ ...(evalMode && { evalMode }),
+ metadata,
+ })) as { id?: string; data?: { id?: string } };
+ onSaved({ id: created?.id ?? created?.data?.id ?? '' });
+ }
+ toast.success(t('lobeBench.case.editor.saved'));
+ onClose();
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const environmentOptions = [
+ { label: t('lobeBench.case.editor.environment.none'), value: '' },
+ ...(environments ?? []).map((environment) => ({
+ label: `${environment.name} · ${t('lobeBench.case.editor.environment.usedBy', {
+ count: environment.testCaseCount ?? 0,
+ })}`,
+ value: environment.id,
+ })),
+ ];
+
+ return (
+ <Drawer
+ open={open}
+ width={640}
+ title={
+ testCase
+ ? `${t('lobeBench.case.editor.edit')} · ${getCaseTitle(testCase)}`
+ : t('lobeBench.case.editor.new')
+ }
+ onClose={onClose}
+ >
+ <Flexbox gap={20}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.title')}</Text>
+ <Input value={title} variant={'filled'} onChange={(e) => setTitle(e.target.value)} />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.input')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 10, minRows: 3 }}
+ placeholder={t('lobeBench.case.editor.input.placeholder')}
+ value={input}
+ variant={'filled'}
+ onChange={(e) => setInput(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('lobeBench.case.editor.turns')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.editor.turns.hint')}
+ </Text>
+ </Flexbox>
+ {turns.map((turn, index) => (
+ <Flexbox gap={6} key={index}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Segmented
+ size={'small'}
+ value={turn.role}
+ options={[
+ { label: 'user', value: 'user' },
+ { label: 'assistant', value: 'assistant' },
+ ]}
+ onChange={(value) =>
+ setTurns((list) =>
+ list.map((item, i) =>
+ i === index ? { ...item, role: value as Role } : item,
+ ),
+ )
+ }
+ />
+ <ActionIcon
+ icon={X}
+ size={'small'}
+ onClick={() => setTurns((list) => list.filter((_, i) => i !== index))}
+ />
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ value={turn.content}
+ variant={'filled'}
+ onChange={(e) =>
+ setTurns((list) =>
+ list.map((item, i) =>
+ i === index ? { ...item, content: e.target.value } : item,
+ ),
+ )
+ }
+ />
+ </Flexbox>
+ ))}
+ <Flexbox horizontal>
+ <Button
+ size={'small'}
+ onClick={() => setTurns((list) => [...list, { content: '', role: 'user' }])}
+ >
+ {t('lobeBench.case.editor.turns.add')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.category')}</Text>
+ <Input
+ value={category}
+ variant={'filled'}
+ onChange={(e) => setCategory(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('lobeBench.case.editor.rules')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.editor.rules.hint')}
+ </Text>
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 12, minRows: 4 }}
+ placeholder={'Must: …\nMust not: …'}
+ value={rules}
+ variant={'filled'}
+ onChange={(e) => setRules(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.environment')}</Text>
+ <Select
+ options={environmentOptions}
+ value={environmentId}
+ variant={'filled'}
+ onChange={(value) => setEnvironmentId((value as string) ?? '')}
+ />
+ </Flexbox>
+ <Flexbox gap={10}>
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('lobeBench.case.editor.overrides')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.editor.overrides.hint')}
+ </Text>
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.case.editor.sessionDate')}</Text>
+ <Input
+ placeholder={'2026-07-20T09:00:00Z'}
+ value={sessionDate}
+ variant={'filled'}
+ onChange={(e) => setSessionDate(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.case.editor.timezone')}</Text>
+ <Input
+ placeholder={'America/New_York'}
+ value={timezone}
+ variant={'filled'}
+ onChange={(e) => setTimezone(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.case.editor.persona')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 8, minRows: 2 }}
+ value={persona}
+ variant={'filled'}
+ onChange={(e) => setPersona(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.case.editor.plugins')}</Text>
+ <Input
+ placeholder={'lobe-web-browsing, gmail'}
+ value={plugins}
+ variant={'filled'}
+ onChange={(e) => setPlugins(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.case.editor.mock')}</Text>
+ <Input
+ placeholder={'gmail, linear'}
+ value={mockServices}
+ variant={'filled'}
+ onChange={(e) => setMockServices(e.target.value)}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={onClose}>{t('lobeBench.new.cancel')}</Button>
+ <Button disabled={!input.trim()} loading={saving} type={'primary'} onClick={save}>
+ {t('lobeBench.case.editor.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Drawer>
+ );
+ },
+);
+
+CaseEditor.displayName = 'LobeBenchCaseEditor';
+
+export default CaseEditor;
diff --git a/src/features/LobeBench/CaseTable.tsx b/src/features/LobeBench/CaseTable.tsx
new file mode 100644
index 00000000000..b216faff054
--- /dev/null
+++ b/src/features/LobeBench/CaseTable.tsx
@@ -0,0 +1,618 @@
+'use client';
+
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import {
+ Block,
+ Button,
+ Checkbox,
+ confirmModal,
+ Drawer,
+ Empty,
+ Flexbox,
+ Input,
+ Select,
+ Tag,
+ Text,
+ toast,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import type { TFunction } from 'i18next';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import CaseEditor, { type CaseDraft } from '@/features/LobeBench/CaseEditor';
+import { openConversationPicker } from '@/features/LobeBench/ConversationPicker';
+import {
+ CASE_LEVELS,
+ getCaseCategory,
+ getCaseConnectors,
+ getCaseDifficulty,
+ getCaseLevel,
+ getCaseRules,
+ getCaseTitle,
+ isBuiltInRow,
+ levelLabelKey,
+ levelTagColor,
+ LOBE_BENCH_PATH,
+ nativeCaseId,
+} from '@/features/LobeBench/lobeBench';
+import { openCreateDatasetModal } from '@/features/LobeBench/PicksDatasetModal';
+import { type LobeBenchCase, useDatasetCases } from '@/features/LobeBench/useLobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { agentEvalService } from '@/services/agentEval';
+
+/** The preset Memory records an attempt starts with, flattened across layers. */
+const presetMemoryRecords = (environment?: EvalCaseEnvironment) =>
+ Object.entries(environment?.memory ?? {}).flatMap(([layer, value]) =>
+ Array.isArray(value)
+ ? (value as Record<string, unknown>[]).map((record) => ({
+ layer: layer.replace(/s$/, ''),
+ title: String(record.title ?? record.summary ?? ''),
+ }))
+ : [],
+ );
+
+/** "Memory read-write · effort medium · starts with 6 preset records", in the user's words. */
+const describeCaseMemory = (environment: EvalCaseEnvironment | undefined, t: TFunction<'eval'>) => {
+ const mode = environment?.agent?.memory;
+ if (mode?.enabled === false) return t('lobeBench.case.runsWith.memoryOff');
+ const records = presetMemoryRecords(environment).length;
+ const start = records
+ ? t('lobeBench.case.runsWith.memoryRecords', { count: records })
+ : t('lobeBench.case.runsWith.memoryEmpty');
+ return `${t('lobeBench.case.runsWith.memoryMode', {
+ effort: mode?.effort ?? 'medium',
+ permission: mode?.toolPermission ?? 'read-write',
+ })} · ${start}`;
+};
+
+const styles = stylex.create({
+ table: {
+ display: 'grid',
+ gridTemplateColumns: '36px minmax(0, 1fr) 150px 110px 240px',
+ columnGap: 12,
+ alignItems: 'center',
+ },
+ // The same columns behind a checkbox, where cases can be picked.
+ tableSelectable: {
+ gridTemplateColumns: '20px 36px minmax(0, 1fr) 150px 110px 240px',
+ },
+ head: {
+ paddingBlock: 8,
+ paddingInline: 12,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ row: {
+ cursor: 'pointer',
+ paddingBlock: 10,
+ paddingInline: 12,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+ pre: {
+ overflow: 'auto',
+ maxHeight: 240,
+ margin: 0,
+ padding: 12,
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ lineHeight: 1.5,
+ whiteSpace: 'pre-wrap',
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+});
+
+interface CaseTableProps {
+ /** The Lobe Bench benchmarks a new dataset can be filed under. */
+ benchmarkIds: string[];
+ /** The case set shown; its metadata says whether its cases can be edited. */
+ dataset?: {
+ benchmarkId?: string | null;
+ evalConfig?: unknown;
+ evalMode?: string | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ name?: string;
+ };
+ /**
+ * The account writes cases here: new ones, ones drafted from a conversation,
+ * edits and deletes. No page passes it yet: a dataset's cases are fixed once
+ * it is made, and the account's own cases are planned as a private part of
+ * the library that checked cases are copied from like built-in ones.
+ */
+ editable?: boolean;
+ /** Built-in datasets of library cases (Hard 50) each case belongs to, by its native id. */
+ memberships?: Record<string, string[]>;
+ /** The library: checked cases make a new dataset of the account's. */
+ selectable?: boolean;
+}
+
+type EditorState = { draft?: CaseDraft; testCase?: LobeBenchCase } | undefined;
+
+/**
+ * The cases of one dataset and a drawer with everything a case carries. In
+ * the library, checked cases make a new dataset of the account's, holding
+ * copies of them; a dataset's cases are fixed once it is made, so its past
+ * runs stay true to it.
+ */
+const CaseTable = memo<CaseTableProps>(
+ ({ benchmarkIds, dataset, editable, memberships, selectable }) => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const datasetId = dataset?.id;
+ const benchmarkId = dataset?.benchmarkId ?? benchmarkIds[0];
+ const { data: cases, isLoading, mutate: refreshCases } = useDatasetCases(datasetId);
+ const picking = !!selectable;
+ const [checked, setChecked] = useState<Set<string>>(() => new Set());
+ const [open, setOpen] = useState<LobeBenchCase>();
+ const [editor, setEditor] = useState<EditorState>();
+ const [busy, setBusy] = useState(false);
+ const [query, setQuery] = useState('');
+ const [categoryFilter, setCategoryFilter] = useState<string>();
+ const [levelFilter, setLevelFilter] = useState<string>();
+ const openLevel = open ? getCaseLevel(open) : undefined;
+
+ const categories = useMemo(
+ () => [...new Set((cases ?? []).map((item) => getCaseCategory(item)))].sort(),
+ [cases],
+ );
+ const levels = useMemo(() => {
+ const present = new Set((cases ?? []).map((item) => getCaseLevel(item)));
+ return CASE_LEVELS.filter((level) => present.has(level));
+ }, [cases]);
+ const levelCounts = useMemo(
+ () =>
+ Object.fromEntries(
+ CASE_LEVELS.map((level) => [
+ level,
+ (cases ?? []).filter((item) => getCaseLevel(item) === level).length,
+ ]),
+ ) as Record<(typeof CASE_LEVELS)[number], number>,
+ [cases],
+ );
+ const visibleCases = useMemo(() => {
+ const needle = query.trim().toLowerCase();
+ return (cases ?? [])
+ .map((item, position) => ({ item, position }))
+ .filter(({ item }) => {
+ if (categoryFilter && getCaseCategory(item) !== categoryFilter) return false;
+ if (levelFilter && getCaseLevel(item) !== levelFilter) return false;
+ if (!needle) return true;
+ return [getCaseTitle(item), item.content?.input ?? '', ...getCaseConnectors(item)]
+ .join(' ')
+ .toLowerCase()
+ .includes(needle);
+ });
+ }, [cases, categoryFilter, levelFilter, query]);
+
+ const fail = (error: unknown) =>
+ toast.error(error instanceof Error ? error.message : String(error));
+
+ // From a conversation: the server drafts request, context, setup and rules;
+ // the author edits before anything is saved.
+ const draftFromConversation = () =>
+ openConversationPicker(async (topicId) => {
+ setBusy(true);
+ const pending = toast.loading(t('lobeBench.case.fromConversation.drafting'));
+ try {
+ const draft = await agentEvalService.draftTestCaseFromTopic({
+ benchmarkId,
+ draftRules: true,
+ topicId,
+ });
+ if (draft.rulesError)
+ toast.warning(
+ t('lobeBench.case.fromConversation.rulesFailed', { error: draft.rulesError }),
+ );
+ setEditor({
+ draft: {
+ environment: draft.agent
+ ? {
+ agent: {
+ ...(draft.agent.systemRole && { systemRole: draft.agent.systemRole }),
+ plugins: draft.agent.plugins,
+ },
+ }
+ : undefined,
+ input: draft.input,
+ messages: draft.messages,
+ rules: draft.rules,
+ sessionDate: draft.sessionDate,
+ sourceTopicId: topicId,
+ title: draft.title,
+ },
+ });
+ } catch (error) {
+ fail(error);
+ } finally {
+ pending.close();
+ setBusy(false);
+ }
+ });
+
+ const remove = (testCase: LobeBenchCase) =>
+ confirmModal({
+ content: t('lobeBench.case.delete.confirm'),
+ okButtonProps: { danger: true },
+ okText: t('lobeBench.case.delete'),
+ onOk: async () => {
+ try {
+ const result = (await agentEvalService.deleteTestCase(testCase.id)) as {
+ error?: string;
+ success?: boolean;
+ };
+ if (result?.success === false) throw new Error(result.error ?? 'Delete failed');
+ setOpen(undefined);
+ await refreshCases();
+ } catch (error) {
+ fail(error);
+ }
+ },
+ title: t('lobeBench.case.delete'),
+ });
+
+ const rowsOf = (caseIds: string[]) =>
+ (cases ?? []).filter((item) => caseIds.includes(nativeCaseId(item)));
+
+ // Library cases are read-only; checked ones make a new dataset of the account's.
+ const createDataset = (caseIds: string[]) => {
+ if (!benchmarkId || caseIds.length === 0) return;
+ openCreateDatasetModal({
+ benchmarkId,
+ cases: rowsOf(caseIds),
+ library: dataset,
+ onDone: (created) => {
+ setChecked(new Set());
+ setOpen(undefined);
+ navigate(`${LOBE_BENCH_PATH}/datasets/${created.id}`);
+ },
+ });
+ };
+
+ const visibleIds = visibleCases.map(({ item }) => nativeCaseId(item));
+ const allVisibleChecked = visibleIds.length > 0 && visibleIds.every((id) => checked.has(id));
+ const toggle = (id: string, on: boolean) =>
+ setChecked((previous) => {
+ const next = new Set(previous);
+ if (on) next.add(id);
+ else next.delete(id);
+ return next;
+ });
+ const toggleVisible = (on: boolean) =>
+ setChecked((previous) => {
+ const next = new Set(previous);
+ for (const id of visibleIds) {
+ if (on) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ });
+
+ return (
+ <>
+ <Block padding={8} variant={'outlined'}>
+ <Flexbox gap={2}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ justify={'space-between'}
+ padding={'4px 12px'}
+ >
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.library.cases', { count: cases?.length ?? 0 })}
+ {levels.length > 0 &&
+ ` · ${t('lobeBench.library.levels', {
+ l1: levelCounts.L1,
+ l2: levelCounts.L2,
+ l3: levelCounts.L3,
+ l4: levelCounts.L4,
+ })}`}
+ </Text>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {checked.size > 0 ? (
+ <>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.picks.selected', { count: checked.size })}
+ </Text>
+ <Button size={'small'} type={'text'} onClick={() => setChecked(new Set())}>
+ {t('lobeBench.picks.clear')}
+ </Button>
+ <Button
+ size={'small'}
+ type={'primary'}
+ onClick={() => createDataset([...checked])}
+ >
+ {t('lobeBench.picks.create')}
+ </Button>
+ </>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {picking && t('lobeBench.picks.hint.library')}
+ </Text>
+ )}
+ {editable && (
+ <>
+ <Button loading={busy} size={'small'} onClick={draftFromConversation}>
+ {t('lobeBench.case.fromConversation')}
+ </Button>
+ <Button size={'small'} type={'default'} onClick={() => setEditor({})}>
+ {t('lobeBench.case.new')}
+ </Button>
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+ {(cases?.length ?? 0) > 5 && (
+ <Flexbox horizontal align={'center'} gap={8} padding={'4px 12px'} wrap={'wrap'}>
+ <Input
+ allowClear
+ placeholder={t('lobeBench.library.filter.search')}
+ size={'small'}
+ style={{ maxWidth: 280 }}
+ value={query}
+ variant={'filled'}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ {categories.length > 1 && (
+ <Select
+ allowClear
+ options={categories.map((category) => ({ label: category, value: category }))}
+ placeholder={t('lobeBench.library.filter.category')}
+ size={'small'}
+ style={{ width: 200 }}
+ value={categoryFilter}
+ variant={'filled'}
+ onChange={(value) => setCategoryFilter((value as string) || undefined)}
+ />
+ )}
+ {levels.length > 1 && (
+ <Select
+ allowClear
+ placeholder={t('lobeBench.library.filter.level')}
+ size={'small'}
+ style={{ width: 150 }}
+ value={levelFilter}
+ variant={'filled'}
+ options={levels.map((level) => ({
+ label: t(levelLabelKey(level)),
+ value: level,
+ }))}
+ onChange={(value) => setLevelFilter((value as string) || undefined)}
+ />
+ )}
+ {(query || categoryFilter || levelFilter) && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.library.filter.count', {
+ shown: visibleCases.length,
+ total: cases?.length ?? 0,
+ })}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ <div
+ className={
+ stylex.props(styles.table, picking && styles.tableSelectable, styles.head).className
+ }
+ >
+ {picking && (
+ <Checkbox
+ checked={allVisibleChecked}
+ disabled={visibleIds.length === 0}
+ indeterminate={!allVisibleChecked && visibleIds.some((id) => checked.has(id))}
+ onChange={toggleVisible}
+ />
+ )}
+ <span>#</span>
+ <span>{t('lobeBench.library.col.case')}</span>
+ <span>{t('lobeBench.library.col.category')}</span>
+ <span>{t('lobeBench.library.col.level')}</span>
+ <span>{t('lobeBench.library.col.tools')}</span>
+ </div>
+ {!isLoading && (cases?.length ?? 0) === 0 && (
+ <Empty description={t('lobeBench.library.empty')} />
+ )}
+ {visibleCases.map(({ item, position }) => {
+ const level = getCaseLevel(item);
+ const connectors = getCaseConnectors(item);
+ // Published sets number their cases; the account's own set counts rows.
+ const index =
+ typeof item.metadata?.index === 'number' ? item.metadata.index : position + 1;
+ return (
+ <div
+ key={item.id}
+ className={
+ stylex.props(styles.table, picking && styles.tableSelectable, styles.row)
+ .className
+ }
+ onClick={() => setOpen(item)}
+ >
+ {picking && (
+ // Picking a case must not open it.
+ <span onClick={(e) => e.stopPropagation()}>
+ <Checkbox
+ checked={checked.has(nativeCaseId(item))}
+ onChange={(on) => toggle(nativeCaseId(item), on)}
+ />
+ </span>
+ )}
+ <span
+ className={stylex.props(styles.mono).className}
+ style={{ color: cssVar.colorTextQuaternary }}
+ >
+ {index}
+ </span>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis>{getCaseTitle(item)}</Text>
+ {memberships?.[nativeCaseId(item)]?.map((name) => (
+ <Tag key={name} style={{ flex: 'none' }}>
+ {name}
+ </Tag>
+ ))}
+ </Flexbox>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {getCaseCategory(item)}
+ </Text>
+ <span>
+ {level && <Tag color={levelTagColor(level)}>{t(levelLabelKey(level))}</Tag>}
+ </span>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {connectors.slice(0, 3).join(' · ')}
+ {connectors.length > 3 && ` +${connectors.length - 3}`}
+ </Text>
+ </div>
+ );
+ })}
+ </Flexbox>
+ </Block>
+
+ <Drawer
+ open={!!open}
+ title={open ? getCaseTitle(open) : ''}
+ width={560}
+ onClose={() => setOpen(undefined)}
+ >
+ {open && (
+ <Flexbox gap={20}>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ <Tag>{getCaseCategory(open)}</Tag>
+ {memberships?.[nativeCaseId(open)]?.map((name) => (
+ <Tag key={name}>{name}</Tag>
+ ))}
+ {openLevel && (
+ <Tag color={levelTagColor(openLevel)}>{t(levelLabelKey(openLevel))}</Tag>
+ )}
+ {!editable && (
+ <Tag>
+ {isBuiltInRow(dataset as { userId?: string | null } | undefined)
+ ? t('lobeBench.builtIn')
+ : t('lobeBench.case.readOnly')}
+ </Tag>
+ )}
+ </Flexbox>
+ {getCaseDifficulty(open)?.signals?.length ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.difficulty.why', {
+ signals: getCaseDifficulty(open)!.signals!.join(', '),
+ })}
+ </Text>
+ ) : null}
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {editable ? (
+ <>
+ <Button size={'small'} onClick={() => setEditor({ testCase: open })}>
+ {t('lobeBench.case.edit')}
+ </Button>
+ <Button danger size={'small'} onClick={() => remove(open)}>
+ {t('lobeBench.case.delete')}
+ </Button>
+ </>
+ ) : (
+ selectable && (
+ <Button size={'small'} onClick={() => createDataset([nativeCaseId(open)])}>
+ {t('lobeBench.picks.create')}
+ </Button>
+ )
+ )}
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.prompt')}</Text>
+ <pre className={stylex.props(styles.pre).className}>{open.content?.input}</pre>
+ </Flexbox>
+ {open.content?.environment?.agent?.systemRole && (
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.persona')}</Text>
+ <pre className={stylex.props(styles.pre).className}>
+ {open.content.environment.agent.systemRole}
+ </pre>
+ </Flexbox>
+ )}
+ {/* What the attempt is given, in the user's words: the simulated
+ connectors, the Memory it starts from and the pinned clock. The
+ shared environment is already merged into content.environment. */}
+ <Flexbox gap={8}>
+ <Text weight={500}>{t('lobeBench.case.runsWith')}</Text>
+ <Flexbox gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.runsWith.connectors')}
+ </Text>
+ {getCaseConnectors(open).length > 0 ? (
+ <Flexbox horizontal gap={6} wrap={'wrap'}>
+ {getCaseConnectors(open).map((id) => (
+ <Tag key={id}>{id}</Tag>
+ ))}
+ </Flexbox>
+ ) : (
+ <Text fontSize={13}>{t('lobeBench.case.runsWith.noConnectors')}</Text>
+ )}
+ </Flexbox>
+ <Flexbox gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.runsWith.memory')}
+ </Text>
+ <Text fontSize={13}>{describeCaseMemory(open.content?.environment, t)}</Text>
+ {presetMemoryRecords(open.content?.environment).length > 0 && (
+ <Flexbox horizontal gap={6} wrap={'wrap'}>
+ {presetMemoryRecords(open.content?.environment).map((record, index) => (
+ <Tag key={index}>
+ {record.layer} · {record.title}
+ </Tag>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ <Flexbox gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.case.runsWith.clock')}
+ </Text>
+ <Text fontSize={13}>
+ {open.content?.environment?.sessionDate
+ ? t('lobeBench.case.runsWith.clockPinned', {
+ date: `${open.content.environment.sessionDate} · ${open.content.environment.timezone ?? 'UTC'}`,
+ })
+ : t('lobeBench.case.runsWith.clockWall')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ {getCaseRules(open).length > 0 && (
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.rules')}</Text>
+ <Flexbox gap={4}>
+ {getCaseRules(open).map((rule, index) => (
+ <Text fontSize={13} key={index}>
+ {rule}
+ </Text>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
+ )}
+ </Drawer>
+
+ {datasetId && (
+ <CaseEditor
+ datasetId={datasetId}
+ draft={editor?.draft}
+ open={!!editor}
+ testCase={editor?.testCase}
+ onClose={() => setEditor(undefined)}
+ onSaved={async () => {
+ setOpen(undefined);
+ await refreshCases();
+ }}
+ />
+ )}
+ </>
+ );
+ },
+);
+
+CaseTable.displayName = 'LobeBenchCaseTable';
+
+export default CaseTable;
diff --git a/src/features/LobeBench/ContenderForm.tsx b/src/features/LobeBench/ContenderForm.tsx
new file mode 100644
index 00000000000..aedca0f67cc
--- /dev/null
+++ b/src/features/LobeBench/ContenderForm.tsx
@@ -0,0 +1,206 @@
+'use client';
+
+import type { EvalRunChatConfig, LobeAgentChatConfig } from '@lobechat/types';
+import { Button, createModal, Flexbox, Input, Slider, Text, useModalContext } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { t as translate } from 'i18next';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ createStore as createChatInputStore,
+ Provider as ChatInputStoreProvider,
+} from '@/features/ChatInput/store';
+import {
+ CONTENDER_SETTING_KEYS,
+ describeSettings,
+ type LobeBenchContender,
+} from '@/features/LobeBench/lobeBench';
+import ModelSelect from '@/features/ModelSelect';
+import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm/ControlsForm';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+interface ContenderFormProps {
+ /** An existing contender to edit; its id is kept. */
+ initial?: LobeBenchContender;
+ onSubmit: (contender: LobeBenchContender) => void;
+ /** The submit button's label; "Add to experiment" by default. */
+ submitLabel?: string;
+}
+
+/** The contender settings in a chatConfig patch from the model-params form; nothing else is sent. */
+const pickContenderSettings = (config: Partial<LobeAgentChatConfig>): EvalRunChatConfig =>
+ Object.fromEntries(
+ CONTENDER_SETTING_KEYS.filter((key) => config[key] !== undefined && config[key] !== null).map(
+ (key) => [key, config[key]],
+ ),
+ ) as EvalRunChatConfig;
+
+/**
+ * Builds one contender: a model from the product's own model list plus the
+ * settings it runs with. The model's own settings (reasoning switch and effort,
+ * thinking level, verbosity …) come from the chat model-params form, so each
+ * model shows the controls it has in chat. Sampling left at
+ * "model default" is not sent.
+ */
+const ContenderForm = memo<ContenderFormProps>(({ initial, onSubmit, submitLabel }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const [target, setTarget] = useState<{ model: string; provider: string } | undefined>(
+ initial && { model: initial.model, provider: initial.provider },
+ );
+ const [name, setName] = useState(initial?.name ?? '');
+ const [temperature, setTemperature] = useState<number | undefined>(initial?.params?.temperature);
+ const [topP, setTopP] = useState<number | undefined>(initial?.params?.top_p);
+ const [settings, setSettings] = useState<EvalRunChatConfig>(initial?.chatConfig ?? {});
+ const enabledModels = useAiInfraStore((s) => s.enabledChatModelList || []);
+ const extendParams = useAiInfraStore((s) =>
+ target ? aiModelSelectors.modelExtendParams(target.model, target.provider)(s) : undefined,
+ );
+
+ const modelInfo = useMemo(() => {
+ if (!target) return undefined;
+ for (const provider of enabledModels) {
+ if (provider.id !== target.provider) continue;
+ const found = provider.children?.find((model) => model.id === target.model);
+ if (found) return found;
+ }
+ return undefined;
+ }, [enabledModels, target]);
+
+ const labels = {
+ reasoning: t('lobeBench.contender.settings.reasoning'),
+ temperature: t('lobeBench.contender.settings.temperature'),
+ topP: t('lobeBench.contender.settings.topP'),
+ };
+ const params = {
+ ...(temperature !== undefined && { temperature }),
+ ...(topP !== undefined && { top_p: topP }),
+ };
+ // A model with a reasoning switch runs with reasoning off until it is turned on
+ // (the product default), so the contender says so instead of "default settings".
+ const chatConfig = pickContenderSettings({
+ ...(extendParams?.includes('enableReasoning') && { enableReasoning: false }),
+ ...settings,
+ });
+ const settingsLabel =
+ describeSettings(params, chatConfig, labels) || t('lobeBench.contender.settings.default');
+ // A model with an empty display name (a custom provider's) is named by its id.
+ const defaultName = target ? `${modelInfo?.displayName || target.model} · ${settingsLabel}` : '';
+
+ const submit = () => {
+ if (!target) return;
+ onSubmit({
+ ...(Object.keys(chatConfig).length > 0 && { chatConfig }),
+ id: initial?.id ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
+ model: target.model,
+ name: name.trim() || defaultName,
+ ...(Object.keys(params).length > 0 && { params }),
+ provider: target.provider,
+ });
+ close();
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text type={'secondary'}>{t('lobeBench.contender.subtitle')}</Text>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.contender.model')}</Text>
+ <ModelSelect
+ placeholder={t('lobeBench.contender.model.placeholder')}
+ requiredAbilities={['functionCall']}
+ value={target}
+ variant={'filled'}
+ onChange={(value) => {
+ setTarget(value as { model: string; provider: string });
+ // Another model has other settings.
+ setSettings({});
+ }}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text weight={500}>{t('lobeBench.contender.temperature')}</Text>
+ <Text type={'secondary'}>
+ {temperature === undefined ? t('lobeBench.contender.modelDefault') : temperature}
+ </Text>
+ </Flexbox>
+ <Slider
+ max={2}
+ min={0}
+ step={0.1}
+ value={temperature ?? 1}
+ onChange={(value) => setTemperature(value as number)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text weight={500}>{t('lobeBench.contender.topP')}</Text>
+ <Text type={'secondary'}>
+ {topP === undefined ? t('lobeBench.contender.modelDefault') : topP}
+ </Text>
+ </Flexbox>
+ <Slider
+ max={1}
+ min={0}
+ step={0.05}
+ value={topP ?? 1}
+ onChange={(value) => setTopP(value as number)}
+ />
+ </Flexbox>
+ {target && extendParams && extendParams.length > 0 && (
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.contender.modelSettings')}</Text>
+ {/* The chat form reads its Agent from a chat input; this one edits no Agent. */}
+ <ChatInputStoreProvider createStore={() => createChatInputStore({ agentId: '' })}>
+ <ControlsForm
+ chatConfig={settings}
+ model={target.model}
+ provider={target.provider}
+ onChatConfigChange={async (patch) => {
+ // The form writes back what it was given; an unchanged value must not re-render it.
+ setSettings((previous) => {
+ const next = { ...previous, ...pickContenderSettings(patch) };
+ return isEqual(next, previous) ? previous : next;
+ });
+ }}
+ />
+ </ChatInputStoreProvider>
+ </Flexbox>
+ )}
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.contender.name')}</Text>
+ <Input
+ placeholder={defaultName || t('lobeBench.contender.name.placeholder')}
+ value={name}
+ variant={'filled'}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('lobeBench.new.cancel')}</Button>
+ <Button disabled={!target} type={'primary'} onClick={submit}>
+ {submitLabel ?? t('lobeBench.contender.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+ContenderForm.displayName = 'LobeBenchContenderForm';
+
+/** Opens the contender form in a modal; `onSubmit` gets the contender once saved. */
+export const openContenderModal = (
+ onSubmit: (contender: LobeBenchContender) => void,
+ title?: string,
+ submitLabel?: string,
+ initial?: LobeBenchContender,
+) =>
+ createModal({
+ content: <ContenderForm initial={initial} submitLabel={submitLabel} onSubmit={onSubmit} />,
+ footer: null,
+ title: title ?? translate('lobeBench.contender.title', { ns: 'eval' }),
+ width: 520,
+ });
+
+export default ContenderForm;
diff --git a/src/features/LobeBench/ContenderRanking.tsx b/src/features/LobeBench/ContenderRanking.tsx
new file mode 100644
index 00000000000..0437633b68c
--- /dev/null
+++ b/src/features/LobeBench/ContenderRanking.tsx
@@ -0,0 +1,253 @@
+'use client';
+
+import type { AgentEvalRunListItem } from '@lobechat/types';
+import { formatCost } from '@lobechat/utils';
+import { modelMappings } from '@lobehub/icons';
+import { Block, Button, DropdownMenu, Flexbox, Select, Text, useTheme } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ChevronDown, Plus } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ModelIcon } from '@/components/LobeIcons';
+import {
+ contenderKeyOf,
+ pickRankedSet,
+ rankContenders,
+ type RankedContender,
+} from '@/features/LobeBench/benchmarkRanking';
+import {
+ formatPercent,
+ LOBE_BENCH_PATH,
+ RANK_ATTEMPTS,
+ type RankableSet,
+} from '@/features/LobeBench/lobeBench';
+import { adaptBrandColor, findBrandColor } from '@/features/LobeBench/modelBrand';
+import RankingBars, { type RankingBarRow } from '@/features/LobeBench/RankingBars';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+const styles = stylex.create({
+ title: {
+ margin: 0,
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+ empty: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: 12,
+ paddingBlock: 40,
+ paddingInline: 24,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+});
+
+interface ContenderRankingProps {
+ benchmarkId: string;
+ runs: AgentEvalRunListItem[];
+ /** The leaderboards ranked, one per benchmark (`rankableSetsOf`). */
+ sets: RankableSet[];
+}
+
+const modelOf = (run: AgentEvalRunListItem) =>
+ (run.config as { model?: string } | null | undefined)?.model;
+
+/**
+ * The benchmark page's headline: the models ranked by their best completed
+ * run on one case set, in LobeBench's ranking form (see `RankingBars`). Every
+ * value is written in the row, so nothing depends on hovering.
+ */
+const ContenderRanking = ({ benchmarkId, runs, sets }: ContenderRankingProps) => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const theme = useTheme();
+ const [chosen, setChosen] = useState<string>();
+ // The contenders picked to compare (by setup); none picked shows them all.
+ const [compared, setCompared] = useState<string[]>([]);
+
+ const rankings = useMemo(
+ () => new Map(sets.map((set) => [set.id, rankContenders(runs, set)])),
+ [runs, sets],
+ );
+ const set =
+ (chosen && sets.find((candidate) => candidate.id === chosen)) || pickRankedSet(sets, rankings);
+ const ranking = set ? rankings.get(set.id) : undefined;
+ const contenders = ranking?.contenders ?? [];
+ // Solid bar: passed all of the benchmark's k attempts; light bar: passed at least one.
+ const rankK = ranking?.k ?? set?.k ?? RANK_ATTEMPTS;
+
+ const describe = (entry: RankedContender) =>
+ [
+ entry.attempts > entry.k &&
+ t('lobeBench.benchmark.rank.estimated', { attempts: entry.attempts }),
+ t('lobeBench.overview.passedOf', { passed: entry.passed, total: entry.total }),
+ entry.perCaseCost !== undefined &&
+ t('lobeBench.benchmark.rank.cost', { cost: formatCost(entry.perCaseCost) }),
+ entry.errors > 0 && t('lobeBench.dashboard.col.errors', { count: entry.errors }),
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
+ const ranked = contenders.map((entry, index) => ({
+ entry,
+ key: contenderKeyOf(entry.run),
+ rank: index + 1,
+ }));
+ // Only picks on this board count; with none, every contender shows.
+ const picked = compared.filter((key) => ranked.some((item) => item.key === key));
+ const shown = picked.length > 0 ? ranked.filter(({ key }) => picked.includes(key)) : ranked;
+ const rows: RankingBarRow[] = shown.map(({ entry, rank }) => {
+ const model = modelOf(entry.run);
+ const brand = findBrandColor(modelMappings, model);
+ const anyRate = entry.k > 1 && entry.total ? (entry.anyK ?? 0) / entry.total : undefined;
+ return {
+ color: brand ? adaptBrandColor(brand, theme.isDarkMode) : undefined,
+ detail: describe(entry),
+ icon: model ? <ModelIcon model={model} size={20} /> : undefined,
+ key: entry.run.id,
+ name: entry.name,
+ // Picking models to compare keeps each one's place on the full board.
+ rank,
+ rate: entry.passRate,
+ reach: anyRate,
+ reachText:
+ anyRate === undefined
+ ? undefined
+ : t('lobeBench.benchmark.rank.anyRate', { k: entry.k, value: formatPercent(anyRate) }),
+ };
+ });
+
+ const notes = [
+ ranking &&
+ ranking.active > 0 &&
+ t('lobeBench.benchmark.rank.active', { count: ranking.active }),
+ ranking &&
+ ranking.unjudged > 0 &&
+ t('lobeBench.benchmark.rank.unjudged', { count: ranking.unjudged }),
+ ranking &&
+ ranking.broken > 0 &&
+ t('lobeBench.benchmark.rank.broken', { count: ranking.broken }),
+ ranking &&
+ ranking.outdated > 0 &&
+ t('lobeBench.benchmark.rank.outdated', { count: ranking.outdated }),
+ ranking &&
+ ranking.fewAttempts > 0 &&
+ t('lobeBench.benchmark.rank.fewAttempts', { count: ranking.fewAttempts, k: rankK }),
+ ].filter(Boolean) as string[];
+
+ const startExperiment = () =>
+ navigate(`${LOBE_BENCH_PATH}/experiments/new${set ? `?dataset=${set.id}` : ''}`);
+
+ // A click opens the run where Lobe Bench reads it (its experiment, with the
+ // same pass^k numbers); a run without one opens the Lab's view.
+ const openRow = (row: RankingBarRow) => {
+ const entry = contenders.find((candidate) => candidate.run.id === row.key);
+ if (!entry) return;
+ navigate(
+ entry.run.experimentId
+ ? `${LOBE_BENCH_PATH}/experiments/${entry.run.experimentId}`
+ : `/eval/bench/${benchmarkId}/runs/${entry.run.id}`,
+ );
+ };
+
+ return (
+ <Block gap={16} padding={20} variant={'outlined'}>
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <h2 {...stylex.props(styles.title)}>{t('lobeBench.benchmark.rank.title')}</h2>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.benchmark.rank.hint', { k: rankK })}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal gap={8} style={{ flex: 'none' }}>
+ {contenders.length > 1 && (
+ // A checklist behind one compact button: picked models never pile up as tags.
+ <DropdownMenu
+ placement={'bottomRight'}
+ items={[
+ {
+ disabled: picked.length === 0,
+ key: 'all',
+ label: t('lobeBench.benchmark.rank.compare.reset'),
+ onClick: () => setCompared([]),
+ },
+ { type: 'divider' as const },
+ ...ranked.map(({ entry, key, rank }) => ({
+ checked: picked.includes(key),
+ key,
+ label: `#${rank} ${entry.name}`,
+ onCheckedChange: (checked: boolean) =>
+ setCompared(checked ? [...picked, key] : picked.filter((item) => item !== key)),
+ type: 'checkbox' as const,
+ })),
+ ]}
+ >
+ <Button icon={ChevronDown} iconPosition={'end'} size={'small'}>
+ {picked.length > 0
+ ? t('lobeBench.benchmark.rank.compare.some', { count: picked.length })
+ : t('lobeBench.benchmark.rank.compare.all')}
+ </Button>
+ </DropdownMenu>
+ )}
+ {sets.length > 1 && (
+ <Select
+ size={'small'}
+ style={{ flex: 'none', width: 240 }}
+ value={set?.id}
+ options={sets.map((candidate) => ({
+ label: t('lobeBench.benchmark.rank.setOption', {
+ count: rankings.get(candidate.id)?.contenders.length ?? 0,
+ name: candidate.name,
+ }),
+ value: candidate.id,
+ }))}
+ onChange={(value) => setChosen(value as string)}
+ />
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ {contenders.length === 0 ? (
+ <Flexbox {...stylex.props(styles.empty)}>
+ <Text style={{ textAlign: 'center' }} type={'secondary'}>
+ {t('lobeBench.benchmark.rank.empty', { set: set?.name ?? '—' })}
+ </Text>
+ {notes.length > 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {notes.join(' · ')}
+ </Text>
+ )}
+ <Button icon={Plus} type={'primary'} onClick={startExperiment}>
+ {t('lobeBench.benchmark.newExperiment')}
+ </Button>
+ </Flexbox>
+ ) : (
+ <>
+ <RankingBars
+ legendRate={t('lobeBench.benchmark.rank.legend.rate', { k: rankK })}
+ legendReach={t('lobeBench.benchmark.rank.legend.reach', { k: rankK })}
+ rows={rows}
+ onSelect={openRow}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {[
+ t('lobeBench.benchmark.rank.summary', {
+ count: contenders.length,
+ runs: ranking?.ranked ?? 0,
+ }),
+ ...notes,
+ ].join(' · ')}
+ </Text>
+ </>
+ )}
+ </Block>
+ );
+};
+
+export default ContenderRanking;
diff --git a/src/features/LobeBench/Contenders/index.tsx b/src/features/LobeBench/Contenders/index.tsx
new file mode 100644
index 00000000000..2a1b5454947
--- /dev/null
+++ b/src/features/LobeBench/Contenders/index.tsx
@@ -0,0 +1,222 @@
+'use client';
+
+import { evalCaseVersionOf } from '@lobechat/types';
+import { Block, Button, confirmModal, Empty, Flexbox, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Plus } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { rankContenders } from '@/features/LobeBench/benchmarkRanking';
+import { openContenderModal } from '@/features/LobeBench/ContenderForm';
+import {
+ benchmarkProtocolOf,
+ describeSettings,
+ experimentPartsOf,
+ formatPercent,
+ isBuiltInBenchmark,
+ isLobeBenchMeta,
+ type LobeBenchContender,
+ sameContender,
+ upsertContenders,
+} from '@/features/LobeBench/lobeBench';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchExperiments,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+import { useSavedContenders } from '@/features/LobeBench/useSavedContenders';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ table: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 1.4fr) 100px 120px 140px',
+ columnGap: 12,
+ alignItems: 'center',
+ },
+ head: {
+ paddingBlock: 8,
+ paddingInline: 12,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ row: {
+ paddingBlock: 10,
+ paddingInline: 12,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+});
+
+/**
+ * The account's contenders: every model-plus-settings that ran before, kept
+ * so the next experiment is one click, with how often each ran and its best
+ * result on a whole case set.
+ */
+const LobeBenchContenders = memo(() => {
+ const { t } = useTranslation('eval');
+ const { benchmark, contenders, save } = useSavedContenders();
+ const builtIn = isBuiltInBenchmark(benchmark);
+ const { benchmarks } = useLobeBenchBenchmarks();
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { experiments } = useLobeBenchExperiments();
+ const { data: runs } = useLobeBenchRuns(benchmarkIds);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ const labels = {
+ reasoning: t('lobeBench.contender.settings.reasoning'),
+ temperature: t('lobeBench.contender.settings.temperature'),
+ topP: t('lobeBench.contender.settings.topP'),
+ };
+
+ const experimentsOf = (contender: LobeBenchContender) =>
+ experiments.filter(
+ (experiment) =>
+ isLobeBenchMeta(experiment.metadata) &&
+ experiment.metadata.contenders.some((c) => sameContender(c, contender)),
+ ).length;
+
+ // Best pass rate among completed runs on a whole set that this contender made, on
+ // the current version of its cases (earlier versions are history, not a result).
+ const bestOf = (contender: LobeBenchContender) => {
+ const ids = new Set(
+ experiments.flatMap((experiment) => {
+ const meta = experiment.metadata;
+ if (!isLobeBenchMeta(meta)) return [];
+ // Its run on every dataset the experiment covers.
+ const parts = experimentPartsOf(meta);
+ return meta.contenders
+ .filter((c) => sameContender(c, contender))
+ .flatMap((c) => parts.flatMap((part) => part.runIds?.[c.id] ?? []));
+ }),
+ );
+ const contenderRuns = (runs ?? []).filter((run) => ids.has(run.id));
+ const rates = (datasets ?? []).flatMap((dataset) =>
+ rankContenders(contenderRuns, {
+ id: dataset.id,
+ caseVersion: evalCaseVersionOf(dataset.metadata),
+ k: benchmarkProtocolOf(benchmarks.find((b) => b.id === dataset.benchmarkId))?.k,
+ }).contenders.map((entry) => entry.passRate),
+ );
+ return rates.length > 0 ? Math.max(...rates) : undefined;
+ };
+
+ const persist = async (list: LobeBenchContender[]) => {
+ try {
+ await save(list);
+ toast.success(t('lobeBench.contenders.saved'));
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ const add = () =>
+ openContenderModal(
+ (contender) => persist(upsertContenders(contenders, [contender])),
+ t('lobeBench.contenders.new'),
+ t('lobeBench.contender.save.list'),
+ );
+ const edit = (contender: LobeBenchContender) =>
+ openContenderModal(
+ (edited) => persist(contenders.map((c) => (c.id === contender.id ? edited : c))),
+ t('lobeBench.contenders.edit'),
+ t('lobeBench.contender.save.list'),
+ contender,
+ );
+ const remove = (contender: LobeBenchContender) =>
+ confirmModal({
+ content: t('lobeBench.contenders.delete.confirm'),
+ okButtonProps: { danger: true },
+ okText: t('lobeBench.case.delete'),
+ onOk: () => persist(contenders.filter((c) => c.id !== contender.id)),
+ title: t('lobeBench.case.delete'),
+ });
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={20}>
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {t('lobeBench.contenders.title')}
+ </Text>
+ <Text type={'secondary'}>
+ {builtIn ? t('lobeBench.contenders.builtIn') : t('lobeBench.contenders.subtitle')}
+ </Text>
+ </Flexbox>
+ {!builtIn && (
+ <Button icon={Plus} type={'primary'} onClick={add}>
+ {t('lobeBench.contenders.new')}
+ </Button>
+ )}
+ </Flexbox>
+
+ <Block padding={8} variant={'outlined'}>
+ <Flexbox gap={2}>
+ <div className={stylex.props(styles.table, styles.head).className}>
+ <span>{t('lobeBench.contenders.col.name')}</span>
+ <span>{t('lobeBench.contenders.col.model')}</span>
+ <span style={{ textAlign: 'right' }}>{t('lobeBench.contenders.col.experiments')}</span>
+ <span style={{ textAlign: 'right' }}>{t('lobeBench.contenders.col.best')}</span>
+ <span />
+ </div>
+ {contenders.length === 0 && <Empty description={t('lobeBench.contenders.empty')} />}
+ {contenders.map((contender) => {
+ const best = bestOf(contender);
+ return (
+ <div className={stylex.props(styles.table, styles.row).className} key={contender.id}>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {contender.name}
+ </Text>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {describeSettings(contender.params, contender.chatConfig, labels) ||
+ t('lobeBench.contender.settings.default')}
+ </Text>
+ </Flexbox>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {contender.model} · {contender.provider}
+ </Text>
+ <Text
+ className={stylex.props(styles.mono).className}
+ style={{ textAlign: 'right' }}
+ >
+ {experimentsOf(contender)}
+ </Text>
+ <Text
+ className={stylex.props(styles.mono).className}
+ style={{ textAlign: 'right' }}
+ >
+ {best === undefined ? '—' : formatPercent(best)}
+ </Text>
+ <Flexbox horizontal gap={4} justify={'flex-end'}>
+ {!builtIn && (
+ <>
+ <Button size={'small'} type={'text'} onClick={() => edit(contender)}>
+ {t('lobeBench.contenders.edit')}
+ </Button>
+ <Button danger size={'small'} type={'text'} onClick={() => remove(contender)}>
+ {t('lobeBench.case.delete')}
+ </Button>
+ </>
+ )}
+ </Flexbox>
+ </div>
+ );
+ })}
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ );
+});
+
+LobeBenchContenders.displayName = 'LobeBenchContenders';
+
+export default LobeBenchContenders;
diff --git a/src/features/LobeBench/ConversationPicker.tsx b/src/features/LobeBench/ConversationPicker.tsx
new file mode 100644
index 00000000000..7d743fd36b0
--- /dev/null
+++ b/src/features/LobeBench/ConversationPicker.tsx
@@ -0,0 +1,126 @@
+'use client';
+
+import { Block, createModal, Flexbox, Input, Text, useModalContext } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import AsyncError from '@/components/AsyncError';
+import { useEvalStore } from '@/store/eval';
+
+const styles = stylex.create({
+ row: {
+ cursor: 'pointer',
+ paddingBlock: 8,
+ paddingInline: 12,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ },
+});
+
+const formatDay = (value?: Date | number | string | null) => {
+ if (!value) return '';
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString();
+};
+
+/**
+ * Picks one of the account's conversations to draft a case from: the recent
+ * ones by default, or a keyword search across all of them.
+ */
+const ConversationPicker = memo<{ onPick: (topicId: string) => void }>(({ onPick }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const [keywords, setKeywords] = useState('');
+ const [submittedQuery, setSubmittedQuery] = useState('');
+ const useFetchConversationTopics = useEvalStore((s) => s.useFetchConversationTopics);
+ const {
+ data: topics,
+ error,
+ isLoading,
+ isValidating,
+ mutate,
+ } = useFetchConversationTopics(submittedQuery);
+ // SWR retains the failure for the error surface; don't leave an unhandled rejection.
+ const retry = () => void mutate().catch(() => undefined);
+
+ const search = () => {
+ const query = keywords.trim();
+ if (query === submittedQuery) retry();
+ else setSubmittedQuery(query);
+ };
+
+ return (
+ <Flexbox gap={12}>
+ <Text type={'secondary'}>{t('lobeBench.case.fromConversation.hint')}</Text>
+ <Input
+ aria-label={t('lobeBench.case.fromConversation.search')}
+ placeholder={t('lobeBench.case.fromConversation.search')}
+ value={keywords}
+ variant={'filled'}
+ onChange={(e) => setKeywords(e.target.value)}
+ onPressEnter={search}
+ />
+ <Block padding={4} style={{ maxHeight: 400, overflowY: 'auto' }} variant={'outlined'}>
+ <AsyncBoundary
+ data={topics}
+ error={error}
+ errorVariant={'inline'}
+ isEmpty={topics?.length === 0}
+ isLoading={isLoading || (topics === undefined && isValidating)}
+ empty={
+ <Text style={{ padding: 12 }} type={'secondary'}>
+ {t('lobeBench.case.fromConversation.empty')}
+ </Text>
+ }
+ onRetry={retry}
+ >
+ {topics?.map((topic) => (
+ <Flexbox
+ className={stylex.props(styles.row).className}
+ gap={2}
+ key={topic.id}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => {
+ onPick(topic.id);
+ close();
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ onPick(topic.id);
+ close();
+ }}
+ >
+ <Text ellipsis weight={500}>
+ {topic.title || topic.id}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {[topic.agentTitle, formatDay(topic.updatedAt)].filter(Boolean).join(' · ')}
+ </Text>
+ </Flexbox>
+ ))}
+ </AsyncBoundary>
+ {topics !== undefined && !!error && (
+ <AsyncError error={error} retrying={isValidating} variant={'inline'} onRetry={retry} />
+ )}
+ </Block>
+ </Flexbox>
+ );
+});
+
+ConversationPicker.displayName = 'LobeBenchConversationPicker';
+
+export const openConversationPicker = (onPick: (topicId: string) => void) =>
+ createModal({
+ content: <ConversationPicker onPick={onPick} />,
+ footer: null,
+ title: translate('lobeBench.case.fromConversation', { ns: 'eval' }),
+ width: 560,
+ });
+
+export default ConversationPicker;
diff --git a/src/features/LobeBench/DashboardCards.tsx b/src/features/LobeBench/DashboardCards.tsx
new file mode 100644
index 00000000000..98ad12c1f8c
--- /dev/null
+++ b/src/features/LobeBench/DashboardCards.tsx
@@ -0,0 +1,374 @@
+'use client';
+
+import type { AgentEvalExperimentListItem, AgentEvalRunListItem } from '@lobechat/types';
+import { Button, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowRight, Beaker, Database, Play, User } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getBenchmarkIcon } from '@/features/LobeBench/benchmarkIcon';
+import type { RankedContender } from '@/features/LobeBench/benchmarkRanking';
+import {
+ formatCost,
+ isCustomBenchmark,
+ isRunActive,
+ LOBE_BENCH_PATH,
+ runStats,
+} from '@/features/LobeBench/lobeBench';
+import { experimentCaseProgress, overviewAttention } from '@/features/LobeBench/overviewResults';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import RunRow from '@/routes/(main)/eval/features/Experiments/RunRow';
+
+// The Evaluation Lab's dashboard cards (features/BenchmarkCard, Experiments/SummaryCard),
+// drawn for Lobe Bench: its pages, its leaderboard rule.
+const styles = stylex.create({
+ card: {
+ height: '100%',
+ padding: 20,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ transition: 'border-color 0.15s ease',
+ },
+ iconBox: {
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 40,
+ height: 40,
+ borderRadius: cssVar.borderRadius,
+ },
+ name: {
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorPrimary },
+ textDecoration: 'none',
+ },
+ detailLink: {
+ display: 'flex',
+ flex: 'none',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 28,
+ height: 28,
+ borderRadius: cssVar.borderRadiusSM,
+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ },
+ // The headline band: the leader's pass rate, as the Evaluation Lab shows a best pass rate.
+ metricBand: {
+ padding: 16,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ metricValue: {
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: cssVar.fontSizeHeading2,
+ fontWeight: 600,
+ lineHeight: 1,
+ color: cssVar.colorText,
+ },
+ ctaBand: {
+ paddingBlock: 24,
+ paddingInline: 16,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ textAlign: 'center',
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+ fixed: { flex: 'none', whiteSpace: 'nowrap' },
+ statValue: { fontFamily: cssVar.fontFamilyCode, fontWeight: 600, color: cssVar.colorText },
+ statDivider: { width: 1, height: 24, backgroundColor: cssVar.colorBorderSecondary },
+ dot: { flexShrink: 0, width: 8, height: 8, borderRadius: '50%' },
+});
+
+const percent = (entry: RankedContender) =>
+ entry.total > 0 ? Math.round((entry.passed / entry.total) * 100) : 0;
+
+/** One labeled figure in the stat strip (big mono number over a quiet label). */
+const Stat = memo<{ label: string; value: number | string }>(({ label, value }) => (
+ <Flexbox gap={2}>
+ <Text className={stylex.props(styles.statValue).className} fontSize={16}>
+ {value}
+ </Text>
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {label}
+ </Text>
+ </Flexbox>
+));
+
+const CardHead = memo<{
+ icon: ReactNode;
+ subtitle?: ReactNode;
+ title: string;
+ to: string;
+}>(({ icon, subtitle, title, to }) => (
+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={12} style={{ minWidth: 0 }}>
+ {icon}
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <WorkspaceLink className={stylex.props(styles.name).className} to={to}>
+ {title}
+ </WorkspaceLink>
+ {subtitle && (
+ <Text color={cssVar.colorTextTertiary} fontSize={12} lineClamp={1}>
+ {subtitle}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <WorkspaceLink className={stylex.props(styles.detailLink).className} to={to}>
+ <Icon icon={ArrowRight} size={16} />
+ </WorkspaceLink>
+ </Flexbox>
+));
+
+const CtaBand = memo<{
+ action: ReactNode;
+ hint: string;
+ icon: typeof Database;
+ title: string;
+}>(({ action, hint, icon, title }) => (
+ <Flexbox align={'center'} className={stylex.props(styles.ctaBand).className} gap={8}>
+ <Icon icon={icon} size={24} style={{ color: cssVar.colorTextQuaternary }} />
+ <Flexbox align={'center'} gap={2}>
+ <Text color={cssVar.colorTextTertiary}>{title}</Text>
+ <Text color={cssVar.colorTextQuaternary} fontSize={12}>
+ {hint}
+ </Text>
+ </Flexbox>
+ {action}
+ </Flexbox>
+));
+
+interface BenchmarkCardProps {
+ benchmark: { description?: string | null; id: string; isSystem?: boolean; name: string };
+ caseCount: number;
+ datasetCount: number;
+ /** The dataset a first experiment starts on. */
+ firstDatasetId?: string;
+ /** Set when the benchmark has several datasets: the one ranked. */
+ rankedOn?: string;
+ /** The leaderboard shown: the benchmark's dataset with the most ranked contenders. */
+ ranking: RankedContender[];
+ runCount: number;
+}
+
+/**
+ * A benchmark on the dashboard: who leads its leaderboard (best full run on the
+ * current cases), the runner-ups, and what it is made of.
+ */
+export const BenchmarkCard = memo<BenchmarkCardProps>(
+ ({ benchmark, caseCount, datasetCount, firstDatasetId, ranking, rankedOn, runCount }) => {
+ const { t } = useTranslation('eval');
+ const to = `${LOBE_BENCH_PATH}/benchmarks/${benchmark.id}`;
+ const own = isCustomBenchmark(benchmark);
+ const [leader, ...rest] = ranking;
+
+ return (
+ <Flexbox className={stylex.props(styles.card).className} gap={16} justify={'space-between'}>
+ <Flexbox gap={16}>
+ <CardHead
+ subtitle={benchmark.description}
+ title={benchmark.name}
+ to={to}
+ icon={
+ <div
+ className={stylex.props(styles.iconBox).className}
+ style={{ background: own ? cssVar.colorSuccessBg : cssVar.colorPrimaryBg }}
+ >
+ <Icon
+ icon={own ? User : getBenchmarkIcon(benchmark.id)}
+ size={22}
+ style={{ color: own ? cssVar.colorSuccess : cssVar.colorPrimary }}
+ />
+ </div>
+ }
+ />
+
+ {datasetCount === 0 ? (
+ <CtaBand
+ hint={t('lobeBench.overview.card.noDatasetHint')}
+ icon={Database}
+ title={t('lobeBench.overview.card.noDataset')}
+ action={
+ <WorkspaceLink style={{ textDecoration: 'none' }} to={to}>
+ <Button size={'small'} type={'fill'}>
+ {t('lobeBench.overview.card.openBenchmark')}
+ </Button>
+ </WorkspaceLink>
+ }
+ />
+ ) : leader ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.metricBand).className}
+ gap={16}
+ justify={'space-between'}
+ >
+ <Flexbox gap={6} style={{ minWidth: 0 }}>
+ <span className={stylex.props(styles.metricValue).className}>
+ {percent(leader)}%
+ </span>
+ <Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>
+ {t('lobeBench.overview.card.top', { name: leader.name })}
+ {rankedOn && ` · ${t('lobeBench.overview.card.on', { dataset: rankedOn })}`}
+ </Text>
+ </Flexbox>
+ {rest.length > 0 && (
+ <Flexbox gap={4} style={{ flex: '0 1 50%', minWidth: 0 }}>
+ {rest.slice(0, 2).map((entry, index) => (
+ <Flexbox horizontal align={'center'} gap={8} key={entry.run.id}>
+ <Text
+ className={stylex.props(styles.mono, styles.fixed).className}
+ color={cssVar.colorTextQuaternary}
+ fontSize={12}
+ >
+ #{index + 2}
+ </Text>
+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }}>
+ {entry.name}
+ </Text>
+ <Text
+ className={stylex.props(styles.mono, styles.fixed).className}
+ fontSize={12}
+ >
+ {percent(entry)}%
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ ) : (
+ <CtaBand
+ hint={t('lobeBench.overview.card.noRunHint')}
+ icon={Beaker}
+ title={t('lobeBench.overview.card.noRun')}
+ action={
+ <WorkspaceLink
+ style={{ textDecoration: 'none' }}
+ to={
+ firstDatasetId
+ ? `${LOBE_BENCH_PATH}/experiments/new?dataset=${firstDatasetId}`
+ : `${LOBE_BENCH_PATH}/experiments/new`
+ }
+ >
+ <Button icon={Play} size={'small'} type={'fill'}>
+ {t('lobeBench.overview.newExperiment')}
+ </Button>
+ </WorkspaceLink>
+ }
+ />
+ )}
+ </Flexbox>
+
+ <Flexbox horizontal align={'center'} gap={20}>
+ <Stat label={t('sidebar.datasets')} value={datasetCount} />
+ <span className={stylex.props(styles.statDivider).className} />
+ <Stat label={t('benchmark.card.casesLabel')} value={caseCount} />
+ <span className={stylex.props(styles.statDivider).className} />
+ <Stat label={t('lobeBench.overview.card.runs')} value={runCount} />
+ <span className={stylex.props(styles.statDivider).className} />
+ <Stat label={t('lobeBench.overview.card.contenders')} value={ranking.length} />
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+BenchmarkCard.displayName = 'LobeBenchDashboardBenchmarkCard';
+
+interface ExperimentCardProps {
+ /** The benchmark each run's page lives under, by run id. */
+ benchmarkIdOf: (run: AgentEvalRunListItem) => string;
+ description: string;
+ experiment: AgentEvalExperimentListItem;
+ runs: AgentEvalRunListItem[];
+}
+
+const ATTENTION = [
+ ['errors', 'lobeBench.overview.attention.errors'],
+ ['judgeErrors', 'lobeBench.overview.attention.judgeErrors'],
+ ['unaccounted', 'lobeBench.overview.attention.ungraded'],
+ ['external', 'lobeBench.overview.attention.external'],
+] as const;
+
+/**
+ * An experiment on the dashboard, as the Evaluation Lab shows one: what it ran,
+ * its progress while running, what needs a look, and its latest runs.
+ */
+export const ExperimentCard = memo<ExperimentCardProps>(
+ ({ benchmarkIdOf, description, experiment, runs }) => {
+ const { t } = useTranslation('eval');
+ const to = `${LOBE_BENCH_PATH}/experiments/${experiment.id}`;
+ const active = runs.some((run) => isRunActive(run.status));
+ const progress = experimentCaseProgress(runs);
+ const cost = runs.reduce((sum, run) => sum + (runStats(run).totalCost ?? 0), 0);
+ const attention = overviewAttention(runs);
+ const flags = ATTENTION.filter(([key]) => attention[key] > 0);
+
+ return (
+ <Flexbox className={stylex.props(styles.card).className} gap={16}>
+ <CardHead
+ subtitle={`${description}${!active && cost > 0 ? ` · ${formatCost(cost, 2)}` : ''}`}
+ title={experiment.name || t('lobeBench.experiment.unnamed')}
+ to={to}
+ icon={
+ <div
+ className={stylex.props(styles.iconBox).className}
+ style={{ background: cssVar.colorInfoBg }}
+ >
+ <Icon icon={Beaker} size={22} style={{ color: cssVar.colorInfo }} />
+ </div>
+ }
+ />
+
+ {(active || flags.length > 0) && (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ {active && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <span
+ className={stylex.props(styles.dot).className}
+ style={{ background: cssVar.colorPrimary }}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.overview.running')} ·{' '}
+ {t('lobeBench.overview.runningLine', {
+ cost: formatCost(cost, 2),
+ done: progress.done,
+ total: progress.total,
+ })}
+ </Text>
+ </Flexbox>
+ )}
+ {flags.map(([key, label]) => (
+ <Tag color={'warning'} key={key}>
+ {t(label, { count: attention[key] })}
+ </Tag>
+ ))}
+ </Flexbox>
+ )}
+
+ {runs.length > 0 && (
+ <Flexbox gap={0}>
+ {runs.slice(0, 3).map((run) => (
+ <RunRow benchmarkId={benchmarkIdOf(run)} key={run.id} run={run} />
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+ExperimentCard.displayName = 'LobeBenchDashboardExperimentCard';
diff --git a/src/features/LobeBench/Dataset/index.tsx b/src/features/LobeBench/Dataset/index.tsx
new file mode 100644
index 00000000000..0a857b7aa94
--- /dev/null
+++ b/src/features/LobeBench/Dataset/index.tsx
@@ -0,0 +1,236 @@
+'use client';
+
+import { Button, confirmModal, Empty, Flexbox, Tag, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ImportIcon, Pencil, Trash2 } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { DatasetConnections } from '@/features/AgentEval/ConnectorBindings/DatasetConnections';
+import CaseTable from '@/features/LobeBench/CaseTable';
+import { refreshLobeBenchDatasets } from '@/features/LobeBench/datasetCases';
+import {
+ caseCountOf,
+ getDatasetMeta,
+ isBuiltInRow,
+ isCustomBenchmark,
+ isCustomDataset,
+ isFullRun,
+ LOBE_BENCH_PATH,
+ runCaseCount,
+} from '@/features/LobeBench/lobeBench';
+import { openRenameDatasetModal } from '@/features/LobeBench/PicksDatasetModal';
+import { useImportLobeBenchDataset } from '@/features/LobeBench/useImportDataset';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import { createRunEditModal } from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal';
+import RunCard from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard';
+import { agentEvalService } from '@/services/agentEval';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ sectionTitle: {
+ margin: 0,
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+ grid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))',
+ gap: 12,
+ },
+ empty: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: 32,
+ paddingInline: 24,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+});
+
+/**
+ * One dataset: the cases it holds and the runs on it, as the Evaluation Lab
+ * shows a dataset. Its cases are fixed once it is made, so
+ * its runs stay true to it. Imported packages create a new dataset, keeping
+ * existing runs attached to their cases, including when all cases are retired.
+ */
+const LobeBenchDataset = memo(() => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const importDataset = useImportLobeBenchDataset();
+ const { datasetId } = useParams<{ datasetId: string }>();
+ const { benchmarks, isLoading } = useLobeBenchBenchmarks();
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ const dataset = datasets?.find((d) => d.id === datasetId);
+ const benchmark = benchmarks.find((b) => b.id === dataset?.benchmarkId);
+ const meta = dataset ? getDatasetMeta(dataset) : {};
+ const own = !!dataset && isCustomDataset(dataset);
+ const { data: allRuns, mutate: refreshRuns } = useLobeBenchRuns(benchmarkIds);
+ const runs = useMemo(
+ () =>
+ (allRuns ?? [])
+ .filter((run) => run.datasetId === datasetId)
+ .sort(
+ (a, b) => new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime(),
+ ),
+ [allRuns, datasetId],
+ );
+
+ if (!dataset) {
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
+ {!isLoading && datasets && <Empty description={t('lobeBench.dataset.notFound')} />}
+ </Flexbox>
+ );
+ }
+
+ const count = caseCountOf(dataset);
+ const remove = () =>
+ confirmModal({
+ content: t('lobeBench.picks.delete.confirm', { name: dataset.name }),
+ okButtonProps: { danger: true },
+ okText: t('lobeBench.picks.delete'),
+ onOk: async () => {
+ const result = (await agentEvalService.deleteDataset(dataset.id)) as {
+ error?: string;
+ success?: boolean;
+ };
+ if (result?.success === false) {
+ toast.error(result.error ?? t('lobeBench.picks.failed'));
+ return;
+ }
+ await refreshLobeBenchDatasets();
+ navigate(`${LOBE_BENCH_PATH}/library`);
+ },
+ title: t('lobeBench.picks.delete'),
+ });
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={20}>
+ <Flexbox horizontal align={'flex-end'} gap={16} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox gap={6} style={{ minWidth: 0 }}>
+ {/* The benchmark the dataset makes up: a built-in one's, or one the account
+ made; the account's other datasets are in none. */}
+ {benchmark && (!own || isCustomBenchmark(benchmark)) && (
+ <WorkspaceLink to={`${LOBE_BENCH_PATH}/benchmarks/${benchmark.id}`}>
+ <Text fontSize={12} type={'secondary'}>
+ {benchmark.name}
+ </Text>
+ </WorkspaceLink>
+ )}
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {dataset.name}
+ </Text>
+ {own ? (
+ <Text type={'secondary'}>{t('lobeBench.dataset.own.subtitle', { count })}</Text>
+ ) : (
+ dataset.description && <Text type={'secondary'}>{dataset.description}</Text>
+ )}
+ <Flexbox horizontal gap={6} wrap={'wrap'}>
+ {own && <Tag>{t('lobeBench.dataset.custom')}</Tag>}
+ {meta.release && <Tag>{t('lobeBench.dataset.release', { release: meta.release })}</Tag>}
+ {!own && (
+ <Tag>
+ {isBuiltInRow(dataset as { userId?: string | null })
+ ? t('lobeBench.builtIn')
+ : t('lobeBench.case.readOnly')}
+ </Tag>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ <Button
+ icon={ImportIcon}
+ type={count === 0 ? 'primary' : 'default'}
+ onClick={() => importDataset()}
+ >
+ {t('dataset.import.package.asNew')}
+ </Button>
+ {own && (
+ <>
+ <Button icon={Pencil} onClick={() => openRenameDatasetModal(dataset)}>
+ {t('lobeBench.picks.rename')}
+ </Button>
+ {/* One in a benchmark is deleted with the benchmark, which keeps it. */}
+ {dataset.benchmarkId ? (
+ <Button disabled icon={Trash2} title={t('lobeBench.dataset.deleteInBenchmark')}>
+ {t('lobeBench.picks.delete')}
+ </Button>
+ ) : (
+ <Button danger icon={Trash2} onClick={remove}>
+ {t('lobeBench.picks.delete')}
+ </Button>
+ )}
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ <CaseTable benchmarkIds={benchmarkIds} dataset={dataset} />
+
+ {/* The runs on this dataset, as the Evaluation Lab lists a dataset's runs. */}
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <h3 className={stylex.props(styles.sectionTitle).className}>
+ {t('lobeBench.benchmark.runs')}
+ </h3>
+ {runs.length > 0 && (
+ <Text type={'secondary'}>
+ {t('lobeBench.dataset.runCount', { count: runs.length })}
+ </Text>
+ )}
+ </Flexbox>
+ {runs.length === 0 ? (
+ <Flexbox className={stylex.props(styles.empty).className}>
+ <Text type={'secondary'}>{t('lobeBench.dataset.noRuns')}</Text>
+ </Flexbox>
+ ) : (
+ <div className={stylex.props(styles.grid).className}>
+ {runs.map((run) => (
+ <RunCard
+ benchmarkId={dataset.benchmarkId ?? benchmarkIds[0]}
+ key={run.id}
+ run={run}
+ note={
+ isFullRun(run) || !count
+ ? undefined
+ : t('lobeBench.benchmark.runCases', {
+ selected: runCaseCount(run, count),
+ total: count,
+ })
+ }
+ onEdit={(editingRun) => createRunEditModal({ run: editingRun })}
+ onRefresh={async () => {
+ await refreshRuns();
+ }}
+ />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ <DatasetConnections datasetId={dataset.id} editable={own} key={dataset.id} />
+ </Flexbox>
+ );
+});
+
+LobeBenchDataset.displayName = 'LobeBenchDataset';
+
+export default LobeBenchDataset;
diff --git a/src/features/LobeBench/Environments/index.tsx b/src/features/LobeBench/Environments/index.tsx
new file mode 100644
index 00000000000..b4d1f0f77bb
--- /dev/null
+++ b/src/features/LobeBench/Environments/index.tsx
@@ -0,0 +1,589 @@
+'use client';
+
+import type { EvalCaseEnvironment, EvalMemoryFixture } from '@lobechat/types';
+import {
+ Block,
+ Button,
+ confirmModal,
+ Drawer,
+ Empty,
+ Flexbox,
+ Input,
+ Segmented,
+ Select,
+ Switch,
+ Tag,
+ Text,
+ TextArea,
+ toast,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Plus } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isBuiltInRow } from '@/features/LobeBench/lobeBench';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+import type { EvalEnvironmentRow } from '@/store/eval/slices/lobeBench/projection';
+
+import { saveEnvironment } from './saveEnvironment';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ table: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1.6fr) minmax(0, 2fr) 120px',
+ columnGap: 12,
+ alignItems: 'center',
+ },
+ head: {
+ paddingBlock: 8,
+ paddingInline: 12,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ row: {
+ cursor: 'pointer',
+ paddingBlock: 10,
+ paddingInline: 12,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+});
+
+type EnvironmentRow = EvalEnvironmentRow;
+
+type Effort = 'high' | 'low' | 'medium';
+type Permission = 'read-only' | 'read-write';
+
+const joinList = (list?: string[]) => (list ?? []).join(', ');
+const splitList = (value: string) =>
+ value
+ .split(',')
+ .map((item) => item.trim())
+ .filter(Boolean);
+
+/** A valid seed fixture in the shape the native Memory schemas expect. */
+const MEMORY_TEMPLATE: EvalMemoryFixture = {
+ contexts: [
+ {
+ details: 'The user is training for a 10 km race in November.',
+ memoryCategory: 'fitness',
+ memoryType: 'context',
+ sourceIds: [],
+ summary: 'Training for a 10 km race in November',
+ tags: ['running', 'race'],
+ title: 'Training for a 10 km race',
+ withContext: {
+ associatedObjects: [],
+ associatedSubjects: [],
+ currentStatus: 'ongoing',
+ description: 'The user is training for a 10 km race in November.',
+ labels: ['running', 'race'],
+ scoreImpact: 0.6,
+ scoreUrgency: 0.5,
+ title: 'Training for a 10 km race',
+ type: 'ongoing',
+ },
+ },
+ ],
+ persona: { narrative: 'A runner who trains three mornings a week.', tagline: 'morning runner' },
+ preferences: [
+ {
+ details: 'Prefers short, numbered plans over long explanations.',
+ memoryCategory: 'format',
+ memoryType: 'preference',
+ sourceIds: [],
+ summary: 'Prefers short, numbered plans',
+ tags: ['format', 'plans'],
+ title: 'Prefers short, numbered plans',
+ withPreference: {
+ appContext: null,
+ conclusionDirectives: 'Give plans as short numbered lists, one line per step.',
+ extractedLabels: ['format', 'plans'],
+ extractedScopes: [],
+ originContext: null,
+ scorePriority: 0.8,
+ suggestions: [],
+ type: 'personal',
+ },
+ },
+ ],
+ seededAt: '2026-07-20T09:00:00Z',
+};
+
+/**
+ * Reusable case environments: the persona, tools, Memory, clock and mock
+ * connectors many cases share. A case points at one and may override a few
+ * fields; changing an environment changes every case that uses it.
+ */
+const LobeBenchEnvironments = memo(() => {
+ const { t } = useTranslation('eval');
+ const {
+ data: environments,
+ isLoading,
+ mutate: refresh,
+ } = useEvalStore.getState().useFetchEvalEnvironments();
+ const [editing, setEditing] = useState<{ row?: EnvironmentRow } | undefined>();
+
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [persona, setPersona] = useState('');
+ const [agentName, setAgentName] = useState('');
+ const [plugins, setPlugins] = useState('');
+ const [memoryEnabled, setMemoryEnabled] = useState(false);
+ const [memoryEffort, setMemoryEffort] = useState<Effort>('medium');
+ const [memoryPermission, setMemoryPermission] = useState<Permission>('read-only');
+ const [memoryJson, setMemoryJson] = useState('');
+ const [sessionDate, setSessionDate] = useState('');
+ const [timezone, setTimezone] = useState('');
+ const [envPrompt, setEnvPrompt] = useState('');
+ const [mockServices, setMockServices] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // The drawer shows the environment being edited, or empty fields for a new one.
+ useEffect(() => {
+ if (!editing) return;
+ const config = editing.row?.config ?? {};
+ setName(editing.row?.name ?? '');
+ setDescription(editing.row?.description ?? '');
+ setPersona(config.agent?.systemRole ?? '');
+ setAgentName(config.agent?.name ?? '');
+ setPlugins(joinList(config.agent?.plugins));
+ setMemoryEnabled(config.agent?.memory?.enabled ?? false);
+ setMemoryEffort((config.agent?.memory?.effort as Effort | undefined) ?? 'medium');
+ setMemoryPermission(config.agent?.memory?.toolPermission ?? 'read-only');
+ setMemoryJson(config.memory ? JSON.stringify(config.memory, null, 2) : '');
+ setSessionDate(config.sessionDate ?? '');
+ setTimezone(config.timezone ?? '');
+ setEnvPrompt(config.envPrompt ?? '');
+ setMockServices(joinList(config.mock?.services));
+ }, [editing]);
+
+ // A rejected save names each bad field: the server answers with the
+ // validator's issue list, which reads badly as one JSON line.
+ const fail = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ try {
+ const issues = JSON.parse(message) as Array<{ message?: string; path?: unknown[] }>;
+ if (Array.isArray(issues) && issues.length > 0) {
+ toast.error(
+ issues
+ .slice(0, 6)
+ .map((issue) => `${(issue.path ?? []).join('.')}: ${issue.message ?? ''}`)
+ .join('\n'),
+ );
+ return;
+ }
+ } catch {
+ /* not a validator answer */
+ }
+ toast.error(message);
+ };
+
+ const buildConfig = (): EvalCaseEnvironment | undefined => {
+ if (sessionDate.trim() && Number.isNaN(Date.parse(sessionDate.trim()))) {
+ toast.error(t('lobeBench.case.editor.invalidDate'));
+ return;
+ }
+ let memory: EvalMemoryFixture | undefined;
+ if (memoryJson.trim()) {
+ try {
+ const parsed = JSON.parse(memoryJson);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
+ throw new Error('object');
+ memory = parsed as EvalMemoryFixture;
+ } catch {
+ toast.error(t('lobeBench.environments.editor.memory.invalid'));
+ return;
+ }
+ }
+ const pluginList = splitList(plugins);
+ const services = splitList(mockServices);
+ const {
+ name: _name,
+ memory: _memory,
+ plugins: _plugins,
+ systemRole: _systemRole,
+ ...agentRest
+ } = editing?.row?.config?.agent ?? {};
+ const agent = {
+ ...agentRest,
+ ...(agentName.trim() && { name: agentName.trim() }),
+ ...(memoryEnabled && {
+ memory: { effort: memoryEffort, enabled: true, toolPermission: memoryPermission },
+ }),
+ ...(plugins.trim() && { plugins: pluginList }),
+ ...(persona.trim() && { systemRole: persona.trim() }),
+ };
+ return {
+ ...(editing?.row?.config?.toolManifests && {
+ toolManifests: editing.row.config.toolManifests,
+ }),
+ ...(editing?.row?.config?.toolForwarding && {
+ toolForwarding: editing.row.config.toolForwarding,
+ }),
+ connectorBindings: editing?.row?.id ? editing.row.config?.connectorBindings : undefined,
+ ...(Object.keys(agent).length > 0 && { agent }),
+ ...(envPrompt.trim() && { envPrompt: envPrompt.trim() }),
+ ...(memory && { memory }),
+ ...(services.length > 0 && { mock: { ...editing?.row?.config?.mock, services } }),
+ ...(sessionDate.trim() && { sessionDate: sessionDate.trim() }),
+ ...(timezone.trim() && { timezone: timezone.trim() }),
+ };
+ };
+
+ const save = async () => {
+ if (!name.trim()) return;
+ const config = buildConfig();
+ if (!config) return;
+ setSaving(true);
+ try {
+ await saveEnvironment({ config, description, name, row: editing?.row });
+ await refresh();
+ toast.success(t('lobeBench.environments.editor.saved'));
+ setEditing(undefined);
+ } catch (error) {
+ fail(error);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const duplicate = () => {
+ if (!editing?.row) return;
+ setEditing({
+ row: {
+ ...editing.row,
+ id: '',
+ name: `${editing.row.name} (copy)`,
+ testCaseCount: 0,
+ },
+ });
+ };
+
+ const remove = () => {
+ const row = editing?.row;
+ if (!row?.id) return;
+ confirmModal({
+ content: t('lobeBench.environments.delete.confirm', { count: row.testCaseCount ?? 0 }),
+ okButtonProps: { danger: true },
+ okText: t('lobeBench.case.delete'),
+ onOk: async () => {
+ try {
+ await agentEvalService.deleteEnvironment(row.id);
+ await refresh();
+ setEditing(undefined);
+ } catch (error) {
+ fail(error);
+ }
+ },
+ title: t('lobeBench.case.delete'),
+ });
+ };
+
+ const isNew = !editing?.row?.id;
+ const usedBy = editing?.row?.testCaseCount ?? 0;
+ // A built-in environment is shown as is; "Duplicate" makes an editable copy.
+ const readOnly = !isNew && isBuiltInRow(editing?.row);
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={20}>
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {t('lobeBench.environments.title')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.environments.subtitle')}</Text>
+ </Flexbox>
+ <Button icon={Plus} type={'primary'} onClick={() => setEditing({})}>
+ {t('lobeBench.environments.new')}
+ </Button>
+ </Flexbox>
+
+ <Block padding={8} variant={'outlined'}>
+ <Flexbox gap={2}>
+ <div className={stylex.props(styles.table, styles.head).className}>
+ <span>{t('lobeBench.environments.col.name')}</span>
+ <span>{t('lobeBench.environments.col.setup')}</span>
+ <span style={{ textAlign: 'right' }}>{t('lobeBench.environments.col.cases')}</span>
+ </div>
+ {!isLoading && (environments?.length ?? 0) === 0 && (
+ <Empty description={t('lobeBench.environments.empty')} />
+ )}
+ {(environments ?? []).map((row) => {
+ const config = row.config ?? {};
+ const parts = [
+ config.agent?.plugins?.length
+ ? t('lobeBench.environments.setup.tools', { count: config.agent.plugins.length })
+ : undefined,
+ config.agent?.memory?.enabled
+ ? t('lobeBench.environments.setup.memory', {
+ permission: config.agent.memory.toolPermission ?? 'read-only',
+ })
+ : undefined,
+ config.sessionDate
+ ? t('lobeBench.environments.setup.clock', { date: config.sessionDate })
+ : undefined,
+ config.mock?.services?.length
+ ? t('lobeBench.environments.setup.mock', { count: config.mock.services.length })
+ : undefined,
+ ].filter(Boolean);
+ return (
+ <div
+ className={stylex.props(styles.table, styles.row).className}
+ key={row.id}
+ onClick={() => setEditing({ row })}
+ >
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Text ellipsis weight={500}>
+ {row.name}
+ </Text>
+ {isBuiltInRow(row) && <Tag>{t('lobeBench.builtIn')}</Tag>}
+ </Flexbox>
+ {row.description && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {row.description}
+ </Text>
+ )}
+ </Flexbox>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {parts.length > 0 ? parts.join(' · ') : t('lobeBench.environments.setup.none')}
+ </Text>
+ <Text
+ className={stylex.props(styles.mono).className}
+ style={{ textAlign: 'right' }}
+ >
+ {row.testCaseCount ?? 0}
+ </Text>
+ </div>
+ );
+ })}
+ </Flexbox>
+ </Block>
+
+ <Drawer
+ open={!!editing}
+ width={640}
+ title={
+ isNew ? t('lobeBench.environments.editor.new') : t('lobeBench.environments.editor.edit')
+ }
+ onClose={() => setEditing(undefined)}
+ >
+ {editing && (
+ <Flexbox gap={20}>
+ {readOnly && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.environments.editor.builtIn')}
+ </Text>
+ )}
+ {!isNew && usedBy > 0 && (
+ <Tag color={'warning'}>
+ {t('lobeBench.environments.editor.impact', { count: usedBy })}
+ </Tag>
+ )}
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.environments.editor.name')}</Text>
+ <Input
+ disabled={readOnly}
+ value={name}
+ variant={'filled'}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.environments.editor.description')}</Text>
+ <Input
+ disabled={readOnly}
+ value={description}
+ variant={'filled'}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.persona')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 10, minRows: 3 }}
+ disabled={readOnly}
+ value={persona}
+ variant={'filled'}
+ onChange={(e) => setPersona(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.environments.editor.agentName')}</Text>
+ <Input
+ disabled={readOnly}
+ value={agentName}
+ variant={'filled'}
+ onChange={(e) => setAgentName(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.plugins')}</Text>
+ <Input
+ disabled={readOnly}
+ placeholder={'lobe-web-browsing, gmail'}
+ value={plugins}
+ variant={'filled'}
+ onChange={(e) => setPlugins(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.mock')}</Text>
+ <Input
+ disabled={readOnly}
+ placeholder={'gmail, linear'}
+ value={mockServices}
+ variant={'filled'}
+ onChange={(e) => setMockServices(e.target.value)}
+ />
+ </Flexbox>
+ {splitList(mockServices).length > 0 && (
+ <Text type="secondary">{t('connections.datasetOnly')}</Text>
+ )}
+ <Flexbox gap={10}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('lobeBench.environments.editor.memory')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.environments.editor.memory.hint')}
+ </Text>
+ </Flexbox>
+ <Switch
+ checked={memoryEnabled}
+ disabled={readOnly}
+ onChange={(value) => setMemoryEnabled(!!value)}
+ />
+ </Flexbox>
+ {memoryEnabled && (
+ <Flexbox horizontal gap={12} wrap={'wrap'}>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>
+ {t('lobeBench.environments.editor.memory.permission')}
+ </Text>
+ <Segmented
+ disabled={readOnly}
+ size={'small'}
+ value={memoryPermission}
+ options={[
+ { label: 'read-only', value: 'read-only' },
+ { label: 'read-write', value: 'read-write' },
+ ]}
+ onChange={(value) => setMemoryPermission(value as Permission)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13}>{t('lobeBench.environments.editor.memory.effort')}</Text>
+ <Select
+ disabled={readOnly}
+ size={'small'}
+ style={{ width: 140 }}
+ value={memoryEffort}
+ options={[
+ { label: 'low', value: 'low' },
+ { label: 'medium', value: 'medium' },
+ { label: 'high', value: 'high' },
+ ]}
+ onChange={(value) => setMemoryEffort(value as Effort)}
+ />
+ </Flexbox>
+ </Flexbox>
+ )}
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text fontSize={13}>{t('lobeBench.environments.editor.memory.seeds')}</Text>
+ {!memoryJson.trim() && (
+ <Button
+ size={'small'}
+ type={'text'}
+ onClick={() => setMemoryJson(JSON.stringify(MEMORY_TEMPLATE, null, 2))}
+ >
+ {t('lobeBench.environments.editor.memory.template')}
+ </Button>
+ )}
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 18, minRows: 4 }}
+ disabled={readOnly}
+ placeholder={t('lobeBench.environments.editor.memory.placeholder')}
+ style={{ fontFamily: cssVar.fontFamilyCode, fontSize: 12 }}
+ value={memoryJson}
+ variant={'filled'}
+ onChange={(e) => setMemoryJson(e.target.value)}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.sessionDate')}</Text>
+ <Input
+ disabled={readOnly}
+ placeholder={'2026-07-20T09:00:00Z'}
+ value={sessionDate}
+ variant={'filled'}
+ onChange={(e) => setSessionDate(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.case.editor.timezone')}</Text>
+ <Input
+ disabled={readOnly}
+ placeholder={'America/New_York'}
+ value={timezone}
+ variant={'filled'}
+ onChange={(e) => setTimezone(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.environments.editor.envPrompt')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ disabled={readOnly}
+ value={envPrompt}
+ variant={'filled'}
+ onChange={(e) => setEnvPrompt(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox horizontal gap={8}>
+ {!isNew && (
+ <>
+ <Button onClick={duplicate}>
+ {t('lobeBench.environments.editor.duplicate')}
+ </Button>
+ {!readOnly && (
+ <Button danger onClick={remove}>
+ {t('lobeBench.case.delete')}
+ </Button>
+ )}
+ </>
+ )}
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ <Button onClick={() => setEditing(undefined)}>{t('lobeBench.new.cancel')}</Button>
+ {!readOnly && (
+ <Button disabled={!name.trim()} loading={saving} type={'primary'} onClick={save}>
+ {t('lobeBench.case.editor.save')}
+ </Button>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Drawer>
+ </Flexbox>
+ );
+});
+
+LobeBenchEnvironments.displayName = 'LobeBenchEnvironments';
+
+export default LobeBenchEnvironments;
diff --git a/src/features/LobeBench/Environments/saveEnvironment.test.ts b/src/features/LobeBench/Environments/saveEnvironment.test.ts
new file mode 100644
index 00000000000..73b68f90feb
--- /dev/null
+++ b/src/features/LobeBench/Environments/saveEnvironment.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentEvalService } from '@/services/agentEval';
+
+import { saveEnvironment } from './saveEnvironment';
+
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: { createEnvironment: vi.fn(), updateEnvironment: vi.fn() },
+}));
+
+const draft = { config: { timezone: 'UTC' }, description: ' description ', name: ' Environment ' };
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('saving environment drafts', () => {
+ it.each([undefined, { id: '' }])(
+ 'creates a new record for a new or duplicated draft: %j',
+ async (row) => {
+ await saveEnvironment({ ...draft, row });
+ expect(agentEvalService.createEnvironment).toHaveBeenCalledWith({
+ config: draft.config,
+ description: 'description',
+ identifier: expect.stringMatching(/^env-/),
+ name: 'Environment',
+ });
+ expect(agentEvalService.updateEnvironment).not.toHaveBeenCalled();
+ },
+ );
+
+ it('updates the existing id and allows its description to be cleared', async () => {
+ await saveEnvironment({ ...draft, description: ' ', row: { id: 'existing-environment' } });
+ expect(agentEvalService.updateEnvironment).toHaveBeenCalledWith({
+ config: draft.config,
+ description: null,
+ id: 'existing-environment',
+ name: 'Environment',
+ });
+ expect(agentEvalService.createEnvironment).not.toHaveBeenCalled();
+ });
+
+ it('propagates a failed save to the editor without a fallback mutation', async () => {
+ const failure = new Error('Environment save rejected');
+ vi.mocked(agentEvalService.createEnvironment).mockRejectedValueOnce(failure);
+ await expect(saveEnvironment(draft)).rejects.toBe(failure);
+ expect(agentEvalService.updateEnvironment).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/LobeBench/Environments/saveEnvironment.ts b/src/features/LobeBench/Environments/saveEnvironment.ts
new file mode 100644
index 00000000000..3e19e04f7fe
--- /dev/null
+++ b/src/features/LobeBench/Environments/saveEnvironment.ts
@@ -0,0 +1,28 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+
+import { agentEvalService } from '@/services/agentEval';
+
+interface EnvironmentDraft {
+ config: EvalCaseEnvironment;
+ description: string;
+ name: string;
+ row?: { id: string };
+}
+
+/** A copied environment has no persisted id and must be saved as a new record. */
+export const saveEnvironment = async ({ config, description, name, row }: EnvironmentDraft) => {
+ if (row?.id) {
+ return agentEvalService.updateEnvironment({
+ config,
+ description: description.trim() || null,
+ id: row.id,
+ name: name.trim(),
+ });
+ }
+ return agentEvalService.createEnvironment({
+ config,
+ description: description.trim() || undefined,
+ identifier: `env-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
+ name: name.trim(),
+ });
+};
diff --git a/src/features/LobeBench/Experiment/LaunchPage.tsx b/src/features/LobeBench/Experiment/LaunchPage.tsx
new file mode 100644
index 00000000000..5cec19bcf4b
--- /dev/null
+++ b/src/features/LobeBench/Experiment/LaunchPage.tsx
@@ -0,0 +1,106 @@
+'use client';
+
+import { Alert, Block, Button, Flexbox, Text } from '@lobehub/ui';
+import { type ReactNode, useEffect, useState, useSyncExternalStore } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import {
+ backgroundLaunchKey,
+ findSavedExperimentLaunch,
+ getBackgroundLaunch,
+ startBackgroundLaunch,
+ subscribeBackgroundLaunch,
+} from '../launchBackground';
+import { launchServices } from '../launchServices';
+import { LOBE_BENCH_PATH } from '../lobeBench';
+import { LaunchProgressPanel } from '../NewExperiment/LaunchProgress';
+import { useLobeBenchExperiments } from '../useLobeBench';
+
+export const LaunchPage = ({ children }: { children: ReactNode }) => {
+ const { experimentId = '' } = useParams<{ experimentId: string }>();
+ const userId = useUserStore(userProfileSelectors.userId);
+ const workspaceId = useActiveWorkspaceId();
+ const navigate = useWorkspaceAwareNavigate();
+ const { t } = useTranslation('eval');
+ const { mutate } = useLobeBenchExperiments();
+ const key = backgroundLaunchKey(userId ?? '', workspaceId, experimentId);
+ const state = useSyncExternalStore(
+ subscribeBackgroundLaunch,
+ () => getBackgroundLaunch(key),
+ () => undefined,
+ );
+ // Scope the checkpoint to the current account and route, including after navigation.
+ const saved = userId ? findSavedExperimentLaunch(userId, workspaceId, experimentId) : undefined;
+ const record = state?.record ?? saved;
+ const [recovering, setRecovering] = useState(false);
+ const [, refreshCheckpoint] = useState(0);
+ useEffect(() => {
+ const update = () => refreshCheckpoint((value) => value + 1);
+ window.addEventListener('storage', update);
+ return () => window.removeEventListener('storage', update);
+ }, []);
+ const hasState = !!state;
+ useEffect(() => {
+ if (!hasState) return;
+ void mutate();
+ }, [hasState, state?.active, state?.outcome, mutate]);
+ if (!record || state?.outcome?.complete) return children;
+ const active = state?.active || recovering;
+ const error =
+ state?.error === 'launch_busy'
+ ? t('lobeBench.new.launch.busy')
+ : (state?.error ?? state?.outcome?.error?.message);
+ const resume = async () => {
+ if (!userId || active) return;
+ setRecovering(true);
+ try {
+ await startBackgroundLaunch(
+ { benchmarkId: record.benchmarkId, userId, workspaceId },
+ record,
+ launchServices,
+ );
+ } catch {
+ /* Displayed through the shared launch state. */
+ } finally {
+ setRecovering(false);
+ }
+ };
+ return (
+ <Flexbox gap={20} padding={32}>
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {record.name}
+ </Text>
+ <Button onClick={() => navigate(LOBE_BENCH_PATH)}>{t('lobeBench.new.launch.back')}</Button>
+ </Flexbox>
+ <Block padding={24}>
+ <Flexbox gap={16}>
+ <Text weight={600}>
+ {t(active ? 'lobeBench.new.launch.title' : 'lobeBench.new.launch.interrupted')}
+ </Text>
+ {state?.progress && (
+ <LaunchProgressPanel
+ active={!!active}
+ createdAt={record.createdAt}
+ progress={state.progress}
+ />
+ )}
+ {error && <Alert title={error} type={'warning'} />}
+ {!active && (
+ <>
+ <Text>{t('lobeBench.new.launch.recovery')}</Text>
+ <Button onClick={resume}>{t('lobeBench.new.launch.recheck')}</Button>
+ </>
+ )}
+ </Flexbox>
+ </Block>
+ {(state?.progress?.stage === 'start' || state?.outcome?.metadataSaved) && children}
+ </Flexbox>
+ );
+};
diff --git a/src/features/LobeBench/Experiment/heatStyle.ts b/src/features/LobeBench/Experiment/heatStyle.ts
new file mode 100644
index 00000000000..fcd2c8a39fd
--- /dev/null
+++ b/src/features/LobeBench/Experiment/heatStyle.ts
@@ -0,0 +1,12 @@
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+
+/** A category cell's colours: greener the higher its pass rate, muted with none. */
+export const heatStyle = (rate: number | undefined) => {
+ if (rate === undefined)
+ return { background: cssVar.colorFillQuaternary, color: cssVar.colorTextQuaternary };
+ const alpha = 0.12 + rate * 0.5;
+ return {
+ background: `color-mix(in srgb, ${cssVar.colorSuccess} ${Math.round(alpha * 100)}%, transparent)`,
+ color: cssVar.colorText,
+ };
+};
diff --git a/src/features/LobeBench/Experiment/index.tsx b/src/features/LobeBench/Experiment/index.tsx
new file mode 100644
index 00000000000..e1ff98fc759
--- /dev/null
+++ b/src/features/LobeBench/Experiment/index.tsx
@@ -0,0 +1,1191 @@
+'use client';
+
+import { evalCaseVersionOf } from '@lobechat/types';
+import {
+ Alert,
+ Block,
+ Button,
+ confirmModal,
+ type DropdownItem,
+ DropdownMenu,
+ Flexbox,
+ Segmented,
+ Tabs,
+ Tag,
+ Text,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Download, Ellipsis, Pencil, Trash2 } from 'lucide-react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import { ExperimentCaseDetails } from '@/features/LobeBench/ExperimentCaseDetails';
+import { ExperimentCaseRow, verdictStyle } from '@/features/LobeBench/ExperimentCaseRow';
+import { openExperimentEditModal } from '@/features/LobeBench/ExperimentEditModal';
+import { ExperimentGradingNotices } from '@/features/LobeBench/ExperimentGradingNotices';
+import { experimentContextSuffix } from '@/features/LobeBench/experimentNavigation';
+import {
+ createExperimentResultsCsv,
+ defaultExperimentCaseFilter,
+ type ExperimentCaseFilter,
+ experimentGradingGaps,
+ experimentResultCoverage,
+ experimentResultsState,
+ experimentRunStats,
+ isUnavailableExperimentResult,
+ lowestPassRateCategory,
+ orderExperimentContenders,
+ scopeExperimentCases,
+ unverifiedCaseCount,
+} from '@/features/LobeBench/experimentResults';
+import { ExperimentResultsState } from '@/features/LobeBench/ExperimentResultsLoading';
+import {
+ CASE_LEVELS,
+ describeSettings,
+ experimentPartMeta,
+ experimentPartsOf,
+ formatCost,
+ formatPercent,
+ getCaseCategory,
+ getCaseConnectors,
+ getCaseIndex,
+ getCaseLevel,
+ getCaseTitle,
+ isLobeBenchMeta,
+ isRunActive,
+ levelLabelKey,
+ type LobeBenchContender,
+ runCaseVersion,
+ runStats,
+ summarizeCaseResult,
+} from '@/features/LobeBench/lobeBench';
+import RunsSection from '@/features/LobeBench/RunsSection';
+import { useDeleteExperiment } from '@/features/LobeBench/useDeleteExperiment';
+import { useExperimentActions } from '@/features/LobeBench/useExperimentActions';
+import {
+ useDatasetCases,
+ useExperimentRuns,
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchExperiments,
+ useRunResultsMap,
+} from '@/features/LobeBench/useLobeBench';
+
+import { heatStyle } from './heatStyle';
+import { LaunchPage } from './LaunchPage';
+import { useExperimentViewState } from './useExperimentViewState';
+
+const styles = stylex.create({
+ container: {
+ minWidth: 0,
+ maxWidth: '100%',
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: { default: 32, [media.md]: 16 },
+ },
+ tableScroll: { overflowX: 'auto', minWidth: 0, maxWidth: '100%' },
+ insights: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
+ gap: 12,
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+ grid: { display: 'grid', columnGap: 8, rowGap: 2, alignItems: 'center' },
+ head: {
+ paddingBlock: 6,
+ paddingInline: 8,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ cell: { paddingBlock: 8, paddingInline: 8, borderRadius: cssVar.borderRadius },
+ heat: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 36,
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ },
+});
+
+type Tab = 'cases' | 'results' | 'setup';
+
+const ExperimentDashboard = memo(() => {
+ const { t } = useTranslation('eval');
+ const { experimentId } = useParams<{ experimentId: string }>();
+ const deleteExperiment = useDeleteExperiment();
+ const {
+ experiments,
+ isInit,
+ error: experimentsError,
+ mutate: refreshExperiments,
+ } = useLobeBenchExperiments();
+ const experiment = experiments.find((e) => e.id === experimentId);
+ const experimentMeta = isLobeBenchMeta(experiment?.metadata) ? experiment!.metadata : undefined;
+ // An experiment can cover several benchmarks, one dataset each;
+ // the page shows one at a time, as an experiment of that dataset alone.
+ const parts = useMemo(
+ () => (experimentMeta ? experimentPartsOf(experimentMeta) : []),
+ [experimentMeta],
+ );
+ const view = useExperimentViewState(experimentId);
+ const { category, filterOverride, level, openCase, partIndex } = view;
+ const { setCategory, setFilter, setLevel, setOpenCase, setPartIndex } = view;
+ const part = parts[Math.min(partIndex, parts.length - 1)];
+ const meta = useMemo(
+ () => (experimentMeta && part ? experimentPartMeta(experimentMeta, part) : experimentMeta),
+ [experimentMeta, part],
+ );
+ const {
+ benchmarks,
+ error: benchmarksError,
+ mutate: refreshBenchmarks,
+ } = useLobeBenchBenchmarks();
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const {
+ data: datasets,
+ error: datasetsError,
+ mutate: refreshDatasets,
+ } = useLobeBenchDatasets(benchmarkIds);
+ const dataset = datasets?.find((d) => d.id === meta?.datasetId);
+ // Made on an earlier version of the cases than the dataset has now: still readable,
+ // but no leaderboard counts it.
+ const currentCaseVersion = evalCaseVersionOf(
+ dataset?.metadata as Record<string, unknown> | undefined,
+ );
+ const benchmarkId = dataset?.benchmarkId ?? benchmarks[0]?.id;
+
+ const [polling, setPolling] = useState(true);
+ const {
+ data: runs,
+ error: runsError,
+ mutate: refreshRuns,
+ } = useExperimentRuns(experimentId, {
+ refreshInterval: polling ? 5000 : undefined,
+ });
+ const active = (runs ?? []).some((run) => isRunActive(run.status));
+ const outdated =
+ !!currentCaseVersion &&
+ (runs ?? []).some(
+ (run) => run.datasetId === dataset?.id && runCaseVersion(run) !== currentCaseVersion,
+ );
+
+ const k = meta?.k ?? 1;
+ const contenders: LobeBenchContender[] = useMemo(() => {
+ const declared = meta?.contenders ?? [];
+ // Runs are the source of truth once started; declared contenders keep the
+ // display order and settings.
+ // Before the run ids are saved a run is found by its name; with several datasets
+ // only among the runs on the dataset shown.
+ const onShownPart = (item: NonNullable<typeof runs>[number]) =>
+ parts.length < 2 ||
+ (item.datasetId === meta?.datasetId &&
+ (item.config?.caseSelection?.caseIds ?? []).join() === (meta?.caseIds ?? []).join());
+ return declared.map((contender) => {
+ const run = (runs ?? []).find(
+ (item) =>
+ item.id === contender.runId ||
+ (!contender.runId && item.name === contender.name && onShownPart(item)),
+ );
+ return { ...contender, runId: run?.id ?? contender.runId };
+ });
+ }, [meta, parts.length, runs]);
+ const runIds = useMemo(
+ () => contenders.map((c) => c.runId).filter(Boolean) as string[],
+ [contenders],
+ );
+ const {
+ data: resultsMap,
+ error: resultsError,
+ mutate: refreshResults,
+ } = useRunResultsMap(runIds, {
+ refreshInterval: active ? 5000 : undefined,
+ });
+ const {
+ data: datasetCases,
+ error: casesError,
+ mutate: refreshCases,
+ } = useDatasetCases(meta?.datasetId);
+ const scope = useMemo(
+ () => scopeExperimentCases(datasetCases ?? [], meta?.caseIds),
+ [datasetCases, meta?.caseIds],
+ );
+ const cases = scope.cases;
+
+ const wasActive = useRef(active);
+ useEffect(() => {
+ if (runs) setPolling(active);
+ if (wasActive.current && !active) void refreshResults();
+ wasActive.current = active;
+ }, [active, runs, refreshResults]);
+
+ const [tab, setTab] = useState<Tab>('results');
+ const filter = filterOverride ?? defaultExperimentCaseFilter(contenders.length);
+ const [refreshing, setRefreshing] = useState(false);
+
+ const resources = [
+ { error: experimentsError, loaded: isInit },
+ { error: runsError, loaded: runs !== undefined },
+ { error: casesError, loaded: !meta || datasetCases !== undefined },
+ { error: resultsError, loaded: runIds.every((id) => resultsMap?.[id] !== undefined) },
+ ];
+ const loadState = experimentResultsState(resources);
+ const loadError = resources.find((item) => !item.loaded && item.error)?.error;
+ const refreshError =
+ experimentsError ?? runsError ?? casesError ?? resultsError ?? benchmarksError ?? datasetsError;
+ const reload = async () => {
+ setRefreshing(true);
+ try {
+ await Promise.allSettled([
+ refreshExperiments(),
+ refreshRuns(),
+ refreshCases(),
+ refreshResults(),
+ refreshBenchmarks(),
+ refreshDatasets(),
+ ]);
+ } finally {
+ setRefreshing(false);
+ }
+ };
+ const clearFilters = () => {
+ setFilter('all');
+ setCategory(undefined);
+ setLevel(undefined);
+ };
+ const hasFilters = filter !== 'all' || !!category || !!level;
+
+ const runOf = (contender: LobeBenchContender) =>
+ (runs ?? []).find((r) => r.id === contender.runId);
+ const statsOf = (contender: LobeBenchContender) =>
+ experimentRunStats(
+ runOf(contender),
+ contender.runId ? resultsMap?.[contender.runId] : undefined,
+ scope.selectedCount,
+ );
+ const progressOf = (contender: LobeBenchContender) => statsOf(contender).progress;
+ const resultUnavailable = (contender: LobeBenchContender, caseId: string) =>
+ isUnavailableExperimentResult(
+ runOf(contender)?.status,
+ contender.runId ? resultsMap?.[contender.runId] : undefined,
+ caseId,
+ );
+ const coverageGaps = contenders.flatMap((contender) => {
+ const run = runOf(contender);
+ const coverage =
+ run?.status === 'completed'
+ ? experimentResultCoverage(statsOf(contender).total, resultsMap?.[run.id])
+ : undefined;
+ return coverage?.missing ? [{ ...coverage, id: contender.id, name: contender.name }] : [];
+ });
+ const gradingGaps = experimentGradingGaps(contenders, runs ?? [], resultsMap);
+ const incomplete =
+ coverageGaps.length > 0 ||
+ gradingGaps.length > 0 ||
+ contenders.some((c) => runOf(c)?.status !== 'completed' || !progressOf(c)?.complete);
+ const attemptOf = (contender: LobeBenchContender, caseId: string) =>
+ summarizeCaseResult(
+ contender.runId
+ ? resultsMap?.[contender.runId]?.find((r) => r.testCaseId === caseId)
+ : undefined,
+ k,
+ );
+
+ const ranked = useMemo(
+ () =>
+ orderExperimentContenders(
+ contenders,
+ (contender) => progressOf(contender)?.allPassed ?? 0,
+ incomplete,
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [contenders, runs, resultsMap, scope.selectedCount, incomplete],
+ );
+ const categories = useMemo(
+ () => [...new Set((cases ?? []).map((item) => getCaseCategory(item)))],
+ [cases],
+ );
+ const levels = useMemo(() => {
+ const present = new Set((cases ?? []).map((item) => getCaseLevel(item)));
+ return CASE_LEVELS.filter((item) => present.has(item));
+ }, [cases]);
+ const levelRate = (contender: LobeBenchContender, item: string) => {
+ const graded = (cases ?? [])
+ .filter((c) => getCaseLevel(c) === item)
+ .map((c) => attemptOf(contender, c.id))
+ .filter((a) => a.verdict === 'passed' || a.verdict === 'failed');
+ if (graded.length === 0) return undefined;
+ return graded.filter((a) => a.verdict === 'passed').length / graded.length;
+ };
+ const categoryRate = (contender: LobeBenchContender, cat: string) => {
+ const items = (cases ?? []).filter((item) => getCaseCategory(item) === cat);
+ const graded = items
+ .map((item) => attemptOf(contender, item.id))
+ .filter((a) => a.verdict === 'passed' || a.verdict === 'failed');
+ if (graded.length === 0) return undefined;
+ return graded.filter((a) => a.verdict === 'passed').length / graded.length;
+ };
+
+ const errors = contenders.reduce((sum, c) => sum + statsOf(c).errors, 0);
+ // Progress and spend count the whole experiment, every dataset it covers; the
+ // rest of the page is the dataset shown.
+ const experimentStats =
+ parts.length > 1
+ ? (runs ?? []).map((run) => runStats(run))
+ : contenders.map((contender) => statsOf(contender));
+ const totalAttempts = experimentStats.reduce((sum, stats) => sum + stats.total * k, 0);
+ const doneAttempts = experimentStats.reduce((sum, stats) => sum + stats.completed * k, 0);
+ const spent = experimentStats.reduce((sum, stats) => sum + (stats.totalCost ?? 0), 0);
+ const labels = {
+ reasoning: t('lobeBench.contender.settings.reasoning'),
+ temperature: t('lobeBench.contender.settings.temperature'),
+ topP: t('lobeBench.contender.settings.topP'),
+ };
+ const settingsOf = (c: LobeBenchContender) =>
+ describeSettings(c.params, c.chatConfig, labels) || t('lobeBench.contender.settings.default');
+
+ const actions = useExperimentActions({
+ experimentId,
+ refreshRuns,
+ refreshResults,
+ onRerunStarted: () => setPolling(true),
+ // Every run of the experiment, on every dataset it covers: Stop stops them all.
+ // Rerun needs a run's results, which load for the dataset shown.
+ targets: (runs ?? []).map((run) => ({
+ runId: run.id,
+ name: run.name ?? '',
+ status: run.status ?? '',
+ unverified: unverifiedCaseCount(resultsMap?.[run.id]),
+ })),
+ });
+
+ const stop = () =>
+ confirmModal({
+ content: t('lobeBench.dashboard.abort.confirm'),
+ okButtonProps: { danger: true },
+ okText: t('lobeBench.dashboard.abort'),
+ onOk: actions.stop,
+ title: t('lobeBench.dashboard.abort'),
+ });
+
+ // One row per case, one column per contender: the verdict, and the passes
+ // out of k when the experiment made several attempts.
+ const exportCsv = () => {
+ const csv = createExperimentResultsCsv(
+ cases.map((item) => ({
+ ...item,
+ index: getCaseIndex(item),
+ title: getCaseTitle(item),
+ category: getCaseCategory(item),
+ results: contenders.map((c) => {
+ if (resultUnavailable(c, item.id)) return 'unavailable';
+ const a = attemptOf(c, item.id);
+ return k > 1 ? `${a.verdict} ${a.passCount}/${a.total}` : a.verdict;
+ }),
+ })),
+ contenders.map((c) => c.name),
+ meta?.caseIds,
+ );
+ const blob = new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = `${experiment?.name || 'experiment'}.csv`;
+ anchor.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const filteredCases = useMemo(() => {
+ let list = cases ?? [];
+ if (category) list = list.filter((item) => getCaseCategory(item) === category);
+ if (level) list = list.filter((item) => getCaseLevel(item) === level);
+ if (filter === 'diff')
+ list = list.filter((item) => {
+ const passes = new Set(contenders.map((c) => attemptOf(c, item.id).passCount));
+ return passes.size > 1;
+ });
+ if (filter === 'allFail')
+ list = list.filter((item) =>
+ contenders.every((c) => attemptOf(c, item.id).verdict === 'failed'),
+ );
+ if (filter === 'errors')
+ list = list.filter((item) =>
+ contenders.some((c) => ['error', 'timeout'].includes(attemptOf(c, item.id).verdict)),
+ );
+ if (filter === 'judgeErrors')
+ list = list.filter((item) =>
+ contenders.some(
+ (c) =>
+ attemptOf(c, item.id).verdict === 'judge_error' ||
+ attemptOf(c, item.id).threads.some((thread) => thread.status === 'judge_error'),
+ ),
+ );
+ return list;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [cases, category, level, filter, contenders, resultsMap]);
+
+ const stateProps = {
+ className: stylex.props(styles.container).className,
+ name: experiment?.name,
+ onRetry: reload,
+ retrying: refreshing,
+ };
+ if ((experimentsError && !isInit) || loadState === 'error')
+ return (
+ <ExperimentResultsState
+ {...stateProps}
+ error={loadError ?? experimentsError}
+ state={'error'}
+ />
+ );
+ if (isInit && (!experiment || !meta))
+ return <ExperimentResultsState {...stateProps} state={'notFound'} />;
+ if (!experiment || !meta || loadState === 'loading')
+ return <ExperimentResultsState {...stateProps} state={'loading'} />;
+ if (!contenders.length || contenders.some((contender) => !runOf(contender)))
+ return <ExperimentResultsState {...stateProps} state={'missingRuns'} />;
+
+ const leader = ranked[0];
+ const leaderStats = leader ? statsOf(leader) : undefined;
+ const second = ranked[1] ? statsOf(ranked[1]) : undefined;
+ const weakest = lowestPassRateCategory(
+ categories.map((cat) => {
+ const rates = contenders
+ .map((c) => categoryRate(c, cat))
+ .filter((r): r is number => r !== undefined);
+ return {
+ cat,
+ rate: rates.length ? rates.reduce((a, b) => a + b, 0) / rates.length : undefined,
+ };
+ }),
+ );
+ const openItem = openCase ? cases?.find((item) => item.id === openCase) : undefined;
+ const gridColumns = `minmax(0, 1fr) ${contenders.map(() => '110px').join(' ')}`;
+
+ const edit = () => {
+ if (experiment) openExperimentEditModal(experiment, () => refreshExperiments());
+ };
+ // Same header as the Lab's experiment page: Edit beside a "more" menu that holds
+ // export and delete; the run-state actions (rerun, stop) stay as buttons.
+ const menuItems: DropdownItem[] = [
+ {
+ icon: <Download size={16} />,
+ key: 'export',
+ label: t('lobeBench.dashboard.export'),
+ onClick: exportCsv,
+ },
+ {
+ danger: true,
+ disabled: active,
+ icon: <Trash2 size={16} />,
+ key: 'delete',
+ label: active ? t('lobeBench.experiment.delete.active') : t('common.delete'),
+ onClick: () => {
+ if (experiment) deleteExperiment(experiment, { active, leave: true });
+ },
+ },
+ ];
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={20}>
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'flex-start'} gap={16} justify={'space-between'} wrap={'wrap'}>
+ <Text
+ as={'h1'}
+ ellipsis={{ tooltipWhenOverflow: true }}
+ fontSize={24}
+ style={{ minWidth: 0, flex: '1 1 220px' }}
+ weight={600}
+ >
+ {experiment.name || t('lobeBench.experiment.unnamed')}
+ </Text>
+ <Flexbox horizontal gap={8} style={{ flexShrink: 0, maxWidth: '100%' }} wrap={'wrap'}>
+ <Button
+ aria-label={t('error.retry', { ns: 'error' })}
+ loading={refreshing}
+ size={'small'}
+ onClick={reload}
+ >
+ {t('error.retry', { ns: 'error' })}
+ </Button>
+ {active ? (
+ <Button
+ danger
+ disabled={actions.busy}
+ loading={actions.pendingAction === 'stop'}
+ size={'small'}
+ onClick={stop}
+ >
+ {t('lobeBench.dashboard.abort')}
+ </Button>
+ ) : (
+ <Button
+ disabled={actions.busy || !actions.canRerun}
+ loading={actions.pendingAction === 'rerun'}
+ size={'small'}
+ title={
+ actions.canRerun
+ ? t('lobeBench.dashboard.rerun.hint')
+ : t('lobeBench.dashboard.rerun.none')
+ }
+ onClick={() =>
+ confirmModal({
+ content: t('lobeBench.dashboard.rerun.confirm', { count: actions.rerunCases }),
+ okText: t('lobeBench.dashboard.rerun'),
+ onOk: actions.rerun,
+ title: t('lobeBench.dashboard.rerun'),
+ })
+ }
+ >
+ {t('lobeBench.dashboard.rerun')}
+ </Button>
+ )}
+ <Button icon={Pencil} size={'small'} onClick={edit}>
+ {t('common.edit')}
+ </Button>
+ <DropdownMenu items={menuItems} placement={'bottomRight'} trigger={['click']}>
+ <Button aria-label={t('lobeBench.experiment.more')} icon={Ellipsis} size={'small'} />
+ </DropdownMenu>
+ </Flexbox>
+ </Flexbox>
+ {meta.question && <Text type={'secondary'}>{meta.question}</Text>}
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Tag>
+ {datasets?.find((d) => d.id === meta.pickedDatasetId)?.name ?? dataset?.name ?? '—'}
+ </Tag>
+ <Tag>
+ {t('lobeBench.experiment.line', {
+ count: contenders.length,
+ dataset: meta.caseIds?.length
+ ? t('lobeBench.new.cases.selected', {
+ selected: scope.selectedCount,
+ total: datasetCases?.length ?? 0,
+ })
+ : t('lobeBench.new.dataset.cases', {
+ count: Math.max(...contenders.map((c) => statsOf(c).total)),
+ }),
+ k,
+ })}
+ </Tag>
+ <Tag color={active ? 'processing' : incomplete ? 'warning' : 'success'}>
+ {active
+ ? t('lobeBench.status.running', { done: doneAttempts, total: totalAttempts })
+ : incomplete
+ ? t('lobeBench.dashboard.statusIncomplete')
+ : t('lobeBench.status.done')}
+ </Tag>
+ {spent > 0 && <Tag>{t('lobeBench.dashboard.spent', { cost: formatCost(spent, 2) })}</Tag>}
+ {outdated && <Tag color={'warning'}>{t('lobeBench.experiment.outdated')}</Tag>}
+ </Flexbox>
+ {parts.length > 1 && (
+ <Segmented
+ value={String(Math.min(partIndex, parts.length - 1))}
+ options={parts.map((item, index) => ({
+ label:
+ datasets?.find((d) => d.id === (item.pickedDatasetId ?? item.datasetId))?.name ??
+ '—',
+ value: String(index),
+ }))}
+ onChange={(value) => setPartIndex(Number(value))}
+ />
+ )}
+ </Flexbox>
+
+ {!!refreshError && (
+ <AsyncError
+ error={refreshError}
+ retrying={refreshing}
+ title={t('lobeBench.dashboard.loadError')}
+ variant={'inline'}
+ onRetry={reload}
+ />
+ )}
+ {scope.missingCount > 0 && (
+ <Alert
+ title={t('lobeBench.dashboard.missingCases', { count: scope.missingCount })}
+ type={'warning'}
+ />
+ )}
+ {coverageGaps.map((gap) => (
+ <Alert key={gap.id} title={t('lobeBench.dashboard.coverageGap', gap)} type={'warning'} />
+ ))}
+ <ExperimentGradingNotices gaps={gradingGaps} />
+
+ {active && (
+ <Block padding={12} variant={'outlined'}>
+ <Text fontSize={13}>
+ {t('lobeBench.dashboard.progress', { done: doneAttempts, total: totalAttempts })}
+ </Text>
+ </Block>
+ )}
+ {errors > 0 && !active && (
+ <Block padding={12} variant={'outlined'}>
+ <Text fontSize={13}>{t('lobeBench.dashboard.errors', { count: errors })}</Text>
+ </Block>
+ )}
+
+ <Tabs
+ activeKey={tab}
+ items={[
+ { key: 'results', label: t('lobeBench.dashboard.tabs.results') },
+ { key: 'cases', label: t('lobeBench.dashboard.tabs.cases') },
+ { key: 'setup', label: t('lobeBench.dashboard.tabs.setup') },
+ ]}
+ onChange={(key) => setTab(key as Tab)}
+ />
+
+ {tab === 'results' && (
+ <Flexbox gap={20}>
+ {!incomplete && leader && leaderStats && (
+ <div className={stylex.props(styles.insights).className}>
+ <Block padding={14} variant={'outlined'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.insight.leader')}
+ </Text>
+ <Text weight={600}>{leader.name}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {k > 1
+ ? t('lobeBench.dashboard.insight.leaderLine', {
+ anyK: leaderStats.anyK ?? leaderStats.passed,
+ k,
+ passed: leaderStats.passed,
+ total: leaderStats.total,
+ })
+ : t('lobeBench.overview.passedOf', {
+ passed: leaderStats.passed,
+ total: leaderStats.total,
+ })}
+ </Text>
+ </Block>
+ {second && (
+ <Block padding={14} variant={'outlined'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.insight.gap')}
+ </Text>
+ <Text weight={600}>
+ {t('lobeBench.dashboard.insight.gapLine', {
+ gap: leaderStats.passed - second.passed,
+ })}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {ranked[1].name} · {second.passed}/{second.total}
+ </Text>
+ </Block>
+ )}
+ {weakest && (
+ <Block padding={14} variant={'outlined'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t(
+ contenders.length === 1
+ ? 'lobeBench.dashboard.insight.lowest'
+ : 'lobeBench.dashboard.insight.weakest',
+ )}
+ </Text>
+ <Text weight={600}>{weakest.cat}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.insight.weakestLine', {
+ rate: formatPercent(weakest.rate!),
+ })}
+ </Text>
+ </Block>
+ )}
+ </div>
+ )}
+
+ <Block
+ className={stylex.props(styles.tableScroll).className}
+ padding={12}
+ variant={'outlined'}
+ >
+ <Flexbox gap={6}>
+ <Text weight={600}>
+ {t(incomplete ? 'lobeBench.contenders.title' : 'lobeBench.dashboard.ranking')}
+ </Text>
+ {incomplete && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.partialCounts')}
+ </Text>
+ )}
+ <div
+ className={stylex.props(styles.grid).className}
+ style={{
+ minWidth: 640,
+ gridTemplateColumns: '28px minmax(0, 1fr) 90px 80px 110px 150px',
+ }}
+ >
+ <span className={stylex.props(styles.head).className}>#</span>
+ <span className={stylex.props(styles.head).className}>
+ {t('lobeBench.dashboard.col.contender')}
+ </span>
+ <span className={stylex.props(styles.head).className}>
+ {k > 1
+ ? t('lobeBench.dashboard.col.passRateAllK', { k })
+ : t('lobeBench.dashboard.col.passRate')}
+ </span>
+ <span className={stylex.props(styles.head).className}>
+ {t(
+ k > 1 ? 'lobeBench.dashboard.col.passedAllK' : 'lobeBench.dashboard.col.passed',
+ { k },
+ )}
+ </span>
+ <span className={stylex.props(styles.head).className}>
+ {k > 1 ? t('lobeBench.dashboard.col.anyK', { k }) : ''}
+ </span>
+ <span className={stylex.props(styles.head).className}>
+ {t('lobeBench.dashboard.col.cost')}
+ </span>
+ {ranked.map((contender, index) => {
+ const s = statsOf(contender);
+ const progress = progressOf(contender);
+ const run = runOf(contender);
+ const hasGap = run?.status !== 'completed' || !progress?.complete;
+ return [
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${contender.id}-rank`}
+ style={{ color: cssVar.colorTextQuaternary }}
+ >
+ {incomplete ? '—' : index + 1}
+ </span>,
+ <Flexbox
+ className={stylex.props(styles.cell).className}
+ gap={2}
+ key={`${contender.id}-name`}
+ style={{ minWidth: 0 }}
+ >
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Text ellipsis weight={500}>
+ {contender.name}
+ </Text>
+ {s.errors > 0 && (
+ <Tag color={'warning'}>
+ {t('lobeBench.dashboard.col.errors', { count: s.errors })}
+ </Tag>
+ )}
+ {hasGap && (
+ <Tag color={'warning'}>{t('lobeBench.dashboard.statusIncomplete')}</Tag>
+ )}
+ {run && isRunActive(run.status) && (
+ <Tag color={'processing'}>{t('lobeBench.overview.running')}</Tag>
+ )}
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {settingsOf(contender)}
+ </Text>
+ {hasGap && progress && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.caseProgress', { ...progress, total: s.total })}
+ </Text>
+ )}
+ </Flexbox>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${contender.id}-rate`}
+ >
+ {hasGap ? '—' : formatPercent(progress.allPassed / s.total)}
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${contender.id}-passed`}
+ >
+ {progress?.hasVerdicts ? `${progress.allPassed}/${s.total}` : '—'}
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${contender.id}-allk`}
+ >
+ {k > 1
+ ? progress?.hasVerdicts
+ ? `${progress.anyPassed}/${s.total}`
+ : '—'
+ : ''}
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${contender.id}-cost`}
+ >
+ {formatCost(s.perCaseCost)}
+ {s.avgMinutes !== undefined &&
+ ` · ${t('lobeBench.unit.min', { value: s.avgMinutes.toFixed(1) })}`}
+ </span>,
+ ];
+ })}
+ </div>
+ </Flexbox>
+ </Block>
+
+ {categories.length > 0 && (
+ <Block
+ className={stylex.props(styles.tableScroll).className}
+ padding={12}
+ variant={'outlined'}
+ >
+ <Flexbox gap={8}>
+ <Flexbox gap={2}>
+ <Text weight={600}>{t('lobeBench.dashboard.byCategory')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.byCategory.hint')}
+ </Text>
+ </Flexbox>
+ <div
+ className={stylex.props(styles.grid).className}
+ style={{
+ gridTemplateColumns: `minmax(140px, 1fr) ${ranked.map(() => 'minmax(90px, 1fr)').join(' ')}`,
+ minWidth: Math.max(380, 160 + ranked.length * 120),
+ }}
+ >
+ <span />
+ {ranked.map((c) => (
+ <Text
+ ellipsis
+ className={stylex.props(styles.head).className}
+ key={c.id}
+ style={{ textAlign: 'center' }}
+ >
+ {c.name.split(' · ')[0]}
+ </Text>
+ ))}
+ {categories.map((cat) => [
+ <Text
+ ellipsis
+ className={stylex.props(styles.cell).className}
+ fontSize={13}
+ key={`${cat}-label`}
+ >
+ {cat}
+ </Text>,
+ ...ranked.map((c) => {
+ const rate = categoryRate(c, cat);
+ return (
+ <div
+ className={stylex.props(styles.heat).className}
+ key={`${cat}-${c.id}`}
+ style={{ cursor: 'pointer', ...heatStyle(rate) }}
+ onClick={() => {
+ setCategory(cat);
+ setFilter('all');
+ setTab('cases');
+ }}
+ >
+ {rate === undefined ? '—' : formatPercent(rate)}
+ </div>
+ );
+ }),
+ ])}
+ </div>
+ </Flexbox>
+ </Block>
+ )}
+
+ {levels.length > 0 && (
+ <Block
+ className={stylex.props(styles.tableScroll).className}
+ padding={12}
+ variant={'outlined'}
+ >
+ <Flexbox gap={8}>
+ <Flexbox gap={2}>
+ <Text weight={600}>{t('lobeBench.dashboard.byLevel')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.byLevel.hint')}
+ </Text>
+ </Flexbox>
+ <div
+ className={stylex.props(styles.grid).className}
+ style={{
+ gridTemplateColumns: `minmax(140px, 1fr) ${ranked.map(() => 'minmax(90px, 1fr)').join(' ')}`,
+ minWidth: Math.max(380, 160 + ranked.length * 120),
+ }}
+ >
+ <span />
+ {ranked.map((c) => (
+ <Text
+ ellipsis
+ className={stylex.props(styles.head).className}
+ key={c.id}
+ style={{ textAlign: 'center' }}
+ >
+ {c.name.split(' · ')[0]}
+ </Text>
+ ))}
+ {levels.map((item) => [
+ <Text
+ ellipsis
+ className={stylex.props(styles.cell).className}
+ fontSize={13}
+ key={`${item}-label`}
+ >
+ {t(levelLabelKey(item))}
+ </Text>,
+ ...ranked.map((c) => {
+ const rate = levelRate(c, item);
+ return (
+ <div
+ className={stylex.props(styles.heat).className}
+ key={`${item}-${c.id}`}
+ style={{ cursor: 'pointer', ...heatStyle(rate) }}
+ onClick={() => {
+ setLevel(item);
+ setFilter('all');
+ setTab('cases');
+ }}
+ >
+ {rate === undefined ? '—' : formatPercent(rate)}
+ </div>
+ );
+ }),
+ ])}
+ </div>
+ </Flexbox>
+ </Block>
+ )}
+ <RunsSection
+ benchmarkId={benchmarkId}
+ countLabel={(count) => t('lobeBench.experiment.runCount', { count })}
+ datasets={datasets}
+ emptyLabel={t('lobeBench.experiment.noRuns')}
+ runs={runs ?? []}
+ onRefresh={refreshRuns}
+ />
+ </Flexbox>
+ )}
+
+ {tab === 'cases' && (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={12} wrap={'wrap'}>
+ <Segmented
+ size={'small'}
+ value={filter}
+ options={[
+ ...(contenders.length > 1
+ ? [{ label: t('lobeBench.dashboard.filter.diff'), value: 'diff' }]
+ : []),
+ { label: t('lobeBench.dashboard.filter.all'), value: 'all' },
+ { label: t('lobeBench.dashboard.filter.allFail'), value: 'allFail' },
+ { label: t('lobeBench.dashboard.filter.errors'), value: 'errors' },
+ { label: t('lobeBench.compare.filter.judgeErrors'), value: 'judgeErrors' },
+ ]}
+ onChange={(value) => setFilter(value as ExperimentCaseFilter)}
+ />
+ {category && (
+ <Tag closable onClose={() => setCategory(undefined)}>
+ {t('lobeBench.dashboard.filter.category', { category })}
+ </Tag>
+ )}
+ {level && (
+ <Tag closable onClose={() => setLevel(undefined)}>
+ {t('lobeBench.dashboard.filter.level', { level: t(levelLabelKey(level)) })}
+ </Tag>
+ )}
+ {hasFilters && (
+ <Button size={'small'} type={'text'} onClick={clearFilters}>
+ {t('lobeBench.dashboard.filter.clear')}
+ </Button>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.cases.count', { count: filteredCases.length, k })}
+ </Text>
+ </Flexbox>
+ <Block
+ className={stylex.props(styles.tableScroll).className}
+ padding={8}
+ variant={'outlined'}
+ >
+ <div
+ className={stylex.props(styles.grid).className}
+ style={{
+ gridTemplateColumns: gridColumns,
+ minWidth: Math.max(380, 260 + contenders.length * 110),
+ }}
+ >
+ <span className={stylex.props(styles.head).className}>
+ {t('lobeBench.library.col.case')}
+ </span>
+ {contenders.map((c) => (
+ <Flexbox
+ className={stylex.props(styles.head).className}
+ key={c.id}
+ style={{ textAlign: 'center' }}
+ >
+ <Text ellipsis fontSize={12}>
+ {c.name.split(' · ')[0]}
+ </Text>
+ <Text ellipsis fontSize={11} type={'secondary'}>
+ {c.name.split(' · ').slice(1).join(' · ')}
+ </Text>
+ </Flexbox>
+ ))}
+ {filteredCases.length === 0 && (
+ <Text style={{ gridColumn: '1 / -1', padding: 16 }} type={'secondary'}>
+ {t(
+ hasFilters
+ ? 'lobeBench.dashboard.cases.empty'
+ : 'lobeBench.dashboard.cases.unavailable',
+ )}
+ </Text>
+ )}
+ {filteredCases.map((item) => (
+ <ExperimentCaseRow
+ columns={gridColumns}
+ index={getCaseIndex(item)}
+ key={item.id}
+ subtitle={`${getCaseCategory(item)} · ${getCaseConnectors(item).slice(0, 3).join(' · ')}`}
+ title={getCaseTitle(item)}
+ results={contenders.map((c) => {
+ const a = attemptOf(c, item.id);
+ return {
+ id: c.id,
+ style: verdictStyle(a.verdict),
+ label: resultUnavailable(c, item.id)
+ ? t('lobeBench.dashboard.caseUnavailable')
+ : a.verdict === 'judge_error'
+ ? t('lobeBench.compare.judgeError')
+ : a.verdict === 'error' || a.verdict === 'timeout'
+ ? t('lobeBench.compare.error')
+ : a.verdict === 'pending' || a.verdict === 'running'
+ ? '…'
+ : `${a.passCount}/${a.total}`,
+ };
+ })}
+ onOpen={() => setOpenCase(item.id)}
+ />
+ ))}
+ </div>
+ </Block>
+ </Flexbox>
+ )}
+
+ {tab === 'setup' && (
+ <Block
+ className={stylex.props(styles.tableScroll).className}
+ padding={12}
+ variant={'outlined'}
+ >
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.dashboard.setup.hint')}
+ </Text>
+ <div
+ className={stylex.props(styles.grid).className}
+ style={{
+ gridTemplateColumns:
+ 'minmax(0, 1.4fr) minmax(0, 1fr) minmax(0, 1fr) 90px 70px 80px 90px',
+ minWidth: 720,
+ }}
+ >
+ {[
+ t('lobeBench.dashboard.col.contender'),
+ t('lobeBench.dashboard.setup.col.model'),
+ t('lobeBench.dashboard.setup.col.settings'),
+ t('lobeBench.dashboard.setup.col.cases'),
+ t('lobeBench.dashboard.setup.col.k'),
+ t('lobeBench.dashboard.setup.col.steps'),
+ t('lobeBench.dashboard.setup.col.cost'),
+ ].map((label) => (
+ <span className={stylex.props(styles.head).className} key={label}>
+ {label}
+ </span>
+ ))}
+ {contenders.map((c) => [
+ <Text
+ ellipsis
+ className={stylex.props(styles.cell).className}
+ key={`${c.id}-n`}
+ weight={500}
+ >
+ {c.name}
+ </Text>,
+ <Text
+ ellipsis
+ className={stylex.props(styles.cell).className}
+ fontSize={12}
+ key={`${c.id}-m`}
+ type={'secondary'}
+ >
+ {c.model} · {c.provider}
+ </Text>,
+ <Text
+ ellipsis
+ className={stylex.props(styles.cell).className}
+ fontSize={12}
+ key={`${c.id}-s`}
+ type={'secondary'}
+ >
+ {settingsOf(c)}
+ </Text>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${c.id}-c`}
+ >
+ {statsOf(c).total}
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${c.id}-k`}
+ >
+ {k}×
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${c.id}-st`}
+ >
+ {meta.maxSteps}
+ </span>,
+ <span
+ className={stylex.props(styles.cell, styles.mono).className}
+ key={`${c.id}-$`}
+ >
+ {formatCost(statsOf(c).totalCost, 2)}
+ </span>,
+ ])}
+ </div>
+ </Flexbox>
+ </Block>
+ )}
+
+ <ExperimentCaseDetails
+ title={openItem ? getCaseTitle(openItem) : undefined}
+ results={
+ openItem
+ ? contenders.map((contender) => {
+ const run = runOf(contender);
+ return {
+ id: contender.id,
+ name: contender.name,
+ attempt: attemptOf(contender, openItem.id),
+ unavailable: resultUnavailable(contender, openItem.id),
+ traceUrl:
+ run && benchmarkId
+ ? `/eval/bench/${benchmarkId}/runs/${run.id}/cases/${openItem.id}${experimentContextSuffix(experimentId)}`
+ : undefined,
+ };
+ })
+ : []
+ }
+ subtitle={
+ openItem
+ ? `${getCaseCategory(openItem)} · ${getCaseConnectors(openItem).join(' · ')}`
+ : ''
+ }
+ onClose={() => setOpenCase(undefined)}
+ />
+ </Flexbox>
+ );
+});
+
+ExperimentDashboard.displayName = 'LobeBenchExperimentDashboard';
+
+const ExperimentPage = () => (
+ <LaunchPage>
+ <ExperimentDashboard />
+ </LaunchPage>
+);
+
+export default ExperimentPage;
diff --git a/src/features/LobeBench/Experiment/useExperimentViewState.test.ts b/src/features/LobeBench/Experiment/useExperimentViewState.test.ts
new file mode 100644
index 00000000000..838d0403007
--- /dev/null
+++ b/src/features/LobeBench/Experiment/useExperimentViewState.test.ts
@@ -0,0 +1,39 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useExperimentViewState } from './useExperimentViewState';
+
+describe('useExperimentViewState', () => {
+ it('resets the selected part and case filters when another experiment opens', () => {
+ const { result, rerender } = renderHook(({ id }) => useExperimentViewState(id), {
+ initialProps: { id: 'experiment-a' },
+ });
+ act(() => {
+ result.current.setPartIndex(2);
+ result.current.setFilter('allFail');
+ result.current.setCategory('Tools');
+ result.current.setLevel('L3');
+ result.current.setOpenCase('case-1');
+ });
+ expect(result.current.partIndex).toBe(2);
+
+ rerender({ id: 'experiment-b' });
+
+ expect(result.current).toMatchObject({
+ category: undefined,
+ filterOverride: undefined,
+ level: undefined,
+ openCase: undefined,
+ partIndex: 0,
+ });
+ });
+
+ it('keeps the choices while the same experiment re-renders', () => {
+ const { result, rerender } = renderHook(({ id }) => useExperimentViewState(id), {
+ initialProps: { id: 'experiment-a' },
+ });
+ act(() => result.current.setPartIndex(1));
+ rerender({ id: 'experiment-a' });
+ expect(result.current.partIndex).toBe(1);
+ });
+});
diff --git a/src/features/LobeBench/Experiment/useExperimentViewState.ts b/src/features/LobeBench/Experiment/useExperimentViewState.ts
new file mode 100644
index 00000000000..c2c24b058d8
--- /dev/null
+++ b/src/features/LobeBench/Experiment/useExperimentViewState.ts
@@ -0,0 +1,37 @@
+import { useEffect, useState } from 'react';
+
+import type { ExperimentCaseFilter } from '@/features/LobeBench/experimentResults';
+import type { CaseLevel } from '@/features/LobeBench/lobeBench';
+
+/**
+ * View choices that belong to one experiment: the selected benchmark part,
+ * case filters and the open case. They reset when the route opens another
+ * experiment, so a choice made on one never points into the next.
+ */
+export const useExperimentViewState = (experimentId?: string) => {
+ const [partIndex, setPartIndex] = useState(0);
+ const [filterOverride, setFilter] = useState<ExperimentCaseFilter>();
+ const [category, setCategory] = useState<string>();
+ const [level, setLevel] = useState<CaseLevel>();
+ const [openCase, setOpenCase] = useState<string>();
+ useEffect(() => {
+ setPartIndex(0);
+ setFilter(undefined);
+ setCategory(undefined);
+ setLevel(undefined);
+ setOpenCase(undefined);
+ }, [experimentId]);
+
+ return {
+ category,
+ filterOverride,
+ level,
+ openCase,
+ partIndex,
+ setCategory,
+ setFilter,
+ setLevel,
+ setOpenCase,
+ setPartIndex,
+ };
+};
diff --git a/src/features/LobeBench/ExperimentCaseDetails.tsx b/src/features/LobeBench/ExperimentCaseDetails.tsx
new file mode 100644
index 00000000000..d41d668e52e
--- /dev/null
+++ b/src/features/LobeBench/ExperimentCaseDetails.tsx
@@ -0,0 +1,168 @@
+import { Alert, Block, Button, Drawer, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
+import { type CaseAttempt, formatCost } from './caseResults';
+import { verdictStyle } from './ExperimentCaseRow';
+
+const styles = stylex.create({
+ attempt: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 22,
+ height: 22,
+ borderRadius: 6,
+ fontSize: 12,
+ },
+ mono: { fontFamily: cssVar.fontFamilyCode, fontVariantNumeric: 'tabular-nums' },
+});
+
+interface CaseDetail {
+ attempt: CaseAttempt;
+ id: string;
+ name: string;
+ traceUrl?: string;
+ unavailable: boolean;
+}
+
+/** Shows scoring diagnostics separately from the retained candidate answer and trace. */
+export const ExperimentCaseDetails = ({
+ onClose,
+ results,
+ subtitle,
+ title,
+}: {
+ onClose: () => void;
+ results: CaseDetail[];
+ subtitle: string;
+ title?: string;
+}) => {
+ const { t } = useTranslation('eval');
+ return (
+ <Drawer open={title !== undefined} title={title ?? ''} width={640} onClose={onClose}>
+ <Flexbox gap={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {subtitle}
+ </Text>
+ {results.map(({ attempt: a, id, name, traceUrl, unavailable }) => (
+ <Block key={id} padding={12} variant={'outlined'}>
+ <Flexbox gap={8}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>
+ <Text weight={500}>{name}</Text>
+ {!unavailable && (
+ <Flexbox horizontal align={'center'} gap={4} wrap={'wrap'}>
+ {a.threads.map((thread, index) => (
+ <span
+ className={stylex.props(styles.attempt).className}
+ key={index}
+ style={verdictStyle(thread.status)}
+ title={`${t('lobeBench.compare.attempt', { n: index + 1 })}${thread.status === 'judge_error' ? ` · ${t('lobeBench.compare.judgeError')}` : ''}`}
+ >
+ {thread.status === 'passed'
+ ? '✓'
+ : thread.status === 'failed'
+ ? '✗'
+ : ['error', 'timeout', 'judge_error'].includes(thread.status)
+ ? '!'
+ : '…'}
+ </span>
+ ))}
+ <Text
+ className={stylex.props(styles.mono).className}
+ fontSize={12}
+ type={'secondary'}
+ >
+ {a.verdict === 'judge_error'
+ ? t('lobeBench.compare.judgeError')
+ : ['error', 'timeout'].includes(a.verdict)
+ ? t('lobeBench.compare.error')
+ : ['pending', 'running'].includes(a.verdict)
+ ? t('lobeBench.compare.pending')
+ : t('lobeBench.compare.passes', {
+ passed: a.passCount,
+ total: a.total,
+ })}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ {unavailable ? (
+ <Alert title={t('lobeBench.dashboard.caseUnavailable')} type={'warning'} />
+ ) : (
+ <>
+ {a.verdict === 'judge_error' && (
+ <Alert title={t('lobeBench.compare.judgeError')} type={'warning'} />
+ )}
+ <Flexbox horizontal gap={16} wrap={'wrap'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.compare.toolCalls')} · {a.toolCalls ?? '—'}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.compare.timeCost')} ·{' '}
+ {a.duration
+ ? t('lobeBench.unit.min', { value: (a.duration / 60_000).toFixed(1) })
+ : '—'}{' '}
+ · {formatCost(a.cost)}
+ </Text>
+ </Flexbox>
+ <Flexbox gap={4}>
+ <Text fontSize={12} weight={500}>
+ {t('lobeBench.compare.reason')}
+ </Text>
+ {a.verdict === 'judge_error' ? (
+ <Text fontSize={13} style={{ whiteSpace: 'pre-wrap' }}>
+ {a.error ?? t('lobeBench.compare.noReason')}
+ </Text>
+ ) : a.verdicts?.length ? (
+ <Flexbox gap={4}>
+ {a.reason?.split('\n')[0] && !a.reason.startsWith('1. ') && (
+ <Text fontSize={13}>{a.reason.split('\n')[0]}</Text>
+ )}
+ {a.verdicts.map((item, index) => (
+ <Text
+ fontSize={12}
+ key={index}
+ type={
+ item.verdict === 'satisfied'
+ ? 'secondary'
+ : item.verdict === 'violated'
+ ? 'danger'
+ : 'warning'
+ }
+ >
+ {item.verdict === 'satisfied'
+ ? '✓'
+ : item.verdict === 'violated'
+ ? '✗'
+ : '?'}{' '}
+ {item.rule}
+ {item.verdict !== 'satisfied' && item.reason ? ` — ${item.reason}` : ''}
+ </Text>
+ ))}
+ </Flexbox>
+ ) : (
+ <Text fontSize={13} style={{ whiteSpace: 'pre-wrap' }}>
+ {a.error && ['error', 'timeout'].includes(a.verdict)
+ ? a.error
+ : (a.reason ?? t('lobeBench.compare.noReason'))}
+ </Text>
+ )}
+ </Flexbox>
+ {traceUrl && (
+ <WorkspaceLink to={traceUrl}>
+ <Button size={'small'}>{t('lobeBench.compare.open')}</Button>
+ </WorkspaceLink>
+ )}
+ </>
+ )}
+ </Flexbox>
+ </Block>
+ ))}
+ </Flexbox>
+ </Drawer>
+ );
+};
diff --git a/src/features/LobeBench/ExperimentCaseRow.tsx b/src/features/LobeBench/ExperimentCaseRow.tsx
new file mode 100644
index 00000000000..a04de7a9eb6
--- /dev/null
+++ b/src/features/LobeBench/ExperimentCaseRow.tsx
@@ -0,0 +1,101 @@
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import type { CSSProperties } from 'react';
+
+import type { CaseAttempt } from './caseResults';
+
+const styles = stylex.create({
+ row: {
+ display: 'grid',
+ gridColumnEnd: '-1',
+ gridColumnStart: '1',
+ columnGap: 8,
+ alignItems: 'center',
+ padding: 0,
+ borderWidth: 0,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillQuaternary },
+ color: 'inherit',
+ fontFamily: 'inherit',
+ textAlign: 'start',
+ cursor: 'pointer',
+ },
+ cell: { paddingBlock: 8, paddingInline: 8, minWidth: 0 },
+ index: {
+ color: cssVar.colorTextQuaternary,
+ fontFamily: cssVar.fontFamilyCode,
+ marginInlineEnd: 8,
+ },
+ heat: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 36,
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ },
+});
+
+interface ExperimentCaseRowProps {
+ columns: string;
+ index: number;
+ onOpen: () => void;
+ results: Array<{ id: string; label: string; style: CSSProperties }>;
+ subtitle: string;
+ title: string;
+}
+
+/** The whole result row is one native keyboard target, with no nested actions. */
+export const ExperimentCaseRow = ({
+ columns,
+ index,
+ onOpen,
+ results,
+ subtitle,
+ title,
+}: ExperimentCaseRowProps) => (
+ <button
+ className={stylex.props(styles.row).className}
+ style={{ gridTemplateColumns: columns }}
+ type={'button'}
+ onClick={onOpen}
+ >
+ <Flexbox className={stylex.props(styles.cell).className} gap={2}>
+ <Text ellipsis fontSize={13}>
+ <span className={stylex.props(styles.index).className}>{index}</span>
+ {title}
+ </Text>
+ <Text ellipsis fontSize={11} type={'secondary'}>
+ {subtitle}
+ </Text>
+ </Flexbox>
+ {results.map((result) => (
+ <div className={stylex.props(styles.cell).className} key={result.id}>
+ <div className={stylex.props(styles.heat).className} style={result.style}>
+ {result.label}
+ </div>
+ </div>
+ ))}
+ </button>
+);
+
+export const verdictStyle = (verdict: CaseAttempt['verdict']) => {
+ switch (verdict) {
+ case 'passed': {
+ return { background: cssVar.colorSuccessBg, color: cssVar.colorSuccessText };
+ }
+ case 'failed': {
+ return { background: cssVar.colorErrorBg, color: cssVar.colorErrorText };
+ }
+ case 'judge_error':
+ case 'error':
+ case 'timeout': {
+ return { background: cssVar.colorWarningBg, color: cssVar.colorWarningText };
+ }
+ default: {
+ return { background: cssVar.colorFillQuaternary, color: cssVar.colorTextQuaternary };
+ }
+ }
+};
diff --git a/src/features/LobeBench/ExperimentEditModal.tsx b/src/features/LobeBench/ExperimentEditModal.tsx
new file mode 100644
index 00000000000..1beef7e04a6
--- /dev/null
+++ b/src/features/LobeBench/ExperimentEditModal.tsx
@@ -0,0 +1,108 @@
+'use client';
+
+import type { AgentEvalExperimentListItem } from '@lobechat/types';
+import {
+ Button,
+ createModal,
+ Flexbox,
+ Input,
+ Text,
+ TextArea,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isLobeBenchMeta } from '@/features/LobeBench/lobeBench';
+import { agentEvalService } from '@/services/agentEval';
+
+type EditableExperiment = Pick<AgentEvalExperimentListItem, 'id' | 'name' | 'metadata'>;
+
+interface ExperimentEditFormProps {
+ experiment: EditableExperiment;
+ onSaved?: () => Promise<unknown> | void;
+}
+
+/**
+ * Name and question of an experiment. The case set, contenders and attempts are frozen
+ * once the experiment starts, so they are not editable here.
+ */
+const ExperimentEditForm = memo<ExperimentEditFormProps>(({ experiment, onSaved }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const meta = isLobeBenchMeta(experiment.metadata) ? experiment.metadata : undefined;
+ const [name, setName] = useState(experiment.name ?? '');
+ const [question, setQuestion] = useState(meta?.question ?? '');
+ const [saving, setSaving] = useState(false);
+
+ const submit = async () => {
+ setSaving(true);
+ try {
+ const trimmedName = name.trim();
+ const trimmedQuestion = question.trim();
+ await agentEvalService.updateExperiment({
+ id: experiment.id,
+ // The whole metadata object is stored, so keep every other Lobe Bench field.
+ metadata: {
+ ...(experiment.metadata as Record<string, unknown> | null | undefined),
+ question: trimmedQuestion || undefined,
+ },
+ // An empty name keeps the current one (the server requires a string).
+ name: trimmedName || experiment.name || undefined,
+ });
+ toast.success(t('lobeBench.experiment.edit.saved'));
+ await onSaved?.();
+ close();
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('lobeBench.experiment.edit.failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.new.name')}</Text>
+ <Input
+ id={'lobe-bench-experiment-name'}
+ placeholder={t('lobeBench.new.name.placeholder')}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.new.question')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 5, minRows: 2 }}
+ id={'lobe-bench-experiment-question'}
+ placeholder={t('lobeBench.new.question.placeholder')}
+ value={question}
+ onChange={(e) => setQuestion(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('common.cancel')}</Button>
+ <Button loading={saving} type={'primary'} onClick={submit}>
+ {t('common.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+ExperimentEditForm.displayName = 'LobeBenchExperimentEditForm';
+
+/** Opens the Lab-style Edit dialog for an experiment; `onSaved` runs after a successful save. */
+export const openExperimentEditModal = (
+ experiment: EditableExperiment,
+ onSaved?: () => Promise<unknown> | void,
+) =>
+ createModal({
+ content: <ExperimentEditForm experiment={experiment} onSaved={onSaved} />,
+ footer: null,
+ title: translate('lobeBench.experiment.edit.title', { ns: 'eval' }),
+ width: 520,
+ });
diff --git a/src/features/LobeBench/ExperimentGradingNotices.tsx b/src/features/LobeBench/ExperimentGradingNotices.tsx
new file mode 100644
index 00000000000..1a8a05952c1
--- /dev/null
+++ b/src/features/LobeBench/ExperimentGradingNotices.tsx
@@ -0,0 +1,43 @@
+import { Alert, Flexbox } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import type { ExperimentGradingGap } from './experimentResults';
+
+/**
+ * What still lacks a verdict, per contender. The remedy is the page's Rerun
+ * button: those cases run again; nothing is re-graded in place.
+ */
+export const ExperimentGradingNotices = ({ gaps }: { gaps: ExperimentGradingGap[] }) => {
+ const { t } = useTranslation('eval');
+ if (!gaps.length) return null;
+ return (
+ <Flexbox gap={8}>
+ {gaps.flatMap((gap) => [
+ gap.judgeError > 0 && (
+ <Alert
+ key={`${gap.id}-judge-error`}
+ title={t('lobeBench.dashboard.judgeErrors', { name: gap.name, count: gap.judgeError })}
+ type={'warning'}
+ />
+ ),
+ gap.ungraded > 0 && (
+ <Alert
+ key={`${gap.id}-ungraded`}
+ title={t('lobeBench.dashboard.gradingGap', { name: gap.name, count: gap.ungraded })}
+ type={'warning'}
+ />
+ ),
+ gap.awaitingExternal > 0 && (
+ <Alert
+ key={`${gap.id}-external`}
+ type={'warning'}
+ title={t('lobeBench.dashboard.awaitingExternal', {
+ name: gap.name,
+ count: gap.awaitingExternal,
+ })}
+ />
+ ),
+ ])}
+ </Flexbox>
+ );
+};
diff --git a/src/features/LobeBench/ExperimentResultsLoading.tsx b/src/features/LobeBench/ExperimentResultsLoading.tsx
new file mode 100644
index 00000000000..1f44c49ddf6
--- /dev/null
+++ b/src/features/LobeBench/ExperimentResultsLoading.tsx
@@ -0,0 +1,90 @@
+import { Alert, Block, Button, Empty, Flexbox, Text } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import SkeletonBar from '@/components/Skeleton/Bar';
+
+export const ExperimentResultsLoading = () => {
+ const { t } = useTranslation('eval');
+ return (
+ <Flexbox aria-busy gap={20}>
+ <Text role={'status'} type={'secondary'}>
+ {t('lobeBench.dashboard.loading')}
+ </Text>
+ <Flexbox horizontal gap={12} wrap={'wrap'}>
+ {[0, 1, 2].map((item) => (
+ <Block key={item} padding={14} style={{ flex: 1, minWidth: 200 }} variant={'outlined'}>
+ <Flexbox gap={12}>
+ <SkeletonBar height={14} width={'45%'} />
+ <SkeletonBar height={24} width={'70%'} />
+ <SkeletonBar height={14} width={'55%'} />
+ </Flexbox>
+ </Block>
+ ))}
+ </Flexbox>
+ <Block padding={14} variant={'outlined'}>
+ <Flexbox gap={20}>
+ {[0, 1, 2].map((item) => (
+ <Flexbox gap={8} key={item}>
+ <SkeletonBar height={16} width={'70%'} />
+ <SkeletonBar height={12} width={'45%'} />
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ );
+};
+
+interface ExperimentResultsStateProps {
+ className?: string;
+ error?: unknown;
+ name?: string | null;
+ onRetry: () => void;
+ retrying: boolean;
+ state: 'error' | 'loading' | 'missingRuns' | 'notFound';
+}
+
+export const ExperimentResultsState = ({
+ className,
+ error,
+ name,
+ onRetry,
+ retrying,
+ state,
+}: ExperimentResultsStateProps) => {
+ const { t } = useTranslation('eval');
+ return (
+ <Flexbox className={className} flex={1} gap={20}>
+ {name && (
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {name}
+ </Text>
+ )}
+ {state === 'notFound' ? (
+ <Empty description={t('lobeBench.dashboard.notFound')} />
+ ) : state === 'error' ? (
+ <AsyncError
+ error={error}
+ retrying={retrying}
+ title={t('lobeBench.dashboard.loadError')}
+ variant={'page'}
+ onRetry={onRetry}
+ />
+ ) : (
+ <>
+ {state === 'loading' ? (
+ <ExperimentResultsLoading />
+ ) : (
+ <Alert title={t('lobeBench.dashboard.missingRuns')} type={'warning'} />
+ )}
+ <Flexbox align={'flex-start'}>
+ <Button loading={retrying} onClick={onRetry}>
+ {t('error.retry', { ns: 'error' })}
+ </Button>
+ </Flexbox>
+ </>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/src/features/LobeBench/Layout/Sidebar/Body.tsx b/src/features/LobeBench/Layout/Sidebar/Body.tsx
new file mode 100644
index 00000000000..b3cfdfc8d4e
--- /dev/null
+++ b/src/features/LobeBench/Layout/Sidebar/Body.tsx
@@ -0,0 +1,372 @@
+'use client';
+
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ AccordionRoot,
+ accordionStyles,
+ AccordionTrigger,
+ ActionIcon,
+ cx,
+ type DropdownItem,
+ DropdownMenu,
+ Flexbox,
+ Text,
+} from '@lobehub/ui';
+import {
+ Beaker,
+ Database,
+ LayoutDashboardIcon,
+ LibraryBig,
+ MoreHorizontalIcon,
+ PlusIcon,
+ Settings2,
+ Trash2,
+ Users,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getBenchmarkIcon } from '@/features/LobeBench/benchmarkIcon';
+import { openCreateBenchmarkModal } from '@/features/LobeBench/BenchmarkModal';
+import {
+ benchmarkDatasetsOf,
+ customDatasetsOf,
+ isCustomBenchmark,
+ isRunActive,
+ LOBE_BENCH_PATH,
+ looseDatasetsOf,
+ sortBenchmarks,
+} from '@/features/LobeBench/lobeBench';
+import { useDeleteExperiment } from '@/features/LobeBench/useDeleteExperiment';
+import { useImportLobeBenchDataset } from '@/features/LobeBench/useImportDataset';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchExperiments,
+} from '@/features/LobeBench/useLobeBench';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+import { isModifierClick } from '@/utils/navigation';
+
+const useActiveKey = () => {
+ const { pathname } = useActiveLocation();
+ if (pathname.endsWith('/experiments/new')) return 'new';
+ if (pathname.endsWith('/library')) return 'library';
+ if (pathname.endsWith('/settings')) return 'settings';
+ if (pathname.endsWith('/contenders')) return 'contenders';
+ const match = pathname.match(/\/lobe-bench\/(experiments|benchmarks|datasets)\/([^/]+)/);
+ if (match) return `${match[1].slice(0, -1)}-${match[2]}`;
+ return 'overview';
+};
+
+const Body = memo(() => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const activeKey = useActiveKey();
+ const { experiments, isInit } = useLobeBenchExperiments();
+ const deleteExperiment = useDeleteExperiment();
+ const importDataset = useImportLobeBenchDataset();
+ const { benchmarks: benchmarkList, isLoading: loadingBenchmarks } = useLobeBenchBenchmarks();
+ const benchmarks = useMemo(() => sortBenchmarks(benchmarkList), [benchmarkList]);
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ // Every benchmark is made of a built-in dataset: those come
+ // first, in benchmark order, then the account's own datasets.
+ const sidebarDatasets = useMemo(
+ () => [
+ ...benchmarks
+ .filter((b) => !isCustomBenchmark(b))
+ .flatMap((b) => benchmarkDatasetsOf(datasets, b)),
+ ...customDatasetsOf(datasets),
+ ],
+ [benchmarks, datasets],
+ );
+ const createBenchmark = () =>
+ openCreateBenchmarkModal({
+ datasets: looseDatasetsOf(datasets, benchmarks),
+ onCreated: (id) => navigate(`${LOBE_BENCH_PATH}/benchmarks/${id}`),
+ });
+
+ const link = (to: string, node: React.ReactNode) => (
+ <WorkspaceLink
+ to={to}
+ onClick={(e) => {
+ if (isModifierClick(e)) return;
+ e.preventDefault();
+ navigate(to);
+ }}
+ >
+ {node}
+ </WorkspaceLink>
+ );
+
+ return (
+ // Fills the scroll area so the utility links can sit at the bottom.
+ <Flexbox gap={8} paddingInline={4} style={{ minHeight: '100%', paddingBlockEnd: 8 }}>
+ <Flexbox gap={1}>
+ {link(
+ LOBE_BENCH_PATH,
+ <NavItem
+ active={activeKey === 'overview'}
+ icon={LayoutDashboardIcon}
+ title={t('lobeBench.sidebar.overview')}
+ />,
+ )}
+ </Flexbox>
+ <AccordionRoot
+ defaultValue={['experiments', 'benchmarks', 'datasets']}
+ indicatorPlacement="inline"
+ style={{ gap: 8 }}
+ >
+ <AccordionItem value={'experiments'}>
+ <AccordionHeader style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
+ <AccordionTrigger>
+ <Flexbox horizontal align="center" gap={4}>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {t('lobeBench.sidebar.experiments')}
+ </Text>
+ {experiments.length > 0 && (
+ <Text fontSize={12} type="secondary">
+ {experiments.length}
+ </Text>
+ )}
+ </Flexbox>
+ </AccordionTrigger>
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={t('lobeBench.sidebar.newExperiment')}
+ onClick={() => navigate(`${LOBE_BENCH_PATH}/experiments/new`)}
+ />
+ </div>
+ </AccordionHeader>
+ <AccordionPanel>
+ <Flexbox gap={1} paddingBlock={1}>
+ {activeKey === 'new' && (
+ <NavItem active icon={Beaker} iconSize={16} title={t('lobeBench.sidebar.draft')} />
+ )}
+ {!isInit && experiments.length === 0 ? (
+ <SkeletonList rows={2} />
+ ) : experiments.length === 0 ? (
+ <Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
+ {t('lobeBench.sidebar.empty')}
+ </Text>
+ ) : (
+ experiments.map((experiment) => {
+ const running = !!experiment.recentRuns?.some((run) => isRunActive(run.status));
+ const current = activeKey === `experiment-${experiment.id}`;
+ // Same row menu as the Lab's lists: delete sits behind "more" and the right click.
+ const menu = (): DropdownItem[] => [
+ {
+ danger: true,
+ disabled: running,
+ icon: <Trash2 size={16} />,
+ key: 'delete',
+ label: running ? t('lobeBench.experiment.delete.active') : t('common.delete'),
+ onClick: () =>
+ deleteExperiment(experiment, { active: running, leave: current }),
+ },
+ ];
+ return (
+ <div key={experiment.id}>
+ {link(
+ `${LOBE_BENCH_PATH}/experiments/${experiment.id}`,
+ <NavItem
+ active={current}
+ contextMenuItems={menu}
+ icon={Beaker}
+ iconSize={16}
+ loading={running}
+ title={experiment.name}
+ actions={
+ // Keep the row's link from firing when the menu is used.
+ <span
+ role={'presentation'}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <DropdownMenu
+ items={menu()}
+ placement={'bottomRight'}
+ trigger={['click']}
+ >
+ <ActionIcon
+ icon={MoreHorizontalIcon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ title={t('lobeBench.experiment.more')}
+ />
+ </DropdownMenu>
+ </span>
+ }
+ />,
+ )}
+ </div>
+ );
+ })
+ )}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ {/* Same three groups as the Evaluation Lab: experiments, benchmarks, datasets. */}
+ <AccordionItem value={'benchmarks'}>
+ <AccordionHeader style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
+ <AccordionTrigger>
+ <Flexbox horizontal align="center" gap={4}>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {t('lobeBench.sidebar.benchmarks')}
+ </Text>
+ {benchmarks.length > 0 && (
+ <Text fontSize={12} type="secondary">
+ {benchmarks.length}
+ </Text>
+ )}
+ </Flexbox>
+ </AccordionTrigger>
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={t('lobeBench.sidebar.newBenchmark')}
+ onClick={createBenchmark}
+ />
+ </div>
+ </AccordionHeader>
+ <AccordionPanel>
+ <Flexbox gap={1} paddingBlock={1}>
+ {benchmarks.length === 0 ? (
+ loadingBenchmarks ? (
+ <SkeletonList rows={2} />
+ ) : (
+ <Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
+ {t('lobeBench.sidebar.benchmarks.empty')}
+ </Text>
+ )
+ ) : (
+ benchmarks.map((benchmark) => (
+ <div key={benchmark.id}>
+ {link(
+ `${LOBE_BENCH_PATH}/benchmarks/${benchmark.id}`,
+ <NavItem
+ active={activeKey === `benchmark-${benchmark.id}`}
+ icon={getBenchmarkIcon(benchmark.id)}
+ iconSize={16}
+ title={benchmark.name}
+ />,
+ )}
+ </div>
+ ))
+ )}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ {/* The datasets the benchmarks are made of, then the account's own (cases
+ picked from the library, or its own), flat like the Evaluation Lab's list. */}
+ <AccordionItem value={'datasets'}>
+ <AccordionHeader style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
+ <AccordionTrigger>
+ <Flexbox horizontal align="center" gap={4}>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {t('lobeBench.sidebar.datasets')}
+ </Text>
+ {sidebarDatasets.length > 0 && (
+ <Text fontSize={12} type="secondary">
+ {sidebarDatasets.length}
+ </Text>
+ )}
+ </Flexbox>
+ </AccordionTrigger>
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size="small"
+ title={t('dataset.import.title')}
+ onClick={() => importDataset()}
+ />
+ </div>
+ </AccordionHeader>
+ <AccordionPanel>
+ <Flexbox gap={1} paddingBlock={1}>
+ {!datasets && (loadingBenchmarks || benchmarkIds.length > 0) ? (
+ <SkeletonList rows={2} />
+ ) : sidebarDatasets.length === 0 ? (
+ <Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">
+ {t('lobeBench.sidebar.datasets.empty')}
+ </Text>
+ ) : (
+ sidebarDatasets.map((dataset) => (
+ <div key={dataset.id}>
+ {link(
+ `${LOBE_BENCH_PATH}/datasets/${dataset.id}`,
+ <NavItem
+ active={activeKey === `dataset-${dataset.id}`}
+ icon={Database}
+ iconSize={16}
+ title={dataset.name}
+ />,
+ )}
+ </div>
+ ))
+ )}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ </AccordionRoot>
+ {/* Reference and account pages: pinned to the bottom, apart from the working lists above. */}
+ <Flexbox gap={1} style={{ marginBlockStart: 'auto' }}>
+ {link(
+ `${LOBE_BENCH_PATH}/library`,
+ <NavItem
+ active={activeKey === 'library'}
+ icon={LibraryBig}
+ title={t('lobeBench.sidebar.library')}
+ />,
+ )}
+ {link(
+ `${LOBE_BENCH_PATH}/contenders`,
+ <NavItem
+ active={activeKey === 'contenders'}
+ icon={Users}
+ title={t('lobeBench.sidebar.contenders')}
+ />,
+ )}
+ {link(
+ `${LOBE_BENCH_PATH}/settings`,
+ <NavItem
+ active={activeKey === 'settings'}
+ icon={Settings2}
+ title={t('lobeBench.sidebar.settings')}
+ />,
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default Body;
diff --git a/src/features/LobeBench/Layout/Sidebar/Content.tsx b/src/features/LobeBench/Layout/Sidebar/Content.tsx
new file mode 100644
index 00000000000..2385b6de1af
--- /dev/null
+++ b/src/features/LobeBench/Layout/Sidebar/Content.tsx
@@ -0,0 +1,11 @@
+'use client';
+
+import { memo } from 'react';
+
+import Body from '@/features/LobeBench/Layout/Sidebar/Body';
+import Header from '@/features/LobeBench/Layout/Sidebar/Header';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+const Content = memo(() => <SideBarLayout body={<Body />} header={<Header />} />);
+
+export default Content;
diff --git a/src/features/LobeBench/Layout/Sidebar/Header.tsx b/src/features/LobeBench/Layout/Sidebar/Header.tsx
new file mode 100644
index 00000000000..4f66763e47b
--- /dev/null
+++ b/src/features/LobeBench/Layout/Sidebar/Header.tsx
@@ -0,0 +1,21 @@
+'use client';
+
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { LOBE_BENCH_PATH } from '@/features/LobeBench/lobeBench';
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+/**
+ * Lobe Bench sits next to the Evaluation Lab under the one `/eval` entry (the
+ * segmented switch at the top), so its breadcrumb is its own name, like the
+ * Lab's is — not a step below the Lab.
+ */
+const Header = memo(() => {
+ const { t } = useTranslation('eval');
+ return (
+ <SideBarHeaderLayout breadcrumb={[{ href: LOBE_BENCH_PATH, title: t('lobeBench.title') }]} />
+ );
+});
+
+export default Header;
diff --git a/src/features/LobeBench/Layout/Sidebar/index.tsx b/src/features/LobeBench/Layout/Sidebar/index.tsx
new file mode 100644
index 00000000000..885906a853e
--- /dev/null
+++ b/src/features/LobeBench/Layout/Sidebar/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo } from 'react';
+
+import Content from '@/features/LobeBench/Layout/Sidebar/Content';
+import NavPanelPortal from '@/features/NavPanel/NavPanelPortal';
+
+const Sidebar = memo(() => (
+ <NavPanelPortal navKey="eval">
+ <Content />
+ </NavPanelPortal>
+));
+
+export default Sidebar;
diff --git a/src/features/LobeBench/Layout/index.tsx b/src/features/LobeBench/Layout/index.tsx
new file mode 100644
index 00000000000..ba7d361250b
--- /dev/null
+++ b/src/features/LobeBench/Layout/index.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { type FC } from 'react';
+import { Outlet } from 'react-router';
+
+import { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
+import AreaSwitch from '@/features/LobeBench/AreaSwitch';
+import Sidebar from '@/features/LobeBench/Layout/Sidebar';
+import { useNarrowBenchNavigation } from '@/features/LobeBench/useNarrowBenchNavigation';
+import NavHeader from '@/features/NavHeader';
+import { styles } from '@/routes/(main)/eval/_layout/style';
+
+const LobeBenchLayout: FC = () => {
+ useNarrowBenchNavigation();
+ return (
+ <>
+ <Sidebar />
+ <Flexbox className={styles.mainContainer} flex={1} height={'100%'} style={{ minWidth: 0 }}>
+ <NavHeader
+ style={{
+ left: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ zIndex: 10,
+ }}
+ styles={{
+ center: { ...AGENT_PROFILE_TABS_CENTER_STYLE, pointerEvents: 'auto' },
+ left: { pointerEvents: 'auto' },
+ }}
+ >
+ <AreaSwitch active={'bench'} />
+ </NavHeader>
+ <Outlet />
+ </Flexbox>
+ </>
+ );
+};
+
+export default LobeBenchLayout;
diff --git a/src/features/LobeBench/Library/index.tsx b/src/features/LobeBench/Library/index.tsx
new file mode 100644
index 00000000000..af896389690
--- /dev/null
+++ b/src/features/LobeBench/Library/index.tsx
@@ -0,0 +1,84 @@
+'use client';
+
+import { Button, Empty, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { ImportIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import CaseTable from '@/features/LobeBench/CaseTable';
+import { datasetsOf, isViewDataset, libraryOf, nativeCaseId } from '@/features/LobeBench/lobeBench';
+import { useImportLobeBenchDataset } from '@/features/LobeBench/useImportDataset';
+import { useLobeBenchBenchmarks, useLobeBenchDatasets } from '@/features/LobeBench/useLobeBench';
+import { useEvalStore } from '@/store/eval';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+});
+
+/**
+ * Compatibility view for previously installed library cases. New datasets
+ * can be imported directly without installing a shared library.
+ */
+const LobeBenchLibrary = memo(() => {
+ const { t } = useTranslation('eval');
+ const importDataset = useImportLobeBenchDataset();
+ const { benchmarks } = useLobeBenchBenchmarks();
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ const library = libraryOf(datasets);
+ // Cases that are also in a built-in dataset of library cases carry its name (Hard 50).
+ const views = useMemo(() => datasetsOf(datasets).filter(isViewDataset), [datasets]);
+ const viewIds = useMemo(() => views.map((view) => view.id), [views]);
+ const { data: viewCases } = useEvalStore.getState().useFetchCasesByDataset(viewIds);
+ const memberships = useMemo(() => {
+ if (!viewCases) return;
+ const names: Record<string, string[]> = {};
+ for (const view of views) {
+ for (const item of viewCases[view.id] ?? []) {
+ (names[nativeCaseId(item)] ??= []).push(view.name);
+ }
+ }
+ return names;
+ }, [viewCases, views]);
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={20}>
+ <Flexbox gap={4}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {t('lobeBench.library.title')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.library.subtitle')}</Text>
+ </Flexbox>
+
+ {library ? (
+ <CaseTable
+ selectable
+ benchmarkIds={benchmarkIds}
+ dataset={library}
+ memberships={memberships}
+ />
+ ) : (
+ <Empty description={t('lobeBench.library.empty')}>
+ <Button
+ icon={ImportIcon}
+ style={{ marginTop: 16 }}
+ type="primary"
+ onClick={() => importDataset()}
+ >
+ {t('dataset.import.title')}
+ </Button>
+ </Empty>
+ )}
+ </Flexbox>
+ );
+});
+
+LobeBenchLibrary.displayName = 'LobeBenchLibrary';
+
+export default LobeBenchLibrary;
diff --git a/src/features/LobeBench/NewExperiment/LaunchProgress.tsx b/src/features/LobeBench/NewExperiment/LaunchProgress.tsx
new file mode 100644
index 00000000000..5bd7dc2e4bd
--- /dev/null
+++ b/src/features/LobeBench/NewExperiment/LaunchProgress.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import { Flexbox, Progress, Text } from '@lobehub/ui';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { LaunchProgress } from '../experimentLaunch';
+
+export const LaunchProgressPanel = ({
+ active,
+ createdAt,
+ progress,
+}: {
+ active: boolean;
+ createdAt: string;
+ progress: LaunchProgress;
+}) => {
+ const { t } = useTranslation('eval');
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (!active) return;
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [active]);
+ // The launch's persisted timestamp survives remounts and resumes. The label
+ // explicitly includes the time before a resume, not just this request's wait.
+ const elapsedSeconds = Math.max(0, Math.floor((now - Date.parse(createdAt)) / 1000));
+ const elapsed = `${Math.floor(elapsedSeconds / 60)}:${String(elapsedSeconds % 60).padStart(2, '0')}`;
+ const stages = {
+ check: t('lobeBench.new.launch.stage.check'),
+ complete: t('lobeBench.new.launch.stage.complete'),
+ experiment: t('lobeBench.new.launch.stage.experiment'),
+ metadata: t('lobeBench.new.launch.stage.metadata'),
+ run: t('lobeBench.new.launch.stage.run'),
+ start: t('lobeBench.new.launch.stage.start'),
+ };
+ const model = progress.contender?.config.model;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox aria-atomic aria-live={'polite'} gap={4} role={'status'}>
+ <Text weight={500}>{stages[progress.stage]}</Text>
+ {progress.contender && (
+ <Text style={{ overflowWrap: 'anywhere' }}>
+ {t('lobeBench.new.launch.currentRun', {
+ index: progress.contenderIndex,
+ name: progress.contender.name,
+ total: progress.contenderCount,
+ })}
+ </Text>
+ )}
+ {typeof model === 'string' && model !== progress.contender?.name && (
+ <Text fontSize={12} style={{ overflowWrap: 'anywhere' }} type={'secondary'}>
+ {model}
+ </Text>
+ )}
+ </Flexbox>
+ <Progress
+ percent={(progress.completedSteps / progress.totalSteps) * 100}
+ showInfo={false}
+ status={progress.status === 'failed' ? 'exception' : 'normal'}
+ aria-label={t('lobeBench.new.launch.steps', {
+ completed: progress.completedSteps,
+ total: progress.totalSteps,
+ })}
+ />
+ <Flexbox horizontal gap={8} justify={'space-between'} wrap={'wrap'}>
+ <Text fontSize={12}>
+ {t('lobeBench.new.launch.steps', {
+ completed: progress.completedSteps,
+ total: progress.totalSteps,
+ })}
+ </Text>
+ <Text fontSize={12} style={{ fontVariantNumeric: 'tabular-nums' }} type={'secondary'}>
+ {t('lobeBench.new.launch.elapsed', { elapsed })}
+ </Text>
+ </Flexbox>
+ {active && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.launch.waiting')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/src/features/LobeBench/NewExperiment/index.tsx b/src/features/LobeBench/NewExperiment/index.tsx
new file mode 100644
index 00000000000..d8f11cef731
--- /dev/null
+++ b/src/features/LobeBench/NewExperiment/index.tsx
@@ -0,0 +1,955 @@
+'use client';
+
+import {
+ Accordion,
+ ActionIcon,
+ Alert,
+ Block,
+ Button,
+ confirmModal,
+ Flexbox,
+ Input,
+ InputNumber,
+ Modal,
+ Select,
+ Tag,
+ Text,
+ toast,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Pencil, Plus, X } from 'lucide-react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useSearchParams } from 'react-router';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { openContenderModal } from '@/features/LobeBench/ContenderForm';
+import { readExperimentDefaults } from '@/features/LobeBench/experimentDefaults';
+import {
+ draftDatasetIds,
+ type ExperimentDraft,
+ getInvalidDraftSelections,
+} from '@/features/LobeBench/experimentDraft';
+import {
+ createExperimentLaunch,
+ type ExperimentLaunch,
+ isResumableLaunch,
+ type LaunchOutcome,
+} from '@/features/LobeBench/experimentLaunch';
+import {
+ benchmarkDatasetsOf,
+ benchmarkIdsOfDatasets,
+ benchmarkProtocolOf,
+ caseCountOf,
+ datasetIdsOfBenchmarks,
+ DEFAULT_MAX_STEPS,
+ DEFAULT_TIMEOUT_MINUTES,
+ describeSettings,
+ getBenchmarkMeta,
+ K_OPTIONS,
+ LOBE_BENCH_KIND,
+ LOBE_BENCH_PATH,
+ type LobeBenchContender,
+ type LobeBenchExperimentMeta,
+ type LobeBenchExperimentPart,
+ pickPrimaryBenchmark,
+ RANK_ATTEMPTS,
+ replaceContender,
+ runStats,
+ sameContender,
+ settingsBenchmarkOf,
+ sortBenchmarks,
+ upsertContenders,
+} from '@/features/LobeBench/lobeBench';
+import { useExperimentDraft } from '@/features/LobeBench/useExperimentDraft';
+import { useExperimentLaunch } from '@/features/LobeBench/useExperimentLaunch';
+import {
+ pickDefaultDataset,
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+import { useSavedContenders } from '@/features/LobeBench/useSavedContenders';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { agentEvalService } from '@/services/agentEval';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { useEvalStore } from '@/store/eval';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import {
+ forgetExperimentLaunch,
+ isExperimentLaunching,
+ startBackgroundLaunch,
+} from '../launchBackground';
+import { launchServices } from '../launchServices';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ form: { width: '100%', maxWidth: 760 },
+ step: {
+ fontSize: 12,
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ letterSpacing: '0.02em',
+ },
+ // One contender per row, the same outline and radius as the page's inputs.
+ row: {
+ display: 'flex',
+ gap: 12,
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingBlock: 10,
+ paddingInline: 12,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ },
+});
+
+const NewExperiment = memo(() => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const refreshExperiments = useEvalStore((s) => s.refreshExperiments);
+ const { benchmarks } = useLobeBenchBenchmarks();
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ // Past runs give a per-case price for a model the account ran before.
+ const { data: pastRuns } = useLobeBenchRuns(benchmarkIds);
+ // Contenders the account saved or ran before: one click adds them again.
+ const { contenders: savedContenders, save: saveContenders } = useSavedContenders();
+
+ const userId = useUserStore(userProfileSelectors.userId);
+ const workspaceId = useActiveWorkspaceId();
+ const enabledModels = useAiInfraStore((s) => s.enabledChatModelList);
+ const modelsReady = useAiInfraStore((s) => s.isInitAiProviderRuntimeState);
+ const [starting, setStarting] = useState(false);
+ const [confirmationOpen, setConfirmationOpen] = useState(false);
+ const [launchError, setLaunchError] = useState<string>();
+ const launchInFlight = useRef(false);
+ const creatingLaunch = useRef(false);
+ const [searchParams, setSearchParams] = useSearchParams();
+ const presetDatasetId = searchParams.get('dataset');
+ const initialDataset =
+ datasets?.find((item) => item.id === presetDatasetId) ||
+ pickDefaultDataset(datasets, pickPrimaryBenchmark(benchmarks)?.id);
+ const getInitialDraft = (benchmarkId: string): ExperimentDraft => {
+ // Hard 50 runs on the library: it starts from the library benchmark's defaults.
+ const benchmark = settingsBenchmarkOf(benchmarks, benchmarkId);
+ const defaults = {
+ ...getBenchmarkMeta(benchmark).defaults,
+ ...readExperimentDefaults(benchmark?.id ?? benchmarkId),
+ };
+ return {
+ contenders: [],
+ datasetId: pickDefaultDataset(datasets, benchmarkId)?.id,
+ // Three attempts by default: what a leaderboard ranks on.
+ k:
+ defaults?.k && K_OPTIONS.includes(defaults.k)
+ ? (defaults.k as ExperimentDraft['k'])
+ : (RANK_ATTEMPTS as ExperimentDraft['k']),
+ maxConcurrency: null,
+ maxSteps: defaults?.maxSteps ?? DEFAULT_MAX_STEPS,
+ name: '',
+ pickCases: false,
+ pickedCaseIds: [],
+ question: '',
+ timeoutMinutes: defaults?.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES,
+ };
+ };
+ const {
+ clearDraft,
+ draft,
+ ready: draftReady,
+ restored,
+ storageError,
+ updateDraft,
+ } = useExperimentDraft({
+ benchmarkIds,
+ getInitialDraft,
+ initialBenchmarkId: initialDataset?.benchmarkId ?? pickPrimaryBenchmark(benchmarks)?.id,
+ presetDatasetId,
+ ready: !!datasets && benchmarks.length > 0,
+ userId,
+ workspaceId,
+ });
+ const currentDraft = draft ?? getInitialDraft(initialDataset?.benchmarkId ?? '');
+ const { contenders, maxConcurrency, name, question } = currentDraft;
+ // An experiment is started on one or more benchmarks (experiments and benchmarks
+ // are n to n), never on a dataset by itself: a dataset the draft names stands for
+ // its benchmark, and each chosen benchmark runs every dataset it is made of.
+ const { datasetId: draftDatasetId, datasetIds: draftDatasetList } = currentDraft;
+ const draftIds = draftDatasetIds({ datasetId: draftDatasetId, datasetIds: draftDatasetList });
+ const { chosenBenchmarkIds, datasetIds } = useMemo(() => {
+ const chosen = benchmarkIdsOfDatasets(
+ datasets,
+ benchmarks,
+ draftDatasetIds({ datasetId: draftDatasetId, datasetIds: draftDatasetList }),
+ );
+ return {
+ chosenBenchmarkIds: chosen,
+ datasetIds: datasetIdsOfBenchmarks(datasets, benchmarks, chosen),
+ };
+ }, [benchmarks, datasets, draftDatasetId, draftDatasetList]);
+ // A launch in progress: the experiment and run ids were fixed before the
+ // first server call, so a failed start resumes against the same ids. While
+ // one exists the form is locked, so a resume cannot change what is running.
+ // The launch record is kept under the first dataset's benchmark.
+ const launchBenchmarkId =
+ (datasets?.find((d) => d.id === datasetIds[0]) ?? initialDataset)?.benchmarkId ?? undefined;
+ const {
+ begin: beginLaunch,
+ clear: clearLaunch,
+ launch,
+ ready: launchReady,
+ } = useExperimentLaunch({ benchmarkId: launchBenchmarkId, userId, workspaceId });
+ const [outcome, setOutcome] = useState<LaunchOutcome>();
+ // Providers this server cannot call for the account (no key), found by the
+ // pre-start check; cleared whenever the contenders or the judge change.
+ const [providerProblems, setProviderProblems] = useState<string[]>([]);
+ const [checkingProviders, setCheckingProviders] = useState(false);
+ const frozen = starting || !!launch;
+ const setContenders = (update: (list: LobeBenchContender[]) => LobeBenchContender[]) =>
+ updateDraft((value) => ({ ...value, contenders: update(value.contenders) }));
+ // Renames or retunes a picked contender; one from the saved list keeps the edit for later experiments too.
+ const editContender = (contender: LobeBenchContender) =>
+ openContenderModal(
+ (edited) => {
+ setContenders((list) => replaceContender(list, edited));
+ const saved = replaceContender(savedContenders, edited);
+ if (saved === savedContenders) return;
+ saveContenders(saved).catch((error: unknown) =>
+ toast.error(error instanceof Error ? error.message : String(error)),
+ );
+ },
+ t('lobeBench.contenders.edit'),
+ t('lobeBench.contender.save.list'),
+ contender,
+ );
+ // Only benchmarks are offered, each with the cases of all its datasets.
+ const benchmarkOptions = useMemo(
+ () =>
+ sortBenchmarks(benchmarks).flatMap((benchmark) => {
+ const madeOf = benchmarkDatasetsOf(datasets, benchmark);
+ return madeOf.length > 0
+ ? [{ benchmark, caseCount: madeOf.reduce((sum, d) => sum + caseCountOf(d), 0) }]
+ : [];
+ }),
+ [benchmarks, datasets],
+ );
+
+ const selected = useMemo(
+ () =>
+ datasetIds.flatMap((id) => {
+ const item = datasets?.find((d) => d.id === id);
+ return item ? [item] : [];
+ }),
+ [datasetIds, datasets],
+ );
+ // An experiment runs whole datasets (no case picking here), one
+ // part each: a run per contender on the dataset, as the Evaluation Lab runs one.
+ const parts = useMemo(
+ () =>
+ selected.map((d) => ({
+ benchmarkId: d.benchmarkId ?? undefined,
+ caseCount: caseCountOf(d),
+ datasetId: d.id,
+ })),
+ [selected],
+ );
+ const partsReady = parts.length > 0;
+ // Every run on a benchmark is graded by the judge the benchmark was made with;
+ // an experiment cannot pick its own.
+ const judgeOf = (benchmarkId?: string) =>
+ getBenchmarkMeta(benchmarks.find((b) => b.id === benchmarkId)).judge;
+ const chosenJudges = chosenBenchmarkIds.flatMap((id) => {
+ const benchmark = benchmarks.find((b) => b.id === id);
+ const judge = judgeOf(id);
+ return benchmark ? [{ benchmark, judge }] : [];
+ });
+ // Every run on a benchmark also follows the run rules (attempts per case, step
+ // limit, timeout) the benchmark was made with. One experiment runs one set of
+ // rules: its page, estimate and leaderboard read a single k.
+ const protocolOfBenchmark = (benchmarkId?: string) =>
+ benchmarkProtocolOf(benchmarks.find((b) => b.id === benchmarkId));
+ const protocol = protocolOfBenchmark(chosenBenchmarkIds[0]);
+ const benchmarksWithoutStandard = chosenJudges.filter(
+ ({ benchmark, judge }) => !judge || !protocolOfBenchmark(benchmark.id),
+ );
+ const mixedRules = chosenBenchmarkIds.some((id) => {
+ const rules = protocolOfBenchmark(id);
+ return (
+ !!rules &&
+ !!protocol &&
+ (rules.k !== protocol.k ||
+ rules.maxSteps !== protocol.maxSteps ||
+ rules.timeoutMinutes !== protocol.timeoutMinutes)
+ );
+ });
+ const k = protocol?.k ?? 1;
+ const caseCount = parts.reduce((sum, part) => sum + part.caseCount, 0);
+ const attempts = caseCount * contenders.length * k;
+ const availableModels = useMemo(
+ () =>
+ (enabledModels ?? []).flatMap((provider) =>
+ (provider.children ?? []).map((model) => ({
+ model: model.id,
+ provider: provider.id,
+ supportsTools: !!model.abilities?.functionCall,
+ })),
+ ),
+ [enabledModels],
+ );
+ const invalid = draft && getInvalidDraftSelections(draft, [], availableModels);
+ // A benchmark's judge must be one this account can call; it is never swapped for another.
+ const judgeUnavailable = chosenJudges.some(
+ ({ judge }) =>
+ !!judge &&
+ !availableModels.some((m) => m.model === judge.model && m.provider === judge.provider),
+ );
+ const missingModels = modelsReady && (!!invalid?.contenders.length || judgeUnavailable);
+ const canStart =
+ draftReady &&
+ launchReady &&
+ !launch &&
+ partsReady &&
+ contenders.length > 0 &&
+ caseCount > 0 &&
+ modelsReady &&
+ !missingModels &&
+ !!protocol &&
+ !mixedRules &&
+ benchmarksWithoutStandard.length === 0;
+ // Estimate from the newest completed run of each contender's model: its
+ // per-case cost times the cases and attempts this experiment will make.
+ const estimate = useMemo(() => {
+ let cost = 0;
+ let known = 0;
+ for (const contender of contenders) {
+ const history = (pastRuns ?? []).find((run) => {
+ const config = (run.config ?? {}) as { model?: string; provider?: string };
+ return (
+ run.status === 'completed' &&
+ config.model === contender.model &&
+ config.provider === contender.provider &&
+ runStats(run).perCaseCost !== undefined
+ );
+ });
+ if (!history) continue;
+ known += 1;
+ cost += runStats(history).perCaseCost! * caseCount * k;
+ }
+ return { cost, known };
+ }, [caseCount, contenders, k, pastRuns]);
+ const labels = {
+ reasoning: t('lobeBench.contender.settings.reasoning'),
+ temperature: t('lobeBench.contender.settings.temperature'),
+ topP: t('lobeBench.contender.settings.topP'),
+ };
+
+ const providersInPlay = [
+ ...new Set([
+ ...contenders.map((c) => c.provider),
+ ...chosenJudges.flatMap(({ judge }) => (judge?.provider ? [judge.provider] : [])),
+ ]),
+ ].sort();
+ const providersKey = providersInPlay.join(',');
+ useEffect(() => {
+ setProviderProblems([]);
+ }, [providersKey]);
+
+ // Money leaves the account only after this: the one confirmation of the flow.
+ // First the same provider construction a run performs: a contender whose
+ // provider has no key on this server would otherwise burn every attempt on
+ // `InvalidProviderAPIKey`.
+ const confirmStart = async () => {
+ if (!canStart || checkingProviders || starting || confirmationOpen) return;
+ setCheckingProviders(true);
+ let problems: string[];
+ try {
+ const checks = (await agentEvalService.checkProviders(providersInPlay)) ?? [];
+ problems = checks.filter((check) => !check.ok).map((check) => check.provider);
+ } catch {
+ toast.error(t('lobeBench.new.providerCheckFailed'));
+ setCheckingProviders(false);
+ return;
+ }
+ setCheckingProviders(false);
+ setProviderProblems(problems);
+ if (problems.length > 0) {
+ toast.error(t('lobeBench.new.providerKeyMissing', { provider: problems.join(', ') }));
+ return;
+ }
+ setOutcome(undefined);
+ setLaunchError(undefined);
+ setConfirmationOpen(true);
+ };
+
+ // The parts as stored: the first also fills the one-dataset fields older readers know.
+ const metaParts = (): LobeBenchExperimentPart[] =>
+ parts.map(({ caseCount: _count, ...part }) => part);
+ const launchMetadata = (): LobeBenchExperimentMeta => {
+ const all = metaParts();
+ const [first] = all;
+ return {
+ contenders,
+ ...(first.caseIds && { caseIds: first.caseIds }),
+ datasetId: first.datasetId,
+ ...(all.length > 1 && { parts: all }),
+ ...(first.pickedDatasetId && { pickedDatasetId: first.pickedDatasetId }),
+ k: protocol!.k,
+ kind: LOBE_BENCH_KIND,
+ maxSteps: protocol!.maxSteps,
+ ...(question.trim() && { question: question.trim() }),
+ timeout: protocol!.timeoutMinutes * 60_000,
+ };
+ };
+ const runConfigFor = (key: string, part: LobeBenchExperimentPart) => {
+ const contender = contenders.find((c) => c.id === key);
+ if (!contender) throw new Error(`Unknown contender ${key}`);
+ // The part's benchmark rules, frozen into the run like every other parameter.
+ const rules = protocolOfBenchmark(part.benchmarkId) ?? protocol!;
+ return {
+ ...(part.caseIds && {
+ caseSelection: { caseIds: part.caseIds, mode: 'include' as const },
+ }),
+ ...(contender.chatConfig && { chatConfig: contender.chatConfig }),
+ // The part's benchmark judge, frozen into the run like every other parameter.
+ ...(judgeOf(part.benchmarkId) && {
+ judgeModel: judgeOf(part.benchmarkId)!.model,
+ judgeProvider: judgeOf(part.benchmarkId)!.provider,
+ }),
+ k: rules.k,
+ ...(maxConcurrency && { maxConcurrency }),
+ maxSteps: rules.maxSteps,
+ model: contender.model,
+ ...(contender.params && { params: contender.params }),
+ provider: contender.provider,
+ timeout: rules.timeoutMinutes * 60_000,
+ };
+ };
+
+ // Runs (or resumes) a launch record. It reads only the record: every id and
+ // every parameter was frozen when the launch began, so the draft, the case
+ // set in the URL or the models available now cannot change what it sends.
+ const runLaunch = async (record: ExperimentLaunch) => {
+ if (launchInFlight.current || !userId) return;
+ launchInFlight.current = true;
+ setStarting(true);
+ setConfirmationOpen(false);
+ setLaunchError(undefined);
+ clearDraft();
+ const task = startBackgroundLaunch(
+ { benchmarkId: record.benchmarkId, userId, workspaceId },
+ record,
+ launchServices,
+ );
+ navigate(`${LOBE_BENCH_PATH}/experiments/${record.experimentId}`);
+ try {
+ const result = await task;
+ if (!result.complete) return;
+ try {
+ await saveContenders(upsertContenders(savedContenders, contenders));
+ } catch {
+ /* Optional preference save. */
+ }
+ await refreshExperiments().catch(() => undefined);
+ await clearLaunch(record.experimentId);
+ } catch {
+ /* The experiment page displays the retained launch error. */
+ } finally {
+ launchInFlight.current = false;
+ setStarting(false);
+ }
+ };
+
+ const start = async () => {
+ if (!canStart || creatingLaunch.current || launchInFlight.current) return;
+ const all = metaParts();
+ const record = createExperimentLaunch({
+ benchmarkId: launchBenchmarkId ?? benchmarks[0].id,
+ // Linked to every benchmark it covers: Hard 50's, the library's, the account's.
+ benchmarkIds: [
+ ...new Set(all.flatMap((part) => (part.benchmarkId ? [part.benchmarkId] : []))),
+ ],
+ // One run per contender and dataset; picked cases run on the library they come from.
+ contenders: all.flatMap((part, index) =>
+ contenders.map((contender) => ({
+ config: runConfigFor(contender.id, part),
+ datasetId: part.datasetId,
+ id: contender.id,
+ name: contender.name,
+ ...(all.length > 1 && { part: index }),
+ })),
+ ),
+ datasetId: all[0].datasetId,
+ metadata: launchMetadata() as unknown as Record<string, unknown>,
+ name: name.trim() || contenders.map((c) => c.name).join(' vs '),
+ });
+ // No checkpoint, no spend: a launch this browser cannot remember cannot be
+ // resumed, and a launch another tab already began must not be overwritten.
+ creatingLaunch.current = true;
+ setStarting(true);
+ try {
+ const begun = await beginLaunch(record);
+ if (!begun.ok) {
+ if (begun.reason === 'occupied') {
+ setConfirmationOpen(false);
+ toast.error(t('lobeBench.new.launch.occupied'));
+ } else {
+ setLaunchError(t('lobeBench.new.launch.storageError'));
+ }
+ return;
+ }
+ await runLaunch(record);
+ } catch (error) {
+ setLaunchError(error instanceof Error ? error.message : t('lobeBench.new.error'));
+ } finally {
+ creatingLaunch.current = false;
+ setStarting(false);
+ }
+ };
+
+ const abandonLaunch = () => {
+ if (!launch) return;
+ if (isExperimentLaunching(launch.experimentId)) {
+ toast.error(t('lobeBench.new.launch.busy'));
+ return;
+ }
+ confirmModal({
+ content: t('lobeBench.new.launch.abandon.confirm'),
+ okText: t('lobeBench.new.launch.abandon'),
+ onOk: async () => {
+ if (isExperimentLaunching(launch.experimentId)) return;
+ await clearLaunch(launch.experimentId);
+ if (userId) forgetExperimentLaunch(userId, workspaceId, launch.experimentId);
+ setOutcome(undefined);
+ },
+ title: t('lobeBench.new.launch.abandon.title'),
+ });
+ };
+ const openLaunch = () => {
+ if (launch) {
+ setConfirmationOpen(false);
+ navigate(`${LOBE_BENCH_PATH}/experiments/${launch.experimentId}`);
+ }
+ };
+ const failureMessage =
+ launchError ??
+ (outcome?.error
+ ? outcome.error.stage === 'metadata'
+ ? t('lobeBench.new.launch.metadataFailed', { error: outcome.error.message })
+ : t('lobeBench.new.launch.failed', {
+ error: outcome.error.message,
+ name: outcome.error.contender?.name ?? t('lobeBench.new.title'),
+ })
+ : outcome && outcome.unconfirmed.length > 0
+ ? t('lobeBench.new.launch.unconfirmed', {
+ count: outcome.unconfirmed.length,
+ names: outcome.unconfirmed.map((c) => c.name).join(', '),
+ })
+ : undefined);
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
+ {/* createModal cannot disable Escape / the header close button in @lobehub/ui 6.15. */}
+ <Modal
+ closable={!starting}
+ keyboard={!starting}
+ maskClosable={!starting}
+ open={confirmationOpen}
+ footer={
+ <Flexbox horizontal gap={8} justify={'flex-end'} wrap={'wrap'}>
+ <Button disabled={starting} onClick={() => setConfirmationOpen(false)}>
+ {t('lobeBench.new.cancel')}
+ </Button>
+ {outcome && (
+ <Button disabled={starting} onClick={openLaunch}>
+ {t('lobeBench.new.launch.open')}
+ </Button>
+ )}
+ <Button
+ disabled={starting || (!!launch && !isResumableLaunch(launch))}
+ loading={starting}
+ type={'primary'}
+ onClick={() => (launch && isResumableLaunch(launch) ? runLaunch(launch) : start())}
+ >
+ {starting
+ ? t('lobeBench.new.launch.title')
+ : launch
+ ? outcome && !outcome.error && outcome.unconfirmed.length > 0
+ ? t('lobeBench.new.launch.recheck')
+ : t('lobeBench.new.launch.continue')
+ : t('lobeBench.new.confirm.ok')}
+ </Button>
+ </Flexbox>
+ }
+ title={
+ !starting && failureMessage
+ ? t('lobeBench.new.launch.interrupted')
+ : t('lobeBench.new.confirm.title')
+ }
+ onCancel={() => {
+ if (!starting) setConfirmationOpen(false);
+ }}
+ >
+ <Flexbox gap={16}>
+ {!failureMessage ? (
+ <Flexbox gap={8}>
+ <Text>
+ {t('lobeBench.new.confirm.line', {
+ attempts,
+ cases: caseCount,
+ contenders: contenders.length,
+ k,
+ })}
+ </Text>
+ <Text type={'secondary'}>
+ {estimate.known > 0
+ ? t('lobeBench.new.confirm.cost', { cost: `$${estimate.cost.toFixed(2)}` })
+ : t('lobeBench.new.confirm.costUnknown')}
+ </Text>
+ <Text type={'secondary'}>
+ {chosenJudges
+ .map(({ benchmark, judge }) => {
+ const rules = protocolOfBenchmark(benchmark.id);
+ return t('lobeBench.new.confirm.standardOf', {
+ benchmark: benchmark.name,
+ k: rules?.k ?? '—',
+ maxSteps: rules?.maxSteps ?? '—',
+ model: judge?.model ?? '—',
+ timeout: rules?.timeoutMinutes ?? '—',
+ });
+ })
+ .join(' · ')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.new.confirm.billing')}</Text>
+ </Flexbox>
+ ) : null}
+ {!starting && failureMessage && <Alert title={failureMessage} type={'warning'} />}
+ {outcome && !outcome.complete && (
+ <Text fontSize={12}>
+ {t('lobeBench.new.launch.progress', {
+ started: outcome.started.length + outcome.kept.length,
+ total: launch?.contenders.length ?? contenders.length,
+ })}
+ </Text>
+ )}
+ </Flexbox>
+ </Modal>
+ <Flexbox className={stylex.props(styles.form).className} gap={28}>
+ <Flexbox gap={4}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {t('lobeBench.new.title')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.new.subtitle')}</Text>
+ </Flexbox>
+
+ {restored && (
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.draft.restored')}
+ </Text>
+ <Button disabled={frozen} size={'small'} onClick={() => clearDraft(true)}>
+ {t('lobeBench.new.draft.discard')}
+ </Button>
+ </Flexbox>
+ )}
+ {storageError && <Alert title={t('lobeBench.new.draft.storageError')} type={'warning'} />}
+ {launch && (
+ <Alert
+ type={'warning'}
+ description={
+ <Flexbox gap={8}>
+ <Text fontSize={12}>
+ {!isResumableLaunch(launch)
+ ? t('lobeBench.new.launch.legacy.hint')
+ : !outcome
+ ? t('lobeBench.new.launch.unknown')
+ : (failureMessage ??
+ t('lobeBench.new.launch.progress', {
+ started: outcome.started.length + outcome.kept.length,
+ total: launch.contenders.length,
+ }))}
+ </Text>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {isResumableLaunch(launch) && (
+ <Button
+ disabled={starting}
+ loading={starting}
+ size={'small'}
+ type={'primary'}
+ onClick={() => runLaunch(launch)}
+ >
+ {outcome && !outcome.error && outcome.unconfirmed.length > 0
+ ? t('lobeBench.new.launch.recheck')
+ : t('lobeBench.new.launch.continue')}
+ </Button>
+ )}
+ <Button disabled={starting} size={'small'} onClick={openLaunch}>
+ {t('lobeBench.new.launch.open')}
+ </Button>
+ <Button disabled={starting} size={'small'} onClick={abandonLaunch}>
+ {t('lobeBench.new.launch.abandon')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ }
+ title={
+ isResumableLaunch(launch)
+ ? t('lobeBench.new.launch.pending')
+ : t('lobeBench.new.launch.legacy')
+ }
+ />
+ )}
+ {launchReady && !launch && benchmarks.length > 1 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.launch.perBenchmark')}
+ </Text>
+ )}
+
+ <Flexbox gap={12}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.new.name')}</Text>
+ <Input
+ disabled={!draftReady || frozen}
+ placeholder={t('lobeBench.new.name.placeholder')}
+ value={name}
+ variant={'filled'}
+ onChange={(e) => updateDraft({ name: e.target.value })}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.new.question')}</Text>
+ <Input
+ disabled={!draftReady || frozen}
+ placeholder={t('lobeBench.new.question.placeholder')}
+ value={question}
+ variant={'filled'}
+ onChange={(e) => updateDraft({ question: e.target.value })}
+ />
+ </Flexbox>
+ </Flexbox>
+
+ <Flexbox gap={10}>
+ <span className={stylex.props(styles.step).className}>
+ {t('lobeBench.new.step.dataset')}
+ </span>
+ <Select
+ disabled={!draftReady || frozen}
+ loading={!datasets}
+ mode={'multiple'}
+ value={chosenBenchmarkIds}
+ variant={'filled'}
+ options={benchmarkOptions.map(({ benchmark, caseCount: count }) => ({
+ label: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <span>{benchmark.name}</span>
+ <span style={{ color: cssVar.colorTextQuaternary, fontSize: 12 }}>
+ {t('lobeBench.new.dataset.cases', { count })}
+ </span>
+ </Flexbox>
+ ),
+ value: benchmark.id,
+ }))}
+ onChange={(value) => {
+ const ids = datasetIdsOfBenchmarks(datasets, benchmarks, value as string[]);
+ updateDraft((current) => ({
+ ...current,
+ datasetId: ids[0],
+ datasetIds: ids,
+ pickedCaseIds: [],
+ }));
+ // The URL named a case set: drop it once it is no longer chosen, so
+ // Back does not restore the old preset over this choice.
+ if (presetDatasetId && !ids.includes(presetDatasetId)) {
+ setSearchParams(
+ (params) => {
+ params.delete('dataset');
+ return params;
+ },
+ { replace: true },
+ );
+ }
+ }}
+ />
+ {draftReady && datasets && draftIds.some((id) => !datasets.some((d) => d.id === id)) && (
+ <Alert title={t('lobeBench.new.draft.datasetUnavailable')} type={'warning'} />
+ )}
+ </Flexbox>
+
+ <Flexbox gap={10}>
+ <span className={stylex.props(styles.step).className}>
+ {t('lobeBench.new.step.contenders')}
+ </span>
+ {savedContenders.some((saved) => !contenders.some((c) => sameContender(c, saved))) && (
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.contenders.saved')}
+ </Text>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {savedContenders
+ .filter((saved) => !contenders.some((c) => sameContender(c, saved)))
+ .map((saved) => (
+ <Button
+ disabled={!draftReady || frozen}
+ key={saved.id}
+ size={'small'}
+ onClick={() => setContenders((list) => [...list, { ...saved }])}
+ >
+ {saved.name}
+ </Button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+ <Flexbox gap={8}>
+ {contenders.map((contender) => {
+ const settings =
+ describeSettings(contender.params, contender.chatConfig, labels) ||
+ t('lobeBench.contender.settings.default');
+ return (
+ <div className={stylex.props(styles.row).className} key={contender.id}>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {contender.name}
+ </Text>
+ {/* The auto name already carries the settings; then show the model instead. */}
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {contender.name.includes(settings)
+ ? `${contender.model} · ${contender.provider}`
+ : `${settings} · ${contender.model} · ${contender.provider}`}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal gap={4} style={{ flex: 'none' }}>
+ <ActionIcon
+ disabled={!draftReady || frozen}
+ icon={Pencil}
+ size={'small'}
+ title={t('lobeBench.contenders.edit')}
+ onClick={() => editContender(contender)}
+ />
+ <ActionIcon
+ disabled={!draftReady || frozen}
+ icon={X}
+ size={'small'}
+ title={t('lobeBench.new.contenders.remove')}
+ onClick={() =>
+ setContenders((list) => list.filter((item) => item.id !== contender.id))
+ }
+ />
+ </Flexbox>
+ </div>
+ );
+ })}
+ <div>
+ <Button
+ disabled={!draftReady || frozen}
+ icon={Plus}
+ onClick={() =>
+ openContenderModal((contender) => setContenders((list) => [...list, contender]))
+ }
+ >
+ {t('lobeBench.new.contenders.add')}
+ </Button>
+ </div>
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {contenders.length === 0
+ ? t('lobeBench.new.contenders.empty')
+ : t('lobeBench.new.contenders.hint')}
+ </Text>
+ </Flexbox>
+
+ <Accordion
+ defaultValue={[]}
+ indicatorPlacement="inline"
+ styles={{ header: { paddingBlock: 8, paddingInline: 4 } }}
+ items={[
+ {
+ children: (
+ <Flexbox gap={16} style={{ paddingTop: 8 }}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.new.maxConcurrency')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.maxConcurrency.hint', { count: k })}
+ </Text>
+ <InputNumber
+ disabled={!draftReady || frozen}
+ max={20}
+ min={1}
+ placeholder={t('lobeBench.new.maxConcurrency.placeholder')}
+ precision={0}
+ style={{ width: '100%' }}
+ value={maxConcurrency}
+ variant={'filled'}
+ onChange={(value) => updateDraft({ maxConcurrency: value as number | null })}
+ />
+ </Flexbox>
+ </Flexbox>
+ ),
+ key: 'advanced',
+ title: t('lobeBench.new.advanced'),
+ },
+ ]}
+ />
+
+ {missingModels && (
+ <Alert title={t('lobeBench.new.draft.modelsUnavailable')} type={'warning'} />
+ )}
+ {benchmarksWithoutStandard.length > 0 && (
+ <Alert
+ type={'error'}
+ title={t('lobeBench.new.standard.missing', {
+ name: benchmarksWithoutStandard.map(({ benchmark }) => benchmark.name).join(', '),
+ })}
+ />
+ )}
+ {mixedRules && <Alert title={t('lobeBench.new.standard.mixed')} type={'error'} />}
+ {providerProblems.length > 0 && (
+ <Alert
+ title={t('lobeBench.new.providerKeyMissing', { provider: providerProblems.join(', ') })}
+ type={'error'}
+ />
+ )}
+
+ <Block padding={16} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Tag>{attempts}</Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.new.estimate', { attempts })}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ <Button disabled={starting} onClick={() => navigate(LOBE_BENCH_PATH)}>
+ {t('lobeBench.new.cancel')}
+ </Button>
+ <Button
+ disabled={!canStart || starting}
+ loading={starting || checkingProviders}
+ type={'primary'}
+ onClick={confirmStart}
+ >
+ {t('lobeBench.new.start')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+NewExperiment.displayName = 'LobeBenchNewExperiment';
+
+export default NewExperiment;
diff --git a/src/features/LobeBench/Overview/index.tsx b/src/features/LobeBench/Overview/index.tsx
new file mode 100644
index 00000000000..9a31f8dfcab
--- /dev/null
+++ b/src/features/LobeBench/Overview/index.tsx
@@ -0,0 +1,285 @@
+'use client';
+
+import { Button, Empty, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Beaker, Database, ImportIcon, Plus } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { openCreateBenchmarkModal } from '@/features/LobeBench/BenchmarkModal';
+import { pickRankedSet, rankContenders } from '@/features/LobeBench/benchmarkRanking';
+import { BenchmarkCard, ExperimentCard } from '@/features/LobeBench/DashboardCards';
+import {
+ benchmarkDatasetsOf,
+ caseCountOf,
+ customDatasetsOf,
+ experimentPartsOf,
+ isCustomBenchmark,
+ isLobeBenchMeta,
+ isRunActive,
+ LOBE_BENCH_PATH,
+ looseDatasetsOf,
+ rankableSetsOf,
+ sortBenchmarks,
+} from '@/features/LobeBench/lobeBench';
+import { isWorkspaceEmpty } from '@/features/LobeBench/overviewResults';
+import { useImportLobeBenchDataset } from '@/features/LobeBench/useImportDataset';
+import {
+ useLobeBenchBenchmarks,
+ useLobeBenchDatasets,
+ useLobeBenchExperiments,
+ useLobeBenchRuns,
+} from '@/features/LobeBench/useLobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ grid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(min(480px, 100%), 1fr))',
+ gap: 20,
+ },
+ sectionTitle: { margin: 0, fontSize: 18, fontWeight: 600 },
+ datasetRow: {
+ display: 'flex',
+ gap: 12,
+ alignItems: 'center',
+ paddingBlock: 14,
+ paddingInline: 16,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },
+ borderRadius: cssVar.borderRadiusLG,
+ color: 'inherit',
+ textDecoration: 'none',
+ },
+ datasetIcon: {
+ display: 'flex',
+ flex: 'none',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 32,
+ height: 32,
+ borderRadius: 10,
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+});
+
+/**
+ * The Lobe Bench dashboard, laid out as the Evaluation Lab's: experiments,
+ * then benchmarks with who leads each, then every dataset.
+ */
+const LobeBenchDashboard = memo(() => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const importDataset = useImportLobeBenchDataset();
+ const { benchmarks: benchmarkList, isLoading: loadingBenchmarks } = useLobeBenchBenchmarks();
+ const benchmarks = useMemo(() => sortBenchmarks(benchmarkList), [benchmarkList]);
+ const benchmarkIds = useMemo(() => benchmarks.map((b) => b.id), [benchmarks]);
+ const { data: datasets } = useLobeBenchDatasets(benchmarkIds);
+ const { experiments } = useLobeBenchExperiments();
+ const hasActive = experiments.some((e) => e.recentRuns?.some((r) => isRunActive(r.status)));
+ const { data: runs } = useLobeBenchRuns(benchmarkIds, {
+ refreshInterval: hasActive ? 5000 : undefined,
+ });
+
+ // The benchmark pages' ranking: per dataset, each contender's best judged full run
+ // on the current cases. A card shows the dataset with the most contenders.
+ const sets = useMemo(() => rankableSetsOf(benchmarks, datasets), [benchmarks, datasets]);
+ const rankings = useMemo(
+ () => new Map(sets.map((set) => [set.id, rankContenders(runs ?? [], set)])),
+ [runs, sets],
+ );
+
+ // Built-in benchmarks' datasets first, in benchmark order, then the account's own.
+ const listedDatasets = useMemo(
+ () => [
+ ...benchmarks
+ .filter((b) => !isCustomBenchmark(b))
+ .flatMap((b) => benchmarkDatasetsOf(datasets, b)),
+ ...customDatasetsOf(datasets),
+ ],
+ [benchmarks, datasets],
+ );
+
+ const runsOf = (experimentId: string) =>
+ (runs ?? []).filter((run) => run.experimentId === experimentId);
+ // A run's page lives under its dataset's benchmark.
+ const benchmarkIdOf = (run: { benchmarkId?: string; datasetId: string }) =>
+ datasets?.find((d) => d.id === run.datasetId)?.benchmarkId ??
+ run.benchmarkId ??
+ benchmarkIds[0];
+
+ const describeExperiment = (experiment: (typeof experiments)[number]) => {
+ const meta = isLobeBenchMeta(experiment.metadata) ? experiment.metadata : undefined;
+ // Named by the datasets it ran (an experiment can cover several benchmarks).
+ const names = (meta ? experimentPartsOf(meta) : []).map(
+ (part) => datasets?.find((d) => d.id === (part.pickedDatasetId ?? part.datasetId))?.name,
+ );
+ return t('lobeBench.experiment.line', {
+ count: meta?.contenders.length ?? 0,
+ dataset: names.length ? names.map((n) => n ?? '—').join(' + ') : '—',
+ k: meta?.k ?? 1,
+ });
+ };
+
+ const createBenchmark = () =>
+ openCreateBenchmarkModal({
+ datasets: looseDatasetsOf(datasets, benchmarks),
+ onCreated: (id) => navigate(`${LOBE_BENCH_PATH}/benchmarks/${id}`),
+ });
+ const newExperiment = () => navigate(`${LOBE_BENCH_PATH}/experiments/new`);
+
+ if (!loadingBenchmarks && isWorkspaceEmpty({ benchmarks, datasets, experiments })) {
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
+ <Empty description={t('lobeBench.overview.notInstalled')} icon={Database}>
+ <Button
+ icon={ImportIcon}
+ style={{ marginTop: 16 }}
+ type="primary"
+ onClick={() => importDataset()}
+ >
+ {t('dataset.import.title')}
+ </Button>
+ </Empty>
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1} gap={32}>
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
+ <Flexbox gap={4} style={{ minWidth: 0 }}>
+ <Text ellipsis as={'h1'} fontSize={30} style={{ lineHeight: 1.3 }} weight={600}>
+ {t('lobeBench.title')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.subtitle')}</Text>
+ </Flexbox>
+ <Button icon={Plus} type={'primary'} onClick={createBenchmark}>
+ {t('lobeBench.overview.createBenchmark')}
+ </Button>
+ </Flexbox>
+
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <h2 className={stylex.props(styles.sectionTitle).className}>
+ {t('overview.sections.experiments.title')}
+ </h2>
+ <Button icon={Plus} size={'small'} onClick={newExperiment}>
+ {t('lobeBench.overview.newExperiment')}
+ </Button>
+ </Flexbox>
+ {experiments.length === 0 ? (
+ <Empty description={t('lobeBench.overview.experiments.empty')} icon={Beaker}>
+ <Button icon={Plus} style={{ marginTop: 16 }} onClick={newExperiment}>
+ {t('lobeBench.overview.newExperiment')}
+ </Button>
+ </Empty>
+ ) : (
+ <div className={stylex.props(styles.grid).className}>
+ {experiments.map((experiment) => (
+ <ExperimentCard
+ benchmarkIdOf={benchmarkIdOf}
+ description={describeExperiment(experiment)}
+ experiment={experiment}
+ key={experiment.id}
+ runs={runsOf(experiment.id)}
+ />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+
+ <Flexbox gap={16}>
+ <h2 className={stylex.props(styles.sectionTitle).className}>
+ {t('overview.sections.benchmarks.title')}
+ </h2>
+ {benchmarks.length === 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.sidebar.benchmarks.empty')}
+ </Text>
+ )}
+ <div className={stylex.props(styles.grid).className}>
+ {benchmarks.map((benchmark) => {
+ const madeOf = benchmarkDatasetsOf(datasets, benchmark);
+ const own = sets.filter((set) => set.benchmarkId === benchmark.id);
+ const ranked = pickRankedSet(own, rankings);
+ return (
+ <BenchmarkCard
+ benchmark={benchmark}
+ caseCount={madeOf.reduce((sum, d) => sum + caseCountOf(d), 0)}
+ datasetCount={madeOf.length}
+ firstDatasetId={madeOf[0]?.id}
+ key={benchmark.id}
+ ranking={(ranked && rankings.get(ranked.id)?.contenders) || []}
+ rankedOn={
+ madeOf.length > 1 ? madeOf.find((d) => d.id === ranked?.id)?.name : undefined
+ }
+ runCount={
+ (runs ?? []).filter((run) => madeOf.some((d) => d.id === run.datasetId)).length
+ }
+ />
+ );
+ })}
+ </div>
+ </Flexbox>
+
+ <Flexbox gap={16}>
+ <Flexbox horizontal align="center" justify="space-between">
+ <h2 className={stylex.props(styles.sectionTitle).className}>
+ {t('overview.sections.datasets.title')}
+ </h2>
+ <Button icon={ImportIcon} size="small" onClick={() => importDataset()}>
+ {t('dataset.import.title')}
+ </Button>
+ </Flexbox>
+ {listedDatasets.length === 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.sidebar.datasets.empty')}
+ </Text>
+ ) : (
+ <div className={stylex.props(styles.grid).className}>
+ {listedDatasets.map((dataset) => {
+ const benchmark = benchmarks.find((b) => b.id === dataset.benchmarkId);
+ // The account's datasets filed under a built-in benchmark are in none.
+ const inBenchmark =
+ benchmark && benchmarkDatasetsOf(datasets, benchmark).includes(dataset);
+ return (
+ <WorkspaceLink
+ className={stylex.props(styles.datasetRow).className}
+ key={dataset.id}
+ to={`${LOBE_BENCH_PATH}/datasets/${dataset.id}`}
+ >
+ <div className={stylex.props(styles.datasetIcon).className}>
+ <Database size={16} style={{ color: cssVar.colorTextSecondary }} />
+ </div>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {dataset.name}
+ </Text>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {t('lobeBench.benchmark.cases', { count: caseCountOf(dataset) })} ·{' '}
+ {inBenchmark ? benchmark.name : t('overview.sections.datasets.noBenchmark')}
+ </Text>
+ </Flexbox>
+ </WorkspaceLink>
+ );
+ })}
+ </div>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+LobeBenchDashboard.displayName = 'LobeBenchDashboard';
+
+export default LobeBenchDashboard;
diff --git a/src/features/LobeBench/PicksDatasetModal.tsx b/src/features/LobeBench/PicksDatasetModal.tsx
new file mode 100644
index 00000000000..c8950ec9c27
--- /dev/null
+++ b/src/features/LobeBench/PicksDatasetModal.tsx
@@ -0,0 +1,156 @@
+'use client';
+
+import { Button, createModal, Flexbox, Input, Text, toast, useModalContext } from '@lobehub/ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createDataset, renameDataset } from '@/features/LobeBench/datasetCases';
+import { type LobeBenchCase } from '@/features/LobeBench/useLobeBench';
+
+/** The library a new dataset takes its mock, judge and case version from. */
+interface LibraryOption {
+ evalConfig?: unknown;
+ evalMode?: string | null;
+ metadata?: Record<string, unknown> | null;
+}
+
+interface PicksDatasetOption {
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ testCaseCount?: number | null;
+}
+
+interface CreateDatasetFormProps {
+ /** The benchmark the dataset is filed under until a benchmark of the account's takes it. */
+ benchmarkId: string;
+ /** The checked library cases, copied in. */
+ cases: LobeBenchCase[];
+ library?: LibraryOption;
+ onDone?: (dataset: { id: string; name: string }) => void;
+}
+
+/**
+ * Makes a dataset of the account's from checked library cases. Its cases are
+ * fixed from then on: another set of cases is another
+ * dataset, so the runs on this one keep meaning what they meant.
+ */
+const CreateDatasetForm = memo<CreateDatasetFormProps>(
+ ({ benchmarkId, cases, library, onDone }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const [name, setName] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ const submit = async () => {
+ setSaving(true);
+ try {
+ const datasetName = name.trim() || t('lobeBench.picks.defaultName');
+ const created = await createDataset(benchmarkId, datasetName, library, cases);
+ toast.success(t('lobeBench.picks.created', { count: cases.length, dataset: datasetName }));
+ close();
+ onDone?.({ id: created.id, name: datasetName });
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('lobeBench.picks.failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('lobeBench.picks.name')}</Text>
+ <Input
+ autoFocus
+ id={'lobe-bench-picks-name'}
+ placeholder={t('lobeBench.picks.name.placeholder')}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onPressEnter={submit}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {t('lobeBench.picks.fixed')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('common.cancel')}</Button>
+ <Button loading={saving} type={'primary'} onClick={submit}>
+ {t('lobeBench.picks.create')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+CreateDatasetForm.displayName = 'LobeBenchCreateDatasetForm';
+
+/** Opens the dialog that makes a dataset of these library cases. */
+export const openCreateDatasetModal = (props: CreateDatasetFormProps) =>
+ createModal({
+ content: <CreateDatasetForm {...props} />,
+ footer: null,
+ title: translate('lobeBench.picks.title', { count: props.cases.length, ns: 'eval' }),
+ width: 480,
+ });
+
+interface RenameDatasetFormProps {
+ dataset: PicksDatasetOption;
+ onSaved?: () => Promise<unknown> | void;
+}
+
+const RenameDatasetForm = memo<RenameDatasetFormProps>(({ dataset, onSaved }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const [name, setName] = useState(dataset.name);
+ const [saving, setSaving] = useState(false);
+
+ const submit = async () => {
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ setSaving(true);
+ try {
+ await renameDataset(dataset, trimmed);
+ await onSaved?.();
+ close();
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('lobeBench.picks.failed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Input
+ autoFocus
+ id={'lobe-bench-dataset-name'}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onPressEnter={submit}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('common.cancel')}</Button>
+ <Button disabled={!name.trim()} loading={saving} type={'primary'} onClick={submit}>
+ {t('common.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+RenameDatasetForm.displayName = 'LobeBenchRenameDatasetForm';
+
+/** Opens the dialog that renames a dataset made of library cases. */
+export const openRenameDatasetModal = (
+ dataset: PicksDatasetOption,
+ onSaved?: () => Promise<unknown> | void,
+) =>
+ createModal({
+ content: <RenameDatasetForm dataset={dataset} onSaved={onSaved} />,
+ footer: null,
+ title: translate('lobeBench.picks.rename', { ns: 'eval' }),
+ width: 420,
+ });
diff --git a/src/features/LobeBench/RankingBars.tsx b/src/features/LobeBench/RankingBars.tsx
new file mode 100644
index 00000000000..a08c7edcbce
--- /dev/null
+++ b/src/features/LobeBench/RankingBars.tsx
@@ -0,0 +1,261 @@
+'use client';
+
+import { cssVar as token } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import type { ReactNode } from 'react';
+
+const ROW_HEIGHT = 44;
+const BAR_SIZE = 24;
+const GRID_TICKS = [25, 50, 75];
+/** Room right of the plot for the reach text that follows the longest bar. */
+const REACH_TEXT_ROOM = 120;
+
+const styles = stylex.create({
+ root: { display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 },
+ // One grid for every row, so the label column is as wide as the longest
+ // name (up to a cap), the ranked score sits right before its bar, and every
+ // bar starts on the same axis.
+ rows: {
+ display: 'grid',
+ gridTemplateColumns: 'fit-content(460px) max-content minmax(160px, 1fr)',
+ minWidth: 0,
+ },
+ row: {
+ display: 'grid',
+ gridColumnStart: 1,
+ gridColumnEnd: -1,
+ gridTemplateColumns: 'subgrid',
+ alignItems: 'center',
+ height: ROW_HEIGHT,
+ minWidth: 0,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillQuaternary },
+ },
+ clickable: { cursor: 'pointer' },
+ label: { display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, paddingInlineEnd: 16 },
+ rank: {
+ flexShrink: 0,
+ minWidth: 24,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 14,
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: 1.3,
+ color: cssVar.colorTextQuaternary,
+ },
+ icon: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 24,
+ height: 24,
+ },
+ stack: {
+ display: 'flex',
+ flex: '1',
+ flexDirection: 'column',
+ gap: 2,
+ justifyContent: 'center',
+ minWidth: 0,
+ },
+ name: {
+ overflow: 'hidden',
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: 1.3,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ detail: {
+ overflow: 'hidden',
+ fontSize: 12,
+ lineHeight: 1.3,
+ color: cssVar.colorTextDescription,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ track: {
+ position: 'relative',
+ height: '100%',
+ minWidth: 0,
+ borderLeftWidth: 1,
+ borderLeftStyle: 'solid',
+ borderLeftColor: cssVar.colorBorder,
+ },
+ // The bars' 0..100% span: the track less room for the text after the bar.
+ plot: {
+ position: 'absolute',
+ top: 0,
+ bottom: 0,
+ left: 0,
+ right: REACH_TEXT_ROOM,
+ },
+ reachText: (left: string) => ({
+ left: `calc(${left} + 8px)`,
+ position: 'absolute',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: 1.3,
+ color: cssVar.colorTextDescription,
+ whiteSpace: 'nowrap',
+ }),
+ gridLine: (left: string) => ({
+ left,
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: 0,
+ bottom: 0,
+ width: 0,
+ borderLeftWidth: 1,
+ borderLeftStyle: 'dashed',
+ borderLeftColor: cssVar.colorBorderSecondary,
+ }),
+ bar: (width: string, backgroundColor: string) => ({
+ width,
+ backgroundColor,
+ position: 'absolute',
+ top: '50%',
+ left: 0,
+ transform: 'translateY(-50%)',
+ height: BAR_SIZE,
+ maxWidth: '100%',
+ }),
+ reach: (left: string, width: string, backgroundColor: string) => ({
+ left,
+ width,
+ backgroundColor,
+ position: 'absolute',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ height: BAR_SIZE,
+ opacity: 0.28,
+ }),
+ score: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'flex-end',
+ minWidth: 48,
+ paddingInlineEnd: 12,
+ },
+ scoreMain: {
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 14,
+ fontWeight: 600,
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: 1.3,
+ color: cssVar.colorText,
+ },
+ legend: { display: 'flex', flexWrap: 'wrap', gap: 16 },
+ legendItem: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 6,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ swatch: { width: 12, height: 12, backgroundColor: cssVar.colorTextTertiary },
+ swatchReach: { opacity: 0.28 },
+});
+
+export interface RankingBarRow {
+ /** Bar fill; the theme's primary color when the model's brand is unknown. */
+ color?: string;
+ detail?: string;
+ icon?: ReactNode;
+ key: string;
+ name: string;
+ rank: number;
+ /** The ranked value, 0..1. */
+ rate: number;
+ /** Where the bar would reach on a looser reading (pass@k); drawn as a faint extension. */
+ reach?: number;
+ /** Short text for `reach`, right after the end of the bar. */
+ reachText?: string;
+}
+
+interface RankingBarsProps {
+ legendRate: string;
+ legendReach: string;
+ onSelect?: (row: RankingBarRow) => void;
+ rows: RankingBarRow[];
+}
+
+const percent = (rate: number) => Math.max(0, Math.min(100, rate * 100));
+
+/**
+ * LobeBench's ranking anatomy (rank · icon · name and detail · ranked score ·
+ * brand-colored bar · reach text), drawn here because the chart package's ranking chart cannot
+ * add the pass@k reach: the solid bar is the ranked pass rate (every attempt
+ * passed), the faint extension of the same bar shows how far the model got
+ * when any attempt counts, so the gap between the two is its flakiness.
+ */
+const RankingBars = ({ legendRate, legendReach, onSelect, rows }: RankingBarsProps) => {
+ const hasReach = rows.some((row) => row.reach !== undefined && row.reach > row.rate);
+ return (
+ <div {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.rows)} role={'list'}>
+ {rows.map((row) => {
+ const pct = percent(row.rate);
+ const reachPct = row.reach === undefined ? pct : percent(row.reach);
+ const fill = row.color ?? token.colorPrimary;
+ return (
+ <div
+ aria-label={`#${row.rank} ${row.name}: ${Math.round(pct)}%`}
+ key={row.key}
+ role={'listitem'}
+ onClick={onSelect ? () => onSelect(row) : undefined}
+ {...stylex.props(styles.row, onSelect && styles.clickable)}
+ >
+ <div {...stylex.props(styles.label)}>
+ <span {...stylex.props(styles.rank)}>#{row.rank}</span>
+ {row.icon && <span {...stylex.props(styles.icon)}>{row.icon}</span>}
+ <div {...stylex.props(styles.stack)}>
+ <div {...stylex.props(styles.name)}>{row.name}</div>
+ {row.detail && <div {...stylex.props(styles.detail)}>{row.detail}</div>}
+ </div>
+ </div>
+ <div {...stylex.props(styles.score)}>
+ <span {...stylex.props(styles.scoreMain)}>{Math.round(pct)}%</span>
+ </div>
+ <div {...stylex.props(styles.track)}>
+ <div {...stylex.props(styles.plot)}>
+ {GRID_TICKS.map((tick) => (
+ <div aria-hidden key={tick} {...stylex.props(styles.gridLine(`${tick}%`))} />
+ ))}
+ {reachPct > pct && (
+ <div {...stylex.props(styles.reach(`${pct}%`, `${reachPct - pct}%`, fill))} />
+ )}
+ <div {...stylex.props(styles.bar(`${pct}%`, fill))} />
+ {row.reachText && (
+ <span {...stylex.props(styles.reachText(`${Math.max(pct, reachPct)}%`))}>
+ {row.reachText}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ <div {...stylex.props(styles.legend)}>
+ <span {...stylex.props(styles.legendItem)}>
+ <span {...stylex.props(styles.swatch)} />
+ {legendRate}
+ </span>
+ {hasReach && (
+ <span {...stylex.props(styles.legendItem)}>
+ <span {...stylex.props(styles.swatch, styles.swatchReach)} />
+ {legendReach}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default RankingBars;
diff --git a/src/features/LobeBench/RunsSection.tsx b/src/features/LobeBench/RunsSection.tsx
new file mode 100644
index 00000000000..86fea3d5c35
--- /dev/null
+++ b/src/features/LobeBench/RunsSection.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+import type { AgentEvalRunListItem } from '@lobechat/types';
+import { Flexbox, Select, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, type ReactNode, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ isFullRun,
+ isRunOnCaseVersion,
+ type RankableSet,
+ runCaseCount,
+ runCoversSet,
+} from '@/features/LobeBench/lobeBench';
+import { createRunEditModal } from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal';
+import RunCard from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard';
+
+const styles = stylex.create({
+ sectionTitle: {
+ margin: 0,
+ fontSize: cssVar.fontSizeLG,
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+ grid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))',
+ gap: 12,
+ },
+ filterEmpty: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: 48,
+ paddingInline: 24,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+});
+
+interface RunsSectionProps {
+ /** Beside the title, e.g. the benchmark's "New experiment". */
+ action?: ReactNode;
+ /** The benchmark a run card links into (its run page lives under it). */
+ benchmarkId?: string;
+ /** How many runs the filter leaves, worded for the page. */
+ countLabel: (count: number) => string;
+ /** Read for each run's case count, to say when it ran only some of the cases. */
+ datasets?: Array<{ id: string; testCaseCount?: number | null }>;
+ emptyLabel: string;
+ onRefresh: () => Promise<unknown>;
+ /** The ranked case sets: a run on an earlier version of their cases says it does not rank. */
+ rankedSets?: RankableSet[];
+ runs: AgentEvalRunListItem[];
+}
+
+/**
+ * The run cards of a Lobe Bench page, newest first, with a status filter: the
+ * benchmark lists every run on its datasets, an experiment one run per contender.
+ */
+const RunsSection = memo<RunsSectionProps>(
+ ({ action, benchmarkId, countLabel, datasets, emptyLabel, onRefresh, rankedSets, runs }) => {
+ const { t } = useTranslation('eval');
+ const [statusFilter, setStatusFilter] = useState<string>('all');
+
+ const sortedRuns = useMemo(
+ () =>
+ [...runs].sort(
+ (a, b) => new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime(),
+ ),
+ [runs],
+ );
+ const filteredRuns = useMemo(() => {
+ if (statusFilter === 'all') return sortedRuns;
+ if (statusFilter === 'active') {
+ return sortedRuns.filter((r) => r.status === 'running' || r.status === 'pending');
+ }
+ return sortedRuns.filter((r) => r.status === statusFilter);
+ }, [sortedRuns, statusFilter]);
+
+ const handleRefresh = useCallback(async () => {
+ await onRefresh();
+ }, [onRefresh]);
+
+ const statusOptions = [
+ { label: t('table.filter.all'), value: 'all' },
+ { label: t('run.status.completed'), value: 'completed' },
+ { label: t('run.filter.active'), value: 'active' },
+ { label: t('run.status.idle'), value: 'idle' },
+ { label: t('run.status.failed'), value: 'failed' },
+ { label: t('run.status.aborted'), value: 'aborted' },
+ ];
+
+ const noteOf = (run: AgentEvalRunListItem) => {
+ // A run on an earlier version of the cases stays listed, but does not rank.
+ if (rankedSets?.some((set) => runCoversSet(run, set) && !isRunOnCaseVersion(run, set)))
+ return t('lobeBench.benchmark.outdatedRun');
+ const setSize = datasets?.find((dataset) => dataset.id === run.datasetId)?.testCaseCount ?? 0;
+ return isFullRun(run) || !setSize
+ ? undefined
+ : t('lobeBench.benchmark.runCases', {
+ selected: runCaseCount(run, setSize),
+ total: setSize,
+ });
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <h3 className={stylex.props(styles.sectionTitle).className}>
+ {t('lobeBench.benchmark.runs')}
+ </h3>
+ {sortedRuns.length > 0 && (
+ <>
+ <Text type={'secondary'}>{countLabel(filteredRuns.length)}</Text>
+ <Select
+ options={statusOptions}
+ size={'small'}
+ style={{ width: 128 }}
+ value={statusFilter}
+ onChange={(value) => setStatusFilter(value as string)}
+ />
+ </>
+ )}
+ </Flexbox>
+ {action}
+ </Flexbox>
+ {sortedRuns.length === 0 ? (
+ <Flexbox className={stylex.props(styles.filterEmpty).className}>
+ <Text type={'secondary'}>{emptyLabel}</Text>
+ </Flexbox>
+ ) : filteredRuns.length === 0 ? (
+ <Flexbox className={stylex.props(styles.filterEmpty).className}>
+ <Text type={'secondary'}>{t('run.filter.empty')}</Text>
+ </Flexbox>
+ ) : (
+ <div className={stylex.props(styles.grid).className}>
+ {filteredRuns.map((run) => (
+ <RunCard
+ benchmarkId={benchmarkId ?? ''}
+ key={run.id}
+ note={noteOf(run)}
+ run={run}
+ onEdit={(editingRun) => createRunEditModal({ run: editingRun })}
+ onRefresh={handleRefresh}
+ />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+RunsSection.displayName = 'RunsSection';
+
+export default RunsSection;
diff --git a/src/features/LobeBench/Settings/index.tsx b/src/features/LobeBench/Settings/index.tsx
new file mode 100644
index 00000000000..248ae3cb49b
--- /dev/null
+++ b/src/features/LobeBench/Settings/index.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
+const styles = stylex.create({
+ container: {
+ overflowY: 'auto',
+ paddingBlockStart: 56,
+ paddingBlockEnd: 32,
+ paddingInline: 32,
+ },
+ form: { width: '100%', maxWidth: 760 },
+});
+
+/**
+ * Lobe Bench settings. A benchmark fixes its judge and run rules (attempts per
+ * case, step limit, timeout) when it is made, so nothing here changes how runs
+ * are graded or run; what is left is where the mock connections are managed.
+ */
+const LobeBenchSettings = memo(() => {
+ const { t } = useTranslation('eval');
+
+ return (
+ <Flexbox className={stylex.props(styles.container).className} flex={1}>
+ <Flexbox className={stylex.props(styles.form).className} gap={24}>
+ <Flexbox gap={4}>
+ <Text as={'h1'} fontSize={24} weight={600}>
+ {t('lobeBench.settings.title')}
+ </Text>
+ <Text type={'secondary'}>{t('lobeBench.settings.subtitle')}</Text>
+ </Flexbox>
+ <Block padding={16} variant="outlined">
+ <Flexbox gap={8}>
+ <Text weight={600}>{t('connections.title')}</Text>
+ <Text type="secondary">{t('connections.settingsHint')}</Text>
+ <WorkspaceLink to="/settings/connector">{t('connections.openManager')}</WorkspaceLink>
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+LobeBenchSettings.displayName = 'LobeBenchSettings';
+
+export default LobeBenchSettings;
diff --git a/src/features/LobeBench/benchmarkIcon.ts b/src/features/LobeBench/benchmarkIcon.ts
new file mode 100644
index 00000000000..7e14c339096
--- /dev/null
+++ b/src/features/LobeBench/benchmarkIcon.ts
@@ -0,0 +1,33 @@
+import {
+ Activity,
+ Award,
+ BarChart3,
+ Gauge,
+ LoaderPinwheel,
+ Server,
+ Target,
+ TrendingUp,
+ Trophy,
+ Volleyball,
+ Zap,
+} from 'lucide-react';
+
+/** The Evaluation Lab's benchmark icons, picked by the same id hash so a benchmark looks the same on both sides. */
+const BENCHMARK_ICONS = [
+ LoaderPinwheel,
+ Volleyball,
+ Server,
+ Target,
+ Award,
+ Trophy,
+ Activity,
+ BarChart3,
+ TrendingUp,
+ Gauge,
+ Zap,
+];
+
+export const getBenchmarkIcon = (id: string) => {
+ const hash = [...id].reduce((acc, char) => acc + (char.codePointAt(0) ?? 0), 0);
+ return BENCHMARK_ICONS[hash % BENCHMARK_ICONS.length];
+};
diff --git a/src/features/LobeBench/benchmarkRanking.test.ts b/src/features/LobeBench/benchmarkRanking.test.ts
new file mode 100644
index 00000000000..6c4b3fc900b
--- /dev/null
+++ b/src/features/LobeBench/benchmarkRanking.test.ts
@@ -0,0 +1,342 @@
+import type { AgentEvalRunListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ contenderName,
+ pickRankedSet,
+ rankContenders,
+} from '@/features/LobeBench/benchmarkRanking';
+
+let seq = 0;
+
+/** A completed, fully judged run of 30 cases, 3 attempts each, unless overridden. */
+const run = (
+ over: Partial<Omit<AgentEvalRunListItem, 'metrics' | 'config'>> & {
+ config?: Record<string, unknown>;
+ metrics?: Record<string, unknown>;
+ passed?: number;
+ } = {},
+): AgentEvalRunListItem => {
+ const { passed = 20, metrics, config, ...rest } = over;
+ seq += 1;
+ return {
+ createdAt: new Date('2026-10-30T00:00:00Z'),
+ datasetId: 'set-a',
+ id: `run-${seq}`,
+ name: `model-${seq}`,
+ status: 'completed',
+ updatedAt: new Date('2026-10-30T01:00:00Z'),
+ ...rest,
+ config: { k: 3, ...config } as AgentEvalRunListItem['config'],
+ metrics: {
+ averageScore: passed / 30,
+ passRate: passed / 30,
+ errorCases: 0,
+ failedCases: 30 - passed,
+ passAllAt: { '3': passed / 30 },
+ passAnyAt: { '3': passed / 30 },
+ passedCases: passed,
+ timeoutCases: 0,
+ totalCases: 30,
+ ...metrics,
+ } as AgentEvalRunListItem['metrics'],
+ } as AgentEvalRunListItem;
+};
+
+describe('contenderName', () => {
+ it('prefers the run name, then the model, then the target Agent', () => {
+ expect(contenderName(run({ config: { model: 'm' }, name: 'DeepSeek · high' }))).toBe(
+ 'DeepSeek · high',
+ );
+ expect(contenderName(run({ config: { model: 'gpt-6.1' }, name: null }))).toBe('gpt-6.1');
+ expect(
+ contenderName(run({ name: null, targetAgent: { id: 'agt', title: 'My Agent' } as any })),
+ ).toBe('My Agent');
+ expect(contenderName(run({ name: null }))).toBe('Unknown');
+ });
+
+ it('puts the model back on a run named by its settings alone', () => {
+ expect(
+ contenderName(
+ run({ config: { model: 'qwen-latest-series-invite-1102' }, name: ' · 推理 on' }),
+ ),
+ ).toBe('qwen-latest-series-invite-1102 · 推理 on');
+ });
+});
+
+describe('rankContenders', () => {
+ it('ranks only runs on the current version of the cases', () => {
+ const current = '2026-10-30-realism-v4+realism-v3';
+ const set = { caseVersion: current, id: 'set-a' };
+ const ranking = rankContenders(
+ [
+ // Made on the current cases: ranks.
+ run({ config: { caseVersion: current }, name: 'DeepSeek', passed: 19 }),
+ // A better score on an earlier version (or before runs recorded one) does not.
+ run({
+ config: { caseVersion: '2026-10-30-realism-v4+realism-v2' },
+ name: 'Terra',
+ passed: 25,
+ }),
+ run({ name: 'Terra', passed: 24 }),
+ ],
+ set,
+ );
+ expect(ranking.contenders.map((c) => c.name)).toEqual(['DeepSeek']);
+ expect(ranking.outdated).toBe(2);
+ expect(ranking.ranked).toBe(1);
+ // A set without a version (cases the account wrote) ranks every run.
+ expect(rankContenders([run({ name: 'X' })], 'set-a').outdated).toBe(0);
+ });
+
+ it('ranks each contender by its best judged full run on the set, best first', () => {
+ const runs = [
+ run({ name: 'B', passed: 12 }),
+ run({ name: 'A', passed: 18 }),
+ // A's earlier, worse run does not add a second row.
+ run({ name: 'A', passed: 9 }),
+ // Other sets and picked-case runs say nothing about this set.
+ run({ datasetId: 'set-b', name: 'C', passed: 30 }),
+ run({
+ config: { caseSelection: { caseIds: ['x'], mode: 'include' } },
+ name: 'D',
+ passed: 30,
+ }),
+ run({ name: 'E', passed: 30, status: 'aborted' }),
+ ];
+ const ranking = rankContenders(runs, 'set-a');
+ expect(ranking.contenders.map((c) => [c.name, c.passed])).toEqual([
+ ['A', 18],
+ ['B', 12],
+ ]);
+ expect(ranking.ranked).toBe(3);
+ expect(ranking.active).toBe(0);
+ expect(ranking.broken).toBe(0);
+ expect(ranking.unjudged).toBe(0);
+ });
+
+ it('counts running and unjudged runs instead of ranking them', () => {
+ const runs = [
+ run({ name: 'A', passed: 18 }),
+ run({ metrics: { passedCases: 0, failedCases: 0 }, name: 'B', status: 'running' }),
+ run({ name: 'C', status: 'pending' }),
+ // Completed, but three cases still wait for the Judge.
+ run({ metrics: { failedCases: 7, judgeErrorCases: 3 }, name: 'D', passed: 20 }),
+ // Completed, but every case errored (no API key): no evidence about the model.
+ run({ metrics: { errorCases: 30, failedCases: 0 }, name: 'E', passed: 0 }),
+ ];
+ const ranking = rankContenders(runs, 'set-a');
+ expect(ranking.contenders.map((c) => c.name)).toEqual(['A']);
+ expect(ranking.active).toBe(2);
+ expect(ranking.unjudged).toBe(1);
+ expect(ranking.broken).toBe(1);
+ expect(ranking.ranked).toBe(1);
+ });
+
+ it('excludes partially broken runs and historical hidden errors despite saved complete scores', () => {
+ const good = run({ name: 'Valid', passed: 12 });
+ const ranking = rankContenders(
+ [
+ good,
+ run({ name: 'Partial error', passed: 29, metrics: { errorCases: 1, failedCases: 0 } }),
+ run({ name: 'Partial timeout', passed: 29, metrics: { timeoutCases: 1, failedCases: 0 } }),
+ run({
+ name: 'Legacy mixed error',
+ passed: 30,
+ hasUnverifiedAttempts: true,
+ metrics: { errorCases: 0 },
+ }),
+ ],
+ 'set-a',
+ );
+ expect(ranking.contenders.map((item) => item.run.id)).toEqual([good.id]);
+ expect(ranking).toMatchObject({ broken: 3, ranked: 1, unjudged: 0 });
+ });
+
+ it('ranks on 3 attempts: a run of 5 by its estimate for 3, one of fewer not at all', () => {
+ const runs = [
+ // 18/30 passed all 3 attempts, 29/30 at least one.
+ run({
+ metrics: { passAllAt: { '3': 0.6 }, passAnyAt: { '3': 29 / 30 } },
+ name: 'A',
+ passed: 29,
+ }),
+ // Five attempts rank on what three would show, not on all five.
+ run({
+ config: { k: 5 },
+ metrics: { passAllAt: { '3': 0.5, '5': 0.3 }, passAnyAt: { '3': 0.9 } },
+ name: 'B',
+ passed: 28,
+ }),
+ // One attempt cannot say how three would go.
+ run({ config: { k: 1 }, name: 'C', passed: 30 }),
+ ];
+ const ranking = rankContenders(runs, 'set-a');
+ expect(ranking.contenders.map((c) => [c.name, c.passed, c.anyK, c.attempts])).toEqual([
+ ['A', 18, 29, 3],
+ ['B', 15, 27, 5],
+ ]);
+ expect(ranking.fewAttempts).toBe(1);
+ expect(ranking.ranked).toBe(2);
+ });
+
+ it('ranks on the benchmark’s own k, whatever it is', () => {
+ const one = run({
+ config: { k: 1 },
+ metrics: { passAllAt: { '1': 0.5 }, passAnyAt: { '1': 0.5 } },
+ name: 'One',
+ passed: 15,
+ });
+ const three = run({
+ metrics: { passAllAt: { '1': 0.8, '3': 20 / 30 }, passAnyAt: { '1': 0.8, '3': 0.9 } },
+ name: 'Three',
+ passed: 20,
+ });
+ // A benchmark of one attempt per case ranks its one-attempt runs, and a run of three on its estimate for one.
+ const onK1 = rankContenders([one, three], { id: 'set-a', k: 1 });
+ expect(onK1.k).toBe(1);
+ expect(onK1.contenders.map((c) => [c.name, c.k])).toEqual([
+ ['Three', 1],
+ ['One', 1],
+ ]);
+ // A benchmark of five attempts ranks neither: both made fewer.
+ const onK5 = rankContenders([one, three], { id: 'set-a', k: 5 });
+ expect(onK5.contenders).toEqual([]);
+ expect(onK5.fewAttempts).toBe(2);
+ });
+
+ it('breaks ties by any-attempt passes, then cost per case, then recency', () => {
+ const runs = [
+ run({ metrics: { perCaseCost: 0.02 }, name: 'pricier', passed: 18 }),
+ run({ metrics: { perCaseCost: 0.01 }, name: 'cheaper', passed: 18 }),
+ run({ name: 'older', passed: 18, updatedAt: new Date('2026-10-01T00:00:00Z') }),
+ run({ name: 'newer', passed: 18, updatedAt: new Date('2026-10-29T00:00:00Z') }),
+ run({ metrics: { passAllAt: { '3': 0.6 }, passAnyAt: { '3': 29 / 30 } }, name: 'anyK 29' }),
+ run({ metrics: { passAllAt: { '3': 0.6 }, passAnyAt: { '3': 25 / 30 } }, name: 'anyK 25' }),
+ ];
+ expect(rankContenders(runs, 'set-a').contenders.map((c) => c.name)).toEqual([
+ 'anyK 29',
+ 'anyK 25',
+ 'cheaper',
+ 'pricier',
+ 'newer',
+ 'older',
+ ]);
+ });
+});
+
+describe('rankContenders by setup, not by name', () => {
+ const setup = (over: Record<string, unknown> = {}) => ({
+ maxSteps: 20,
+ model: 'deepseek/deepseek-v4.1-flash',
+ provider: 'openrouter',
+ timeout: 900_000,
+ ...over,
+ });
+
+ it('keeps the same model with another setting apart, even under one name', () => {
+ const ranking = rankContenders(
+ [
+ run({ config: setup(), name: 'DeepSeek', passed: 18 }),
+ run({
+ config: setup({ chatConfig: { thinkingLevel: 'high' } }),
+ name: 'DeepSeek',
+ passed: 22,
+ }),
+ // A bigger step budget is another setup too.
+ run({ config: setup({ maxSteps: 40 }), name: 'DeepSeek', passed: 20 }),
+ ],
+ 'set-a',
+ );
+ expect(ranking.contenders.map((c) => [c.name, c.passed])).toEqual([
+ ['DeepSeek (openrouter · thinking level high · 20 steps · 15 min)', 22],
+ ['DeepSeek (openrouter · default settings · 40 steps · 15 min)', 20],
+ ['DeepSeek (openrouter · default settings · 20 steps · 15 min)', 18],
+ ]);
+ });
+
+ it('keeps different Judge models and providers as separate comparisons', () => {
+ const judgeA = setup({ judgeModel: 'judge-a', judgeProvider: 'provider-one' });
+ const runs = [
+ run({ config: judgeA, name: 'Same contender', passed: 10 }),
+ run({ config: judgeA, name: 'Same contender', passed: 12 }),
+ run({
+ config: setup({ judgeModel: 'judge-b', judgeProvider: 'provider-one' }),
+ name: 'Same contender',
+ passed: 20,
+ }),
+ run({
+ config: setup({ judgeModel: 'judge-a', judgeProvider: 'provider-two' }),
+ name: 'Same contender',
+ passed: 25,
+ }),
+ ];
+ const ranking = rankContenders(runs, 'set-a');
+ expect(ranking.contenders.map((item) => item.run.id)).toEqual([
+ runs[3].id,
+ runs[2].id,
+ runs[1].id,
+ ]);
+ expect(ranking.ranked).toBe(4);
+ });
+
+ it('counts one setup once, whatever it was named', () => {
+ const ranking = rankContenders(
+ [
+ run({
+ config: setup({ params: { temperature: 0.2, top_p: 0.9 } }),
+ name: 'DeepSeek · temperature 0.2',
+ passed: 15,
+ }),
+ run({
+ config: setup({ params: { top_p: 0.9, temperature: 0.2 } }),
+ name: 'Mine',
+ passed: 19,
+ }),
+ ],
+ 'set-a',
+ );
+ expect(ranking.contenders.map((c) => [c.name, c.passed])).toEqual([['Mine', 19]]);
+ expect(ranking.ranked).toBe(2);
+ });
+});
+
+describe('rankContenders on a dataset that holds copies of library cases', () => {
+ it('ranks the runs on that dataset of all its cases, not runs on the library', () => {
+ const runs = [
+ run({ datasetId: 'hard', name: 'A', passed: 2 }),
+ // Some of its cases only: not a result on the dataset.
+ run({
+ config: { caseSelection: { caseIds: ['c1'], mode: 'include' } },
+ datasetId: 'hard',
+ name: 'B',
+ }),
+ // A run on the library is the library's, whatever cases it ran.
+ run({ datasetId: 'library', name: 'D', passed: 30 }),
+ ];
+ expect(rankContenders(runs, { id: 'hard' }).contenders.map((c) => c.name)).toEqual(['A']);
+ expect(rankContenders(runs, { id: 'library' }).contenders.map((c) => c.name)).toEqual(['D']);
+ });
+});
+
+describe('pickRankedSet', () => {
+ it('picks the set with the most ranked contenders, the first listed on a tie', () => {
+ const sets = [{ id: 'published' }, { id: 'mine' }, { id: 'subset' }];
+ const rankings = new Map([
+ ['published', rankContenders([run({ datasetId: 'published' })], 'published')],
+ ['mine', rankContenders([], 'mine')],
+ [
+ 'subset',
+ rankContenders(
+ [run({ datasetId: 'subset', name: 'A' }), run({ datasetId: 'subset', name: 'B' })],
+ 'subset',
+ ),
+ ],
+ ]);
+ expect(pickRankedSet(sets, rankings)?.id).toBe('subset');
+ rankings.set('published', rankings.get('subset')!);
+ expect(pickRankedSet(sets, rankings)?.id).toBe('published');
+ expect(pickRankedSet([], rankings)).toBeUndefined();
+ expect(pickRankedSet(sets, new Map())?.id).toBe('published');
+ });
+});
diff --git a/src/features/LobeBench/benchmarkRanking.ts b/src/features/LobeBench/benchmarkRanking.ts
new file mode 100644
index 00000000000..ab4c9024aa8
--- /dev/null
+++ b/src/features/LobeBench/benchmarkRanking.ts
@@ -0,0 +1,239 @@
+import type { AgentEvalRunListItem, EvalRunConfig } from '@lobechat/types';
+
+import {
+ describeSettings,
+ isRunActive,
+ isRunOnCaseVersion,
+ RANK_ATTEMPTS,
+ type RankableSet,
+ runCoversSet,
+ type RunStats,
+ runStats,
+ stableJson,
+} from '@/features/LobeBench/lobeBench';
+import { isRunGradingComplete } from '@/features/LobeBench/overviewResults';
+
+export interface RankedContender extends RunStats {
+ /** Attempts per case the run made; it ranks on `RANK_ATTEMPTS` of them. */
+ attempts: number;
+ /** The contender's label: the run's name, else its model, else its target Agent. */
+ name: string;
+ /** The best completed run the row stands for. */
+ run: AgentEvalRunListItem;
+}
+
+export interface SetRanking {
+ /** Runs still pending or running on the set; the ranking changes when they finish. */
+ active: number;
+ /**
+ * Completed full runs that errored on every case (a missing API key, a dead
+ * tool service): they say nothing about the model, so they are not ranked.
+ */
+ broken: number;
+ /** Each contender's best completed, judged run on the whole set, best first. */
+ contenders: RankedContender[];
+ /** Completed runs of fewer attempts per case than a leaderboard ranks on. */
+ fewAttempts: number;
+ /** Attempts per case the leaderboard ranks on: the benchmark's k. */
+ k: number;
+ /**
+ * Runs on the set made on an earlier version of its cases (or before runs recorded
+ * one): cases are edited in place, so only runs on the current version rank.
+ */
+ outdated: number;
+ /** Completed, judged full runs the ranking is drawn from. */
+ ranked: number;
+ /** Completed full runs whose judging has not finished; they are not ranked yet. */
+ unjudged: number;
+}
+
+export const contenderName = (run: AgentEvalRunListItem) => {
+ const config = (run.config ?? {}) as { model?: string };
+ const name = run.name?.trim();
+ // Runs named before a model without a display name fell back to its id
+ // start with the settings alone ("· reasoning on"): put the model back.
+ if (name?.startsWith('·') && config.model) return `${config.model} ${name}`;
+ return name || config.model || run.targetAgent?.title || run.targetAgent?.id || 'Unknown';
+};
+
+/**
+ * Who a run stands for on a leaderboard: the model and every setting it ran
+ * with (sampling, reasoning, step and time limits), never the name it was
+ * given; every run ranks on the same number of attempts, so they are not
+ * part of it. The same model with another setting is another contender, and
+ * two names for one setup are one. A run of an Agent stands for that Agent;
+ * one with neither falls back to its name.
+ */
+export const contenderKeyOf = (run: AgentEvalRunListItem) => {
+ const config = (run.config ?? {}) as EvalRunConfig;
+ const agentId = run.targetAgentId ?? run.targetAgent?.id;
+ return stableJson({
+ judgeModel: config.judgeModel,
+ judgeProvider: config.judgeProvider,
+ maxSteps: config.maxSteps,
+ timeout: config.timeout,
+ ...(config.model
+ ? {
+ chatConfig: config.chatConfig ?? {},
+ model: config.model,
+ params: config.params ?? {},
+ provider: config.provider,
+ }
+ : agentId
+ ? { agentId }
+ : { name: contenderName(run) }),
+ });
+};
+
+/** The setup a row stands for, to tell apart two rows that were given the same name. */
+const setupLabelOf = (run: AgentEvalRunListItem) => {
+ const config = (run.config ?? {}) as EvalRunConfig;
+ return [
+ config.provider,
+ describeSettings(config.params, config.chatConfig) || 'default settings',
+ config.maxSteps !== undefined && `${config.maxSteps} steps`,
+ config.timeout !== undefined && `${Math.round(config.timeout / 60_000)} min`,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+};
+
+/**
+ * A run's standing on `rankK` attempts per case (the benchmark's k): cases
+ * passing all of them (the solid bar) and at least one (the light bar). A run of
+ * more attempts is scored from its unbiased estimates (`passAllAt`); a run of
+ * fewer has none.
+ */
+export const rankedStatsOf = (
+ run: AgentEvalRunListItem,
+ rankK: number = RANK_ATTEMPTS,
+): RunStats | undefined => {
+ const stats = runStats(run);
+ if (stats.k < rankK) return undefined;
+ const metrics = (run.metrics ?? {}) as {
+ passAllAt?: Record<string, number>;
+ passAnyAt?: Record<string, number>;
+ };
+ const all = metrics.passAllAt?.[String(rankK)];
+ // Runs finished before the estimate was recorded: only one of exactly as many attempts says it.
+ if (all === undefined) return stats.k === rankK ? stats : undefined;
+ const any = metrics.passAnyAt?.[String(rankK)];
+ const cases = (share: number) => Math.round(share * stats.total * 10) / 10;
+ return {
+ ...stats,
+ allK: cases(all),
+ anyK: any === undefined ? stats.anyK : cases(any),
+ k: rankK,
+ passRate: all,
+ passed: cases(all),
+ };
+};
+
+const finishedAt = (run: AgentEvalRunListItem) =>
+ new Date(run.updatedAt ?? run.createdAt ?? 0).getTime();
+
+/** Unknown cost sorts last among equals without turning the comparison into NaN. */
+const costOf = (entry: RankedContender) => entry.perCaseCost ?? Number.MAX_VALUE;
+
+/** Best first: more cases passed, then more passed on any attempt, then cheaper per case, then newer. */
+export const compareContenders = (a: RankedContender, b: RankedContender) =>
+ b.passed - a.passed ||
+ (b.anyK ?? 0) - (a.anyK ?? 0) ||
+ costOf(a) - costOf(b) ||
+ finishedAt(b.run) - finishedAt(a.run);
+
+/**
+ * Who leads on one case set: each contender's best completed run over the
+ * whole set, ranked by cases passed. A contender is a setup, not a name
+ * (`contenderKeyOf`). A run that picked some cases says nothing
+ * about the set and is left out. Only runs on the
+ * current version of the cases rank; a completed run whose
+ * judging has not finished is counted but not ranked, as is one that errored
+ * on every case. Every run ranks on `RANK_ATTEMPTS` attempts per case: a case
+ * counts when it passes all of them (`rankedStatsOf`); a run of fewer attempts
+ * is counted but not ranked.
+ */
+export const rankContenders = (
+ runs: AgentEvalRunListItem[],
+ set: string | Pick<RankableSet, 'caseVersion' | 'id' | 'k'>,
+): SetRanking => {
+ const target: Pick<RankableSet, 'caseVersion' | 'id' | 'k'> =
+ typeof set === 'string' ? { id: set } : set;
+ // Ranked on the benchmark's own attempts per case, whatever k is.
+ const rankK = target.k ?? RANK_ATTEMPTS;
+ const best = new Map<string, RankedContender>();
+ let active = 0;
+ let broken = 0;
+ let fewAttempts = 0;
+ let outdated = 0;
+ let ranked = 0;
+ let unjudged = 0;
+ for (const run of runs) {
+ if (!runCoversSet(run, target)) continue;
+ if (!isRunOnCaseVersion(run, target)) {
+ outdated += 1;
+ continue;
+ }
+ if (isRunActive(run.status)) {
+ active += 1;
+ continue;
+ }
+ if (run.status !== 'completed') continue;
+ const stats = runStats(run);
+ if (run.hasUnverifiedAttempts || stats.errors > 0 || (run.metrics?.timeoutCases ?? 0) > 0) {
+ broken += 1;
+ continue;
+ }
+ if (!isRunGradingComplete(run)) {
+ unjudged += 1;
+ continue;
+ }
+ const onRankAttempts = rankedStatsOf(run, rankK);
+ if (!onRankAttempts) {
+ fewAttempts += 1;
+ continue;
+ }
+ ranked += 1;
+ const entry: RankedContender = {
+ ...onRankAttempts,
+ attempts: stats.k,
+ name: contenderName(run),
+ run,
+ };
+ const key = contenderKeyOf(run);
+ const prev = best.get(key);
+ if (!prev || compareContenders(entry, prev) < 0) best.set(key, entry);
+ }
+ const contenders = [...best.values()].sort(compareContenders);
+ // Rows of different setups that were given one name say which setup they are.
+ const named = new Map<string, number>();
+ for (const entry of contenders) named.set(entry.name, (named.get(entry.name) ?? 0) + 1);
+ for (const entry of contenders) {
+ if ((named.get(entry.name) ?? 0) > 1) entry.name = `${entry.name} (${setupLabelOf(entry.run)})`;
+ }
+ return {
+ active,
+ broken,
+ contenders,
+ fewAttempts,
+ k: rankK,
+ outdated,
+ ranked,
+ unjudged,
+ };
+};
+
+/**
+ * The set the page ranks on until the reader picks one: the set with the most
+ * ranked contenders, the first listed (the benchmark's published set) on a tie.
+ */
+export const pickRankedSet = <T extends { id: string }>(
+ sets: T[],
+ rankings: Map<string, SetRanking>,
+): T | undefined =>
+ sets.reduce<T | undefined>((top, set) => {
+ if (!top) return set;
+ const count = rankings.get(set.id)?.contenders.length ?? 0;
+ const topCount = rankings.get(top.id)?.contenders.length ?? 0;
+ return count > topCount ? set : top;
+ }, undefined);
diff --git a/src/features/LobeBench/caseEditorContent.test.ts b/src/features/LobeBench/caseEditorContent.test.ts
new file mode 100644
index 00000000000..ffdb1c65e05
--- /dev/null
+++ b/src/features/LobeBench/caseEditorContent.test.ts
@@ -0,0 +1,105 @@
+import type { EvalCaseEnvironment, ImportedMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildCaseContent } from './caseEditorContent';
+
+const draft = { category: '', environment: {}, input: ' Task ', turns: [] };
+
+describe('case editor content patches', () => {
+ it('explicitly clears previous inline overrides without clearing the shared environment binding', () => {
+ const previous = { input: 'Task', environment: { timezone: 'America/Chicago' } };
+ const content = buildCaseContent(draft);
+ // updateTestCase merges the top-level JSONB keys, so omission would retain the old overrides.
+ expect({ ...previous, ...content }).toMatchObject({ input: 'Task', environment: {} });
+ expect(content).not.toHaveProperty('environmentId');
+ });
+
+ it('preserves nonempty overrides, expected output, and nonempty conversation turns', () => {
+ const environment = { agent: { systemRole: 'Be concise' }, timezone: 'UTC' };
+ expect(
+ buildCaseContent({
+ ...draft,
+ category: ' Tools ',
+ environment,
+ expected: 'Expected answer',
+ turns: [
+ { content: 'Earlier request', role: 'user' },
+ { content: ' ', role: 'assistant' },
+ ],
+ }),
+ ).toEqual({
+ category: 'Tools',
+ environment,
+ expected: 'Expected answer',
+ input: 'Task',
+ messages: [{ content: 'Earlier request', role: 'user' }],
+ });
+ });
+
+ it('explicitly clears the category and all previous turns when the draft removes them', () => {
+ expect(buildCaseContent(draft)).toMatchObject({ category: '', messages: [] });
+ });
+
+ it('preserves inline fields that the editor does not expose when saving other case fields', () => {
+ const originalEnvironment: EvalCaseEnvironment = {
+ agent: { memory: { enabled: true }, name: 'Assistant', plugins: [], systemRole: '' },
+ envPrompt: 'Keep this context',
+ memory: { persona: { narrative: 'Keep this fixture' } },
+ toolForwarding: { calendar: { timeoutMs: 5000 } },
+ };
+ expect(buildCaseContent({ ...draft, originalEnvironment }).environment).toEqual(
+ originalEnvironment,
+ );
+ });
+
+ it('clears only editable overrides while retaining the other inline agent and Memory fields', () => {
+ const preserved: EvalCaseEnvironment = {
+ agent: { memory: { enabled: true }, title: 'Assistant' },
+ memory: { persona: { narrative: 'Original fixture' } },
+ };
+ const originalEnvironment = {
+ ...preserved,
+ agent: { ...preserved.agent, plugins: ['calendar'], systemRole: 'Old role' },
+ mock: { services: ['calendar'] },
+ sessionDate: '2026-11-01T12:00:00Z',
+ timezone: 'America/Chicago',
+ };
+ const before = structuredClone(originalEnvironment);
+ expect(buildCaseContent({ ...draft, originalEnvironment }).environment).toEqual(preserved);
+ expect(originalEnvironment).toEqual(before);
+ expect(
+ buildCaseContent({
+ ...draft,
+ originalEnvironment,
+ environment: { agent: { systemRole: 'New role' }, timezone: 'UTC' },
+ }).environment,
+ ).toEqual({
+ ...preserved,
+ agent: { ...preserved.agent, systemRole: 'New role' },
+ timezone: 'UTC',
+ });
+ });
+
+ it.each([false, true])(
+ 'preserves unedited history including hidden roles and tool data (visible=%s)',
+ (visible) => {
+ const originalMessages: ImportedMessage[] = [
+ { content: 'Prior system context', role: 'system' },
+ ...(visible ? [{ content: 'Prior request', id: 'user-1', role: 'user' as const }] : []),
+ { content: 'Tool result', role: 'tool', tool_call_id: 'call-1' },
+ ];
+ const turns = visible ? [{ content: 'Prior request', role: 'user' as const }] : [];
+ expect(buildCaseContent({ ...draft, originalMessages, turns }).messages).toEqual(
+ originalMessages,
+ );
+ },
+ );
+
+ it('clears the entire history when the user removes its visible turns', () => {
+ const originalMessages: ImportedMessage[] = [
+ { content: 'Previous request', role: 'user' },
+ { content: 'Tool result', role: 'tool', tool_call_id: 'call-1' },
+ ];
+ expect(buildCaseContent({ ...draft, originalMessages }).messages).toEqual([]);
+ });
+});
diff --git a/src/features/LobeBench/caseEditorContent.ts b/src/features/LobeBench/caseEditorContent.ts
new file mode 100644
index 00000000000..f090b61296f
--- /dev/null
+++ b/src/features/LobeBench/caseEditorContent.ts
@@ -0,0 +1,67 @@
+import type { EvalCaseEnvironment, ImportedMessage } from '@lobechat/types';
+
+interface CaseContentDraft {
+ category: string;
+ environment: EvalCaseEnvironment;
+ expected?: string;
+ input: string;
+ originalEnvironment?: EvalCaseEnvironment;
+ originalMessages?: ImportedMessage[];
+ turns: Array<{ content: string; role: 'assistant' | 'user' }>;
+}
+
+/** The form edits five fields; the rest of the inline runtime setup stays intact. */
+const mergeCaseEnvironment = (
+ original: EvalCaseEnvironment = {},
+ edited: EvalCaseEnvironment,
+): EvalCaseEnvironment => {
+ const environment = { ...original, ...edited };
+ for (const key of ['sessionDate', 'timezone'] as const) {
+ if (original[key] && !edited[key]) delete environment[key];
+ }
+ if (original.mock?.services.length && !edited.mock) delete environment.mock;
+
+ const agent = { ...original.agent, ...edited.agent };
+ if (original.agent?.systemRole && !edited.agent?.systemRole) delete agent.systemRole;
+ if (original.agent?.plugins?.length && !edited.agent?.plugins) delete agent.plugins;
+ if (Object.keys(agent).length > 0) environment.agent = agent;
+ else if (Object.keys(original.agent ?? {}).length > 0) delete environment.agent;
+
+ return environment;
+};
+
+const messagesAfterEdit = (
+ turns: CaseContentDraft['turns'],
+ original?: ImportedMessage[],
+): ImportedMessage[] => {
+ if (original) {
+ const visible = original.filter(({ role }) => role === 'user' || role === 'assistant');
+ if (
+ visible.length === turns.length &&
+ visible.every(
+ (message, index) =>
+ message.role === turns[index].role && message.content === turns[index].content,
+ )
+ )
+ return original;
+ }
+ return turns.filter((turn) => turn.content.trim());
+};
+
+/** Build the content patch shared by creating and editing a case. */
+export const buildCaseContent = ({
+ category,
+ environment,
+ expected,
+ input,
+ originalEnvironment,
+ originalMessages,
+ turns,
+}: CaseContentDraft) => ({
+ category: category.trim(),
+ // An empty object clears inline overrides; omission would preserve them on update.
+ environment: mergeCaseEnvironment(originalEnvironment, environment),
+ ...(expected && { expected }),
+ input: input.trim(),
+ messages: messagesAfterEdit(turns, originalMessages),
+});
diff --git a/src/features/LobeBench/caseResults.test.ts b/src/features/LobeBench/caseResults.test.ts
new file mode 100644
index 00000000000..d3c9851f7b4
--- /dev/null
+++ b/src/features/LobeBench/caseResults.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+
+import { summarizeCaseResult } from './caseResults';
+
+describe('Judge error result presentation', () => {
+ it('preserves diagnostics without presenting a missing score as zero or a model failure', () => {
+ const result = summarizeCaseResult(
+ {
+ testCaseId: 'case',
+ topicId: 'original-answer',
+ status: 'judge_error',
+ score: null,
+ passed: null,
+ evalResult: {
+ errorPhase: 'judge',
+ judgeError: 'Judge unavailable',
+ error: 'Old execution message',
+ rubricScores: [],
+ },
+ },
+ 1,
+ );
+ expect(result).toMatchObject({
+ verdict: 'judge_error',
+ error: 'Judge unavailable',
+ passCount: 0,
+ });
+ expect(result.score).toBeUndefined();
+ expect(result.threads).toEqual([{ status: 'judge_error' }]);
+ });
+
+ it('uses explicit Judge provenance over stale passed flags and scores', () => {
+ expect(
+ summarizeCaseResult(
+ {
+ testCaseId: 'case',
+ topicId: 'topic',
+ status: 'passed',
+ passed: true,
+ score: 1,
+ evalResult: {
+ errorPhase: 'judge',
+ error: 'Judge unavailable',
+ rubricScores: [{ rubricId: 'r', score: 1 }],
+ },
+ },
+ 1,
+ ),
+ ).toMatchObject({ verdict: 'judge_error', score: undefined, passCount: 0 });
+ });
+
+ it('keeps valid thread passes visible while marking a partially graded case incomplete', () => {
+ const result = summarizeCaseResult(
+ {
+ testCaseId: 'case',
+ topicId: 'topic',
+ status: 'judge_error',
+ score: null,
+ evalResult: {
+ threads: [
+ { threadId: 'a', status: 'passed', passed: true },
+ { threadId: 'b', status: 'judge_error', passed: true, judgeError: 'Judge timeout' },
+ { threadId: 'c', status: 'judge_error', passed: true },
+ ],
+ },
+ },
+ 3,
+ );
+ expect(result.passCount).toBe(1);
+ expect(result.verdict).toBe('judge_error');
+ expect(result.error).toBe('Judge timeout');
+ expect(result.score).toBeUndefined();
+ expect(result.threads.map(({ status }) => status)).toEqual([
+ 'passed',
+ 'judge_error',
+ 'judge_error',
+ ]);
+ });
+
+ it('retains genuine zero-score model failures as failures', () => {
+ expect(
+ summarizeCaseResult(
+ {
+ testCaseId: 'case',
+ topicId: 'topic',
+ status: 'failed',
+ passed: false,
+ score: 0,
+ evalResult: { rubricScores: [{ rubricId: 'r', score: 0, reason: 'Rule violated' }] },
+ },
+ 1,
+ ),
+ ).toMatchObject({ verdict: 'failed', score: 0, reason: 'Rule violated' });
+ });
+});
diff --git a/src/features/LobeBench/caseResults.ts b/src/features/LobeBench/caseResults.ts
new file mode 100644
index 00000000000..36744b8fc3b
--- /dev/null
+++ b/src/features/LobeBench/caseResults.ts
@@ -0,0 +1,102 @@
+import type { AgentEvalRunTopicResult, EvalRuleVerdict, EvalRunTopicResult } from '@lobechat/types';
+
+// ---------- attempts ----------
+
+export type AttemptVerdict =
+ 'error' | 'failed' | 'judge_error' | 'passed' | 'pending' | 'running' | 'timeout';
+
+export interface CaseAttempt {
+ cost?: number;
+ duration?: number;
+ error?: string;
+ passCount: number;
+ reason?: string;
+ score?: number;
+ threads: Array<{ status: AttemptVerdict; threadId?: string }>;
+ toolCalls?: number;
+ total: number;
+ verdict: AttemptVerdict;
+ /** Per-rule verdicts when the case is graded as a rule checklist. */
+ verdicts?: EvalRuleVerdict[];
+}
+
+const asVerdict = (
+ status?: string | null,
+ passed?: boolean | null,
+ errorPhase?: string,
+): AttemptVerdict => {
+ if (errorPhase === 'judge') return 'judge_error';
+ switch (status) {
+ case 'completed': {
+ return typeof passed === 'boolean' ? (passed ? 'passed' : 'failed') : 'pending';
+ }
+ case 'passed':
+ case 'failed':
+ case 'error':
+ case 'judge_error':
+ case 'timeout':
+ case 'running': {
+ return status;
+ }
+ default: {
+ return 'pending';
+ }
+ }
+};
+
+/** One contender's attempt(s) at one case, from the run's per-topic result. */
+export const summarizeCaseResult = (
+ result: AgentEvalRunTopicResult | undefined,
+ k: number,
+): CaseAttempt => {
+ const evalResult = (result?.evalResult ?? undefined) as EvalRunTopicResult | undefined;
+ const threads = evalResult?.threads ?? [];
+ const verdict = threads.some(
+ (thread) => asVerdict(thread.status, thread.passed) === 'judge_error',
+ )
+ ? 'judge_error'
+ : asVerdict(result?.status, result?.passed, evalResult?.errorPhase);
+ if (threads.length > 0) {
+ const passCount = threads.filter(
+ (thread) => asVerdict(thread.status, thread.passed) === 'passed',
+ ).length;
+ const first = threads[0];
+ const judgeFailure = threads.find((thread) => thread.status === 'judge_error');
+ return {
+ cost: evalResult?.totalCost ?? evalResult?.cost,
+ duration: evalResult?.duration,
+ error:
+ evalResult?.judgeError ??
+ judgeFailure?.judgeError ??
+ evalResult?.error ??
+ judgeFailure?.error,
+ passCount,
+ reason: first?.rubricScores?.[0]?.reason ?? evalResult?.rubricScores?.[0]?.reason,
+ score: verdict === 'judge_error' ? undefined : (result?.score ?? undefined),
+ threads: threads.map((thread) => ({
+ status: asVerdict(thread.status, thread.passed),
+ threadId: thread.threadId,
+ })),
+ toolCalls: evalResult?.toolCalls,
+ total: Math.max(k, threads.length),
+ verdict,
+ verdicts: first?.rubricScores?.[0]?.verdicts ?? evalResult?.rubricScores?.[0]?.verdicts,
+ };
+ }
+ return {
+ cost: evalResult?.cost,
+ duration: evalResult?.duration,
+ error: evalResult?.judgeError ?? evalResult?.error,
+ passCount: verdict === 'passed' ? 1 : 0,
+ reason: evalResult?.rubricScores?.[0]?.reason,
+ score: verdict === 'judge_error' ? undefined : (result?.score ?? undefined),
+ threads: [{ status: verdict }],
+ toolCalls: evalResult?.toolCalls,
+ total: k,
+ verdict,
+ verdicts: evalResult?.rubricScores?.[0]?.verdicts,
+ };
+};
+
+export const formatCost = (value?: number, digits = 3) =>
+ value === undefined ? '—' : `$${value.toFixed(digits)}`;
diff --git a/src/features/LobeBench/datasetCases.test.ts b/src/features/LobeBench/datasetCases.test.ts
new file mode 100644
index 00000000000..71f69d1e702
--- /dev/null
+++ b/src/features/LobeBench/datasetCases.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createDataset } from '@/features/LobeBench/datasetCases';
+import type { LobeBenchCase } from '@/features/LobeBench/useLobeBench';
+import { agentEvalService } from '@/services/agentEval';
+
+const refreshLobeBenchDatasets = vi.hoisted(() => vi.fn());
+vi.mock('@/store/eval', () => ({
+ useEvalStore: { getState: () => ({ refreshLobeBenchDatasets }) },
+}));
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: {
+ batchCreateTestCases: vi.fn(),
+ createDataset: vi.fn(),
+ deleteDataset: vi.fn(),
+ updateDataset: vi.fn(),
+ },
+}));
+
+const cases: LobeBenchCase[] = [
+ {
+ content: { input: 'Complete the task', environment: { mergedSharedValue: true } },
+ environment: { id: 'shared-env', name: 'Shared environment' },
+ environmentId: 'shared-env',
+ environmentOverrides: { currentDate: '2026-01-01' },
+ evalConfig: { criteria: ['A rule'], model: 'case-judge' },
+ evalMode: 'rule-checklist',
+ id: 'case-a',
+ metadata: { caseId: 'native-a', title: 'A case' },
+ sortOrder: 4,
+ },
+];
+const library = {
+ evalConfig: { model: 'library-judge' },
+ evalMode: 'rule-checklist',
+ metadata: { mock: { endpoint: '/mock' }, presentation: 'v2', release: 'release-v1' },
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('atomic dataset creation request', () => {
+ it.each([{ id: 'new-set' }, { data: { id: 'new-set' } }])(
+ 'submits the dataset and copied cases once with response %j',
+ async (response) => {
+ vi.mocked(agentEvalService.createDataset).mockResolvedValue(response as never);
+ expect(await createDataset('bench', 'My dataset', library, cases)).toEqual({ id: 'new-set' });
+ expect(agentEvalService.createDataset).toHaveBeenCalledTimes(1);
+ expect(agentEvalService.createDataset).toHaveBeenCalledWith(
+ expect.objectContaining({
+ benchmarkId: 'bench',
+ name: 'My dataset',
+ evalConfig: library.evalConfig,
+ evalMode: library.evalMode,
+ metadata: expect.objectContaining(library.metadata),
+ cases: [
+ {
+ content: { input: 'Complete the task', environment: { currentDate: '2026-01-01' } },
+ environmentId: 'shared-env',
+ evalConfig: cases[0].evalConfig,
+ evalMode: cases[0].evalMode,
+ metadata: { ...cases[0].metadata, source: 'library' },
+ sortOrder: 4,
+ },
+ ],
+ }),
+ );
+ expect(agentEvalService.batchCreateTestCases).not.toHaveBeenCalled();
+ expect(refreshLobeBenchDatasets).toHaveBeenCalledTimes(1);
+ expect(cases[0].content?.environment).toEqual({ mergedSharedValue: true });
+ },
+ );
+
+ it('propagates transaction failure without a second mutation or a success refresh', async () => {
+ const failure = new Error('Case validation rejected the transaction');
+ vi.mocked(agentEvalService.createDataset).mockRejectedValue(failure);
+ await expect(createDataset('bench', 'My dataset', library, cases)).rejects.toBe(failure);
+ expect(agentEvalService.createDataset).toHaveBeenCalledTimes(1);
+ expect(agentEvalService.createDataset).toHaveBeenCalledWith(
+ expect.objectContaining({ cases: expect.any(Array) }),
+ );
+ expect(agentEvalService.batchCreateTestCases).not.toHaveBeenCalled();
+ expect(agentEvalService.deleteDataset).not.toHaveBeenCalled();
+ expect(refreshLobeBenchDatasets).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/LobeBench/datasetCases.ts b/src/features/LobeBench/datasetCases.ts
new file mode 100644
index 00000000000..c3b751a1315
--- /dev/null
+++ b/src/features/LobeBench/datasetCases.ts
@@ -0,0 +1,94 @@
+import type { RubricType } from '@lobechat/types';
+
+import { LOBE_BENCH_KIND } from '@/features/LobeBench/lobeBench';
+import { type LobeBenchCase, ownEnvironmentOf } from '@/features/LobeBench/useLobeBench';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+/** Revalidates every mounted Lobe Bench dataset list (sidebar, pickers, pages). */
+export const refreshLobeBenchDatasets = () => useEvalStore.getState().refreshLobeBenchDatasets();
+
+interface LibraryDataset {
+ evalConfig?: unknown;
+ evalMode?: string | null;
+ metadata?: Record<string, unknown> | null;
+}
+
+/**
+ * The row a library case is copied into a dataset as: its own content (the
+ * shared environment stays referenced, not merged in), rules, judge and ids.
+ * The copy is marked as coming from the library; a dataset's cases are fixed
+ * once it is made.
+ */
+const copyOf = (item: LobeBenchCase) => {
+ const overrides = ownEnvironmentOf(item);
+ const { environment: _merged, ...content } = (item.content ?? {}) as Record<string, unknown>;
+ return {
+ content: {
+ ...content,
+ ...(overrides && Object.keys(overrides).length > 0 && { environment: overrides }),
+ } as { input: string },
+ environmentId: item.environmentId ?? null,
+ ...(item.evalConfig && { evalConfig: item.evalConfig }),
+ ...(item.evalMode && { evalMode: item.evalMode as RubricType }),
+ metadata: { ...item.metadata, source: 'library' },
+ sortOrder: item.sortOrder ?? undefined,
+ };
+};
+
+/**
+ * A new account dataset that holds copies of these library cases, as an
+ * Evaluation Lab dataset holds its cases. It takes the
+ * library's mock, judge and case version, so it runs in any benchmark. Its
+ * cases are fixed from then on, so the runs on it stay true to it.
+ */
+export const createDataset = async (
+ benchmarkId: string,
+ name: string,
+ library: LibraryDataset | undefined,
+ cases: LobeBenchCase[],
+): Promise<{ id: string }> => {
+ const libraryMeta = library?.metadata ?? {};
+ const created = (await agentEvalService.createDataset({
+ benchmarkId,
+ cases: cases.map(copyOf),
+ ...(library?.evalConfig ? { evalConfig: library.evalConfig as never } : {}),
+ ...(library?.evalMode ? { evalMode: library.evalMode as never } : {}),
+ identifier: `dataset-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
+ metadata: {
+ custom: true,
+ kind: LOBE_BENCH_KIND,
+ ...(libraryMeta.mock ? { mock: libraryMeta.mock } : {}),
+ ...(libraryMeta.presentation ? { presentation: libraryMeta.presentation } : {}),
+ ...(libraryMeta.release ? { release: libraryMeta.release } : {}),
+ },
+ name,
+ })) as { id?: string; data?: { id?: string } };
+ const id = created?.id ?? created?.data?.id;
+ if (!id) throw new Error('Dataset was not created');
+ await refreshLobeBenchDatasets();
+ return { id };
+};
+
+/** Renames an account dataset. */
+export const renameDataset = async (
+ dataset: { id: string; metadata?: Record<string, unknown> | null },
+ name: string,
+) => {
+ await agentEvalService.updateDataset({ id: dataset.id, metadata: dataset.metadata ?? {}, name });
+ await refreshLobeBenchDatasets();
+};
+
+/**
+ * Files account datasets under a benchmark: one the account made, or back under
+ * the library's benchmark, where they are in no benchmark of the account's.
+ */
+export const moveDatasets = async (
+ datasets: Array<{ id: string; name: string }>,
+ benchmarkId: string,
+) => {
+ for (const dataset of datasets) {
+ await agentEvalService.updateDataset({ benchmarkId, id: dataset.id, name: dataset.name });
+ }
+ await refreshLobeBenchDatasets();
+};
diff --git a/src/features/LobeBench/experimentBenchmarks.test.ts b/src/features/LobeBench/experimentBenchmarks.test.ts
new file mode 100644
index 00000000000..39baf314100
--- /dev/null
+++ b/src/features/LobeBench/experimentBenchmarks.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+
+import { benchmarkIdsOfDatasets, benchmarkProtocolOf, datasetIdsOfBenchmarks } from './lobeBench';
+
+const benchmarks = [
+ { id: 'evb_hard10', isSystem: false },
+ { id: 'evb_lb50', isSystem: false },
+];
+const datasets = [
+ { benchmarkId: 'evb_hard10', id: 'ds_v2', metadata: { custom: true } },
+ { benchmarkId: 'evb_hard10', id: 'ds_v3', metadata: { custom: true } },
+ { benchmarkId: 'evb_lb50', id: 'ds_lb50', metadata: { custom: true } },
+ // The account's picked cases, filed under no benchmark of its own.
+ { benchmarkId: null, id: 'ds_loose', metadata: { custom: true } },
+];
+
+describe('experiments start on benchmarks only', () => {
+ it('runs every dataset a chosen benchmark is made of', () => {
+ expect(datasetIdsOfBenchmarks(datasets, benchmarks, ['evb_hard10'])).toEqual([
+ 'ds_v2',
+ 'ds_v3',
+ ]);
+ });
+
+ it('never runs a dataset that is in no benchmark', () => {
+ const chosen = benchmarkIdsOfDatasets(datasets, benchmarks, ['ds_loose']);
+ expect(chosen).toEqual([]);
+ expect(datasetIdsOfBenchmarks(datasets, benchmarks, chosen)).toEqual([]);
+ });
+
+ it('turns a preset dataset into its whole benchmark', () => {
+ const chosen = benchmarkIdsOfDatasets(datasets, benchmarks, ['ds_v3', 'ds_loose']);
+ expect(chosen).toEqual(['evb_hard10']);
+ expect(datasetIdsOfBenchmarks(datasets, benchmarks, chosen)).toEqual(['ds_v2', 'ds_v3']);
+ });
+
+ it('ignores an unknown benchmark', () => {
+ expect(datasetIdsOfBenchmarks(datasets, benchmarks, ['evb_gone'])).toEqual([]);
+ });
+});
+
+describe('a benchmark’s fixed run rules', () => {
+ const protocol = { k: 3, maxSteps: 30, timeoutMinutes: 20 };
+
+ it('reads them from the benchmark, or from an older benchmark’s complete defaults', () => {
+ expect(benchmarkProtocolOf({ metadata: { protocol } })).toEqual(protocol);
+ expect(benchmarkProtocolOf({ metadata: { defaults: protocol } })).toEqual(protocol);
+ });
+
+ it('has none when they are missing or incomplete', () => {
+ expect(benchmarkProtocolOf({ metadata: { defaults: { k: 3 } } })).toBeUndefined();
+ expect(benchmarkProtocolOf({ metadata: {} })).toBeUndefined();
+ expect(benchmarkProtocolOf(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/features/LobeBench/experimentDefaults.ts b/src/features/LobeBench/experimentDefaults.ts
new file mode 100644
index 00000000000..be0770e2393
--- /dev/null
+++ b/src/features/LobeBench/experimentDefaults.ts
@@ -0,0 +1,40 @@
+/**
+ * What a new experiment starts with, per person. The built-in benchmark's own
+ * defaults apply to everyone; a person's choices here lay over them and live
+ * in this browser only (a convenience, like a remembered filter).
+ */
+export interface ExperimentDefaults {
+ k?: number;
+ maxSteps?: number;
+ timeoutMinutes?: number;
+}
+
+const storageKey = (benchmarkId: string) => `lobe-bench:experiment-defaults:${benchmarkId}`;
+
+export const readExperimentDefaults = (benchmarkId?: string): ExperimentDefaults | undefined => {
+ if (!benchmarkId) return undefined;
+ try {
+ const raw = globalThis.localStorage?.getItem(storageKey(benchmarkId));
+ if (!raw) return undefined;
+ const parsed = JSON.parse(raw) as ExperimentDefaults;
+ return parsed && typeof parsed === 'object' ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const writeExperimentDefaults = (benchmarkId: string, defaults: ExperimentDefaults) => {
+ try {
+ globalThis.localStorage?.setItem(storageKey(benchmarkId), JSON.stringify(defaults));
+ } catch {
+ /* storage unavailable: the form still works for this visit */
+ }
+};
+
+export const clearExperimentDefaults = (benchmarkId: string) => {
+ try {
+ globalThis.localStorage?.removeItem(storageKey(benchmarkId));
+ } catch {
+ /* nothing stored */
+ }
+};
diff --git a/src/features/LobeBench/experimentDraft.ts b/src/features/LobeBench/experimentDraft.ts
new file mode 100644
index 00000000000..d03ecd3ede3
--- /dev/null
+++ b/src/features/LobeBench/experimentDraft.ts
@@ -0,0 +1,115 @@
+import { type EvalRunChatConfig } from '@lobechat/types';
+import { z } from 'zod';
+
+import { CONTENDER_SETTING_KEYS } from '@/features/LobeBench/lobeBench';
+
+const modelSchema = z.object({ model: z.string().min(1), provider: z.string().min(1) });
+const contenderSchema = modelSchema.extend({
+ // Every setting a contender can carry (each model's own reasoning-effort key
+ // included), so a restored draft runs what its name says; nothing else.
+ chatConfig: z
+ .record(z.string(), z.unknown())
+ .transform(
+ (config) =>
+ Object.fromEntries(
+ CONTENDER_SETTING_KEYS.filter(
+ (key) => config[key] !== undefined && config[key] !== null,
+ ).map((key) => [key, config[key]]),
+ ) as EvalRunChatConfig,
+ )
+ .optional(),
+ id: z.string().min(1),
+ name: z.string(),
+ params: z
+ .object({
+ frequency_penalty: z.number().optional(),
+ presence_penalty: z.number().optional(),
+ temperature: z.number().optional(),
+ top_p: z.number().optional(),
+ })
+ .optional(),
+});
+
+const draftSchema = z.object({
+ contenders: z.array(contenderSchema),
+ datasetId: z.string().optional(),
+ /** Every dataset the experiment will run, one or more; a draft saved before has `datasetId` only. */
+ datasetIds: z.array(z.string()).optional(),
+ judge: modelSchema.optional(),
+ k: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5)]),
+ /** Cases each run executes at once; null or absent (a draft saved before) means no limit. */
+ maxConcurrency: z.number().int().min(1).max(20).nullable().optional(),
+ maxSteps: z.number().int().min(1).max(1000).nullable(),
+ name: z.string(),
+ pickCases: z.boolean(),
+ pickedCaseIds: z.array(z.string()),
+ question: z.string(),
+ timeoutMinutes: z.number().min(1).max(240).nullable(),
+});
+
+export type ExperimentDraft = z.infer<typeof draftSchema>;
+export interface ExperimentDraftScope {
+ benchmarkId: string;
+ userId: string;
+ workspaceId: string | null;
+}
+
+export const experimentDraftKey = ({ benchmarkId, userId, workspaceId }: ExperimentDraftScope) =>
+ `lobe-bench:experiment-draft:v1:${JSON.stringify([userId, workspaceId, benchmarkId])}`;
+
+export const experimentDraftLocationKey = (userId: string, workspaceId: string | null) =>
+ `lobe-bench:experiment-draft-location:v1:${JSON.stringify([userId, workspaceId])}`;
+
+/** Only known form fields are restored; run IDs and arbitrary stored fields are excluded. */
+export const parseExperimentDraft = (raw: string | null): ExperimentDraft | undefined => {
+ if (!raw) return;
+ try {
+ const parsed = draftSchema.safeParse(JSON.parse(raw));
+ return parsed.success ? parsed.data : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/** The datasets a draft runs: its list, or the one dataset a draft saved before names. */
+export const draftDatasetIds = (draft: Pick<ExperimentDraft, 'datasetId' | 'datasetIds'>) =>
+ draft.datasetIds ?? (draft.datasetId ? [draft.datasetId] : []);
+
+/** An explicit case-set entry takes precedence without reusing another set's picked cases. */
+export const applyPresetDataset = (
+ draft: ExperimentDraft,
+ datasetId?: string | null,
+): ExperimentDraft =>
+ datasetId && (datasetId !== draft.datasetId || draftDatasetIds(draft).join() !== datasetId)
+ ? { ...draft, datasetId, datasetIds: [datasetId], pickedCaseIds: [] }
+ : draft;
+
+export interface AvailableDraftModel {
+ model: string;
+ provider: string;
+ supportsTools: boolean;
+}
+
+export const getInvalidDraftSelections = (
+ draft: ExperimentDraft,
+ availableCaseIds: string[],
+ availableModels: AvailableDraftModel[],
+) => ({
+ caseIds: draft.pickCases
+ ? draft.pickedCaseIds.filter((id) => !availableCaseIds.includes(id))
+ : [],
+ contenders: draft.contenders.filter(
+ (contender) =>
+ !availableModels.some(
+ (model) =>
+ model.model === contender.model &&
+ model.provider === contender.provider &&
+ model.supportsTools,
+ ),
+ ),
+ judge:
+ !!draft.judge &&
+ !availableModels.some(
+ (model) => model.model === draft.judge?.model && model.provider === draft.judge?.provider,
+ ),
+});
diff --git a/src/features/LobeBench/experimentLaunch.test.ts b/src/features/LobeBench/experimentLaunch.test.ts
new file mode 100644
index 00000000000..5b2b4163eb1
--- /dev/null
+++ b/src/features/LobeBench/experimentLaunch.test.ts
@@ -0,0 +1,650 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ beginLaunchInStorage,
+ clearLaunchInStorage,
+ createExperimentLaunch,
+ experimentLaunchKey,
+ isAcceptedRunStatus,
+ isResumableLaunch,
+ isStartableRunStatus,
+ LAUNCH_LEASE_MS,
+ launchExperiment,
+ type LaunchProgress,
+ launchResumeLockName,
+ type LaunchServices,
+ type LaunchStorage,
+ parseExperimentLaunch,
+ runExclusiveLaunch,
+} from './experimentLaunch';
+
+const snapshot = () => ({
+ benchmarkId: 'evb_1',
+ contenders: [
+ { config: { k: 1, model: 'model-a', provider: 'p' }, id: 'c-a', name: 'A' },
+ { config: { k: 1, model: 'model-b', provider: 'p' }, id: 'c-b', name: 'B' },
+ ],
+ datasetId: 'ds_1',
+ metadata: {
+ contenders: [
+ { id: 'c-a', model: 'model-a', name: 'A', provider: 'p' },
+ { id: 'c-b', model: 'model-b', name: 'B', provider: 'p' },
+ ],
+ datasetId: 'ds_1',
+ k: 1,
+ kind: 'lobe-bench',
+ },
+ name: 'A vs B',
+});
+
+/** An in-memory server: idempotent creates on caller ids, runs start once. */
+const fakeServer = (before?: (method: keyof LaunchServices) => Promise<void>) => {
+ const runs = new Map<string, { id: string; status: string }>();
+ const services: LaunchServices = {
+ createExperiment: vi.fn(async ({ id }) => {
+ await before?.('createExperiment');
+ return { data: { id } };
+ }),
+ createRun: vi.fn(async ({ id }) => {
+ await before?.('createRun');
+ if (!runs.has(id)) runs.set(id, { id, status: 'idle' });
+ return runs.get(id);
+ }),
+ listRuns: vi.fn(async () => {
+ await before?.('listRuns');
+ return [...runs.values()];
+ }),
+ startRun: vi.fn(async (id) => {
+ await before?.('startRun');
+ runs.get(id)!.status = 'pending';
+ return { success: true };
+ }),
+ updateExperiment: vi.fn(async () => {
+ await before?.('updateExperiment');
+ return { success: true };
+ }),
+ };
+ return { runs, services };
+};
+
+const memoryStorage = (): LaunchStorage & { map: Map<string, string> } => {
+ const map = new Map<string, string>();
+ return {
+ getItem: (key) => map.get(key) ?? null,
+ map,
+ removeItem: (key) => void map.delete(key),
+ setItem: (key, value) => void map.set(key, value),
+ };
+};
+
+describe('launch progress', () => {
+ it.each([
+ ['createExperiment', 'experiment', 0],
+ ['listRuns', 'check', 1],
+ ['createRun', 'run', 2],
+ ['updateExperiment', 'metadata', 4],
+ ['startRun', 'start', 5],
+ ] as const)(
+ 'does not advance while %s is awaiting acknowledgement',
+ async (method, stage, completedSteps) => {
+ const launch = createExperimentLaunch(snapshot());
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let gated = false;
+ const { services } = fakeServer(async (called) => {
+ if (called !== method || gated) return;
+ gated = true;
+ await gate;
+ });
+ const events: LaunchProgress[] = [];
+ const task = launchExperiment(launch, services, (event) => events.push(event));
+ await vi.waitFor(() =>
+ expect(events.at(-1)).toMatchObject({
+ completedSteps,
+ stage,
+ status: 'working',
+ totalSteps: 7,
+ }),
+ );
+ const pending = events.at(-1);
+ await Promise.resolve();
+ expect(events.at(-1)).toBe(pending);
+ if (stage === 'run' || stage === 'start') {
+ expect(pending).toMatchObject({
+ contender: launch.contenders[0],
+ contenderIndex: 1,
+ contenderCount: 2,
+ });
+ }
+ release();
+ expect((await task).complete).toBe(true);
+ expect(events.at(-1)).toMatchObject({
+ completedSteps: 7,
+ stage: 'complete',
+ status: 'complete',
+ });
+ },
+ );
+
+ it('keeps the last confirmed progress and partial launch on a later start failure', async () => {
+ const launch = createExperimentLaunch(snapshot());
+ const { services } = fakeServer();
+ vi.mocked(services.startRun)
+ .mockResolvedValueOnce({ success: true })
+ .mockRejectedValueOnce(new Error('connection unavailable'));
+ const events: LaunchProgress[] = [];
+ const result = await launchExperiment(launch, services, (event) => events.push(event));
+ expect(result.started).toEqual([launch.contenders[0]]);
+ expect(result.error).toMatchObject({ contender: launch.contenders[1], stage: 'start' });
+ expect(events.at(-1)).toMatchObject({
+ completedSteps: 6,
+ contenderIndex: 2,
+ stage: 'start',
+ status: 'failed',
+ totalSteps: 7,
+ });
+ expect(events.some((event) => event.completedSteps === 7)).toBe(false);
+ });
+
+ it('does not report completion or submit again when a previous dispatch is unconfirmed', async () => {
+ const launch = createExperimentLaunch(snapshot());
+ const { runs, services } = fakeServer();
+ runs.set(launch.contenders[0].runId, { id: launch.contenders[0].runId, status: 'pending' });
+ const events: LaunchProgress[] = [];
+ const result = await launchExperiment(launch, services, (event) => events.push(event));
+ expect(result.complete).toBe(false);
+ expect(result.unconfirmed).toEqual([launch.contenders[0]]);
+ expect(services.startRun).toHaveBeenCalledTimes(1);
+ expect(events.at(-1)).toMatchObject({
+ completedSteps: 6,
+ status: 'unconfirmed',
+ totalSteps: 7,
+ });
+ });
+});
+
+describe('createExperimentLaunch', () => {
+ it('freezes the case set, name, metadata and each run config under stable server-shaped ids', () => {
+ const launch = createExperimentLaunch(snapshot());
+ expect(launch.version).toBe(2);
+ expect(launch.experimentId).toMatch(/^exp_[\dA-Za-z]{12}$/);
+ expect(launch).toMatchObject({ benchmarkId: 'evb_1', datasetId: 'ds_1', name: 'A vs B' });
+ expect(launch.contenders.map((c) => [c.key, c.config.model])).toEqual([
+ ['c-a', 'model-a'],
+ ['c-b', 'model-b'],
+ ]);
+ for (const c of launch.contenders) expect(c.runId).toMatch(/^run_[\dA-Za-z]{12}$/);
+ expect(new Set(launch.contenders.map((c) => c.runId)).size).toBe(2);
+ });
+
+ it('round-trips through storage and rejects anything else', () => {
+ const launch = createExperimentLaunch(snapshot());
+ expect(parseExperimentLaunch(JSON.stringify(launch))).toEqual(launch);
+ expect(parseExperimentLaunch('{"experimentId":"x"}')).toBeUndefined();
+ expect(parseExperimentLaunch('not json')).toBeUndefined();
+ expect(parseExperimentLaunch(null)).toBeUndefined();
+ });
+
+ it('reads a first-version record as legacy: visible, not resumable', () => {
+ const legacy = {
+ contenders: [{ key: 'c-a', name: 'A', runId: 'run_old' }],
+ createdAt: '2026-10-29T00:00:00.000Z',
+ experimentId: 'exp_old',
+ };
+ const parsed = parseExperimentLaunch(JSON.stringify(legacy));
+ expect(parsed).toEqual({ ...legacy, version: 1 });
+ expect(isResumableLaunch(parsed!)).toBe(false);
+ expect(isResumableLaunch(createExperimentLaunch(snapshot()))).toBe(true);
+ });
+
+ it('scopes the record to user, workspace and benchmark', () => {
+ const a = experimentLaunchKey({ benchmarkId: 'b', userId: 'u1', workspaceId: null });
+ const b = experimentLaunchKey({ benchmarkId: 'b', userId: 'u2', workspaceId: null });
+ const c = experimentLaunchKey({ benchmarkId: 'b', userId: 'u1', workspaceId: 'ws' });
+ expect(new Set([a, b, c]).size).toBe(3);
+ });
+});
+
+describe('run states', () => {
+ it('starts only an idle run and trusts only dispatched or finished states', () => {
+ expect(isStartableRunStatus('idle')).toBe(true);
+ for (const status of ['running', 'completed', 'failed', 'aborted', 'external'])
+ expect(isAcceptedRunStatus(status)).toBe(true);
+ // Pending is neither: it may or may not have been dispatched.
+ expect(isStartableRunStatus('pending')).toBe(false);
+ expect(isAcceptedRunStatus('pending')).toBe(false);
+ expect(isAcceptedRunStatus(undefined)).toBe(false);
+ expect(isAcceptedRunStatus('idle')).toBe(false);
+ });
+});
+
+describe('storage compare-before-write', () => {
+ const key = experimentLaunchKey({ benchmarkId: 'b', userId: 'u', workspaceId: null });
+
+ it('writes into an empty scope and again for the same experiment', () => {
+ const storage = memoryStorage();
+ const launch = createExperimentLaunch(snapshot());
+ expect(beginLaunchInStorage(storage, key, launch)).toEqual({ ok: true });
+ expect(beginLaunchInStorage(storage, key, launch)).toEqual({ ok: true });
+ expect(parseExperimentLaunch(storage.getItem(key))).toEqual(launch);
+ });
+
+ it("refuses to overwrite another tab's launch and hands it back", () => {
+ const storage = memoryStorage();
+ const theirs = createExperimentLaunch(snapshot());
+ storage.setItem(key, JSON.stringify(theirs));
+ const mine = createExperimentLaunch(snapshot());
+ expect(beginLaunchInStorage(storage, key, mine)).toEqual({
+ existing: theirs,
+ ok: false,
+ reason: 'occupied',
+ });
+ expect(parseExperimentLaunch(storage.getItem(key))).toEqual(theirs);
+ });
+
+ it('reports a storage failure instead of pretending to checkpoint', () => {
+ const storage = memoryStorage();
+ storage.setItem = () => {
+ throw new Error('QuotaExceededError');
+ };
+ expect(beginLaunchInStorage(storage, key, createExperimentLaunch(snapshot()))).toEqual({
+ ok: false,
+ reason: 'storage',
+ });
+ });
+
+ it('clears only the experiment it was asked to clear', () => {
+ const storage = memoryStorage();
+ const theirs = createExperimentLaunch(snapshot());
+ storage.setItem(key, JSON.stringify(theirs));
+ expect(clearLaunchInStorage(storage, key, 'exp_somethingElse')).toBe(false);
+ expect(storage.getItem(key)).not.toBeNull();
+ expect(clearLaunchInStorage(storage, key, theirs.experimentId)).toBe(true);
+ expect(storage.getItem(key)).toBeNull();
+ expect(clearLaunchInStorage(storage, key, theirs.experimentId)).toBe(true);
+ });
+});
+
+describe('launchExperiment', () => {
+ it('creates the experiment and runs, saves the run ids, then starts every idle run once', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+
+ const outcome = await launchExperiment(launch, services);
+
+ expect(outcome.complete).toBe(true);
+ expect(outcome.started.map((c) => c.key)).toEqual(['c-a', 'c-b']);
+ expect([...runs.values()].map((r) => r.status)).toEqual(['pending', 'pending']);
+ expect(services.createExperiment).toHaveBeenCalledWith({
+ benchmarkIds: ['evb_1'],
+ id: launch.experimentId,
+ metadata: launch.metadata,
+ name: 'A vs B',
+ });
+ expect(services.createRun).toHaveBeenCalledWith({
+ config: { k: 1, model: 'model-a', provider: 'p' },
+ datasetId: 'ds_1',
+ experimentId: launch.experimentId,
+ id: launch.contenders[0].runId,
+ name: 'A',
+ });
+ expect(services.updateExperiment).toHaveBeenCalledWith({
+ id: launch.experimentId,
+ metadata: expect.objectContaining({
+ contenders: [
+ expect.objectContaining({ id: 'c-a', runId: launch.contenders[0].runId }),
+ expect.objectContaining({ id: 'c-b', runId: launch.contenders[1].runId }),
+ ],
+ }),
+ });
+ // Run ids are saved before any start, so a start failure never leaves an
+ // experiment that does not know its runs.
+ const order = [
+ ...vi.mocked(services.updateExperiment).mock.invocationCallOrder,
+ ...vi.mocked(services.startRun).mock.invocationCallOrder,
+ ];
+ expect(order).toEqual([...order].sort((a, b) => a - b));
+ });
+
+ it('covers several benchmarks: one run per contender and dataset, each part told its runs', async () => {
+ const { services } = fakeServer();
+ const library = { caseSelection: { caseIds: ['h1', 'h2'], mode: 'include' } };
+ const launch = createExperimentLaunch({
+ ...snapshot(),
+ benchmarkIds: ['evb_1', 'evb_hard'],
+ contenders: [
+ { config: { model: 'model-a' }, datasetId: 'ds_1', id: 'c-a', name: 'A', part: 0 },
+ { config: { model: 'model-b' }, datasetId: 'ds_1', id: 'c-b', name: 'B', part: 0 },
+ {
+ config: { ...library, model: 'model-a' },
+ datasetId: 'ds_1',
+ id: 'c-a',
+ name: 'A',
+ part: 1,
+ },
+ {
+ config: { ...library, model: 'model-b' },
+ datasetId: 'ds_1',
+ id: 'c-b',
+ name: 'B',
+ part: 1,
+ },
+ ],
+ metadata: {
+ ...snapshot().metadata,
+ parts: [
+ { datasetId: 'ds_1' },
+ { caseIds: ['h1', 'h2'], datasetId: 'ds_1', pickedDatasetId: 'ds_hard' },
+ ],
+ },
+ });
+
+ const outcome = await launchExperiment(launch, services);
+
+ expect(outcome.complete).toBe(true);
+ expect(outcome.started).toHaveLength(4);
+ expect(vi.mocked(services.createExperiment).mock.calls[0][0].benchmarkIds).toEqual([
+ 'evb_1',
+ 'evb_hard',
+ ]);
+ const [a0, b0, a1, b1] = launch.contenders.map((c) => c.runId);
+ expect(vi.mocked(services.updateExperiment).mock.calls[0][0].metadata).toMatchObject({
+ // The first dataset's runs stay on the contenders, as for an experiment of one dataset.
+ contenders: [
+ { id: 'c-a', runId: a0 },
+ { id: 'c-b', runId: b0 },
+ ],
+ parts: [
+ { datasetId: 'ds_1', runIds: { 'c-a': a0, 'c-b': b0 } },
+ { pickedDatasetId: 'ds_hard', runIds: { 'c-a': a1, 'c-b': b1 } },
+ ],
+ });
+ });
+
+ it('sends the frozen snapshot, whatever happened to the draft since', async () => {
+ const { services } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ // The draft changed after the launch began: a different model, name and case set.
+ const driftedDraft = { ...snapshot(), datasetId: 'ds_other', name: 'renamed' };
+ void driftedDraft;
+
+ await launchExperiment(launch, services);
+
+ for (const call of vi.mocked(services.createRun).mock.calls) {
+ expect(call[0].datasetId).toBe('ds_1');
+ expect(['model-a', 'model-b']).toContain(call[0].config.model);
+ }
+ expect(vi.mocked(services.createExperiment).mock.calls[0][0].name).toBe('A vs B');
+ });
+
+ it('A started, B failed: resuming starts B only and never touches A again', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ vi.mocked(services.startRun).mockImplementationOnce(async (id) => {
+ runs.get(id)!.status = 'running';
+ return { success: true };
+ });
+ vi.mocked(services.startRun).mockImplementationOnce(async () => {
+ throw new Error('network down');
+ });
+
+ const first = await launchExperiment(launch, services);
+ expect(first.complete).toBe(false);
+ expect(first.error).toEqual({
+ contender: launch.contenders[1],
+ message: 'network down',
+ stage: 'start',
+ });
+ expect(first.started.map((c) => c.key)).toEqual(['c-a']);
+
+ const second = await launchExperiment(launch, services);
+ expect(second.complete).toBe(true);
+ expect(second.kept.map((c) => c.key)).toEqual(['c-a']);
+ expect(second.started.map((c) => c.key)).toEqual(['c-b']);
+ expect(runs.size).toBe(2);
+ expect(services.createRun).toHaveBeenCalledTimes(2);
+ expect(
+ vi.mocked(services.startRun).mock.calls.filter(([id]) => id === launch.contenders[0].runId),
+ ).toHaveLength(1);
+ });
+
+ it('a lost create response is retried with the same id, so the server sees one run', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ const realCreate = vi.mocked(services.createRun).getMockImplementation()!;
+ vi.mocked(services.createRun).mockImplementationOnce(async (params) => {
+ await realCreate(params); // the server committed the row…
+ throw new Error('socket closed'); // …but the response never arrived
+ });
+
+ const first = await launchExperiment(launch, services);
+ expect(first.error?.stage).toBe('run');
+ expect(runs.size).toBe(1);
+ expect(services.startRun).not.toHaveBeenCalled();
+
+ const second = await launchExperiment(launch, services);
+ expect(second.complete).toBe(true);
+ expect(runs.size).toBe(2);
+ expect(vi.mocked(services.createRun).mock.calls.map(([p]) => p.id)).toEqual([
+ launch.contenders[0].runId,
+ launch.contenders[1].runId,
+ ]);
+ });
+
+ it('never restarts a run that is running or finished', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ runs.set(launch.contenders[0].runId, { id: launch.contenders[0].runId, status: 'completed' });
+ runs.set(launch.contenders[1].runId, { id: launch.contenders[1].runId, status: 'running' });
+
+ const outcome = await launchExperiment(launch, services);
+
+ expect(outcome.complete).toBe(true);
+ expect(outcome.kept.map((c) => c.key)).toEqual(['c-a', 'c-b']);
+ expect(services.createRun).not.toHaveBeenCalled();
+ expect(services.startRun).not.toHaveBeenCalled();
+ expect(runs.get(launch.contenders[0].runId)!.status).toBe('completed');
+ });
+
+ it('a pending run is unconfirmed: not complete, not started again, resolved on re-check', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ runs.set(launch.contenders[0].runId, { id: launch.contenders[0].runId, status: 'pending' });
+
+ const first = await launchExperiment(launch, services);
+ expect(first.complete).toBe(false);
+ expect(first.error).toBeUndefined();
+ expect(first.unconfirmed.map((c) => c.key)).toEqual(['c-a']);
+ expect(first.started.map((c) => c.key)).toEqual(['c-b']);
+ expect(
+ vi.mocked(services.startRun).mock.calls.some(([id]) => id === launch.contenders[0].runId),
+ ).toBe(false);
+
+ // The server moved both on (the one it had, and the one this attempt
+ // started): the re-check accepts them without another start.
+ runs.get(launch.contenders[0].runId)!.status = 'running';
+ runs.get(launch.contenders[1].runId)!.status = 'running';
+ const second = await launchExperiment(launch, services);
+ expect(second.complete).toBe(true);
+ expect(second.kept.map((c) => c.key).sort()).toEqual(['c-a', 'c-b']);
+ expect(services.startRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('a run this attempt started earlier but still pending stays unconfirmed on re-check', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+
+ const first = await launchExperiment(launch, services);
+ expect(first.complete).toBe(true);
+ expect([...runs.values()].map((r) => r.status)).toEqual(['pending', 'pending']);
+
+ // Dispatch has not moved them past pending: the launch cannot tell a slow
+ // dispatch from a lost one, so it waits instead of starting again.
+ const second = await launchExperiment(launch, services);
+ expect(second.complete).toBe(false);
+ expect(second.unconfirmed).toHaveLength(2);
+ expect(services.startRun).toHaveBeenCalledTimes(2);
+ });
+
+ it('a create that answers without a status is unconfirmed too', async () => {
+ const { services } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ vi.mocked(services.createRun).mockResolvedValue({ success: true });
+
+ const outcome = await launchExperiment(launch, services);
+
+ expect(outcome.complete).toBe(false);
+ expect(outcome.unconfirmed).toHaveLength(2);
+ expect(services.startRun).not.toHaveBeenCalled();
+ });
+
+ it('stops before any start when the run ids cannot be saved, and finishes on resume', async () => {
+ const { services } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ vi.mocked(services.updateExperiment).mockRejectedValueOnce(new Error('offline'));
+
+ const first = await launchExperiment(launch, services);
+ expect(first).toMatchObject({
+ complete: false,
+ error: { message: 'offline', stage: 'metadata' },
+ metadataSaved: false,
+ });
+ expect(services.startRun).not.toHaveBeenCalled();
+
+ const second = await launchExperiment(launch, services);
+ expect(second.complete).toBe(true);
+ expect(second.started).toHaveLength(2);
+ expect(services.createRun).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops before any run when the experiment cannot be created', async () => {
+ const { services } = fakeServer();
+ vi.mocked(services.createExperiment).mockRejectedValueOnce(new Error('403'));
+
+ const outcome = await launchExperiment(createExperimentLaunch(snapshot()), services);
+
+ expect(outcome).toMatchObject({
+ complete: false,
+ error: { message: '403', stage: 'experiment' },
+ });
+ expect(services.createRun).not.toHaveBeenCalled();
+ expect(services.startRun).not.toHaveBeenCalled();
+ });
+});
+
+describe('runExclusiveLaunch', () => {
+ /**
+ * A Web Locks stand-in with the real `ifAvailable` contract: the callback is
+ * always invoked, with the Lock when granted and with `null` when another
+ * holder has it. A helper that ignores its argument would run anyway.
+ */
+ const fakeLocks = () => {
+ const held = new Set<string>();
+ return {
+ request: async <T>(
+ name: string,
+ _options: { ifAvailable: true },
+ callback: (lock: Lock | null) => Promise<T>,
+ ): Promise<T> => {
+ if (held.has(name)) return callback(null);
+ held.add(name);
+ try {
+ return await callback({ mode: 'exclusive', name } as Lock);
+ } finally {
+ held.delete(name);
+ }
+ },
+ };
+ };
+ const defer = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+ };
+
+ it('two tabs continuing the same launch: one resumes, the other is told it is busy, runs start once', async () => {
+ const { services, runs } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ const locks = fakeLocks();
+ const gate = defer();
+ // Tab A reads the runs, then stalls before starting: the window the bug lived in.
+ vi.mocked(services.listRuns).mockImplementationOnce(async () => {
+ await gate.promise;
+ return [...runs.values()];
+ });
+ const name = launchResumeLockName('scope', launch.experimentId);
+ const options = { leaseKey: name, lockName: name, locks };
+
+ const tabA = runExclusiveLaunch(options, () => launchExperiment(launch, services));
+ const tabB = await runExclusiveLaunch(options, () => launchExperiment(launch, services));
+ expect(tabB).toEqual({ ran: false, reason: 'busy' });
+
+ gate.resolve();
+ const resultA = await tabA;
+ expect(resultA.ran).toBe(true);
+ expect(services.startRun).toHaveBeenCalledTimes(2);
+ expect([...runs.values()].map((r) => r.status)).toEqual(['pending', 'pending']);
+ });
+
+ it('does not run the task when the lock manager hands the callback null', async () => {
+ const task = vi.fn(async () => 'ran');
+ const locks = {
+ request: async <T>(
+ _name: string,
+ _options: { ifAvailable: true },
+ callback: (lock: Lock | null) => Promise<T>,
+ ) => callback(null),
+ };
+ const name = 'scope:resume:exp_1';
+
+ expect(await runExclusiveLaunch({ leaseKey: name, lockName: name, locks }, task)).toEqual({
+ ran: false,
+ reason: 'busy',
+ });
+ expect(task).not.toHaveBeenCalled();
+ });
+
+ it('releases the lock after the resume, so a later re-check can run', async () => {
+ const { services } = fakeServer();
+ const launch = createExperimentLaunch(snapshot());
+ const locks = fakeLocks();
+ const name = launchResumeLockName('scope', launch.experimentId);
+ const options = { leaseKey: name, lockName: name, locks };
+
+ await runExclusiveLaunch(options, () => launchExperiment(launch, services));
+ const again = await runExclusiveLaunch(options, () => launchExperiment(launch, services));
+ expect(again.ran).toBe(true);
+ });
+
+ it('without Web Locks a storage lease keeps a second resume out while the first is in flight', async () => {
+ const storage = memoryStorage();
+ const name = 'scope:resume:exp_1';
+ const gate = defer();
+ let clock = 1_000;
+ const options = { leaseKey: name, lockName: name, now: () => clock, storage };
+
+ const first = runExclusiveLaunch(options, async () => {
+ await gate.promise;
+ return 'done';
+ });
+ expect(await runExclusiveLaunch(options, async () => 'second')).toEqual({
+ ran: false,
+ reason: 'busy',
+ });
+ gate.resolve();
+ expect(await first).toEqual({ ran: true, result: 'done' });
+ expect(storage.getItem(name)).toBeNull();
+
+ // An abandoned lease (tab closed mid-resume) expires instead of blocking forever.
+ storage.setItem(name, String(clock));
+ clock += LAUNCH_LEASE_MS + 1;
+ expect(await runExclusiveLaunch(options, async () => 'later')).toEqual({
+ ran: true,
+ result: 'later',
+ });
+ });
+});
diff --git a/src/features/LobeBench/experimentLaunch.ts b/src/features/LobeBench/experimentLaunch.ts
new file mode 100644
index 00000000000..3414e2ace5b
--- /dev/null
+++ b/src/features/LobeBench/experimentLaunch.ts
@@ -0,0 +1,511 @@
+import { createNanoId } from '@lobechat/utils';
+import { z } from 'zod';
+
+/**
+ * Launching a Lobe Bench experiment is several server calls: create the
+ * experiment, then for every contender create a run and start it, then save
+ * the run ids into the experiment. Any of them can fail or lose its response.
+ *
+ * The launch record below is written once, before the first call, and freezes
+ * everything the launch needs: every id, the case set, the name, the
+ * experiment metadata and each contender's full run config. The server creates
+ * idempotently on those ids, so running the same record again after a failure
+ * reaches the same experiment and the same runs with the same parameters,
+ * whatever the draft looks like by then. Nothing is created twice; a run is
+ * started only while the server still reports it `idle`.
+ */
+
+const runConfigSchema = z.record(z.string(), z.unknown());
+
+const launchContenderSchema = z.object({
+ /** The run config this contender was launched with; a resume sends exactly this. */
+ config: runConfigSchema,
+ /** The dataset this run is on, when the experiment covers several (else the launch's). */
+ datasetId: z.string().min(1).optional(),
+ /** The draft contender this run belongs to (`LobeBenchContender.id`). */
+ key: z.string().min(1),
+ name: z.string(),
+ /** Which of the experiment's `metadata.parts` this run is, when it has several. */
+ part: z.number().int().min(0).optional(),
+ runId: z.string().min(1),
+});
+
+const launchSchema = z.object({
+ /** Where the record is kept (one launch at a time per benchmark). */
+ benchmarkId: z.string().min(1),
+ /** Every benchmark the experiment covers (experiments and benchmarks are n to n); else `benchmarkId`. */
+ benchmarkIds: z.array(z.string().min(1)).min(1).optional(),
+ contenders: z.array(launchContenderSchema).min(1),
+ createdAt: z.string(),
+ datasetId: z.string().min(1),
+ experimentId: z.string().min(1),
+ /** The experiment metadata as launched, without run ids (added once every run exists). */
+ metadata: z.record(z.string(), z.unknown()),
+ name: z.string(),
+ version: z.literal(2),
+});
+
+/** The first record shape: ids only. It can be opened or discarded, never resumed. */
+const legacyLaunchSchema = z.object({
+ contenders: z.array(z.object({ key: z.string(), name: z.string(), runId: z.string() })).min(1),
+ createdAt: z.string(),
+ experimentId: z.string().min(1),
+ version: z.undefined().optional(),
+});
+
+export type ExperimentLaunch = z.infer<typeof launchSchema>;
+export type ExperimentLaunchContender = z.infer<typeof launchContenderSchema>;
+export interface LegacyExperimentLaunch {
+ contenders: Array<{ key: string; name: string; runId: string }>;
+ createdAt: string;
+ experimentId: string;
+ version: 1;
+}
+export type StoredExperimentLaunch = ExperimentLaunch | LegacyExperimentLaunch;
+
+export const isResumableLaunch = (launch: StoredExperimentLaunch): launch is ExperimentLaunch =>
+ launch.version === 2;
+
+export interface ExperimentLaunchScope {
+ benchmarkId: string;
+ userId: string;
+ workspaceId: string | null;
+}
+
+/**
+ * One record per user, workspace and benchmark. The key is unchanged from the
+ * first version on purpose: an older record under it is read as legacy instead
+ * of being silently left behind under another key.
+ */
+export const experimentLaunchKey = ({ benchmarkId, userId, workspaceId }: ExperimentLaunchScope) =>
+ `lobe-bench:experiment-launch:v1:${JSON.stringify([userId, workspaceId, benchmarkId])}`;
+
+export const parseExperimentLaunch = (raw: string | null): StoredExperimentLaunch | undefined => {
+ if (!raw) return;
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+ const current = launchSchema.safeParse(value);
+ if (current.success) return current.data;
+ const legacy = legacyLaunchSchema.safeParse(value);
+ if (legacy.success) {
+ const { version: _version, ...rest } = legacy.data;
+ return { ...rest, version: 1 };
+ }
+ return undefined;
+};
+
+// Same shape as the server's ids (`exp_` / `run_` + 12 alphanumerics), so a
+// client-made id reads like any other in logs and URLs.
+const ID_SIZE = 12;
+const makeId = (prefix: string) => `${prefix}_${createNanoId(ID_SIZE)()}`;
+
+/**
+ * A fresh launch record: one experiment id, one run id per contender (per contender
+ * and dataset, when the experiment covers several), every parameter frozen.
+ */
+export const createExperimentLaunch = (
+ snapshot: {
+ benchmarkId: string;
+ benchmarkIds?: string[];
+ contenders: Array<{
+ config: Record<string, unknown>;
+ datasetId?: string;
+ id: string;
+ name: string;
+ part?: number;
+ }>;
+ datasetId: string;
+ metadata: Record<string, unknown>;
+ name: string;
+ },
+ now = new Date(),
+): ExperimentLaunch => ({
+ benchmarkId: snapshot.benchmarkId,
+ ...(snapshot.benchmarkIds?.length && { benchmarkIds: snapshot.benchmarkIds }),
+ contenders: snapshot.contenders.map((contender) => ({
+ config: contender.config,
+ ...(contender.datasetId && { datasetId: contender.datasetId }),
+ key: contender.id,
+ name: contender.name,
+ ...(contender.part !== undefined && { part: contender.part }),
+ runId: makeId('run'),
+ })),
+ createdAt: now.toISOString(),
+ datasetId: snapshot.datasetId,
+ experimentId: makeId('exp'),
+ metadata: snapshot.metadata,
+ name: snapshot.name,
+ version: 2,
+});
+
+// ---- Run states as the launch reads them ------------------------------------
+
+/** Waiting for its first start. */
+export const isStartableRunStatus = (status: string | null | undefined) => status === 'idle';
+
+/**
+ * Accepted by the server: dispatched and past `pending`, or finished. A
+ * `pending` run is not in this set: the server marks a run pending *before*
+ * dispatching its workflow and does not roll back a failed dispatch, so from
+ * the outside pending cannot be told apart from "never dispatched". Starting
+ * it again could dispatch twice, so a resume leaves it alone and reports it
+ * as unconfirmed; only this attempt's own `startRun` acknowledgement counts.
+ */
+export const ACCEPTED_RUN_STATUSES = new Set([
+ 'running',
+ 'completed',
+ 'failed',
+ 'aborted',
+ 'external',
+]);
+export const isAcceptedRunStatus = (status: string | null | undefined) =>
+ !!status && ACCEPTED_RUN_STATUSES.has(status);
+
+// ---- Storage: compare-before-write so two tabs cannot clobber each other ------
+
+export interface LaunchStorage {
+ getItem: (key: string) => string | null;
+ removeItem: (key: string) => void;
+ setItem: (key: string, value: string) => void;
+}
+
+export type BeginResult =
+ | { ok: true }
+ | { ok: false; reason: 'storage' }
+ | { existing: StoredExperimentLaunch; ok: false; reason: 'occupied' };
+
+/**
+ * Write a new record unless the scope already holds a different launch. Not
+ * atomic across tabs (localStorage has no transactions); the caller narrows the
+ * window with a Web Lock when the browser has one.
+ */
+export const beginLaunchInStorage = (
+ storage: LaunchStorage,
+ key: string,
+ launch: ExperimentLaunch,
+): BeginResult => {
+ let existing: StoredExperimentLaunch | undefined;
+ try {
+ existing = parseExperimentLaunch(storage.getItem(key));
+ } catch {
+ return { ok: false, reason: 'storage' };
+ }
+ if (existing && existing.experimentId !== launch.experimentId) {
+ return { existing, ok: false, reason: 'occupied' };
+ }
+ try {
+ storage.setItem(key, JSON.stringify(launch));
+ } catch {
+ return { ok: false, reason: 'storage' };
+ }
+ return { ok: true };
+};
+
+/** Remove the record only when it still is the launch the caller finished with. */
+export const clearLaunchInStorage = (
+ storage: LaunchStorage,
+ key: string,
+ experimentId: string,
+): boolean => {
+ try {
+ const existing = parseExperimentLaunch(storage.getItem(key));
+ if (!existing) return true;
+ if (existing.experimentId !== experimentId) return false;
+ storage.removeItem(key);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+// ---- The launch itself ----------------------------------------------------------
+
+export interface LaunchServices {
+ createExperiment: (params: {
+ benchmarkIds: string[];
+ id: string;
+ metadata: Record<string, unknown>;
+ name: string;
+ }) => Promise<unknown>;
+ createRun: (params: {
+ config: Record<string, unknown>;
+ datasetId: string;
+ experimentId: string;
+ id: string;
+ name: string;
+ }) => Promise<unknown>;
+ listRuns: (experimentId: string) => Promise<Array<{ id: string; status?: string | null }>>;
+ startRun: (runId: string) => Promise<unknown>;
+ updateExperiment: (params: { id: string; metadata: Record<string, unknown> }) => Promise<unknown>;
+}
+
+export type LaunchStage = 'experiment' | 'metadata' | 'run' | 'start';
+
+/** Acknowledged launch steps, not case execution or individual connection checks. */
+export interface LaunchProgress {
+ completedSteps: number;
+ contender?: ExperimentLaunchContender;
+ contenderCount: number;
+ contenderIndex?: number;
+ stage: LaunchStage | 'check' | 'complete';
+ status: 'working' | 'failed' | 'unconfirmed' | 'complete';
+ totalSteps: number;
+}
+
+export interface LaunchOutcome {
+ /** Every run is accepted and the experiment holds the run ids. */
+ complete: boolean;
+ error?: { contender?: ExperimentLaunchContender; message: string; stage: LaunchStage };
+ experimentId: string;
+ /** Accepted before this attempt (running, finished …): left untouched. */
+ kept: ExperimentLaunchContender[];
+ metadataSaved: boolean;
+ /** Started by this attempt: the server acknowledged `startRun`. */
+ started: ExperimentLaunchContender[];
+ /**
+ * Reported `pending` or in a state the launch does not know: possibly
+ * dispatched, possibly not. Not started again; the user re-checks later.
+ */
+ unconfirmed: ExperimentLaunchContender[];
+}
+
+const messageOf = (error: unknown) =>
+ error instanceof Error && error.message ? error.message : String(error);
+
+const statusOf = (created: unknown): string | null | undefined => {
+ if (!created || typeof created !== 'object') return undefined;
+ const direct = (created as { status?: string | null }).status;
+ if (direct !== undefined) return direct;
+ return (created as { data?: { status?: string | null } }).data?.status;
+};
+
+/**
+ * Run (or resume) a launch record. Reads nothing but the record: the resume of
+ * a launch sends what the launch froze. Order: experiment, then every run row,
+ * then the run ids into the experiment, then the starts. So no run is started
+ * before the experiment knows it, and a failed step stops the attempt where
+ * it is; the next attempt begins by reading what the server already has.
+ */
+export const launchExperiment = async (
+ launch: ExperimentLaunch,
+ services: LaunchServices,
+ onProgress?: (progress: LaunchProgress) => void,
+): Promise<LaunchOutcome> => {
+ const outcome: LaunchOutcome = {
+ complete: false,
+ experimentId: launch.experimentId,
+ kept: [],
+ metadataSaved: false,
+ started: [],
+ unconfirmed: [],
+ };
+ let progress: LaunchProgress = {
+ completedSteps: 0,
+ contenderCount: launch.contenders.length,
+ stage: 'experiment',
+ status: 'working',
+ // Experiment, existing run check, metadata, then prepare and submit each run.
+ totalSteps: 3 + launch.contenders.length * 2,
+ };
+ const report = (update: Partial<LaunchProgress>) => {
+ progress = { ...progress, ...update };
+ onProgress?.(progress);
+ };
+ const acknowledged = () => report({ completedSteps: progress.completedSteps + 1 });
+ const failed = () => {
+ report({ status: 'failed' });
+ return outcome;
+ };
+
+ report({});
+ try {
+ await services.createExperiment({
+ benchmarkIds: launch.benchmarkIds ?? [launch.benchmarkId],
+ id: launch.experimentId,
+ metadata: launch.metadata,
+ name: launch.name,
+ });
+ acknowledged();
+ } catch (error) {
+ outcome.error = { message: messageOf(error), stage: 'experiment' };
+ return failed();
+ }
+
+ const status = new Map<string, string | null | undefined>();
+ report({ stage: 'check' });
+ try {
+ for (const run of await services.listRuns(launch.experimentId)) status.set(run.id, run.status);
+ acknowledged();
+ } catch (error) {
+ outcome.error = { message: messageOf(error), stage: 'run' };
+ return failed();
+ }
+
+ for (const [index, contender] of launch.contenders.entries()) {
+ report({ contender, contenderIndex: index + 1, stage: 'run' });
+ if (status.has(contender.runId)) {
+ acknowledged();
+ continue;
+ }
+ try {
+ const created = await services.createRun({
+ config: contender.config,
+ datasetId: contender.datasetId ?? launch.datasetId,
+ experimentId: launch.experimentId,
+ id: contender.runId,
+ name: contender.name,
+ });
+ status.set(contender.runId, statusOf(created));
+ acknowledged();
+ } catch (error) {
+ outcome.error = { contender, message: messageOf(error), stage: 'run' };
+ return failed();
+ }
+ }
+
+ // Each contender's run on the first dataset stays on the contender (what an
+ // experiment of one dataset always had); every dataset's runs go on its part.
+ const runIdsOfPart = (part: number) =>
+ new Map(launch.contenders.filter((c) => (c.part ?? 0) === part).map((c) => [c.key, c.runId]));
+ const runIdByKey = runIdsOfPart(0);
+ const contenders = Array.isArray(launch.metadata.contenders)
+ ? (launch.metadata.contenders as Array<{ id?: string }>)
+ : [];
+ const parts = Array.isArray(launch.metadata.parts)
+ ? (launch.metadata.parts as Array<Record<string, unknown>>)
+ : undefined;
+ report({ contender: undefined, contenderIndex: undefined, stage: 'metadata' });
+ try {
+ await services.updateExperiment({
+ id: launch.experimentId,
+ metadata: {
+ ...launch.metadata,
+ contenders: contenders.map((contender) => ({
+ ...contender,
+ runId: contender.id ? runIdByKey.get(contender.id) : undefined,
+ })),
+ ...(parts && {
+ parts: parts.map((part, index) => ({
+ ...part,
+ runIds: Object.fromEntries(runIdsOfPart(index)),
+ })),
+ }),
+ },
+ });
+ outcome.metadataSaved = true;
+ acknowledged();
+ } catch (error) {
+ outcome.error = { message: messageOf(error), stage: 'metadata' };
+ return failed();
+ }
+
+ for (const [index, contender] of launch.contenders.entries()) {
+ report({ contender, contenderIndex: index + 1, stage: 'start' });
+ const current = status.get(contender.runId);
+ if (isAcceptedRunStatus(current)) {
+ outcome.kept.push(contender);
+ acknowledged();
+ continue;
+ }
+ if (!isStartableRunStatus(current)) {
+ outcome.unconfirmed.push(contender);
+ continue;
+ }
+ try {
+ await services.startRun(contender.runId);
+ outcome.started.push(contender);
+ acknowledged();
+ } catch (error) {
+ outcome.error = { contender, message: messageOf(error), stage: 'start' };
+ return failed();
+ }
+ }
+
+ outcome.complete = outcome.unconfirmed.length === 0;
+ report({
+ contender: undefined,
+ contenderIndex: undefined,
+ stage: outcome.complete ? 'complete' : 'start',
+ status: outcome.complete ? 'complete' : 'unconfirmed',
+ });
+ return outcome;
+};
+
+// ---- One resume at a time per launch ----------------------------------------------
+
+/**
+ * The subset of the Web Locks API the launch uses: a non-queuing request. A
+ * lock that is not free yields `null` instead of waiting, so a second tab that
+ * clicks Continue is told the launch is busy and never queues a second round
+ * of starts behind the first.
+ */
+export interface LaunchLockManager {
+ request: <T>(
+ name: string,
+ options: { ifAvailable: true },
+ callback: (lock: Lock | null) => Promise<T>,
+ ) => Promise<T>;
+}
+
+/** Name of the lock a launch resume holds; distinct from the record's scope lock, so the two never nest. */
+export const launchResumeLockName = (scopeKey: string, experimentId: string) =>
+ `${scopeKey}:resume:${experimentId}`;
+
+/** How long a storage lease (the fallback without Web Locks) counts as held. */
+export const LAUNCH_LEASE_MS = 2 * 60_000;
+
+export type ExclusiveResult<T> = { ran: true; result: T } | { ran: false; reason: 'busy' };
+
+/**
+ * Run `task` only if no other tab is resuming the same launch right now.
+ *
+ * With Web Locks the exclusion holds across tabs. Without them a lease in
+ * storage (compare-before-write, expiring after `LAUNCH_LEASE_MS`) narrows the
+ * window; it is not atomic, so on such browsers two tabs can still both get
+ * through, and the launch then relies on re-reading server state.
+ */
+export const runExclusiveLaunch = async <T>(
+ options: {
+ leaseKey: string;
+ locks?: LaunchLockManager | null;
+ lockName: string;
+ now?: () => number;
+ storage?: LaunchStorage;
+ },
+ task: () => Promise<T>,
+): Promise<ExclusiveResult<T>> => {
+ const { leaseKey, lockName, locks, storage } = options;
+ if (locks) {
+ // With `ifAvailable`, a lock someone else holds still invokes the callback,
+ // with `null` instead of a Lock; the task runs only on a granted lock.
+ const held = await locks.request(lockName, { ifAvailable: true }, async (lock) =>
+ lock ? { result: await task() } : null,
+ );
+ return held ? { ran: true, result: held.result } : { ran: false, reason: 'busy' };
+ }
+ const now = options.now ?? Date.now;
+ if (storage) {
+ try {
+ const lease = Number(storage.getItem(leaseKey));
+ if (Number.isFinite(lease) && lease > 0 && now() - lease < LAUNCH_LEASE_MS) {
+ return { ran: false, reason: 'busy' };
+ }
+ storage.setItem(leaseKey, String(now()));
+ } catch {
+ // No lease possible: run anyway; the server state read inside the task is the last guard.
+ }
+ }
+ try {
+ return { ran: true, result: await task() };
+ } finally {
+ try {
+ storage?.removeItem(leaseKey);
+ } catch {
+ // The lease expires on its own.
+ }
+ }
+};
diff --git a/src/features/LobeBench/experimentNavigation.test.ts b/src/features/LobeBench/experimentNavigation.test.ts
new file mode 100644
index 00000000000..897a7fa2cd1
--- /dev/null
+++ b/src/features/LobeBench/experimentNavigation.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ benchmarkDatasetPath,
+ benchmarkHomePath,
+ benchmarkSidebarBackPath,
+ experimentContextSuffix,
+ newExperimentPath,
+ parseExperimentId,
+ runBackPath,
+} from './experimentNavigation';
+
+describe('experiment case navigation', () => {
+ it('keeps a generated experiment id in the previous/next case context', () => {
+ const id = parseExperimentId('exp_aB09_-cdEF12');
+ expect(id).toBe('exp_aB09_-cdEF12');
+ expect(experimentContextSuffix(id)).toBe('?experiment=exp_aB09_-cdEF12');
+ });
+
+ it.each(['custom-experiment_42', 'exp_', 'A1'])(
+ 'preserves a safe caller-supplied id %s',
+ (value) => {
+ expect(parseExperimentId(value)).toBe(value);
+ expect(new URLSearchParams(experimentContextSuffix(value)).get('experiment')).toBe(value);
+ },
+ );
+
+ it('encodes query metacharacters when building a case link', () => {
+ const suffix = experimentContextSuffix('custom&tab=setup');
+ expect(new URLSearchParams(suffix).get('experiment')).toBe('custom&tab=setup');
+ expect(new URLSearchParams(suffix).has('tab')).toBe(false);
+ });
+
+ it.each([
+ null,
+ '',
+ ' ',
+ 'https://external.example',
+ '//external.example',
+ '../../../../settings',
+ 'exp_../settings',
+ 'exp_value&tab=setup',
+ 'exp_value?other=1',
+ 'exp_value#anchor',
+ 'exp_value/another',
+ 'exp_value\\another',
+ 'exp_%2e%2e',
+ ])('drops invalid experiment context %j', (value) => {
+ const id = parseExperimentId(value);
+ expect(id).toBeUndefined();
+ expect(experimentContextSuffix(id)).toBe('');
+ });
+});
+
+describe('back navigation from the Lab run page', () => {
+ it('returns a Lobe Bench run to the experiment it was started from', () => {
+ expect(runBackPath({ benchmarkId: 'evb_1', experimentId: 'exp_9', lobeBench: true })).toBe(
+ '/eval/lobe-bench/experiments/exp_9',
+ );
+ });
+
+ it('returns a Lobe Bench run without an experiment to its Lobe Bench benchmark', () => {
+ expect(runBackPath({ benchmarkId: 'evb_1', experimentId: null, lobeBench: true })).toBe(
+ '/eval/lobe-bench/benchmarks/evb_1',
+ );
+ expect(runBackPath({ benchmarkId: 'evb_1', experimentId: '../x', lobeBench: true })).toBe(
+ '/eval/lobe-bench/benchmarks/evb_1',
+ );
+ });
+
+ it('keeps an Evaluation Lab run in the Lab, even when it has an experiment', () => {
+ expect(runBackPath({ benchmarkId: 'b1', experimentId: 'exp_9', lobeBench: false })).toBe(
+ '/eval/bench/b1',
+ );
+ });
+
+ it('points the sidebar back arrow and benchmark name at the same side', () => {
+ expect(benchmarkSidebarBackPath('evb_1', true)).toBe('/eval/lobe-bench/benchmarks/evb_1');
+ expect(benchmarkSidebarBackPath('b1', false)).toBe('/eval');
+ expect(benchmarkHomePath('evb_1', true)).toBe('/eval/lobe-bench/benchmarks/evb_1');
+ expect(benchmarkHomePath('b1', false)).toBe('/eval/bench/b1');
+ });
+
+ it("opens a benchmark sidebar's dataset on the benchmark's own side", () => {
+ expect(benchmarkDatasetPath('ds_1', true)).toBe('/eval/lobe-bench/datasets/ds_1');
+ expect(benchmarkDatasetPath('ds_1', false)).toBe('/eval/datasets/ds_1');
+ });
+});
+
+describe('newExperimentPath', () => {
+ it('opens the new experiment page on the named dataset', () => {
+ expect(newExperimentPath('ds_ZEmC8pJFtXVs')).toBe(
+ '/eval/lobe-bench/experiments/new?dataset=ds_ZEmC8pJFtXVs',
+ );
+ });
+
+ it('encodes the id and opens the plain page without one', () => {
+ expect(newExperimentPath('a&b')).toBe('/eval/lobe-bench/experiments/new?dataset=a%26b');
+ expect(newExperimentPath(undefined)).toBe('/eval/lobe-bench/experiments/new');
+ expect(newExperimentPath(null)).toBe('/eval/lobe-bench/experiments/new');
+ });
+});
diff --git a/src/features/LobeBench/experimentNavigation.ts b/src/features/LobeBench/experimentNavigation.ts
new file mode 100644
index 00000000000..14814135633
--- /dev/null
+++ b/src/features/LobeBench/experimentNavigation.ts
@@ -0,0 +1,53 @@
+/** Accept generated and caller-supplied opaque ids without path/query syntax. */
+export const parseExperimentId = (value: string | null): string | undefined =>
+ value && /^[\w-]+$/.test(value) ? value : undefined;
+
+export const experimentContextSuffix = (experimentId: string | undefined): string =>
+ experimentId ? `?${new URLSearchParams({ experiment: experimentId })}` : '';
+
+const LOBE_BENCH_ROOT = '/eval/lobe-bench';
+
+/**
+ * Where the Evaluation Lab's run page leads back to. Lobe Bench opens its runs
+ * on that page too, so a Lobe Bench run returns to Lobe Bench: the experiment
+ * it was started from, else its benchmark.
+ */
+export const runBackPath = ({
+ benchmarkId,
+ experimentId,
+ lobeBench,
+}: {
+ benchmarkId: string;
+ experimentId?: string | null;
+ lobeBench: boolean;
+}): string => {
+ if (!lobeBench) return `/eval/bench/${benchmarkId}`;
+ const experiment = parseExperimentId(experimentId ?? null);
+ return experiment
+ ? `${LOBE_BENCH_ROOT}/experiments/${experiment}`
+ : `${LOBE_BENCH_ROOT}/benchmarks/${benchmarkId}`;
+};
+
+/** The benchmark page on its own side: Lobe Bench's, or the Evaluation Lab's. */
+export const benchmarkHomePath = (benchmarkId: string, lobeBench: boolean): string =>
+ lobeBench ? `${LOBE_BENCH_ROOT}/benchmarks/${benchmarkId}` : `/eval/bench/${benchmarkId}`;
+
+/** Where the benchmark sidebar's back arrow leads: Lobe Bench's benchmark page, or the Lab's home. */
+export const benchmarkSidebarBackPath = (benchmarkId: string, lobeBench: boolean): string =>
+ lobeBench ? benchmarkHomePath(benchmarkId, true) : '/eval';
+
+/**
+ * Where a benchmark sidebar's dataset opens: a Lobe Bench dataset in Lobe Bench,
+ * any other at its benchmark-free Lab address (not the legacy one that redirects there).
+ */
+export const benchmarkDatasetPath = (datasetId: string, lobeBench: boolean): string =>
+ lobeBench ? `${LOBE_BENCH_ROOT}/datasets/${datasetId}` : `/eval/datasets/${datasetId}`;
+
+/**
+ * Lobe Bench's one place to start an experiment, opened on a dataset's
+ * benchmark when one is named. Every "new run / new experiment" button for a
+ * Lobe Bench benchmark leads here, including those on the Evaluation Lab pages
+ * its runs open in, so an experiment always starts the same way.
+ */
+export const newExperimentPath = (datasetId?: string | null): string =>
+ `${LOBE_BENCH_ROOT}/experiments/new${datasetId ? `?${new URLSearchParams({ dataset: datasetId })}` : ''}`;
diff --git a/src/features/LobeBench/experimentResults.test.ts b/src/features/LobeBench/experimentResults.test.ts
new file mode 100644
index 00000000000..6b5bd1f5fdc
--- /dev/null
+++ b/src/features/LobeBench/experimentResults.test.ts
@@ -0,0 +1,534 @@
+import type { EvalThreadResult } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ attemptGradeState,
+ createExperimentResultsCsv,
+ defaultExperimentCaseFilter,
+ experimentGradingCoverage,
+ experimentGradingGaps,
+ experimentPassProgress,
+ experimentResultCoverage,
+ experimentResultsState,
+ experimentRunStats,
+ isUnavailableExperimentResult,
+ lowestPassRateCategory,
+ orderExperimentContenders,
+ scopeExperimentCases,
+ unverifiedCaseCount,
+} from './experimentResults';
+
+describe('experiment results', () => {
+ const pass = (threadId: string) => ({
+ threadId,
+ status: 'passed' as const,
+ passed: true,
+ rubricScores: [{ rubricId: 'judge', score: 1 }],
+ });
+ const topic = (id: string, threads: EvalThreadResult[]) => ({
+ testCaseId: id,
+ topicId: id,
+ status: 'passed',
+ passed: true,
+ evalResult: { threads },
+ });
+
+ it('retains confirmed all-attempt passes while provider errors make the run incomplete', () => {
+ const results = [
+ topic('all', [pass('a1'), pass('a2'), pass('a3')]),
+ {
+ ...topic('mixed', [pass('b1'), pass('b2')]),
+ status: 'error',
+ evalResult: {
+ threads: [
+ pass('b1'),
+ pass('b2'),
+ { threadId: 'b3', status: 'error' as const, error: '429' },
+ ],
+ },
+ },
+ topic('still-running', [pass('c1')]),
+ ];
+ expect(experimentPassProgress(results, 3, 4)).toEqual({
+ allPassed: 1,
+ anyPassed: 3,
+ complete: false,
+ errors: 1,
+ evaluated: 1,
+ hasVerdicts: true,
+ pending: 2,
+ });
+ });
+
+ it('distinguishes missing grades from a genuine zero and preserves completed scores', () => {
+ expect(experimentPassProgress(undefined, 3, 1)).toBeUndefined();
+ expect(experimentPassProgress([], 3, 1)).toMatchObject({
+ complete: false,
+ hasVerdicts: false,
+ pending: 1,
+ });
+ const failed = [pass('a1'), pass('a2'), pass('a3')].map((t) => ({
+ ...t,
+ passed: false,
+ status: 'failed' as const,
+ }));
+ expect(experimentPassProgress([topic('a', failed)], 3, 1)).toMatchObject({
+ allPassed: 0,
+ anyPassed: 0,
+ complete: true,
+ evaluated: 1,
+ hasVerdicts: true,
+ });
+ expect(
+ experimentPassProgress([topic('a', [pass('a1'), pass('a2'), pass('a3')])], 3, 1),
+ ).toMatchObject({
+ allPassed: 1,
+ anyPassed: 1,
+ complete: true,
+ });
+ });
+
+ it('requires all expected distinct judged attempts, not a passing case status', () => {
+ for (const threads of [
+ [pass('a1'), pass('a2')],
+ [pass('a1'), pass('a1'), pass('a1')],
+ [pass('a1'), pass('a2'), { ...pass('a3'), passed: undefined }],
+ [pass('a1'), pass('a2'), { threadId: 'a3', status: 'external' as const }],
+ ]) {
+ expect(
+ experimentPassProgress([{ ...topic('a', []), evalResult: { threads } }], 3, 1),
+ ).toMatchObject({
+ allPassed: 0,
+ complete: false,
+ evaluated: 0,
+ pending: 1,
+ });
+ }
+ });
+
+ it('keeps Judge errors and timeouts out of passes even if a stale boolean says passed', () => {
+ for (const status of ['judge_error', 'timeout', 'error'] as const) {
+ const result = topic('a', [pass('a1'), pass('a2'), { ...pass('a3'), status }]);
+ expect(experimentPassProgress([result], 3, 1)).toMatchObject({
+ allPassed: 0,
+ anyPassed: 1,
+ complete: false,
+ errors: 1,
+ pending: 0,
+ });
+ }
+ });
+
+ it('does not turn duplicated case rows into complete coverage', () => {
+ const result = topic('a', [pass('a1'), pass('a2'), pass('a3')]);
+ expect(experimentPassProgress([result, result], 3, 2)).toMatchObject({ complete: false });
+ });
+
+ it('supports single-attempt results and explicit external verdicts', () => {
+ const single = {
+ testCaseId: 'a',
+ topicId: 'a',
+ status: 'passed',
+ passed: true,
+ evalResult: { rubricScores: [{ rubricId: 'judge', score: 1 }] },
+ };
+ expect(experimentPassProgress([single], 1, 1)).toMatchObject({ allPassed: 1, complete: true });
+ const external = {
+ ...topic('a', []),
+ evalResult: { threads: [{ threadId: 'a1', status: 'completed' as const, passed: true }] },
+ };
+ expect(experimentPassProgress([external], 1, 1)).toMatchObject({
+ allPassed: 1,
+ complete: true,
+ });
+ });
+
+ it('uses the same complete verdict counts for insights and the table when historical metrics are missing', () => {
+ const stats = experimentRunStats(
+ { config: { k: 3 }, metrics: { totalCases: 1 }, status: 'completed' } as Parameters<
+ typeof experimentRunStats
+ >[0],
+ [topic('a', [pass('a1'), pass('a2'), pass('a3')])],
+ );
+ expect(stats.progress).toMatchObject({ allPassed: 1, anyPassed: 1, complete: true });
+ expect(stats.passed).toBe(stats.progress?.allPassed);
+ expect(stats.anyK).toBe(stats.progress?.anyPassed);
+ });
+
+ it('preserves genuine zero for completed step-limit failures without treating an unknown grade as zero', () => {
+ const result = topic(
+ 'a',
+ [1, 2, 3].map((i) => ({
+ threadId: `a${i}`,
+ status: 'failed',
+ passed: false,
+ error: 'Step cap reached',
+ })),
+ );
+ expect(experimentPassProgress([result], 3, 1)).toMatchObject({
+ complete: true,
+ allPassed: 0,
+ hasVerdicts: true,
+ });
+ expect(
+ experimentPassProgress(
+ [{ ...topic('a', []), evalResult: { threads: [{ ...pass('a1'), passed: undefined }] } }],
+ 3,
+ 1,
+ ),
+ ).toMatchObject({ complete: false, hasVerdicts: false });
+ });
+
+ const cases = [
+ { id: 'db-a', metadata: { caseId: 'native-a' } },
+ { id: 'db-b', metadata: { caseId: 'native-b' } },
+ { id: 'custom' },
+ ];
+
+ it('shows all cases by default when there is no second model to disagree with', () => {
+ expect(defaultExperimentCaseFilter(0)).toBe('all');
+ expect(defaultExperimentCaseFilter(1)).toBe('all');
+ expect(defaultExperimentCaseFilter(2)).toBe('diff');
+ });
+
+ it('keeps declared order until every contender has complete results', () => {
+ const contenders = [
+ { id: 'unfinished', passed: 0 },
+ { id: 'complete', passed: 3 },
+ ];
+ expect(orderExperimentContenders(contenders, (item) => item.passed, true)).toEqual(contenders);
+ expect(
+ orderExperimentContenders(contenders, (item) => item.passed, false).map((item) => item.id),
+ ).toEqual(['complete', 'unfinished']);
+ expect(contenders[0].id).toBe('unfinished');
+ });
+
+ it('uses only the native IDs selected for the experiment for all downstream views', () => {
+ expect(scopeExperimentCases(cases, ['native-b']).cases).toEqual([cases[1]]);
+ expect(scopeExperimentCases(cases, ['db-b']).cases).toEqual([]);
+ expect(scopeExperimentCases(cases, ['custom']).cases).toEqual([cases[2]]);
+ });
+
+ it('preserves full-set behavior and distinguishes missing selections from filter emptiness', () => {
+ expect(scopeExperimentCases(cases).cases).toBe(cases);
+ expect(scopeExperimentCases(cases, []).cases).toBe(cases);
+ expect(scopeExperimentCases(cases, ['native-b', 'deleted', 'deleted'])).toEqual({
+ cases: [cases[1]],
+ missingCount: 1,
+ selectedCount: 2,
+ });
+ });
+
+ it('reports the 293/284 history gap without replacing the saved denominator', () => {
+ const results = Array.from({ length: 284 }, (_, index) => ({ testCaseId: `${index}` }));
+ expect(experimentResultCoverage(293, results)).toEqual({
+ available: 284,
+ expected: 293,
+ missing: 9,
+ });
+ expect(experimentResultCoverage(293, undefined)).toBeUndefined();
+ });
+
+ it('does not count duplicate rows as recovered evidence or produce negative gaps', () => {
+ expect(experimentResultCoverage(2, [{ testCaseId: 'a' }, { testCaseId: 'a' }])?.missing).toBe(
+ 1,
+ );
+ expect(experimentResultCoverage(0, [{ testCaseId: 'a' }])?.missing).toBe(0);
+ });
+
+ it('distinguishes missing terminal-run evidence from pending execution or loading', () => {
+ expect(isUnavailableExperimentResult('completed', [], 'a')).toBe(true);
+ expect(isUnavailableExperimentResult('aborted', [], 'a')).toBe(true);
+ expect(isUnavailableExperimentResult('running', [], 'a')).toBe(false);
+ expect(isUnavailableExperimentResult('completed', undefined, 'a')).toBe(false);
+ expect(isUnavailableExperimentResult('completed', [{ testCaseId: 'a' }], 'a')).toBe(false);
+ });
+
+ it('does not render absent or failed resources as ready zero-score results', () => {
+ expect(experimentResultsState([{ loaded: true }, { loaded: false }])).toBe('loading');
+ expect(experimentResultsState([{ loaded: false, error: new Error('offline') }])).toBe('error');
+ expect(experimentResultsState([{ loaded: true, error: new Error('refresh failed') }])).toBe(
+ 'ready',
+ );
+ expect(experimentResultsState([{ loaded: true }])).toBe('ready');
+ });
+
+ it('does not label a fully passing category as a weak spot', () => {
+ expect(lowestPassRateCategory([{ rate: undefined }, { rate: 1 }])).toBeUndefined();
+ expect(
+ lowestPassRateCategory([
+ { name: 'a', rate: 0.5 },
+ { name: 'b', rate: 0 },
+ ]),
+ ).toEqual({
+ name: 'b',
+ rate: 0,
+ });
+ });
+
+ it('keeps a completed run with an ungraded row visibly incomplete', () => {
+ const results = [{ testCaseId: 'a', topicId: 'topic', status: 'running' }];
+ expect(experimentResultCoverage(1, results)?.missing).toBe(0);
+ expect(
+ experimentGradingGaps(
+ [{ id: 'c', name: 'Model', runId: 'run' }],
+ [{ id: 'run', status: 'completed' }],
+ { run: results },
+ ),
+ ).toEqual([{ id: 'c', name: 'Model', ungraded: 1, awaitingExternal: 0, judgeError: 0 }]);
+ expect(
+ experimentGradingGaps(
+ [{ id: 'c', name: 'Model', runId: 'run' }],
+ [{ id: 'run', status: 'running' }],
+ { run: results },
+ ),
+ ).toEqual([]);
+ });
+
+ it('separates step-cap no-answer and execution errors from unfinished grading', () => {
+ expect(
+ attemptGradeState({ status: 'failed', error: 'Step cap reached', rubricScores: [] }),
+ ).toBe('noAnswer');
+ expect(attemptGradeState({ status: 'error', error: 'Provider unavailable' })).toBe('error');
+ expect(attemptGradeState({ status: 'timeout' })).toBe('error');
+ expect(attemptGradeState({ status: 'failed' })).toBe('ungraded');
+ expect(attemptGradeState({ status: 'passed', rubricScores: [{}] })).toBe('graded');
+ expect(attemptGradeState({ status: null })).toBe('ungraded');
+ });
+
+ it('offers Rerun for legacy empty replies while retaining step-limit model failures', () => {
+ const noOutput = {
+ error: 'No assistant output',
+ passed: false,
+ rubricScores: [],
+ status: 'failed' as const,
+ };
+ const stepCap = {
+ error: 'Reached the step limit (20) without a final answer',
+ passed: false,
+ rubricScores: [],
+ status: 'failed' as const,
+ };
+ expect(attemptGradeState(noOutput)).toBe('error');
+ expect(attemptGradeState(stepCap)).toBe('noAnswer');
+ const legacySingle = {
+ testCaseId: 'single',
+ topicId: 'single-topic',
+ status: 'failed',
+ evalResult: noOutput,
+ };
+ const legacyMixed = {
+ testCaseId: 'mixed',
+ topicId: 'mixed-topic',
+ status: 'passed',
+ evalResult: {
+ threads: [
+ {
+ threadId: 'passed',
+ status: 'passed' as const,
+ passed: true,
+ rubricScores: [{ rubricId: 'judge', score: 1 }],
+ },
+ { threadId: 'empty', ...noOutput },
+ ],
+ },
+ };
+ const modelFailure = {
+ testCaseId: 'step-cap',
+ topicId: 'cap-topic',
+ status: 'failed',
+ evalResult: stepCap,
+ };
+ expect(unverifiedCaseCount([legacySingle, legacyMixed, modelFailure])).toBe(2);
+ expect(experimentGradingCoverage([legacySingle, legacyMixed, modelFailure])).toMatchObject({
+ error: 2,
+ graded: 1,
+ noAnswer: 1,
+ ungraded: 0,
+ });
+ });
+
+ it('counts external completed threads as graded only with an explicit pass/fail boolean', () => {
+ expect(
+ experimentGradingCoverage([
+ {
+ testCaseId: 'a',
+ topicId: 'topic',
+ status: 'passed',
+ evalResult: {
+ threads: [
+ { threadId: 't1', status: 'completed', passed: true },
+ { threadId: 't2', status: 'completed', passed: false },
+ { threadId: 't3', status: 'completed' },
+ { threadId: 't4', status: 'external' },
+ { threadId: 't5', status: 'error' },
+ { threadId: 't6', status: 'failed', error: 'Step cap reached' },
+ ],
+ },
+ },
+ ]),
+ ).toEqual({
+ graded: 2,
+ ungraded: 1,
+ awaitingExternal: 1,
+ error: 1,
+ noAnswer: 1,
+ judgeError: 0,
+ });
+ expect(attemptGradeState({ awaitingExternalEval: true, status: 'running' })).toBe(
+ 'awaitingExternal',
+ );
+ });
+
+ it('counts the cases a rerun would run again: no verdict on the case or on any attempt', () => {
+ const graded = {
+ testCaseId: 'case',
+ topicId: 'topic',
+ status: 'passed',
+ evalResult: { rubricScores: [{ rubricId: 'judge', score: 1 }] },
+ };
+ expect(unverifiedCaseCount(undefined)).toBe(0);
+ expect(unverifiedCaseCount([graded, { ...graded, status: 'failed' }])).toBe(0);
+ expect(
+ unverifiedCaseCount([
+ { ...graded, status: 'error' },
+ { ...graded, status: 'timeout' },
+ { ...graded, status: 'judge_error' },
+ ]),
+ ).toBe(3);
+ // k > 1: one blocked attempt inside a passed case still needs the rerun.
+ expect(
+ unverifiedCaseCount([
+ {
+ ...graded,
+ evalResult: {
+ threads: [
+ { threadId: '1', status: 'passed' },
+ { threadId: '2', status: 'error', error: 'Provider blocked the response' },
+ ],
+ },
+ },
+ ]),
+ ).toBe(1);
+ expect(
+ unverifiedCaseCount([
+ {
+ ...graded,
+ evalResult: {
+ threads: [
+ { threadId: '1', status: 'passed' },
+ { threadId: '2', status: 'failed' },
+ ],
+ },
+ },
+ ]),
+ ).toBe(0);
+ });
+ it('keeps Judge failures separate from execution errors and graded samples', () => {
+ expect(attemptGradeState({ status: 'judge_error', rubricScores: [{}] })).toBe('judgeError');
+ expect(attemptGradeState({ status: 'passed', errorPhase: 'judge', rubricScores: [{}] })).toBe(
+ 'judgeError',
+ );
+ const topic = {
+ testCaseId: 'a',
+ topicId: 'topic',
+ status: 'judge_error',
+ evalResult: { errorPhase: 'judge' as const, error: 'Judge unavailable', rubricScores: [] },
+ };
+ // A judge failure is no verdict: Rerun runs the case again.
+ expect(unverifiedCaseCount([topic])).toBe(1);
+ expect(
+ experimentGradingGaps(
+ [{ id: 'c', name: 'Model', runId: 'run' }],
+ [{ id: 'run', status: 'completed' }],
+ { run: [topic] },
+ ),
+ ).toEqual([{ id: 'c', name: 'Model', ungraded: 0, awaitingExternal: 0, judgeError: 1 }]);
+ });
+
+ it('counts incomplete Judge attempts within k and can re-grade the retained answers', () => {
+ const topic = {
+ testCaseId: 'a',
+ topicId: 'topic',
+ status: 'judge_error',
+ evalResult: {
+ threads: [
+ {
+ threadId: 'passed',
+ status: 'passed' as const,
+ rubricScores: [{ rubricId: 'r', score: 1 }],
+ },
+ {
+ threadId: 'judge',
+ status: 'judge_error' as const,
+ judgeError: 'Judge unavailable',
+ },
+ ],
+ },
+ };
+ expect(experimentGradingCoverage([topic])).toEqual({
+ graded: 1,
+ judgeError: 1,
+ error: 0,
+ noAnswer: 0,
+ ungraded: 0,
+ awaitingExternal: 0,
+ });
+ expect(unverifiedCaseCount([topic])).toBe(1);
+ });
+
+ it('escapes CSV commas, quotes, and line breaks in all fields', () => {
+ const csv = createExperimentResultsCsv(
+ [
+ {
+ id: 'a',
+ category: 'Notes\rTasks',
+ index: 8,
+ results: ['passed'],
+ title: 'Read, "notes"\nthen write',
+ },
+ ],
+ ['Model, "one"'],
+ );
+ expect(csv).toBe(
+ '#,Case,Category,"Model, ""one"""\n8,"Read, ""notes""\nthen write","Notes\rTasks",passed',
+ );
+ });
+
+ it('neutralizes spreadsheet formulas in exported text, including after leading whitespace', () => {
+ const csv = createExperimentResultsCsv(
+ [
+ {
+ id: 'a',
+ category: '\t@SUM(A1)',
+ index: 3,
+ results: ['-2+3', '\r=1'],
+ title: '=HYPERLINK("https://example.test")',
+ },
+ ],
+ ['+Model', ' @Other'],
+ );
+ expect(csv).toBe(
+ [
+ "#,Case,Category,'+Model,' @Other",
+ `3,"'=HYPERLINK(""https://example.test"")",'\t@SUM(A1),'-2+3,"'\r=1"`,
+ ].join('\n'),
+ );
+ });
+
+ it('exports exactly the selected native cases, in case order, without inventing missing results', () => {
+ const csvCases = cases.map((item, index) => ({
+ ...item,
+ category: 'Tools',
+ index: index + 1,
+ results: [index === 1 ? 'unavailable' : 'passed'],
+ title: `Case ${index + 1}`,
+ }));
+ expect(createExperimentResultsCsv(csvCases, ['Model'], ['native-b', 'missing'])).toBe(
+ '#,Case,Category,Model\n2,Case 2,Tools,unavailable',
+ );
+ expect(
+ createExperimentResultsCsv([...csvCases].reverse(), ['Model'], ['custom', 'native-a']),
+ ).toBe('#,Case,Category,Model\n1,Case 1,Tools,passed\n3,Case 3,Tools,passed');
+ });
+});
diff --git a/src/features/LobeBench/experimentResults.ts b/src/features/LobeBench/experimentResults.ts
new file mode 100644
index 00000000000..7a83090ce09
--- /dev/null
+++ b/src/features/LobeBench/experimentResults.ts
@@ -0,0 +1,294 @@
+import type { AgentEvalRunTopicResult } from '@lobechat/types';
+
+import { runStats } from './lobeBench';
+
+interface ExperimentCase {
+ id: string;
+ metadata?: Record<string, unknown> | null;
+}
+
+export type ExperimentCaseFilter = 'all' | 'allFail' | 'diff' | 'errors' | 'judgeErrors';
+
+export const defaultExperimentCaseFilter = (contenderCount: number): ExperimentCaseFilter =>
+ contenderCount > 1 ? 'diff' : 'all';
+
+/** An unfinished comparison must not imply that a completed contender has won. */
+export const orderExperimentContenders = <T>(
+ contenders: T[],
+ passed: (contender: T) => number,
+ incomplete: boolean,
+) => (incomplete ? [...contenders] : [...contenders].sort((a, b) => passed(b) - passed(a)));
+
+export const isUnavailableExperimentResult = (
+ runStatus: string | undefined,
+ results: Array<{ testCaseId: string }> | undefined,
+ caseId: string,
+) =>
+ !!results &&
+ ['completed', 'failed', 'aborted'].includes(runStatus ?? '') &&
+ !results.some((item) => item.testCaseId === caseId);
+
+/** Selection IDs are dataset-native IDs, not necessarily database primary keys. */
+export const scopeExperimentCases = <T extends ExperimentCase>(
+ cases: T[],
+ selectedIds?: string[],
+) => {
+ if (!selectedIds?.length) return { cases, missingCount: 0, selectedCount: cases.length };
+ const selected = new Set(selectedIds);
+ const available = new Set<string>();
+ const scoped = cases.filter((item) => {
+ const nativeId = item.metadata?.caseId;
+ const id = typeof nativeId === 'string' && nativeId ? nativeId : item.id;
+ if (!selected.has(id)) return false;
+ available.add(id);
+ return true;
+ });
+ return {
+ cases: scoped,
+ missingCount: selected.size - available.size,
+ selectedCount: selected.size,
+ };
+};
+
+/** Compare preserved summary totals with evidence, without recomputing historic grades. */
+export const experimentResultCoverage = (
+ expected: number,
+ results: Array<{ testCaseId: string }> | undefined,
+) => {
+ if (!results) return undefined;
+ const available = new Set(results.map((item) => item.testCaseId)).size;
+ return { available, expected, missing: Math.max(0, expected - available) };
+};
+
+export type AttemptGradeState =
+ 'awaitingExternal' | 'error' | 'graded' | 'judgeError' | 'noAnswer' | 'ungraded';
+
+interface GradeAttempt {
+ awaitingExternalEval?: boolean;
+ error?: string | null;
+ errorPhase?: string;
+ passed?: boolean | null;
+ rubricScores?: unknown[] | null;
+ status?: string | null;
+}
+
+/** A present result row is evidence of an attempt, not proof that grading finished. */
+export const attemptGradeState = (attempt: GradeAttempt): AttemptGradeState => {
+ if (attempt.status === 'judge_error' || attempt.errorPhase === 'judge') return 'judgeError';
+ if (
+ attempt.status === 'error' ||
+ attempt.status === 'timeout' ||
+ attempt.error === 'No assistant output'
+ )
+ return 'error';
+ if (['passed', 'failed'].includes(attempt.status ?? '') && attempt.rubricScores?.length)
+ return 'graded';
+ if (attempt.status === 'completed' && typeof attempt.passed === 'boolean') return 'graded';
+ if (attempt.status === 'failed' && !attempt.rubricScores?.length && attempt.error)
+ return 'noAnswer';
+ if (attempt.status === 'external' || attempt.awaitingExternalEval) return 'awaitingExternal';
+ return 'ungraded';
+};
+
+/** Live evidence counts, separate from the final quality estimates stored on a run. */
+export const experimentPassProgress = (
+ results: AgentEvalRunTopicResult[] | undefined,
+ k: number,
+ total: number,
+) => {
+ if (!results) return undefined;
+ let allPassed = 0;
+ let anyPassed = 0;
+ let evaluated = 0;
+ let errors = 0;
+ let hasVerdicts = false;
+ const cases = new Map(results.map((result) => [result.testCaseId, result]));
+ for (const result of cases.values()) {
+ const evaluation = result.evalResult;
+ const threads = evaluation?.threads;
+ const attempts: GradeAttempt[] = threads?.length
+ ? threads
+ : [{ ...evaluation, passed: result.passed, status: result.status }];
+ const states = attempts.map(attemptGradeState);
+ const passed = attempts.filter(
+ (attempt, index) => states[index] === 'graded' && attempt.passed === true,
+ ).length;
+ const caseError =
+ states.some((state) => state === 'error' || state === 'judgeError') ||
+ ['error', 'timeout', 'judge_error'].includes(result.status ?? '') ||
+ evaluation?.errorPhase === 'judge';
+ const distinct = !threads?.length || new Set(threads.map((t) => t.threadId)).size === k;
+ const graded = attempts.every(
+ (attempt, index) =>
+ (states[index] === 'graded' && typeof attempt.passed === 'boolean') ||
+ states[index] === 'noAnswer',
+ );
+ const complete = !caseError && attempts.length === k && distinct && graded;
+ if (passed > 0) anyPassed++;
+ if (complete && passed === k) allPassed++;
+ if (complete) evaluated++;
+ if (caseError) errors++;
+ if (
+ complete ||
+ attempts.some((attempt, i) => states[i] === 'graded' && typeof attempt.passed === 'boolean')
+ )
+ hasVerdicts = true;
+ }
+ return {
+ allPassed,
+ anyPassed,
+ complete: total > 0 && evaluated === total && cases.size === total && results.length === total,
+ errors,
+ evaluated,
+ hasVerdicts,
+ pending: Math.max(0, total - evaluated - errors),
+ };
+};
+
+/** Keep the table and complete-state insights on the same preserved verdict counts. */
+export const experimentRunStats = (
+ run: Parameters<typeof runStats>[0],
+ results: AgentEvalRunTopicResult[] | undefined,
+ totalCases?: number,
+) => {
+ const stats = runStats(run, totalCases);
+ const progress = experimentPassProgress(results, stats.k, stats.total);
+ return {
+ ...stats,
+ anyK: progress?.anyPassed ?? stats.anyK,
+ passed: progress?.allPassed ?? stats.passed,
+ progress,
+ };
+};
+
+export const experimentGradingCoverage = (results: AgentEvalRunTopicResult[]) => {
+ const counts: Record<AttemptGradeState, number> = {
+ awaitingExternal: 0,
+ error: 0,
+ graded: 0,
+ judgeError: 0,
+ noAnswer: 0,
+ ungraded: 0,
+ };
+ for (const topic of results) {
+ const evaluation = topic.evalResult;
+ const attempts: GradeAttempt[] = evaluation?.threads?.length
+ ? evaluation.threads
+ : [
+ {
+ awaitingExternalEval: evaluation?.awaitingExternalEval,
+ error: evaluation?.error,
+ errorPhase: evaluation?.errorPhase,
+ passed: topic.passed,
+ rubricScores: evaluation?.rubricScores,
+ status: topic.status,
+ },
+ ];
+ for (const attempt of attempts) counts[attemptGradeState(attempt)]++;
+ }
+ return counts;
+};
+
+const UNVERIFIED_STATUSES = new Set(['error', 'judge_error', 'timeout']);
+
+/**
+ * Cases Rerun would run again: the case, or any of its attempts, has no verdict
+ * (the model never answered, timed out, or the judge could not grade it).
+ * Mirrors the server's `needsRerun`.
+ */
+export const unverifiedCaseCount = (results: AgentEvalRunTopicResult[] | undefined) =>
+ (results ?? []).filter(
+ (topic) =>
+ UNVERIFIED_STATUSES.has(topic.status ?? '') ||
+ topic.evalResult?.error === 'No assistant output' ||
+ (topic.evalResult?.threads ?? []).some(
+ (thread) =>
+ UNVERIFIED_STATUSES.has(thread.status ?? '') || thread.error === 'No assistant output',
+ ),
+ ).length;
+
+export interface ExperimentGradingGap {
+ awaitingExternal: number;
+ id: string;
+ judgeError: number;
+ name: string;
+ ungraded: number;
+}
+
+export const experimentGradingGaps = (
+ contenders: Array<{ id: string; name: string; runId?: string }>,
+ runs: Array<{ id: string; status: string }>,
+ resultsMap: Record<string, AgentEvalRunTopicResult[]> | undefined,
+): ExperimentGradingGap[] =>
+ contenders.flatMap((contender) => {
+ const run = runs.find((item) => item.id === contender.runId);
+ const results = contender.runId ? resultsMap?.[contender.runId] : undefined;
+ if (!run || !results || !['completed', 'failed', 'aborted'].includes(run.status)) return [];
+ const coverage = experimentGradingCoverage(results);
+ return coverage.ungraded || coverage.awaitingExternal || coverage.judgeError
+ ? [
+ {
+ id: contender.id,
+ name: contender.name,
+ ungraded: coverage.ungraded,
+ judgeError: coverage.judgeError,
+ awaitingExternal: coverage.awaitingExternal,
+ },
+ ]
+ : [];
+ });
+
+interface ResultResource {
+ error?: unknown;
+ loaded: boolean;
+}
+
+/** An error is never an empty experiment or a zero score; cached data survives refresh errors. */
+export const experimentResultsState = (resources: ResultResource[]) => {
+ const failed = resources.find((item) => !item.loaded && item.error);
+ if (failed) return 'error';
+ if (resources.some((item) => !item.loaded)) return 'loading';
+ return 'ready';
+};
+
+export const lowestPassRateCategory = <T extends { rate: number | undefined }>(categories: T[]) =>
+ categories
+ .filter((item): item is T & { rate: number } => item.rate !== undefined && item.rate < 1)
+ .sort((a, b) => a.rate - b.rate)[0];
+
+interface ExperimentCsvCase extends ExperimentCase {
+ category: string;
+ index: number;
+ results: string[];
+ title: string;
+}
+
+const FORMULA_TRIGGERS = new Set(['=', '+', '-', '@']);
+
+/**
+ * Spreadsheet apps evaluate a cell that starts with a formula trigger, even
+ * after leading whitespace or control characters. Prefix such text with `'`
+ * so an exported case title or model name is shown as text, never run.
+ */
+const neutralizeSpreadsheetFormula = (text: string) => {
+ const first = [...text].find((char) => char.trim() !== '' && char.charCodeAt(0) > 0x1f);
+ return first && FORMULA_TRIGGERS.has(first) ? `'${text}` : text;
+};
+
+/** A complete export of the experiment selection, independent of on-screen filters. */
+export const createExperimentResultsCsv = (
+ cases: ExperimentCsvCase[],
+ contenderNames: string[],
+ selectedIds?: string[],
+) => {
+ const quote = (value: string | number) => {
+ const text = typeof value === 'string' ? neutralizeSpreadsheetFormula(value) : String(value);
+ return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
+ };
+ const rows = [...scopeExperimentCases(cases, selectedIds).cases]
+ .sort((a, b) => a.index - b.index)
+ .map((item) => [item.index, item.title, item.category, ...item.results]);
+ return [['#', 'Case', 'Category', ...contenderNames], ...rows]
+ .map((row) => row.map(quote).join(','))
+ .join('\n');
+};
diff --git a/src/features/LobeBench/launchBackground.test.ts b/src/features/LobeBench/launchBackground.test.ts
new file mode 100644
index 00000000000..c94e8300a03
--- /dev/null
+++ b/src/features/LobeBench/launchBackground.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createExperimentLaunch,
+ experimentLaunchKey,
+ type LaunchServices,
+ type LaunchStorage,
+} from './experimentLaunch';
+import {
+ backgroundLaunchKey,
+ findSavedExperimentLaunch,
+ forgetExperimentLaunch,
+ getBackgroundLaunch,
+ startBackgroundLaunch,
+ subscribeBackgroundLaunch,
+} from './launchBackground';
+
+const setup = () => {
+ const record = createExperimentLaunch({
+ benchmarkId: 'b',
+ datasetId: 'd',
+ name: 'Trial',
+ metadata: {},
+ contenders: [{ id: 'm', name: 'Model', config: {} }],
+ });
+ const scope = { benchmarkId: 'b', userId: 'u', workspaceId: null };
+ const data = new Map([[experimentLaunchKey(scope), JSON.stringify(record)]]);
+ const storage: LaunchStorage = {
+ getItem: (k) => data.get(k) ?? null,
+ setItem: (k, v) => {
+ data.set(k, v);
+ },
+ removeItem: (k) => {
+ data.delete(k);
+ },
+ };
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const services: LaunchServices = {
+ createExperiment: vi.fn(async () => ({})),
+ listRuns: vi.fn(async () => []),
+ createRun: vi.fn(async () => {
+ await gate;
+ return { status: 'idle' };
+ }),
+ updateExperiment: vi.fn(async () => ({})),
+ startRun: vi.fn(async () => ({})),
+ };
+ return {
+ record,
+ scope,
+ storage,
+ services,
+ release,
+ key: backgroundLaunchKey('u', null, record.experimentId),
+ };
+};
+describe('route-independent experiment launch', () => {
+ it('continues after the page unsubscribes and exposes completion on return', async () => {
+ const f = setup();
+ const listener = vi.fn();
+ const unsubscribe = subscribeBackgroundLaunch(listener);
+ const task = startBackgroundLaunch(f.scope, f.record, f.services, f.storage);
+ await vi.waitFor(() => expect(f.services.createRun).toHaveBeenCalledOnce());
+ expect(getBackgroundLaunch(f.key)?.progress?.stage).toBe('run');
+ unsubscribe();
+ listener.mockClear();
+ f.release();
+ await task;
+ expect(listener).not.toHaveBeenCalled();
+ expect(getBackgroundLaunch(f.key)?.outcome?.complete).toBe(true);
+ expect(f.services.startRun).toHaveBeenCalledOnce();
+ expect(f.storage.getItem(experimentLaunchKey(f.scope))).toBeNull();
+ });
+ it('deduplicates a second start while the route changes', async () => {
+ const f = setup();
+ const task = startBackgroundLaunch(f.scope, f.record, f.services, f.storage);
+ expect(startBackgroundLaunch(f.scope, f.record, f.services, f.storage)).toBe(task);
+ f.release();
+ await task;
+ expect(f.services.startRun).toHaveBeenCalledOnce();
+ expect(
+ getBackgroundLaunch(backgroundLaunchKey('other', null, f.record.experimentId)),
+ ).toBeUndefined();
+ });
+ it('retains the error and checkpoint for a retry after navigating away', async () => {
+ const f = setup();
+ vi.mocked(f.services.createRun).mockRejectedValueOnce(new Error('Connection unavailable'));
+ const result = await startBackgroundLaunch(f.scope, f.record, f.services, f.storage);
+ expect(result.complete).toBe(false);
+ expect(getBackgroundLaunch(f.key)?.active).toBe(false);
+ expect(getBackgroundLaunch(f.key)?.outcome?.error?.message).toBe('Connection unavailable');
+ expect(f.storage.getItem(experimentLaunchKey(f.scope))).not.toBeNull();
+ f.release();
+ expect((await startBackgroundLaunch(f.scope, f.record, f.services, f.storage)).complete).toBe(
+ true,
+ );
+ });
+});
+
+describe('deleted launch recovery', () => {
+ it('removes only the deleted experiment checkpoint and retained failed state', async () => {
+ const f = setup();
+ vi.mocked(f.services.createRun).mockRejectedValueOnce(new Error('offline'));
+ await startBackgroundLaunch(f.scope, f.record, f.services, f.storage);
+ const ownKey = experimentLaunchKey(f.scope);
+ const otherKey = experimentLaunchKey({ ...f.scope, userId: 'other' });
+ localStorage.setItem(ownKey, JSON.stringify(f.record));
+ localStorage.setItem(otherKey, JSON.stringify(f.record));
+ expect(findSavedExperimentLaunch('u', null, f.record.experimentId)?.experimentId).toBe(
+ f.record.experimentId,
+ );
+ expect(
+ findSavedExperimentLaunch('u', 'different-workspace', f.record.experimentId),
+ ).toBeUndefined();
+ forgetExperimentLaunch('u', null, f.record.experimentId);
+ expect(getBackgroundLaunch(f.key)).toBeUndefined();
+ expect(localStorage.getItem(ownKey)).toBeNull();
+ expect(localStorage.getItem(otherKey)).not.toBeNull();
+ localStorage.removeItem(otherKey);
+ });
+});
diff --git a/src/features/LobeBench/launchBackground.ts b/src/features/LobeBench/launchBackground.ts
new file mode 100644
index 00000000000..22ee55e07f4
--- /dev/null
+++ b/src/features/LobeBench/launchBackground.ts
@@ -0,0 +1,120 @@
+import {
+ clearLaunchInStorage,
+ type ExperimentLaunch,
+ experimentLaunchKey,
+ type ExperimentLaunchScope,
+ launchExperiment,
+ type LaunchOutcome,
+ type LaunchProgress,
+ launchResumeLockName,
+ type LaunchServices,
+ type LaunchStorage,
+ parseExperimentLaunch,
+ runExclusiveLaunch,
+} from './experimentLaunch';
+
+export interface BackgroundLaunch {
+ active: boolean;
+ error?: string;
+ outcome?: LaunchOutcome;
+ progress?: LaunchProgress;
+ record: ExperimentLaunch;
+}
+const states = new Map<string, BackgroundLaunch>();
+const pending = new Map<string, Promise<LaunchOutcome>>();
+const listeners = new Set<() => void>();
+export const backgroundLaunchKey = (userId: string, workspaceId: string | null, id: string) =>
+ JSON.stringify([userId, workspaceId, id]);
+export const getBackgroundLaunch = (key: string) => states.get(key);
+export const subscribeBackgroundLaunch = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+const publish = (key: string, state: BackgroundLaunch) => {
+ states.set(key, state);
+ listeners.forEach((listener) => listener());
+};
+
+/** The promise belongs to the browser session, never to a mounted route. */
+export function startBackgroundLaunch(
+ scope: ExperimentLaunchScope,
+ record: ExperimentLaunch,
+ services: LaunchServices,
+ storage: LaunchStorage = localStorage,
+ locks = typeof navigator === 'undefined' ? undefined : navigator.locks,
+): Promise<LaunchOutcome> {
+ const key = backgroundLaunchKey(scope.userId, scope.workspaceId, record.experimentId);
+ const existing = pending.get(key);
+ if (existing) return existing;
+ const storageKey = experimentLaunchKey(scope);
+ let state: BackgroundLaunch = { active: true, record };
+ const task = Promise.resolve().then(async () => {
+ try {
+ const lockName = launchResumeLockName(storageKey, record.experimentId);
+ const result = await runExclusiveLaunch(
+ { leaseKey: lockName, lockName, locks, storage },
+ () =>
+ launchExperiment(record, services, (progress) => {
+ state = { ...state, progress };
+ publish(key, state);
+ }),
+ );
+ if (!result.ran) throw new Error('launch_busy');
+ const outcome = result.result;
+ state = { ...state, outcome };
+ if (outcome.complete) {
+ clearLaunchInStorage(storage, storageKey, record.experimentId);
+ if (typeof window !== 'undefined')
+ window.dispatchEvent(new StorageEvent('storage', { key: storageKey }));
+ }
+ return outcome;
+ } catch (error) {
+ state = { ...state, error: error instanceof Error ? error.message : String(error) };
+ throw error;
+ } finally {
+ pending.delete(key);
+ publish(key, { ...state, active: false });
+ }
+ });
+ pending.set(key, task);
+ publish(key, state);
+ return task;
+}
+
+/** Refresh recovery is explicit; never automatically repeat an uncertain dispatch. */
+export function findSavedExperimentLaunch(userId: string, workspaceId: string | null, id: string) {
+ try {
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (!key?.startsWith('lobe-bench:experiment-launch:v1:')) continue;
+ const record = parseExperimentLaunch(localStorage.getItem(key));
+ if (record?.version !== 2 || record.experimentId !== id) continue;
+ if (key === experimentLaunchKey({ benchmarkId: record.benchmarkId, userId, workspaceId }))
+ return record;
+ }
+ } catch {
+ /* Storage may be unavailable; the experiment remains readable. */
+ }
+}
+
+export const isExperimentLaunching = (id: string) =>
+ [...states.values()].some((state) => state.record.experimentId === id && state.active);
+
+export function forgetExperimentLaunch(userId: string, workspaceId: string | null, id: string) {
+ const key = backgroundLaunchKey(userId, workspaceId, id);
+ if (states.get(key)?.active) return;
+ const record = states.get(key)?.record ?? findSavedExperimentLaunch(userId, workspaceId, id);
+ if (record) {
+ const storageKey = experimentLaunchKey({
+ benchmarkId: record.benchmarkId,
+ userId,
+ workspaceId,
+ });
+ clearLaunchInStorage(localStorage, storageKey, id);
+ window.dispatchEvent(new StorageEvent('storage', { key: storageKey }));
+ }
+ states.delete(key);
+ listeners.forEach((listener) => listener());
+}
diff --git a/src/features/LobeBench/launchServices.ts b/src/features/LobeBench/launchServices.ts
new file mode 100644
index 00000000000..21dc3abbf88
--- /dev/null
+++ b/src/features/LobeBench/launchServices.ts
@@ -0,0 +1,17 @@
+import { agentEvalService } from '@/services/agentEval';
+
+export const launchServices = {
+ createExperiment: (params: Parameters<typeof agentEvalService.createExperiment>[0]) =>
+ agentEvalService.createExperiment(params),
+ createRun: (params: {
+ config: Record<string, unknown>;
+ datasetId: string;
+ experimentId: string;
+ id: string;
+ name: string;
+ }) => agentEvalService.createRun(params as Parameters<typeof agentEvalService.createRun>[0]),
+ listRuns: (experimentId: string) => agentEvalService.listAllRuns({ experimentId }),
+ startRun: (runId: string) => agentEvalService.startRun(runId),
+ updateExperiment: (params: { id: string; metadata: Record<string, unknown> }) =>
+ agentEvalService.updateExperiment(params),
+};
diff --git a/src/features/LobeBench/lobeBench.test.ts b/src/features/LobeBench/lobeBench.test.ts
new file mode 100644
index 00000000000..00c65248849
--- /dev/null
+++ b/src/features/LobeBench/lobeBench.test.ts
@@ -0,0 +1,530 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ benchmarkDatasetsOf,
+ caseCountOf,
+ customDatasetsOf,
+ datasetsOf,
+ describeSettings,
+ experimentPartMeta,
+ experimentPartsOf,
+ getCaseConnectors,
+ getCaseIndex,
+ getCaseTitle,
+ isFullRun,
+ isLobeBenchMeta,
+ isViewDataset,
+ libraryOf,
+ looseDatasetsOf,
+ nativeCaseId,
+ orderDatasetsForPicker,
+ pickDefaultDataset,
+ rankableSetsOf,
+ replaceContender,
+ runCaseCount,
+ runCoversSet,
+ runStats,
+ sameContender,
+ settingsBenchmarkOf,
+ sortBenchmarks,
+ stableJson,
+ summarizeCaseResult,
+ withRanContenders,
+} from '@/features/LobeBench/lobeBench';
+
+describe('lobeBench helpers', () => {
+ it('recognises a Lobe Bench experiment by its metadata', () => {
+ expect(isLobeBenchMeta({ contenders: [], datasetId: 'ds', k: 1, kind: 'lobe-bench' })).toBe(
+ true,
+ );
+ expect(isLobeBenchMeta({ kind: 'lobe-bench' })).toBe(false);
+ expect(isLobeBenchMeta(null)).toBe(false);
+ });
+
+ it('describes a contender by the settings that differ from the model default', () => {
+ expect(describeSettings()).toBe('');
+ expect(describeSettings({ temperature: 0.2 }, { reasoningEffort: 'high' })).toBe(
+ 'temperature 0.2 · reasoning high',
+ );
+ // Every setting that tells contenders apart shows, so default names differ.
+ expect(
+ describeSettings(
+ { presence_penalty: 0.5 },
+ {
+ enableReasoning: false,
+ textVerbosity: 'low',
+ thinking: 'enabled',
+ thinkingLevel: 'high',
+ },
+ ),
+ ).toBe(
+ 'presence penalty 0.5 · reasoning off · thinking enabled · thinking level high · verbosity low',
+ );
+ });
+
+ it('writes equal settings as equal text, whatever the key order', () => {
+ expect(stableJson({ b: 1, a: { d: 2, c: undefined } })).toBe(stableJson({ a: { d: 2 }, b: 1 }));
+ expect(
+ sameContender(
+ { id: '1', model: 'm', name: 'x', params: { temperature: 0.2, top_p: 1 }, provider: 'p' },
+ { id: '2', model: 'm', name: 'y', params: { top_p: 1, temperature: 0.2 }, provider: 'p' },
+ ),
+ ).toBe(true);
+ });
+
+ it('reads a case title, index and connectors from an imported case', () => {
+ const testCase = {
+ content: {
+ environment: { mock: { services: ['twitter', 'lobe-skills', 'lobe-web-browsing'] } },
+ input: 'Generate an X daily brief\nfrom recent posts',
+ },
+ id: 'tc_1',
+ metadata: { index: 7, title: 'Generate an X daily brief from recent posts' },
+ sortOrder: 6,
+ };
+ expect(getCaseTitle(testCase)).toBe('Generate an X daily brief from recent posts');
+ expect(getCaseTitle({ ...testCase, metadata: null })).toBe('Generate an X daily brief');
+ expect(getCaseIndex(testCase)).toBe(7);
+ expect(getCaseIndex({ ...testCase, metadata: null })).toBe(7);
+ expect(getCaseConnectors(testCase)).toEqual(['twitter', 'lobe-web-browsing']);
+ });
+
+ it('summarises a single attempt and a pass@k attempt the same way', () => {
+ const single = summarizeCaseResult(
+ {
+ evalResult: { rubricScores: [{ reason: 'ok', rubricId: 'r', score: 1 }], toolCalls: 3 },
+ status: 'passed',
+ testCaseId: 'tc',
+ topicId: 'tpc',
+ },
+ 1,
+ );
+ expect(single).toMatchObject({
+ passCount: 1,
+ reason: 'ok',
+ toolCalls: 3,
+ total: 1,
+ verdict: 'passed',
+ });
+
+ const multi = summarizeCaseResult(
+ {
+ evalResult: {
+ threads: [
+ { passed: true, status: 'passed', threadId: 'a' },
+ { passed: false, status: 'failed', threadId: 'b' },
+ { passed: false, status: 'error', threadId: 'c' },
+ ],
+ },
+ status: 'passed',
+ testCaseId: 'tc',
+ topicId: 'tpc',
+ },
+ 3,
+ );
+ expect(multi.passCount).toBe(1);
+ expect(multi.total).toBe(3);
+ expect(multi.threads.map((thread) => thread.status)).toEqual(['passed', 'failed', 'error']);
+
+ expect(summarizeCaseResult(undefined, 3)).toMatchObject({
+ passCount: 0,
+ total: 3,
+ verdict: 'pending',
+ });
+ });
+
+ it('shows externally completed threads as pass/fail only when a verdict was reported', () => {
+ const result = summarizeCaseResult(
+ {
+ testCaseId: 'tc',
+ topicId: 'topic',
+ status: 'passed',
+ evalResult: {
+ threads: [
+ { threadId: 'passed', status: 'completed', passed: true },
+ { threadId: 'failed', status: 'completed', passed: false },
+ { threadId: 'ungraded', status: 'completed' },
+ ],
+ },
+ },
+ 3,
+ );
+ expect(result.threads.map((thread) => thread.status)).toEqual(['passed', 'failed', 'pending']);
+ expect(result.passCount).toBe(1);
+ });
+
+ it('derives a contender row from run metrics', () => {
+ const stats = runStats({
+ id: 'run',
+ metrics: {
+ completedCases: 30,
+ errorCases: 2,
+ failedCases: 10,
+ passedCases: 18,
+ perCaseCost: 0.02,
+ totalCases: 30,
+ totalCost: 0.6,
+ totalDuration: 3_600_000,
+ },
+ status: 'completed',
+ } as any);
+ expect(stats).toMatchObject({
+ active: false,
+ completed: 30,
+ errors: 2,
+ passed: 18,
+ perCaseCost: 0.02,
+ totalCost: 0.6,
+ });
+ expect(stats.passRate).toBeCloseTo(0.6);
+ expect(stats.avgMinutes).toBeCloseTo(2);
+ expect(runStats(undefined, 30)).toMatchObject({ passed: 0, total: 30 });
+ });
+
+ it('counts a case as passed only when every attempt passed once k > 1', () => {
+ const stats = runStats({
+ config: { k: 3 },
+ id: 'run',
+ metrics: {
+ completedCases: 30,
+ failedCases: 1,
+ passAllK: 0.6,
+ passAtK: 29 / 30,
+ passedCases: 29,
+ totalCases: 30,
+ },
+ status: 'completed',
+ } as any);
+ expect(stats).toMatchObject({ allK: 18, anyK: 29, k: 3, passed: 18, total: 30 });
+ expect(stats.passRate).toBeCloseTo(0.6);
+ // A single attempt per case: the three numbers coincide.
+ expect(
+ runStats({
+ config: { k: 1 },
+ id: 'run',
+ metrics: { passedCases: 25, totalCases: 30 },
+ status: 'completed',
+ } as any),
+ ).toMatchObject({ allK: 25, anyK: 25, k: 1, passed: 25 });
+ });
+});
+
+describe('case sets', () => {
+ const benchmarks = [
+ { id: 'b-sample', identifier: 'lobe-bench-sample' },
+ { id: 'b-main', identifier: 'lobe-bench' },
+ ];
+ const datasets = [
+ {
+ benchmarkId: 'b-main',
+ createdAt: '2026-10-25',
+ id: 'mine',
+ metadata: { custom: true },
+ name: 'My cases',
+ testCaseCount: 2,
+ },
+ {
+ benchmarkId: 'b-main',
+ createdAt: '2026-10-23',
+ id: 'b30',
+ metadata: { release: 'v26' },
+ name: 'Benchmark 30',
+ testCaseCount: 30,
+ },
+ {
+ benchmarkId: 'b-sample',
+ createdAt: '2026-10-22',
+ id: 'date',
+ metadata: null,
+ name: 'Date check',
+ testCaseCount: 1,
+ },
+ {
+ benchmarkId: 'b-sample',
+ createdAt: '2026-10-21',
+ id: 'sample',
+ metadata: null,
+ name: 'Persona sample',
+ testCaseCount: 3,
+ },
+ {
+ benchmarkId: 'b-main',
+ createdAt: '2026-11-01',
+ id: 'extra',
+ metadata: null,
+ name: 'Extra cases',
+ testCaseCount: 4,
+ },
+ ];
+
+ it("lists a benchmark's sets in creation order with the account's own last", () => {
+ expect(datasetsOf(datasets, 'b-main').map((d) => d.id)).toEqual(['b30', 'extra', 'mine']);
+ expect(customDatasetsOf(datasets, 'b-main').map((d) => d.id)).toEqual(['mine']);
+ expect(pickDefaultDataset(datasets, 'b-main')?.id).toBe('b30');
+ expect(pickDefaultDataset(datasets, 'b-sample')?.id).toBe('sample');
+ expect(pickDefaultDataset([datasets[0]], 'b-main')?.id).toBe('mine');
+ });
+
+ it("orders a picker by benchmark (primary first), then each benchmark's sets", () => {
+ expect(orderDatasetsForPicker(datasets, benchmarks).map((d) => d.id)).toEqual([
+ 'b30',
+ 'extra',
+ 'mine',
+ 'sample',
+ 'date',
+ ]);
+ });
+
+ it('finds the built-in library and never takes an account dataset for it', () => {
+ expect(libraryOf(datasets, 'b-main')?.id).toBe('b30');
+ expect(libraryOf([datasets[0]], 'b-main')).toBeUndefined();
+ });
+
+ it('counts a dataset by the cases it holds', () => {
+ const own = {
+ benchmarkId: 'b-main',
+ createdAt: '2026-10-30',
+ id: 'finance',
+ metadata: { custom: true },
+ name: 'Finance',
+ testCaseCount: 3,
+ };
+ expect(caseCountOf(own)).toBe(3);
+ expect(caseCountOf(datasets[0])).toBe(2);
+ expect(caseCountOf(undefined)).toBe(0);
+ // An account dataset, listed with the account's own, never as the library.
+ expect(customDatasetsOf([...datasets, own], 'b-main').map((d) => d.id)).toEqual([
+ 'mine',
+ 'finance',
+ ]);
+ });
+});
+
+describe('datasets that hold their cases', () => {
+ const library = {
+ benchmarkId: 'b',
+ createdAt: '2026-10-01',
+ id: 'lib',
+ metadata: {},
+ name: 'Case library',
+ };
+ const hard = {
+ benchmarkId: 'h',
+ createdAt: '2026-10-30',
+ id: 'hard',
+ metadata: { release: 'hard-v1', view: { id: 'lobe-bench-hard-50', version: 'hard-v1' } },
+ name: 'Hard 50',
+ };
+ const mine = {
+ benchmarkId: 'b',
+ createdAt: '2026-10-31',
+ id: 'mine',
+ metadata: { custom: true },
+ name: 'Mine',
+ };
+
+ const benchmarks = [
+ {
+ createdAt: '2026-10-30',
+ id: 'h',
+ identifier: 'lobe-bench-hard-50',
+ isSystem: true,
+ metadata: { kind: 'lobe-bench', view: { id: 'lobe-bench-hard-50', version: 'v2' } },
+ name: 'Lobe Bench Hard 50',
+ },
+ {
+ createdAt: '2026-10-01',
+ id: 'b',
+ identifier: 'lobe-bench',
+ isSystem: true,
+ metadata: { kind: 'lobe-bench' },
+ name: 'Lobe Bench',
+ },
+ ];
+ const [hardBenchmark, libraryBenchmark] = benchmarks;
+ const accountBenchmark = {
+ createdAt: '2026-10-31',
+ id: 'u',
+ identifier: 'lobe-bench-u',
+ isSystem: false,
+ metadata: { kind: 'lobe-bench' },
+ name: 'Finance',
+ };
+
+ it('keeps the library apart from Hard 50 and the account datasets', () => {
+ const all = [hard, mine, library];
+ expect(libraryOf(all, 'b')?.id).toBe('lib');
+ expect(libraryOf(all)?.id).toBe('lib');
+ expect(isViewDataset(hard)).toBe(true);
+ expect(isViewDataset(mine)).toBe(false);
+ expect(isViewDataset(library)).toBe(false);
+ });
+
+ it('makes each benchmark of its built-in dataset; account datasets belong to none', () => {
+ const all = [hard, mine, library];
+ expect(benchmarkDatasetsOf(all, libraryBenchmark).map((d) => d.id)).toEqual(['lib']);
+ expect(benchmarkDatasetsOf(all, hardBenchmark).map((d) => d.id)).toEqual(['hard']);
+ expect(sortBenchmarks(benchmarks).map((b) => b.id)).toEqual(['b', 'h']);
+ // Built-in benchmarks come before the account's, whatever their age.
+ expect(
+ sortBenchmarks([{ ...accountBenchmark, createdAt: '2026-10-01' }, hardBenchmark]).map(
+ (b) => b.id,
+ ),
+ ).toEqual(['h', 'u']);
+ // Without the library's benchmark in the list, the oldest still comes first.
+ expect(sortBenchmarks([accountBenchmark, hardBenchmark]).map((b) => b.id)).toEqual(['h', 'u']);
+ // One leaderboard per benchmark, named by it, on the dataset it is made of.
+ expect(rankableSetsOf(sortBenchmarks(benchmarks), all)).toEqual([
+ { benchmarkId: 'b', caseVersion: undefined, id: 'lib', name: 'Lobe Bench' },
+ { benchmarkId: 'h', caseVersion: 'hard-v1', id: 'hard', name: 'Lobe Bench Hard 50' },
+ ]);
+ });
+
+ it('takes the settings of a benchmark made of library cases from the library', () => {
+ expect(settingsBenchmarkOf(benchmarks, 'h')?.id).toBe('b');
+ expect(settingsBenchmarkOf(benchmarks, 'b')?.id).toBe('b');
+ });
+
+ it('makes an account benchmark of the datasets moved into it', () => {
+ const second = { ...mine, id: 'mine-2', name: 'Mine 2' };
+ const moved = { ...mine, benchmarkId: 'u' };
+ const all = [hard, moved, { ...second, benchmarkId: 'u' }, library];
+ const withAccount = [...sortBenchmarks(benchmarks), accountBenchmark];
+ expect(benchmarkDatasetsOf(all, accountBenchmark).map((d) => d.id)).toEqual(['mine', 'mine-2']);
+ // In a benchmark of the account's, so no longer loose; the other one still is.
+ expect(looseDatasetsOf(all, withAccount)).toEqual([]);
+ expect(looseDatasetsOf([hard, mine, library], withAccount).map((d) => d.id)).toEqual(['mine']);
+ // Several datasets: one leaderboard each, named by benchmark and dataset.
+ expect(
+ rankableSetsOf(withAccount, all)
+ .filter((set) => set.benchmarkId === 'u')
+ .map((set) => set.name),
+ ).toEqual(['Finance · Mine', 'Finance · Mine 2']);
+ // Its experiment defaults are the library benchmark's.
+ expect(settingsBenchmarkOf(withAccount, 'u')?.id).toBe('b');
+ });
+
+ it('counts a run for a set when it ran all of that dataset', () => {
+ const on = (datasetId: string, caseIds?: string[]) => ({
+ config: caseIds ? { caseSelection: { caseIds, mode: 'include' } } : {},
+ datasetId,
+ });
+ expect(runCoversSet(on('hard'), { id: 'hard' })).toBe(true);
+ expect(runCoversSet(on('hard', ['c1']), { id: 'hard' })).toBe(false);
+ expect(runCoversSet(on('lib'), { id: 'hard' })).toBe(false);
+ });
+});
+
+describe('experiments over several benchmarks', () => {
+ const meta = {
+ contenders: [
+ { id: 'c-a', model: 'a', name: 'A', provider: 'p', runId: 'run-a' },
+ { id: 'c-b', model: 'b', name: 'B', provider: 'p', runId: 'run-b' },
+ ],
+ datasetId: 'lib',
+ k: 1,
+ kind: 'lobe-bench' as const,
+ maxSteps: 20,
+ timeout: 900_000,
+ };
+
+ it('reads an experiment of one dataset as one part', () => {
+ expect(experimentPartsOf(meta)).toEqual([
+ {
+ caseIds: undefined,
+ datasetId: 'lib',
+ pickedDatasetId: undefined,
+ runIds: { 'c-a': 'run-a', 'c-b': 'run-b' },
+ },
+ ]);
+ expect(experimentPartMeta(meta, experimentPartsOf(meta)[0]).contenders).toEqual(
+ meta.contenders,
+ );
+ });
+
+ it('shows each part as an experiment of that dataset alone', () => {
+ const parts = [
+ { benchmarkId: 'b', datasetId: 'lib', runIds: { 'c-a': 'run-a', 'c-b': 'run-b' } },
+ {
+ benchmarkId: 'h',
+ caseIds: ['c1', 'c2'],
+ datasetId: 'lib',
+ pickedDatasetId: 'hard',
+ runIds: { 'c-a': 'run-a2', 'c-b': 'run-b2' },
+ },
+ ];
+ const both = { ...meta, parts };
+ expect(experimentPartsOf(both)).toBe(parts);
+ const hard = experimentPartMeta(both, parts[1]);
+ expect(hard).toMatchObject({
+ caseIds: ['c1', 'c2'],
+ datasetId: 'lib',
+ pickedDatasetId: 'hard',
+ });
+ expect(hard.contenders.map((c) => c.runId)).toEqual(['run-a2', 'run-b2']);
+ });
+});
+
+describe('case selection', () => {
+ it('selects a case by its dataset-native id, else its primary key', () => {
+ expect(nativeCaseId({ id: 'case_1', metadata: { caseId: 'designed-gap-01' } })).toBe(
+ 'designed-gap-01',
+ );
+ expect(nativeCaseId({ id: 'case_2', metadata: { caseId: '' } })).toBe('case_2');
+ expect(nativeCaseId({ id: 'case_3' })).toBe('case_3');
+ });
+
+ it('tells whole-set runs from runs that picked cases, and counts their cases', () => {
+ const whole = { config: { caseSelection: undefined } };
+ const all = { config: { caseSelection: { mode: 'all' as const } } };
+ const some = { config: { caseSelection: { caseIds: ['a', 'b'], mode: 'include' as const } } };
+ const most = { config: { caseSelection: { caseIds: ['a'], mode: 'exclude' as const } } };
+ expect([whole, all, some, most].map(isFullRun)).toEqual([true, true, false, false]);
+ expect([whole, all, some, most].map((run) => runCaseCount(run, 30))).toEqual([30, 30, 2, 29]);
+ });
+});
+
+describe('withRanContenders', () => {
+ const flash = {
+ chatConfig: { enableReasoning: true },
+ id: 'c1',
+ model: 'deepseek/deepseek-v4.1-flash',
+ name: 'DeepSeek V4.1 Flash',
+ provider: 'openrouter',
+ };
+
+ it("keeps a renamed contender's new name over the copy an earlier experiment recorded", () => {
+ const renamed = { ...flash, name: 'DeepSeek V4.1 Flash · reasoning on' };
+ const list = withRanContenders([renamed], [{ ...flash, runId: 'run_1' }]);
+ expect(list).toEqual([renamed]);
+ });
+
+ it('adds what experiments ran that the saved list does not have, once', () => {
+ const haiku = {
+ id: 'c2',
+ model: 'anthropic/claude-haiku-5.5',
+ name: 'Claude Haiku 5.5',
+ provider: 'openrouter',
+ };
+ const list = withRanContenders(
+ [flash],
+ [haiku, { ...haiku, id: 'c3' }, { ...flash, id: 'c4' }],
+ );
+ expect(list.map((c) => c.id)).toEqual(['c1', 'c2']);
+ });
+});
+
+describe('replaceContender', () => {
+ const qwen = { id: 'q1', model: 'qwen4', name: ' · 推理 on', provider: 'custom' };
+ const other = { id: 'o1', model: 'glm-5.3-flash', name: 'GLM 5.3 Flash', provider: 'zhipu' };
+
+ it('renames a saved contender picked into an experiment, in the draft and the saved list', () => {
+ const edited = { ...qwen, name: 'Qwen4 · 推理 on' };
+ expect(replaceContender([other, qwen], edited)).toEqual([other, edited]);
+ });
+
+ it('leaves a list without that contender as it is', () => {
+ const list = [other];
+ expect(replaceContender(list, { ...qwen, name: 'Qwen4' })).toBe(list);
+ });
+});
diff --git a/src/features/LobeBench/lobeBench.ts b/src/features/LobeBench/lobeBench.ts
new file mode 100644
index 00000000000..17021ac3607
--- /dev/null
+++ b/src/features/LobeBench/lobeBench.ts
@@ -0,0 +1,740 @@
+import {
+ type AgentEvalRunListItem,
+ evalCaseVersionOf,
+ type EvalRunChatConfig,
+ type EvalRunModelParams,
+} from '@lobechat/types';
+
+import { LOBE_BENCH_KIND } from '@/store/eval/kinds';
+
+export {
+ CASE_LEVELS,
+ type CaseLevel,
+ getCaseDifficulty,
+ getCaseLevel,
+ levelLabelKey,
+ levelTagColor,
+} from '@/features/Eval/caseDifficulty';
+
+/** `agent_eval_benchmarks.metadata.kind` / `agent_eval_experiments.metadata.kind` of Lobe Bench rows. */
+export { LOBE_BENCH_KIND };
+export const LOBE_BENCH_PATH = '/eval/lobe-bench';
+export const DEFAULT_MAX_STEPS = 30;
+export const DEFAULT_TIMEOUT_MINUTES = 20;
+export const K_OPTIONS = [1, 2, 3, 4, 5];
+/**
+ * Attempts per case a leaderboard ranks on: a case counts
+ * when it passes all of them. Runs of more attempts rank on their estimate for
+ * this many; runs of fewer are not ranked.
+ */
+export const RANK_ATTEMPTS = 3;
+
+/**
+ * A contender is a model plus the settings it runs with; the same model with
+ * another setting is a different contender. One experiment run per contender.
+ */
+export interface LobeBenchContender {
+ chatConfig?: EvalRunChatConfig;
+ id: string;
+ model: string;
+ name: string;
+ params?: EvalRunModelParams;
+ provider: string;
+ /** Filled in once the experiment started. */
+ runId?: string;
+}
+
+/**
+ * One dataset an experiment ran, in the benchmark it is part of. An experiment can
+ * cover several benchmarks (experiments and benchmarks are n to n),
+ * one part each; every contender has a run on every part.
+ */
+export interface LobeBenchExperimentPart {
+ /** The benchmark the dataset is part of. */
+ benchmarkId?: string;
+ /** Dataset-native ids of the cases run, when the part ran some of the dataset's cases. */
+ caseIds?: string[];
+ /** The dataset the runs are on. */
+ datasetId: string;
+ /**
+ * Experiments from before datasets held their cases (until 2026-10-31): the
+ * dataset whose case ids were run on the library.
+ */
+ pickedDatasetId?: string;
+ /** Each contender's run on this part, by contender id, once the runs exist. */
+ runIds?: Record<string, string>;
+}
+
+/** What Lobe Bench stores in `agent_eval_experiments.metadata`. */
+export interface LobeBenchExperimentMeta {
+ /** Dataset-native ids of the cases the experiment ran; absent when it ran the whole set. */
+ caseIds?: string[];
+ contenders: LobeBenchContender[];
+ datasetId: string;
+ k: number;
+ kind: typeof LOBE_BENCH_KIND;
+ maxSteps: number;
+ /**
+ * Every dataset the experiment ran, when it covers more than one. The fields
+ * above (`datasetId`, `caseIds`, `pickedDatasetId`, each contender's `runId`)
+ * then repeat the first part, for readers that know one dataset.
+ */
+ parts?: LobeBenchExperimentPart[];
+ /**
+ * Experiments from before datasets held their cases (until 2026-10-31): the
+ * dataset whose case ids were run on the library.
+ */
+ pickedDatasetId?: string;
+ question?: string;
+ timeout: number;
+}
+
+type Metadata = Record<string, unknown> | null | undefined;
+
+/** What the Settings page keeps in `agent_eval_benchmarks.metadata` (beside `kind` and `mock`). */
+export interface LobeBenchBenchmarkMeta {
+ /** Contenders the account saved or ran before, offered again on the next experiment. */
+ contenders?: LobeBenchContender[];
+ /** What a new experiment starts with. */
+ defaults?: { k?: number; maxSteps?: number; timeoutMinutes?: number };
+ /** The judge every attempt is graded with; fixed when the benchmark is made. */
+ judge?: { model: string; provider: string };
+ kind?: string;
+ /** Mock-side dataset segment and timeout; the address is server configuration, never stored here. */
+ mock?: { dataset?: string; timeoutMs?: number };
+ /** How every case is run (attempts, step limit, timeout); fixed when the benchmark is made. */
+ protocol?: LobeBenchProtocol;
+ /**
+ * A benchmark made of library cases (Hard 50): the engine view (frozen Pack Release)
+ * it was seeded from. Its runs are on the library, so the library's benchmark holds
+ * their judge, mock and defaults.
+ */
+ view?: { id: string; manifestSha256?: string; version: string };
+}
+
+/** A benchmark's fixed run rules: every case runs `k` attempts under these limits. */
+export interface LobeBenchProtocol {
+ k: number;
+ maxSteps: number;
+ timeoutMinutes: number;
+}
+
+const isProtocol = (value: unknown): value is LobeBenchProtocol => {
+ const v = value as Partial<LobeBenchProtocol> | undefined;
+ return (
+ !!v &&
+ Number.isInteger(v.k) &&
+ Number.isInteger(v.maxSteps) &&
+ Number.isInteger(v.timeoutMinutes) &&
+ v.k! >= 1 &&
+ v.maxSteps! >= 1 &&
+ v.timeoutMinutes! >= 1
+ );
+};
+
+/**
+ * The run rules a benchmark fixes: its `protocol`, or for one made before they
+ * were fixed, its complete `defaults` (the server reads them the same way).
+ */
+export const benchmarkProtocolOf = (
+ benchmark?: { metadata?: Metadata } | null,
+): LobeBenchProtocol | undefined => {
+ const meta = getBenchmarkMeta(benchmark);
+ const value = meta.protocol ?? meta.defaults;
+ return isProtocol(value)
+ ? { k: value.k, maxSteps: value.maxSteps, timeoutMinutes: value.timeoutMinutes }
+ : undefined;
+};
+
+/** The run rules a new benchmark starts the form with. */
+export const DEFAULT_PROTOCOL: LobeBenchProtocol = {
+ k: 3,
+ maxSteps: 30,
+ timeoutMinutes: 20,
+};
+
+export const getBenchmarkMeta = (benchmark?: { metadata?: Metadata } | null) =>
+ (benchmark?.metadata ?? {}) as LobeBenchBenchmarkMeta;
+
+/** A benchmark made of library cases (Hard 50), as opposed to the library's own benchmark. */
+export const isViewBenchmark = (benchmark?: { metadata?: Metadata } | null) =>
+ !!getBenchmarkMeta(benchmark).view;
+
+/** JSON with object keys in one order and unset fields left out, so equal settings give equal text. */
+export const stableJson = (value: unknown) =>
+ JSON.stringify(value, (_key, item) =>
+ item && typeof item === 'object' && !Array.isArray(item)
+ ? Object.fromEntries(
+ Object.entries(item as Record<string, unknown>)
+ .filter(([, field]) => field !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
+ )
+ : item,
+ );
+
+/** Two contenders are the same when their model and settings match, whatever the name. */
+export const sameContender = (a: LobeBenchContender, b: LobeBenchContender) =>
+ a.model === b.model &&
+ a.provider === b.provider &&
+ stableJson(a.params ?? {}) === stableJson(b.params ?? {}) &&
+ stableJson(a.chatConfig ?? {}) === stableJson(b.chatConfig ?? {});
+
+/** The saved list with these contenders added or refreshed (matched by id, then by setup). */
+export const upsertContenders = (
+ saved: LobeBenchContender[] | undefined,
+ added: LobeBenchContender[],
+): LobeBenchContender[] => {
+ const list = [...(saved ?? [])];
+ for (const contender of added) {
+ const { runId: _runId, ...entry } = contender;
+ const index = list.findIndex((item) => item.id === entry.id || sameContender(item, entry));
+ if (index === -1) list.push(entry);
+ // The same setup again keeps its saved id and name; an explicit edit
+ // (same id) takes the new values.
+ else if (list[index].id === entry.id) list[index] = { ...list[index], ...entry };
+ }
+ return list;
+};
+
+/**
+ * The saved list followed by the contenders past experiments ran that it does
+ * not have yet. A saved contender keeps its own name and settings: the copy an
+ * experiment recorded (same id) is from before any later edit.
+ */
+export const withRanContenders = (
+ saved: LobeBenchContender[] | undefined,
+ ran: LobeBenchContender[],
+): LobeBenchContender[] => {
+ const list = saved ?? [];
+ const extra = upsertContenders([], ran).filter(
+ (contender) => !list.some((item) => item.id === contender.id || sameContender(item, contender)),
+ );
+ return [...list, ...extra];
+};
+
+/**
+ * The list with a contender edited in place (same id); a list that does not
+ * hold it comes back as the same array, so a caller can tell nothing changed.
+ */
+export const replaceContender = (
+ list: LobeBenchContender[],
+ edited: LobeBenchContender,
+): LobeBenchContender[] =>
+ list.some((item) => item.id === edited.id)
+ ? list.map((item) => (item.id === edited.id ? edited : item))
+ : list;
+
+/** The datasets an experiment ran: its parts, or the one dataset an older experiment names. */
+export const experimentPartsOf = (meta: LobeBenchExperimentMeta): LobeBenchExperimentPart[] =>
+ meta.parts?.length
+ ? meta.parts
+ : [
+ {
+ caseIds: meta.caseIds,
+ datasetId: meta.datasetId,
+ pickedDatasetId: meta.pickedDatasetId,
+ runIds: Object.fromEntries(
+ meta.contenders.flatMap((c) => (c.runId ? [[c.id, c.runId] as const] : [])),
+ ),
+ },
+ ];
+
+/** The experiment as one of its parts: that dataset, its cases and each contender's run on it. */
+export const experimentPartMeta = <T extends LobeBenchExperimentMeta>(
+ meta: T,
+ part: LobeBenchExperimentPart,
+): T => ({
+ ...meta,
+ caseIds: part.caseIds,
+ contenders: meta.contenders.map((contender) => ({
+ ...contender,
+ runId: part.runIds?.[contender.id],
+ })),
+ datasetId: part.datasetId,
+ pickedDatasetId: part.pickedDatasetId,
+});
+
+export const isLobeBenchMeta = (
+ metadata: Metadata,
+): metadata is LobeBenchExperimentMeta & Record<string, unknown> =>
+ !!metadata && metadata.kind === LOBE_BENCH_KIND && Array.isArray(metadata.contenders);
+
+export const isLobeBenchBenchmark = (benchmark: { metadata?: Metadata }) =>
+ benchmark.metadata?.kind === LOBE_BENCH_KIND;
+
+export const isRunActive = (status?: string | null) => status === 'pending' || status === 'running';
+
+/**
+ * The model settings a contender can carry: what the chat model-params panel
+ * offers (per the model's `settings.extendParams`) and a run's chatConfig
+ * accepts, in the order their labels read.
+ */
+export const CONTENDER_SETTING_KEYS = [
+ 'enableReasoning',
+ 'enableAdaptiveThinking',
+ 'reasoningEffort',
+ 'gpt5ReasoningEffort',
+ 'gpt5_1ReasoningEffort',
+ 'gpt5_2ReasoningEffort',
+ 'gpt5_2ProReasoningEffort',
+ 'gpt5_6ReasoningEffort',
+ 'gpt6ReasoningEffort',
+ 'codexMaxReasoningEffort',
+ 'deepseekV4ReasoningEffort',
+ 'deepseekV4GAReasoningEffort',
+ 'glm5_2ReasoningEffort',
+ 'glm5_3ReasoningEffort',
+ 'grok4_3ReasoningEffort',
+ 'grok4_5ReasoningEffort',
+ 'grok4_6ReasoningEffort',
+ 'grok4_7ReasoningEffort',
+ 'grok4_20ReasoningEffort',
+ 'hy3ReasoningEffort',
+ 'kimiK3ReasoningEffort',
+ 'qwen38ReasoningEffort',
+ 'ring2_6ReasoningEffort',
+ 'step3_5ReasoningEffort',
+ 'effort',
+ 'opus47Effort',
+ 'reasoningMode',
+ 'reasoningBudgetToken',
+ 'reasoningBudgetToken32k',
+ 'reasoningBudgetToken80k',
+ 'thinking',
+ 'thinkingLevel',
+ 'thinkingLevel2',
+ 'thinkingLevel3',
+ 'thinkingLevel4',
+ 'thinkingBudget',
+ 'preserveThinking',
+ 'textVerbosity',
+ 'disableContextCaching',
+] as const satisfies readonly (keyof EvalRunChatConfig)[];
+
+/** Human-readable settings of a contender, e.g. "temperature 0.2 · reasoning high". */
+export const describeSettings = (
+ params?: EvalRunModelParams,
+ chatConfig?: EvalRunChatConfig,
+ labels?: { reasoning: string; temperature: string; topP: string },
+) => {
+ const parts: string[] = [];
+ if (params?.temperature !== undefined)
+ parts.push(`${labels?.temperature ?? 'temperature'} ${params.temperature}`);
+ if (params?.top_p !== undefined) parts.push(`${labels?.topP ?? 'top_p'} ${params.top_p}`);
+ if (params?.frequency_penalty !== undefined)
+ parts.push(`frequency penalty ${params.frequency_penalty}`);
+ if (params?.presence_penalty !== undefined)
+ parts.push(`presence penalty ${params.presence_penalty}`);
+ // Every setting a contender is told apart by shows, so two contenders of one
+ // model never carry the same default name.
+ const reasoning = labels?.reasoning ?? 'reasoning';
+ for (const key of CONTENDER_SETTING_KEYS) {
+ const value = chatConfig?.[key];
+ if (value === undefined || value === null) continue;
+ if (key === 'enableReasoning') parts.push(`${reasoning} ${value ? 'on' : 'off'}`);
+ else if (key === 'enableAdaptiveThinking')
+ parts.push(`adaptive thinking ${value ? 'on' : 'off'}`);
+ else if (key === 'disableContextCaching') {
+ if (value) parts.push('context caching off');
+ } else if (key === 'preserveThinking') parts.push(`keep thinking ${value ? 'on' : 'off'}`);
+ else if (/effort$/i.test(key)) parts.push(`${reasoning} ${value}`);
+ else if (key.startsWith('reasoningBudgetToken')) parts.push(`reasoning budget ${value}`);
+ else if (key === 'reasoningMode') parts.push(`${reasoning} mode ${value}`);
+ else if (key.startsWith('thinkingLevel')) parts.push(`thinking level ${value}`);
+ else if (key === 'thinkingBudget') parts.push(`thinking budget ${value}`);
+ else if (key === 'thinking') parts.push(`thinking ${value}`);
+ else if (key === 'textVerbosity') parts.push(`verbosity ${value}`);
+ }
+ return parts.join(' · ');
+};
+
+// ---------- cases ----------
+
+interface CaseLike {
+ content?: {
+ category?: string | null;
+ environment?: {
+ agent?: { plugins?: string[]; systemRole?: string };
+ memory?: unknown;
+ mock?: { services?: string[] };
+ sessionDate?: string;
+ timezone?: string;
+ toolForwarding?: Record<string, unknown>;
+ };
+ input?: string;
+ } | null;
+ evalConfig?: { judgePrompt?: string } | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ sortOrder?: number | null;
+}
+
+export const getCaseTitle = (testCase: CaseLike) => {
+ const title = testCase.metadata?.title;
+ if (typeof title === 'string' && title.trim()) return title.trim();
+ const firstLine = (testCase.content?.input ?? '').split('\n')[0].trim();
+ return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine || testCase.id;
+};
+
+export const getCaseCategory = (testCase: CaseLike, fallback = 'Other') => {
+ const category = testCase.metadata?.category ?? testCase.content?.category;
+ return typeof category === 'string' && category.trim() ? category.trim() : fallback;
+};
+
+export const getCaseIndex = (testCase: CaseLike) => {
+ const index = testCase.metadata?.index;
+ if (typeof index === 'number') return index;
+ return (testCase.sortOrder ?? 0) + 1;
+};
+
+/** Connectors the case runs against the mock (declared services, or the explicit forwarding table). */
+export const getCaseConnectors = (testCase: CaseLike): string[] => {
+ const environment = testCase.content?.environment;
+ const services = environment?.mock?.services ?? Object.keys(environment?.toolForwarding ?? {});
+ return services.filter((id) => !['lobe-creds', 'lobe-skill-store', 'lobe-skills'].includes(id));
+};
+
+export const getCaseRules = (testCase: CaseLike): string[] =>
+ (testCase.evalConfig?.judgePrompt ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+export {
+ type AttemptVerdict,
+ type CaseAttempt,
+ formatCost,
+ summarizeCaseResult,
+} from '@/features/LobeBench/caseResults';
+
+// ---------- runs ----------
+
+export interface RunStats {
+ active: boolean;
+ /** Cases that passed every attempt (pass^k). Equals `passed` when k = 1. */
+ allK?: number;
+ /** Cases that passed at least one attempt (pass@k). Equals `passed` when k = 1. */
+ anyK?: number;
+ avgMinutes?: number;
+ completed: number;
+ errors: number;
+ failed: number;
+ /** Attempts per case the run made. */
+ k: number;
+ passed: number;
+ passRate: number;
+ perCaseCost?: number;
+ total: number;
+ totalCost?: number;
+}
+
+const num = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+/**
+ * A run's headline numbers. With several attempts per case (k > 1) the pass
+ * rate counts a case only when every attempt passed (pass^k): the server's
+ * `passedCases` is pass@k (any attempt), which is kept as `anyK` for the
+ * secondary column.
+ */
+export const runStats = (run: AgentEvalRunListItem | undefined, totalCases?: number): RunStats => {
+ const metrics = (run?.metrics ?? {}) as Record<string, unknown>;
+ const k = num((run?.config as { k?: unknown } | null | undefined)?.k) ?? 1;
+ const total = num(metrics.totalCases) ?? totalCases ?? 0;
+ const anyK = num(metrics.passedCases) ?? 0;
+ const allKRatio = num(metrics.passAllK);
+ const allK = k > 1 ? (allKRatio === undefined ? undefined : Math.round(allKRatio * total)) : anyK;
+ const passed = k > 1 ? (allK ?? 0) : anyK;
+ const failed = num(metrics.failedCases) ?? 0;
+ const errors = num(metrics.errorCases) ?? 0;
+ const completed = num(metrics.completedCases) ?? anyK + failed + errors;
+ const totalDuration = num(metrics.totalDuration);
+ return {
+ active: isRunActive(run?.status),
+ allK,
+ anyK,
+ avgMinutes: totalDuration && completed ? totalDuration / completed / 60_000 : undefined,
+ completed,
+ errors,
+ failed,
+ k,
+ passRate: total ? passed / total : 0,
+ passed,
+ perCaseCost: num(metrics.perCaseCost),
+ total,
+ totalCost: num(metrics.totalCost) ?? num(metrics.cost),
+ };
+};
+
+export const formatPercent = (value: number) => `${Math.round(value * 100)}%`;
+
+// ---- The case library and datasets ------------------------------------------
+//
+// Lobe Bench follows the Evaluation Lab: a dataset holds its cases and a run
+// runs a dataset. The built-in case library is the dataset
+// "All cases" of the "Lobe Bench" benchmark. Hard 50 and the account's datasets
+// hold copies of library cases (`metadata.source = 'library'`), checked in the
+// library when the dataset is made and fixed from then on, so the runs on a
+// dataset stay true to it. A benchmark is made of datasets: a built-in one of
+// its published datasets, one the account made of the datasets moved into it.
+
+export interface LobeBenchDatasetMeta {
+ /** The account's own dataset, kept apart from the built-in library. */
+ custom?: boolean;
+ kind?: string;
+ /** How the bench engine renders the cases' tool results (part of their version). */
+ presentation?: string;
+ /** Provenance of a published set, e.g. the benchmark release it was imported from. */
+ release?: string;
+ /** A built-in dataset of library cases (Hard 50): the engine view (frozen Pack Release) it was seeded from. */
+ view?: { id: string; manifestSha256?: string; version: string };
+}
+
+interface DatasetLike {
+ benchmarkId?: string | null;
+ createdAt?: Date | string | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ name?: string;
+ testCaseCount?: number | null;
+}
+
+export const PRIMARY_BENCHMARK_IDENTIFIER = 'lobe-bench';
+
+export const getDatasetMeta = (dataset: DatasetLike): LobeBenchDatasetMeta =>
+ (dataset.metadata ?? {}) as LobeBenchDatasetMeta;
+
+export const isCustomDataset = (dataset: DatasetLike) => getDatasetMeta(dataset).custom === true;
+
+/** A built-in dataset of library cases seeded from an engine view (Hard 50), not the library itself. */
+export const isViewDataset = (dataset?: DatasetLike | null) =>
+ !!dataset && !!getDatasetMeta(dataset).view;
+
+/** How many cases a dataset runs: the cases it holds. */
+export const caseCountOf = (dataset?: DatasetLike | null) => dataset?.testCaseCount ?? 0;
+
+/** Built-in rows (the product's own case sets, environments) belong to no account: everyone reads them, nobody edits them. */
+export const isBuiltInRow = (row?: { userId?: string | null } | null) =>
+ !!row && row.userId == null;
+
+/** The built-in benchmark: its judge, mock service and defaults are set by whoever installed it. */
+export const isBuiltInBenchmark = (benchmark?: { isSystem?: boolean } | null) =>
+ benchmark?.isSystem === true;
+
+/** A benchmark the account made out of its own datasets. */
+export const isCustomBenchmark = (benchmark?: { isSystem?: boolean } | null) =>
+ !!benchmark && !isBuiltInBenchmark(benchmark);
+
+const createdTime = (dataset: DatasetLike) =>
+ dataset.createdAt ? new Date(dataset.createdAt).getTime() : 0;
+
+/** The case sets of one benchmark (or of all): published sets in creation order, the account's own sets last. */
+export const datasetsOf = <T extends DatasetLike>(datasets?: T[], benchmarkId?: string): T[] =>
+ (datasets ?? [])
+ .filter((d) => !benchmarkId || d.benchmarkId === benchmarkId)
+ .sort((a, b) => {
+ const ca = isCustomDataset(a) ? 1 : 0;
+ const cb = isCustomDataset(b) ? 1 : 0;
+ return ca - cb || createdTime(a) - createdTime(b);
+ });
+
+/** The account's own case sets under one benchmark (or all). */
+export const customDatasetsOf = <T extends DatasetLike>(
+ datasets?: T[],
+ benchmarkId?: string,
+): T[] => datasetsOf(datasets, benchmarkId).filter(isCustomDataset);
+
+/** The built-in case library: the published dataset every library case comes from (in one benchmark, or in any). */
+export const libraryOf = <T extends DatasetLike>(datasets?: T[], benchmarkId?: string) =>
+ datasetsOf(datasets, benchmarkId).find((d) => !isCustomDataset(d) && !isViewDataset(d));
+
+/**
+ * The datasets a benchmark is made of: a built-in benchmark's published datasets
+ * (the account's datasets filed under it are in no benchmark), or every dataset
+ * in a benchmark the account made.
+ */
+export const benchmarkDatasetsOf = <T extends DatasetLike>(
+ datasets: T[] | undefined,
+ benchmark: { id: string; isSystem?: boolean },
+) =>
+ datasetsOf(datasets, benchmark.id).filter(
+ (d) => isCustomBenchmark(benchmark) || !isCustomDataset(d),
+ );
+
+/** The account's datasets in no benchmark it made: the ones it can put into one. */
+export const looseDatasetsOf = <T extends DatasetLike>(
+ datasets: T[] | undefined,
+ benchmarks: Array<{ id: string; isSystem?: boolean }>,
+) =>
+ customDatasetsOf(datasets).filter(
+ (d) => !isCustomBenchmark(benchmarks.find((b) => b.id === d.benchmarkId)),
+ );
+
+/**
+ * What a benchmark's leaderboard ranks: one dataset it is made of, from the
+ * runs on all of its cases.
+ */
+export interface RankableSet {
+ /** The benchmark whose leaderboard this is. */
+ benchmarkId: string;
+ /** The current version of the dataset's cases; only runs on it rank. */
+ caseVersion?: string;
+ /** The dataset ranked on. */
+ id: string;
+ /** Attempts per case its benchmark runs: the leaderboard ranks on this many. */
+ k?: number;
+ /** The benchmark's name, with the dataset's when the benchmark has several. */
+ name: string;
+}
+
+/** One leaderboard per dataset a benchmark is made of, in the order the benchmarks are given. */
+export const rankableSetsOf = <T extends DatasetLike>(
+ benchmarks: Array<{ id: string; isSystem?: boolean; metadata?: Metadata; name: string }>,
+ datasets: T[] | undefined,
+): RankableSet[] =>
+ benchmarks.flatMap((benchmark) => {
+ const madeOf = benchmarkDatasetsOf(datasets, benchmark);
+ const k = benchmarkProtocolOf(benchmark)?.k;
+ return madeOf.map((dataset) => ({
+ benchmarkId: benchmark.id,
+ caseVersion: evalCaseVersionOf(dataset.metadata),
+ id: dataset.id,
+ ...(k && { k }),
+ name: madeOf.length > 1 ? `${benchmark.name} · ${dataset.name ?? ''}` : benchmark.name,
+ }));
+ });
+
+/** The set the overview ranks on and a new experiment starts from: the case library, else the first set. */
+export const pickDefaultDataset = <T extends DatasetLike>(
+ datasets?: T[],
+ benchmarkId?: string,
+): T | undefined => libraryOf(datasets, benchmarkId) ?? datasetsOf(datasets, benchmarkId)[0];
+
+/** The benchmark Lobe Bench is about when several carry its kind. */
+export const pickPrimaryBenchmark = <T extends { id: string; identifier?: string | null }>(
+ benchmarks: T[],
+): T | undefined =>
+ benchmarks.find((b) => b.identifier === PRIMARY_BENCHMARK_IDENTIFIER) ?? benchmarks[0];
+
+/**
+ * Benchmarks in the order Lobe Bench lists them: the library's own first, the
+ * other built-in ones next, then the account's; each group by age.
+ */
+export const sortBenchmarks = <
+ T extends {
+ createdAt?: Date | string | null;
+ id: string;
+ identifier?: string | null;
+ isSystem?: boolean;
+ },
+>(
+ benchmarks: T[],
+): T[] => {
+ // Only the real one: a list without it keeps age order instead of promoting its first row.
+ const primary = benchmarks.find((b) => b.identifier === PRIMARY_BENCHMARK_IDENTIFIER);
+ const rank = (b: T) => (b.id === primary?.id ? 0 : isBuiltInBenchmark(b) ? 1 : 2);
+ const time = (b: T) => (b.createdAt ? new Date(b.createdAt).getTime() : 0);
+ return [...benchmarks].sort((a, b) => rank(a) - rank(b) || time(a) - time(b));
+};
+
+/**
+ * The benchmark whose settings (judge, mock, experiment defaults) apply to a
+ * benchmark's runs: its own, or for one made of library cases (Hard 50, the
+ * account's) the library's.
+ */
+export const settingsBenchmarkOf = <
+ T extends { id: string; identifier?: string | null; isSystem?: boolean; metadata?: Metadata },
+>(
+ benchmarks: T[],
+ benchmarkId?: string,
+): T | undefined => {
+ const benchmark = benchmarks.find((b) => b.id === benchmarkId);
+ return benchmark && !isViewBenchmark(benchmark) && !isCustomBenchmark(benchmark)
+ ? benchmark
+ : pickPrimaryBenchmark(benchmarks);
+};
+
+/**
+ * An experiment is started on benchmarks, never on a dataset by itself: it runs
+ * every dataset each chosen benchmark is made of. A dataset in no benchmark (one
+ * the account picked, or its draft cases) is never run.
+ */
+export const datasetIdsOfBenchmarks = <T extends DatasetLike>(
+ datasets: T[] | undefined,
+ benchmarks: Array<{ id: string; isSystem?: boolean }>,
+ benchmarkIds: string[],
+): string[] =>
+ benchmarkIds.flatMap((id) => {
+ const benchmark = benchmarks.find((b) => b.id === id);
+ return benchmark ? benchmarkDatasetsOf(datasets, benchmark).map((d) => d.id) : [];
+ });
+
+/** The benchmarks a set of datasets belongs to, in the given benchmark order; a dataset in none counts for nothing. */
+export const benchmarkIdsOfDatasets = <T extends DatasetLike>(
+ datasets: T[] | undefined,
+ benchmarks: Array<{ id: string; isSystem?: boolean }>,
+ datasetIds: string[],
+): string[] =>
+ benchmarks
+ .filter((benchmark) =>
+ benchmarkDatasetsOf(datasets, benchmark).some((d) => datasetIds.includes(d.id)),
+ )
+ .map((benchmark) => benchmark.id);
+
+/** Case sets for a picker: per benchmark (primary first), published sets then the account's own. */
+export const orderDatasetsForPicker = <T extends DatasetLike>(
+ datasets: T[] | undefined,
+ benchmarks: Array<{ createdAt?: Date | string | null; id: string; identifier?: string | null }>,
+): T[] => {
+ // Primary first, then by age: the order the sidebar lists the benchmarks in.
+ return sortBenchmarks(benchmarks).flatMap((benchmark) => datasetsOf(datasets, benchmark.id));
+};
+
+// ---- Case selection --------------------------------------------------------
+
+interface SelectableCase {
+ id: string;
+ metadata?: Record<string, unknown> | null;
+}
+
+/** The id a run selects a case by: its dataset-native `metadata.caseId`, else its primary key. */
+export const nativeCaseId = (testCase: SelectableCase) => {
+ const caseId = testCase.metadata?.caseId;
+ return typeof caseId === 'string' && caseId ? caseId : testCase.id;
+};
+
+interface SelectableRun {
+ config?: { caseSelection?: { caseIds?: string[]; mode?: string } | null } | null;
+}
+
+/** A run on the whole case set, as opposed to one that picked some cases. Only these rank. */
+export const isFullRun = (run: SelectableRun) => {
+ const selection = run.config?.caseSelection;
+ return !selection || selection.mode === 'all' || !(selection.caseIds?.length ?? 0);
+};
+
+/** Whether a run counts for a leaderboard set: a run on that dataset, of all its cases. */
+export const runCoversSet = (
+ run: SelectableRun & { datasetId?: string | null },
+ set: Pick<RankableSet, 'id'>,
+) => run.datasetId === set.id && isFullRun(run);
+
+/** The version of the cases a run was made on (recorded by the server at creation). */
+export const runCaseVersion = (run: SelectableRun) =>
+ (run.config as { caseVersion?: unknown } | null | undefined)?.caseVersion;
+
+/**
+ * Whether a run was made on the set's current case version. Cases are edited in
+ * place, so a run on an earlier version (or one from before runs recorded it) is
+ * history, not a result on these cases.
+ */
+export const isRunOnCaseVersion = (run: SelectableRun, set: Pick<RankableSet, 'caseVersion'>) =>
+ !set.caseVersion || runCaseVersion(run) === set.caseVersion;
+
+/** How many of the set's cases the run covers. */
+export const runCaseCount = (run: SelectableRun, datasetCaseCount: number) => {
+ const selection = run.config?.caseSelection;
+ if (!selection || selection.mode === 'all') return datasetCaseCount;
+ const picked = selection.caseIds?.length ?? 0;
+ return selection.mode === 'include' ? picked : Math.max(datasetCaseCount - picked, 0);
+};
diff --git a/src/features/LobeBench/modelBrand.test.ts b/src/features/LobeBench/modelBrand.test.ts
new file mode 100644
index 00000000000..22aa3f4e888
--- /dev/null
+++ b/src/features/LobeBench/modelBrand.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { adaptBrandColor, findBrandColor } from '@/features/LobeBench/modelBrand';
+
+const mappings = [
+ { Icon: { colorPrimary: '#000' }, keywords: ['gpt-6', 'gpt-5'] },
+ { Icon: { colorPrimary: '#4D6BFE' }, keywords: ['deepseek'] },
+ { Icon: {}, keywords: ['mimo'] },
+];
+
+describe('findBrandColor', () => {
+ it('matches the first mapping whose keyword pattern appears in the model id', () => {
+ expect(findBrandColor(mappings, 'openrouter/deepseek/deepseek-v4.1-flash')).toBe('#4D6BFE');
+ expect(findBrandColor(mappings, 'GPT-6.1-sol')).toBe('#000');
+ });
+
+ it('returns nothing for unknown models, brands without a color, or no catalog yet', () => {
+ expect(findBrandColor(mappings, 'kimi-k2.6')).toBeUndefined();
+ expect(findBrandColor(mappings, 'mimo-v2.6-flash')).toBeUndefined();
+ expect(findBrandColor(undefined, 'deepseek-v4.1-flash')).toBeUndefined();
+ expect(findBrandColor(mappings, undefined)).toBeUndefined();
+ });
+});
+
+describe('adaptBrandColor', () => {
+ it('flips near-black and near-white brands to the theme ink and keeps the rest', () => {
+ expect(adaptBrandColor('#000', false)).toBe('#000000');
+ expect(adaptBrandColor('#000', true)).toBe('#ffffff');
+ expect(adaptBrandColor('#FFFFFF', false)).toBe('#000000');
+ expect(adaptBrandColor('#4D6BFE', true)).toBe('#4D6BFE');
+ });
+});
diff --git a/src/features/LobeBench/modelBrand.ts b/src/features/LobeBench/modelBrand.ts
new file mode 100644
index 00000000000..e4977307745
--- /dev/null
+++ b/src/features/LobeBench/modelBrand.ts
@@ -0,0 +1,34 @@
+/**
+ * Brand colors for the leaderboard's bars, the way LobeBench posters color
+ * them: each model's brand from `@lobehub/icons`, matched the way `ModelIcon`
+ * matches an icon (the first mapping with a keyword pattern in the model id).
+ */
+export interface BrandMapping {
+ Icon: unknown;
+ keywords: string[];
+}
+
+export const findBrandColor = (
+ mappings: readonly BrandMapping[] | undefined,
+ model: string | undefined,
+): string | undefined => {
+ if (!mappings || !model) return undefined;
+ const id = model.toLowerCase();
+ const hit = mappings.find((item) =>
+ item.keywords.some((keyword) => new RegExp(keyword, 'i').test(id)),
+ );
+ return (hit?.Icon as { colorPrimary?: string } | undefined)?.colorPrimary || undefined;
+};
+
+// lobe-design-ignore LOBE-RAW-COLOR: Parse provider brand-color data; these values are not interface theme tokens.
+const BLACKS = new Set(['#000', '#000000', 'black', 'rgb(0,0,0)', 'rgb(0, 0, 0)']);
+// lobe-design-ignore LOBE-RAW-COLOR: Parse provider brand-color data; these values are not interface theme tokens.
+const WHITES = new Set(['#fff', '#ffffff', 'white', 'rgb(255,255,255)', 'rgb(255, 255, 255)']);
+
+/** Flip near-black / near-white brands (OpenAI, xAI) so the bar shows on either theme. */
+export const adaptBrandColor = (color: string, isDarkMode: boolean) => {
+ const normalized = color.trim().toLowerCase();
+ // lobe-design-ignore LOBE-RAW-COLOR: Preserve the monochrome provider brand while adapting it to the current theme.
+ if (BLACKS.has(normalized) || WHITES.has(normalized)) return isDarkMode ? '#ffffff' : '#000000';
+ return color;
+};
diff --git a/src/features/LobeBench/overviewResults.test.ts b/src/features/LobeBench/overviewResults.test.ts
new file mode 100644
index 00000000000..066ac9efd62
--- /dev/null
+++ b/src/features/LobeBench/overviewResults.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ experimentCaseProgress,
+ isExperimentGradingComplete,
+ isRunGradingComplete,
+ isWorkspaceEmpty,
+ overviewAttention,
+ runGradingGap,
+} from './overviewResults';
+
+describe('overview grading completeness', () => {
+ it('finds legacy grading gaps even when execution marked every case completed', () => {
+ const run = {
+ status: 'completed',
+ metrics: { totalCases: 3, completedCases: 3, passedCases: 1, failedCases: 1 },
+ };
+ expect(runGradingGap(run)).toEqual({ judgeErrors: 0, external: 0, unaccounted: 1 });
+ expect(isRunGradingComplete(run)).toBe(false);
+ });
+
+ it('separates Judge faults and external grading without double-counting them as unknown gaps', () => {
+ const run = {
+ status: 'completed',
+ metrics: {
+ totalCases: 7,
+ passedCases: 1,
+ failedCases: 1,
+ errorCases: 1,
+ timeoutCases: 1,
+ judgeErrorCases: 1,
+ externalCases: 1,
+ },
+ };
+ expect(runGradingGap(run)).toEqual({ judgeErrors: 1, external: 1, unaccounted: 1 });
+ expect(isRunGradingComplete(run)).toBe(false);
+ });
+
+ it('uses case counts for K=2 completion, progress, and leaderboard eligibility', () => {
+ const run = {
+ config: { k: 2 },
+ status: 'completed',
+ metrics: { totalCases: 3, completedCases: 3, passedCases: 2, failedCases: 1 },
+ };
+ expect(runGradingGap(run)).toEqual({ judgeErrors: 0, external: 0, unaccounted: 0 });
+ expect(experimentCaseProgress([run])).toEqual({ done: 3, total: 3 });
+ expect(isRunGradingComplete(run)).toBe(true);
+ });
+
+ it('excludes incomplete, external, and Judge-failed runs before selecting leaderboard scores', () => {
+ const complete = { status: 'completed', metrics: { totalCases: 2, passedCases: 2 } };
+ const pending = { ...complete, status: 'running' };
+ const judge = {
+ status: 'completed',
+ metrics: { totalCases: 2, passedCases: 1, judgeErrorCases: 1 },
+ };
+ const external = {
+ status: 'completed',
+ metrics: { totalCases: 2, passedCases: 1, externalCases: 1 },
+ };
+ const legacy = {
+ status: 'completed',
+ metrics: { totalCases: 2, passedCases: 1, completedCases: 2 },
+ };
+ expect([complete, pending, judge, external, legacy].filter(isRunGradingComplete)).toEqual([
+ complete,
+ ]);
+ expect(isExperimentGradingComplete([complete])).toBe(true);
+ expect(experimentCaseProgress([complete])).toEqual({ done: 2, total: 2 });
+ for (const incomplete of [pending, judge, external, legacy])
+ expect(isExperimentGradingComplete([complete, incomplete])).toBe(false);
+ expect(isExperimentGradingComplete([])).toBe(false);
+ });
+
+ it('keeps gap counts finite and nonnegative with absent or corrupt metrics', () => {
+ expect(
+ runGradingGap({
+ metrics: { totalCases: 2, judgeErrorCases: NaN, externalCases: Infinity, failedCases: -5 },
+ }),
+ ).toEqual({ judgeErrors: 0, external: 0, unaccounted: 2 });
+ expect(runGradingGap({ metrics: { totalCases: 1, passedCases: 4 } }).unaccounted).toBe(0);
+ expect(runGradingGap({})).toEqual({ judgeErrors: 0, external: 0, unaccounted: 0 });
+ });
+
+ it('offers distinct attention reasons and does not label work still running as a historical grading gap', () => {
+ const attention = overviewAttention([
+ {
+ status: 'completed',
+ metrics: { totalCases: 4, errorCases: 1, judgeErrorCases: 1, externalCases: 1 },
+ },
+ { status: 'running', metrics: { totalCases: 5 } },
+ ]);
+ expect(attention).toEqual({ errors: 1, judgeErrors: 1, external: 1, unaccounted: 1 });
+ });
+ it('requires valid execution evidence as well as complete grading counts', () => {
+ const complete = {
+ status: 'completed',
+ metrics: { totalCases: 3, completedCases: 3, passedCases: 2, failedCases: 1 },
+ };
+ const invalid = [
+ { ...complete, metrics: { ...complete.metrics, failedCases: 0, errorCases: 1 } },
+ { ...complete, metrics: { ...complete.metrics, failedCases: 0, timeoutCases: 1 } },
+ { ...complete, hasUnverifiedAttempts: true, metrics: { ...complete.metrics, errorCases: 0 } },
+ ];
+ for (const run of invalid) {
+ expect(runGradingGap(run).unaccounted).toBe(0);
+ expect(experimentCaseProgress([run])).toEqual({ done: 3, total: 3 });
+ expect(isRunGradingComplete(run)).toBe(false);
+ expect(isExperimentGradingComplete([complete, run])).toBe(false);
+ }
+ expect(isRunGradingComplete({ ...complete, hasUnverifiedAttempts: false })).toBe(true);
+ });
+});
+
+describe('dashboard empty state', () => {
+ it('is empty only when there are no benchmarks, datasets or experiments', () => {
+ expect(isWorkspaceEmpty({ benchmarks: [], datasets: [], experiments: [] })).toBe(true);
+ // An import makes a dataset in no benchmark: the dashboard must still show it.
+ expect(isWorkspaceEmpty({ benchmarks: [], datasets: [{ id: 'ds' }], experiments: [] })).toBe(
+ false,
+ );
+ expect(isWorkspaceEmpty({ benchmarks: [], datasets: [], experiments: [{ id: 'exp' }] })).toBe(
+ false,
+ );
+ expect(isWorkspaceEmpty({ benchmarks: [], datasets: undefined, experiments: [] })).toBe(false);
+ });
+});
diff --git a/src/features/LobeBench/overviewResults.ts b/src/features/LobeBench/overviewResults.ts
new file mode 100644
index 00000000000..39ce8868c0d
--- /dev/null
+++ b/src/features/LobeBench/overviewResults.ts
@@ -0,0 +1,87 @@
+interface OverviewRun {
+ hasUnverifiedAttempts?: boolean;
+ metrics?: Record<string, unknown> | null;
+ status?: string | null;
+}
+
+const count = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0;
+
+/** Metrics count cases, including pass@k cases, never individual K attempts. */
+export const runGradingGap = (run: OverviewRun) => {
+ const metrics = run.metrics ?? {};
+ const judgeErrors = count(metrics.judgeErrorCases);
+ const external = count(metrics.externalCases);
+ const accounted = ['passedCases', 'failedCases', 'errorCases', 'timeoutCases'].reduce(
+ (sum, key) => sum + count(metrics[key]),
+ judgeErrors + external,
+ );
+ return {
+ external,
+ judgeErrors,
+ unaccounted: Math.max(0, count(metrics.totalCases) - accounted),
+ };
+};
+
+export const isRunGradingComplete = (run: OverviewRun) => {
+ const { external, judgeErrors, unaccounted } = runGradingGap(run);
+ return (
+ run.status === 'completed' &&
+ !run.hasUnverifiedAttempts &&
+ count(run.metrics?.errorCases) === 0 &&
+ count(run.metrics?.timeoutCases) === 0 &&
+ external === 0 &&
+ judgeErrors === 0 &&
+ unaccounted === 0
+ );
+};
+
+export const isExperimentGradingComplete = (runs: OverviewRun[]) =>
+ runs.length > 0 && runs.every(isRunGradingComplete);
+
+export const experimentCaseProgress = (runs: OverviewRun[]) =>
+ runs.reduce(
+ (progress, run) => ({
+ done:
+ progress.done +
+ (typeof run.metrics?.completedCases === 'number' &&
+ Number.isFinite(run.metrics.completedCases)
+ ? count(run.metrics.completedCases)
+ : Math.max(0, count(run.metrics?.totalCases) - runGradingGap(run).unaccounted)),
+ total: progress.total + count(run.metrics?.totalCases),
+ }),
+ { done: 0, total: 0 },
+ );
+
+/** Keep candidate failures and Judge recovery separate; running work is not a historical gap. */
+export const overviewAttention = (runs: OverviewRun[]) =>
+ runs.reduce(
+ (attention, run) => {
+ const gap = runGradingGap(run);
+ return {
+ errors: attention.errors + count(run.metrics?.errorCases),
+ external: attention.external + gap.external,
+ judgeErrors: attention.judgeErrors + gap.judgeErrors,
+ unaccounted:
+ attention.unaccounted +
+ (['pending', 'running'].includes(run.status ?? '') ? 0 : gap.unaccounted),
+ };
+ },
+ { errors: 0, external: 0, judgeErrors: 0, unaccounted: 0 },
+ );
+
+/**
+ * The dashboard is empty only when the account has nothing at all. An import
+ * makes a dataset in no benchmark, so having no benchmark is not "empty": the
+ * datasets and experiments still need their sections. While datasets load, it
+ * is not known to be empty.
+ */
+export const isWorkspaceEmpty = (state: {
+ benchmarks: readonly unknown[];
+ datasets: readonly unknown[] | undefined;
+ experiments: readonly unknown[];
+}) =>
+ state.benchmarks.length === 0 &&
+ state.datasets !== undefined &&
+ state.datasets.length === 0 &&
+ state.experiments.length === 0;
diff --git a/src/features/LobeBench/useDeleteExperiment.tsx b/src/features/LobeBench/useDeleteExperiment.tsx
new file mode 100644
index 00000000000..66d0beada9f
--- /dev/null
+++ b/src/features/LobeBench/useDeleteExperiment.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { confirmModal, toast } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { LOBE_BENCH_PATH } from '@/features/LobeBench/lobeBench';
+import { useLobeBenchExperiments } from '@/features/LobeBench/useLobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { agentEvalService } from '@/services/agentEval';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { forgetExperimentLaunch, isExperimentLaunching } from './launchBackground';
+
+interface DeleteExperimentOptions {
+ /** A run is still in flight: refuse and say to stop the experiment first. */
+ active?: boolean;
+ /** The experiment's own page is open: go back to the overview once it is gone. */
+ leave?: boolean;
+}
+
+/**
+ * Confirms and deletes an experiment the Lobe Bench way: the experiment owns its runs, so
+ * the runs, their per-case results and Judge verdicts go with it and the leaderboard is
+ * computed without them. Shared by the experiment page header and the sidebar row menu.
+ */
+export const useDeleteExperiment = () => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+ const userId = useUserStore(userProfileSelectors.userId);
+ const workspaceId = useActiveWorkspaceId();
+ const { mutate } = useLobeBenchExperiments();
+
+ return (
+ experiment: { id: string; name?: string | null },
+ { active, leave }: DeleteExperimentOptions = {},
+ ) => {
+ if (active || isExperimentLaunching(experiment.id)) {
+ toast.error(t('lobeBench.experiment.delete.active'));
+ return;
+ }
+ confirmModal({
+ content: t('lobeBench.experiment.delete.confirm', {
+ name: experiment.name || t('lobeBench.experiment.unnamed'),
+ }),
+ okButtonProps: { danger: true },
+ okText: t('common.delete'),
+ onOk: async () => {
+ if (isExperimentLaunching(experiment.id)) {
+ toast.error(t('lobeBench.experiment.delete.active'));
+ return;
+ }
+ const result = await agentEvalService.deleteExperiment(experiment.id, { withRuns: true });
+ if (result.success === false) {
+ toast.error(result.error || t('lobeBench.experiment.delete.failed'));
+ return;
+ }
+ if (userId) forgetExperimentLaunch(userId, workspaceId, experiment.id);
+ toast.success(t('lobeBench.experiment.delete.done'));
+ await mutate();
+ if (leave) navigate(LOBE_BENCH_PATH);
+ },
+ title: t('lobeBench.experiment.delete'),
+ });
+ };
+};
diff --git a/src/features/LobeBench/useExperimentActions.test.ts b/src/features/LobeBench/useExperimentActions.test.ts
new file mode 100644
index 00000000000..176b1cddeb5
--- /dev/null
+++ b/src/features/LobeBench/useExperimentActions.test.ts
@@ -0,0 +1,165 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useExperimentActions } from './useExperimentActions';
+
+const service = vi.hoisted(() => ({
+ abortRun: vi.fn(),
+ rerunRunUnverified: vi.fn(),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('@/services/agentEval', () => ({ agentEvalService: service }));
+vi.mock('@lobehub/ui', () => ({ toast }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values: unknown) => `${key}:${JSON.stringify(values)}`,
+ }),
+}));
+
+const options = () => ({
+ experimentId: 'experiment',
+ onRerunStarted: vi.fn(),
+ refreshResults: vi.fn().mockResolvedValue(undefined),
+ refreshRuns: vi.fn().mockResolvedValue(undefined),
+ targets: [
+ { runId: 'a', name: 'Model A', status: 'completed', unverified: 2 },
+ { runId: 'b', name: 'Model B', status: 'completed', unverified: 1 },
+ ],
+});
+
+describe('useExperimentActions', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ it('offers a rerun only for finished runs with an attempt without a verdict', async () => {
+ const props = options();
+ props.targets = [
+ { runId: 'a', name: 'Model A', status: 'completed', unverified: 0 },
+ { runId: 'b', name: 'Model B', status: 'running', unverified: 3 },
+ ];
+ const { result } = renderHook(() => useExperimentActions(props));
+ expect(result.current.canRerun).toBe(false);
+ expect(result.current.rerunCases).toBe(0);
+ await act(() => result.current.rerun());
+ expect(service.rerunRunUnverified).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('counts the cases a rerun covers and reports per-run outcomes', async () => {
+ const props = options();
+ props.refreshRuns.mockRejectedValue(new Error('Refresh unavailable'));
+ service.rerunRunUnverified.mockImplementation((id: string) =>
+ id === 'a'
+ ? Promise.resolve({ rerunCount: 2, runId: 'a', success: true })
+ : Promise.reject(new Error('Dispatch unavailable')),
+ );
+ const { result } = renderHook(() => useExperimentActions(props));
+ expect(result.current.rerunCases).toBe(3);
+ await act(() => result.current.rerun());
+ expect(service.rerunRunUnverified.mock.calls.map(([id]) => id)).toEqual(['a', 'b']);
+ // SWR mutate(undefined) writes to the cache; revalidation must receive no arguments.
+ expect(props.refreshRuns).toHaveBeenCalledTimes(1);
+ expect(props.refreshRuns.mock.calls[0]).toEqual([]);
+ expect(props.refreshResults).toHaveBeenCalledTimes(1);
+ expect(props.refreshResults.mock.calls[0]).toEqual([]);
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('Model A'));
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('"count":2'));
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('action.rerunFailed'));
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Model B'));
+ expect(props.onRerunStarted).toHaveBeenCalledTimes(1);
+ expect(result.current.busy).toBe(false);
+ });
+
+ it('does not start polling when nothing was dispatched', async () => {
+ const props = options();
+ service.rerunRunUnverified.mockRejectedValue(new Error('Dispatch unavailable'));
+ const { result } = renderHook(() => useExperimentActions(props));
+ await act(() => result.current.rerun());
+ expect(props.onRerunStarted).not.toHaveBeenCalled();
+ expect(props.refreshRuns).toHaveBeenCalledTimes(1);
+ expect(props.refreshResults).toHaveBeenCalledTimes(1);
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('tells a run that is still running apart from other failures', async () => {
+ const props = options();
+ service.rerunRunUnverified.mockImplementation((id: string) =>
+ id === 'a'
+ ? Promise.reject(new Error('Cannot rerun a running run'))
+ : Promise.resolve({ rerunCount: 1, runId: 'b', success: true }),
+ );
+ const { result } = renderHook(() => useExperimentActions(props));
+ await act(() => result.current.rerun());
+ expect(toast.error).toHaveBeenCalledTimes(1);
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('action.stillRunning'));
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('Model B'));
+ });
+
+ it('shares one busy guard across rerun and stop, including same-tick clicks', async () => {
+ let finish!: (value: { rerunCount: number }) => void;
+ service.rerunRunUnverified.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useExperimentActions(options()));
+ let request!: Promise<void>;
+ act(() => {
+ request = result.current.rerun();
+ void result.current.stop();
+ void result.current.rerun();
+ });
+ expect(result.current.busy).toBe(true);
+ expect(result.current.pendingAction).toBe('rerun');
+ expect(service.rerunRunUnverified).toHaveBeenCalledTimes(2);
+ expect(service.abortRun).not.toHaveBeenCalled();
+ await act(async () => {
+ finish({ rerunCount: 1 });
+ await request;
+ });
+ expect(result.current.busy).toBe(false);
+ });
+
+ it('refreshes both datasets when stopping a batch partially fails', async () => {
+ const props = options();
+ props.targets = props.targets.map((target) => ({ ...target, status: 'running' }));
+ service.abortRun.mockImplementation((id: string) =>
+ id === 'a'
+ ? Promise.resolve({ success: true })
+ : Promise.reject(new Error('Stop unavailable')),
+ );
+ const { result } = renderHook(() => useExperimentActions(props));
+ expect(result.current.canRerun).toBe(false);
+ await act(() => result.current.stop());
+ expect(props.refreshRuns).toHaveBeenCalledTimes(1);
+ expect(props.refreshResults).toHaveBeenCalledTimes(1);
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('Model A'));
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Model B'));
+ });
+
+ it('ignores a response that arrives after switching to another experiment', async () => {
+ const props = options();
+ let finish!: (value: { rerunCount: number }) => void;
+ service.rerunRunUnverified.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result, rerender } = renderHook((value) => useExperimentActions(value), {
+ initialProps: props,
+ });
+ let request!: Promise<void>;
+ act(() => {
+ request = result.current.rerun();
+ });
+ rerender({ ...props, experimentId: 'another-experiment' });
+ await act(async () => {
+ finish({ rerunCount: 1 });
+ await request;
+ });
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(props.onRerunStarted).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/LobeBench/useExperimentActions.ts b/src/features/LobeBench/useExperimentActions.ts
new file mode 100644
index 00000000000..7174c971aac
--- /dev/null
+++ b/src/features/LobeBench/useExperimentActions.ts
@@ -0,0 +1,131 @@
+import { toast } from '@lobehub/ui';
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+
+type ExperimentAction = 'rerun' | 'stop';
+interface ActionTarget {
+ name: string;
+ runId: string;
+ status: string;
+ /** Cases with an attempt that has no verdict; Rerun runs them again. */
+ unverified: number;
+}
+interface ExperimentActionsOptions {
+ experimentId?: string;
+ onRerunStarted: () => void;
+ refreshResults: () => Promise<unknown>;
+ refreshRuns: () => Promise<unknown>;
+ targets: ActionTarget[];
+}
+
+const isActive = (target: ActionTarget) => ['pending', 'running'].includes(target.status);
+const isFinished = (target: ActionTarget) =>
+ ['completed', 'failed', 'aborted'].includes(target.status);
+
+/**
+ * The experiment's two run-state actions, sent to every contender's run at once:
+ * Rerun (cases without a verdict run again) and Stop. Per-run outcomes are
+ * kept apart in the toasts, then both the summary and the evidence refresh.
+ */
+export const useExperimentActions = ({
+ experimentId,
+ onRerunStarted,
+ refreshResults,
+ refreshRuns,
+ targets,
+}: ExperimentActionsOptions) => {
+ const { t } = useTranslation('eval');
+ const [pendingAction, setPendingAction] = useState<ExperimentAction>();
+ const pendingRef = useRef<ExperimentAction | undefined>(undefined);
+ const currentExperiment = useRef(experimentId);
+ useEffect(() => {
+ currentExperiment.current = experimentId;
+ }, [experimentId]);
+
+ const rerunTargets = targets.filter((target) => target.unverified > 0 && isFinished(target));
+
+ const execute = async (action: ExperimentAction, selected: ActionTarget[]) => {
+ if (pendingRef.current || !selected.length) return;
+ pendingRef.current = action;
+ setPendingAction(action);
+ let rerunStarted = false;
+ try {
+ const outcomes = await Promise.allSettled(
+ selected.map((target) =>
+ action === 'rerun'
+ ? agentEvalService.rerunRunUnverified(target.runId)
+ : agentEvalService.abortRun(target.runId),
+ ),
+ );
+ const succeeded: string[] = [];
+ const failed: ActionTarget[] = [];
+ const stillRunning: ActionTarget[] = [];
+ let rerunCases = 0;
+ outcomes.forEach((outcome, index) => {
+ const target = selected[index];
+ if (outcome.status === 'fulfilled') {
+ succeeded.push(target.name);
+ const value = outcome.value as { rerunCount?: number } | null;
+ rerunCases += typeof value?.rerunCount === 'number' ? value.rerunCount : 0;
+ return;
+ }
+ failed.push(target);
+ const message = outcome.reason instanceof Error ? outcome.reason.message : '';
+ if (/status=(?:running|pending)|Cannot rerun a (?:running|pending) run/.test(message)) {
+ stillRunning.push(target);
+ }
+ console.error(`[LobeBench] ${action} failed for ${target.runId}`, outcome.reason);
+ });
+ if (currentExperiment.current !== experimentId) return;
+ rerunStarted = action === 'rerun' && rerunCases > 0;
+ if (succeeded.length) {
+ toast.success(
+ t(
+ action === 'rerun'
+ ? 'lobeBench.dashboard.action.rerunSuccess'
+ : 'lobeBench.dashboard.action.stopSuccess',
+ { count: rerunCases, models: succeeded.join(', ') },
+ ),
+ );
+ }
+ if (stillRunning.length) {
+ toast.error(
+ t('lobeBench.dashboard.action.stillRunning', {
+ models: stillRunning.map((target) => target.name).join(', '),
+ }),
+ );
+ }
+ const otherFailures = failed.filter((target) => !stillRunning.includes(target));
+ if (otherFailures.length) {
+ toast.error(
+ t(
+ action === 'rerun'
+ ? 'lobeBench.dashboard.action.rerunFailed'
+ : 'lobeBench.dashboard.action.failed',
+ { models: otherFailures.map((target) => target.name).join(', ') },
+ ),
+ );
+ }
+ } finally {
+ await Promise.allSettled([
+ Promise.resolve().then(() => refreshRuns()),
+ Promise.resolve().then(() => refreshResults()),
+ ]);
+ if (rerunStarted && currentExperiment.current === experimentId) onRerunStarted();
+ pendingRef.current = undefined;
+ setPendingAction(undefined);
+ }
+ };
+
+ return {
+ busy: pendingAction !== undefined,
+ canRerun: rerunTargets.length > 0,
+ pendingAction,
+ rerun: () => execute('rerun', rerunTargets),
+ /** Cases the rerun would run again, across the eligible contenders. */
+ rerunCases: rerunTargets.reduce((sum, target) => sum + target.unverified, 0),
+ stop: () => execute('stop', targets.filter(isActive)),
+ };
+};
diff --git a/src/features/LobeBench/useExperimentDraft.test.ts b/src/features/LobeBench/useExperimentDraft.test.ts
new file mode 100644
index 00000000000..5015f99693b
--- /dev/null
+++ b/src/features/LobeBench/useExperimentDraft.test.ts
@@ -0,0 +1,236 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type ExperimentDraft,
+ experimentDraftKey,
+ getInvalidDraftSelections,
+ parseExperimentDraft,
+} from './experimentDraft';
+import { useExperimentDraft } from './useExperimentDraft';
+
+const initial = (benchmarkId: string): ExperimentDraft => ({
+ contenders: [],
+ datasetId: `dataset-${benchmarkId}`,
+ k: 1,
+ maxSteps: 30,
+ name: '',
+ pickCases: false,
+ pickedCaseIds: [],
+ question: '',
+ timeoutMinutes: 20,
+});
+const contender = {
+ id: 'contender-1',
+ model: 'model-1',
+ name: 'Model one',
+ provider: 'provider-1',
+};
+const options = {
+ benchmarkIds: ['bench-1', 'bench-2'],
+ getInitialDraft: initial,
+ initialBenchmarkId: 'bench-1',
+ ready: true,
+ userId: 'user-1',
+ workspaceId: null as string | null,
+};
+const key = experimentDraftKey({ benchmarkId: 'bench-1', userId: 'user-1', workspaceId: null });
+
+describe('useExperimentDraft', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('restores the whole form after leaving the route or reloading', () => {
+ const first = renderHook(() => useExperimentDraft(options));
+ act(() =>
+ first.result.current.updateDraft({
+ contenders: [
+ { ...contender, params: { temperature: 0.7 }, chatConfig: { reasoningEffort: 'high' } },
+ ],
+ judge: { model: 'judge-1', provider: 'provider-1' },
+ k: 3,
+ maxSteps: 50,
+ name: 'My experiment',
+ pickCases: true,
+ pickedCaseIds: ['4'],
+ question: 'Can this model do the task?',
+ timeoutMinutes: 40,
+ }),
+ );
+ const before = first.result.current.draft;
+ // The write is already durable before unmount; no cleanup or debounce is needed.
+ expect(JSON.parse(localStorage.getItem(key)!)).toEqual(before);
+ first.unmount();
+ const second = renderHook(() => useExperimentDraft(options));
+ expect(second.result.current.draft).toEqual(before);
+ expect(second.result.current.restored).toBe(true);
+ });
+
+ it('waits for account and datasets before restoring, without overwriting the saved form', () => {
+ localStorage.setItem(key, JSON.stringify({ ...initial('bench-1'), name: 'Saved' }));
+ const { result, rerender } = renderHook((props) => useExperimentDraft(props), {
+ initialProps: { ...options, ready: false, userId: undefined as string | undefined },
+ });
+ expect(result.current.ready).toBe(false);
+ act(() => result.current.updateDraft({ name: 'Too early' }));
+ expect(JSON.parse(localStorage.getItem(key)!).name).toBe('Saved');
+ rerender({ ...options, ready: true });
+ expect(result.current.draft?.name).toBe('Saved');
+ });
+
+ it('isolates drafts when the active account or workspace changes', () => {
+ const { result, rerender } = renderHook((props) => useExperimentDraft(props), {
+ initialProps: options,
+ });
+ act(() => result.current.updateDraft({ name: 'Private draft' }));
+ rerender({ ...options, userId: 'user-2' });
+ expect(result.current.draft?.name).toBe('');
+ act(() => result.current.updateDraft({ name: 'Other user' }));
+ rerender({ ...options, workspaceId: 'workspace-2' });
+ expect(result.current.draft?.name).toBe('');
+ act(() => result.current.updateDraft({ name: 'Team draft' }));
+ rerender(options);
+ expect(result.current.draft?.name).toBe('Private draft');
+ });
+
+ it('keeps separate benchmark drafts and restores the last selected benchmark on return', () => {
+ const first = renderHook(() => useExperimentDraft(options));
+ act(() => first.result.current.updateDraft({ name: 'First benchmark' }));
+ act(() => first.result.current.selectDataset('bench-2', 'dataset-bench-2'));
+ expect(first.result.current.draft?.name).toBe('');
+ act(() => first.result.current.updateDraft({ name: 'Second benchmark' }));
+ first.unmount();
+ const second = renderHook(() => useExperimentDraft(options));
+ expect(second.result.current.draft?.name).toBe('Second benchmark');
+ act(() => second.result.current.selectDataset('bench-1', 'dataset-bench-1'));
+ expect(second.result.current.draft?.name).toBe('First benchmark');
+ });
+
+ it('honors an explicit dataset URL while never applying another dataset’s picked IDs', () => {
+ localStorage.setItem(
+ key,
+ JSON.stringify({
+ ...initial('bench-1'),
+ name: 'Saved',
+ pickCases: true,
+ pickedCaseIds: ['old-case'],
+ }),
+ );
+ const { result } = renderHook(() =>
+ useExperimentDraft({ ...options, presetDatasetId: 'dataset-new' }),
+ );
+ expect(result.current.draft).toMatchObject({
+ datasetId: 'dataset-new',
+ name: 'Saved',
+ pickCases: true,
+ pickedCaseIds: [],
+ });
+ // Reading a different entry point does not destroy the existing draft.
+ expect(JSON.parse(localStorage.getItem(key)!).pickedCaseIds).toEqual(['old-case']);
+ });
+
+ it('keeps failed or unfinished starts and clears only on explicit success or discard', () => {
+ const { result, unmount } = renderHook(() => useExperimentDraft(options));
+ act(() => result.current.updateDraft({ name: 'Retry this experiment' }));
+ // An unsuccessful API request never calls clearDraft, so its inputs survive.
+ expect(JSON.parse(localStorage.getItem(key)!).name).toBe('Retry this experiment');
+ act(() => result.current.clearDraft());
+ expect(localStorage.getItem(key)).toBeNull();
+ unmount();
+ const next = renderHook(() => useExperimentDraft(options));
+ expect(next.result.current.draft?.name).toBe('');
+ act(() => next.result.current.updateDraft({ name: 'Discard this' }));
+ act(() => next.result.current.clearDraft(true));
+ expect(next.result.current.draft).toEqual(initial('bench-1'));
+ expect(localStorage.getItem(key)).toBeNull();
+ });
+
+ it('does not reapply another benchmark’s URL preset after discarding a switched draft', () => {
+ const { result } = renderHook(() =>
+ useExperimentDraft({ ...options, presetDatasetId: 'preset-bench-1' }),
+ );
+ act(() => result.current.selectDataset('bench-2', 'dataset-bench-2'));
+ act(() => result.current.updateDraft({ name: 'Discard second benchmark' }));
+ act(() => result.current.clearDraft(true));
+ expect(result.current.draft).toEqual(initial('bench-2'));
+ });
+
+ it('retains in-memory input and exposes a storage failure instead of throwing', () => {
+ const { result } = renderHook(() => useExperimentDraft(options));
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('Quota exceeded');
+ });
+ act(() => result.current.updateDraft({ name: 'Do not lose this' }));
+ expect(result.current.draft?.name).toBe('Do not lose this');
+ expect(result.current.storageError).toBe(true);
+ });
+});
+
+describe('experiment draft validation', () => {
+ it('ignores corrupt or incompatible storage and strips unrelated execution fields', () => {
+ expect(parseExperimentDraft('{')).toBeUndefined();
+ expect(parseExperimentDraft(JSON.stringify({ name: 1 }))).toBeUndefined();
+ expect(
+ parseExperimentDraft(
+ JSON.stringify({
+ ...initial('bench-1'),
+ contenders: [{ ...contender, runId: 'run-1' }],
+ secret: 'not-a-form-field',
+ }),
+ ),
+ ).toEqual({ ...initial('bench-1'), contenders: [contender] });
+ });
+
+ it("keeps every contender setting, so a restored draft runs the model's newer reasoning effort", () => {
+ const gpt = {
+ ...contender,
+ chatConfig: { gpt6ReasoningEffort: 'high' as const },
+ name: 'GPT-6.1 Sol · reasoning high',
+ };
+ const deepseek = {
+ ...contender,
+ chatConfig: { deepseekV4GAReasoningEffort: 'max' as const },
+ id: 'contender-2',
+ };
+ const draft = { ...initial('bench-1'), contenders: [gpt, deepseek] };
+ expect(parseExperimentDraft(JSON.stringify(draft))).toEqual(draft);
+ });
+
+ it('drops chat settings a contender cannot carry', () => {
+ const stored = { ...contender, chatConfig: { enableReasoning: true, systemRole: 'x' } };
+ expect(
+ parseExperimentDraft(JSON.stringify({ ...initial('bench-1'), contenders: [stored] }))
+ ?.contenders[0].chatConfig,
+ ).toEqual({ enableReasoning: true });
+ });
+
+ it('identifies missing cases and unavailable model capabilities without changing the draft', () => {
+ const draft: ExperimentDraft = {
+ ...initial('bench-1'),
+ contenders: [contender],
+ judge: { model: 'judge-1', provider: 'provider-1' },
+ pickCases: true,
+ pickedCaseIds: ['valid', 'removed'],
+ };
+ const unavailable = getInvalidDraftSelections(
+ draft,
+ ['valid'],
+ [{ model: 'model-1', provider: 'provider-1', supportsTools: false }],
+ );
+ expect(unavailable).toEqual({ caseIds: ['removed'], contenders: [contender], judge: true });
+ expect(draft.pickedCaseIds).toEqual(['valid', 'removed']);
+ expect(draft.pickCases).toBe(true);
+ expect(
+ getInvalidDraftSelections(
+ draft,
+ ['valid', 'removed'],
+ [
+ { model: 'model-1', provider: 'provider-1', supportsTools: true },
+ { model: 'judge-1', provider: 'provider-1', supportsTools: false },
+ ],
+ ),
+ ).toEqual({ caseIds: [], contenders: [], judge: false });
+ });
+});
diff --git a/src/features/LobeBench/useExperimentDraft.ts b/src/features/LobeBench/useExperimentDraft.ts
new file mode 100644
index 00000000000..a66d6a0682b
--- /dev/null
+++ b/src/features/LobeBench/useExperimentDraft.ts
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from 'react';
+
+import {
+ applyPresetDataset,
+ type ExperimentDraft,
+ experimentDraftKey,
+ experimentDraftLocationKey,
+ parseExperimentDraft,
+} from './experimentDraft';
+
+interface DraftOptions {
+ benchmarkIds: string[];
+ getInitialDraft: (benchmarkId: string) => ExperimentDraft;
+ initialBenchmarkId?: string;
+ presetDatasetId?: string | null;
+ ready: boolean;
+ userId?: string;
+ workspaceId: string | null;
+}
+
+interface DraftSession {
+ benchmarkId: string;
+ context: string;
+ draft: ExperimentDraft;
+ restored: boolean;
+ storageError: boolean;
+}
+
+export const useExperimentDraft = (options: DraftOptions) => {
+ const { initialBenchmarkId, presetDatasetId, ready, userId, workspaceId } = options;
+ const context =
+ userId && initialBenchmarkId
+ ? JSON.stringify([userId, workspaceId, initialBenchmarkId, presetDatasetId ?? null])
+ : undefined;
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+ const sessionRef = useRef<DraftSession | undefined>(undefined);
+ const [session, setSession] = useState<DraftSession>();
+
+ const publish = (next: DraftSession) => {
+ sessionRef.current = next;
+ setSession(next);
+ };
+
+ const readDraft = (
+ benchmarkId: string,
+ datasetId?: string | null,
+ ): Pick<DraftSession, 'draft' | 'restored' | 'storageError'> => {
+ const initial = optionsRef.current.getInitialDraft(benchmarkId);
+ try {
+ const stored = parseExperimentDraft(
+ localStorage.getItem(experimentDraftKey({ benchmarkId, userId: userId!, workspaceId })),
+ );
+ return {
+ draft: applyPresetDataset(stored ?? initial, datasetId),
+ restored: !!stored,
+ storageError: false,
+ };
+ } catch {
+ return { draft: applyPresetDataset(initial, datasetId), restored: false, storageError: true };
+ }
+ };
+
+ useEffect(() => {
+ if (
+ !ready ||
+ !context ||
+ !initialBenchmarkId ||
+ !userId ||
+ sessionRef.current?.context === context
+ )
+ return;
+ let benchmarkId = initialBenchmarkId;
+ let storageError = false;
+ // Remember the last edited benchmark so a generic Back/reload restores the same form.
+ if (!presetDatasetId) {
+ try {
+ const previous = localStorage.getItem(experimentDraftLocationKey(userId, workspaceId));
+ if (previous && optionsRef.current.benchmarkIds.includes(previous)) benchmarkId = previous;
+ } catch {
+ storageError = true;
+ }
+ }
+ const restored = readDraft(benchmarkId, presetDatasetId);
+ publish({
+ ...restored,
+ benchmarkId,
+ context,
+ storageError: storageError || restored.storageError,
+ });
+ }, [context, initialBenchmarkId, presetDatasetId, ready, userId, workspaceId]);
+
+ const current = session?.context === context ? session : undefined;
+ const updateDraft = (
+ update: Partial<ExperimentDraft> | ((draft: ExperimentDraft) => ExperimentDraft),
+ ) => {
+ const previous = sessionRef.current;
+ if (!previous || previous.context !== context || !userId) return;
+ const draft =
+ typeof update === 'function' ? update(previous.draft) : { ...previous.draft, ...update };
+ let storageError = false;
+ try {
+ // Save in the event, before navigation can unmount this page.
+ localStorage.setItem(
+ experimentDraftKey({ benchmarkId: previous.benchmarkId, userId, workspaceId }),
+ JSON.stringify(draft),
+ );
+ localStorage.setItem(experimentDraftLocationKey(userId, workspaceId), previous.benchmarkId);
+ } catch {
+ storageError = true;
+ }
+ publish({ ...previous, draft, storageError });
+ };
+
+ const selectDataset = (benchmarkId: string, datasetId: string) => {
+ const previous = sessionRef.current;
+ if (!previous || previous.context !== context) return;
+ if (benchmarkId !== previous.benchmarkId) {
+ publish({ ...readDraft(benchmarkId, datasetId), benchmarkId, context: previous.context });
+ }
+ updateDraft((draft) => applyPresetDataset(draft, datasetId));
+ };
+
+ /** Call only after all runs have started, or when the user explicitly discards the draft. */
+ const clearDraft = (reset = false) => {
+ const previous = sessionRef.current;
+ if (!previous || previous.context !== context || !userId) return;
+ let storageError = false;
+ try {
+ localStorage.removeItem(
+ experimentDraftKey({ benchmarkId: previous.benchmarkId, userId, workspaceId }),
+ );
+ localStorage.removeItem(experimentDraftLocationKey(userId, workspaceId));
+ } catch {
+ storageError = true;
+ }
+ publish({
+ ...previous,
+ draft: reset
+ ? applyPresetDataset(
+ optionsRef.current.getInitialDraft(previous.benchmarkId),
+ previous.benchmarkId === initialBenchmarkId ? presetDatasetId : undefined,
+ )
+ : previous.draft,
+ restored: false,
+ storageError,
+ });
+ };
+
+ return {
+ clearDraft,
+ draft: current?.draft,
+ ready: !!current,
+ restored: current?.restored ?? false,
+ selectDataset,
+ storageError: current?.storageError ?? false,
+ updateDraft,
+ };
+};
diff --git a/src/features/LobeBench/useExperimentLaunch.test.ts b/src/features/LobeBench/useExperimentLaunch.test.ts
new file mode 100644
index 00000000000..5795e9d6fd9
--- /dev/null
+++ b/src/features/LobeBench/useExperimentLaunch.test.ts
@@ -0,0 +1,119 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createExperimentLaunch, experimentLaunchKey } from './experimentLaunch';
+import { useExperimentLaunch } from './useExperimentLaunch';
+
+const options = { benchmarkId: 'bench-1', userId: 'user-1', workspaceId: null as string | null };
+const key = experimentLaunchKey({ benchmarkId: 'bench-1', userId: 'user-1', workspaceId: null });
+const snapshot = () => ({
+ benchmarkId: 'bench-1',
+ contenders: [{ config: { model: 'm' }, id: 'c-a', name: 'A' }],
+ datasetId: 'ds-1',
+ metadata: { contenders: [{ id: 'c-a' }] },
+ name: 'A',
+});
+
+describe('useExperimentLaunch', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('begins a launch, keeps it across remounts, and clears only that experiment', async () => {
+ const launch = createExperimentLaunch(snapshot());
+ const first = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(first.result.current.ready).toBe(true));
+
+ await act(async () => {
+ expect(await first.result.current.begin(launch)).toEqual({ ok: true });
+ });
+ expect(first.result.current.launch).toEqual(launch);
+
+ const second = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(second.result.current.launch).toEqual(launch));
+
+ await act(async () => {
+ expect(await second.result.current.clear('exp_other')).toBe(false);
+ });
+ expect(second.result.current.launch).toEqual(launch);
+ await act(async () => {
+ expect(await second.result.current.clear(launch.experimentId)).toBe(true);
+ });
+ expect(second.result.current.launch).toBeUndefined();
+ expect(localStorage.getItem(key)).toBeNull();
+ });
+
+ it('does not overwrite a launch another tab began, and shows that one instead', async () => {
+ const theirs = createExperimentLaunch(snapshot());
+ localStorage.setItem(key, JSON.stringify(theirs));
+ const { result } = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(result.current.launch).toEqual(theirs));
+
+ const mine = createExperimentLaunch(snapshot());
+ await act(async () => {
+ expect(await result.current.begin(mine)).toEqual({
+ existing: theirs,
+ ok: false,
+ reason: 'occupied',
+ });
+ });
+ expect(result.current.launch).toEqual(theirs);
+ expect(JSON.parse(localStorage.getItem(key)!)).toEqual(theirs);
+ });
+
+ it('follows storage events from other tabs', async () => {
+ const { result } = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ expect(result.current.launch).toBeUndefined();
+
+ const theirs = createExperimentLaunch(snapshot());
+ localStorage.setItem(key, JSON.stringify(theirs));
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key, newValue: localStorage.getItem(key) }),
+ );
+ });
+ await waitFor(() => expect(result.current.launch).toEqual(theirs));
+ });
+
+ it('reports a storage failure instead of claiming a checkpoint', async () => {
+ const { result } = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('QuotaExceededError');
+ });
+
+ await act(async () => {
+ expect(await result.current.begin(createExperimentLaunch(snapshot()))).toEqual({
+ ok: false,
+ reason: 'storage',
+ });
+ });
+ expect(result.current.launch).toBeUndefined();
+ });
+});
+
+describe('useExperimentLaunch.resume', () => {
+ it('runs one resume at a time in this tab: a second call while one is in flight is busy', async () => {
+ const { result } = renderHook(() => useExperimentLaunch(options));
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ let release!: () => void;
+ const gate = new Promise<void>((r) => {
+ release = r;
+ });
+
+ let first!: Promise<unknown>;
+ let second!: Promise<unknown>;
+ await act(async () => {
+ first = result.current.resume('exp_1', async () => {
+ await gate;
+ return 'first';
+ });
+ second = result.current.resume('exp_1', async () => 'second');
+ await expect(second).resolves.toEqual({ ran: false, reason: 'busy' });
+ release();
+ await expect(first).resolves.toEqual({ ran: true, result: 'first' });
+ });
+ });
+});
diff --git a/src/features/LobeBench/useExperimentLaunch.ts b/src/features/LobeBench/useExperimentLaunch.ts
new file mode 100644
index 00000000000..550d53324c7
--- /dev/null
+++ b/src/features/LobeBench/useExperimentLaunch.ts
@@ -0,0 +1,125 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import {
+ beginLaunchInStorage,
+ type BeginResult,
+ clearLaunchInStorage,
+ type ExclusiveResult,
+ type ExperimentLaunch,
+ experimentLaunchKey,
+ type ExperimentLaunchScope,
+ launchResumeLockName,
+ parseExperimentLaunch,
+ runExclusiveLaunch,
+ type StoredExperimentLaunch,
+} from './experimentLaunch';
+
+interface LaunchOptions {
+ benchmarkId?: string;
+ userId?: string;
+ workspaceId: string | null;
+}
+
+/**
+ * Serialise read-check-write on one record across tabs with the Web Locks API
+ * when the browser has it. Without it the compare-before-write in storage is
+ * all there is: a smaller window, not an atomic one.
+ */
+const withScopeLock = async <T>(key: string, task: () => T): Promise<T> => {
+ const locks = typeof navigator === 'undefined' ? undefined : navigator.locks;
+ if (!locks) return task();
+ return locks.request(key, async () => task());
+};
+
+const readStored = (key: string): StoredExperimentLaunch | undefined => {
+ try {
+ return parseExperimentLaunch(localStorage.getItem(key));
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * The launch record of the new-experiment page, kept in this browser per
+ * user, workspace and benchmark. `begin` must succeed before any server call
+ * is made: a launch that cannot be checkpointed cannot be resumed, so it is
+ * not started. Other tabs' changes arrive through the `storage` event.
+ */
+export const useExperimentLaunch = ({ benchmarkId, userId, workspaceId }: LaunchOptions) => {
+ const scope: ExperimentLaunchScope | undefined =
+ userId && benchmarkId ? { benchmarkId, userId, workspaceId } : undefined;
+ const key = scope ? experimentLaunchKey(scope) : undefined;
+ const [state, setState] = useState<{ key: string; launch?: StoredExperimentLaunch }>();
+
+ const reload = useCallback(() => {
+ if (!key) return;
+ setState({ key, launch: readStored(key) });
+ }, [key]);
+
+ useEffect(() => {
+ if (!key) return;
+ reload();
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === null || event.key === key) reload();
+ };
+ window.addEventListener('storage', onStorage);
+ return () => window.removeEventListener('storage', onStorage);
+ }, [key, reload]);
+
+ /** Persist a new record; refused when the scope already holds another launch or storage fails. */
+ const begin = async (launch: ExperimentLaunch): Promise<BeginResult> => {
+ if (!key) return { ok: false, reason: 'storage' };
+ const result = await withScopeLock(key, () => beginLaunchInStorage(localStorage, key, launch));
+ reload();
+ return result;
+ };
+
+ /** Remove the record for this experiment only; another launch under the scope is kept. */
+ const clear = async (experimentId: string): Promise<boolean> => {
+ if (!key) return false;
+ const removed = await withScopeLock(key, () =>
+ clearLaunchInStorage(localStorage, key, experimentId),
+ );
+ reload();
+ return removed;
+ };
+
+ /**
+ * Run one resume of a launch at a time: across tabs through a Web Lock on
+ * this launch (not the scope lock `begin`/`clear` take, so nothing nests),
+ * or a storage lease where the browser has no Web Locks; and within this
+ * tab through a ref, so a double click cannot start a second round.
+ */
+ const inFlight = useRef<string | undefined>(undefined);
+ const resume = async <T>(
+ experimentId: string,
+ task: () => Promise<T>,
+ ): Promise<ExclusiveResult<T>> => {
+ if (!key || inFlight.current) return { ran: false, reason: 'busy' };
+ inFlight.current = experimentId;
+ try {
+ const lockName = launchResumeLockName(key, experimentId);
+ return await runExclusiveLaunch(
+ {
+ leaseKey: lockName,
+ lockName,
+ locks: typeof navigator === 'undefined' ? null : (navigator.locks ?? null),
+ storage: localStorage,
+ },
+ task,
+ );
+ } finally {
+ inFlight.current = undefined;
+ }
+ };
+
+ const current = state && state.key === key ? state : undefined;
+ return {
+ begin,
+ clear,
+ launch: current?.launch,
+ ready: !!key && !!current,
+ reload,
+ resume,
+ };
+};
diff --git a/src/features/LobeBench/useImportDataset.ts b/src/features/LobeBench/useImportDataset.ts
new file mode 100644
index 00000000000..487167c0d65
--- /dev/null
+++ b/src/features/LobeBench/useImportDataset.ts
@@ -0,0 +1,36 @@
+import { toast } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { refreshLobeBenchDatasets } from '@/features/LobeBench/datasetCases';
+import { LOBE_BENCH_PATH } from '@/features/LobeBench/lobeBench';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { createDatasetImportModal } from '@/routes/(main)/eval/features/DatasetImportModal';
+import { useEvalStore } from '@/store/eval';
+
+/**
+ * Imports a dataset ZIP as a dataset of its own, in no benchmark: a benchmark
+ * is made separately, of datasets, with its judge and run rules.
+ */
+export const useImportLobeBenchDataset = () => {
+ const { t } = useTranslation('eval');
+ const navigate = useWorkspaceAwareNavigate();
+
+ return () =>
+ createDatasetImportModal({
+ archiveOnly: true,
+ onSuccess: async (datasetId) => {
+ try {
+ await useEvalStore.getState().refreshBenchmarks();
+ await Promise.all([
+ refreshLobeBenchDatasets(),
+ useEvalStore.getState().refreshDatasetCases(datasetId),
+ ]);
+ } catch {
+ // Import has committed. A cache refresh failure must not suggest importing twice.
+ toast.error(t('dataset.import.package.refreshError'));
+ } finally {
+ navigate(`${LOBE_BENCH_PATH}/datasets/${datasetId}`);
+ }
+ },
+ });
+};
diff --git a/src/features/LobeBench/useIsLobeBenchBenchmark.ts b/src/features/LobeBench/useIsLobeBenchBenchmark.ts
new file mode 100644
index 00000000000..ee6452830bd
--- /dev/null
+++ b/src/features/LobeBench/useIsLobeBenchBenchmark.ts
@@ -0,0 +1,12 @@
+import { useEvalStore } from '@/store/eval';
+import { isLobeBenchKind } from '@/store/eval/kinds';
+
+/** Whether this benchmark belongs to Lobe Bench (the Lab's pages also show Lobe Bench runs). */
+export const useIsLobeBenchBenchmark = (benchmarkId?: string) =>
+ useEvalStore((s) =>
+ benchmarkId
+ ? isLobeBenchKind(
+ s.benchmarkDetailMap[benchmarkId] ?? s.benchmarkList.find((b) => b.id === benchmarkId),
+ )
+ : false,
+ );
diff --git a/src/features/LobeBench/useLobeBench.runs.test.ts b/src/features/LobeBench/useLobeBench.runs.test.ts
new file mode 100644
index 00000000000..4d9794792e6
--- /dev/null
+++ b/src/features/LobeBench/useLobeBench.runs.test.ts
@@ -0,0 +1,118 @@
+import type { AgentEvalRunListItem } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentEvalService } from '@/services/agentEval';
+import { fetchLobeBenchRuns } from '@/store/eval/slices/lobeBench/fetchers';
+
+import { useExperimentActions } from './useExperimentActions';
+
+/** What the experiment run list's replica fetches. */
+const loadExperimentRuns = () => agentEvalService.listAllRuns({ experimentId: 'experiment-a' });
+
+const mocks = vi.hoisted(() => ({
+ abort: vi.fn(),
+ list: vi.fn(),
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ agentEval: { abortRun: { mutate: mocks.abort }, listRuns: { query: mocks.list } },
+ },
+}));
+vi.mock('@/store/eval', () => ({ useEvalStore: vi.fn() }));
+vi.mock('@lobehub/ui', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const runs = (count: number, prefix = 'run') =>
+ Array.from({ length: count }, (_, index) => ({
+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, count - index)).toISOString(),
+ id: `${prefix}-${index}`,
+ name: `${prefix} ${index}`,
+ status: index % 2 ? 'pending' : 'running',
+ })) as AgentEvalRunListItem[];
+
+const pageResponse = (items: AgentEvalRunListItem[], limit = 50, offset = 0) => {
+ const data = items.slice(offset, offset + limit);
+ // The current API reports page length, not the total number of matching runs.
+ return { data, total: data.length };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.abort.mockResolvedValue({ success: true });
+});
+
+describe('complete LobeBench run lists', () => {
+ it.each([55, 205])('loads and stops every active run in a %i-run experiment', async (count) => {
+ const all = runs(count);
+ mocks.list.mockImplementation(({ limit, offset }) =>
+ Promise.resolve(pageResponse(all, limit, offset)),
+ );
+ const loaded = await loadExperimentRuns();
+ expect(loaded.map(({ id }) => id)).toEqual(all.map(({ id }) => id));
+ expect(mocks.list.mock.calls.every(([params]) => params.experimentId === 'experiment-a')).toBe(
+ true,
+ );
+
+ const { result } = renderHook(() =>
+ useExperimentActions({
+ experimentId: 'experiment-a',
+ onRerunStarted: vi.fn(),
+ refreshResults: vi.fn().mockResolvedValue(undefined),
+ refreshRuns: vi.fn().mockResolvedValue(undefined),
+ targets: loaded.map((run) => ({
+ name: run.name!,
+ runId: run.id,
+ status: run.status,
+ unverified: 0,
+ })),
+ }),
+ );
+ await act(() => result.current.stop());
+ expect(mocks.abort.mock.calls.map(([params]) => params.id)).toEqual(all.map(({ id }) => id));
+ });
+
+ it('loads every benchmark page before combining and sorting history', async () => {
+ const first = runs(210, 'first');
+ const second = runs(55, 'second');
+ mocks.list.mockImplementation(({ benchmarkId, limit, offset }) =>
+ Promise.resolve(pageResponse(benchmarkId === 'first' ? first : second, limit, offset)),
+ );
+ const loaded = await fetchLobeBenchRuns(['first', 'second']);
+ expect(loaded).toHaveLength(265);
+ expect(new Set(loaded.map(({ id }) => id))).toEqual(
+ new Set([...first, ...second].map(({ id }) => id)),
+ );
+ expect(loaded.map(({ createdAt }) => new Date(createdAt).getTime())).toEqual(
+ loaded.map(({ createdAt }) => new Date(createdAt).getTime()).sort((a, b) => b - a),
+ );
+ });
+
+ it('terminates on an empty page when the total is a multiple of the page size', async () => {
+ const all = runs(100);
+ mocks.list.mockImplementation(({ limit, offset }) =>
+ Promise.resolve(pageResponse(all, limit, offset)),
+ );
+ expect(await loadExperimentRuns()).toHaveLength(100);
+ expect(mocks.list.mock.calls.at(-1)?.[0].offset).toBe(100);
+ });
+
+ it('rejects a later page failure instead of returning an incomplete success', async () => {
+ const failure = new Error('Next page unavailable');
+ mocks.list.mockImplementation(({ limit, offset = 0 }) =>
+ offset > 0
+ ? Promise.reject(failure)
+ : Promise.resolve(pageResponse(runs(205), limit, offset)),
+ );
+ await expect(loadExperimentRuns()).rejects.toBe(failure);
+ });
+
+ it('deduplicates overlapping pages when concurrent creation shifts the offset', async () => {
+ const all = runs(125);
+ mocks.list.mockImplementation(({ offset = 0 }) =>
+ Promise.resolve({ data: offset === 0 ? all.slice(0, 100) : all.slice(99), total: 100 }),
+ );
+ const loaded = await loadExperimentRuns();
+ expect(loaded.map(({ id }) => id)).toEqual(all.map(({ id }) => id));
+ });
+});
diff --git a/src/features/LobeBench/useLobeBench.ts b/src/features/LobeBench/useLobeBench.ts
new file mode 100644
index 00000000000..64553d5e9e0
--- /dev/null
+++ b/src/features/LobeBench/useLobeBench.ts
@@ -0,0 +1,69 @@
+import type { AgentEvalExperimentListItem } from '@lobechat/types';
+import { useMemo } from 'react';
+
+import { isLobeBenchBenchmark, isLobeBenchMeta } from '@/features/LobeBench/lobeBench';
+import { useEvalStore } from '@/store/eval';
+import type { LobeBenchCase } from '@/store/eval/slices/lobeBench/projection';
+
+interface PollConfig {
+ refreshInterval?: number;
+}
+
+/** Benchmarks flagged `metadata.kind = 'lobe-bench'` (usually one). */
+export const useLobeBenchBenchmarks = () => {
+ const benchmarkList = useEvalStore((s) => s.benchmarkList);
+ const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
+ const swr = useFetchBenchmarks();
+ const benchmarks = useMemo(() => benchmarkList.filter(isLobeBenchBenchmark), [benchmarkList]);
+ return { ...swr, benchmarks };
+};
+
+/** Experiments created by Lobe Bench, newest first. */
+export const useLobeBenchExperiments = () => {
+ const experimentList = useEvalStore((s) => s.experimentList);
+ const isInit = useEvalStore((s) => s.experimentListInit);
+ const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);
+ const swr = useFetchExperiments();
+ const experiments = useMemo(
+ () =>
+ (experimentList as AgentEvalExperimentListItem[])
+ .filter((experiment) => isLobeBenchMeta(experiment.metadata))
+ .sort(
+ (a, b) =>
+ new Date(b.updatedAt ?? b.createdAt ?? 0).getTime() -
+ new Date(a.updatedAt ?? a.createdAt ?? 0).getTime(),
+ ),
+ [experimentList],
+ );
+ return { ...swr, experiments, isInit };
+};
+
+/** The case set an overview talks about and a new experiment starts from. */
+export { pickDefaultDataset } from '@/features/LobeBench/lobeBench';
+
+/** Case sets of the Lobe Bench benchmarks, plus the standalone imported ones. */
+export const useLobeBenchDatasets = (benchmarkIds: string[]) =>
+ useEvalStore.getState().useFetchLobeBenchDatasets(benchmarkIds);
+
+/** Every run under the Lobe Bench benchmarks, newest first. */
+export const useLobeBenchRuns = (benchmarkIds: string[], config?: PollConfig) =>
+ useEvalStore.getState().useFetchLobeBenchRuns(benchmarkIds, config);
+
+/** The runs of one experiment (one per contender). */
+export const useExperimentRuns = (experimentId: string | undefined, config?: PollConfig) =>
+ useEvalStore.getState().useFetchExperimentRuns(experimentId, config);
+
+/** Per-case results of several runs, keyed by run id. */
+export const useRunResultsMap = (runIds: string[], config?: PollConfig) =>
+ useEvalStore.getState().useFetchRunResultsByRun(runIds, config);
+
+export { fetchDatasetCases } from '@/store/eval/slices/lobeBench/fetchers';
+export type { LobeBenchCase } from '@/store/eval/slices/lobeBench/projection';
+
+/** The environment fields a case carries itself (not those of its shared environment). */
+export const ownEnvironmentOf = (testCase: LobeBenchCase): Record<string, any> | undefined =>
+ testCase.environment ? (testCase.environmentOverrides ?? {}) : testCase.content?.environment;
+
+/** All cases of a dataset, in benchmark order. */
+export const useDatasetCases = (datasetId: string | undefined) =>
+ useEvalStore.getState().useFetchDatasetCases(datasetId);
diff --git a/src/features/LobeBench/useNarrowBenchNavigation.test.ts b/src/features/LobeBench/useNarrowBenchNavigation.test.ts
new file mode 100644
index 00000000000..600942f6ae6
--- /dev/null
+++ b/src/features/LobeBench/useNarrowBenchNavigation.test.ts
@@ -0,0 +1,66 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useNarrowBenchNavigation } from './useNarrowBenchNavigation';
+
+const viewport = vi.hoisted(() => ({ md: true }));
+const location = vi.hoisted(() => ({ key: 'first' }));
+const state = vi.hoisted(() => ({
+ isStatusInit: true,
+ status: { showLeftPanel: true },
+ toggleLeftPanel: vi.fn(),
+}));
+vi.mock('@lobehub/ui', () => ({ useResponsive: () => viewport }));
+vi.mock('react-router', () => ({ useLocation: () => location }));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: Object.assign((selector: (value: typeof state) => unknown) => selector(state), {
+ getState: () => state,
+ }),
+}));
+
+describe('useNarrowBenchNavigation', () => {
+ beforeEach(() => {
+ viewport.md = true;
+ location.key = 'first';
+ state.isStatusInit = true;
+ state.status.showLeftPanel = true;
+ state.toggleLeftPanel.mockReset().mockImplementation((value: boolean) => {
+ state.status.showLeftPanel = value;
+ });
+ });
+
+ it('collapses on narrow entry without overriding a manual reopen until navigation', () => {
+ viewport.md = false;
+ const { rerender } = renderHook(() => useNarrowBenchNavigation());
+ expect(state.toggleLeftPanel).toHaveBeenCalledTimes(1);
+ state.status.showLeftPanel = true;
+ rerender();
+ expect(state.toggleLeftPanel).toHaveBeenCalledTimes(1);
+ location.key = 'next';
+ rerender();
+ expect(state.toggleLeftPanel).toHaveBeenCalledTimes(2);
+ expect(state.status.showLeftPanel).toBe(false);
+ });
+
+ it('handles wide-to-narrow transitions and does not automatically reopen on wide', () => {
+ const { rerender } = renderHook(() => useNarrowBenchNavigation());
+ expect(state.toggleLeftPanel).not.toHaveBeenCalled();
+ viewport.md = false;
+ rerender();
+ expect(state.status.showLeftPanel).toBe(false);
+ viewport.md = true;
+ rerender();
+ expect(state.status.showLeftPanel).toBe(false);
+ expect(state.toggleLeftPanel).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits for persisted status hydration before applying the initial collapse', () => {
+ viewport.md = false;
+ state.isStatusInit = false;
+ const { rerender } = renderHook(() => useNarrowBenchNavigation());
+ expect(state.toggleLeftPanel).not.toHaveBeenCalled();
+ state.isStatusInit = true;
+ rerender();
+ expect(state.toggleLeftPanel).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/src/features/LobeBench/useNarrowBenchNavigation.ts b/src/features/LobeBench/useNarrowBenchNavigation.ts
new file mode 100644
index 00000000000..d4fa000d428
--- /dev/null
+++ b/src/features/LobeBench/useNarrowBenchNavigation.ts
@@ -0,0 +1,26 @@
+import { useResponsive } from '@lobehub/ui';
+import { useEffect, useRef } from 'react';
+import { useLocation } from 'react-router';
+
+import { useGlobalStore } from '@/store/global';
+
+/** Keep desktop LobeBench usable in narrow windows, using the existing panel toggle. */
+export const useNarrowBenchNavigation = () => {
+ const { md = true } = useResponsive();
+ const isNarrow = !md;
+ const { key } = useLocation();
+ const isStatusInit = useGlobalStore((state) => state.isStatusInit);
+ const previous = useRef<{ key: string; narrow: boolean } | undefined>(undefined);
+ useEffect(() => {
+ if (!isStatusInit) return;
+ const enteredNarrow = isNarrow && !previous.current?.narrow;
+ const navigated = previous.current !== undefined && previous.current.key !== key;
+ if (isNarrow && (enteredNarrow || navigated)) {
+ const { status, toggleLeftPanel } = useGlobalStore.getState();
+ // This intentionally uses the persisted preference, as the shared header
+ // toggle does. Resizing back to wide does not automatically reopen it.
+ if (status.showLeftPanel) toggleLeftPanel(false);
+ }
+ previous.current = { key, narrow: isNarrow };
+ }, [isNarrow, isStatusInit, key]);
+};
diff --git a/src/features/LobeBench/useSavedContenders.ts b/src/features/LobeBench/useSavedContenders.ts
new file mode 100644
index 00000000000..a414da9a3fc
--- /dev/null
+++ b/src/features/LobeBench/useSavedContenders.ts
@@ -0,0 +1,53 @@
+import { useCallback, useMemo } from 'react';
+
+import {
+ getBenchmarkMeta,
+ isBuiltInBenchmark,
+ isLobeBenchMeta,
+ type LobeBenchContender,
+ pickPrimaryBenchmark,
+ withRanContenders,
+} from '@/features/LobeBench/lobeBench';
+import { useLobeBenchBenchmarks, useLobeBenchExperiments } from '@/features/LobeBench/useLobeBench';
+import { useEvalStore } from '@/store/eval';
+
+/**
+ * The account's contenders: the ones saved in the primary benchmark's
+ * metadata plus every contender a past experiment ran, so nothing that ran
+ * before has to be set up twice. `save` replaces the saved list and refreshes
+ * every reader.
+ */
+export const useSavedContenders = () => {
+ const { benchmarks } = useLobeBenchBenchmarks();
+ const { experiments } = useLobeBenchExperiments();
+ const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
+ const benchmark = pickPrimaryBenchmark(benchmarks);
+ const saved = getBenchmarkMeta(benchmark).contenders;
+
+ const contenders = useMemo(() => {
+ // Oldest experiment first; the saved list (with its edited names) wins over what they recorded.
+ const ran = [...experiments]
+ .reverse()
+ .flatMap((experiment) =>
+ isLobeBenchMeta(experiment.metadata) ? experiment.metadata.contenders : [],
+ );
+ return withRanContenders(saved, ran);
+ }, [experiments, saved]);
+
+ const save = useCallback(
+ async (list: LobeBenchContender[]) => {
+ // A built-in benchmark cannot carry an account's list; its contenders
+ // are the ones past experiments ran.
+ if (!benchmark || isBuiltInBenchmark(benchmark)) return;
+ await updateBenchmark({
+ description: benchmark.description ?? undefined,
+ id: benchmark.id,
+ metadata: { ...benchmark.metadata, contenders: list },
+ name: benchmark.name,
+ });
+ },
+ [benchmark, updateBenchmark],
+ );
+
+ return { benchmark, contenders, save };
+};
diff --git a/src/routes/(main)/eval/(home)/_layout/index.tsx b/src/routes/(main)/eval/(home)/_layout/index.tsx
index 3c359342242..ccac42e7e0c 100644
--- a/src/routes/(main)/eval/(home)/_layout/index.tsx
+++ b/src/routes/(main)/eval/(home)/_layout/index.tsx
@@ -4,6 +4,8 @@ import { Flexbox } from '@lobehub/ui';
import { type FC } from 'react';
import { Outlet } from 'react-router';
+import { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
+import AreaSwitch from '@/features/LobeBench/AreaSwitch';
import NavHeader from '@/features/NavHeader';
import Sidebar from '../../_layout/Sidebar';
@@ -14,7 +16,24 @@ const EvalHomeLayout: FC = () => {
<>
<Sidebar />
<Flexbox className={styles.mainContainer} flex={1} height={'100%'}>
- <NavHeader style={{ left: 0, position: 'absolute', top: 0, zIndex: 10 }} />
+ {/* Spans the whole header band so the area switch can sit at its
+ centre; the band itself lets clicks through to the page. */}
+ <NavHeader
+ style={{
+ left: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ zIndex: 10,
+ }}
+ styles={{
+ center: { ...AGENT_PROFILE_TABS_CENTER_STYLE, pointerEvents: 'auto' },
+ left: { pointerEvents: 'auto' },
+ }}
+ >
+ <AreaSwitch active={'agent'} />
+ </NavHeader>
<Outlet />
</Flexbox>
</>
diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
index 64717ef708a..220d91ae267 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/BenchmarkList.tsx
@@ -28,7 +28,7 @@ import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useEvalStore } from '@/store/eval';
+import { benchmarkSelectors, useEvalStore } from '@/store/eval';
import { isModifierClick } from '@/utils/navigation';
const SYSTEM_ICONS = [
@@ -58,7 +58,7 @@ interface BenchmarkListProps {
const BenchmarkList = memo<BenchmarkListProps>(({ activeKey, itemKey }) => {
const { t } = useTranslation('eval');
const navigate = useWorkspaceAwareNavigate();
- const benchmarkList = useEvalStore((s) => s.benchmarkList);
+ const benchmarkList = useEvalStore(benchmarkSelectors.agentBenchmarkList);
const isInit = useEvalStore((s) => s.benchmarkListInit);
return (
diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/DatasetList.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/DatasetList.tsx
index a7ed5e43379..b0bfd48b7a8 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/Body/DatasetList.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/DatasetList.tsx
@@ -16,7 +16,7 @@ import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useEvalStore } from '@/store/eval';
+import { datasetSelectors, useEvalStore } from '@/store/eval';
import { isModifierClick } from '@/utils/navigation';
interface DatasetListProps {
@@ -33,8 +33,10 @@ const DatasetList = memo<DatasetListProps>(({ activeKey, itemKey }) => {
const { t } = useTranslation('eval');
const navigate = useWorkspaceAwareNavigate();
const useFetchAllDatasets = useEvalStore((s) => s.useFetchAllDatasets);
- const { data, isLoading } = useFetchAllDatasets();
- const datasets: Array<{ id: string; name: string }> = data ?? [];
+ const { isLoading } = useFetchAllDatasets();
+ const datasets: Array<{ id: string; name: string }> = useEvalStore(
+ datasetSelectors.agentDatasets,
+ );
return (
<AccordionItem value={itemKey}>
diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx
index 7fd9d1cd280..fc424954092 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx
@@ -17,7 +17,7 @@ import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useEvalStore } from '@/store/eval';
+import { experimentSelectors, useEvalStore } from '@/store/eval';
import { isModifierClick } from '@/utils/navigation';
interface ExperimentListProps {
@@ -29,7 +29,7 @@ const ExperimentList = memo<ExperimentListProps>(({ activeKey, itemKey }) => {
const { t } = useTranslation('eval');
const { t: tCommon } = useTranslation('common');
const navigate = useWorkspaceAwareNavigate();
- const experimentList = useEvalStore((s) => s.experimentList);
+ const experimentList = useEvalStore(experimentSelectors.agentExperimentList);
const isInit = useEvalStore((s) => s.experimentListInit);
const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);
const { error, mutate } = useFetchExperiments();
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
index 1dc0e500cd3..83180c57eae 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx
@@ -12,6 +12,8 @@ import { Database } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { benchmarkDatasetPath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -29,6 +31,7 @@ const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey })
const navigate = useWorkspaceAwareNavigate();
const datasetList = useEvalStore(datasetSelectors.datasetList(benchmarkId));
const isLoading = useEvalStore(datasetSelectors.isLoadingDatasetList(benchmarkId));
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
return (
<AccordionItem value={itemKey}>
@@ -54,10 +57,10 @@ const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey })
datasetList.map((ds: any) => (
<WorkspaceLink
key={ds.id}
- to={`/eval/bench/${benchmarkId}/datasets/${ds.id}`}
+ to={benchmarkDatasetPath(ds.id, lobeBench)}
onClick={(e) => {
e.preventDefault();
- navigate(`/eval/bench/${benchmarkId}/datasets/${ds.id}`);
+ navigate(benchmarkDatasetPath(ds.id, lobeBench));
}}
>
<NavItem
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
index b549f5e7f3b..ac256a76f65 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx
@@ -5,6 +5,8 @@ import { LayoutDashboard } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { benchmarkHomePath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
@@ -17,15 +19,18 @@ const Body = memo(() => {
const { t } = useTranslation('eval');
const { activeKey, benchmarkId } = useActiveBenchmarkSidebarRoute();
const navigate = useWorkspaceAwareNavigate();
+ // A Lobe Bench run opens here; its dashboard is Lobe Bench's benchmark page.
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
+ const dashboardPath = benchmarkHomePath(benchmarkId || '', lobeBench);
return (
<Flexbox gap={8} paddingInline={4}>
<Flexbox paddingInline={4}>
<WorkspaceLink
- to={`/eval/bench/${benchmarkId}`}
+ to={dashboardPath}
onClick={(e) => {
e.preventDefault();
- navigate(`/eval/bench/${benchmarkId}`);
+ navigate(dashboardPath);
}}
>
<NavItem
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
index 8a6cb6f5f75..0d2f7c3e94b 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/BenchmarkHead.tsx
@@ -28,8 +28,10 @@ import {
} from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
+import { benchmarkHomePath } from '@/features/LobeBench/experimentNavigation';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useEvalStore } from '@/store/eval';
+import { isLobeBenchKind } from '@/store/eval/kinds';
const SYSTEM_ICONS = [
LoaderPinwheel,
@@ -66,23 +68,29 @@ const BenchmarkHead = memo<{ id: string }>(({ id }) => {
const name = benchmark?.name || benchmarkList.find((b: any) => b.id === id)?.name;
const Icon = useMemo(() => getSystemIcon(id), [id]);
+ const onLobeBench = isLobeBenchKind(benchmarkList.find((b: any) => b.id === id) ?? benchmark);
+
const handleClick = useCallback(() => {
- navigate(`/eval/bench/${id}`);
- }, [id, navigate]);
+ navigate(benchmarkHomePath(id, onLobeBench));
+ }, [id, navigate, onLobeBench]);
const handleBenchmarkSwitch = useCallback(
(benchmarkId: string) => {
setTimeout(() => {
- navigate(`/eval/bench/${benchmarkId}`);
+ navigate(benchmarkHomePath(benchmarkId, onLobeBench));
}, 0);
},
- [navigate],
+ [navigate, onLobeBench],
);
const menuItems = useMemo<DropdownItem[]>(() => {
if (!benchmarkList || benchmarkList.length === 0) return [];
- return benchmarkList.map((b: any) => ({
+ // The switcher stays on one side: a Lobe Bench benchmark offers the other
+ // Lobe Bench benchmarks, an Evaluation Lab benchmark the Evaluation Lab's.
+ const sameSide = benchmarkList.filter((b: any) => isLobeBenchKind(b) === onLobeBench);
+
+ return sameSide.map((b: any) => ({
icon: (
<Center className={styles.menuIcon} style={{ minWidth: 16 }} width={16}>
{(() => {
@@ -96,7 +104,7 @@ const BenchmarkHead = memo<{ id: string }>(({ id }) => {
onClick: () => handleBenchmarkSwitch(b.id),
style: b.id === id ? { backgroundColor: cssVar.controlItemBgActive } : {},
}));
- }, [benchmarkList, handleBenchmarkSwitch, id]);
+ }, [benchmarkList, handleBenchmarkSwitch, id, onLobeBench]);
return (
<Block
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx
index 495715b0858..5f2b195e370 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx
@@ -3,6 +3,8 @@
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { benchmarkSidebarBackPath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
import { useActiveBenchmarkId } from '../useActiveBenchmarkId';
@@ -11,9 +13,10 @@ import BenchmarkHead from './BenchmarkHead';
const Header = memo(() => {
const benchmarkId = useActiveBenchmarkId();
const { t } = useTranslation('common');
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
return (
<SideBarHeaderLayout
- backTo="/eval"
+ backTo={benchmarkSidebarBackPath(benchmarkId, lobeBench)}
left={<BenchmarkHead id={benchmarkId} />}
breadcrumb={[
{
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/TitleBar.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/TitleBar.tsx
new file mode 100644
index 00000000000..92bd7836f0d
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/TitleBar.tsx
@@ -0,0 +1,144 @@
+'use client';
+
+import {
+ Button,
+ confirmModal,
+ type DropdownItem,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ toast,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Edit, EllipsisVertical, type LucideIcon, Server, Trash2, User } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useEvalStore } from '@/store/eval';
+
+import { createBenchmarkEditModal } from '../../../../features/BenchmarkEditModal';
+
+const styles = stylex.create({
+ description: {
+ margin: 0,
+ marginBlockStart: 2,
+ fontSize: cssVar.fontSize,
+ color: cssVar.colorTextTertiary,
+ },
+ iconBox: {
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 40,
+ height: 40,
+ borderRadius: cssVar.borderRadiusLG,
+ },
+ iconSystem: { backgroundColor: cssVar.colorPrimaryBg, color: cssVar.colorPrimary },
+ iconUser: { backgroundColor: cssVar.colorSuccessBg, color: cssVar.colorSuccess },
+ title: {
+ margin: 0,
+ fontSize: cssVar.fontSizeHeading3,
+ fontWeight: 600,
+ color: cssVar.colorText,
+ },
+});
+
+export interface BenchmarkTitleBarProps {
+ benchmark: any;
+ /** What the delete confirm says, when deleting does more than drop the benchmark. */
+ deleteConfirm?: string;
+ onBenchmarkUpdate?: (benchmark: any) => void;
+ /** Deletes the benchmark instead of the default (delete it, then open the Evaluation Lab). */
+ onDelete?: () => Promise<void>;
+ systemIcon?: LucideIcon;
+}
+
+/**
+ * A benchmark's name and description with its Edit and more menu: the same
+ * row on the Evaluation Lab's page and on Lobe Bench's.
+ */
+const BenchmarkTitleBar = memo<BenchmarkTitleBarProps>(
+ ({ benchmark, deleteConfirm, onBenchmarkUpdate, onDelete, systemIcon = Server }) => {
+ const { t } = useTranslation(['eval', 'common']);
+ const navigate = useWorkspaceAwareNavigate();
+ const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
+ const refreshBenchmarkDetail = useEvalStore((s) => s.refreshBenchmarkDetail);
+
+ const handleEditSuccess = async () => {
+ await refreshBenchmarkDetail(benchmark.id);
+ onBenchmarkUpdate?.(benchmark);
+ };
+
+ const handleEdit = () => createBenchmarkEditModal({ benchmark, onSuccess: handleEditSuccess });
+
+ const handleDelete = () => {
+ confirmModal({
+ content: deleteConfirm ?? t('benchmark.actions.delete.confirm'),
+ okButtonProps: { danger: true },
+ okText: t('benchmark.actions.delete'),
+ onOk: async () => {
+ try {
+ if (onDelete) {
+ await onDelete();
+ return;
+ }
+ await deleteBenchmark(benchmark.id);
+ navigate('/eval');
+ } catch (error) {
+ // Stay on the page: the row was rolled back and the user can retry.
+ toast.error(error instanceof Error ? error.message : t('benchmark.delete.error'));
+ }
+ },
+ title: t('benchmark.actions.delete'),
+ });
+ };
+
+ // Built-in benchmarks (every account sees them) cannot be deleted; say so in the
+ // menu instead of failing after the confirm.
+ const builtIn = Boolean(benchmark.isSystem);
+ const menuItems: DropdownItem[] = [
+ {
+ danger: !builtIn,
+ disabled: builtIn,
+ icon: <Trash2 size={16} />,
+ key: 'delete',
+ label: builtIn ? t('benchmark.actions.delete.builtIn') : t('common.delete'),
+ onClick: handleDelete,
+ },
+ ];
+
+ const byUser = benchmark.source === 'user';
+
+ return (
+ <Flexbox horizontal align="start" justify="space-between">
+ <Flexbox horizontal align="start" gap={12}>
+ <div {...stylex.props(styles.iconBox, byUser ? styles.iconUser : styles.iconSystem)}>
+ <Icon icon={byUser ? User : systemIcon} size={20} />
+ </div>
+ <Flexbox gap={4}>
+ <h1 {...stylex.props(styles.title)}>{benchmark.name}</h1>
+ {benchmark.description && (
+ <p {...stylex.props(styles.description)}>{benchmark.description}</p>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ <Flexbox horizontal gap={8}>
+ <Button icon={Edit} size="small" onClick={handleEdit}>
+ {t('common.edit')}
+ </Button>
+ <DropdownMenu items={menuItems} placement="bottomRight">
+ <Button icon={EllipsisVertical} size="small" title={t('more', { ns: 'common' })} />
+ </DropdownMenu>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+BenchmarkTitleBar.displayName = 'BenchmarkTitleBar';
+
+export default BenchmarkTitleBar;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
index eadc1959d39..a9a1f15f576 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
@@ -2,38 +2,15 @@
import type { AgentEvalRunListItem } from '@lobechat/types';
import { formatCost } from '@lobechat/utils';
-import {
- Button,
- confirmModal,
- createStaticStyles,
- cssVar,
- type DropdownItem,
- DropdownMenu,
- Flexbox,
- Icon,
- Text,
-} from '@lobehub/ui';
-import {
- CircleDollarSign,
- Clock,
- Edit,
- EllipsisVertical,
- Layers,
- Server,
- Trash2,
- Trophy,
- User,
-} from 'lucide-react';
-import { type LucideIcon } from 'lucide-react';
+import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
+import { CircleDollarSign, Clock, Layers, type LucideIcon, Trophy } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useEvalStore } from '@/store/eval';
-
-import { createBenchmarkEditModal } from '../../../../features/BenchmarkEditModal';
import Sparkline from '../../../../features/Sparkline';
import { formatDuration, formatDurationMinutes } from '../../../../utils';
+import BenchmarkTitleBar from './TitleBar';
+import { topPerformersOf } from './topPerformers';
const RANK_COLORS = [cssVar.colorPrimary, cssVar.colorSuccess, cssVar.colorTextQuaternary];
@@ -50,22 +27,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
line-height: 1;
color: ${cssVar.colorText};
`,
- description: css`
- margin: 0;
- margin-block-start: 2px;
- font-size: ${cssVar.fontSize};
- color: ${cssVar.colorTextTertiary};
- `,
- iconBox: css`
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
-
- width: 40px;
- height: 40px;
- border-radius: ${cssVar.borderRadiusLG};
- `,
statCard: css`
flex: 1;
@@ -88,12 +49,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-weight: 600;
color: ${cssVar.colorTextSecondary};
`,
- title: css`
- margin: 0;
- font-size: ${cssVar.fontSizeHeading3};
- font-weight: 600;
- color: ${cssVar.colorText};
- `,
}));
interface BenchmarkHeaderProps {
@@ -103,79 +58,25 @@ interface BenchmarkHeaderProps {
onBenchmarkUpdate?: (benchmark: any) => void;
runCount: number;
systemIcon?: LucideIcon;
+ /** Label of the top-performers card; defaults to "Top Agents". */
+ topLabel?: string;
totalCases: number;
}
const BenchmarkHeader = memo<BenchmarkHeaderProps>(
- ({
- benchmark,
- completedRuns,
- datasets,
- onBenchmarkUpdate,
- runCount,
- systemIcon = Server,
- totalCases,
- }) => {
+ ({ benchmark, completedRuns, datasets, onBenchmarkUpdate, systemIcon, topLabel, totalCases }) => {
const { t } = useTranslation('eval');
- const navigate = useWorkspaceAwareNavigate();
- const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
- const refreshBenchmarkDetail = useEvalStore((s) => s.refreshBenchmarkDetail);
-
- const handleEditSuccess = async () => {
- await refreshBenchmarkDetail(benchmark.id);
- onBenchmarkUpdate?.(benchmark);
- };
-
- const handleEdit = () => createBenchmarkEditModal({ benchmark, onSuccess: handleEditSuccess });
-
- const handleDelete = () => {
- confirmModal({
- content: t('benchmark.actions.delete.confirm'),
- okButtonProps: { danger: true },
- okText: t('benchmark.actions.delete'),
- onOk: async () => {
- await deleteBenchmark(benchmark.id);
- navigate('/eval');
- },
- title: t('benchmark.actions.delete'),
- });
- };
-
- const menuItems: DropdownItem[] = [
- {
- danger: true,
- icon: <Trash2 size={16} />,
- key: 'delete',
- label: t('common.delete'),
- onClick: handleDelete,
- },
- ];
// === Stats Computations ===
const hasDatasets = datasets.length > 0;
const hasCompletedRuns = completedRuns.length > 0;
- // Top Agents: group by targetAgent, compute avg passRate, sort desc, take top 3
- const topAgents = useMemo(() => {
- if (!hasCompletedRuns) return [];
- const agentMap = new Map<string, { name: string; passRates: number[] }>();
- for (const run of completedRuns) {
- const agentName = run.targetAgent?.title || run.targetAgent?.id || 'Unknown';
- const agentId = run.targetAgentId || run.targetAgent?.id || agentName;
- if (!agentMap.has(agentId)) {
- agentMap.set(agentId, { name: agentName, passRates: [] });
- }
- agentMap.get(agentId)!.passRates.push(run.passRate ?? run.metrics?.passRate ?? 0);
- }
- return [...agentMap.entries()]
- .map(([, v]) => ({
- avgPassRate: v.passRates.reduce((a, b) => a + b, 0) / v.passRates.length,
- name: v.name,
- }))
- .sort((a, b) => b.avgPassRate - a.avgPassRate)
- .slice(0, 3);
- }, [completedRuns, hasCompletedRuns]);
+ // Top performers: an Agent's runs, or a model contender's runs (Lobe Bench), by average pass rate.
+ const topAgents = useMemo(
+ () => (hasCompletedRuns ? topPerformersOf(completedRuns) : []),
+ [completedRuns, hasCompletedRuns],
+ );
// Best agent for the summary line
const bestAgent = topAgents.length > 0 ? topAgents[0] : null;
@@ -225,42 +126,11 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
return (
<>
{/* Header */}
- <Flexbox gap={16}>
- <Flexbox horizontal align="start" justify="space-between">
- <Flexbox horizontal align="start" gap={12}>
- <div
- className={styles.iconBox}
- style={{
- background:
- benchmark.source === 'user' ? cssVar.colorSuccessBg : cssVar.colorPrimaryBg,
- }}
- >
- <Icon
- icon={benchmark.source === 'user' ? User : systemIcon}
- size={20}
- style={{
- color: benchmark.source === 'user' ? cssVar.colorSuccess : cssVar.colorPrimary,
- }}
- />
- </div>
- <Flexbox gap={4}>
- <h1 className={styles.title}>{benchmark.name}</h1>
- {benchmark.description && (
- <p className={styles.description}>{benchmark.description}</p>
- )}
- </Flexbox>
- </Flexbox>
-
- <Flexbox horizontal gap={8}>
- <Button icon={Edit} size="small" onClick={handleEdit}>
- {t('common.edit')}
- </Button>
- <DropdownMenu items={menuItems} placement="bottomRight">
- <Button icon={EllipsisVertical} size="small" />
- </DropdownMenu>
- </Flexbox>
- </Flexbox>
- </Flexbox>
+ <BenchmarkTitleBar
+ benchmark={benchmark}
+ systemIcon={systemIcon}
+ onBenchmarkUpdate={onBenchmarkUpdate}
+ />
{/* Results hero — headline best pass rate + trend across completed runs.
Always rendered (shows a muted dash before the first completed run) so
@@ -297,7 +167,9 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
<div className={styles.statIcon} style={{ background: cssVar.colorWarningBg }}>
<Trophy size={16} style={{ color: cssVar.colorWarning }} />
</div>
- <span className={styles.statLabel}>{t('benchmark.detail.stats.topAgents')}</span>
+ <span className={styles.statLabel}>
+ {topLabel ?? t('benchmark.detail.stats.topAgents')}
+ </span>
</Flexbox>
{!hasDatasets && !hasCompletedRuns && (
@@ -332,8 +204,14 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
{hasCompletedRuns && topAgents.length > 0 && (
<Flexbox gap={6}>
{topAgents.map((agent, idx) => (
- <Flexbox horizontal align="center" justify="space-between" key={agent.name}>
- <Flexbox horizontal align="center" gap={8}>
+ <Flexbox
+ horizontal
+ align="center"
+ gap={8}
+ justify="space-between"
+ key={agent.name}
+ >
+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>
<span
style={{
color: RANK_COLORS[idx] || RANK_COLORS[2],
@@ -347,10 +225,14 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
{idx + 1}
</span>
<span
+ title={agent.name}
style={{
color: cssVar.colorText,
fontSize: cssVar.fontSize,
fontWeight: 500,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
}}
>
{agent.name}
@@ -359,8 +241,10 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
<span
style={{
color: cssVar.colorTextSecondary,
+ flex: 'none',
fontFamily: cssVar.fontFamilyCode,
fontSize: cssVar.fontSize,
+ whiteSpace: 'nowrap',
}}
>
{(agent.avgPassRate * 100).toFixed(1)}%
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.test.ts b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.test.ts
new file mode 100644
index 00000000000..8fbe144db86
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.test.ts
@@ -0,0 +1,38 @@
+import type { AgentEvalRunListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { topPerformersOf } from './topPerformers';
+
+const run = (fields: Record<string, unknown>) => fields as unknown as AgentEvalRunListItem;
+
+describe('topPerformersOf', () => {
+ it('names model runs by their contender instead of grouping them all as Unknown', () => {
+ const top = topPerformersOf([
+ run({
+ config: { model: 'deepseek/deepseek-v4.1-flash', provider: 'openrouter' },
+ name: 'DeepSeek V4.1 Flash',
+ passRate: 0.8,
+ }),
+ run({
+ config: { model: 'anthropic/claude-haiku-5.5', provider: 'openrouter' },
+ name: 'Claude Haiku 5.5',
+ passRate: 0.6,
+ }),
+ run({
+ config: { model: 'deepseek/deepseek-v4.1-flash', provider: 'openrouter' },
+ name: 'DeepSeek V4.1 Flash',
+ passRate: 0.7,
+ }),
+ ]);
+ expect(top.map((p) => p.name)).toEqual(['DeepSeek V4.1 Flash', 'Claude Haiku 5.5']);
+ expect(top[0].avgPassRate).toBeCloseTo(0.75);
+ });
+
+ it("keeps grouping an Agent's runs under its title", () => {
+ const top = topPerformersOf([
+ run({ passRate: 0.5, targetAgent: { id: 'agt_1', title: 'Writer' }, targetAgentId: 'agt_1' }),
+ run({ passRate: 1, targetAgent: { id: 'agt_1', title: 'Writer' }, targetAgentId: 'agt_1' }),
+ ]);
+ expect(top).toEqual([{ avgPassRate: 0.75, name: 'Writer' }]);
+ });
+});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.ts b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.ts
new file mode 100644
index 00000000000..a00fdd54674
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/topPerformers.ts
@@ -0,0 +1,32 @@
+import type { AgentEvalRunListItem } from '@lobechat/types';
+
+import { contenderKeyOf, contenderName } from '@/features/LobeBench/benchmarkRanking';
+
+export interface TopPerformer {
+ avgPassRate: number;
+ name: string;
+}
+
+/**
+ * The best performers of completed runs, by average pass rate. A run of an
+ * Agent stands for that Agent; a run of a bare model (Lobe Bench) stands for
+ * its contender, the model with its settings, under the run's name.
+ */
+export const topPerformersOf = (runs: AgentEvalRunListItem[], limit = 3): TopPerformer[] => {
+ const groups = new Map<string, { name: string; passRates: number[] }>();
+ for (const run of runs) {
+ const agentId = run.targetAgentId || run.targetAgent?.id;
+ const key = agentId ? `agent:${agentId}` : `contender:${contenderKeyOf(run)}`;
+ const name = run.targetAgent?.title || run.targetAgent?.id || contenderName(run);
+ const group = groups.get(key) ?? { name, passRates: [] };
+ group.passRates.push(run.passRate ?? run.metrics?.passRate ?? 0);
+ groups.set(key, group);
+ }
+ return [...groups.values()]
+ .map(({ name, passRates }) => ({
+ avgPassRate: passRates.reduce((a, b) => a + b, 0) / passRates.length,
+ name,
+ }))
+ .sort((a, b) => b.avgPassRate - a.avgPassRate)
+ .slice(0, limit);
+};
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
index 1fb34331a32..7fee25cab1b 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx
@@ -15,6 +15,8 @@ import { ArrowRight, ChevronRight, Database, Ellipsis, Pencil, Play, Trash2 } fr
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { benchmarkDatasetPath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useEvalStore } from '@/store/eval';
@@ -178,6 +180,7 @@ const DatasetCard = memo<DatasetCardProps>(
}) => {
const { t } = useTranslation('eval');
const deleteDataset = useEvalStore((s) => s.deleteDataset);
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
const handleDelete = useCallback(() => {
confirmModal({
@@ -292,7 +295,7 @@ const DatasetCard = memo<DatasetCardProps>(
<Flexbox horizontal align="center" className={styles.footer} justify="center">
<WorkspaceLink
className={styles.footerLink}
- to={`/eval/bench/${benchmarkId}/datasets/${dataset.id}`}
+ to={benchmarkDatasetPath(dataset.id, lobeBench)}
>
<Button icon={ArrowRight} iconPosition="end" size="small" type="text">
{t('dataset.detail.viewDetail')}
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
index 24c587f9ff9..c050d7cffd6 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
@@ -22,7 +22,7 @@ import { createDatasetCreateModal } from '../../../../features/DatasetCreateModa
import { createDatasetEditModal } from '../../../../features/DatasetEditModal';
import { createDatasetImportModal } from '../../../../features/DatasetImportModal';
import { createTestCaseCreateModal } from '../../../../features/TestCaseCreateModal';
-import { createRunCreateModal } from '../RunCreateModal';
+import { useCreateRun } from '../RunCreateModal/useCreateRun';
import DatasetCard from './DatasetCard';
import EmptyState from './EmptyState';
@@ -143,15 +143,10 @@ const DatasetsTab = memo<DatasetsTabProps>(
[handleRefreshTestCases],
);
+ const { createRun } = useCreateRun(benchmarkId);
const handleRunDataset = useCallback(
- (ds: any) => {
- createRunCreateModal({
- benchmarkId,
- datasetId: ds.id,
- datasetName: ds.name,
- });
- },
- [benchmarkId],
+ (ds: any) => createRun({ id: ds.id, name: ds.name }),
+ [createRun],
);
const handleDeleteCase = useCallback(
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
index e9cfc85a05b..af5cabd4917 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
@@ -185,11 +185,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
const timeoutMinutes = values.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES;
const k = values.k ?? 1;
const run = await createRun({
- config: {
- k,
- maxSteps,
- timeout: timeoutMinutes * 60_000,
- },
+ config: { k, maxSteps, timeout: timeoutMinutes * 60_000 },
datasetId: (isDatasetMode ? datasetId : values.datasetId)!,
experimentId,
name: values.name,
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.test.ts b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.test.ts
new file mode 100644
index 00000000000..77f51507c50
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.test.ts
@@ -0,0 +1,74 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useCreateRun } from './useCreateRun';
+
+const navigate = vi.fn();
+const createRunCreateModal = vi.fn();
+let lobeBench = false;
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigate,
+}));
+vi.mock('@/features/LobeBench/useIsLobeBenchBenchmark', () => ({
+ useIsLobeBenchBenchmark: () => lobeBench,
+}));
+vi.mock('./index', () => ({
+ createRunCreateModal: (props: unknown) => createRunCreateModal(props),
+}));
+vi.mock('@/store/eval', () => {
+ const state = {
+ datasetListMap: { bm_1: [{ id: 'ds_first' }, { id: 'ds_second' }] },
+ useFetchBenchmarkDetail: () => ({}),
+ };
+ return {
+ datasetSelectors: {
+ datasetList: (id?: string) => (s: typeof state) =>
+ (id ? (s.datasetListMap as Record<string, { id: string }[]>)[id] : undefined) ?? [],
+ },
+ useEvalStore: (selector: (s: typeof state) => unknown) => selector(state),
+ };
+});
+
+describe('useCreateRun', () => {
+ beforeEach(() => {
+ navigate.mockReset();
+ createRunCreateModal.mockReset();
+ });
+
+ it('opens the Lab run modal for a Lab benchmark', () => {
+ lobeBench = false;
+ const { result } = renderHook(() => useCreateRun('bm_1'));
+
+ act(() => result.current.createRun({ id: 'ds_second', name: 'Second' }));
+
+ expect(createRunCreateModal).toHaveBeenCalledWith({
+ benchmarkId: 'bm_1',
+ datasetId: 'ds_second',
+ datasetName: 'Second',
+ });
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ // Lobe Bench runs open on the Lab pages; their "new run" buttons used to open
+ // the Lab's single-agent modal, a second, different way to start an experiment.
+ it('sends a Lobe Bench benchmark to the new experiment page on the dataset', () => {
+ lobeBench = true;
+ const { result } = renderHook(() => useCreateRun('bm_1'));
+
+ act(() => result.current.createRun({ id: 'ds_second', name: 'Second' }));
+
+ expect(navigate).toHaveBeenCalledWith('/eval/lobe-bench/experiments/new?dataset=ds_second');
+ expect(createRunCreateModal).not.toHaveBeenCalled();
+ expect(result.current.lobeBench).toBe(true);
+ });
+
+ it('uses the benchmark first dataset when the button names none', () => {
+ lobeBench = true;
+ const { result } = renderHook(() => useCreateRun('bm_1'));
+
+ act(() => result.current.createRun());
+
+ expect(navigate).toHaveBeenCalledWith('/eval/lobe-bench/experiments/new?dataset=ds_first');
+ });
+});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.ts b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.ts
new file mode 100644
index 00000000000..4b072e8b141
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/useCreateRun.ts
@@ -0,0 +1,37 @@
+import { useCallback } from 'react';
+
+import { newExperimentPath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { datasetSelectors, useEvalStore } from '@/store/eval';
+
+import { createRunCreateModal } from './index';
+
+/**
+ * The "new run" action of a benchmark page. A Lab benchmark opens the run
+ * modal; a Lobe Bench benchmark, whose runs also open on these Lab pages,
+ * goes to Lobe Bench's new experiment page instead, so its experiments start
+ * in one place, with contenders and the benchmark's standard.
+ */
+export const useCreateRun = (benchmarkId?: string) => {
+ const navigate = useWorkspaceAwareNavigate();
+ const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);
+ // The dataset page can open before the benchmark list: load the benchmark to know its side.
+ useFetchBenchmarkDetail(benchmarkId);
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
+ const firstDatasetId = useEvalStore((s) => datasetSelectors.datasetList(benchmarkId)(s)[0]?.id);
+
+ const createRun = useCallback(
+ (dataset?: { id: string; name?: string }) => {
+ if (!benchmarkId) return;
+ if (lobeBench) {
+ navigate(newExperimentPath(dataset?.id ?? firstDatasetId));
+ return;
+ }
+ createRunCreateModal({ benchmarkId, datasetId: dataset?.id, datasetName: dataset?.name });
+ },
+ [benchmarkId, firstDatasetId, lobeBench, navigate],
+ );
+
+ return { createRun, lobeBench };
+};
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/EmptyState.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/EmptyState.tsx
index cc3d11d5c27..696643f81fa 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/EmptyState.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/EmptyState.tsx
@@ -32,10 +32,12 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface EmptyStateProps {
+ /** The button text; a Lobe Bench benchmark starts an experiment rather than a run. */
+ createLabel?: string;
onCreate: () => void;
}
-const EmptyState = memo<EmptyStateProps>(({ onCreate }) => {
+const EmptyState = memo<EmptyStateProps>(({ createLabel, onCreate }) => {
const { t } = useTranslation('eval');
return (
@@ -50,7 +52,7 @@ const EmptyState = memo<EmptyStateProps>(({ onCreate }) => {
</Text>
</Flexbox>
<Button icon={Plus} type="primary" onClick={onCreate}>
- {t('run.actions.create')}
+ {createLabel ?? t('run.actions.create')}
</Button>
</Flexbox>
);
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
index 21598a46b86..71efefa575f 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
@@ -181,12 +181,14 @@ const styles = createStaticStyles(({ css }) => ({
interface RunCardProps {
benchmarkId: string;
+ /** A note shown beside the status, e.g. how many of the set's cases the run picked. */
+ note?: string;
onEdit?: (run: AgentEvalRunListItem) => void;
onRefresh?: () => Promise<void>;
run: AgentEvalRunListItem;
}
-const RunCard = memo<RunCardProps>(({ benchmarkId, run, onRefresh, onEdit }) => {
+const RunCard = memo<RunCardProps>(({ benchmarkId, run, note, onRefresh, onEdit }) => {
const { t } = useTranslation('eval');
const deleteRun = useEvalStore((s) => s.deleteRun);
@@ -332,6 +334,7 @@ const RunCard = memo<RunCardProps>(({ benchmarkId, run, onRefresh, onEdit }) =>
<Flexbox horizontal align="center" gap={8}>
<span className={styles.name}>{run.name}</span>
<StatusBadge status={run.status} />
+ {note && <span className={styles.metaHighlight}>{note}</span>}
</Flexbox>
{metaParts.length > 0 && (
<Flexbox horizontal align="center" className={styles.meta} gap={4} wrap="wrap">
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
index 326ad26309c..efe56121a2d 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { runSelectors, useEvalStore } from '@/store/eval';
-import { createRunCreateModal } from '../RunCreateModal';
+import { useCreateRun } from '../RunCreateModal/useCreateRun';
import { createRunEditModal } from '../RunEditModal';
import EmptyState from './EmptyState';
import RunCard from './RunCard';
@@ -48,6 +48,8 @@ const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {
const runList = useEvalStore(runSelectors.runList(benchmarkId));
const refreshRuns = useEvalStore((s) => s.refreshRuns);
useFetchRuns(benchmarkId);
+ const { createRun, lobeBench } = useCreateRun(benchmarkId);
+ const createLabel = lobeBench ? t('lobeBench.benchmark.newExperiment') : t('run.actions.create');
const sortedRuns = useMemo(
() =>
@@ -90,19 +92,14 @@ const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {
onChange={setStatusFilter}
/>
</Flexbox>
- <Button
- icon={Plus}
- size="small"
- type="primary"
- onClick={() => createRunCreateModal({ benchmarkId })}
- >
- {t('run.actions.create')}
+ <Button icon={Plus} size="small" type="primary" onClick={() => createRun()}>
+ {createLabel}
</Button>
</Flexbox>
)}
{sortedRuns.length === 0 ? (
- <EmptyState onCreate={() => createRunCreateModal({ benchmarkId })} />
+ <EmptyState createLabel={createLabel} onCreate={() => createRun()} />
) : filteredRuns.length === 0 ? (
<Flexbox className={styles.filterEmpty}>
<Text color={cssVar.colorTextTertiary}>{t('run.filter.empty')}</Text>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx
index e6b121866f7..4fc52f4e9a4 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx
@@ -20,6 +20,8 @@ import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
+import BenchmarkLeaderboard from '@/features/LobeBench/BenchmarkLeaderboard';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import { datasetSelectors, runSelectors, useEvalStore } from '@/store/eval';
import BenchmarkHeader from './features/BenchmarkHeader';
@@ -88,6 +90,7 @@ const BenchmarkDetail = memo(() => {
const refreshDatasets = useEvalStore((s) => s.refreshDatasets);
const useFetchRuns = useEvalStore((s) => s.useFetchRuns);
const runList = useEvalStore(runSelectors.runList(benchmarkId));
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
const { error, isLoading, mutate } = useFetchBenchmarkDetail(benchmarkId);
useFetchDatasets(benchmarkId);
@@ -125,10 +128,14 @@ const BenchmarkDetail = memo(() => {
datasets={datasets}
runCount={runList.length}
systemIcon={systemIcon}
+ topLabel={lobeBench ? t('benchmark.detail.stats.topModels') : undefined}
totalCases={totalCases}
onBenchmarkUpdate={handleBenchmarkUpdate}
/>
+ {/* A Lobe Bench benchmark ranks its contenders here too, as on its Lobe Bench page. */}
+ {lobeBench && <BenchmarkLeaderboard benchmarkId={benchmarkId!} />}
+
{/* Tags */}
{(benchmark as any).tags && (benchmark as any).tags.length > 0 && (
<Flexbox horizontal gap={8} style={{ flexWrap: 'wrap' }}>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/ChatArea/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/ChatArea/index.tsx
index 2f34825fd4f..a3843f268ff 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/ChatArea/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/ChatArea/index.tsx
@@ -24,11 +24,13 @@ const styles = createStaticStyles(({ css }) => ({
interface ChatAreaProps {
agentId: string;
+ /** Changes when the attempt's state does, so a page opened mid-run reloads the messages. */
+ reloadKey?: string | null;
threadId?: string;
topicId: string;
}
-const ChatArea = memo<ChatAreaProps>(({ agentId, topicId, threadId }) => {
+const ChatArea = memo<ChatAreaProps>(({ agentId, topicId, threadId, reloadKey }) => {
const { t } = useTranslation('eval');
useInitAgentConfig(agentId);
@@ -37,8 +39,9 @@ const ChatArea = memo<ChatAreaProps>(({ agentId, topicId, threadId }) => {
[],
);
- // Use threadId as part of key to force re-render when switching threads
- const contextKey = threadId ? `${topicId}-${threadId}` : topicId;
+ // Use threadId as part of key to force re-render when switching threads; the
+ // reload key does the same when the attempt finishes after the page opened.
+ const contextKey = [topicId, threadId, reloadKey].filter(Boolean).join('-');
return (
<ConversationProvider context={{ agentId, threadId, topicId }} key={contextKey}>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx
index eb885d548fa..ff225fdaf83 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx
@@ -1,9 +1,11 @@
'use client';
-import type { EvalRubricScore } from '@lobechat/types';
+import type { EvalMemorySnapshot, EvalRubricScore } from '@lobechat/types';
import { formatCost, formatShortenNumber } from '@lobechat/utils';
import {
Accordion,
+ Alert,
+ Button,
createStaticStyles,
cssVar,
Flexbox,
@@ -14,6 +16,10 @@ import {
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import { levelLabelKey, resolveCaseDifficulty } from '@/features/Eval/caseDifficulty';
+import { getJudgeFailure } from '@/features/Eval/judgeError';
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+
import SegmentBar from '../../../../../../../../features/SegmentBar';
const styles = createStaticStyles(({ css }) => ({
@@ -87,7 +93,11 @@ export interface EvalResultDisplayData {
cost?: number;
duration?: number;
error?: string;
+ errorPhase?: string;
externalResult?: Record<string, unknown>;
+ judgeError?: string;
+ /** The attempt's Memory at the end: what the case seeded and what the model wrote. */
+ memorySnapshot?: EvalMemorySnapshot;
rubricScores?: EvalRubricScore[];
steps?: number;
tokens?: number;
@@ -95,8 +105,10 @@ export interface EvalResultDisplayData {
interface InfoSidebarProps {
evalResult?: EvalResultDisplayData | null;
+ experimentId?: string;
passed?: boolean | null;
score?: number | null;
+ status?: string | null;
testCase?: any;
}
@@ -130,10 +142,13 @@ const isDeterministicMode = (rubricId: string): boolean => {
return DETERMINISTIC_MODES.has(getEvalModeFromRubricId(rubricId));
};
-const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, score }) => {
+const InfoSidebar = memo<InfoSidebarProps>((props) => {
+ const { testCase, evalResult, passed, score, status, experimentId } = props;
const { t } = useTranslation('eval');
+ const judgeFailure = getJudgeFailure(status, evalResult);
+ const difficulty = resolveCaseDifficulty(testCase?.metadata);
const rubricScores = evalResult?.rubricScores;
- const hasRubricScores = rubricScores && rubricScores.length > 0;
+ const hasRubricScores = !judgeFailure && rubricScores && rubricScores.length > 0;
// Check if all rubrics are deterministic (no score/reason display needed)
const allDeterministic =
@@ -143,8 +158,18 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
? rubricScores.filter((s) => !isDeterministicMode(s.rubricId))
: [];
- const hasScore = score !== undefined && score !== null;
+ const hasScore = !judgeFailure && score !== undefined && score !== null;
const scorePct = hasScore ? Math.max(0, Math.min(100, Math.round(score * 100))) : 0;
+ // A rule-checklist judge reports one verdict per rule beside its prose reason.
+ const ruleVerdicts = judgeFailure
+ ? []
+ : (rubricScores?.find((s) => s.verdicts?.length)?.verdicts ?? []);
+ const memoryEntries = evalResult?.memorySnapshot?.entries;
+ const formatDay = (value?: string) => {
+ if (!value) return '';
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? value : date.toISOString().slice(0, 10);
+ };
return (
<Flexbox
@@ -153,8 +178,28 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
padding={16}
style={{ height: '100%', overflowY: 'auto', width: 320 }}
>
+ {judgeFailure && (
+ <Flexbox className={styles.section} gap={8}>
+ <Alert title={t('lobeBench.compare.judgeError')} type={'warning'} />
+ {judgeFailure.diagnostic && (
+ <Text className={styles.copyBlock} type={'warning'}>
+ {judgeFailure.diagnostic}
+ </Text>
+ )}
+ {experimentId && (
+ <>
+ <Text fontSize={12} type={'secondary'}>
+ {t('caseDetail.judgeError.regradeHint')}
+ </Text>
+ <WorkspaceLink to={`/eval/lobe-bench/experiments/${experimentId}`}>
+ <Button size={'small'}>{t('lobeBench.attempt.backToExperiment')}</Button>
+ </WorkspaceLink>
+ </>
+ )}
+ </Flexbox>
+ )}
{/* Failure reason — error states surface at the top of the panel */}
- {evalResult?.error && (
+ {!judgeFailure && evalResult?.error && (
<Flexbox className={styles.section} gap={8}>
<SectionTitle>{t('caseDetail.failureReason')}</SectionTitle>
<Text className={styles.copyBlock} type="danger">
@@ -185,20 +230,26 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
</Flexbox>
)}
- {testCase?.metadata?.difficulty && (
+ {difficulty && (
<Flexbox gap={4}>
<Text fontSize={12} type="secondary">
{t('caseDetail.difficulty')}
</Text>
<Flexbox horizontal>
- <Tag>{t(`difficulty.${testCase.metadata.difficulty}` as any)}</Tag>
+ <Tag>
+ {t(
+ difficulty.kind === 'level'
+ ? levelLabelKey(difficulty.level)
+ : `difficulty.${difficulty.value}`,
+ )}
+ </Tag>
</Flexbox>
</Flexbox>
)}
</Flexbox>
{/* Scoring Details */}
- {(hasRubricScores || score !== undefined) && (
+ {!judgeFailure && (hasRubricScores || score !== undefined) && (
<Flexbox className={styles.section} gap={12}>
<SectionTitle>{t('caseDetail.section.scoring')}</SectionTitle>
@@ -227,7 +278,10 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
</Flexbox>
<SegmentBar
segments={[
- { color: passed ? cssVar.colorSuccess : cssVar.colorError, value: scorePct },
+ {
+ color: passed ? cssVar.colorSuccess : cssVar.colorError,
+ value: scorePct,
+ },
{ color: cssVar.colorFillSecondary, value: 100 - scorePct },
]}
/>
@@ -259,6 +313,35 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
</Flexbox>
)}
+ {/* Rules: one line per rule, the reason only where the judge found it unmet */}
+ {ruleVerdicts.length > 0 && (
+ <Flexbox className={styles.section} gap={8}>
+ <SectionTitle>{t('caseDetail.section.rules')}</SectionTitle>
+ <Flexbox gap={6}>
+ {ruleVerdicts.map((item, index) => (
+ <Flexbox gap={2} key={index}>
+ <Text
+ fontSize={12}
+ type={
+ item.verdict === 'satisfied'
+ ? 'secondary'
+ : item.verdict === 'violated'
+ ? 'danger'
+ : 'warning'
+ }
+ >
+ {item.verdict === 'satisfied' ? '✓' : item.verdict === 'violated' ? '✗' : '?'}{' '}
+ {item.rule}
+ </Text>
+ {item.verdict !== 'satisfied' && item.reason && (
+ <span className={styles.rubricReason}>{item.reason}</span>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+
{/* Runtime */}
<Flexbox gap={8}>
<SectionTitle>{t('caseDetail.section.runtime')}</SectionTitle>
@@ -299,6 +382,46 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor
)}
</Flexbox>
+ {/* Memory the attempt ended with: seeded rows and rows the model wrote */}
+ {memoryEntries && (
+ <Flexbox gap={8}>
+ <SectionTitle>{t('caseDetail.section.memory')}</SectionTitle>
+ {memoryEntries.length === 0 ? (
+ <Text fontSize={12} type="secondary">
+ {t('caseDetail.memory.empty')}
+ </Text>
+ ) : (
+ <Flexbox gap={8}>
+ {memoryEntries.map((entry) => (
+ <Flexbox gap={2} key={entry.id}>
+ <Flexbox horizontal align="center" gap={6} wrap="wrap">
+ <Tag>{entry.layer}</Tag>
+ <Tag color={entry.source === 'agent' ? 'processing' : undefined}>
+ {entry.source === 'agent'
+ ? t('caseDetail.memory.agent')
+ : t('caseDetail.memory.seed')}
+ </Tag>
+ {entry.removedReason && (
+ <Tag color="warning">{t('caseDetail.memory.removed')}</Tag>
+ )}
+ <span className={styles.rubricScore}>{formatDay(entry.capturedAt)}</span>
+ </Flexbox>
+ <Text
+ fontSize={12}
+ style={entry.removedReason ? { textDecoration: 'line-through' } : undefined}
+ >
+ {entry.title || entry.summary || entry.details || entry.layer}
+ </Text>
+ {entry.title && entry.summary && entry.summary !== entry.title && (
+ <span className={styles.rubricReason}>{entry.summary}</span>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ )}
+
{evalResult?.externalResult && (
<Flexbox gap={8}>
<SectionTitle>{t('caseDetail.section.externalResult')}</SectionTitle>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
index 6e7c15a944f..f6f0a5ef22e 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
@@ -4,10 +4,14 @@ import type { EvalThreadResult } from '@lobechat/types';
import { cssVar, Flexbox, Tabs } from '@lobehub/ui';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
+import { useParams, useSearchParams } from 'react-router';
import AsyncBoundary from '@/components/AsyncBoundary';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
+import {
+ experimentContextSuffix,
+ parseExperimentId,
+} from '@/features/LobeBench/experimentNavigation';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { runSelectors, useEvalStore } from '@/store/eval';
@@ -25,6 +29,10 @@ const CaseDetail = memo(() => {
}>();
const { t } = useTranslation('eval');
const navigate = useWorkspaceAwareNavigate();
+ // Opened from a Lobe Bench experiment: "back" returns there and prev/next keep the context.
+ const [searchParams] = useSearchParams();
+ const experimentId = parseExperimentId(searchParams.get('experiment'));
+ const suffix = experimentContextSuffix(experimentId);
const useFetchRunDetail = useEvalStore((s) => s.useFetchRunDetail);
const useFetchRunResults = useEvalStore((s) => s.useFetchRunResults);
const isActive = useEvalStore(runSelectors.isRunActive(runId!));
@@ -108,10 +116,20 @@ const CaseDetail = memo(() => {
<CaseHeader
caseNumber={(caseResult.testCase?.sortOrder ?? 0) + 1}
evalResult={displayEvalResult}
- runName={runDetail?.name || runId!.slice(0, 8)}
- onBack={() => navigate(`/eval/bench/${benchmarkId}/runs/${runId}`)}
- onNext={nextCaseId ? () => navigate(`${basePath}/${nextCaseId}`) : undefined}
- onPrev={prevCaseId ? () => navigate(`${basePath}/${prevCaseId}`) : undefined}
+ runName={
+ experimentId
+ ? t('lobeBench.attempt.backToExperiment')
+ : runDetail?.name || runId!.slice(0, 8)
+ }
+ onNext={nextCaseId ? () => navigate(`${basePath}/${nextCaseId}${suffix}`) : undefined}
+ onPrev={prevCaseId ? () => navigate(`${basePath}/${prevCaseId}${suffix}`) : undefined}
+ onBack={() =>
+ navigate(
+ experimentId
+ ? `/eval/lobe-bench/experiments/${experimentId}`
+ : `/eval/bench/${benchmarkId}/runs/${runId}`,
+ )
+ }
/>
{hasMultipleThreads && (
<Flexbox
@@ -132,6 +150,7 @@ const CaseDetail = memo(() => {
{topicId && agentId ? (
<ChatArea
agentId={agentId}
+ reloadKey={caseResult.status}
threadId={activeThreadId ?? undefined}
topicId={topicId}
/>
@@ -140,8 +159,10 @@ const CaseDetail = memo(() => {
)}
<InfoSidebar
evalResult={displayEvalResult}
+ experimentId={experimentId ?? undefined}
passed={displayPassed}
score={displayScore}
+ status={currentThread ? currentThread.status : caseResult.status}
testCase={caseResult.testCase}
/>
</Flexbox>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
index 8daa6643da6..748a54f3f60 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
@@ -30,6 +30,8 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import AgentAvatar from '@/components/AgentAvatar';
+import { benchmarkDatasetPath, runBackPath } from '@/features/LobeBench/experimentNavigation';
+import { useIsLobeBenchBenchmark } from '@/features/LobeBench/useIsLobeBenchBenchmark';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
@@ -200,6 +202,9 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
const canStart = run.status === 'idle' || run.status === 'failed' || run.status === 'aborted';
const [starting, setStarting] = useState(false);
const [showConfig, setShowConfig] = useState(false);
+ const lobeBench = useIsLobeBenchBenchmark(benchmarkId);
+ const backPath = runBackPath({ benchmarkId, experimentId: run.experimentId, lobeBench });
+ const backToExperiment = lobeBench && backPath.includes('/experiments/');
const snapshot = run.config?.agentSnapshot;
const agentTitle = run.targetAgent?.title || t('run.detail.agent.unnamed');
@@ -224,7 +229,7 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
okText: t('run.actions.delete'),
onOk: async () => {
await deleteRun(run.id);
- navigate(`/eval/bench/${benchmarkId}`);
+ navigate(backPath);
},
title: t('run.actions.delete'),
});
@@ -274,9 +279,11 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
return (
<Flexbox gap={16}>
{/* Back link */}
- <WorkspaceLink className={styles.backLink} to={`/eval/bench/${benchmarkId}`}>
+ <WorkspaceLink className={styles.backLink} to={backPath}>
<ArrowLeft size={16} />
- {t('run.detail.backToBenchmark')}
+ {backToExperiment
+ ? t('lobeBench.attempt.backToExperiment')
+ : t('run.detail.backToBenchmark')}
</WorkspaceLink>
{/* Header band — results-led: run name + status prominent, meta as a quiet stat row */}
@@ -300,7 +307,7 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
<WorkspaceLink
className={styles.datasetLink}
target="_blank"
- to={`/eval/bench/${benchmarkId}/datasets/${run.dataset.id}`}
+ to={benchmarkDatasetPath(run.dataset.id, lobeBench)}
>
<span className={styles.metaItem}>{run.dataset.name}</span>
</WorkspaceLink>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.test.ts b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.test.ts
new file mode 100644
index 00000000000..9b927032c12
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.test.ts
@@ -0,0 +1,52 @@
+import type { EvalRunMetrics } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { attemptRates } from './attemptRates';
+
+const metrics = (extra: Partial<EvalRunMetrics>): EvalRunMetrics => ({
+ completedCases: 50,
+ errorCases: 0,
+ failedCases: 9,
+ passedCases: 41,
+ passRate: 0.82,
+ totalCases: 50,
+ ...extra,
+});
+
+describe('attemptRates', () => {
+ it('reports pass@k, pass^k and the per-attempt rate of a run of several attempts', () => {
+ const rates = attemptRates(
+ metrics({ passAllK: 0.48, passAnyAt: { '1': 0.6667, '3': 0.82 }, passAtK: 0.82 }),
+ 3,
+ );
+
+ expect(rates).toEqual({
+ allK: { count: 24, rate: 0.48 },
+ anyK: { count: 41, rate: 0.82 },
+ k: 3,
+ perAttempt: { rate: 0.6667 },
+ });
+ });
+
+ it('falls back to the per-j estimates when the k fields are absent', () => {
+ const rates = attemptRates(
+ metrics({ passAllAt: { '1': 0.66, '2': 0.55, '3': 0.48 }, passAnyAt: { '3': 0.82 } }),
+ 3,
+ );
+
+ expect(rates?.allK).toEqual({ count: 24, rate: 0.48 });
+ expect(rates?.anyK).toEqual({ count: 41, rate: 0.82 });
+ });
+
+ // An unfinished run has no pass^k yet; it must not read as 0%.
+ it('leaves a rate the server has not filled undefined', () => {
+ const rates = attemptRates(metrics({}), 3);
+
+ expect(rates).toEqual({ allK: undefined, anyK: undefined, k: 3, perAttempt: undefined });
+ });
+
+ it('has nothing to add for a run of one attempt', () => {
+ expect(attemptRates(metrics({ passAtK: 0.82 }), 1)).toBeUndefined();
+ expect(attemptRates(undefined, 3)).toBeUndefined();
+ });
+});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.ts b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.ts
new file mode 100644
index 00000000000..9b3a470dce0
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/attemptRates.ts
@@ -0,0 +1,46 @@
+import type { EvalRunMetrics } from '@lobechat/types';
+
+export interface AttemptRate {
+ /** Cases counted, when the rate is a share of whole cases. */
+ count?: number;
+ rate: number;
+}
+
+export interface AttemptRates {
+ /** Cases that passed every one of the k attempts (pass^k). */
+ allK?: AttemptRate;
+ /** Cases that passed at least one of the k attempts (pass@k). */
+ anyK?: AttemptRate;
+ k: number;
+ /** Share of single attempts that passed (pass@1). */
+ perAttempt?: AttemptRate;
+}
+
+const ratio = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+/**
+ * The rates a run of several attempts per case reports beside its pass rate.
+ * The server fills them only once every case is judged, so a missing one stays
+ * missing instead of reading as 0%. Returns undefined for a run of one attempt,
+ * where all three equal the pass rate.
+ */
+export const attemptRates = (
+ metrics: EvalRunMetrics | undefined,
+ k: number,
+): AttemptRates | undefined => {
+ if (!metrics || !(k > 1)) return undefined;
+ const total = metrics.totalCases ?? 0;
+ const ofCases = (value: unknown): AttemptRate | undefined => {
+ const rate = ratio(value);
+ if (rate === undefined) return undefined;
+ return { count: total > 0 ? Math.round(rate * total) : undefined, rate };
+ };
+ const perAttempt = ratio(metrics.passAnyAt?.['1']);
+ return {
+ allK: ofCases(metrics.passAllK ?? metrics.passAllAt?.[String(k)]),
+ anyK: ofCases(metrics.passAtK ?? metrics.passAnyAt?.[String(k)]),
+ k,
+ perAttempt: perAttempt === undefined ? undefined : { rate: perAttempt },
+ };
+};
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/index.tsx
index e69d8f3b730..e863b2c1fec 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/StatsCards/index.tsx
@@ -8,6 +8,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { formatDuration } from '../../../../../../utils';
+import { attemptRates } from './attemptRates';
const styles = createStaticStyles(({ css }) => ({
card: css`
@@ -66,6 +67,16 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillSecondary};
`,
+ attemptRates: css`
+ padding-block-start: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ attemptValue: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeLG};
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
subtitle: css`
font-size: ${cssVar.fontSize};
color: ${cssVar.colorTextSecondary};
@@ -83,16 +94,31 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface StatsCardsProps {
+ /** Attempts per case; above 1 the pass rate is pass@k and pass^k is shown beside it. */
+ k?: number;
metrics?: EvalRunMetrics;
}
-const StatsCards = memo<StatsCardsProps>(({ metrics }) => {
+const percent = (rate: number) => `${Math.round(rate * 100)}%`;
+
+const StatsCards = memo<StatsCardsProps>(({ k = 1, metrics }) => {
const { t } = useTranslation('eval');
const passedCount = metrics?.passedCases ?? 0;
const totalCases = metrics?.totalCases ?? 0;
const hasPassRate = metrics?.passRate !== undefined;
const passPct = hasPassRate ? Math.round((metrics?.passRate ?? 0) * 100) : 0;
+ const rates = attemptRates(metrics, k);
+ const attemptItems = rates
+ ? [
+ {
+ count: rates.allK?.count,
+ label: t('run.metrics.passAllK', { k }),
+ rate: rates.allK?.rate,
+ },
+ { label: t('run.metrics.perAttempt'), rate: rates.perAttempt?.rate },
+ ]
+ : [];
const cards = [
{
@@ -149,7 +175,9 @@ const StatsCards = memo<StatsCardsProps>(({ metrics }) => {
<div className={styles.iconBox} style={{ background: cssVar.colorSuccessBg }}>
<Icon icon={CheckCircle2} size={16} style={{ color: cssVar.colorSuccess }} />
</div>
- <span className={styles.label}>{t('run.metrics.passRate')}</span>
+ <span className={styles.label}>
+ {rates ? t('run.metrics.passRate.anyK', { k }) : t('run.metrics.passRate')}
+ </span>
</Flexbox>
<span className={styles.heroValue}>{hasPassRate ? `${passPct}%` : '-'}</span>
</Flexbox>
@@ -165,6 +193,25 @@ const StatsCards = memo<StatsCardsProps>(({ metrics }) => {
<div className={styles.progressFill} style={{ width: `${passPct}%` }} />
</div>
)}
+ {attemptItems.length > 0 && (
+ <Flexbox horizontal className={styles.attemptRates} gap={32} wrap={'wrap'}>
+ {attemptItems.map((item) => (
+ <Flexbox gap={2} key={item.label}>
+ <span className={styles.label}>{item.label}</span>
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <span className={styles.attemptValue}>
+ {item.rate === undefined ? '-' : percent(item.rate)}
+ </span>
+ {item.count !== undefined && totalCases > 0 && (
+ <span className={styles.subtitleUnit}>
+ {item.count}/{totalCases}
+ </span>
+ )}
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
</Flexbox>
{/* Secondary metrics */}
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
index 3af745100f3..ec14a8047d3 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
@@ -134,7 +134,7 @@ const RunDetail = memo(() => {
<span className={styles.panelLabel}>{t('run.detail.report')}</span>
</header>
<div className={styles.panelBody}>
- <StatsCards metrics={runDetail.metrics ?? undefined} />
+ <StatsCards k={k} metrics={runDetail.metrics ?? undefined} />
{hasResults && (
<BenchmarkCharts
benchmarkId={benchmarkId!}
diff --git a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
index 887befa04fb..e201dcf7108 100644
--- a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
+++ b/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
@@ -16,6 +16,7 @@ import { useParams } from 'react-router';
import AsyncBoundary from '@/components/AsyncBoundary';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
+import { DatasetConnections } from '@/features/AgentEval/ConnectorBindings/DatasetConnections';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { agentEvalService } from '@/services/agentEval';
@@ -23,7 +24,7 @@ import { runSelectors, testCaseSelectors, useEvalStore } from '@/store/eval';
import TestCasePreviewPanel from '../../bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel';
import TestCaseTable from '../../bench/[benchmarkId]/features/DatasetsTab/TestCaseTable';
-import { createRunCreateModal } from '../../bench/[benchmarkId]/features/RunCreateModal';
+import { useCreateRun } from '../../bench/[benchmarkId]/features/RunCreateModal/useCreateRun';
import EmptyState from '../../bench/[benchmarkId]/features/RunsTab/EmptyState';
import RunCard from '../../bench/[benchmarkId]/features/RunsTab/RunCard';
import { createDatasetEditModal } from '../../features/DatasetEditModal';
@@ -120,6 +121,7 @@ const DatasetDetail = memo(() => {
const benchmarkId: string | null =
(dataset as { benchmarkId?: string | null })?.benchmarkId ?? null;
useFetchDatasetRuns(datasetId);
+ const { createRun, lobeBench } = useCreateRun(benchmarkId ?? undefined);
const sortedRuns = useMemo(
() =>
@@ -308,6 +310,8 @@ const DatasetDetail = memo(() => {
)}
</Flexbox>
+ <DatasetConnections datasetId={dataset.id} editable={!!dataset.userId} />
+
{/* Test Cases */}
<Flexbox gap={12}>
<Flexbox horizontal align="center" justify="space-between">
@@ -361,15 +365,11 @@ const DatasetDetail = memo(() => {
<Button
icon={Plus}
size="small"
- onClick={() =>
- createRunCreateModal({
- benchmarkId: benchmarkId!,
- datasetId: datasetId!,
- datasetName: dataset.name,
- })
- }
+ onClick={() => createRun({ id: datasetId!, name: dataset.name })}
>
- {t('dataset.detail.addRun')}
+ {lobeBench
+ ? t('lobeBench.benchmark.newExperiment')
+ : t('dataset.detail.addRun')}
</Button>
</Flexbox>
{sortedRuns.length > 0 ? (
@@ -380,13 +380,8 @@ const DatasetDetail = memo(() => {
</Flexbox>
) : (
<EmptyState
- onCreate={() =>
- createRunCreateModal({
- benchmarkId: benchmarkId!,
- datasetId: datasetId!,
- datasetName: dataset.name,
- })
- }
+ createLabel={lobeBench ? t('lobeBench.benchmark.newExperiment') : undefined}
+ onCreate={() => createRun({ id: datasetId!, name: dataset.name })}
/>
)}
</Flexbox>
diff --git a/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
index 8ad79bc6136..01b08c9f655 100644
--- a/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
@@ -1,19 +1,12 @@
'use client';
-import { cssVar, Input, Select, TextArea, toast, useModalContext } from '@lobehub/ui';
-import { Form, useForm, useWatch } from '@lobehub/ui/form';
-import { type FC, useEffect, useState } from 'react';
+import { Input, TextArea, toast, useModalContext } from '@lobehub/ui';
+import { Form, useForm } from '@lobehub/ui/form';
+import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import { useEvalStore } from '@/store/eval';
-const toIdentifier = (name: string) =>
- name
- .trim()
- .toLowerCase()
- .replaceAll(/\s+/g, '-')
- .replaceAll(/[^\da-z-]/g, '');
-
export interface BenchmarkEditContentProps {
benchmark: {
description?: string;
@@ -21,7 +14,6 @@ export interface BenchmarkEditContentProps {
identifier: string;
metadata?: any;
name: string;
- tags?: string[];
};
formId: string;
onLoadingChange?: (loading: boolean) => void;
@@ -37,7 +29,6 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [identifierTouched, setIdentifierTouched] = useState(false);
const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
const handleFinish = async (values: any) => {
@@ -46,9 +37,7 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
await updateBenchmark({
description: values.description?.trim() || undefined,
id: benchmark.id,
- identifier: values.identifier.trim(),
name: values.name.trim(),
- tags: values.tags?.length > 0 ? values.tags : undefined,
});
toast.success(t('benchmark.edit.success'));
close();
@@ -63,19 +52,10 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
const form = useForm({
initialValues: {
description: benchmark.description || '',
- identifier: benchmark.identifier,
name: benchmark.name,
- tags: benchmark.tags || [],
},
onSubmit: handleFinish,
});
- const nameValue = useWatch(form, 'name');
-
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
return (
<Form form={form} id={formId} layout="vertical">
@@ -87,31 +67,9 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
<Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
</Form.Field>
- <Form.Field
- label={t('benchmark.create.identifier.label')}
- name="identifier"
- required={t('benchmark.create.identifierRequired')}
- >
- <Input
- placeholder={t('benchmark.create.identifier.placeholder')}
- style={{ fontFamily: cssVar.fontFamilyCode }}
- onChange={() => setIdentifierTouched(true)}
- />
- </Form.Field>
-
<Form.Field label={t('benchmark.create.description.label')} name="description">
<TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
</Form.Field>
-
- <Form.Field label={t('benchmark.create.tags.label')} name="tags">
- <Select
- mode="tags"
- open={false}
- placeholder={t('benchmark.create.tags.placeholder')}
- style={{ width: '100%' }}
- tokenSeparators={[',', ',', ' ']}
- />
- </Form.Field>
</Form>
);
};
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
index 401603b05d6..9debb151d24 100644
--- a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
@@ -1,6 +1,6 @@
'use client';
-import { cssVar, Input, Select, TextArea, toast, useModalContext } from '@lobehub/ui';
+import { cssVar, Input, TextArea, toast, useModalContext } from '@lobehub/ui';
import { Form, useForm, useWatch } from '@lobehub/ui/form';
import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -35,7 +35,6 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
description: values.description?.trim() || undefined,
identifier: values.identifier.trim(),
name: values.name.trim(),
- tags: values.tags?.length > 0 ? values.tags : undefined,
});
toast.success(t('benchmark.create.success'));
close();
@@ -85,16 +84,6 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
<Form.Field label={t('benchmark.create.description.label')} name="description">
<TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
</Form.Field>
-
- <Form.Field label={t('benchmark.create.tags.label')} name="tags">
- <Select
- mode="tags"
- open={false}
- placeholder={t('benchmark.create.tags.placeholder')}
- style={{ width: '100%' }}
- tokenSeparators={[',', ',', ' ']}
- />
- </Form.Field>
</Form>
);
};
diff --git a/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
index 991ebbb0c89..3a825b3ee68 100644
--- a/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
@@ -141,7 +141,8 @@ const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
benchmarkId,
description: values.description,
evalConfig:
- values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ (values.evalMode === 'llm-rubric' || values.evalMode === 'rule-checklist') &&
+ values.evalConfig?.judgePrompt
? values.evalConfig
: undefined,
evalMode: values.evalMode || undefined,
@@ -221,12 +222,13 @@ const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
{ label: t('evalMode.equals'), value: 'equals' },
{ label: t('evalMode.contains'), value: 'contains' },
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.rule-checklist'), value: 'rule-checklist' },
{ label: t('evalMode.external'), value: 'external' },
]}
/>
</Form.Field>
- {evalModeValue === 'llm-rubric' && (
+ {(evalModeValue === 'llm-rubric' || evalModeValue === 'rule-checklist') && (
<Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
</Form.Field>
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
index a7417fc3720..e69f0ff7332 100644
--- a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
@@ -136,7 +136,9 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
await agentEvalService.updateDataset({
description: values.description?.trim() || undefined,
evalConfig:
- (values.evalMode === 'llm-rubric' || values.evalMode === 'answer-relevance') &&
+ (values.evalMode === 'llm-rubric' ||
+ values.evalMode === 'rule-checklist' ||
+ values.evalMode === 'answer-relevance') &&
values.evalConfig?.judgePrompt
? values.evalConfig
: null,
@@ -206,13 +208,16 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
{ label: t('evalMode.equals'), value: 'equals' },
{ label: t('evalMode.contains'), value: 'contains' },
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.rule-checklist'), value: 'rule-checklist' },
{ label: t('evalMode.answer-relevance'), value: 'answer-relevance' },
{ label: t('evalMode.external'), value: 'external' },
]}
/>
</Form.Field>
- {(evalModeValue === 'llm-rubric' || evalModeValue === 'answer-relevance') && (
+ {(evalModeValue === 'llm-rubric' ||
+ evalModeValue === 'rule-checklist' ||
+ evalModeValue === 'answer-relevance') && (
<>
<Form.Field label={t('evalMode.provider.label')} name="evalConfig.provider">
<TextArea placeholder={t('evalMode.provider.placeholder')} rows={1} />
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx b/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx
index 103fa09d6cd..1dc2b7a08ea 100644
--- a/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx
@@ -1,9 +1,16 @@
'use client';
-import { toast } from '@lobehub/ui';
+import type {
+ AgentEvalDatasetPackageBindings,
+ AgentEvalDatasetPackagePreview,
+} from '@lobechat/types';
+import { Alert, Flexbox, toast } from '@lobehub/ui';
import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { hasPartialConnectorBindings } from '@/features/AgentEval/ConnectorBindings/bindings';
+import { DatasetPackagePreview } from '@/features/AgentEval/DatasetPackagePreview';
+import { datasetImportErrorMessage } from '@/features/AgentEval/DatasetPackagePreview/importError';
import { agentEvalService } from '@/services/agentEval';
import { uploadService } from '@/services/upload';
import { type FileUploadState } from '@/types/files/upload';
@@ -16,16 +23,18 @@ type MappingTarget =
'choices' | 'category' | 'expected' | 'ignore' | 'input' | 'metadata' | 'sortOrder';
export interface DatasetImportContentProps {
+ archiveOnly?: boolean;
close: () => void;
- datasetId: string;
+ datasetId?: string;
onImportReady: (api: { canImport: () => boolean; runImport: () => Promise<void> }) => void;
- onStateChange: (state: { canImport: boolean; step: 0 | 1 }) => void;
+ onStateChange: (state: { busy: boolean; canImport: boolean; step: 0 | 1 }) => void;
onSuccess?: (datasetId: string) => void;
presetId?: string;
setPrev: (fn: () => void) => void;
}
const DatasetImportContent: FC<DatasetImportContentProps> = ({
+ archiveOnly,
close,
datasetId,
onImportReady,
@@ -38,6 +47,8 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
const [step, setStep] = useState<0 | 1>(0);
const [uploading, setUploading] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const [error, setError] = useState<string>();
const [uploadProgress, setUploadProgress] = useState<FileUploadState>();
const [pathname, setPathname] = useState('');
@@ -46,7 +57,10 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
const [headers, setHeaders] = useState<string[]>([]);
const [preview, setPreview] = useState<Record<string, any>[]>([]);
const [totalCount, setTotalCount] = useState(0);
- const [format, setFormat] = useState<'csv' | 'json' | 'jsonl' | 'xlsx'>();
+ const [format, setFormat] = useState<'csv' | 'json' | 'jsonl' | 'xlsx' | 'zip'>();
+ const [datasetPackage, setDatasetPackage] = useState<AgentEvalDatasetPackagePreview>();
+ const [connectionBindings, setConnectionBindings] = useState<AgentEvalDatasetPackageBindings>({});
+ const [packageName, setPackageName] = useState('');
const [mapping, setMapping] = useState<Record<string, MappingTarget>>({});
const [delimiter, setDelimiter] = useState('');
@@ -54,17 +68,37 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
const preset = useMemo(() => (presetId ? getPresetById(presetId) : undefined), [presetId]);
const hasInputMapping = Object.values(mapping).includes('input');
+ const canImport =
+ format === 'zip'
+ ? !!datasetPackage &&
+ !hasPartialConnectorBindings(datasetPackage.connectionRequirements, connectionBindings) &&
+ // An import only imports: a dataset of its own, in no benchmark.
+ (!!datasetId || !!packageName.trim())
+ : !!datasetId && hasInputMapping;
useEffect(() => {
- onStateChange({ canImport: hasInputMapping, step });
- }, [hasInputMapping, onStateChange, step]);
+ onStateChange({ busy: uploading || importing, canImport, step });
+ }, [canImport, importing, onStateChange, step, uploading]);
useEffect(() => {
- setPrev(() => setStep(0));
+ setPrev(() => {
+ setError(undefined);
+ setStep(0);
+ });
}, [setPrev]);
const handleFileSelect = useCallback(
async (file: File) => {
+ setError(undefined);
+ const isArchive = file.name.toLowerCase().endsWith('.zip');
+ if (archiveOnly && !isArchive) {
+ setError(t('dataset.import.package.zipRequired'));
+ return;
+ }
+ if (isArchive && file.size > 10 * 1024 * 1024) {
+ setError(t('dataset.import.package.tooLarge'));
+ return;
+ }
setUploading(true);
setUploadProgress(undefined);
try {
@@ -86,22 +120,25 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
setHeaders(result.headers);
setPreview(result.preview);
setTotalCount(result.totalCount);
- setFormat(result.format as 'csv' | 'json' | 'jsonl' | 'xlsx');
-
- const inferred = autoInferMapping(result.headers, preset);
- setMapping(inferred);
+ setFormat(result.format === 'auto' ? undefined : result.format);
+ if (result.format === 'zip') {
+ setDatasetPackage(result.datasetPackage);
+ setConnectionBindings({});
+ setPackageName(result.datasetPackage.name);
+ } else {
+ setDatasetPackage(undefined);
+ setMapping(autoInferMapping(result.headers, preset));
+ }
setStep(1);
- } catch {
- setTimeout(() => {
- toast.error(t('dataset.import.parseError'));
- }, 0);
+ } catch (error) {
+ setError(datasetImportErrorMessage(error, t('dataset.import.parseError')));
} finally {
setUploading(false);
setUploadProgress(undefined);
}
},
- [preset, t],
+ [archiveOnly, preset, t],
);
const buildFieldMapping = useCallback((): FieldMappingValue | null => {
@@ -131,10 +168,28 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
}, [mapping, delimiter]);
const runImport = useCallback(async () => {
- const fieldMapping = buildFieldMapping();
- if (!fieldMapping) return;
-
+ if (!canImport) return;
+ setError(undefined);
+ setImporting(true);
try {
+ if (format === 'zip') {
+ const result = await agentEvalService.importDatasetPackage({
+ ...connectionBindings,
+ ...(datasetId
+ ? { datasetId }
+ : {
+ name: packageName.trim(),
+ }),
+ filename,
+ pathname,
+ });
+ toast.success(t('dataset.import.success', { count: result.count }));
+ close();
+ onSuccess?.(result.datasetId);
+ return;
+ }
+ const fieldMapping = buildFieldMapping();
+ if (!fieldMapping || !datasetId) return;
const result = await agentEvalService.importDataset({
datasetId,
fieldMapping: {
@@ -155,24 +210,38 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
}, 0);
close();
onSuccess?.(datasetId);
- } catch {
- setTimeout(() => {
- toast.error(t('dataset.import.error'));
- }, 0);
+ } catch (error) {
+ setError(datasetImportErrorMessage(error, t('dataset.import.error')));
+ } finally {
+ setImporting(false);
}
- }, [buildFieldMapping, close, datasetId, filename, format, onSuccess, pathname, t]);
+ }, [
+ buildFieldMapping,
+ canImport,
+ close,
+ connectionBindings,
+ datasetId,
+ filename,
+ format,
+ onSuccess,
+ packageName,
+ pathname,
+ t,
+ ]);
useEffect(() => {
onImportReady({
- canImport: () => hasInputMapping,
+ canImport: () => canImport,
runImport,
});
- }, [hasInputMapping, onImportReady, runImport]);
+ }, [canImport, onImportReady, runImport]);
return (
- <>
+ <Flexbox gap={16}>
+ {error && <Alert title={error} type="error" />}
{step === 0 && (
<UploadStep
+ archiveOnly={archiveOnly}
loading={uploading}
preset={preset}
uploadProgress={uploadProgress}
@@ -180,7 +249,20 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
/>
)}
- {step === 1 && (
+ {step === 1 && datasetPackage && format === 'zip' && (
+ <DatasetPackagePreview
+ bindings={connectionBindings}
+ datasetId={datasetId}
+ disabled={importing}
+ existingDataset={!!datasetId}
+ name={packageName}
+ preview={datasetPackage}
+ samples={preview}
+ onBindingsChange={setConnectionBindings}
+ onNameChange={setPackageName}
+ />
+ )}
+ {step === 1 && format !== 'zip' && (
<MappingStep
delimiter={delimiter}
headers={headers}
@@ -191,7 +273,7 @@ const DatasetImportContent: FC<DatasetImportContentProps> = ({
onMappingChange={setMapping}
/>
)}
- </>
+ </Flexbox>
);
};
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx b/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
index bc5c628dda1..fefc036f48e 100644
--- a/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
+++ b/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
@@ -84,6 +84,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface UploadStepProps {
+ archiveOnly?: boolean;
loading: boolean;
onFileSelect: (file: File) => void;
preset?: DatasetPreset;
@@ -107,115 +108,126 @@ const getFieldRole = (
}
};
-const UploadStep = memo<UploadStepProps>(({ onFileSelect, loading, preset, uploadProgress }) => {
- const { t } = useTranslation('eval');
-
- const fields = useMemo(() => {
- if (!preset) return [];
-
- const required = preset.requiredFields.map((name) => ({
- name,
- required: true,
- role: getFieldRole(name, preset.fieldInference),
- }));
-
- const optional = preset.optionalFields.map((name) => ({
- name,
- required: false,
- role: getFieldRole(name, preset.fieldInference),
- }));
-
- return [...required, ...optional];
- }, [preset]);
-
- return (
- <Flexbox gap={16}>
- {preset && (
- <Flexbox className={styles.container} gap={16}>
- {/* Identity */}
- <Flexbox horizontal align="center" gap={12}>
- <Center className={styles.iconCenter} flex="none" height={40} width={40}>
- <Icon icon={preset.icon} size={20} />
- </Center>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <div className={styles.presetName}>{preset.name}</div>
- <div className={styles.presetDescription}>{preset.description}</div>
+const UploadStep = memo<UploadStepProps>(
+ ({ archiveOnly, onFileSelect, loading, preset, uploadProgress }) => {
+ const { t } = useTranslation('eval');
+
+ const fields = useMemo(() => {
+ if (!preset) return [];
+
+ const required = preset.requiredFields.map((name) => ({
+ name,
+ required: true,
+ role: getFieldRole(name, preset.fieldInference),
+ }));
+
+ const optional = preset.optionalFields.map((name) => ({
+ name,
+ required: false,
+ role: getFieldRole(name, preset.fieldInference),
+ }));
+
+ return [...required, ...optional];
+ }, [preset]);
+
+ return (
+ <Flexbox gap={16}>
+ {preset && (
+ <Flexbox className={styles.container} gap={16}>
+ {/* Identity */}
+ <Flexbox horizontal align="center" gap={12}>
+ <Center className={styles.iconCenter} flex="none" height={40} width={40}>
+ <Icon icon={preset.icon} size={20} />
+ </Center>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <div className={styles.presetName}>{preset.name}</div>
+ <div className={styles.presetDescription}>{preset.description}</div>
+ </Flexbox>
</Flexbox>
- </Flexbox>
- {preset.formatDescription && (
- <div className={styles.formatDescription}>{preset.formatDescription}</div>
- )}
+ {preset.formatDescription && (
+ <div className={styles.formatDescription}>{preset.formatDescription}</div>
+ )}
- {/* Field-role legend */}
- {fields.length > 0 && (
- <Flexbox gap={8}>
- <span className={styles.sectionLabel}>{t('dataset.import.fieldMapping')}</span>
- <Flexbox horizontal className={styles.fieldsWrapper} gap={8}>
- {fields.map((field) => {
- const color = field.role ? ROLE_COLORS[field.role] : undefined;
- return (
- <Flexbox align="center" gap={2} key={field.name}>
- <Tag
- style={
- color
- ? {
- background: `color-mix(in srgb, ${color} 15%, transparent)`,
- borderColor: 'transparent',
- color,
- }
- : undefined
- }
- >
- {field.name}
- {field.required && ' *'}
- </Tag>
- {field.role && (
- <div className={styles.roleLabel} style={{ color: color || undefined }}>
- {field.role}
- </div>
- )}
- </Flexbox>
- );
- })}
+ {/* Field-role legend */}
+ {fields.length > 0 && (
+ <Flexbox gap={8}>
+ <span className={styles.sectionLabel}>{t('dataset.import.fieldMapping')}</span>
+ <Flexbox horizontal className={styles.fieldsWrapper} gap={8}>
+ {fields.map((field) => {
+ const color = field.role ? ROLE_COLORS[field.role] : undefined;
+ return (
+ <Flexbox align="center" gap={2} key={field.name}>
+ <Tag
+ style={
+ color
+ ? {
+ background: `color-mix(in srgb, ${color} 15%, transparent)`,
+ borderColor: 'transparent',
+ color,
+ }
+ : undefined
+ }
+ >
+ {field.name}
+ {field.required && ' *'}
+ </Tag>
+ {field.role && (
+ <div className={styles.roleLabel} style={{ color: color || undefined }}>
+ {field.role}
+ </div>
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
</Flexbox>
- </Flexbox>
- )}
- </Flexbox>
- )}
-
- <Upload
- dragger
- accept=".csv,.xlsx,.xls,.json,.jsonl"
- className={styles.dragger}
- disabled={loading}
- maxCount={1}
- onFiles={([file]) => onFileSelect(file)}
- >
- {loading ? (
- <Center className={styles.draggerContent} gap={16}>
- <Icon
- className={styles.icon}
- icon={CloudUpload}
- size={{ size: 44, strokeWidth: 1.5 }}
- />
- <p className={styles.uploadText}>{t('dataset.import.uploading')}</p>
- {uploadProgress && (
- <div className={styles.progressWrapper}>
- <Progress percent={uploadProgress.progress} size="small" />
- </div>
)}
- </Center>
- ) : (
- <Center className={styles.draggerContent} gap={12}>
- <Icon className={styles.icon} icon={ImportIcon} size={{ size: 44, strokeWidth: 1.5 }} />
- <p className={styles.uploadText}>{t('dataset.import.upload.text')}</p>
- <p className={styles.hintText}>{t('dataset.import.upload.hint')}</p>
- </Center>
+ </Flexbox>
+ )}
+
+ <Upload
+ dragger
+ accept={archiveOnly ? '.zip' : '.csv,.xlsx,.xls,.json,.jsonl,.zip'}
+ className={styles.dragger}
+ disabled={loading}
+ maxCount={1}
+ onFiles={([file]) => file && onFileSelect(file)}
+ >
+ {loading ? (
+ <Center className={styles.draggerContent} gap={16}>
+ <Icon
+ className={styles.icon}
+ icon={CloudUpload}
+ size={{ size: 44, strokeWidth: 1.5 }}
+ />
+ <p className={styles.uploadText}>{t('dataset.import.uploading')}</p>
+ {uploadProgress && (
+ <div className={styles.progressWrapper}>
+ <Progress percent={uploadProgress.progress} size="small" />
+ </div>
+ )}
+ </Center>
+ ) : (
+ <Center className={styles.draggerContent} gap={12}>
+ <Icon
+ className={styles.icon}
+ icon={ImportIcon}
+ size={{ size: 44, strokeWidth: 1.5 }}
+ />
+ <p className={styles.uploadText}>{t('dataset.import.upload.text')}</p>
+ <p className={styles.hintText}>
+ {t(archiveOnly ? 'dataset.import.package.hint' : 'dataset.import.upload.hint')}
+ </p>
+ </Center>
+ )}
+ </Upload>
+ {archiveOnly && (
+ <p className={styles.hintText}>{t('dataset.import.package.instructions')}</p>
)}
- </Upload>
- </Flexbox>
- );
-});
+ </Flexbox>
+ );
+ },
+);
export default UploadStep;
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/index.tsx b/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
index 3d00cd12f01..b5a2b0946cd 100644
--- a/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
+++ b/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
@@ -7,12 +7,14 @@ import DatasetImportContent from './Content';
import DatasetImportFooter from './Footer';
interface CreateOptions {
- datasetId: string;
+ archiveOnly?: boolean;
+ datasetId?: string;
onSuccess?: (datasetId: string) => void;
presetId?: string;
}
export const createDatasetImportModal = ({
+ archiveOnly,
datasetId,
onSuccess,
presetId,
@@ -21,6 +23,7 @@ export const createDatasetImportModal = ({
let step: 0 | 1 = 0;
let canImport = false;
let importing = false;
+ let busy = false;
let runImport: () => Promise<void> = async () => {};
let prev: () => void = () => {};
@@ -48,6 +51,7 @@ export const createDatasetImportModal = ({
ref.instance = createModal({
content: (
<DatasetImportContent
+ archiveOnly={archiveOnly}
close={() => ref.instance?.close()}
datasetId={datasetId}
presetId={presetId}
@@ -59,10 +63,15 @@ export const createDatasetImportModal = ({
runImport = api.runImport;
}}
onStateChange={(next) => {
- if (next.step === step && next.canImport === canImport) return;
+ if (next.step === step && next.canImport === canImport && next.busy === busy) return;
step = next.step;
canImport = next.canImport;
- ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ busy = next.busy;
+ ref.instance?.update({
+ closable: !busy,
+ keyboard: !busy,
+ footer: renderFooter(),
+ } as Partial<ImperativeModalProps>);
}}
/>
),
diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
index a4bf9fa77cf..96a3daaa265 100644
--- a/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
+++ b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
@@ -37,7 +37,7 @@ const ExperimentModalContent = memo<ExperimentModalContentProps>(
const createExperiment = useEvalStore((s) => s.createExperiment);
const updateExperiment = useEvalStore((s) => s.updateExperiment);
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
- const benchmarkList = useEvalStore(benchmarkSelectors.benchmarkList);
+ const benchmarkList = useEvalStore(benchmarkSelectors.agentBenchmarkList);
useFetchBenchmarks();
diff --git a/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
index 906e73fe3c4..1206b048134 100644
--- a/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
@@ -60,7 +60,8 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
},
datasetId,
evalConfig:
- values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ (values.evalMode === 'llm-rubric' || values.evalMode === 'rule-checklist') &&
+ values.evalConfig?.judgePrompt
? values.evalConfig
: undefined,
evalMode: values.evalMode || undefined,
@@ -125,10 +126,11 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
{ label: t('evalMode.equals'), value: 'equals' },
{ label: t('evalMode.contains'), value: 'contains' },
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.rule-checklist'), value: 'rule-checklist' },
]}
/>
</Form.Field>
- {evalModeValue === 'llm-rubric' && (
+ {(evalModeValue === 'llm-rubric' || evalModeValue === 'rule-checklist') && (
<Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea
autoSize={{ maxRows: 8, minRows: 3 }}
diff --git a/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
index b439115ff47..9e15d9b8255 100644
--- a/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
@@ -60,7 +60,8 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
input: values.input,
},
evalConfig:
- values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ (values.evalMode === 'llm-rubric' || values.evalMode === 'rule-checklist') &&
+ values.evalConfig?.judgePrompt
? values.evalConfig
: null,
evalMode: values.evalMode || null,
@@ -133,10 +134,11 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
{ label: t('evalMode.equals'), value: 'equals' },
{ label: t('evalMode.contains'), value: 'contains' },
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.rule-checklist'), value: 'rule-checklist' },
]}
/>
</Form.Field>
- {evalModeValue === 'llm-rubric' && (
+ {(evalModeValue === 'llm-rubric' || evalModeValue === 'rule-checklist') && (
<Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea
autoSize={{ maxRows: 8, minRows: 3 }}
diff --git a/src/routes/(main)/eval/index.tsx b/src/routes/(main)/eval/index.tsx
index a778f07b4c2..c8a17c5667b 100644
--- a/src/routes/(main)/eval/index.tsx
+++ b/src/routes/(main)/eval/index.tsx
@@ -7,7 +7,12 @@ import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useEvalStore } from '@/store/eval';
+import {
+ benchmarkSelectors,
+ datasetSelectors,
+ experimentSelectors,
+ useEvalStore,
+} from '@/store/eval';
import BenchmarkCard from './features/BenchmarkCard';
import { createCreateBenchmarkModal } from './features/CreateBenchmarkModal';
@@ -88,13 +93,16 @@ const SkeletonGrid = memo(() => (
const EvalOverview = memo(() => {
const { t } = useTranslation('eval');
- const benchmarkList = useEvalStore((s) => s.benchmarkList);
+ // The Evaluation Lab shows its own benchmarks, datasets and experiments;
+ // Lobe Bench's live in the same tables and have their own pages.
+ const benchmarkList = useEvalStore(benchmarkSelectors.agentBenchmarkList);
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
const useFetchAllDatasets = useEvalStore((s) => s.useFetchAllDatasets);
const { data, isLoading, error, mutate } = useFetchBenchmarks();
- const { data: allDatasets } = useFetchAllDatasets();
+ useFetchAllDatasets();
+ const allDatasets = useEvalStore(datasetSelectors.agentDatasets);
- const experimentList = useEvalStore((s) => s.experimentList);
+ const experimentList = useEvalStore(experimentSelectors.agentExperimentList);
const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);
const {
data: experimentData,
diff --git a/src/routes/(main)/eval/lobe-bench/_layout/index.tsx b/src/routes/(main)/eval/lobe-bench/_layout/index.tsx
new file mode 100644
index 00000000000..40a75574c94
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/_layout/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Layout';
diff --git a/src/routes/(main)/eval/lobe-bench/benchmarks/[benchmarkId]/index.tsx b/src/routes/(main)/eval/lobe-bench/benchmarks/[benchmarkId]/index.tsx
new file mode 100644
index 00000000000..bdeeba232ff
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/benchmarks/[benchmarkId]/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Benchmark';
diff --git a/src/routes/(main)/eval/lobe-bench/contenders/index.tsx b/src/routes/(main)/eval/lobe-bench/contenders/index.tsx
new file mode 100644
index 00000000000..22b64c2958f
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/contenders/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Contenders';
diff --git a/src/routes/(main)/eval/lobe-bench/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/lobe-bench/datasets/[datasetId]/index.tsx
new file mode 100644
index 00000000000..d8457afb7ca
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/datasets/[datasetId]/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Dataset';
diff --git a/src/routes/(main)/eval/lobe-bench/environments/index.tsx b/src/routes/(main)/eval/lobe-bench/environments/index.tsx
new file mode 100644
index 00000000000..d25d96f2146
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/environments/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Environments';
diff --git a/src/routes/(main)/eval/lobe-bench/experiments/[experimentId]/index.tsx b/src/routes/(main)/eval/lobe-bench/experiments/[experimentId]/index.tsx
new file mode 100644
index 00000000000..c8c172aebd3
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/experiments/[experimentId]/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Experiment';
diff --git a/src/routes/(main)/eval/lobe-bench/experiments/new/index.tsx b/src/routes/(main)/eval/lobe-bench/experiments/new/index.tsx
new file mode 100644
index 00000000000..d28a850dbc5
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/experiments/new/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/NewExperiment';
diff --git a/src/routes/(main)/eval/lobe-bench/index.tsx b/src/routes/(main)/eval/lobe-bench/index.tsx
new file mode 100644
index 00000000000..a8467a5db5d
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Overview';
diff --git a/src/routes/(main)/eval/lobe-bench/library/index.tsx b/src/routes/(main)/eval/lobe-bench/library/index.tsx
new file mode 100644
index 00000000000..2d896341d05
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/library/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Library';
diff --git a/src/routes/(main)/eval/lobe-bench/settings/index.tsx b/src/routes/(main)/eval/lobe-bench/settings/index.tsx
new file mode 100644
index 00000000000..530ce6108f1
--- /dev/null
+++ b/src/routes/(main)/eval/lobe-bench/settings/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/LobeBench/Settings';
diff --git a/src/services/agentEval.ts b/src/services/agentEval.ts
index e64bda2ceac..23e04223fdf 100644
--- a/src/services/agentEval.ts
+++ b/src/services/agentEval.ts
@@ -1,4 +1,12 @@
-import type { EvalRunInputConfig, RubricType } from '@lobechat/types';
+import type {
+ AgentEvalDatasetPackageBindings,
+ AgentEvalRunListItem,
+ EvalCaseEnvironment,
+ EvalConfig,
+ EvalRunInputConfig,
+ EvalTestCaseContent,
+ RubricType,
+} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -15,6 +23,8 @@ class AgentEvalService {
async createExperiment(params: {
benchmarkIds: string[];
description?: string;
+ /** Caller-supplied id: creating again with the same id returns the existing experiment. */
+ id?: string;
metadata?: Record<string, unknown>;
name: string;
}) {
@@ -31,8 +41,9 @@ class AgentEvalService {
return lambdaClient.agentEval.updateExperiment.mutate(params);
}
- async deleteExperiment(id: string) {
- return lambdaClient.agentEval.deleteExperiment.mutate({ id });
+ /** `withRuns` deletes the experiment's runs (results, topics, case Agents) with it. */
+ async deleteExperiment(id: string, options?: { withRuns?: boolean }) {
+ return lambdaClient.agentEval.deleteExperiment.mutate({ id, ...options });
}
// ============ Benchmark ============
@@ -50,7 +61,6 @@ class AgentEvalService {
metadata?: Record<string, unknown>;
name: string;
rubrics?: any[];
- tags?: string[];
}) {
return lambdaClient.agentEval.createBenchmark.mutate(params);
}
@@ -58,10 +68,8 @@ class AgentEvalService {
async updateBenchmark(params: {
description?: string;
id: string;
- identifier: string;
metadata?: Record<string, unknown>;
name: string;
- tags?: string[];
}) {
return lambdaClient.agentEval.updateBenchmark.mutate(params);
}
@@ -71,6 +79,80 @@ class AgentEvalService {
}
// ============ Dataset ============
+ // ============================================
+ // Environments
+ // ============================================
+ async listEvalConnectors(datasetId: string) {
+ return lambdaClient.agentEval.listEvalConnectors.query({ datasetId });
+ }
+
+ async getEvalConnector(datasetId: string, id: string) {
+ return lambdaClient.agentEval.getEvalConnector.query({ datasetId, id });
+ }
+
+ async saveEvalConnector(params: {
+ datasetId: string;
+ id?: string;
+ isEnabled?: boolean;
+ name: string;
+ mcpServerUrl: string;
+ credentials?:
+ | { type: 'bearer'; token: string }
+ | { type: 'header'; headers: Record<string, string> }
+ | null;
+ }) {
+ return params.id
+ ? lambdaClient.agentEval.updateEvalConnector.mutate({ ...params, id: params.id })
+ : lambdaClient.agentEval.createEvalConnector.mutate(params);
+ }
+
+ async testEvalConnector(datasetId: string, id: string) {
+ return lambdaClient.agentEval.testEvalConnector.mutate({ datasetId, id });
+ }
+
+ async getDatasetConnectorBindings(datasetId: string) {
+ return lambdaClient.agentEval.getDatasetConnectorBindings.query({ datasetId });
+ }
+
+ async updateDatasetConnectorBindings(
+ params: AgentEvalDatasetPackageBindings & { datasetId: string },
+ ) {
+ return lambdaClient.agentEval.updateDatasetConnectorBindings.mutate(params);
+ }
+
+ async listEnvironments() {
+ return lambdaClient.agentEval.listEnvironments.query();
+ }
+
+ async getEnvironment(id: string) {
+ return lambdaClient.agentEval.getEnvironment.query({ id });
+ }
+
+ async createEnvironment(params: {
+ config: EvalCaseEnvironment;
+ description?: string;
+ identifier?: string;
+ metadata?: Record<string, unknown>;
+ name: string;
+ }) {
+ return lambdaClient.agentEval.createEnvironment.mutate(params);
+ }
+
+ async updateEnvironment(params: {
+ config?: EvalCaseEnvironment;
+ description?: string | null;
+ id: string;
+ identifier?: string | null;
+ metadata?: Record<string, unknown> | null;
+ name?: string;
+ }) {
+ return lambdaClient.agentEval.updateEnvironment.mutate(params);
+ }
+
+ async deleteEnvironment(id: string) {
+ return lambdaClient.agentEval.deleteEnvironment.mutate({ id });
+ }
+
async listDatasets(benchmarkId: string) {
return lambdaClient.agentEval.listDatasets.query({ benchmarkId });
}
@@ -85,6 +167,14 @@ class AgentEvalService {
}
async createDataset(params: {
+ cases?: Array<{
+ content: EvalTestCaseContent;
+ environmentId?: string | null;
+ evalConfig?: EvalConfig;
+ evalMode?: RubricType;
+ metadata?: Record<string, unknown>;
+ sortOrder?: number;
+ }>;
benchmarkId: string;
description?: string;
evalConfig?: { judgePrompt?: string };
@@ -98,6 +188,8 @@ class AgentEvalService {
}
async updateDataset(params: {
+ /** Moves the dataset into this benchmark (one the account can see). */
+ benchmarkId?: string;
description?: string;
evalConfig?: { judgePrompt?: string } | null;
evalMode?: RubricType | null;
@@ -116,6 +208,18 @@ class AgentEvalService {
return lambdaClient.agentEval.parseDatasetFile.mutate(params);
}
+ async importDatasetPackage(
+ params: AgentEvalDatasetPackageBindings & {
+ benchmarkId?: string;
+ datasetId?: string;
+ filename?: string;
+ name?: string;
+ pathname: string;
+ },
+ ) {
+ return lambdaClient.agentEval.importDatasetPackage.mutate(params);
+ }
+
async importDataset(params: {
datasetId: string;
pathname: string;
@@ -139,26 +243,31 @@ class AgentEvalService {
return lambdaClient.agentEval.getTestCase.query({ id });
}
+ async draftTestCaseFromTopic(params: {
+ benchmarkId?: string;
+ draftRules?: boolean;
+ topicId: string;
+ }) {
+ return lambdaClient.agentEval.draftTestCaseFromTopic.mutate(params);
+ }
+
async listTestCases(params: { datasetId: string; limit?: number; offset?: number }) {
return lambdaClient.agentEval.listTestCases.query(params);
}
async createTestCase(params: {
+ environmentId?: string | null;
content: {
category?: string;
choices?: string[];
+ environment?: EvalCaseEnvironment;
expected?: string;
input: string;
/**
* Conversation replayed into the eval topic before `input` is sent. The
* router has always accepted it; this client had not exposed it.
*/
- messages?: Array<{
- content: string;
- id?: string;
- parentId?: string;
- role: 'assistant' | 'system' | 'user';
- }>;
+ messages?: EvalTestCaseContent['messages'];
};
datasetId: string;
evalConfig?: { criteria?: string; judgePrompt?: string };
@@ -168,12 +277,31 @@ class AgentEvalService {
return lambdaClient.agentEval.createTestCase.mutate(params);
}
+ /** Creates several cases at once, each with its own rules and judge (a dataset's copies). */
+ async batchCreateTestCases(params: {
+ cases: Array<{
+ content: { input: string } & Record<string, unknown>;
+ environmentId?: string | null;
+ evalConfig?: Record<string, unknown>;
+ evalMode?: RubricType;
+ metadata?: Record<string, unknown>;
+ sortOrder?: number;
+ }>;
+ datasetId: string;
+ }) {
+ return lambdaClient.agentEval.batchCreateTestCases.mutate(params as never);
+ }
+
async updateTestCase(params: {
+ environmentId?: string | null;
id: string;
content?: {
category?: string;
+ choices?: string[];
+ environment?: EvalCaseEnvironment;
expected?: string;
input?: string;
+ messages?: EvalTestCaseContent['messages'];
};
evalConfig?: { criteria?: string; judgePrompt?: string } | null;
evalMode?: RubricType | null;
@@ -188,10 +316,29 @@ class AgentEvalService {
}
// ============ Run ============
- async listRuns(params: { benchmarkId?: string; datasetId?: string; experimentId?: string }) {
+ async listRuns(params: {
+ benchmarkId?: string;
+ datasetId?: string;
+ experimentId?: string;
+ limit?: number;
+ offset?: number;
+ }) {
return lambdaClient.agentEval.listRuns.query(params);
}
+ /** Complete run list for summaries and actions that must cover every run. */
+ async listAllRuns(params: { benchmarkId?: string; datasetId?: string; experimentId?: string }) {
+ const runs = new Map<string, AgentEvalRunListItem>();
+ const limit = 100;
+ for (let offset = 0; ; offset += limit) {
+ const { data } = await this.listRuns({ ...params, limit, offset });
+ // Concurrent inserts can shift an offset boundary between requests.
+ for (const run of data) runs.set(run.id, run);
+ // listRuns.total currently counts this page, not all matching runs.
+ if (data.length < limit) return [...runs.values()];
+ }
+ }
+
async getRunDetails(id: string) {
return lambdaClient.agentEval.getRunDetails.query({ id });
}
@@ -204,6 +351,8 @@ class AgentEvalService {
config?: EvalRunInputConfig;
datasetId: string;
experimentId?: string;
+ /** Caller-supplied id: creating again with the same id and parameters returns the existing run. */
+ id?: string;
name?: string;
parentRunId?: string;
targetAgentId?: string;
@@ -211,6 +360,11 @@ class AgentEvalService {
return lambdaClient.agentEval.createRun.mutate(params);
}
+ /** Which of these providers this server can call for the current user (key present). */
+ async checkProviders(providers: string[]) {
+ return lambdaClient.agentEval.checkProviders.query({ providers });
+ }
+
async startRun(id: string, force?: boolean) {
return lambdaClient.agentEval.startRun.mutate({ force, id });
}
@@ -223,6 +377,15 @@ class AgentEvalService {
return lambdaClient.agentEval.retryRunErrors.mutate({ id });
}
+ /** Grade a finished run again from its recorded trajectories; nothing is re-run. */
+ async rejudgeRun(id: string) {
+ return lambdaClient.agentEval.rejudgeRun.mutate({ id });
+ }
+
+ async rerunRunUnverified(id: string) {
+ return lambdaClient.agentEval.rerunRunUnverified.mutate({ id });
+ }
+
async retryRunCase(runId: string, testCaseId: string) {
return lambdaClient.agentEval.retryRunCase.mutate({ runId, testCaseId });
}
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 43081efdc50..597600429b8 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -41,6 +41,7 @@ import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShel
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
import { agentPageChildren } from '@/spa/router/agentPageRoutes';
+import { evalRoute } from '@/spa/router/evalRoutes';
import { memoryChildren } from '@/spa/router/memoryRoutes';
import { onboardingRoute } from '@/spa/router/onboardingRoute';
import { pageListLoader } from '@/spa/router/pageListLoader';
@@ -468,109 +469,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
...BusinessDesktopRoutesWithMainLayout,
// Eval routes
- {
- children: [
- // Home (overview)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval'),
- 'Desktop > Eval > Overview',
- { preloadId: 'eval' },
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/experiments/[experimentId]'),
- 'Desktop > Eval > Experiment Detail',
- ),
- path: 'experiments/:experimentId',
- },
- // A dataset and a case are addressable on their own — a dataset need
- // not belong to a benchmark, so a benchmark id cannot be part of
- // their canonical path. They live in the home group to keep the eval
- // workspace sidebar; the bench group's sidebar is benchmark-scoped
- // and has nothing to show for a dataset that belongs to none.
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/datasets/[datasetId]'),
- 'Desktop > Eval > Dataset Detail',
- ),
- path: 'datasets/:datasetId',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/cases/[caseId]'),
- 'Desktop > Eval > Test Case Detail',
- ),
- path: 'cases/:caseId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/(home)/_layout'),
- 'Desktop > Eval > Home > Layout',
- { preloadId: 'eval' },
- ),
- },
- // Bench routes (with dedicated sidebar)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
- 'Desktop > Eval > Benchmark Detail',
- ),
- handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('detail') }) },
- index: true,
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
- 'Desktop > Eval > Run Detail',
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
- 'Desktop > Eval > Case Detail',
- ),
- path: 'cases/:caseId',
- },
- ],
- path: 'runs/:runId',
- },
- {
- // Legacy shape, kept so existing links still resolve; it redirects
- // to the benchmark-free `/eval/datasets/:datasetId`.
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
- 'Desktop > Eval > Dataset Detail (legacy redirect)',
- ),
- path: 'datasets/:datasetId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
- 'Desktop > Eval > Bench > Layout',
- ),
- path: 'bench/:benchmarkId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/_layout'),
- 'Desktop > Eval > Layout',
- { preloadId: 'eval' },
- ),
- errorElement: <ErrorBoundary />,
- handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },
- path: 'eval',
- },
+ evalRoute,
...collaborationRoutes,
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 9eecfb03f39..ce79a63b2a0 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -88,6 +88,7 @@ async function readRouterSources() {
'memoryRoutes.tsx',
'onboardingRoute.tsx',
'collaborationRoutes.tsx',
+ 'evalRoutes.tsx',
].map((filename) => readFile(path.join(process.cwd(), 'src/spa/router', filename), 'utf8')),
);
}
diff --git a/src/spa/router/evalRoutes.tsx b/src/spa/router/evalRoutes.tsx
new file mode 100644
index 00000000000..8d178221184
--- /dev/null
+++ b/src/spa/router/evalRoutes.tsx
@@ -0,0 +1,184 @@
+import type { RouteObject } from 'react-router';
+
+import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
+import { routeMeta } from '@/spa/router/routeMeta';
+import { dynamicElement, ErrorBoundary } from '@/utils/router';
+
+/**
+ * `/eval/*`: the eval workspace (Agent Eval home, benchmark-scoped pages) and
+ * Lobe Bench. Mounted in `desktopRouter.shared.tsx` among the main-area routes.
+ */
+export const evalRoute: RouteObject = {
+ children: [
+ // Home (overview)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval'),
+ 'Desktop > Eval > Overview',
+ { preloadId: 'eval' },
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/experiments/[experimentId]'),
+ 'Desktop > Eval > Experiment Detail',
+ ),
+ path: 'experiments/:experimentId',
+ },
+ // A dataset and a case are addressable on their own — a dataset need
+ // not belong to a benchmark, so a benchmark id cannot be part of
+ // their canonical path. They live in the home group to keep the eval
+ // workspace sidebar; the bench group's sidebar is benchmark-scoped
+ // and has nothing to show for a dataset that belongs to none.
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/datasets/[datasetId]'),
+ 'Desktop > Eval > Dataset Detail',
+ ),
+ path: 'datasets/:datasetId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/cases/[caseId]'),
+ 'Desktop > Eval > Test Case Detail',
+ ),
+ path: 'cases/:caseId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/(home)/_layout'),
+ 'Desktop > Eval > Home > Layout',
+ { preloadId: 'eval' },
+ ),
+ },
+ // Lobe Bench: LobeHub's standard cases, compared across models
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench'),
+ 'Desktop > Eval > Lobe Bench > Overview',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/experiments/new'),
+ 'Desktop > Eval > Lobe Bench > New Experiment',
+ ),
+ path: 'experiments/new',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/experiments/[experimentId]'),
+ 'Desktop > Eval > Lobe Bench > Experiment',
+ ),
+ path: 'experiments/:experimentId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/library'),
+ 'Desktop > Eval > Lobe Bench > Library',
+ ),
+ path: 'library',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/environments'),
+ 'Desktop > Eval > Lobe Bench > Environments',
+ ),
+ path: 'environments',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/contenders'),
+ 'Desktop > Eval > Lobe Bench > Contenders',
+ ),
+ path: 'contenders',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/settings'),
+ 'Desktop > Eval > Lobe Bench > Settings',
+ ),
+ path: 'settings',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/benchmarks/[benchmarkId]'),
+ 'Desktop > Eval > Lobe Bench > Benchmark',
+ ),
+ path: 'benchmarks/:benchmarkId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/datasets/[datasetId]'),
+ 'Desktop > Eval > Lobe Bench > Case set',
+ ),
+ path: 'datasets/:datasetId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/lobe-bench/_layout'),
+ 'Desktop > Eval > Lobe Bench > Layout',
+ ),
+ path: 'lobe-bench',
+ },
+ // Bench routes (with dedicated sidebar)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
+ 'Desktop > Eval > Benchmark Detail',
+ ),
+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('detail') }) },
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
+ 'Desktop > Eval > Run Detail',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
+ 'Desktop > Eval > Case Detail',
+ ),
+ path: 'cases/:caseId',
+ },
+ ],
+ path: 'runs/:runId',
+ },
+ {
+ // Legacy shape, kept so existing links still resolve; it redirects
+ // to the benchmark-free `/eval/datasets/:datasetId`.
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
+ 'Desktop > Eval > Dataset Detail (legacy redirect)',
+ ),
+ path: 'datasets/:datasetId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
+ 'Desktop > Eval > Bench > Layout',
+ ),
+ path: 'bench/:benchmarkId',
+ },
+ ],
+ element: dynamicElement(() => import('@/routes/(main)/eval/_layout'), 'Desktop > Eval > Layout', {
+ preloadId: 'eval',
+ }),
+ errorElement: <ErrorBoundary />,
+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },
+ path: 'eval',
+};
diff --git a/src/store/eval/initialState.ts b/src/store/eval/initialState.ts
index c11cab4a93a..97021177d1d 100644
--- a/src/store/eval/initialState.ts
+++ b/src/store/eval/initialState.ts
@@ -1,24 +1,36 @@
import { benchmarkInitialState, type BenchmarkSliceState } from './slices/benchmark/initialState';
+import { connectorInitialState, type ConnectorSliceState } from './slices/connector/initialState';
+import {
+ conversationInitialState,
+ type ConversationSliceState,
+} from './slices/conversation/initialState';
import { datasetInitialState, type DatasetSliceState } from './slices/dataset/initialState';
import {
experimentInitialState,
type ExperimentSliceState,
} from './slices/experiment/initialState';
+import { lobeBenchInitialState, type LobeBenchSliceState } from './slices/lobeBench/initialState';
import { runInitialState, type RunSliceState } from './slices/run/initialState';
import { testCaseInitialState, type TestCaseSliceState } from './slices/testCase/initialState';
export interface EvalStoreState
extends
BenchmarkSliceState,
+ ConnectorSliceState,
+ ConversationSliceState,
DatasetSliceState,
ExperimentSliceState,
+ LobeBenchSliceState,
RunSliceState,
TestCaseSliceState {}
export const initialState: EvalStoreState = {
...benchmarkInitialState,
+ ...connectorInitialState,
+ ...conversationInitialState,
...datasetInitialState,
...experimentInitialState,
+ ...lobeBenchInitialState,
...runInitialState,
...testCaseInitialState,
};
diff --git a/src/store/eval/kinds.ts b/src/store/eval/kinds.ts
new file mode 100644
index 00000000000..658894d01f2
--- /dev/null
+++ b/src/store/eval/kinds.ts
@@ -0,0 +1,13 @@
+/**
+ * Lobe Bench and the Evaluation Lab share the eval tables (benchmarks,
+ * datasets, experiments, runs). A benchmark or experiment created for Lobe
+ * Bench carries `metadata.kind = 'lobe-bench'`; each surface lists only its
+ * own side, so the shared storage never shows through.
+ */
+export const LOBE_BENCH_KIND = 'lobe-bench';
+
+export const isLobeBenchKind = (item?: { metadata?: unknown } | null): boolean =>
+ !!item &&
+ typeof item.metadata === 'object' &&
+ item.metadata !== null &&
+ (item.metadata as { kind?: unknown }).kind === LOBE_BENCH_KIND;
diff --git a/src/store/eval/replicaQuery.ts b/src/store/eval/replicaQuery.ts
new file mode 100644
index 00000000000..5f5785cc671
--- /dev/null
+++ b/src/store/eval/replicaQuery.ts
@@ -0,0 +1,26 @@
+import type { ReplicaSyncResult } from '@/libs/replica';
+
+/**
+ * The `{ data, error, isLoading, mutate }` shape the eval pages read, backed by
+ * a replica entry instead of a hand-keyed SWR cache. `data` is the store entry.
+ */
+export interface ReplicaQueryResult<T> extends ReplicaSyncResult {
+ /** The entry once it has settled (hydrated or fetched), else `undefined`. */
+ data: T | undefined;
+ /** First load in flight with nothing settled yet; never true for a disabled hook. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+}
+
+/** A failed first load is neither loading nor settled, so the page reaches its error state. */
+export const toReplicaQueryResult = <T>(
+ sync: ReplicaSyncResult,
+ data: T | undefined,
+ active: boolean,
+): ReplicaQueryResult<T> => ({
+ ...sync,
+ data,
+ isLoading: active && data === undefined && !sync.error,
+ mutate: sync.revalidate,
+});
diff --git a/src/store/eval/slices/benchmark/action.test.ts b/src/store/eval/slices/benchmark/action.test.ts
index ad478bff551..bebf0722211 100644
--- a/src/store/eval/slices/benchmark/action.test.ts
+++ b/src/store/eval/slices/benchmark/action.test.ts
@@ -160,6 +160,25 @@ describe('BenchmarkAction replica wiring', () => {
expect(agentEvalService.deleteBenchmark).toHaveBeenCalledWith('b1');
expect(useEvalStore.getState().benchmarkDetailMap.b1).toBeUndefined();
});
+
+ it('throws when the server refuses (built-in benchmark) and keeps the detail cache', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.deleteBenchmark).mockResolvedValue({
+ error: 'system benchmarks cannot be deleted',
+ success: false,
+ } as any);
+ useEvalStore.setState({
+ benchmarkDetailMap: { b1: { id: 'b1', name: 'Lobe Bench' } as any },
+ });
+
+ await expect(useEvalStore.getState().deleteBenchmark('b1')).rejects.toThrow(
+ 'system benchmarks cannot be deleted',
+ );
+ expect(useEvalStore.getState().benchmarkDetailMap.b1).toEqual({
+ id: 'b1',
+ name: 'Lobe Bench',
+ });
+ });
});
describe('updateBenchmark', () => {
diff --git a/src/store/eval/slices/benchmark/action.ts b/src/store/eval/slices/benchmark/action.ts
index 8e2608a7d90..f1ee59b7354 100644
--- a/src/store/eval/slices/benchmark/action.ts
+++ b/src/store/eval/slices/benchmark/action.ts
@@ -104,7 +104,6 @@ export class BenchmarkActionImpl {
metadata?: Record<string, unknown>;
name: string;
rubrics?: any[];
- tags?: string[];
}): Promise<any> => {
const result = await agentEvalService.createBenchmark({
description: params.description,
@@ -112,14 +111,16 @@ export class BenchmarkActionImpl {
metadata: params.metadata,
name: params.name,
rubrics: params.rubrics ?? [],
- tags: params.tags,
});
await this.refreshBenchmarks();
return result;
};
deleteBenchmark = async (id: string): Promise<void> => {
- await agentEvalService.deleteBenchmark(id);
+ const result = await agentEvalService.deleteBenchmark(id);
+ // Built-in benchmarks are refused with `{ success: false }`; surface it instead of
+ // dropping the row and letting the refresh bring it back.
+ if (result?.success === false) throw new Error(result.error);
// Drop the row from the list and the detail cache at once, then converge.
this.#entity.remove(id);
await this.refreshBenchmarks();
@@ -128,10 +129,8 @@ export class BenchmarkActionImpl {
updateBenchmark = async (params: {
description?: string;
id: string;
- identifier: string;
metadata?: Record<string, unknown>;
name: string;
- tags?: string[];
}): Promise<void> => {
// Optimistic on every copy; the refetch below reconciles server-owned fields.
await this.#entity.optimistic(
@@ -141,10 +140,8 @@ export class BenchmarkActionImpl {
agentEvalService.updateBenchmark({
description: params.description,
id: params.id,
- identifier: params.identifier,
metadata: params.metadata,
name: params.name,
- tags: params.tags,
}),
);
await Promise.all([this.refreshBenchmarks(), this.refreshBenchmarkDetail(params.id)]);
diff --git a/src/store/eval/slices/benchmark/selectors.ts b/src/store/eval/slices/benchmark/selectors.ts
index 35ec08825ac..ae9a4029e93 100644
--- a/src/store/eval/slices/benchmark/selectors.ts
+++ b/src/store/eval/slices/benchmark/selectors.ts
@@ -1,10 +1,14 @@
+import { isLobeBenchKind } from '@/store/eval/kinds';
import type { EvalStore } from '@/store/eval/store';
const benchmarkList = (s: EvalStore) => s.benchmarkList;
+/** The Evaluation Lab's benchmarks: everything that is not Lobe Bench's. */
+const agentBenchmarkList = (s: EvalStore) => s.benchmarkList.filter((b) => !isLobeBenchKind(b));
const isBenchmarkListInit = (s: EvalStore) => s.benchmarkListInit;
const getBenchmarkById = (id: string) => (s: EvalStore) => s.benchmarkList.find((b) => b.id === id);
export const benchmarkSelectors = {
+ agentBenchmarkList,
benchmarkList,
getBenchmarkById,
isBenchmarkListInit,
diff --git a/src/store/eval/slices/connector/action.test.ts b/src/store/eval/slices/connector/action.test.ts
new file mode 100644
index 00000000000..24c4922dfba
--- /dev/null
+++ b/src/store/eval/slices/connector/action.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment happy-dom
+
+import { renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: {
+ getDatasetConnectorBindings: vi.fn(),
+ getEvalConnector: vi.fn(),
+ listEvalConnectors: vi.fn(),
+ },
+}));
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },
+ children,
+ );
+
+const connection = (id: string) => ({ id, name: id }) as never;
+
+beforeEach(() => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('eval-user:personal');
+ vi.spyOn(cacheScope, 'use').mockReturnValue('eval-user:personal');
+ useEvalStore.setState({
+ datasetConnectorBindingsMap: {},
+ evalConnectorDetailMap: {},
+ evalConnectorListMap: {},
+ });
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('Dataset connection replicas', () => {
+ it('does not fetch a global inventory before a Dataset exists', async () => {
+ const { result } = renderHook(() => useEvalStore.getState().useFetchEvalConnectors(), {
+ wrapper,
+ });
+ await Promise.resolve();
+ expect(agentEvalService.listEvalConnectors).not.toHaveBeenCalled();
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it('keeps each Dataset’s connections in its own entry', async () => {
+ vi.mocked(agentEvalService.listEvalConnectors).mockImplementation(
+ async (datasetId) => [connection(`${datasetId}-connection`)] as never,
+ );
+ const { result } = renderHook(
+ () => ({
+ a: useEvalStore.getState().useFetchEvalConnectors('a'),
+ b: useEvalStore.getState().useFetchEvalConnectors('b'),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.b.data).toBeDefined());
+ await waitFor(() => expect(result.current.a.data).toBeDefined());
+ expect(agentEvalService.listEvalConnectors).toHaveBeenCalledWith('a');
+ expect(agentEvalService.listEvalConnectors).toHaveBeenCalledWith('b');
+ expect(useEvalStore.getState().evalConnectorListMap).toEqual({
+ a: [connection('a-connection')],
+ b: [connection('b-connection')],
+ });
+ });
+
+ it('reads one connection within its Dataset', async () => {
+ vi.mocked(agentEvalService.getEvalConnector).mockResolvedValue(connection('c1'));
+ const { result } = renderHook(() => useEvalStore.getState().useFetchEvalConnector('a', 'c1'), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.data).toEqual(connection('c1')));
+ expect(agentEvalService.getEvalConnector).toHaveBeenCalledWith('a', 'c1');
+ });
+
+ it('exposes a failed first load instead of a loading state', async () => {
+ const failure = new Error('Service unavailable');
+ vi.mocked(agentEvalService.getDatasetConnectorBindings).mockRejectedValue(failure);
+ const { result } = renderHook(
+ () => useEvalStore.getState().useFetchDatasetConnectorBindings('a'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBe(failure));
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.data).toBeUndefined();
+ });
+});
diff --git a/src/store/eval/slices/connector/action.ts b/src/store/eval/slices/connector/action.ts
new file mode 100644
index 00000000000..eb505ca510d
--- /dev/null
+++ b/src/store/eval/slices/connector/action.ts
@@ -0,0 +1,88 @@
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { agentEvalService } from '@/services/agentEval';
+import { type ReplicaQueryResult, toReplicaQueryResult } from '@/store/eval/replicaQuery';
+import { type EvalStore, useEvalStore } from '@/store/eval/store';
+import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ connectorDetailKey,
+ type DatasetConnectorBindings,
+ datasetConnectorBindingsResource,
+ type EvalConnectorDetail,
+ evalConnectorDetailResource,
+ type EvalConnectorList,
+ evalConnectorListResource,
+} from './projection';
+
+const n = setNamespace('evalConnector');
+
+type Setter = StoreSetter<EvalStore>;
+
+export const createConnectorSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
+ new ConnectorActionImpl(set, get, _api);
+
+/** A dataset's connections and bindings, read by the connection pickers and editor. */
+export class ConnectorActionImpl {
+ readonly #bindings;
+ readonly #detail;
+ readonly #list;
+
+ constructor(set: Setter, get: () => EvalStore, _api?: unknown) {
+ void _api;
+ this.#list = createReplicaSlice(evalConnectorListResource, {
+ actionPrefix: n('list'),
+ fetcher: (datasetId) => agentEvalService.listEvalConnectors(datasetId),
+ get,
+ set,
+ stateKey: 'evalConnectorListReplica',
+ view: recordLens<EvalStore, EvalConnectorList>('evalConnectorListMap'),
+ });
+ this.#detail = createReplicaSlice(evalConnectorDetailResource, {
+ actionPrefix: n('detail'),
+ fetcher: ({ datasetId, id }) => agentEvalService.getEvalConnector(datasetId, id),
+ get,
+ set,
+ stateKey: 'evalConnectorDetailReplica',
+ view: recordLens<EvalStore, EvalConnectorDetail>('evalConnectorDetailMap'),
+ });
+ this.#bindings = createReplicaSlice(datasetConnectorBindingsResource, {
+ actionPrefix: n('bindings'),
+ fetcher: (datasetId) => agentEvalService.getDatasetConnectorBindings(datasetId),
+ get,
+ set,
+ stateKey: 'datasetConnectorBindingsReplica',
+ view: recordLens<EvalStore, DatasetConnectorBindings>('datasetConnectorBindingsMap'),
+ });
+ }
+
+ useFetchEvalConnectors = (datasetId?: string): ReplicaQueryResult<EvalConnectorList> => {
+ const data = useEvalStore((s) => (datasetId ? s.evalConnectorListMap[datasetId] : undefined));
+ const sync = this.#list.useSync(datasetId ?? null);
+ return toReplicaQueryResult(sync, data, !!datasetId);
+ };
+
+ useFetchEvalConnector = (
+ datasetId: string,
+ id?: string,
+ ): ReplicaQueryResult<EvalConnectorDetail> => {
+ const params = id ? { datasetId, id } : null;
+ const data = useEvalStore((s) =>
+ params ? s.evalConnectorDetailMap[connectorDetailKey(params)] : undefined,
+ );
+ const sync = this.#detail.useSync(params);
+ return toReplicaQueryResult(sync, data, !!params);
+ };
+
+ useFetchDatasetConnectorBindings = (
+ datasetId?: string,
+ ): ReplicaQueryResult<DatasetConnectorBindings> => {
+ const data = useEvalStore((s) =>
+ datasetId ? s.datasetConnectorBindingsMap[datasetId] : undefined,
+ );
+ const sync = this.#bindings.useSync(datasetId ?? null);
+ return toReplicaQueryResult(sync, data, !!datasetId);
+ };
+}
+
+export type ConnectorAction = Pick<ConnectorActionImpl, keyof ConnectorActionImpl>;
diff --git a/src/store/eval/slices/connector/initialState.ts b/src/store/eval/slices/connector/initialState.ts
new file mode 100644
index 00000000000..bcf86749b0e
--- /dev/null
+++ b/src/store/eval/slices/connector/initialState.ts
@@ -0,0 +1,25 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type {
+ DatasetConnectorBindings,
+ EvalConnectorDetail,
+ EvalConnectorList,
+} from './projection';
+
+export interface ConnectorSliceState {
+ datasetConnectorBindingsMap: Record<string, DatasetConnectorBindings>;
+ datasetConnectorBindingsReplica: ReplicaState<DatasetConnectorBindings>;
+ evalConnectorDetailMap: Record<string, EvalConnectorDetail>;
+ evalConnectorDetailReplica: ReplicaState<EvalConnectorDetail>;
+ evalConnectorListMap: Record<string, EvalConnectorList>;
+ evalConnectorListReplica: ReplicaState<EvalConnectorList>;
+}
+
+export const connectorInitialState: ConnectorSliceState = {
+ datasetConnectorBindingsMap: {},
+ datasetConnectorBindingsReplica: createReplicaState(),
+ evalConnectorDetailMap: {},
+ evalConnectorDetailReplica: createReplicaState(),
+ evalConnectorListMap: {},
+ evalConnectorListReplica: createReplicaState(),
+};
diff --git a/src/store/eval/slices/connector/projection.ts b/src/store/eval/slices/connector/projection.ts
new file mode 100644
index 00000000000..42ce592f5cd
--- /dev/null
+++ b/src/store/eval/slices/connector/projection.ts
@@ -0,0 +1,43 @@
+import { defineReplica } from '@/libs/replica';
+import type { agentEvalService } from '@/services/agentEval';
+
+export type EvalConnectorList = Awaited<ReturnType<typeof agentEvalService.listEvalConnectors>>;
+export type EvalConnectorDetail = Awaited<ReturnType<typeof agentEvalService.getEvalConnector>>;
+export type DatasetConnectorBindings = Awaited<
+ ReturnType<typeof agentEvalService.getDatasetConnectorBindings>
+>;
+
+/**
+ * Connections and bindings are memory only: they describe credentialed MCP
+ * endpoints, and even redacted they stay out of the persisted cache.
+ */
+
+/** The connections of a dataset (`evalConnectorListMap[datasetId]`). */
+export const evalConnectorListResource = defineReplica<string, EvalConnectorList>({
+ key: (datasetId) => datasetId,
+ name: 'evalConnectorList',
+ storage: 'memory',
+ version: 1,
+});
+
+/** One connection being edited (`evalConnectorDetailMap[connectorDetailKey(...)]`). */
+export const connectorDetailKey = ({ datasetId, id }: { datasetId: string; id: string }) =>
+ `${datasetId}:${id}`;
+
+export const evalConnectorDetailResource = defineReplica<
+ { datasetId: string; id: string },
+ EvalConnectorDetail
+>({
+ key: connectorDetailKey,
+ name: 'evalConnectorDetail',
+ storage: 'memory',
+ version: 1,
+});
+
+/** What a dataset's cases need and which connection serves each (`datasetConnectorBindingsMap`). */
+export const datasetConnectorBindingsResource = defineReplica<string, DatasetConnectorBindings>({
+ key: (datasetId) => datasetId,
+ name: 'evalDatasetConnectorBindings',
+ storage: 'memory',
+ version: 1,
+});
diff --git a/src/store/eval/slices/conversation/action.test.ts b/src/store/eval/slices/conversation/action.test.ts
new file mode 100644
index 00000000000..f0b859a3c43
--- /dev/null
+++ b/src/store/eval/slices/conversation/action.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment happy-dom
+
+import type { ChatTopic, RecentTopic } from '@lobechat/types';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { topicService } from '@/services/topic';
+import { useEvalStore } from '@/store/eval';
+
+const scope = vi.hoisted(() => ({ workspaceId: undefined as string | undefined }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => scope.workspaceId,
+ useActiveWorkspaceId: () => scope.workspaceId,
+}));
+vi.mock('@/services/topic', () => ({
+ topicService: { getRecentTopics: vi.fn(), searchTopics: vi.fn() },
+}));
+
+const recent = (id: string, type: RecentTopic['type'] = 'agent'): RecentTopic => ({
+ agent: null,
+ group: null,
+ id,
+ title: id,
+ type,
+ updatedAt: new Date(0),
+});
+const searchResult = (id: string): ChatTopic =>
+ ({ id, title: id, updatedAt: new Date(0) }) as unknown as ChatTopic;
+
+const createWrapper = () => {
+ const cache = new Map();
+ return ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { provider: () => cache, shouldRetryOnError: false } },
+ children,
+ );
+};
+
+const actions = {
+ useFetchConversationTopics: (query: string) =>
+ useEvalStore.getState().useFetchConversationTopics(query),
+};
+
+beforeEach(() => {
+ scope.workspaceId = undefined;
+ vi.resetAllMocks();
+ // Picker results live in the store, partitioned like the cache by workspace.
+ const current = () => `eval-user:${scope.workspaceId ?? 'personal'}`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(current);
+ vi.spyOn(cacheScope, 'use').mockImplementation(current);
+ useEvalStore.setState({ conversationTopicMap: {} });
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('eval conversation picker requests', () => {
+ it('exposes an initial failure, then recovers with a retry rather than reporting empty', async () => {
+ const failure = new Error('Service unavailable');
+ vi.mocked(topicService.getRecentTopics)
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce([recent('topic-a'), recent('group-a', 'group')]);
+ const { result } = renderHook(() => ({ ...actions.useFetchConversationTopics('') }), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.error).toBe(failure));
+ expect(result.current.data).toBeUndefined();
+ await act(async () => {
+ await result.current.mutate();
+ });
+ expect(result.current.error).toBeUndefined();
+ expect(result.current.data?.map((topic) => topic.id)).toEqual(['topic-a']);
+ });
+
+ it('keeps a settled empty result when background revalidation fails', async () => {
+ vi.mocked(topicService.getRecentTopics).mockResolvedValueOnce([]);
+ const { result } = renderHook(() => ({ ...actions.useFetchConversationTopics('') }), {
+ wrapper: createWrapper(),
+ });
+ await waitFor(() => expect(result.current.data).toEqual([]));
+
+ vi.mocked(topicService.getRecentTopics).mockRejectedValueOnce(new Error('Refresh failed'));
+ await act(async () => {
+ await result.current.mutate().catch(() => undefined);
+ });
+ expect(result.current.data).toEqual([]);
+ expect(result.current.error).toBeInstanceOf(Error);
+ });
+
+ it('does not replace a newer search with a late response to an older query', async () => {
+ let resolveOlder!: (value: ChatTopic[]) => void;
+ vi.mocked(topicService.searchTopics).mockImplementation((query) =>
+ query === 'older'
+ ? new Promise((resolve) => {
+ resolveOlder = resolve;
+ })
+ : Promise.resolve([searchResult('newer-result')]),
+ );
+ const { result, rerender } = renderHook(
+ ({ query }) => ({ ...actions.useFetchConversationTopics(query) }),
+ { initialProps: { query: 'older' }, wrapper: createWrapper() },
+ );
+
+ rerender({ query: 'newer' });
+ await waitFor(() => expect(result.current.data?.[0].id).toBe('newer-result'));
+ await act(async () => resolveOlder([searchResult('older-result')]));
+ expect(result.current.data?.[0].id).toBe('newer-result');
+ });
+
+ it('does not show another workspace’s recent topics while the new scope loads', async () => {
+ vi.mocked(topicService.getRecentTopics).mockResolvedValueOnce([recent('personal-topic')]);
+ const { result, rerender } = renderHook(() => ({ ...actions.useFetchConversationTopics('') }), {
+ wrapper: createWrapper(),
+ });
+ await waitFor(() => expect(result.current.data?.[0].id).toBe('personal-topic'));
+
+ let resolveWorkspace!: (value: RecentTopic[]) => void;
+ vi.mocked(topicService.getRecentTopics).mockImplementationOnce(
+ () => new Promise((resolve) => (resolveWorkspace = resolve)),
+ );
+ scope.workspaceId = 'workspace-b';
+ rerender();
+ expect(result.current.data).toBeUndefined();
+ await act(async () => resolveWorkspace([recent('workspace-topic')]));
+ await waitFor(() => expect(result.current.data?.[0].id).toBe('workspace-topic'));
+ });
+});
diff --git a/src/store/eval/slices/conversation/action.ts b/src/store/eval/slices/conversation/action.ts
new file mode 100644
index 00000000000..1688e3cdbac
--- /dev/null
+++ b/src/store/eval/slices/conversation/action.ts
@@ -0,0 +1,76 @@
+import type { ChatTopic, RecentTopic } from '@lobechat/types';
+
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { topicService } from '@/services/topic';
+import { type ReplicaQueryResult, toReplicaQueryResult } from '@/store/eval/replicaQuery';
+import { type EvalStore, useEvalStore } from '@/store/eval/store';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ CONVERSATION_PICKER_LIMIT,
+ conversationPickerKey,
+ conversationPickerResource,
+ type EvalConversationTopic,
+} from './projection';
+
+export type { EvalConversationTopic } from './projection';
+
+const n = setNamespace('evalConversation');
+
+type Setter = StoreSetter<EvalStore>;
+
+const searchTopic = (topic: ChatTopic): EvalConversationTopic => ({
+ id: topic.id,
+ title: topic.title,
+ updatedAt: topic.updatedAt,
+});
+
+const recentTopic = (topic: RecentTopic): EvalConversationTopic => ({
+ agentTitle: topic.agent?.title,
+ id: topic.id,
+ title: topic.title,
+ updatedAt: topic.updatedAt,
+});
+
+/** Search matches for a query, or the recent agent conversations for an empty one. */
+export const fetchConversationTopics = async ({
+ query,
+}: {
+ query: string;
+}): Promise<EvalConversationTopic[]> => {
+ if (query) return (await topicService.searchTopics(query)).map(searchTopic);
+
+ return (await topicService.getRecentTopics(CONVERSATION_PICKER_LIMIT))
+ .filter((topic) => topic.type === 'agent')
+ .map(recentTopic);
+};
+
+export const createConversationSlice = (set: Setter, get: () => EvalStore, api?: unknown) =>
+ new ConversationActionImpl(set, get, api);
+
+export class ConversationActionImpl {
+ readonly #topics;
+
+ constructor(set: Setter, get: () => EvalStore, _api?: unknown) {
+ void _api;
+ this.#topics = createReplicaSlice(conversationPickerResource, {
+ actionPrefix: n('topics'),
+ fetcher: fetchConversationTopics,
+ get,
+ set,
+ stateKey: 'conversationTopicReplica',
+ view: recordLens<EvalStore, EvalConversationTopic[]>('conversationTopicMap'),
+ });
+ }
+
+ /** Topics the case picker offers for a submitted query. */
+ useFetchConversationTopics = (query: string): ReplicaQueryResult<EvalConversationTopic[]> => {
+ const params = { query };
+ const data = useEvalStore((s) => s.conversationTopicMap[conversationPickerKey(params)]);
+ const sync = this.#topics.useSync(params);
+ return toReplicaQueryResult(sync, data, true);
+ };
+}
+
+export type ConversationAction = Pick<ConversationActionImpl, keyof ConversationActionImpl>;
diff --git a/src/store/eval/slices/conversation/initialState.ts b/src/store/eval/slices/conversation/initialState.ts
new file mode 100644
index 00000000000..4443c548958
--- /dev/null
+++ b/src/store/eval/slices/conversation/initialState.ts
@@ -0,0 +1,14 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { EvalConversationTopic } from './projection';
+
+export interface ConversationSliceState {
+ /** Picker results, keyed by `conversationPickerKey`. */
+ conversationTopicMap: Record<string, EvalConversationTopic[]>;
+ conversationTopicReplica: ReplicaState<EvalConversationTopic[]>;
+}
+
+export const conversationInitialState: ConversationSliceState = {
+ conversationTopicMap: {},
+ conversationTopicReplica: createReplicaState(),
+};
diff --git a/src/store/eval/slices/conversation/projection.ts b/src/store/eval/slices/conversation/projection.ts
new file mode 100644
index 00000000000..d2ad1f9ee9e
--- /dev/null
+++ b/src/store/eval/slices/conversation/projection.ts
@@ -0,0 +1,28 @@
+import { defineReplica } from '@/libs/replica';
+
+export interface EvalConversationTopic {
+ agentTitle?: string | null;
+ id: string;
+ title: string | null;
+ updatedAt?: Date | number | string | null;
+}
+
+/** How many topics the picker lists: the most recent ones, or the best search matches. */
+export const CONVERSATION_PICKER_LIMIT = 30;
+
+/** Entry key of a picker query; the empty query lists the recent topics. */
+export const conversationPickerKey = ({ query }: { query: string }) => query || '@recent';
+
+/**
+ * Topics the case picker offers (`conversationTopicMap[conversationPickerKey]`).
+ * Memory only: it is a transient lookup keyed by free text, and the topics
+ * themselves are persisted by the chat's own replicas.
+ */
+export const conversationPickerResource = defineReplica<{ query: string }, EvalConversationTopic[]>(
+ {
+ key: conversationPickerKey,
+ name: 'evalConversationPicker',
+ storage: 'memory',
+ version: 1,
+ },
+);
diff --git a/src/store/eval/slices/dataset/selectors.ts b/src/store/eval/slices/dataset/selectors.ts
index ced3e661e6c..9c4111d5726 100644
--- a/src/store/eval/slices/dataset/selectors.ts
+++ b/src/store/eval/slices/dataset/selectors.ts
@@ -1,5 +1,6 @@
import type { AgentEvalDatasetListItem } from '@lobechat/types';
+import { isLobeBenchKind } from '@/store/eval/kinds';
import type { EvalStore } from '@/store/eval/store';
import { ALL_DATASETS_KEY } from './projection';
@@ -17,6 +18,18 @@ const datasetList = (benchmarkId?: string) => (s: EvalStore) =>
/** Every dataset of the active scope (the scope-wide list entry). */
const allDatasets = (s: EvalStore) => s.datasetListMap[ALL_DATASETS_KEY] ?? EMPTY_DATASETS;
+/**
+ * The Evaluation Lab's datasets: the scope-wide list without the datasets of
+ * Lobe Bench benchmarks. Needs the benchmark list loaded to know which those are.
+ */
+const agentDatasets = (s: EvalStore) => {
+ const hidden = new Set(s.benchmarkList.filter((b) => isLobeBenchKind(b)).map((b) => b.id));
+ const datasets = allDatasets(s);
+ return hidden.size === 0
+ ? datasets
+ : datasets.filter((dataset) => !dataset.benchmarkId || !hidden.has(dataset.benchmarkId));
+};
+
/**
* The benchmark list has no local copy yet (`undefined` is the loading
* signal) — the sidebar / datasets tab keep their skeleton until the first paint.
@@ -27,6 +40,7 @@ const isLoadingDatasetList = (benchmarkId?: string) => (s: EvalStore) =>
const getDatasetById = (id: string) => (s: EvalStore) => s.datasetDetailMap[id];
export const datasetSelectors = {
+ agentDatasets,
allDatasets,
datasetList,
getDatasetById,
diff --git a/src/store/eval/slices/experiment/action.test.ts b/src/store/eval/slices/experiment/action.test.ts
index f817b6ceb6c..5f0186ed8b0 100644
--- a/src/store/eval/slices/experiment/action.test.ts
+++ b/src/store/eval/slices/experiment/action.test.ts
@@ -194,6 +194,23 @@ describe('ExperimentAction replica wiring', () => {
await expect(useEvalStore.getState().deleteExperiment('e1')).rejects.toThrow('boom');
expect(useEvalStore.getState().experimentList).toEqual([{ id: 'e1', name: 'Sweep' }]);
});
+
+ it('treats a refused delete ({ success: false }) like a rejection and keeps the row', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.deleteExperiment).mockResolvedValue({
+ error: 'Experiment not found',
+ success: false,
+ } as any);
+ useEvalStore.setState({
+ experimentList: [{ id: 'e1', name: 'Sweep' } as any],
+ experimentListInit: true,
+ });
+
+ await expect(useEvalStore.getState().deleteExperiment('e1')).rejects.toThrow(
+ 'Experiment not found',
+ );
+ expect(useEvalStore.getState().experimentList).toEqual([{ id: 'e1', name: 'Sweep' }]);
+ });
});
describe('updateExperiment', () => {
diff --git a/src/store/eval/slices/experiment/action.ts b/src/store/eval/slices/experiment/action.ts
index 64210defc4c..80736b8c4e8 100644
--- a/src/store/eval/slices/experiment/action.ts
+++ b/src/store/eval/slices/experiment/action.ts
@@ -116,7 +116,13 @@ export class ExperimentActionImpl {
deleteExperiment = async (id: string): Promise<void> => {
// Optimistic: drop the row from the list (and the detail cache) right away,
// rolling back if the server rejects it, then converge on the server list.
- await this.#entity.optimistic(id, 'remove', () => agentEvalService.deleteExperiment(id));
+ await this.#entity.optimistic(id, 'remove', async () => {
+ const result = await agentEvalService.deleteExperiment(id);
+ // The procedure reports a refusal as `{ success: false }` instead of throwing; without
+ // this the row would vanish, then come back on the next refresh.
+ if (result?.success === false) throw new Error(result.error);
+ return result;
+ });
await this.refreshExperiments();
};
diff --git a/src/store/eval/slices/experiment/selectors.ts b/src/store/eval/slices/experiment/selectors.ts
index 886428a2d01..594f432bcc3 100644
--- a/src/store/eval/slices/experiment/selectors.ts
+++ b/src/store/eval/slices/experiment/selectors.ts
@@ -1,10 +1,15 @@
+import { isLobeBenchKind } from '@/store/eval/kinds';
import type { EvalStore } from '@/store/eval/store';
const experimentList = (s: EvalStore) => s.experimentList;
+/** The Evaluation Lab's experiments: everything that is not Lobe Bench's. */
+const agentExperimentList = (s: EvalStore) =>
+ s.experimentList.filter((experiment) => !isLobeBenchKind(experiment));
const isExperimentListInit = (s: EvalStore) => s.experimentListInit;
const getExperimentDetailById = (id: string) => (s: EvalStore) => s.experimentDetailMap[id];
export const experimentSelectors = {
+ agentExperimentList,
experimentList,
getExperimentDetailById,
isExperimentListInit,
diff --git a/src/store/eval/slices/lobeBench/action.test.ts b/src/store/eval/slices/lobeBench/action.test.ts
new file mode 100644
index 00000000000..a711cdca3eb
--- /dev/null
+++ b/src/store/eval/slices/lobeBench/action.test.ts
@@ -0,0 +1,135 @@
+// @vitest-environment happy-dom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+import { idSetKey } from './projection';
+
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: {
+ getRunResults: vi.fn(),
+ listAllDatasets: vi.fn(),
+ listAllRuns: vi.fn(),
+ listDatasets: vi.fn(),
+ listEnvironments: vi.fn(),
+ listTestCases: vi.fn(),
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const dataset = (id: string, extra: Record<string, unknown> = {}) =>
+ ({ createdAt: '2026-01-01T00:00:00.000Z', id, name: id, ...extra }) as never;
+
+beforeEach(() => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('eval-user:personal');
+ vi.spyOn(cacheScope, 'use').mockReturnValue('eval-user:personal');
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ useEvalStore.setState({
+ datasetCaseListMap: {},
+ lobeBenchDatasetListMap: {},
+ lobeBenchRunListMap: {},
+ runResultsByRunMap: {},
+ });
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+describe('Lobe Bench replicas', () => {
+ it('keys a benchmark set by its members, not their order', () => {
+ expect(idSetKey(['b', 'a'])).toBe(idSetKey(['a', 'b']));
+ expect(idSetKey([])).not.toBe(idSetKey(['']));
+ });
+
+ it('lists benchmark datasets plus standalone Lobe Bench ones into the store', async () => {
+ vi.mocked(agentEvalService.listDatasets).mockResolvedValue([
+ dataset('in-bench', { benchmarkId: 'bench' }),
+ ] as never);
+ vi.mocked(agentEvalService.listAllDatasets).mockResolvedValue([
+ dataset('in-bench', { benchmarkId: 'bench' }),
+ dataset('imported', { metadata: { kind: 'lobe-bench' } }),
+ dataset('lab-only'),
+ ] as never);
+
+ const { result } = renderHook(
+ () => useEvalStore.getState().useFetchLobeBenchDatasets(['bench']),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.data!.map((item: { id: string }) => item.id)).toEqual([
+ 'in-bench',
+ 'imported',
+ ]);
+ expect(useEvalStore.getState().lobeBenchDatasetListMap[idSetKey(['bench'])]).toBe(
+ result.current.data,
+ );
+ });
+
+ it('does not request runs or results without ids, and is not loading', async () => {
+ const { result } = renderHook(
+ () => ({
+ results: useEvalStore.getState().useFetchRunResultsByRun([]),
+ runs: useEvalStore.getState().useFetchLobeBenchRuns([]),
+ }),
+ { wrapper },
+ );
+ await Promise.resolve();
+ expect(agentEvalService.listAllRuns).not.toHaveBeenCalled();
+ expect(agentEvalService.getRunResults).not.toHaveBeenCalled();
+ expect(result.current.runs.isLoading).toBe(false);
+ expect(result.current.results.isLoading).toBe(false);
+ });
+
+ it('collects each run’s results under its id', async () => {
+ vi.mocked(agentEvalService.getRunResults).mockImplementation(
+ async (runId) => ({ results: [{ testCaseId: `${runId}-case` }] }) as never,
+ );
+ const { result } = renderHook(
+ () => useEvalStore.getState().useFetchRunResultsByRun(['r1', 'r2']),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(result.current.data).toEqual({
+ r1: [{ testCaseId: 'r1-case' }],
+ r2: [{ testCaseId: 'r2-case' }],
+ });
+ });
+
+ it('re-reads a dataset’s cases after an import, without a mounted view', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue({
+ data: [{ id: 'case-1' }],
+ total: 1,
+ } as never);
+
+ await act(() => useEvalStore.getState().refreshDatasetCases('set-1'));
+
+ expect(agentEvalService.listTestCases).toHaveBeenCalledWith({
+ datasetId: 'set-1',
+ limit: 100,
+ offset: 0,
+ });
+ expect(useEvalStore.getState().datasetCaseListMap['set-1']).toEqual([{ id: 'case-1' }]);
+ });
+});
diff --git a/src/store/eval/slices/lobeBench/action.ts b/src/store/eval/slices/lobeBench/action.ts
new file mode 100644
index 00000000000..b97a7106e8d
--- /dev/null
+++ b/src/store/eval/slices/lobeBench/action.ts
@@ -0,0 +1,198 @@
+import type { AgentEvalDatasetListItem, AgentEvalRunListItem } from '@lobechat/types';
+
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { agentEvalService } from '@/services/agentEval';
+import { type ReplicaQueryResult, toReplicaQueryResult } from '@/store/eval/replicaQuery';
+import { type EvalStore, useEvalStore } from '@/store/eval/store';
+import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ fetchCasesByDataset,
+ fetchDatasetCases,
+ fetchLobeBenchDatasets,
+ fetchLobeBenchRuns,
+ fetchRunResultsByRun,
+} from './fetchers';
+import {
+ type CasesByDataset,
+ casesByDatasetResource,
+ datasetCaseListResource,
+ ENVIRONMENT_LIST_KEY,
+ ENVIRONMENT_LIST_PARAMS,
+ environmentListResource,
+ type EvalEnvironmentRow,
+ experimentRunListResource,
+ idSetKey,
+ type LobeBenchCase,
+ lobeBenchDatasetListResource,
+ lobeBenchRunListResource,
+ type RunResultsByRun,
+ runResultsByRunResource,
+} from './projection';
+
+const n = setNamespace('evalLobeBench');
+
+type Setter = StoreSetter<EvalStore>;
+
+/** Only the scheduling knob callers pass today; `useSync` accepts the full schedule. */
+type PollConfig = { refreshInterval?: number };
+
+export const createLobeBenchSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
+ new LobeBenchActionImpl(set, get, _api);
+
+/**
+ * The Lobe Bench pages' server data. Each list is a replica owning one map of
+ * the store; the hooks keep the `{ data, error, isLoading, mutate }` shape.
+ */
+export class LobeBenchActionImpl {
+ readonly #casesByDataset;
+ readonly #datasetCases;
+ readonly #datasets;
+ readonly #environments;
+ readonly #experimentRuns;
+ readonly #runResults;
+ readonly #runs;
+
+ constructor(set: Setter, get: () => EvalStore, _api?: unknown) {
+ void _api;
+
+ this.#datasets = createReplicaSlice(lobeBenchDatasetListResource, {
+ actionPrefix: n('datasets'),
+ fetcher: ({ benchmarkIds }) => fetchLobeBenchDatasets(benchmarkIds),
+ get,
+ set,
+ stateKey: 'lobeBenchDatasetListReplica',
+ view: recordLens<EvalStore, AgentEvalDatasetListItem[]>('lobeBenchDatasetListMap'),
+ });
+ this.#runs = createReplicaSlice(lobeBenchRunListResource, {
+ actionPrefix: n('runs'),
+ fetcher: ({ benchmarkIds }) => fetchLobeBenchRuns(benchmarkIds),
+ get,
+ set,
+ stateKey: 'lobeBenchRunListReplica',
+ view: recordLens<EvalStore, AgentEvalRunListItem[]>('lobeBenchRunListMap'),
+ });
+ this.#experimentRuns = createReplicaSlice(experimentRunListResource, {
+ actionPrefix: n('experimentRuns'),
+ fetcher: (experimentId) => agentEvalService.listAllRuns({ experimentId }),
+ get,
+ set,
+ stateKey: 'experimentRunListReplica',
+ view: recordLens<EvalStore, AgentEvalRunListItem[]>('experimentRunListMap'),
+ });
+ this.#runResults = createReplicaSlice(runResultsByRunResource, {
+ actionPrefix: n('runResults'),
+ fetcher: fetchRunResultsByRun,
+ get,
+ set,
+ stateKey: 'runResultsByRunReplica',
+ view: recordLens<EvalStore, RunResultsByRun>('runResultsByRunMap'),
+ });
+ this.#datasetCases = createReplicaSlice(datasetCaseListResource, {
+ actionPrefix: n('datasetCases'),
+ fetcher: fetchDatasetCases,
+ get,
+ set,
+ stateKey: 'datasetCaseListReplica',
+ view: recordLens<EvalStore, LobeBenchCase[]>('datasetCaseListMap'),
+ });
+ this.#casesByDataset = createReplicaSlice(casesByDatasetResource, {
+ actionPrefix: n('casesByDataset'),
+ fetcher: fetchCasesByDataset,
+ get,
+ set,
+ stateKey: 'casesByDatasetReplica',
+ view: recordLens<EvalStore, CasesByDataset>('casesByDatasetMap'),
+ });
+ this.#environments = createReplicaSlice(environmentListResource, {
+ actionPrefix: n('environments'),
+ fetcher: async () => (await agentEvalService.listEnvironments()) as EvalEnvironmentRow[],
+ get,
+ set,
+ stateKey: 'environmentListReplica',
+ view: recordLens<EvalStore, EvalEnvironmentRow[]>('environmentListMap'),
+ });
+ }
+
+ /** Revalidates every mounted Lobe Bench dataset list (sidebar, pickers, pages). */
+ refreshLobeBenchDatasets = async (): Promise<void> => {
+ await this.#datasets.revalidate();
+ };
+
+ /** Re-reads the cases of a dataset, mounted or not. */
+ refreshDatasetCases = async (datasetId: string): Promise<void> => {
+ await this.#datasetCases.fetch(datasetId, { fresh: true });
+ };
+
+ /** Case sets of the given Lobe Bench benchmarks plus the standalone imported ones. */
+ useFetchLobeBenchDatasets = (
+ benchmarkIds: string[],
+ ): ReplicaQueryResult<AgentEvalDatasetListItem[]> => {
+ const data = useEvalStore((s) => s.lobeBenchDatasetListMap[idSetKey(benchmarkIds)]);
+ const sync = this.#datasets.useSync({ benchmarkIds });
+ return toReplicaQueryResult(sync, data, true);
+ };
+
+ /** Every run under the given Lobe Bench benchmarks, newest first. */
+ useFetchLobeBenchRuns = (
+ benchmarkIds: string[],
+ config?: PollConfig,
+ ): ReplicaQueryResult<AgentEvalRunListItem[]> => {
+ const active = benchmarkIds.length > 0;
+ const data = useEvalStore((s) =>
+ active ? s.lobeBenchRunListMap[idSetKey(benchmarkIds)] : undefined,
+ );
+ const sync = this.#runs.useSync(active ? { benchmarkIds } : null, config);
+ return toReplicaQueryResult(sync, data, active);
+ };
+
+ /** The runs of one experiment (one per contender). */
+ useFetchExperimentRuns = (
+ experimentId: string | undefined,
+ config?: PollConfig,
+ ): ReplicaQueryResult<AgentEvalRunListItem[]> => {
+ const data = useEvalStore((s) =>
+ experimentId ? s.experimentRunListMap[experimentId] : undefined,
+ );
+ const sync = this.#experimentRuns.useSync(experimentId ?? null, config);
+ return toReplicaQueryResult(sync, data, !!experimentId);
+ };
+
+ /** Per-case results of several runs, keyed by run id. */
+ useFetchRunResultsByRun = (
+ runIds: string[],
+ config?: PollConfig,
+ ): ReplicaQueryResult<RunResultsByRun> => {
+ const active = runIds.length > 0;
+ const data = useEvalStore((s) => (active ? s.runResultsByRunMap[idSetKey(runIds)] : undefined));
+ const sync = this.#runResults.useSync(active ? runIds : null, config);
+ return toReplicaQueryResult(sync, data, active);
+ };
+
+ /** All cases of a dataset, in benchmark order. */
+ useFetchDatasetCases = (datasetId: string | undefined): ReplicaQueryResult<LobeBenchCase[]> => {
+ const data = useEvalStore((s) => (datasetId ? s.datasetCaseListMap[datasetId] : undefined));
+ const sync = this.#datasetCases.useSync(datasetId ?? null);
+ return toReplicaQueryResult(sync, data, !!datasetId);
+ };
+
+ /** All cases of several datasets, keyed by dataset id. */
+ useFetchCasesByDataset = (datasetIds: string[]): ReplicaQueryResult<CasesByDataset> => {
+ const active = datasetIds.length > 0;
+ const data = useEvalStore((s) =>
+ active ? s.casesByDatasetMap[idSetKey(datasetIds)] : undefined,
+ );
+ const sync = this.#casesByDataset.useSync(active ? datasetIds : null);
+ return toReplicaQueryResult(sync, data, active);
+ };
+
+ /** Reusable case environments of the active scope. */
+ useFetchEvalEnvironments = (): ReplicaQueryResult<EvalEnvironmentRow[]> => {
+ const data = useEvalStore((s) => s.environmentListMap[ENVIRONMENT_LIST_KEY]);
+ const sync = this.#environments.useSync(ENVIRONMENT_LIST_PARAMS);
+ return toReplicaQueryResult(sync, data, true);
+ };
+}
+
+export type LobeBenchAction = Pick<LobeBenchActionImpl, keyof LobeBenchActionImpl>;
diff --git a/src/store/eval/slices/lobeBench/fetchers.ts b/src/store/eval/slices/lobeBench/fetchers.ts
new file mode 100644
index 00000000000..efb523c7dfc
--- /dev/null
+++ b/src/store/eval/slices/lobeBench/fetchers.ts
@@ -0,0 +1,79 @@
+import type { AgentEvalDatasetListItem, AgentEvalRunTopicResult } from '@lobechat/types';
+
+import { agentEvalService } from '@/services/agentEval';
+import { isLobeBenchKind } from '@/store/eval/kinds';
+
+import type { CasesByDataset, LobeBenchCase, RunResultsByRun } from './projection';
+
+const byNewest = (a: { createdAt?: unknown }, b: { createdAt?: unknown }) =>
+ new Date((b.createdAt as string | number | Date | undefined) ?? 0).getTime() -
+ new Date((a.createdAt as string | number | Date | undefined) ?? 0).getTime();
+
+const listOf = <T>(response: unknown): T[] => {
+ if (Array.isArray(response)) return response as T[];
+ const data = (response as { data?: unknown } | null)?.data;
+ return Array.isArray(data) ? (data as T[]) : [];
+};
+
+/** Datasets of the given benchmarks, plus the imported ones that belong to none. */
+export const fetchLobeBenchDatasets = async (benchmarkIds: string[]) => {
+ const [lists, all] = await Promise.all([
+ Promise.all(benchmarkIds.map((id) => agentEvalService.listDatasets(id))),
+ agentEvalService.listAllDatasets(),
+ ]);
+ // An imported dataset belongs to no benchmark until one is made of it.
+ const standalone = listOf<AgentEvalDatasetListItem>(all).filter(
+ (dataset) => !dataset.benchmarkId && isLobeBenchKind(dataset),
+ );
+ return [...lists.flatMap((list) => listOf<AgentEvalDatasetListItem>(list)), ...standalone].sort(
+ byNewest,
+ );
+};
+
+/** Every run under the given benchmarks, newest first. */
+export const fetchLobeBenchRuns = async (benchmarkIds: string[]) => {
+ const lists = await Promise.all(
+ benchmarkIds.map((benchmarkId) => agentEvalService.listAllRuns({ benchmarkId })),
+ );
+ return lists.flat().sort(byNewest);
+};
+
+/** Per-case results of several runs, keyed by run id. */
+export const fetchRunResultsByRun = async (runIds: string[]): Promise<RunResultsByRun> => {
+ const entries = await Promise.all(
+ runIds.map(async (runId) => {
+ const response = (await agentEvalService.getRunResults(runId)) as {
+ data?: { results?: AgentEvalRunTopicResult[] };
+ results?: AgentEvalRunTopicResult[];
+ };
+ return [runId, response?.results ?? response?.data?.results ?? []] as const;
+ }),
+ );
+ return Object.fromEntries(entries);
+};
+
+const CASE_PAGE = 100;
+
+/** All cases of a dataset, in benchmark order. */
+export const fetchDatasetCases = async (datasetId: string) => {
+ const cases: LobeBenchCase[] = [];
+ for (let offset = 0; ; offset += CASE_PAGE) {
+ const response = (await agentEvalService.listTestCases({
+ datasetId,
+ limit: CASE_PAGE,
+ offset,
+ })) as { data?: LobeBenchCase[]; total?: number };
+ const page = response?.data ?? [];
+ cases.push(...page);
+ if (page.length < CASE_PAGE || cases.length >= (response?.total ?? cases.length)) break;
+ }
+ return cases;
+};
+
+/** All cases of several datasets, keyed by dataset id. */
+export const fetchCasesByDataset = async (datasetIds: string[]): Promise<CasesByDataset> => {
+ const result: CasesByDataset = {};
+ // One dataset at a time: a library view may hold several large case sets.
+ for (const datasetId of datasetIds) result[datasetId] = await fetchDatasetCases(datasetId);
+ return result;
+};
diff --git a/src/store/eval/slices/lobeBench/initialState.ts b/src/store/eval/slices/lobeBench/initialState.ts
new file mode 100644
index 00000000000..0f2e39cbc82
--- /dev/null
+++ b/src/store/eval/slices/lobeBench/initialState.ts
@@ -0,0 +1,52 @@
+import type { AgentEvalDatasetListItem, AgentEvalRunListItem } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type {
+ CasesByDataset,
+ EvalEnvironmentRow,
+ LobeBenchCase,
+ RunResultsByRun,
+} from './projection';
+
+/** Replica views of the Lobe Bench pages; a missing entry is the loading signal. */
+export interface LobeBenchSliceState {
+ /** Cases of several datasets, keyed by `idSetKey(datasetIds)`. */
+ casesByDatasetMap: Record<string, CasesByDataset>;
+ casesByDatasetReplica: ReplicaState<CasesByDataset>;
+ /** All cases of a dataset, keyed by dataset id. */
+ datasetCaseListMap: Record<string, LobeBenchCase[]>;
+ datasetCaseListReplica: ReplicaState<LobeBenchCase[]>;
+ /** Case environments of the active scope, under `ENVIRONMENT_LIST_KEY`. */
+ environmentListMap: Record<string, EvalEnvironmentRow[]>;
+ environmentListReplica: ReplicaState<EvalEnvironmentRow[]>;
+ /** Runs of one experiment, keyed by experiment id. */
+ experimentRunListMap: Record<string, AgentEvalRunListItem[]>;
+ experimentRunListReplica: ReplicaState<AgentEvalRunListItem[]>;
+ /** Lobe Bench datasets, keyed by `idSetKey(benchmarkIds)`. */
+ lobeBenchDatasetListMap: Record<string, AgentEvalDatasetListItem[]>;
+ lobeBenchDatasetListReplica: ReplicaState<AgentEvalDatasetListItem[]>;
+ /** Runs under the Lobe Bench benchmarks, keyed by `idSetKey(benchmarkIds)`. */
+ lobeBenchRunListMap: Record<string, AgentEvalRunListItem[]>;
+ lobeBenchRunListReplica: ReplicaState<AgentEvalRunListItem[]>;
+ /** Per-case results of several runs, keyed by `idSetKey(runIds)`. */
+ runResultsByRunMap: Record<string, RunResultsByRun>;
+ runResultsByRunReplica: ReplicaState<RunResultsByRun>;
+}
+
+export const lobeBenchInitialState: LobeBenchSliceState = {
+ casesByDatasetMap: {},
+ casesByDatasetReplica: createReplicaState(),
+ datasetCaseListMap: {},
+ datasetCaseListReplica: createReplicaState(),
+ environmentListMap: {},
+ environmentListReplica: createReplicaState(),
+ experimentRunListMap: {},
+ experimentRunListReplica: createReplicaState(),
+ lobeBenchDatasetListMap: {},
+ lobeBenchDatasetListReplica: createReplicaState(),
+ lobeBenchRunListMap: {},
+ lobeBenchRunListReplica: createReplicaState(),
+ runResultsByRunMap: {},
+ runResultsByRunReplica: createReplicaState(),
+};
diff --git a/src/store/eval/slices/lobeBench/projection.ts b/src/store/eval/slices/lobeBench/projection.ts
new file mode 100644
index 00000000000..6e9f496a22c
--- /dev/null
+++ b/src/store/eval/slices/lobeBench/projection.ts
@@ -0,0 +1,134 @@
+import type {
+ AgentEvalDatasetListItem,
+ AgentEvalRunListItem,
+ AgentEvalRunTopicResult,
+ EvalCaseEnvironment,
+} from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+/** One case of a Lobe Bench dataset, as the case list returns it. */
+export interface LobeBenchCase {
+ content?: Record<string, any> | null;
+ /** The shared environment the case runs in, when it has one. */
+ environment?: { id: string; name: string } | null;
+ environmentId?: string | null;
+ /** The case's own environment fields, laid over the shared environment (present with one). */
+ environmentOverrides?: Record<string, any>;
+ evalConfig?: Record<string, any> | null;
+ evalMode?: string | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ sortOrder?: number | null;
+}
+
+/** A reusable case environment, as `listEnvironments` returns it. */
+export interface EvalEnvironmentRow {
+ config: EvalCaseEnvironment;
+ description?: string | null;
+ id: string;
+ identifier?: string | null;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ testCaseCount?: number;
+ /** Null for a built-in environment (one of the product's own case sets). */
+ userId?: string | null;
+}
+
+/** Per-case results of several runs, keyed by run id. */
+export type RunResultsByRun = Record<string, AgentEvalRunTopicResult[]>;
+/** Every case of several datasets, keyed by dataset id. */
+export type CasesByDataset = Record<string, LobeBenchCase[]>;
+
+/** Order-free entry key of a set of ids; the empty set has a key of its own. */
+export const idSetKey = (ids: readonly string[]): string =>
+ ids.length === 0 ? '-' : [...ids].sort().join(',');
+
+/**
+ * Lists keyed by a set of ids grow one persisted row per combination the user
+ * ever opened; keep the recent ones, since a combination changes only when a
+ * benchmark or run is added.
+ */
+const ID_SET_ROWS = 20;
+
+/**
+ * Case sets of the Lobe Bench benchmarks plus the standalone imported ones,
+ * newest first (`lobeBenchDatasetListMap[idSetKey(benchmarkIds)]`).
+ */
+export const lobeBenchDatasetListResource = defineReplica<
+ { benchmarkIds: string[] },
+ AgentEvalDatasetListItem[]
+>({
+ key: ({ benchmarkIds }) => idSetKey(benchmarkIds),
+ name: 'lobeBenchDatasetList',
+ persist: { maxEntries: ID_SET_ROWS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Every run under the Lobe Bench benchmarks, newest first (`lobeBenchRunListMap`). */
+export const lobeBenchRunListResource = defineReplica<
+ { benchmarkIds: string[] },
+ AgentEvalRunListItem[]
+>({
+ key: ({ benchmarkIds }) => idSetKey(benchmarkIds),
+ name: 'lobeBenchRunList',
+ persist: { maxEntries: ID_SET_ROWS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The runs of one experiment, one per contender (`experimentRunListMap[experimentId]`). */
+export const experimentRunListResource = defineReplica<string, AgentEvalRunListItem[]>({
+ key: (experimentId) => experimentId,
+ name: 'lobeBenchExperimentRunList',
+ persist: { maxEntries: ID_SET_ROWS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Per-case results of an experiment's runs (`runResultsByRunMap[idSetKey(runIds)]`).
+ * Memory only: the set changes as runs are retried, and each run's results are
+ * already persisted by `evalRunResults`.
+ */
+export const runResultsByRunResource = defineReplica<string[], RunResultsByRun>({
+ key: idSetKey,
+ name: 'lobeBenchRunResultsByRun',
+ storage: 'memory',
+ version: 1,
+});
+
+/** All cases of one dataset, in benchmark order (`datasetCaseListMap[datasetId]`). */
+export const datasetCaseListResource = defineReplica<string, LobeBenchCase[]>({
+ key: (datasetId) => datasetId,
+ name: 'lobeBenchDatasetCaseList',
+ persist: { maxEntries: ID_SET_ROWS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * All cases of several datasets (`casesByDatasetMap[idSetKey(datasetIds)]`).
+ * Memory only: the library view derives memberships from it once per visit.
+ */
+export const casesByDatasetResource = defineReplica<string[], CasesByDataset>({
+ key: idSetKey,
+ name: 'lobeBenchCasesByDataset',
+ storage: 'memory',
+ version: 1,
+});
+
+/** Entry key of the scope-wide environment list. */
+export const ENVIRONMENT_LIST_KEY = 'all';
+
+/** The scope-wide list takes no params; a literal keeps `useSync` enabled (`null` disables it). */
+export const ENVIRONMENT_LIST_PARAMS = {} as Record<string, never>;
+
+/** Reusable case environments of the active scope (`environmentListMap.all`). */
+export const environmentListResource = defineReplica<Record<string, never>, EvalEnvironmentRow[]>({
+ key: () => ENVIRONMENT_LIST_KEY,
+ name: 'lobeBenchEnvironmentList',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/eval/store.ts b/src/store/eval/store.ts
index 7bf176e9559..812d4043652 100644
--- a/src/store/eval/store.ts
+++ b/src/store/eval/store.ts
@@ -8,14 +8,20 @@ import { flattenActions } from '../utils/flattenActions';
import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';
import { type EvalStoreState, initialState } from './initialState';
import { type BenchmarkAction, createBenchmarkSlice } from './slices/benchmark/action';
+import { type ConnectorAction, createConnectorSlice } from './slices/connector/action';
+import { type ConversationAction, createConversationSlice } from './slices/conversation/action';
import { createDatasetSlice, type DatasetAction } from './slices/dataset/action';
import { createExperimentSlice, type ExperimentAction } from './slices/experiment/action';
+import { createLobeBenchSlice, type LobeBenchAction } from './slices/lobeBench/action';
import { createRunSlice, type RunAction } from './slices/run/action';
import { createTestCaseSlice, type TestCaseAction } from './slices/testCase/action';
type EvalStoreAction = BenchmarkAction &
+ ConnectorAction &
+ ConversationAction &
DatasetAction &
ExperimentAction &
+ LobeBenchAction &
RunAction &
TestCaseAction &
ResetableStore;
@@ -32,8 +38,11 @@ const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (
...initialState,
...flattenActions<EvalStoreAction>([
createBenchmarkSlice(...parameters),
+ createConversationSlice(...parameters),
+ createConnectorSlice(...parameters),
createDatasetSlice(...parameters),
createExperimentSlice(...parameters),
+ createLobeBenchSlice(...parameters),
createRunSlice(...parameters),
createTestCaseSlice(...parameters),
new EvalStoreResetAction(...parameters),