-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexperiment-detail-view.tsx
More file actions
1860 lines (1793 loc) · 68.2 KB
/
Copy pathexperiment-detail-view.tsx
File metadata and controls
1860 lines (1793 loc) · 68.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import {
useCallback,
useDeferredValue,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import useSWR from "swr";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { ExperimentTrialsTable } from "@/components/experiment-trials-table";
import { QaCostSuffix } from "@/components/qa-cost-suffix";
import { TagEditor } from "@/components/tag-editor";
import { UnifiedDrawerWrapper } from "@/components/unified-drawer-wrapper";
import { fetcher } from "@/lib/api";
import { prBadge, prNumberFromUrl, taskPrUrl } from "@/lib/utils";
import {
formatCostUsd,
formatTokenCount,
hasDisplayableCostUsd,
} from "@/lib/format";
import {
EMPTY_TRIAL_AGGREGATE,
accumulateTrial,
} from "@/lib/trial-aggregation";
import type {
ExperimentCostTotals,
Task,
Trial,
UserTagRef,
} from "@/lib/types";
import { ExternalLink, GitPullRequest, Info, Loader2 } from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
buildExperimentAgentSummaries,
getExperimentAgentKey,
isBaselineAgentName,
type ExperimentAgentSummary,
} from "@/lib/experiment-agent-grouping";
import { resolveExperimentTaskVersion } from "@/lib/experiment-task-version";
import {
formatLineRange,
parseLineRange,
type LineRange,
} from "@/lib/line-range";
import { sameFilePath } from "@/lib/file-path";
import { expandTrialParam, shortTrialParam } from "@/lib/trial-url";
type DrawerMode = "task" | "trial";
import { ProbeDetailPanel } from "@/components/probe-detail-panel";
const TrialDetailPanel = dynamic(
() =>
import("@/components/trial-detail-panel").then(
(mod) => mod.TrialDetailPanel
),
{
ssr: false,
loading: () => <DrawerContentLoading label="Loading trial details..." />,
}
);
const TaskFilesPanel = dynamic(
() =>
import("@/components/task-files-panel").then((mod) => mod.TaskFilesPanel),
{
ssr: false,
loading: () => <DrawerContentLoading label="Loading task files..." />,
}
);
function DrawerContentLoading({ label }: { label: string }) {
return (
<div className="text-muted-foreground flex h-full min-h-[180px] items-center justify-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
<span>{label}</span>
</div>
);
}
type DrawerState = {
isOpen: boolean;
mode: DrawerMode;
task: Task;
taskIndex: number;
orderedTasks: Task[];
trial: Trial | null;
trialIndex: number | null;
orderedTrials: Trial[];
trialGroups: Array<{
agent: string;
model: string | null;
trials: Trial[];
}>;
} | null;
interface ExperimentDetailViewProps {
experimentId?: string;
tasksForExperiment: Task[];
// Server-side spend rollup for the whole experiment. Omit (as the public
// share view does) to fall back to summing the loaded trials, which
// understates cost while pages are unloaded.
costTotals?: ExperimentCostTotals;
// True while the rollup is still in flight, so the cost tiles show a
// placeholder instead of the (wrong) client sum. See experiment-client.
costTotalsPending?: boolean;
isLoading: boolean;
isLoadingTrials?: boolean;
hasError?: boolean;
errorTitle?: string;
errorDescription?: string;
headerLeft: React.ReactNode;
headerStatus?: React.ReactNode;
headerRight?: React.ReactNode;
headerDescription?: React.ReactNode;
inlineAlert?: React.ReactNode;
readOnly?: boolean;
allowRetry?: boolean;
showAnalysis?: boolean;
apiBaseUrl?: string;
onTaskUnlink?: (task: Task) => Promise<void>;
onTrialDelete?: (trial: Trial, task: Task | null) => Promise<void>;
onRerun?: (taskIds?: string[]) => void;
// Logged-in exp page sends slim trials, so set true to fetch a clicked
// trial's full detail on open. Public share page omits it (it passes full
// trials and can't use the authed /api/trials route).
loadFullTrialOnOpen?: boolean;
}
const AGENT_SUMMARY_STORAGE_PREFIX = "oddish:experiment-agent-summaries:";
function getModelScopedAgentsFromSummaries(
summaries: ExperimentAgentSummary[]
): Set<string> {
return new Set(
summaries
.filter((summary) => summary.isModelScoped)
.map((summary) => summary.agent)
);
}
type ExperimentSummary = {
rewardSuccess: number;
rewardSum: number;
rewardTotal: number;
/**
* Mean over tasks of the per-task mean reward (scored trials only,
* nop/oracle baselines excluded). Null until at least one task has a
* scored trial.
*/
avgScore: number | null;
totalTrials: number;
completedTrials: number;
failedTrials: number;
skippedTrials: number;
passCount: number;
partialCount: number;
failCount: number;
harnessErrorCount: number;
pendingCount: number;
costUsd: number;
costTrialCount: number;
costHasEstimated: boolean;
costHasNative: boolean;
qaCostUsd: number;
ownedQaCostUsd: number;
qaHasEstimated: boolean;
ownedCostUsd: number;
ownedTrialCount: number;
ownedHasEstimated: boolean;
ownedHasNative: boolean;
tokenCount: number;
tokenTrialCount: number;
ownedTokenCount: number;
ownedTokenTrialCount: number;
billedCostUsd: number;
billedTrialCount: number;
billedHasEstimated: boolean;
billedHasNative: boolean;
billedTokenCount: number;
billedTokenTrialCount: number;
};
function buildExperimentSummary(tasksForExperiment: Task[]): ExperimentSummary {
const acc = { ...EMPTY_TRIAL_AGGREGATE };
// ``rewardSuccess`` mirrors ``passCount`` from the trials path but folds in
// task-level fallbacks for tasks whose trials aren't loaded yet.
let rewardSuccess = 0;
let totalTrialsFallback = 0;
let completedFallback = 0;
let failedFallback = 0;
let skippedFallback = 0;
let rewardSumFallback = 0;
let rewardTotalFallback = 0;
// Per-task mean reward over scored trials (baselines excluded); the avg
// score is the mean of these so every task carries equal weight
// regardless of how many trials it ran.
let taskScoreSum = 0;
let taskScoreCount = 0;
for (const task of tasksForExperiment) {
const trials = (task.trials ?? []).filter((t) => !t.is_probe);
if (trials.length > 0) {
// task.experiment_id is the viewing experiment (set by the backend
// builders); trials homed elsewhere count as cost (they price the work
// shown) but not as owned/new spend.
for (const trial of trials)
accumulateTrial(
acc,
trial,
trial.experiment_id == null ||
trial.experiment_id === task.experiment_id
);
let scoredRewardSum = 0;
let scoredCount = 0;
for (const trial of trials) {
if (isBaselineAgentName(trial.agent)) continue;
if (trial.status !== "success" || trial.reward == null) continue;
scoredRewardSum += trial.reward;
scoredCount += 1;
}
if (scoredCount > 0) {
taskScoreSum += scoredRewardSum / scoredCount;
taskScoreCount += 1;
}
} else {
rewardSuccess += task.reward_success ?? 0;
rewardSumFallback += task.reward_sum ?? task.reward_success ?? 0;
rewardTotalFallback += task.reward_total ?? 0;
totalTrialsFallback += task.total;
completedFallback += task.completed;
failedFallback += task.failed;
skippedFallback += task.skipped ?? 0;
}
}
return {
rewardSuccess: rewardSuccess + acc.passCount,
rewardSum: acc.rewardSum + rewardSumFallback,
rewardTotal: acc.rewardTotal + rewardTotalFallback,
avgScore: taskScoreCount > 0 ? taskScoreSum / taskScoreCount : null,
totalTrials: acc.trialCount + totalTrialsFallback,
completedTrials: acc.completed + completedFallback,
failedTrials: acc.failed + failedFallback,
skippedTrials: acc.skipped + skippedFallback,
passCount: acc.passCount,
partialCount: acc.partialCount,
failCount: acc.failCount,
harnessErrorCount: acc.harnessErrorCount,
pendingCount: acc.pendingCount,
costUsd: acc.costUsd,
costTrialCount: acc.costTrialCount,
costHasEstimated: acc.costHasEstimated,
costHasNative: acc.costHasNative,
// QA has no client-side fold -- it rides in only via the server rollup
// (the ``costTotals`` override below), so the base value is always zero.
qaCostUsd: 0,
ownedQaCostUsd: 0,
qaHasEstimated: false,
ownedCostUsd: acc.ownedCostUsd,
ownedTrialCount: acc.ownedTrialCount,
ownedHasEstimated: acc.ownedHasEstimated,
ownedHasNative: acc.ownedHasNative,
tokenCount: acc.tokenCount,
tokenTrialCount: acc.tokenTrialCount,
ownedTokenCount: acc.ownedTokenCount,
ownedTokenTrialCount: acc.ownedTokenTrialCount,
billedCostUsd: acc.billedCostUsd,
billedTrialCount: acc.billedTrialCount,
billedHasEstimated: acc.billedHasEstimated,
billedHasNative: acc.billedHasNative,
billedTokenCount: acc.billedTokenCount,
billedTokenTrialCount: acc.billedTokenTrialCount,
};
}
function ExperimentHeaderMeta({
isLoading,
isInitialLoading,
headerStatus,
showPassAtK,
onToggleShowPassAtK,
headerRight,
prLink,
}: {
isLoading: boolean;
isInitialLoading: boolean;
headerStatus?: React.ReactNode;
showPassAtK: boolean;
onToggleShowPassAtK: () => void;
headerRight?: React.ReactNode;
prLink?: React.ReactNode;
}) {
return (
<div className="flex flex-wrap items-center justify-end gap-2">
{headerStatus}
{prLink}
{isLoading && (
<div className="inline-flex items-center gap-1.5 rounded-[7px] border border-[color:var(--paper-line)] bg-[color:var(--paper-surface-2)] px-2 py-1 text-xs text-[color:var(--paper-ink-3)]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
<span>{isInitialLoading ? "Loading tasks..." : "Refreshing..."}</span>
</div>
)}
<Button
type="button"
variant="ghost"
onClick={onToggleShowPassAtK}
aria-pressed={showPassAtK}
className={`h-8 gap-[7px] rounded-[7px] border px-3 text-[12px] leading-none transition-colors select-none ${
showPassAtK
? "border-[color:var(--paper-ink)] bg-[color:var(--paper-ink)] text-[color:var(--paper-bg)] hover:bg-[color:color-mix(in_oklch,var(--paper-ink),white_12%)]"
: "border-[color:var(--paper-line)] bg-[color:var(--paper-surface)] text-[color:var(--paper-ink)] hover:border-[color:var(--paper-ink-4)] hover:bg-[color:var(--paper-surface-2)]"
}`}
>
<svg
width="13"
height="13"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M3 3v18h18" />
<path d="M7 14l4-4 4 4 5-5" />
</svg>
Pass/k graph
</Button>
{headerRight}
</div>
);
}
function MetaDot() {
return (
<span
aria-hidden="true"
className="h-[3px] w-[3px] rounded-full bg-[color:var(--paper-ink-4)]"
/>
);
}
function formatRelativeTime(iso: string): string {
const t = new Date(iso).getTime();
if (!Number.isFinite(t)) return "";
const diffSec = Math.max(0, Math.floor((Date.now() - t) / 1000));
if (diffSec < 45) return "just now";
if (diffSec < 60 * 60) return `${Math.round(diffSec / 60)}m ago`;
if (diffSec < 60 * 60 * 24) return `${Math.round(diffSec / 3600)}h ago`;
if (diffSec < 60 * 60 * 24 * 30)
return `${Math.round(diffSec / (3600 * 24))}d ago`;
return new Date(iso).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
}
function pickExperimentCreationMeta(tasks: Task[]): {
createdAt: string | null;
author: string | null;
} {
if (tasks.length === 0) return { createdAt: null, author: null };
const experimentCreatedAt =
tasks.find((task) => task.experiment_created_at)?.experiment_created_at ??
null;
let earliest: Task = tasks[0];
for (const task of tasks) {
if (
new Date(task.created_at).getTime() <
new Date(earliest.created_at).getTime()
) {
earliest = task;
}
}
// Prefer the experiment's own owner (the creating run's submitter, stamped
// on the experiment). Fall back to the earliest task's author for
// experiments with no stamped owner.
const experimentOwner =
tasks.find((task) => task.experiment_owner)?.experiment_owner ?? null;
return {
createdAt: experimentCreatedAt ?? earliest.created_at,
author:
experimentOwner ?? earliest.github_username ?? earliest.user ?? null,
};
}
function pickExperimentPr(tasks: Task[]): {
prUrl: string | null;
prTitle: string | null;
prNumber: string | null;
} {
// Prefer the experiment's own PR link (stamped set-once from the creating
// run); it is immune to other experiments re-running a shared task. Fall back
// to the task-derived link for experiments with no stamped link.
const experimentLink =
tasks.find((t) => t.experiment_link)?.experiment_link ?? null;
if (experimentLink) {
return {
prUrl: experimentLink,
prTitle: null,
prNumber: prNumberFromUrl(experimentLink),
};
}
const task = tasks.find((t) => taskPrUrl(t.link, t.github_meta));
const meta = task?.github_meta;
const prUrl = taskPrUrl(task?.link, meta);
return {
prUrl,
prTitle: meta?.pr_title ?? null,
prNumber: meta?.pr_number ?? prNumberFromUrl(prUrl),
};
}
// Dedicated header affordance linking an experiment back to the GitHub PR that
// spawned it (lineage tracing). The PR URL rides in along every task's
// `github_meta` (set via `oddish run --github-meta`); we surface the first task
// that carries one. Renders nothing when no PR metadata is present.
function ExperimentPrLink({
tasks,
isInitialLoading,
}: {
tasks: Task[];
isInitialLoading: boolean;
}) {
if (isInitialLoading) return null;
const { prUrl, prTitle, prNumber } = pickExperimentPr(tasks);
if (!prUrl) {
return (
<span
title="No pull request linked to this experiment"
className="inline-flex h-8 items-center gap-[7px] rounded-[7px] border border-[color:var(--paper-line)] bg-[color:var(--paper-surface)] px-3 text-[12px] leading-none text-[color:var(--paper-ink-3)] opacity-60 select-none"
>
<GitPullRequest className="h-3.5 w-3.5 shrink-0" aria-hidden />
no PR linked
</span>
);
}
const { label, number } = prBadge(prUrl, prNumber);
return (
<a
href={prUrl}
target="_blank"
rel="noreferrer"
title={
prTitle ? `${prTitle} — view on GitHub` : "View pull request on GitHub"
}
className="inline-flex h-8 max-w-[200px] items-center gap-[7px] rounded-[7px] border border-[color:var(--paper-line)] bg-[color:var(--paper-surface)] px-3 text-[12px] leading-none text-[color:var(--paper-ink)] transition-colors select-none hover:border-[color:var(--paper-ink-4)] hover:bg-[color:var(--paper-surface-2)]"
>
<GitPullRequest className="h-3.5 w-3.5 shrink-0" aria-hidden />
<span className="min-w-0 truncate">
{label}
{number && (
<span className="text-[color:var(--paper-ink-3)]"> #{number}</span>
)}
</span>
<ExternalLink className="h-3 w-3 shrink-0 opacity-50" aria-hidden />
</a>
);
}
function ExperimentMetaStrip({
tasks,
isInitialLoading,
experimentId,
readOnly = false,
}: {
tasks: Task[];
isInitialLoading: boolean;
experimentId?: string;
readOnly?: boolean;
}) {
const [copied, setCopied] = useState(false);
const handleCopyExperimentId = useCallback(async () => {
if (!experimentId) return;
try {
await navigator.clipboard.writeText(experimentId);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch (error) {
console.error("Failed to copy experiment id", error);
}
}, [experimentId]);
if (isInitialLoading) return null;
const { createdAt, author } = pickExperimentCreationMeta(tasks);
const showAuthor = Boolean(author) && !readOnly;
if (!createdAt && !showAuthor && !experimentId) return null;
return (
<div className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 font-mono text-[11.5px] text-[color:var(--paper-ink-3)]">
{createdAt && (
<span title={new Date(createdAt).toLocaleString()}>
created {formatRelativeTime(createdAt)}
</span>
)}
{createdAt && showAuthor && <MetaDot />}
{showAuthor && <span>by {author}</span>}
{(createdAt || showAuthor) && experimentId && <MetaDot />}
{experimentId && (
<span className="inline-flex items-center gap-1">
<span>id</span>
<Button
type="button"
variant="ghost"
onClick={handleCopyExperimentId}
className="h-auto cursor-pointer rounded-sm bg-transparent p-0 font-mono text-[11.5px] font-normal text-[color:var(--paper-ink-2)] transition hover:bg-transparent hover:text-[color:var(--paper-ink)]"
aria-label={`Copy experiment id ${experimentId}`}
title={copied ? "Copied" : "Click to copy experiment id"}
>
<span className="select-all">{experimentId}</span>
</Button>
{copied && <span aria-live="polite">copied</span>}
</span>
)}
</div>
);
}
function KpiTile({
label,
labelInfo,
children,
className = "",
}: {
label: string;
labelInfo?: string;
children: React.ReactNode;
className?: string;
}) {
return (
<div
className={`flex flex-col gap-1.5 border-r border-[color:var(--paper-line-2)] px-4 py-3 last:border-r-0 ${className}`}
>
<span className="inline-flex items-center gap-1 font-mono text-[10px] font-semibold tracking-[0.09em] text-[color:var(--paper-ink-3)] uppercase">
{label}
{labelInfo && (
<TooltipProvider delayDuration={150}>
<Tooltip>
<TooltipTrigger asChild>
<Info
className="h-3 w-3 cursor-help text-[color:var(--paper-ink-3)]"
aria-label={`How ${label} is calculated`}
/>
</TooltipTrigger>
<TooltipContent className="max-w-xs normal-case">
{labelInfo}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</span>
{children}
</div>
);
}
function ExperimentSummaryBar({
taskCount,
summary,
isInitialLoading,
isLoadingTrials,
showNewSpend,
// True when cost came from the server rollup, which reports SPEND: every
// trial that ran, including earlier task versions, superseded retries and
// probes that the table below filters out. Drives the tooltip's disclosure.
costIsSpend,
costPending,
}: {
taskCount: number;
summary: ExperimentSummary;
isInitialLoading: boolean;
isLoadingTrials: boolean;
showNewSpend: boolean;
costIsSpend: boolean;
costPending: boolean;
}) {
if (isInitialLoading) {
return (
<div className="flex items-center gap-2 rounded-[10px] border border-[color:var(--paper-line)] bg-[color:var(--paper-surface)] px-4 py-3 text-xs text-[color:var(--paper-ink-3)]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Loading experiment summary...
</div>
);
}
const scorePct = summary.avgScore != null ? summary.avgScore * 100 : null;
// "Completion" is how many trials have finished — success, failed, AND
// skipped are all terminal — matching the backend's done count
// (resolve_task_status). The pass count lives in the Avg-score tile.
const doneTrials =
summary.completedTrials + summary.failedTrials + summary.skippedTrials;
const completionPct =
summary.totalTrials > 0 ? (doneTrials / summary.totalTrials) * 100 : 0;
// Skipped is a terminal non-pass (its own bucket), so it belongs in the
// outcome distribution alongside pass/partial/fail/harness — otherwise the
// bar's percentages disagree with the pass metrics (e.g. 2 pass + 3 skipped
// would read as 100% pass here while the pass rate is 2/5).
const outcomeTotal =
summary.passCount +
summary.partialCount +
summary.failCount +
summary.harnessErrorCount +
summary.skippedTrials;
const passPct = outcomeTotal ? (summary.passCount / outcomeTotal) * 100 : 0;
const partialPct = outcomeTotal
? (summary.partialCount / outcomeTotal) * 100
: 0;
const failPct = outcomeTotal ? (summary.failCount / outcomeTotal) * 100 : 0;
const errPct = outcomeTotal
? (summary.harnessErrorCount / outcomeTotal) * 100
: 0;
const skippedPct = outcomeTotal
? (summary.skippedTrials / outcomeTotal) * 100
: 0;
return (
<div
className={`grid grid-cols-2 overflow-hidden rounded-[10px] border border-[color:var(--paper-line)] bg-[color:var(--paper-surface)] ${
showNewSpend
? "md:grid-cols-[1.1fr_1fr_0.9fr_0.9fr_0.9fr_1.4fr]"
: "md:grid-cols-[1.1fr_1fr_0.9fr_0.9fr_1.4fr]"
}`}
>
<KpiTile
label="Avg score"
labelInfo="Average of per-task average reward, nop/oracle excluded"
>
<span className="font-display flex items-baseline gap-2 text-[26px] leading-none font-medium tracking-[-0.02em] text-[color:var(--paper-ink)]">
{isLoadingTrials ? (
// The score is computed from streamed trial pages; rendering an
// intermediate value would show a number that jumps once the
// remaining pages land.
<Loader2 className="h-5 w-5 animate-spin text-[color:var(--paper-ink-3)]" />
) : scorePct != null ? (
`${scorePct.toFixed(1)}%`
) : (
"—"
)}
</span>
</KpiTile>
<KpiTile label="Completion">
<span className="font-display flex items-baseline gap-2 text-[26px] leading-none font-medium tracking-[-0.02em] text-[color:var(--paper-ink)]">
{doneTrials}
<span className="font-mono text-xs font-normal text-[color:var(--paper-ink-3)]">
/ {summary.totalTrials} trials
</span>
</span>
<span className="font-mono text-[10px] text-[color:var(--paper-ink-3)]">
{completionPct.toFixed(0)}%
{summary.skippedTrials > 0 && (
<span className="ml-1.5 text-[color:var(--paper-ink-3)]">
· {summary.skippedTrials} skipped
</span>
)}
{summary.failedTrials > 0 && (
<span className="ml-1.5 text-[color:var(--paper-fail)]">
· {summary.failedTrials} failing
</span>
)}
</span>
</KpiTile>
<KpiTile label="Tasks">
<span className="font-display flex items-baseline gap-2 text-[26px] leading-none font-medium tracking-[-0.02em] text-[color:var(--paper-ink)]">
{taskCount}
<span className="font-mono text-xs font-normal text-[color:var(--paper-ink-3)]">
tasks
</span>
</span>
</KpiTile>
<KpiTile
label="Cost"
labelInfo="Total cost of all trials shown in this experiment, including trials gathered from other experiments."
>
<span
className="font-display flex items-baseline gap-1 text-[26px] leading-none font-medium tracking-[-0.02em] text-[color:var(--paper-ink)]"
title={
// Must agree with the VALUE rendered below: while the rollup is in
// flight the tile shows an em dash, so the tooltip cannot describe
// the client fold's (partial, grid-scoped) counts.
costPending
? "Calculating experiment spend…"
: summary.costTrialCount > 0
? `Summed across ${summary.costTrialCount} trial${
summary.costTrialCount === 1 ? "" : "s"
} shown in this experiment${
// Gathered/shared-task spend is deliberately included: it
// prices the work on this page. Warn that those dollars
// are also reported on their home experiments so nobody
// sums Cost tiles across pages.
summary.costTrialCount > summary.ownedTrialCount
? ", including trials gathered from other experiments (their spend is also reported there)"
: ""
}${
// Spend covers every trial that ran; the table is filtered to
// each task's current version. Say so, or the tile reads as
// "wrong" whenever a task was re-uploaded or a trial retried.
costIsSpend
? ". The table shows only current-version trials"
: ""
}${
summary.costHasEstimated && summary.costHasNative
? ". Mixed native + estimated values; ~ marks estimates."
: summary.costHasEstimated
? ". Estimated from token counts × static model pricing."
: ". Reported by the agent runtime."
}`
: "No cost data reported yet"
}
>
{costPending ? (
<span className="text-[color:var(--paper-ink-3)]">—</span>
) : summary.costTrialCount > 0 &&
hasDisplayableCostUsd(summary.costUsd) ? (
<>
{summary.costHasEstimated && !summary.costHasNative && (
<span className="font-mono text-[16px] text-[color:var(--paper-ink-3)]">
~
</span>
)}
{formatCostUsd(summary.costUsd)}
{summary.costHasEstimated && summary.costHasNative && (
<span className="font-mono text-[16px] text-[color:var(--paper-ink-3)]">
*
</span>
)}
</>
) : (
<span className="text-[color:var(--paper-ink-3)]">—</span>
)}
{!costPending && (
<QaCostSuffix
costUsd={summary.qaCostUsd}
size="tile"
title={
summary.qaHasEstimated
? "QA/analysis spend across this experiment's trials. Some values estimated from token counts × static model pricing. Not included in the cost figure."
: "QA/analysis spend across this experiment's trials. Not included in the cost figure."
}
/>
)}
</span>
{!costPending && summary.tokenTrialCount > 0 && (
<span className="font-mono text-[10px] text-[color:var(--paper-ink-3)]">
{formatTokenCount(summary.tokenCount)}
</span>
)}
</KpiTile>
{showNewSpend && (
<KpiTile
label="New spend"
labelInfo="Spend from trials this experiment ran itself — excludes trials gathered from other experiments."
>
<span
className="font-display flex items-baseline gap-1 text-[26px] leading-none font-medium tracking-[-0.02em] text-[color:var(--paper-ink)]"
title={
costPending
? "Calculating new spend…"
: summary.ownedTrialCount > 0
? `Summed across ${summary.ownedTrialCount} trial${
summary.ownedTrialCount === 1 ? "" : "s"
} this experiment ran itself${
// Billing attribution is a property of who pays, not of
// what the experiment did; surface it here rather than
// in the headline.
summary.billedTrialCount > 0
? `. ${formatCostUsd(summary.billedCostUsd)} of this was billed to user quotas`
: ". None of it was billed to a user quota"
}${
costIsSpend
? ". The table shows only current-version trials"
: ""
}${
summary.ownedHasEstimated && summary.ownedHasNative
? ". Mixed native + estimated values; ~ marks estimates."
: summary.ownedHasEstimated
? ". Estimated from token counts × static model pricing."
: ". Reported by the agent runtime."
}`
: // Owned usage first: an experiment whose own trials
// reported tokens but no priced cost DID run work — it
// must not read as a pure collection.
summary.ownedTokenTrialCount > 0
? "No cost data reported yet for this experiment's own trials"
: summary.costTrialCount > 0
? "This experiment ran no trials of its own; every priced trial shown was gathered from another experiment, where its spend is reported."
: "No spend from this experiment yet"
}
>
{costPending ? (
<span className="text-[color:var(--paper-ink-3)]">—</span>
) : summary.ownedTrialCount > 0 ? (
<>
{summary.ownedHasEstimated && !summary.ownedHasNative && (
<span className="font-mono text-[16px] text-[color:var(--paper-ink-3)]">
~
</span>
)}
{formatCostUsd(summary.ownedCostUsd)}
{summary.ownedHasEstimated && summary.ownedHasNative && (
<span className="font-mono text-[16px] text-[color:var(--paper-ink-3)]">
*
</span>
)}
</>
) : summary.ownedTokenTrialCount === 0 &&
summary.costTrialCount > 0 ? (
// Priced work exists and this experiment's own trials reported
// nothing at all: an explicit zero ("nothing new was spent")
// reads honestly where a dash would read as "unknown". With
// owned usage awaiting pricing, the dash is the honest one.
<>{formatCostUsd(0)}</>
) : (
<span className="text-[color:var(--paper-ink-3)]">—</span>
)}
{!costPending && (
<QaCostSuffix
costUsd={summary.ownedQaCostUsd}
size="tile"
title="QA/analysis spend on this experiment's own trials. Not included in the new spend figure."
/>
)}
</span>
{!costPending && summary.ownedTokenTrialCount > 0 && (
<span className="font-mono text-[10px] text-[color:var(--paper-ink-3)]">
{formatTokenCount(summary.ownedTokenCount)}
</span>
)}
</KpiTile>
)}
<KpiTile
label="Outcome distribution"
className="col-span-2 md:col-span-1"
>
<div className="flex h-1.5 overflow-hidden rounded-[3px] bg-[color:var(--paper-bg-2)]">
<span
style={{ width: `${passPct}%`, background: "var(--paper-pass)" }}
/>
<span
style={{
width: `${partialPct}%`,
background: "var(--paper-partial)",
}}
/>
<span
style={{ width: `${failPct}%`, background: "var(--paper-fail)" }}
/>
<span
style={{ width: `${errPct}%`, background: "var(--paper-error)" }}
/>
<span
style={{
width: `${skippedPct}%`,
background: "var(--paper-ink-3)",
}}
/>
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-[11px] text-[color:var(--paper-ink-2)]">
<span className="inline-flex items-center gap-1.5">
<i className="inline-block h-2 w-2 rounded-[2px] bg-[color:var(--paper-pass)]" />
{summary.passCount}
<span className="text-[color:var(--paper-ink-3)]">pass</span>
</span>
{summary.partialCount > 0 && (
<span className="inline-flex items-center gap-1.5">
<i className="inline-block h-2 w-2 rounded-[2px] bg-[color:var(--paper-partial)]" />
{summary.partialCount}
<span className="text-[color:var(--paper-ink-3)]">partial</span>
</span>
)}
<span className="inline-flex items-center gap-1.5">
<i className="inline-block h-2 w-2 rounded-[2px] bg-[color:var(--paper-fail)]" />
{summary.failCount}
<span className="text-[color:var(--paper-ink-3)]">fail</span>
</span>
{summary.harnessErrorCount > 0 && (
<span className="inline-flex items-center gap-1.5">
<i className="inline-block h-2 w-2 rounded-[2px] bg-[color:var(--paper-error)]" />
{summary.harnessErrorCount}
<span className="text-[color:var(--paper-ink-3)]">error</span>
</span>
)}
{summary.skippedTrials > 0 && (
<span className="inline-flex items-center gap-1.5">
<i className="inline-block h-2 w-2 rounded-[2px] bg-[color:var(--paper-ink-3)]" />
{summary.skippedTrials}
<span className="text-[color:var(--paper-ink-3)]">skipped</span>
</span>
)}
</div>
</KpiTile>
</div>
);
}
export function ExperimentDetailView({
experimentId,
tasksForExperiment,
costTotals,
costTotalsPending = false,
isLoading,
isLoadingTrials = false,
hasError = false,
errorTitle = "Failed to load experiment",
errorDescription = "Check the API connection and try again.",
headerLeft,
headerStatus,
headerRight,
headerDescription,
inlineAlert,
readOnly = false,
allowRetry = true,
showAnalysis = true,
apiBaseUrl = "/api",
onTaskUnlink,
onTrialDelete,
onRerun,
loadFullTrialOnOpen = false,
}: ExperimentDetailViewProps) {
const searchParams = useSearchParams();
// The experiment's own direct tags (the header editor chips); fetched
// separately because no experiment payload carries them.
const { data: experimentTags, mutate: mutateExperimentTags } = useSWR<
UserTagRef[]
>(
experimentId
? `/api/tags/for-target?scope=EXPERIMENT&target_id=${encodeURIComponent(experimentId)}`
: null,
fetcher,
{ revalidateOnFocus: false }
);
const [drawerState, setDrawerState] = useState<DrawerState>(null);
// Task-definition pane addressing. The drawer can show the task's file
// tree beside the trial view, so the two panes address independently:
// the trial pane owns ?file= / ?lines= (see TrialDetailPanel) and the
// task pane owns ?taskFile= / ?taskLines=.
const [taskPaneFile, setTaskPaneFile] = useState<string | null>(() =>
searchParams.get("taskFile")
);
const [taskPaneLines, setTaskPaneLines] = useState<LineRange | null>(() =>
parseLineRange(searchParams.get("taskLines"))
);
// ?taskView=reward addresses the task pane's reward-design view; the
// overview is the unmarked default.
const [taskPaneView, setTaskPaneView] = useState<"reward" | null>(() =>
searchParams.get("taskView") === "reward" ? "reward" : null
);
const handleTaskPaneViewChange = useCallback(
(view: "overview" | "reward" | null) => {
setTaskPaneView(view === "reward" ? "reward" : null);
},
[]
);
// Mirrors taskPaneFile so the change handler can compare without an
// impure setState updater.
const taskPaneFileRef = useRef<string | null>(taskPaneFile);
const handleTaskPaneFileChange = useCallback((path: string | null) => {
// A different file makes the old line anchor meaningless — drop it.
if (!sameFilePath(taskPaneFileRef.current, path)) setTaskPaneLines(null);
taskPaneFileRef.current = path;
setTaskPaneFile(path);
}, []);
// Reset the pane address when the drawer moves to another task (grid
// selection, prev/next nav) or closes — the old path belongs to the old
// task. The first open keeps it so deep links land.
const lastDrawerTaskIdRef = useRef<string | null>(null);
useEffect(() => {
const taskId = drawerState?.task.id ?? null;
if (
lastDrawerTaskIdRef.current !== null &&
taskId !== lastDrawerTaskIdRef.current
) {
handleTaskPaneFileChange(null);
setTaskPaneView(null);
}
lastDrawerTaskIdRef.current = taskId;
}, [drawerState?.task.id, handleTaskPaneFileChange]);
// Probe cells open main's sliding ProbeDetailPanel (kept from origin/main).
// On the slim experiment path the grid has no probe trials to click, so this
// stays dormant until probes are fed to that path -- the code is retained so
// main's probe-drawer feature is preserved and the merge stays coherent.
const [probeDrawer, setProbeDrawer] = useState<{
taskId: string;