tuxevil-rotator 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +4 -2
  3. package/package.json +2 -1
  4. package/src/access-evidence.ts +153 -0
  5. package/src/access-probe.ts +85 -0
  6. package/src/admin-auth.ts +4 -1
  7. package/src/auto-access-shadow.ts +11 -0
  8. package/src/auto-model-access.ts +185 -0
  9. package/src/auto-output-health.ts +12 -0
  10. package/src/auto-routing-evaluation.ts +80 -0
  11. package/src/auto-routing-quality.ts +308 -0
  12. package/src/auto-routing.ts +403 -26
  13. package/src/compat.ts +223 -36
  14. package/src/compression/index.ts +6 -6
  15. package/src/compression/lite.ts +3 -9
  16. package/src/compression/rtk/index.ts +0 -3
  17. package/src/config-defaults.ts +7 -0
  18. package/src/dashboard.ts +5 -0
  19. package/src/db-store.ts +10 -0
  20. package/src/index.ts +2 -0
  21. package/src/model-access-api.ts +74 -0
  22. package/src/model-access.ts +56 -0
  23. package/src/ollama-output-gate.ts +18 -0
  24. package/src/onboarding.ts +1 -1
  25. package/src/provider-catalog-evidence.ts +26 -0
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
  27. package/src/providers/google-antigravity/quota.ts +3 -0
  28. package/src/providers/ollama/context-window.ts +13 -0
  29. package/src/providers/ollama/quota.ts +4 -0
  30. package/src/providers/ollama/translators.ts +19 -2
  31. package/src/providers/openai-codex/compat.ts +5 -1
  32. package/src/providers/openai-codex/credentials.ts +22 -6
  33. package/src/providers/openai-codex/index.ts +9 -1
  34. package/src/providers/openai-codex/quota.ts +19 -6
  35. package/src/providers/opencode-zen/forward.ts +1 -1
  36. package/src/providers/opencode-zen/quota.ts +2 -0
  37. package/src/proxy.ts +78 -3
  38. package/src/quota-observation.ts +26 -0
  39. package/src/quota-pools.ts +322 -0
  40. package/src/rotator.ts +151 -38
  41. package/src/settings-repository.ts +1 -0
  42. package/src/types.ts +28 -0
  43. package/src/usage-limits-auth.ts +24 -0
  44. package/src/usage-limits.ts +148 -0
  45. package/src/validators.ts +26 -0
  46. package/src/web/components/icons.tsx +15 -0
  47. package/src/web/components/overlays.tsx +4 -0
  48. package/src/web/components/ui.tsx +9 -9
  49. package/src/web/lib/playground.ts +35 -0
  50. package/src/web/lib/pool-navigation.ts +4 -0
  51. package/src/web/lib/pools.ts +2 -243
  52. package/src/web/pages/AccountDetail.tsx +2 -1
  53. package/src/web/pages/ModelAccess.tsx +88 -0
  54. package/src/web/pages/Models.tsx +2 -0
  55. package/src/web/pages/Overview.tsx +26 -9
  56. package/src/web/pages/Playground.tsx +1132 -551
  57. package/src/web/pages/Transcription.tsx +304 -170
  58. package/src/web/state/api.ts +3 -0
  59. package/src/web/styles/app.css +501 -45
@@ -1,14 +1,19 @@
1
- import type { JSX } from "preact";
2
- import { useEffect, useRef, useState } from "preact/hooks";
1
+ import { Fragment, type JSX } from "preact";
2
+ import { useEffect, useId, useRef, useState } from "preact/hooks";
3
3
  import {
4
4
  Button,
5
5
  EmptyState,
6
+ KeyValue,
6
7
  PageHeader,
7
8
  Panel,
8
9
  Pill,
9
10
  Segmented,
10
11
  Spinner,
12
+ Switch,
13
+ Tag,
11
14
  } from "../components/ui.js";
15
+ import { Icon } from "../components/icons.js";
16
+ import { Menu, type MenuItem } from "../components/overlays.js";
12
17
  import { confirmAction, toast } from "../state/actions.js";
13
18
  import { api } from "../state/api.js";
14
19
  import { query, setQuery } from "../state/router.js";
@@ -26,13 +31,17 @@ import {
26
31
  buildChatRequest,
27
32
  newTranscription,
28
33
  CASES,
34
+ complianceJobs,
29
35
  complianceRequest,
36
+ DEFAULT_PARAMETERS,
30
37
  emptyResult,
31
38
  errorVerdict,
32
39
  evaluateCompliance,
40
+ isAudioOnlyModel,
33
41
  newDocument,
34
42
  newId,
35
43
  newPanel,
44
+ runnableComplianceModels,
36
45
  userMessage,
37
46
  VERDICT_LABELS,
38
47
  type CaseId,
@@ -41,13 +50,17 @@ import {
41
50
  type ComplianceResult,
42
51
  type ImageAttachment,
43
52
  type Parameters,
53
+ type PlaygroundDocument,
44
54
  type PlaygroundPanel,
45
55
  type PlaygroundTab,
46
56
  type Turn,
57
+ type Verdict,
47
58
  } from "../lib/playground.js";
48
59
  import { parsePlaygroundDocument } from "../lib/playground-storage.js";
60
+ import type { Tone } from "../lib/status.js";
49
61
  import { TranscriptionPage } from "./Transcription.js";
50
- import { formatMs } from "../lib/format.js";
62
+ import { copyText } from "./shared.js";
63
+ import { formatMs, formatUsd } from "../lib/format.js";
51
64
 
52
65
  const TABS: Array<{ value: PlaygroundTab; label: string }> = [
53
66
  { value: "chat", label: "Chat" },
@@ -55,8 +68,43 @@ const TABS: Array<{ value: PlaygroundTab; label: string }> = [
55
68
  { value: "compliance", label: "Compliance" },
56
69
  { value: "transcription", label: "Transcription" },
57
70
  ];
71
+ const DESCRIPTION =
72
+ "Chat with, compare and test models through the rotator. Requests use real quota.";
73
+ const MAX_COMPLIANCE_MODELS = 3;
74
+ const VERDICT_TONES: Record<Verdict, Tone> = {
75
+ passed: "ok",
76
+ failed: "bad",
77
+ error: "bad",
78
+ unsupported: "warn",
79
+ cancelled: "muted",
80
+ };
81
+ const CANCELLED_MESSAGE = "Request cancelled.";
58
82
  const errorText = (err: unknown): string =>
59
83
  err instanceof Error ? err.message : String(err);
84
+ /** Seconds keep playgrounds saved in the same minute apart; under the privacy
85
+ * mask every title reads "Saved playground". */
86
+ const savedAt = (ms: number): string =>
87
+ new Date(ms).toLocaleString([], {
88
+ month: "short",
89
+ day: "numeric",
90
+ hour: "2-digit",
91
+ minute: "2-digit",
92
+ second: "2-digit",
93
+ });
94
+ const historyLabel = (d: PlaygroundDocument): string =>
95
+ `${masked.value ? "Saved playground" : d.title} · ${savedAt(d.updatedAt)}`;
96
+ const copy = async (text: string): Promise<void> =>
97
+ toast((await copyText(text)) ? "Copied to the clipboard" : "Copy failed", "info");
98
+ /** Times that were never measured (null, or 0 before a response) read "—";
99
+ * formatMs alone turns null into "0ms". */
100
+ const duration = (ms: number | null | undefined): string =>
101
+ ms ? formatMs(ms) : "—";
102
+
103
+ interface ComplianceProgress {
104
+ done: number;
105
+ total: number;
106
+ retry: boolean;
107
+ }
60
108
 
61
109
  export function PlaygroundPage(): JSX.Element {
62
110
  const doc = currentDocument();
@@ -67,10 +115,13 @@ export function PlaygroundPage(): JSX.Element {
67
115
  requestedTab === "transcription"
68
116
  ? requestedTab
69
117
  : "chat";
70
- const [models, setModels] = useState<string[]>([]);
118
+ // null until the first load settles, so "No enabled models" never flashes.
119
+ const [models, setModels] = useState<string[] | null>(null);
71
120
  const [modelError, setModelError] = useState("");
72
121
  const [busy, setBusy] = useState<string[]>([]);
73
122
  const [checking, setChecking] = useState(false);
123
+ const [progress, setProgress] = useState<ComplianceProgress | null>(null);
124
+ const [finished, setFinished] = useState("");
74
125
  const [audioBusy, setAudioBusy] = useState(false);
75
126
  const [maxBodyBytes, setMaxBodyBytes] = useState(25 * 1024 * 1024);
76
127
  const controllers = useRef(new Map<string, AbortController>());
@@ -86,6 +137,7 @@ export function PlaygroundPage(): JSX.Element {
86
137
  ]),
87
138
  ]);
88
139
  const running = checking || busy.length > 0 || audioBusy;
140
+ const available = models ?? [];
89
141
 
90
142
  const loadModels = async () => {
91
143
  try {
@@ -200,7 +252,7 @@ export function PlaygroundPage(): JSX.Element {
200
252
  const next = userMessage(doc.draft, doc.images);
201
253
  if (!retryPanel && !doc.draft.trim() && !doc.images.length) return;
202
254
  const requests = panels.map((panel) => {
203
- if (!models.includes(panel.model))
255
+ if (!available.includes(panel.model))
204
256
  throw new Error("Choose an enabled model in every panel.");
205
257
  const lastRequest = panel.turns.at(-1)?.request;
206
258
  const message =
@@ -264,6 +316,17 @@ export function PlaygroundPage(): JSX.Element {
264
316
  toast(errorText(err), "error");
265
317
  }
266
318
  }
319
+ function newPlayground(): void {
320
+ const fresh = newDocument();
321
+ saveWorkspace(
322
+ {
323
+ ...workspace.value!,
324
+ currentId: fresh.id,
325
+ documents: [...workspace.value!.documents, fresh],
326
+ },
327
+ true,
328
+ );
329
+ }
267
330
  function exportDoc(): void {
268
331
  if (!doc) return;
269
332
  const url = URL.createObjectURL(
@@ -318,20 +381,11 @@ export function PlaygroundPage(): JSX.Element {
318
381
  );
319
382
  }
320
383
  async function runCompliance(retry = false): Promise<void> {
321
- if (!doc || !doc.complianceModels.length || !doc.cases.length) return;
384
+ if (!doc) return;
385
+ const jobs = complianceJobs(doc, retry);
386
+ if (!jobs.length) return;
322
387
  const documentId = doc.id;
323
- const failed = doc.results.filter(
324
- (r) => r.verdict === "failed" || r.verdict === "error",
325
- );
326
- const jobs = doc.complianceModels.map((model) => ({
327
- model,
328
- cases: doc.cases.filter(
329
- (caseId) =>
330
- !retry ||
331
- failed.some((r) => r.model === model && r.caseId === caseId),
332
- ),
333
- }));
334
- if (jobs.some((job) => !models.includes(job.model))) {
388
+ if (jobs.some((job) => !available.includes(job.model))) {
335
389
  toast("Select enabled models before running compliance.", "error");
336
390
  return;
337
391
  }
@@ -348,6 +402,9 @@ export function PlaygroundPage(): JSX.Element {
348
402
  ? d.results.filter((r) => !selected.has(jobKey(r.model, r.caseId)))
349
403
  : [],
350
404
  }));
405
+ let done = 0;
406
+ setFinished("");
407
+ setProgress({ done, total: selected.size, retry });
351
408
  setChecking(true);
352
409
  try {
353
410
  await Promise.all(
@@ -361,7 +418,7 @@ export function PlaygroundPage(): JSX.Element {
361
418
  try {
362
419
  if (controller.signal.aborted)
363
420
  throw new PlaygroundError(
364
- "Request cancelled.",
421
+ CANCELLED_MESSAGE,
365
422
  emptyResult(),
366
423
  true,
367
424
  );
@@ -395,6 +452,8 @@ export function PlaygroundPage(): JSX.Element {
395
452
  }
396
453
  if (currentDocument()?.id === documentId)
397
454
  updateDocument((d) => ({ ...d, results: [...d.results, row] }));
455
+ done += 1;
456
+ setProgress({ done, total: selected.size, retry });
398
457
  }
399
458
  } finally {
400
459
  controllers.current.delete(`compliance:${model}`);
@@ -403,50 +462,128 @@ export function PlaygroundPage(): JSX.Element {
403
462
  );
404
463
  } finally {
405
464
  setChecking(false);
465
+ setProgress(null);
466
+ const latest = currentDocument();
467
+ if (latest?.id === documentId) {
468
+ const passed = latest.results.filter(
469
+ (r) => r.verdict === "passed",
470
+ ).length;
471
+ setFinished(
472
+ `Compliance run finished: ${passed} of ${latest.results.length} tests passed.`,
473
+ );
474
+ }
406
475
  }
407
476
  }
408
477
 
409
- if (!doc) return <Spinner />;
410
- const panels = tab === "compare" ? doc.compare : [doc.chat];
478
+ if (!doc)
479
+ return (
480
+ <>
481
+ <PageHeader title="Playground" description={DESCRIPTION} />
482
+ <div class="panel">
483
+ <div class="panel-loading">
484
+ <Spinner />
485
+ </div>
486
+ </div>
487
+ </>
488
+ );
489
+
490
+ const compare = tab === "compare";
491
+ const stopAll = running && (
492
+ <Button
493
+ size="sm"
494
+ icon="stop"
495
+ onClick={() => {
496
+ for (const c of controllers.current.values()) c.abort();
497
+ }}
498
+ >
499
+ Stop all
500
+ </Button>
501
+ );
502
+ const selectedCount = runnableComplianceModels(doc).length;
503
+ const testCount = complianceJobs(doc).reduce(
504
+ (sum, job) => sum + job.cases.length,
505
+ 0,
506
+ );
507
+ const failedCount = complianceJobs(doc, true).reduce(
508
+ (sum, job) => sum + job.cases.length,
509
+ 0,
510
+ );
511
+ const progressLabel = progress
512
+ ? `Running ${progress.done}/${progress.total}`
513
+ : "";
514
+
411
515
  return (
412
516
  <>
413
517
  <PageHeader
414
518
  title="Playground"
415
- description="Chat, compare, transcribe audio and check API compatibility through your rotator."
519
+ description={DESCRIPTION}
416
520
  actions={
417
521
  <>
522
+ <label class="inline-select pg-history">
523
+ <span class="sr-only">Saved playground</span>
524
+ <select
525
+ class="select"
526
+ title={historyLabel(doc)}
527
+ disabled={running}
528
+ value={doc.id}
529
+ onChange={(e) =>
530
+ saveWorkspace(
531
+ { ...workspace.value!, currentId: e.currentTarget.value },
532
+ true,
533
+ )
534
+ }
535
+ >
536
+ {workspace.value!.documents.map((d) => (
537
+ <option key={d.id} value={d.id}>
538
+ {historyLabel(d)}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <Menu
544
+ label="More playground actions"
545
+ size="md"
546
+ triggerClass="btn btn-secondary btn-md btn-icon"
547
+ items={[
548
+ { heading: "Saved in this browser" },
549
+ { label: "Export", icon: "download", onSelect: exportDoc },
550
+ {
551
+ label: "Import…",
552
+ icon: "upload",
553
+ disabled: running,
554
+ onSelect: () => importRef.current?.click(),
555
+ },
556
+ "separator",
557
+ {
558
+ label: "Delete this playground…",
559
+ icon: "trash",
560
+ danger: true,
561
+ disabled: running,
562
+ onSelect: () => void deleteHistory(false),
563
+ },
564
+ {
565
+ label: "Delete all history…",
566
+ danger: true,
567
+ disabled: running,
568
+ onSelect: () => void deleteHistory(true),
569
+ },
570
+ ]}
571
+ />
418
572
  <Button
573
+ variant="primary"
574
+ icon="plus"
575
+ class="pg-new"
419
576
  disabled={running}
420
- onClick={() => {
421
- const fresh = newDocument();
422
- saveWorkspace(
423
- {
424
- ...workspace.value!,
425
- currentId: fresh.id,
426
- documents: [...workspace.value!.documents, fresh],
427
- },
428
- true,
429
- );
430
- }}
577
+ onClick={newPlayground}
431
578
  >
432
579
  New playground
433
580
  </Button>
434
- <Button icon="download" onClick={exportDoc}>
435
- Export JSON
436
- </Button>
437
- <Button
438
- icon="upload"
439
- disabled={running}
440
- onClick={() => importRef.current?.click()}
441
- >
442
- Import JSON
443
- </Button>
444
581
  <input
445
582
  ref={importRef}
446
583
  type="file"
447
584
  accept="application/json,.json"
448
585
  class="sr-only"
449
- aria-label="Import playground JSON"
586
+ aria-label="Import playground"
450
587
  onChange={(e) => {
451
588
  const file = e.currentTarget.files?.[0];
452
589
  e.currentTarget.value = "";
@@ -456,404 +593,383 @@ export function PlaygroundPage(): JSX.Element {
456
593
  </>
457
594
  }
458
595
  />
459
- <div class="playground">
460
- {storageError.value && (
461
- <div class="callout tone-warn" role="alert">
462
- Local history could not be saved. Your work is still in memory;
463
- export JSON to keep it. {masker.value.text(storageError.value)}
596
+ {storageError.value && (
597
+ <div class="callout tone-warn" role="alert">
598
+ <Icon name="warning" size={16} />
599
+ <div>
600
+ <strong>Local history could not be saved</strong>
601
+ <p>
602
+ Your work is still in memory; export it to keep it.{" "}
603
+ {masker.value.text(storageError.value)}
604
+ </p>
605
+ <Button size="sm" icon="download" onClick={exportDoc}>
606
+ Export
607
+ </Button>
464
608
  </div>
465
- )}
466
- {modelError && (
467
- <div class="callout tone-bad" role="alert">
468
- {modelError}{" "}
469
- <Button size="sm" onClick={() => void loadModels()}>
609
+ </div>
610
+ )}
611
+ {modelError && (
612
+ <div class="callout tone-bad" role="alert">
613
+ <Icon name="critical" size={16} />
614
+ <div>
615
+ <strong>Could not load models</strong>
616
+ <p>{modelError}</p>
617
+ <Button size="sm" icon="refresh" onClick={() => void loadModels()}>
470
618
  Reload models
471
619
  </Button>
472
620
  </div>
473
- )}
474
- <div class="pg-toolbar">
475
- <Segmented
476
- label="Playground mode"
477
- value={tab}
478
- options={TABS}
479
- onChange={(value) => setQuery({ tab: value }, { replace: false })}
480
- />
481
- <label class="field pg-history">
482
- <span class="sr-only">Local history</span>
483
- <select
484
- class="input"
485
- aria-label="Local history"
486
- disabled={running}
487
- value={doc.id}
488
- onChange={(e) =>
489
- saveWorkspace(
490
- { ...workspace.value!, currentId: e.currentTarget.value },
491
- true,
492
- )
493
- }
494
- >
495
- {workspace.value!.documents.map((d) => (
496
- <option key={d.id} value={d.id}>
497
- {masked.value ? "Saved playground" : d.title} ·{" "}
498
- {new Date(d.updatedAt).toLocaleString()}
499
- </option>
500
- ))}
501
- </select>
502
- </label>
503
- <Button
504
- size="sm"
505
- disabled={running}
506
- onClick={() => void deleteHistory(false)}
507
- >
508
- Delete
509
- </Button>
510
- <Button
511
- size="sm"
512
- disabled={running}
513
- onClick={() => void deleteHistory(true)}
514
- >
515
- Clear history
516
- </Button>
517
- {running && (
518
- <Button
519
- variant="danger"
520
- onClick={() => {
521
- for (const c of controllers.current.values()) c.abort();
522
- }}
523
- >
524
- Stop all
525
- </Button>
526
- )}
527
621
  </div>
528
- <p class="field-hint">
529
- History stays in this browser. Requests use real quota and may also
530
- appear in the rotator's server logs.
531
- </p>
532
- {!models.length && !modelError && (
533
- <EmptyState icon="models" title="No enabled models">
534
- Connect a provider and enable models on the Models page, then reload
535
- the catalog.{" "}
536
- <Button onClick={() => void loadModels()}>Reload models</Button>
537
- </EmptyState>
538
- )}
539
- {tab === "transcription" ? (
540
- <TranscriptionPage
541
- key={doc.id}
542
- state={doc.transcription ?? newTranscription()}
543
- models={models}
544
- maxBodyBytes={maxBodyBytes}
545
- disabled={checking || busy.length > 0}
546
- onBusyChange={setAudioBusy}
547
- controllers={controllers.current}
548
- onChange={(update) =>
549
- updateDocument(
550
- (d) => ({
551
- ...d,
552
- transcription: update(d.transcription ?? newTranscription()),
553
- }),
554
- true,
555
- )
556
- }
557
- />
558
- ) : tab === "compliance" ? (
559
- <>
560
- <Panel
561
- title="API compliance"
562
- subtitle="Observed Chat Completions behavior through the rotator. Select up to three models. Tests consume real quota."
563
- >
564
- <div
565
- class="pg-check-models"
566
- role="group"
567
- aria-label="Compliance models"
568
- >
569
- {[...new Set([...models, ...doc.complianceModels])].map(
570
- (model) => (
571
- <label key={model}>
572
- <input
573
- type="checkbox"
574
- checked={doc.complianceModels.includes(model)}
575
- disabled={
576
- running ||
577
- (!doc.complianceModels.includes(model) &&
578
- doc.complianceModels.length >= 3)
579
- }
580
- onChange={(e) =>
581
- updateDocument((d) => ({
582
- ...d,
583
- complianceModels: e.currentTarget.checked
584
- ? [...d.complianceModels, model]
585
- : d.complianceModels.filter((m) => m !== model),
622
+ )}
623
+ <div class="toolbar">
624
+ <Segmented
625
+ class="pg-modes"
626
+ label="Playground mode"
627
+ value={tab}
628
+ options={TABS}
629
+ onChange={(value) => setQuery({ tab: value }, { replace: false })}
630
+ />
631
+ {(running || compare) && (
632
+ <div class="toolbar-right">
633
+ {stopAll}
634
+ {compare && (
635
+ <>
636
+ <Switch
637
+ label="Same parameters for all models"
638
+ checked={doc.sync}
639
+ disabled={running}
640
+ onChange={(on) =>
641
+ updateDocument((d) => ({
642
+ ...d,
643
+ sync: on,
644
+ compare: on
645
+ ? d.compare.map((p) => ({
646
+ ...p,
647
+ params: { ...d.compare[0].params },
586
648
  }))
587
- }
588
- />
589
- {model}
590
- {!models.includes(model) ? " (unavailable)" : ""}
591
- </label>
592
- ),
649
+ : d.compare,
650
+ }))
651
+ }
652
+ />
653
+ {doc.compare.length < 3 && (
654
+ <Button
655
+ size="sm"
656
+ icon="plus"
657
+ disabled={running}
658
+ onClick={() =>
659
+ updateDocument((d) => ({
660
+ ...d,
661
+ compare: [
662
+ ...d.compare,
663
+ {
664
+ ...newPanel(),
665
+ params: d.sync
666
+ ? { ...d.compare[0].params }
667
+ : { ...newPanel().params },
668
+ },
669
+ ],
670
+ }))
671
+ }
672
+ >
673
+ Add model
674
+ </Button>
593
675
  )}
594
- </div>
595
- <div
596
- class="pg-toolbar"
597
- role="group"
598
- aria-label="Compliance cases"
599
- >
600
- {CASES.map((c) => (
601
- <label key={c.id}>
602
- <input
603
- type="checkbox"
604
- disabled={running}
605
- checked={doc.cases.includes(c.id)}
606
- onChange={(e) =>
607
- updateDocument((d) => ({
608
- ...d,
609
- cases: e.currentTarget.checked
610
- ? [...d.cases, c.id]
611
- : d.cases.filter((id) => id !== c.id),
612
- }))
613
- }
614
- />{" "}
615
- {c.label}
616
- </label>
617
- ))}
618
- </div>
619
- <div class="pg-toolbar">
676
+ </>
677
+ )}
678
+ </div>
679
+ )}
680
+ </div>
681
+ {models && !models.length && (
682
+ <div class="panel">
683
+ <EmptyState
684
+ icon="models"
685
+ title="No enabled models"
686
+ action={
687
+ <Button icon="refresh" onClick={() => void loadModels()}>
688
+ Reload models
689
+ </Button>
690
+ }
691
+ >
692
+ Connect a provider and enable models on the Models page, then
693
+ reload the catalog.
694
+ </EmptyState>
695
+ </div>
696
+ )}
697
+ {models === null && !modelError ? (
698
+ <div class="panel">
699
+ <div class="panel-loading">
700
+ <Spinner />
701
+ </div>
702
+ </div>
703
+ ) : tab === "transcription" ? (
704
+ <TranscriptionPage
705
+ key={doc.id}
706
+ state={doc.transcription ?? newTranscription()}
707
+ models={available}
708
+ maxBodyBytes={maxBodyBytes}
709
+ disabled={checking || busy.length > 0}
710
+ onBusyChange={setAudioBusy}
711
+ controllers={controllers.current}
712
+ onChange={(update) =>
713
+ updateDocument(
714
+ (d) => ({
715
+ ...d,
716
+ transcription: update(d.transcription ?? newTranscription()),
717
+ }),
718
+ true,
719
+ )
720
+ }
721
+ />
722
+ ) : tab === "compliance" ? (
723
+ <>
724
+ <Panel
725
+ title="API compliance"
726
+ subtitle="Checks Chat Completions behavior through the rotator. Select up to three models. Uses real quota."
727
+ actions={
728
+ <>
729
+ <span class="sr-only" role="status">
730
+ {progress
731
+ ? `Running ${progress.done} of ${progress.total} tests`
732
+ : finished}
733
+ </span>
620
734
  <Button
621
- variant="primary"
622
- disabled={
623
- running || !doc.complianceModels.length || !doc.cases.length
624
- }
625
- onClick={() => void runCompliance()}
735
+ icon="refresh"
736
+ loading={!!progress?.retry}
737
+ disabled={running || !failedCount}
738
+ onClick={() => void runCompliance(true)}
626
739
  >
627
- Run selected tests
740
+ {progress?.retry ? progressLabel : "Retry failed"}
628
741
  </Button>
629
742
  <Button
630
- disabled={
631
- running ||
632
- !doc.results.some(
633
- (r) => r.verdict === "failed" || r.verdict === "error",
634
- )
635
- }
636
- onClick={() => void runCompliance(true)}
743
+ variant="primary"
744
+ icon="play"
745
+ loading={!!progress && !progress.retry}
746
+ disabled={running || !testCount}
747
+ onClick={() => void runCompliance()}
637
748
  >
638
- Retry failed tests
749
+ {progress && !progress.retry
750
+ ? progressLabel
751
+ : testCount
752
+ ? `Run ${testCount} ${testCount === 1 ? "test" : "tests"}`
753
+ : "Run tests"}
639
754
  </Button>
640
- {checking && (
641
- <span role="status">
642
- <Spinner /> {doc.results.length} results
755
+ </>
756
+ }
757
+ >
758
+ <div class="form pg-picker">
759
+ <div class="field">
760
+ <div class="field-label-row">
761
+ <span class="field-label">Models</span>
762
+ <span class="muted">
763
+ {selectedCount} of {MAX_COMPLIANCE_MODELS} selected
643
764
  </span>
644
- )}
645
- </div>
646
- </Panel>
647
- <div class="pg-results">
648
- {doc.results.map((row, i) => (
649
- <Panel
650
- key={i}
651
- title={`${row.model} · ${CASES.find((c) => c.id === row.caseId)?.label}`}
652
- actions={
653
- <Pill
654
- tone={
655
- row.verdict === "passed"
656
- ? "ok"
657
- : row.verdict === "failed" || row.verdict === "error"
658
- ? "bad"
659
- : "warn"
765
+ <span class="spacer" />
766
+ {doc.complianceModels.length > 0 && !running && (
767
+ <button
768
+ type="button"
769
+ class="link-button"
770
+ onClick={() =>
771
+ updateDocument((d) => ({ ...d, complianceModels: [] }))
660
772
  }
661
773
  >
662
- {VERDICT_LABELS[row.verdict]}
663
- </Pill>
664
- }
774
+ Clear
775
+ </button>
776
+ )}
777
+ </div>
778
+ <div
779
+ class="model-groups"
780
+ role="group"
781
+ aria-label="Compliance models"
665
782
  >
666
- <p>{masker.value.text(row.explanation)}</p>
667
- <TurnView turn={row.turn} />
668
- </Panel>
669
- ))}
670
- </div>
671
- </>
672
- ) : (
673
- <>
674
- {tab === "compare" && (
675
- <div class="pg-toolbar">
676
- <label>
677
- <input
678
- type="checkbox"
679
- checked={doc.sync}
680
- disabled={running}
681
- onChange={(e) =>
682
- updateDocument((d) => ({
683
- ...d,
684
- sync: e.currentTarget.checked,
685
- compare: e.currentTarget.checked
686
- ? d.compare.map((p) => ({
687
- ...p,
688
- params: { ...d.compare[0].params },
689
- }))
690
- : d.compare,
691
- }))
692
- }
693
- />{" "}
694
- Sync settings across models
695
- </label>
696
- <Button
697
- size="sm"
698
- disabled={running || doc.compare.length >= 3}
699
- onClick={() =>
700
- updateDocument((d) => ({
701
- ...d,
702
- compare: [
703
- ...d.compare,
704
- {
705
- ...newPanel(),
706
- params: d.sync
707
- ? { ...d.compare[0].params }
708
- : { ...newPanel().params },
709
- },
710
- ],
711
- }))
712
- }
783
+ <div class="model-grid">
784
+ {[...new Set([...available, ...doc.complianceModels])].map(
785
+ (model) => {
786
+ const checked = doc.complianceModels.includes(model);
787
+ const audioOnly = isAudioOnlyModel(model);
788
+ return (
789
+ <label key={model} class="checkbox model-option">
790
+ <input
791
+ type="checkbox"
792
+ checked={checked}
793
+ disabled={
794
+ running ||
795
+ (!checked &&
796
+ (audioOnly ||
797
+ selectedCount >= MAX_COMPLIANCE_MODELS))
798
+ }
799
+ onChange={(e) =>
800
+ updateDocument((d) => ({
801
+ ...d,
802
+ complianceModels: e.currentTarget.checked
803
+ ? [...d.complianceModels, model]
804
+ : d.complianceModels.filter(
805
+ (m) => m !== model,
806
+ ),
807
+ }))
808
+ }
809
+ />
810
+ <span class="truncate" title={model}>
811
+ {model}
812
+ </span>
813
+ {!available.includes(model) ? (
814
+ <Pill tone="warn" dot={false}>
815
+ Unavailable
816
+ </Pill>
817
+ ) : (
818
+ audioOnly && (
819
+ <Pill tone="muted" dot={false}>
820
+ Audio only
821
+ </Pill>
822
+ )
823
+ )}
824
+ </label>
825
+ );
826
+ },
827
+ )}
828
+ </div>
829
+ </div>
830
+ </div>
831
+ <div class="field">
832
+ <div class="field-label-row">
833
+ <span class="field-label">Tests</span>
834
+ </div>
835
+ <div
836
+ class="model-groups"
837
+ role="group"
838
+ aria-label="Compliance tests"
713
839
  >
714
- Add model
715
- </Button>
840
+ <div class="model-grid">
841
+ {CASES.map((c) => (
842
+ <label key={c.id} class="checkbox model-option">
843
+ <input
844
+ type="checkbox"
845
+ disabled={running}
846
+ checked={doc.cases.includes(c.id)}
847
+ onChange={(e) =>
848
+ updateDocument((d) => ({
849
+ ...d,
850
+ cases: e.currentTarget.checked
851
+ ? [...d.cases, c.id]
852
+ : d.cases.filter((id) => id !== c.id),
853
+ }))
854
+ }
855
+ />
856
+ <span class="truncate" title={c.label}>
857
+ {c.label}
858
+ </span>
859
+ </label>
860
+ ))}
861
+ </div>
862
+ </div>
716
863
  </div>
717
- )}
718
- <div class={`pg-panels pg-panels-${panels.length}`}>
719
- {panels.map((panel) => (
720
- <Panel
864
+ </div>
865
+ </Panel>
866
+ <Panel title="Results" flush>
867
+ <ComplianceResults results={doc.results} running={checking} />
868
+ </Panel>
869
+ </>
870
+ ) : (
871
+ <>
872
+ {compare ? (
873
+ <div class={`pg-compare pg-compare-${doc.compare.length}`}>
874
+ {doc.compare.map((panel, i) => (
875
+ <ConversationPanel
721
876
  key={panel.id}
722
- title={
723
- tab === "chat"
724
- ? "Conversation"
725
- : `Model ${panels.indexOf(panel) + 1}`
877
+ panel={panel}
878
+ label={`Model ${i + 1}`}
879
+ compare
880
+ models={available}
881
+ busy={busy.includes(panel.id)}
882
+ running={running}
883
+ onModel={(model) =>
884
+ patchPanel(panel.id, (p) => ({ ...p, model, turns: [] }))
726
885
  }
727
- actions={
728
- tab === "compare" && doc.compare.length > 2 ? (
729
- <Button
730
- size="sm"
731
- disabled={running}
732
- onClick={() =>
886
+ onParams={(patch) => changeParams(panel.id, patch)}
887
+ onRetry={() => void send(panel)}
888
+ onClear={() =>
889
+ patchPanel(panel.id, (p) => ({ ...p, turns: [] }))
890
+ }
891
+ onRemove={
892
+ doc.compare.length > 2
893
+ ? () => {
733
894
  updateDocument((d) => ({
734
895
  ...d,
735
896
  compare: d.compare.filter((p) => p.id !== panel.id),
736
- }))
897
+ }));
898
+ // The removed column took focus with it; move to
899
+ // the model select of the column now in its place.
900
+ requestAnimationFrame(() => {
901
+ const selects = document.querySelectorAll<HTMLElement>(
902
+ ".pg-compare .pg-model select",
903
+ );
904
+ selects[Math.min(i, selects.length - 1)]?.focus();
905
+ });
737
906
  }
738
- >
739
- Remove
740
- </Button>
741
- ) : undefined
907
+ : undefined
742
908
  }
743
- >
744
- <label class="field">
745
- <span class="field-label">Model</span>
746
- <select
747
- class="input"
748
- aria-label="Model"
749
- disabled={running}
750
- value={panel.model}
751
- onChange={(e) =>
752
- patchPanel(panel.id, (p) => ({
753
- ...p,
754
- model: e.currentTarget.value,
755
- turns: [],
756
- }))
757
- }
758
- >
759
- <option value="">Choose a model</option>
760
- {panel.model && !models.includes(panel.model) && (
761
- <option value={panel.model}>
762
- {panel.model} (unavailable)
763
- </option>
764
- )}
765
- {models.map((model) => (
766
- <option value={model} key={model}>
767
- {model}
768
- </option>
769
- ))}
770
- </select>
771
- </label>
772
- <ParameterEditor
773
- params={panel.params}
774
- disabled={running}
775
- onChange={(patch) => changeParams(panel.id, patch)}
776
- />
777
- <div
778
- class="pg-turns"
779
- aria-live="polite"
780
- aria-busy={busy.includes(panel.id)}
781
- >
782
- {panel.turns.length ? (
783
- panel.turns.map((turn, i) => (
784
- <TurnView key={i} turn={turn} />
785
- ))
786
- ) : (
787
- <p class="muted">Send a message to start testing.</p>
788
- )}
789
- </div>
790
- <div class="pg-toolbar">
791
- {busy.includes(panel.id) ? (
792
- <Button
793
- variant="danger"
794
- size="sm"
795
- onClick={() =>
796
- controllers.current.get(panel.id)?.abort()
797
- }
798
- >
799
- Stop
800
- </Button>
801
- ) : (
802
- <Button
803
- size="sm"
804
- disabled={running || !panel.turns.length}
805
- onClick={() => void send(panel)}
806
- >
807
- Retry last turn
808
- </Button>
809
- )}
810
- <Button
811
- size="sm"
812
- disabled={running || !panel.turns.length}
813
- onClick={() =>
814
- patchPanel(panel.id, (p) => ({ ...p, turns: [] }))
815
- }
816
- >
817
- Clear conversation
818
- </Button>
819
- </div>
820
- </Panel>
909
+ onStop={() => controllers.current.get(panel.id)?.abort()}
910
+ />
821
911
  ))}
822
912
  </div>
823
- <form
824
- class="pg-composer"
825
- onSubmit={(e) => {
826
- e.preventDefault();
827
- if (!running) void send();
828
- }}
829
- >
830
- <label class="field">
831
- <span class="field-label">
832
- Message {tab === "compare" && "to all models"}
833
- </span>
834
- <textarea
835
- class="input"
836
- rows={3}
837
- value={doc.draft}
838
- disabled={running}
839
- placeholder="Ask a question or attach an image…"
840
- onInput={(e) =>
841
- updateDocument((d) => ({
842
- ...d,
843
- draft: e.currentTarget.value,
844
- }))
845
- }
846
- />
847
- </label>
913
+ ) : (
914
+ <ConversationPanel
915
+ key={doc.chat.id}
916
+ panel={doc.chat}
917
+ label="Model"
918
+ compare={false}
919
+ models={available}
920
+ busy={busy.includes(doc.chat.id)}
921
+ running={running}
922
+ onModel={(model) =>
923
+ patchPanel(doc.chat.id, (p) => ({ ...p, model, turns: [] }))
924
+ }
925
+ onParams={(patch) => changeParams(doc.chat.id, patch)}
926
+ onRetry={() => void send(doc.chat)}
927
+ onClear={() =>
928
+ patchPanel(doc.chat.id, (p) => ({ ...p, turns: [] }))
929
+ }
930
+ onStop={() => controllers.current.get(doc.chat.id)?.abort()}
931
+ />
932
+ )}
933
+ <form
934
+ class="panel pg-composer"
935
+ onSubmit={(e) => {
936
+ e.preventDefault();
937
+ if (!running) void send();
938
+ }}
939
+ >
940
+ <div class="panel-body">
941
+ <textarea
942
+ class="input"
943
+ rows={3}
944
+ aria-label={compare ? "Message all models" : "Message"}
945
+ placeholder={
946
+ compare
947
+ ? "Message all models…"
948
+ : "Ask a question or attach an image…"
949
+ }
950
+ value={doc.draft}
951
+ disabled={running}
952
+ onInput={(e) =>
953
+ updateDocument((d) => ({
954
+ ...d,
955
+ draft: e.currentTarget.value,
956
+ }))
957
+ }
958
+ />
848
959
  {!!doc.images.length && (
849
- <div class="pg-images">
960
+ <div class="pg-attachments">
850
961
  {doc.images.map((image, i) => (
851
- <div key={i}>
852
- {!masked.value && (
962
+ <div key={i} class="pg-attachment">
963
+ {masked.value ? (
964
+ <Icon name="image" size={20} />
965
+ ) : (
853
966
  <img src={image.url} alt={image.name} />
854
967
  )}
855
968
  <Button
969
+ variant="ghost"
856
970
  size="sm"
971
+ icon="x"
972
+ iconOnly
857
973
  disabled={running}
858
974
  onClick={() =>
859
975
  updateDocument((d) => ({
@@ -862,15 +978,16 @@ export function PlaygroundPage(): JSX.Element {
862
978
  }))
863
979
  }
864
980
  >
865
- Remove {masked.value ? "image" : image.name}
981
+ {`Remove ${masked.value ? "image" : image.name}`}
866
982
  </Button>
867
983
  </div>
868
984
  ))}
869
985
  </div>
870
986
  )}
871
- <div class="pg-toolbar">
987
+ <div class="pg-composer-foot">
872
988
  <Button
873
- icon="plus"
989
+ icon="image"
990
+ title="Requires a vision model"
874
991
  disabled={running}
875
992
  onClick={() => imageRef.current?.click()}
876
993
  >
@@ -895,26 +1012,210 @@ export function PlaygroundPage(): JSX.Element {
895
1012
  type="submit"
896
1013
  disabled={
897
1014
  running ||
898
- !models.length ||
1015
+ !available.length ||
899
1016
  (!doc.draft.trim() && !doc.images.length)
900
1017
  }
901
1018
  >
902
- Send {tab === "compare" ? "to all" : "message"}
1019
+ {compare ? "Send to all" : "Send"}
903
1020
  </Button>
904
1021
  </div>
905
- <p class="field-hint">
906
- Tools are displayed without executing them. Start a new
907
- conversation after inspecting tool calls. Images require a model
908
- with vision support.
909
- </p>
910
- </form>
911
- </>
1022
+ </div>
1023
+ </form>
1024
+ </>
1025
+ )}
1026
+ </>
1027
+ );
1028
+ }
1029
+
1030
+ /** Chat's "Conversation" panel and each Compare column. */
1031
+ function ConversationPanel({
1032
+ panel,
1033
+ label,
1034
+ compare,
1035
+ models,
1036
+ busy,
1037
+ running,
1038
+ onModel,
1039
+ onParams,
1040
+ onRetry,
1041
+ onClear,
1042
+ onRemove,
1043
+ onStop,
1044
+ }: {
1045
+ panel: PlaygroundPanel;
1046
+ /** Accessible name of the model select ("Model", "Model 1", …). */
1047
+ label: string;
1048
+ compare: boolean;
1049
+ models: string[];
1050
+ busy: boolean;
1051
+ running: boolean;
1052
+ onModel: (model: string) => void;
1053
+ onParams: (patch: Partial<Parameters>) => void;
1054
+ onRetry: () => void;
1055
+ onClear: () => void;
1056
+ onRemove?: () => void;
1057
+ onStop: () => void;
1058
+ }): JSX.Element {
1059
+ const [paramsOpen, setParamsOpen] = useState(false);
1060
+ const turnsRef = useRef<HTMLDivElement>(null);
1061
+ const paramsId = `pg-params-${panel.id}`;
1062
+ const tags = parameterTags(panel.params);
1063
+ const idle = running || !panel.turns.length;
1064
+ const items: MenuItem[] = [
1065
+ {
1066
+ label: "Retry last turn",
1067
+ icon: "refresh",
1068
+ disabled: idle,
1069
+ onSelect: onRetry,
1070
+ },
1071
+ { label: "Clear conversation", icon: "x", disabled: idle, onSelect: onClear },
1072
+ ];
1073
+ if (onRemove)
1074
+ items.push("separator", {
1075
+ label: "Remove model",
1076
+ icon: "trash",
1077
+ danger: true,
1078
+ disabled: running,
1079
+ onSelect: onRemove,
1080
+ });
1081
+ const actions = (
1082
+ <>
1083
+ <label class="pg-model">
1084
+ <span class="sr-only">{label}</span>
1085
+ <select
1086
+ class="select"
1087
+ title={panel.model || "Choose a model"}
1088
+ disabled={running}
1089
+ value={panel.model}
1090
+ onChange={(e) => onModel(e.currentTarget.value)}
1091
+ >
1092
+ <option value="">Choose a model</option>
1093
+ {panel.model && !models.includes(panel.model) && (
1094
+ <option value={panel.model}>{panel.model} (unavailable)</option>
1095
+ )}
1096
+ {models.map((model) => (
1097
+ <option value={model} key={model}>
1098
+ {model}
1099
+ </option>
1100
+ ))}
1101
+ </select>
1102
+ </label>
1103
+ {compare && busy && (
1104
+ <Button
1105
+ size="sm"
1106
+ icon="stop"
1107
+ class="pg-collapsible"
1108
+ title={`Stop ${label}`}
1109
+ aria-label={`Stop ${label}`}
1110
+ onClick={onStop}
1111
+ >
1112
+ Stop
1113
+ </Button>
1114
+ )}
1115
+ <Button
1116
+ variant="ghost"
1117
+ size="sm"
1118
+ icon="settings"
1119
+ class="pg-collapsible"
1120
+ title="Parameters"
1121
+ aria-label={compare ? `${label} parameters` : undefined}
1122
+ aria-expanded={paramsOpen}
1123
+ aria-controls={paramsOpen ? paramsId : undefined}
1124
+ onClick={() => setParamsOpen(!paramsOpen)}
1125
+ >
1126
+ Parameters
1127
+ </Button>
1128
+ <Menu
1129
+ label={compare ? `${label} actions` : "Conversation actions"}
1130
+ items={items}
1131
+ disabled={
1132
+ !items.some(
1133
+ (item) =>
1134
+ typeof item === "object" && "onSelect" in item && !item.disabled,
1135
+ )
1136
+ }
1137
+ />
1138
+ </>
1139
+ );
1140
+ return (
1141
+ <Panel
1142
+ class="pg-panel"
1143
+ title={compare ? undefined : "Conversation"}
1144
+ actions={actions}
1145
+ >
1146
+ {tags.length > 0 && (
1147
+ <span class="tag-row">
1148
+ {tags.map((tag) => (
1149
+ <Tag key={tag}>{tag}</Tag>
1150
+ ))}
1151
+ </span>
1152
+ )}
1153
+ {paramsOpen && (
1154
+ <div id={paramsId} class="pg-params">
1155
+ <ParameterEditor
1156
+ params={panel.params}
1157
+ disabled={running}
1158
+ onChange={onParams}
1159
+ />
1160
+ </div>
1161
+ )}
1162
+ <div
1163
+ ref={turnsRef}
1164
+ class="pg-turns"
1165
+ tabIndex={-1}
1166
+ aria-live="polite"
1167
+ aria-busy={busy}
1168
+ >
1169
+ {panel.turns.length ? (
1170
+ panel.turns.map((turn, i) => (
1171
+ <TurnView
1172
+ key={i}
1173
+ turn={turn}
1174
+ detailsLabel={
1175
+ compare
1176
+ ? `${label}, turn ${i + 1} details`
1177
+ : `Turn ${i + 1} details`
1178
+ }
1179
+ onRetry={
1180
+ i === panel.turns.length - 1 && !busy
1181
+ ? () => {
1182
+ // The callout holding Retry is replaced by the new
1183
+ // turn; keep focus in this conversation.
1184
+ turnsRef.current?.focus({ preventScroll: true });
1185
+ onRetry();
1186
+ }
1187
+ : undefined
1188
+ }
1189
+ running={running}
1190
+ />
1191
+ ))
1192
+ ) : (
1193
+ <EmptyState icon="play" title="No messages yet">
1194
+ Send a message to test this model.
1195
+ </EmptyState>
912
1196
  )}
913
1197
  </div>
914
- </>
1198
+ </Panel>
915
1199
  );
916
1200
  }
917
1201
 
1202
+ /** Parameters that differ from a new panel, shown as tags in the panel body. */
1203
+ function parameterTags(params: Parameters): string[] {
1204
+ const tags: string[] = [];
1205
+ if (params.system.trim()) tags.push("System prompt");
1206
+ if (params.temperature !== DEFAULT_PARAMETERS.temperature)
1207
+ tags.push(`Temperature ${params.temperature}`);
1208
+ if (params.maxTokens !== DEFAULT_PARAMETERS.maxTokens)
1209
+ tags.push(
1210
+ params.maxTokens ? `Max tokens ${params.maxTokens}` : "No max tokens",
1211
+ );
1212
+ if (params.effort) tags.push(`Reasoning ${params.effort}`);
1213
+ if (params.tools.trim()) tags.push("Tools");
1214
+ if (params.stream !== DEFAULT_PARAMETERS.stream)
1215
+ tags.push(params.stream ? "Streaming" : "Streaming off");
1216
+ return tags;
1217
+ }
1218
+
918
1219
  function ParameterEditor({
919
1220
  params,
920
1221
  disabled,
@@ -924,51 +1225,53 @@ function ParameterEditor({
924
1225
  disabled: boolean;
925
1226
  onChange: (patch: Partial<Parameters>) => void;
926
1227
  }): JSX.Element {
1228
+ const id = useId();
927
1229
  return (
928
- <details class="pg-parameters">
929
- <summary>Parameters & system prompt</summary>
930
- <fieldset disabled={disabled} class="form">
1230
+ <div class="form">
1231
+ <label class="field">
1232
+ <span class="field-label">System prompt</span>
1233
+ <textarea
1234
+ class="input"
1235
+ rows={3}
1236
+ placeholder="Optional instructions sent before every message"
1237
+ disabled={disabled}
1238
+ value={params.system}
1239
+ onInput={(e) => onChange({ system: e.currentTarget.value })}
1240
+ />
1241
+ </label>
1242
+ <div class="form-grid">
931
1243
  <label class="field">
932
- <span class="field-label">System prompt</span>
933
- <textarea
1244
+ <span class="field-label">Temperature</span>
1245
+ <input
934
1246
  class="input"
935
- rows={3}
936
- value={params.system}
937
- onInput={(e) => onChange({ system: e.currentTarget.value })}
1247
+ type="number"
1248
+ min="0"
1249
+ max="2"
1250
+ step="0.1"
1251
+ placeholder="Provider default"
1252
+ disabled={disabled}
1253
+ value={params.temperature}
1254
+ onInput={(e) => onChange({ temperature: e.currentTarget.value })}
1255
+ />
1256
+ </label>
1257
+ <label class="field">
1258
+ <span class="field-label">Max tokens</span>
1259
+ <input
1260
+ class="input"
1261
+ type="number"
1262
+ min="1"
1263
+ step="1"
1264
+ placeholder="Provider default"
1265
+ disabled={disabled}
1266
+ value={params.maxTokens}
1267
+ onInput={(e) => onChange({ maxTokens: e.currentTarget.value })}
938
1268
  />
939
1269
  </label>
940
- <div class="form-grid">
941
- <label class="field">
942
- <span class="field-label">Temperature</span>
943
- <input
944
- class="input"
945
- type="number"
946
- min="0"
947
- max="2"
948
- step="0.1"
949
- placeholder="Provider default"
950
- value={params.temperature}
951
- onInput={(e) => onChange({ temperature: e.currentTarget.value })}
952
- />
953
- </label>
954
- <label class="field">
955
- <span class="field-label">Max tokens</span>
956
- <input
957
- class="input"
958
- type="number"
959
- min="1"
960
- step="1"
961
- placeholder="Provider default"
962
- value={params.maxTokens}
963
- onInput={(e) => onChange({ maxTokens: e.currentTarget.value })}
964
- />
965
- </label>
966
- </div>
967
1270
  <label class="field">
968
1271
  <span class="field-label">Reasoning effort</span>
969
1272
  <select
970
- class="input"
971
- aria-label="Reasoning effort"
1273
+ class="select"
1274
+ disabled={disabled}
972
1275
  value={params.effort}
973
1276
  onChange={(e) => onChange({ effort: e.currentTarget.value })}
974
1277
  >
@@ -980,35 +1283,51 @@ function ParameterEditor({
980
1283
  ))}
981
1284
  </select>
982
1285
  </label>
983
- <label>
984
- <input
985
- type="checkbox"
986
- checked={params.stream}
987
- onChange={(e) => onChange({ stream: e.currentTarget.checked })}
988
- />{" "}
989
- Stream response
990
- </label>
991
- <label class="field">
992
- <span class="field-label">Tools JSON (optional)</span>
993
- <textarea
994
- class="input pg-code"
995
- rows={4}
996
- spellcheck={false}
997
- placeholder='[{"type":"function","function":{"name":"example","parameters":{"type":"object"}}}]'
998
- value={params.tools}
999
- onInput={(e) => onChange({ tools: e.currentTarget.value })}
1000
- />
1286
+ </div>
1287
+ <div class="field">
1288
+ <label class="field-label" for={`${id}-tools`}>
1289
+ Tools JSON (optional)
1001
1290
  </label>
1002
- <p class="field-hint">
1003
- Parameters are sent as entered. Support depends on the model and
1004
- adapter.
1005
- </p>
1006
- </fieldset>
1007
- </details>
1291
+ <textarea
1292
+ id={`${id}-tools`}
1293
+ class="code-input"
1294
+ rows={4}
1295
+ spellcheck={false}
1296
+ aria-describedby={`${id}-tools-hint`}
1297
+ placeholder='[{"type":"function","function":{"name":"example","parameters":{"type":"object"}}}]'
1298
+ disabled={disabled}
1299
+ value={params.tools}
1300
+ onInput={(e) => onChange({ tools: e.currentTarget.value })}
1301
+ />
1302
+ <span class="field-hint" id={`${id}-tools-hint`}>
1303
+ Sent as entered; support depends on the model. Tool calls are shown,
1304
+ not executed.
1305
+ </span>
1306
+ </div>
1307
+ <Switch
1308
+ label="Stream response"
1309
+ checked={params.stream}
1310
+ disabled={disabled}
1311
+ onChange={(on) => onChange({ stream: on })}
1312
+ />
1313
+ </div>
1008
1314
  );
1009
1315
  }
1010
1316
 
1011
- function TurnView({ turn }: { turn: Turn }): JSX.Element {
1317
+ function TurnView({
1318
+ turn,
1319
+ detailsLabel,
1320
+ onRetry,
1321
+ running,
1322
+ }: {
1323
+ turn: Turn;
1324
+ /** Accessible name of the Details toggle ("Turn 2 details", …). */
1325
+ detailsLabel: string;
1326
+ /** Offered on a failed last turn. */
1327
+ onRetry?: () => void;
1328
+ running: boolean;
1329
+ }): JSX.Element {
1330
+ const [open, setOpen] = useState(false);
1012
1331
  const result = turn.result;
1013
1332
  const lastMessage = turn.request.messages.at(-1)?.content;
1014
1333
  const m = masker.value;
@@ -1016,96 +1335,358 @@ function TurnView({ turn }: { turn: Turn }): JSX.Element {
1016
1335
  typeof lastMessage === "string"
1017
1336
  ? [{ type: "text" as const, text: lastMessage }]
1018
1337
  : (lastMessage ?? []);
1338
+ const images = content.flatMap((part) =>
1339
+ part.type === "image_url" ? [part.image_url.url] : [],
1340
+ );
1019
1341
  return (
1020
1342
  <article class="pg-turn">
1021
1343
  <div class="pg-user">
1022
- <strong>You</strong>
1023
- {content.map((part, i) =>
1024
- part.type === "text" ? (
1025
- <p key={i}>{m.text(part.text)}</p>
1026
- ) : masked.value ? (
1027
- <p key={i}>[Image hidden]</p>
1028
- ) : (
1029
- <img key={i} src={part.image_url.url} alt="Attached image" />
1030
- ),
1344
+ <span class="field-label">You</span>
1345
+ {content.map(
1346
+ (part, i) =>
1347
+ part.type === "text" && (
1348
+ <p key={i} class="pg-message">
1349
+ {m.text(part.text)}
1350
+ </p>
1351
+ ),
1352
+ )}
1353
+ {!!images.length && (
1354
+ <div class="pg-attachments">
1355
+ {images.map((url, i) => (
1356
+ <div key={i} class="pg-attachment">
1357
+ {masked.value ? (
1358
+ <>
1359
+ <Icon name="image" size={20} />
1360
+ <span class="sr-only">Image hidden</span>
1361
+ </>
1362
+ ) : (
1363
+ <img src={url} alt="Attached image" />
1364
+ )}
1365
+ </div>
1366
+ ))}
1367
+ </div>
1031
1368
  )}
1032
1369
  </div>
1033
1370
  <div class="pg-assistant">
1034
- <strong>Assistant</strong>
1371
+ <span class="field-label">Assistant</span>
1372
+ {result?.reasoning && (
1373
+ <div
1374
+ class="pg-reasoning"
1375
+ tabIndex={0}
1376
+ role="region"
1377
+ aria-label="Reasoning"
1378
+ >
1379
+ {m.text(result.reasoning)}
1380
+ </div>
1381
+ )}
1035
1382
  {result?.content ? (
1036
- <pre class="pg-answer">{m.text(result.content)}</pre>
1383
+ <p class="pg-message">{m.text(result.content)}</p>
1037
1384
  ) : (
1038
1385
  !turn.error &&
1039
1386
  !result?.tools.length && (
1040
- <p class="muted">
1387
+ <p class="pg-message muted">
1041
1388
  {result?.done ? "Empty response." : "Waiting for response…"}
1042
1389
  </p>
1043
1390
  )
1044
1391
  )}
1045
- {result?.reasoning && (
1046
- <details>
1047
- <summary>Reasoning</summary>
1048
- <pre class="pg-answer">{m.text(result.reasoning)}</pre>
1049
- </details>
1050
- )}
1051
1392
  {!!result?.tools.length && (
1052
- <details open>
1053
- <summary>Tool calls (not executed)</summary>
1054
- <pre class="pg-code">
1393
+ <>
1394
+ <span class="field-label">Tool calls (not executed)</span>
1395
+ <pre class="code">
1055
1396
  {m.text(JSON.stringify(result.tools, null, 2))}
1056
1397
  </pre>
1057
- </details>
1398
+ </>
1058
1399
  )}
1059
1400
  {turn.error && (
1060
- <p class="form-error" role="alert">
1061
- {m.text(turn.error)}
1062
- </p>
1063
- )}
1064
- {result && (
1065
- <div class="pg-metrics">
1066
- <span>Total: {formatMs(result.durationMs)}</span>
1067
- <span>
1068
- First content:{" "}
1069
- {result.firstContentMs === null
1070
- ? "Not available"
1071
- : formatMs(result.firstContentMs)}
1072
- </span>
1073
- <span>
1074
- Tokens in/out: {result.inputTokens ?? "N/A"} /{" "}
1075
- {result.outputTokens ?? "N/A"}
1076
- </span>
1077
- {result.finishReason && <span>Finish: {result.finishReason}</span>}
1078
- {result.metadata["x-rotator-cost-usd"] && (
1079
- <span>
1080
- Estimated list price: ${result.metadata["x-rotator-cost-usd"]}
1081
- </span>
1082
- )}
1401
+ <div class="callout tone-bad" role="alert">
1402
+ <Icon name="critical" size={16} />
1403
+ <div>
1404
+ <strong>
1405
+ {turn.error === CANCELLED_MESSAGE
1406
+ ? "Request stopped"
1407
+ : "Request failed"}
1408
+ </strong>
1409
+ <p>{m.text(turn.error)}</p>
1410
+ {onRetry && (
1411
+ <Button
1412
+ size="sm"
1413
+ icon="refresh"
1414
+ disabled={running}
1415
+ onClick={onRetry}
1416
+ >
1417
+ Retry
1418
+ </Button>
1419
+ )}
1420
+ </div>
1083
1421
  </div>
1084
1422
  )}
1085
- <details class="pg-inspect">
1086
- <summary>Request, response & routing</summary>
1087
- {masked.value ? (
1088
- <p class="muted">
1089
- Raw details hidden while the privacy mask is on.
1090
- </p>
1091
- ) : (
1092
- <pre class="pg-code">
1093
- {JSON.stringify(
1094
- {
1095
- request: turn.request,
1096
- response: result?.raw,
1097
- routing: result?.metadata,
1098
- },
1099
- (_, value: unknown) =>
1100
- typeof value === "string" && value.startsWith("data:image/")
1101
- ? `${value.slice(0, 45)}… [image data omitted from preview]`
1102
- : value,
1103
- 2,
1104
- )}
1105
- </pre>
1106
- )}
1107
- </details>
1423
+ <div class="pg-turn-foot">
1424
+ {result && <Metrics result={result} class="pg-metrics" />}
1425
+ <Button
1426
+ variant="ghost"
1427
+ size="sm"
1428
+ icon={open ? "chevronDown" : "chevronRight"}
1429
+ aria-label={detailsLabel}
1430
+ aria-expanded={open}
1431
+ onClick={() => setOpen(!open)}
1432
+ >
1433
+ Details
1434
+ </Button>
1435
+ </div>
1436
+ {open && <TurnInspector turn={turn} />}
1108
1437
  </div>
1109
1438
  </article>
1110
1439
  );
1111
1440
  }
1441
+
1442
+ function Metrics({
1443
+ result,
1444
+ class: className,
1445
+ }: {
1446
+ result: ChatResult;
1447
+ class?: string;
1448
+ }): JSX.Element {
1449
+ const cost = Number(result.metadata["x-rotator-cost-usd"] ?? NaN);
1450
+ return (
1451
+ <div class={`inspector-meta${className ? ` ${className}` : ""}`}>
1452
+ <span>Total {duration(result.durationMs)}</span>
1453
+ <span>First content {duration(result.firstContentMs)}</span>
1454
+ <span>
1455
+ Tokens {result.inputTokens ?? "—"} / {result.outputTokens ?? "—"}
1456
+ </span>
1457
+ <span>Finish {result.finishReason ?? "—"}</span>
1458
+ <span>
1459
+ List-price value {Number.isFinite(cost) ? formatUsd(cost) : "—"}
1460
+ </span>
1461
+ </div>
1462
+ );
1463
+ }
1464
+
1465
+ const INSPECTOR_TABS = [
1466
+ { value: "request", label: "Request" },
1467
+ { value: "response", label: "Response" },
1468
+ { value: "routing", label: "Routing" },
1469
+ ] as const;
1470
+ type InspectorTab = (typeof INSPECTOR_TABS)[number]["value"];
1471
+
1472
+ /** Inline image data would swamp the preview; keep a recognizable prefix. */
1473
+ const omitImageData = (_: string, value: unknown): unknown =>
1474
+ typeof value === "string" && value.startsWith("data:image/")
1475
+ ? `${value.slice(0, 45)}… [image data omitted from preview]`
1476
+ : value;
1477
+
1478
+ /** Request / Response / Routing payloads, as in the Requests inspector. */
1479
+ function TurnInspector({
1480
+ turn,
1481
+ meta,
1482
+ note,
1483
+ }: {
1484
+ turn: Turn;
1485
+ /** Repeat the turn metrics above the tabs (table rows have no room). */
1486
+ meta?: boolean;
1487
+ /** A line above everything else, such as a compliance explanation. */
1488
+ note?: string;
1489
+ }): JSX.Element {
1490
+ const [tab, setTab] = useState<InspectorTab>("request");
1491
+ const result = turn.result;
1492
+ const metrics = (
1493
+ <>
1494
+ {note && <p>{note}</p>}
1495
+ {meta && result && <Metrics result={result} />}
1496
+ </>
1497
+ );
1498
+ // The turn list is a polite live region; raw JSON must not be read out
1499
+ // when Details opens or a tab switches.
1500
+ if (masked.value)
1501
+ return (
1502
+ <div class="inspector" aria-live="off">
1503
+ {metrics}
1504
+ <p class="muted">Raw details hidden while the privacy mask is on.</p>
1505
+ </div>
1506
+ );
1507
+ const raw = result?.raw ?? [];
1508
+ const routing = Object.entries(result?.metadata ?? {});
1509
+ const payload =
1510
+ tab === "request"
1511
+ ? turn.request
1512
+ : tab === "response"
1513
+ ? raw.length > 1
1514
+ ? raw
1515
+ : raw[0]
1516
+ : routing.length
1517
+ ? result?.metadata
1518
+ : undefined;
1519
+ const text =
1520
+ payload === undefined ? "" : JSON.stringify(payload, omitImageData, 2);
1521
+ // Copy keeps inline images so a copied request can be replayed as is.
1522
+ const full = payload === undefined ? "" : JSON.stringify(payload, null, 2);
1523
+ return (
1524
+ <div class="inspector" aria-live="off">
1525
+ {metrics}
1526
+ <div class="tabs tabs-sm" role="tablist" aria-label="Turn details">
1527
+ {INSPECTOR_TABS.map((t) => (
1528
+ <button
1529
+ key={t.value}
1530
+ type="button"
1531
+ role="tab"
1532
+ aria-selected={tab === t.value}
1533
+ class={tab === t.value ? "is-active" : undefined}
1534
+ onClick={() => setTab(t.value)}
1535
+ >
1536
+ {t.label}
1537
+ </button>
1538
+ ))}
1539
+ <span class="tabs-spacer" />
1540
+ <Button
1541
+ size="sm"
1542
+ variant="ghost"
1543
+ icon="copy"
1544
+ disabled={!text}
1545
+ onClick={() => void copy(full)}
1546
+ >
1547
+ Copy
1548
+ </Button>
1549
+ </div>
1550
+ {!text ? (
1551
+ <p class="muted">Nothing recorded.</p>
1552
+ ) : tab === "routing" ? (
1553
+ <KeyValue items={routing.map(([key, value]) => [key, value])} />
1554
+ ) : (
1555
+ <pre class="code">{text}</pre>
1556
+ )}
1557
+ </div>
1558
+ );
1559
+ }
1560
+
1561
+ const SUMMARY: Array<[Verdict, string, string]> = [
1562
+ ["passed", "passed", "passed"],
1563
+ ["failed", "failed", "failed"],
1564
+ ["unsupported", "not supported", "not supported"],
1565
+ ["error", "error", "errors"],
1566
+ ["cancelled", "cancelled", "cancelled"],
1567
+ ];
1568
+
1569
+ function ComplianceResults({
1570
+ results,
1571
+ running,
1572
+ }: {
1573
+ results: ComplianceResult[];
1574
+ running: boolean;
1575
+ }): JSX.Element {
1576
+ const [open, setOpen] = useState<string | null>(null);
1577
+ const m = masker.value;
1578
+ if (!results.length)
1579
+ return running ? (
1580
+ <div class="panel-loading">
1581
+ <Spinner />
1582
+ </div>
1583
+ ) : (
1584
+ <EmptyState icon="checkCircle" title="No results yet">
1585
+ Choose models and tests, then run them.
1586
+ </EmptyState>
1587
+ );
1588
+ const counts = new Map<Verdict, number>();
1589
+ for (const r of results)
1590
+ counts.set(r.verdict, (counts.get(r.verdict) ?? 0) + 1);
1591
+ // Parallel runs finish out of order; group by model, then test order.
1592
+ const order = CASES.map((c) => c.id);
1593
+ const rows = results
1594
+ .map((row, index) => ({ row, index }))
1595
+ .sort(
1596
+ (a, b) =>
1597
+ a.row.model.localeCompare(b.row.model) ||
1598
+ order.indexOf(a.row.caseId) - order.indexOf(b.row.caseId) ||
1599
+ a.index - b.index,
1600
+ );
1601
+ return (
1602
+ <>
1603
+ <div class="stats stats-inline">
1604
+ {SUMMARY.map(([verdict, one, many]) => {
1605
+ const count = counts.get(verdict) ?? 0;
1606
+ return (
1607
+ (count > 0 || verdict === "passed") && (
1608
+ <span key={verdict}>
1609
+ <strong class="num">{count}</strong>{" "}
1610
+ {count === 1 ? one : many}
1611
+ </span>
1612
+ )
1613
+ );
1614
+ })}
1615
+ </div>
1616
+ <div class="table-scroll">
1617
+ <table class="table table-compact pg-results">
1618
+ <thead>
1619
+ <tr>
1620
+ <th scope="col">Model</th>
1621
+ <th scope="col">Test</th>
1622
+ <th scope="col">Result</th>
1623
+ <th scope="col" class="num-col hide-sm">
1624
+ Duration
1625
+ </th>
1626
+ <th scope="col">
1627
+ <span class="sr-only">Details</span>
1628
+ </th>
1629
+ </tr>
1630
+ </thead>
1631
+ <tbody>
1632
+ {rows.map(({ row, index }) => {
1633
+ const key = JSON.stringify([row.model, row.caseId]);
1634
+ const expanded = open === key;
1635
+ const toggle = () => setOpen(expanded ? null : key);
1636
+ const explanation = m.text(row.explanation);
1637
+ const testLabel =
1638
+ CASES.find((c) => c.id === row.caseId)?.label ?? row.caseId;
1639
+ return (
1640
+ <Fragment key={`${key}:${index}`}>
1641
+ <tr
1642
+ class={`history-row${expanded ? " is-open" : ""}`}
1643
+ onClick={toggle}
1644
+ >
1645
+ <td>{row.model}</td>
1646
+ <td>{testLabel}</td>
1647
+ <td>
1648
+ <Pill
1649
+ tone={VERDICT_TONES[row.verdict]}
1650
+ title={row.verdict === "passed" ? explanation : undefined}
1651
+ >
1652
+ {VERDICT_LABELS[row.verdict]}
1653
+ </Pill>
1654
+ {row.verdict !== "passed" && explanation && (
1655
+ <div class="cell-sub">{explanation}</div>
1656
+ )}
1657
+ </td>
1658
+ <td class="num num-col hide-sm">
1659
+ {duration(row.turn.result?.durationMs)}
1660
+ </td>
1661
+ <td class="cell-action">
1662
+ <Button
1663
+ size="sm"
1664
+ variant="ghost"
1665
+ iconOnly
1666
+ icon={expanded ? "chevronDown" : "chevronRight"}
1667
+ aria-expanded={expanded}
1668
+ onClick={(event) => {
1669
+ event.stopPropagation();
1670
+ toggle();
1671
+ }}
1672
+ >
1673
+ {`${expanded ? "Hide" : "Show"} details for ${row.model}, ${testLabel}`}
1674
+ </Button>
1675
+ </td>
1676
+ </tr>
1677
+ {expanded && (
1678
+ <tr class="history-detail">
1679
+ <td colSpan={5}>
1680
+ <TurnInspector turn={row.turn} meta note={explanation} />
1681
+ </td>
1682
+ </tr>
1683
+ )}
1684
+ </Fragment>
1685
+ );
1686
+ })}
1687
+ </tbody>
1688
+ </table>
1689
+ </div>
1690
+ </>
1691
+ );
1692
+ }