Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract shared Digital Twin evaluation-suite lifecycle (#2372)

Adam Eivy9bde5d0afcc9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d50873b61a..41f0b4e496 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -32,6 +32,8 @@
## Changed
+- **[issue-2372] The three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn) now share one lifecycle + presentation shell instead of each re-implementing ~315 lines.** The panels had drifted — Values-Alignment loaded its suite/history without the `{ silent: true }` option its siblings use, so a failed load double-toasted. That drift is fixed at the API layer (`getValuesAlignmentTests`/`getValuesAlignmentTestHistory` now accept options) and the shared load path always silences. The duplicated loading, multi-provider parallel run, persona-not-found handling, result expansion, reactive history prepend, and toast fan-out now live in a `useTwinEvaluationSuite` hook plus a `TwinEvaluationSuitePanel` presentation component; each panel is reduced to a small suite descriptor (copy + status semantics + api calls) and its one genuinely-different expanded-detail renderer. Every suite's observable copy and status fields (Aligned/Held/Consistent, score labels, per-run counts) are preserved unchanged. New hook-level behavior tests cover silenced loads, parallel runs, history prepend/cap, and the persona/partial-failure toast branches.
+
- **[issue-2373] The six data-import services now share one streaming-ZIP lifecycle helper instead of each re-implementing it.** browserHistory, spotify, youtube, whatsapp, takeoutLocation, and discord all repeated the same ZIP predicate plus a hand-rolled `createReadStream → parseZip` lifecycle (single-settle guard, source/parser teardown on early failure, autodrain of skipped members, per-entry promise collection, and close/error coordination). That is now centralized in `server/lib/zipStream.js` as `isZipUpload(file)` and `collectZipEntries(path, { match, onMatch, maxBytes? })` — which owns teardown, autodrain, and awaiting every matching entry's work — leaving each importer with only its domain match/parse callbacks. No behavior change; covered by new failure / truncated-archive / corrupt-member regression tests.
- **CoS scheduled tasks get a day-of-week + time-of-day picker — no more typing crontab syntax for weekly schedules.** Every CoS cron surface (Schedule tab overrides and global config, the Workflow/Timeline schedule editor's pinned-time mode, CoS system jobs, and per-app custom tasks) now leads with a row of day pills (S M T W T F S) plus a time input: click the days it should run and set the time, and the cron expression is built for you (no days selected = every day). The raw crontab field and presets are still there behind an "Advanced" toggle for interval/stepped schedules the picker can't represent, and it round-trips — an existing `0 9 * * 1,3` lights up Mon/Wed at 09:00. Built on a shared `WeekdayTimePicker` component and `parseSimpleCron`/`buildWeeklyCron` helpers so all surfaces stay consistent.
diff --git a/client/src/components/digital-twin/tabs/AdversarialBoundaryPanel.jsx b/client/src/components/digital-twin/tabs/AdversarialBoundaryPanel.jsx
index 679edd7674..31b40e10c7 100644
--- a/client/src/components/digital-twin/tabs/AdversarialBoundaryPanel.jsx
+++ b/client/src/components/digital-twin/tabs/AdversarialBoundaryPanel.jsx
@@ -1,316 +1,71 @@
-import { useState, useEffect } from 'react';
-import {
- Play,
- ShieldAlert,
- CheckCircle,
- XCircle,
- AlertCircle,
- Clock,
- ChevronDown,
- ChevronRight,
- History
-} from 'lucide-react';
-import BrailleSpinner from '../../BrailleSpinner';
+import { ShieldAlert } from 'lucide-react';
import * as api from '../../../services/api';
-import toast from '../../ui/Toast';
-
-import PersonaBadge from '../PersonaBadge';
-import { ADVERSARIAL_STATUS, scoreToColor } from '../constants';
-import { timeAgo } from '../../../utils/formatters';
+import { ADVERSARIAL_STATUS } from '../constants';
+import TwinEvaluationSuitePanel, { SuiteModelResponses } from './TwinEvaluationSuitePanel';
/**
* Adversarial Boundary testing (M34 P6). Tries to manipulate the embodied twin
* — authority pressure, flattery, guilt, incremental escalation, harmful
* reframing — into crossing a stated boundary, then grades whether the twin
* held the line. Reuses the provider/model + persona selection from the parent
- * TestTab via props so the three suites share one configuration.
+ * TestTab via props so the three suites share one configuration. Lifecycle +
+ * shared presentation live in `TwinEvaluationSuitePanel`; this file only
+ * declares the Adversarial suite descriptor and its expanded-detail renderer.
*/
-export default function AdversarialBoundaryPanel({ selectedProviders = [], personaId = '', onPersonaNotFound, onRefresh }) {
- const [scenarios, setScenarios] = useState([]);
- const [history, setHistory] = useState([]);
- const [loading, setLoading] = useState(true);
- const [running, setRunning] = useState(false);
- const [results, setResults] = useState([]);
- const [expanded, setExpanded] = useState(null);
-
- useEffect(() => {
- loadData();
- }, []);
-
- const loadData = async () => {
- setLoading(true);
- // These loads own their fallback ([]) so silence the helper's default toast.
- const [scenarioData, historyData] = await Promise.all([
- api.getAdversarialTests({ silent: true }).catch(() => []),
- api.getAdversarialTestHistory(5, { silent: true }).catch(() => [])
- ]);
- setScenarios(scenarioData);
- setHistory(historyData);
- setLoading(false);
- };
-
- const runTests = async () => {
- if (selectedProviders.length === 0) {
- toast.error('Select at least one provider/model above');
- return;
- }
-
- setRunning(true);
- setResults([]);
-
- // These calls own their error UI below (and one path delegates to the
- // parent), so silence the helper's default toast to avoid double-toasting.
- const runResults = await Promise.all(
- selectedProviders.map(({ providerId, model }) =>
- api.runAdversarialTests(providerId, model, null, personaId || null, { silent: true })
- .then(result => ({ providerId, model, ...result }))
- .catch(err => ({ providerId, model, error: err.message, code: err?.code }))
- )
- );
-
- setResults(runResults);
- // The run response already carries each run's history entry — prepend it
- // to the local list instead of refetching (reactive-update convention).
- const fresh = runResults
- .filter(r => !r.error && r.runId)
- .map(({ runId, score, held, total, timestamp, model, personaName }) => ({ runId, score, held, total, timestamp, model, personaName }));
- if (fresh.length) setHistory(prev => [...fresh, ...prev].slice(0, 5));
- setRunning(false);
-
- // A stale/deleted persona is rejected by the same route guard the
- // behavioral runner hits; ask the parent (which owns the picker) to clear
- // it, and show a persona-specific message instead of the generic one.
- if (runResults.some(r => r.code === 'NOT_FOUND')) {
- onPersonaNotFound?.();
- toast.error('That persona no longer exists — switched to the base twin. Try again.');
- } else if (runResults.some(r => r.error)) {
- toast.error('Some runs failed — check provider availability');
- } else {
- toast.success('Adversarial boundary tests completed');
- }
- onRefresh?.();
- };
-
- const getResultIcon = (result) => {
- switch (result) {
- case 'held':
- return <CheckCircle className="w-5 h-5 text-port-success" />;
- case 'breached':
- return <XCircle className="w-5 h-5 text-port-error" />;
- case 'partial':
- return <AlertCircle className="w-5 h-5 text-port-warning" />;
- default:
- return <Clock className="w-5 h-5 text-gray-400" />;
- }
- };
-
- if (loading) {
- return (
- <div className="flex items-center justify-center h-32">
- <BrailleSpinner text="Loading boundary suite" />
+const SUITE = {
+ HeaderIcon: ShieldAlert,
+ title: 'Adversarial Boundary Tests',
+ description: 'Manipulation attempts scored on whether your twin held its boundaries (non-negotiables & error-intolerances).',
+ runLabel: 'Run Scenarios',
+ loadingText: 'Loading boundary suite',
+ itemLabel: 'Scenario',
+ emptyState: (
+ <>
+ No adversarial-boundary suite found. Add an <span className="text-gray-300">ADVERSARIAL_BOUNDARY_SUITE.md</span> to your digital twin folder to enable these tests.
+ </>
+ ),
+ scoreLabel: 'Boundary Score',
+ countField: 'held',
+ historyTitle: 'Recent Boundary Runs',
+ statusMap: ADVERSARIAL_STATUS,
+ passResult: 'held',
+ failResult: 'breached',
+ getTests: api.getAdversarialTests,
+ getHistory: api.getAdversarialTestHistory,
+ runTests: api.runAdversarialTests,
+ successToast: 'Adversarial boundary tests completed'
+};
+
+const renderDetail = (scenario, ctx) => (
+ <div className="space-y-4">
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Manipulation Setup</h4>
+ <p className="text-white bg-port-card p-3 rounded">{scenario.setup}</p>
+ </div>
+ {scenario.boundaryTested?.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {scenario.boundaryTested.map(b => (
+ <span key={b} className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent">
+ {b}
+ </span>
+ ))}
</div>
- );
- }
-
- return (
- <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
- <div className="p-4 border-b border-port-border flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="font-semibold text-white flex items-center gap-2">
- <ShieldAlert className="w-5 h-5 text-port-accent" />
- Adversarial Boundary Tests
- </h3>
- <p className="text-xs text-gray-500 mt-1">
- Manipulation attempts scored on whether your twin held its boundaries (non-negotiables &amp; error-intolerances).
- </p>
- </div>
- <button
- onClick={runTests}
- disabled={running || scenarios.length === 0 || selectedProviders.length === 0}
- className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {running ? (
- <>
- <BrailleSpinner />
- Running...
- </>
- ) : (
- <>
- <Play className="w-4 h-4" />
- Run Scenarios
- </>
- )}
- </button>
+ )}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
+ <div>
+ <div className="text-port-success text-xs mb-1">Held Response</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.heldResponse}</div>
</div>
+ <div>
+ <div className="text-port-error text-xs mb-1">Breached Response</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.breachedResponse}</div>
+ </div>
+ </div>
- {scenarios.length === 0 ? (
- <div className="p-6 text-center text-sm text-gray-400">
- No adversarial-boundary suite found. Add an <span className="text-gray-300">ADVERSARIAL_BOUNDARY_SUITE.md</span> to your digital twin folder to enable these tests.
- </div>
- ) : (
- <>
- {/* Results table */}
- {results.length > 0 && (
- <div className="overflow-x-auto -mx-4 sm:mx-0">
- <table className="w-full min-w-[500px]">
- <thead>
- <tr className="border-b border-port-border">
- <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Scenario</th>
- {results.map(r => (
- <th key={`${r.providerId}-${r.model}`} className="px-4 py-3 text-left text-sm font-medium text-gray-400">
- {r.model}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {scenarios.map(scenario => (
- <tr
- key={scenario.testId}
- className="border-b border-port-border last:border-b-0 hover:bg-port-border/30"
- >
- <td className="px-4 py-3">
- <button
- onClick={() => setExpanded(expanded === scenario.testId ? null : scenario.testId)}
- className="flex items-center gap-2 text-sm text-white text-left"
- >
- {expanded === scenario.testId ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
- {scenario.testId}. {scenario.testName}
- </button>
- </td>
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === scenario.testId);
- return (
- <td key={`${r.providerId}-${r.model}`} className="px-4 py-3">
- {tr ? (
- <div className="flex items-center gap-2">
- {getResultIcon(tr.result)}
- <span className={`text-sm ${ADVERSARIAL_STATUS[tr.result]?.color?.split(' ')[1]}`}>
- {ADVERSARIAL_STATUS[tr.result]?.label}
- </span>
- </div>
- ) : (
- <span className="text-gray-500">—</span>
- )}
- </td>
- );
- })}
- </tr>
- ))}
-
- {/* Summary row */}
- <tr className="bg-port-border/30">
- <td className="px-4 py-3 font-medium text-white">Boundary Score</td>
- {results.map(r => (
- <td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
- {r.error ? (
- <span className="text-sm text-port-error">{r.error}</span>
- ) : (
- <>
- <span className={`text-lg font-bold ${scoreToColor(r.score || 0)}`}>
- {Math.round((r.score || 0) * 100)}%
- </span>
- <span className="text-sm text-gray-500 ml-2">
- ({r.held || 0}/{r.total || 0})
- </span>
- </>
- )}
- </td>
- ))}
- </tr>
- </tbody>
- </table>
- </div>
- )}
-
- {/* Expanded scenario detail */}
- {expanded && (
- <div className="p-4 bg-port-bg border-t border-port-border">
- {(() => {
- const scenario = scenarios.find(s => s.testId === expanded);
- if (!scenario) return null;
- return (
- <div className="space-y-4">
- <div>
- <h4 className="text-sm font-medium text-gray-400 mb-1">Manipulation Setup</h4>
- <p className="text-white bg-port-card p-3 rounded">{scenario.setup}</p>
- </div>
- {scenario.boundaryTested?.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {scenario.boundaryTested.map(b => (
- <span key={b} className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent">
- {b}
- </span>
- ))}
- </div>
- )}
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
- <div>
- <div className="text-port-success text-xs mb-1">Held Response</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.heldResponse}</div>
- </div>
- <div>
- <div className="text-port-error text-xs mb-1">Breached Response</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.breachedResponse}</div>
- </div>
- </div>
-
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === expanded);
- if (!tr) return null;
- return (
- <div key={`${r.providerId}-${r.model}-resp`}>
- <h4 className="text-sm font-medium text-gray-400 mb-1 flex items-center gap-2">
- {r.model} Response {getResultIcon(tr.result)}
- </h4>
- <div className="bg-port-card p-3 rounded">
- <p className="text-white whitespace-pre-wrap">{tr.response}</p>
- {tr.reasoning && (
- <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
- Reasoning: {tr.reasoning}
- </p>
- )}
- </div>
- </div>
- );
- })}
- </div>
- );
- })()}
- </div>
- )}
+ <SuiteModelResponses item={scenario} label="Response" {...ctx} />
+ </div>
+);
- {/* History */}
- {history.length > 0 && (
- <div className="p-4 border-t border-port-border">
- <h4 className="font-semibold text-white mb-3 flex items-center gap-2 text-sm">
- <History size={16} />
- Recent Boundary Runs
- </h4>
- <div className="space-y-2">
- {history.map(run => (
- <div key={run.runId} className="flex items-center justify-between p-3 rounded bg-port-bg">
- <div className="flex items-center gap-4">
- <span className={`text-xl font-bold ${scoreToColor(run.score)}`}>
- {Math.round(run.score * 100)}%
- </span>
- <div>
- <div className="text-sm text-white flex items-center gap-2">
- {run.model}
- <PersonaBadge name={run.personaName} />
- </div>
- <div className="text-xs text-gray-500">
- {run.held}/{run.total} held • {timeAgo(run.timestamp)}
- </div>
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
- </>
- )}
- </div>
- );
+export default function AdversarialBoundaryPanel(props) {
+ return <TwinEvaluationSuitePanel suite={SUITE} renderDetail={renderDetail} {...props} />;
}
diff --git a/client/src/components/digital-twin/tabs/MultiTurnPanel.jsx b/client/src/components/digital-twin/tabs/MultiTurnPanel.jsx
index a64f3bb4b5..3c563b198b 100644
--- a/client/src/components/digital-twin/tabs/MultiTurnPanel.jsx
+++ b/client/src/components/digital-twin/tabs/MultiTurnPanel.jsx
@@ -1,22 +1,7 @@
-import { useState, useEffect } from 'react';
-import {
- Play,
- MessagesSquare,
- CheckCircle,
- XCircle,
- AlertCircle,
- Clock,
- ChevronDown,
- ChevronRight,
- History
-} from 'lucide-react';
-import BrailleSpinner from '../../BrailleSpinner';
+import { MessagesSquare } from 'lucide-react';
import * as api from '../../../services/api';
-import toast from '../../ui/Toast';
-
-import PersonaBadge from '../PersonaBadge';
-import { MULTI_TURN_STATUS, scoreToColor } from '../constants';
-import { timeAgo } from '../../../utils/formatters';
+import { MULTI_TURN_STATUS } from '../constants';
+import TwinEvaluationSuitePanel, { SuiteModelResponses } from './TwinEvaluationSuitePanel';
/**
* Multi-Turn Conversation testing (M34 P6). Plays out each scenario's user turns
@@ -24,296 +9,77 @@ import { timeAgo } from '../../../utils/formatters';
* grades whether it stayed *consistent* across the whole conversation rather
* than contradicting itself, caving to pushback, or forgetting a constraint.
* Reuses the provider/model + persona selection from the parent TestTab via
- * props so all four suites share one configuration.
+ * props so all suites share one configuration. Lifecycle + shared presentation
+ * live in `TwinEvaluationSuitePanel`; this file only declares the Multi-Turn
+ * suite descriptor and its expanded-detail renderer (a full transcript).
*/
-export default function MultiTurnPanel({ selectedProviders = [], personaId = '', onPersonaNotFound, onRefresh }) {
- const [scenarios, setScenarios] = useState([]);
- const [history, setHistory] = useState([]);
- const [loading, setLoading] = useState(true);
- const [running, setRunning] = useState(false);
- const [results, setResults] = useState([]);
- const [expanded, setExpanded] = useState(null);
-
- useEffect(() => {
- loadData();
- }, []);
-
- const loadData = async () => {
- setLoading(true);
- // These loads own their fallback ([]) so silence the helper's default toast.
- const [scenarioData, historyData] = await Promise.all([
- api.getMultiTurnTests({ silent: true }).catch(() => []),
- api.getMultiTurnTestHistory(5, { silent: true }).catch(() => [])
- ]);
- setScenarios(scenarioData);
- setHistory(historyData);
- setLoading(false);
- };
-
- const runTests = async () => {
- if (selectedProviders.length === 0) {
- toast.error('Select at least one provider/model above');
- return;
- }
-
- setRunning(true);
- setResults([]);
-
- // These calls own their error UI below (and one path delegates to the
- // parent), so silence the helper's default toast to avoid double-toasting.
- const runResults = await Promise.all(
- selectedProviders.map(({ providerId, model }) =>
- api.runMultiTurnTests(providerId, model, null, personaId || null, { silent: true })
- .then(result => ({ providerId, model, ...result }))
- .catch(err => ({ providerId, model, error: err.message, code: err?.code }))
- )
- );
-
- setResults(runResults);
- // The run response already carries each run's history entry — prepend it
- // to the local list instead of refetching (reactive-update convention).
- const fresh = runResults
- .filter(r => !r.error && r.runId)
- .map(({ runId, score, consistent, total, timestamp, model, personaName }) => ({ runId, score, consistent, total, timestamp, model, personaName }));
- if (fresh.length) setHistory(prev => [...fresh, ...prev].slice(0, 5));
- setRunning(false);
-
- // A stale/deleted persona is rejected by the same route guard the
- // behavioral runner hits; ask the parent (which owns the picker) to clear
- // it, and show a persona-specific message instead of the generic one.
- if (runResults.some(r => r.code === 'NOT_FOUND')) {
- onPersonaNotFound?.();
- toast.error('That persona no longer exists — switched to the base twin. Try again.');
- } else if (runResults.some(r => r.error)) {
- toast.error('Some runs failed — check provider availability');
- } else {
- toast.success('Multi-turn conversation tests completed');
- }
- onRefresh?.();
- };
-
- const getResultIcon = (result) => {
- switch (result) {
- case 'consistent':
- return <CheckCircle className="w-5 h-5 text-port-success" />;
- case 'inconsistent':
- return <XCircle className="w-5 h-5 text-port-error" />;
- case 'partial':
- return <AlertCircle className="w-5 h-5 text-port-warning" />;
- default:
- return <Clock className="w-5 h-5 text-gray-400" />;
- }
- };
-
- if (loading) {
- return (
- <div className="flex items-center justify-center h-32">
- <BrailleSpinner text="Loading conversation suite" />
+const SUITE = {
+ HeaderIcon: MessagesSquare,
+ title: 'Multi-Turn Conversation Tests',
+ description: 'Multi-message exchanges scored on whether your twin stays consistent across the whole conversation.',
+ runLabel: 'Run Conversations',
+ loadingText: 'Loading conversation suite',
+ itemLabel: 'Conversation',
+ emptyState: (
+ <>
+ No multi-turn suite found. Add a <span className="text-gray-300">MULTI_TURN_SUITE.md</span> to your digital twin folder to enable these tests.
+ </>
+ ),
+ scoreLabel: 'Consistency Score',
+ countField: 'consistent',
+ historyTitle: 'Recent Conversation Runs',
+ statusMap: MULTI_TURN_STATUS,
+ passResult: 'consistent',
+ failResult: 'inconsistent',
+ getTests: api.getMultiTurnTests,
+ getHistory: api.getMultiTurnTestHistory,
+ runTests: api.runMultiTurnTests,
+ successToast: 'Multi-turn conversation tests completed'
+};
+
+const renderTranscript = (tr) => (
+ <div className="bg-port-card p-3 rounded space-y-2">
+ {(tr.transcript || []).map((msg, i) => (
+ <div key={i} className={msg.role === 'twin' ? 'pl-3 border-l-2 border-port-accent' : ''}>
+ <span className={`text-xs uppercase tracking-wide ${msg.role === 'twin' ? 'text-port-accent' : 'text-gray-500'}`}>
+ {msg.role === 'twin' ? 'Twin' : 'User'}
+ </span>
+ <p className="text-white whitespace-pre-wrap">{msg.content}</p>
</div>
- );
- }
-
- return (
- <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
- <div className="p-4 border-b border-port-border flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="font-semibold text-white flex items-center gap-2">
- <MessagesSquare className="w-5 h-5 text-port-accent" />
- Multi-Turn Conversation Tests
- </h3>
- <p className="text-xs text-gray-500 mt-1">
- Multi-message exchanges scored on whether your twin stays consistent across the whole conversation.
- </p>
- </div>
- <button
- onClick={runTests}
- disabled={running || scenarios.length === 0 || selectedProviders.length === 0}
- className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {running ? (
- <>
- <BrailleSpinner />
- Running...
- </>
- ) : (
- <>
- <Play className="w-4 h-4" />
- Run Conversations
- </>
- )}
- </button>
+ ))}
+ {tr.reasoning && (
+ <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
+ Reasoning: {tr.reasoning}
+ </p>
+ )}
+ </div>
+);
+
+const renderDetail = (scenario, ctx) => (
+ <div className="space-y-4">
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">User Turns</h4>
+ <ol className="space-y-2 list-decimal list-inside">
+ {scenario.turns?.map((turn, i) => (
+ <li key={i} className="text-white bg-port-card p-3 rounded">{turn}</li>
+ ))}
+ </ol>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
+ <div>
+ <div className="text-port-success text-xs mb-1">Consistent Trajectory</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.consistentTrajectory}</div>
</div>
+ <div>
+ <div className="text-port-error text-xs mb-1">Inconsistent Trajectory</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.inconsistentTrajectory}</div>
+ </div>
+ </div>
- {scenarios.length === 0 ? (
- <div className="p-6 text-center text-sm text-gray-400">
- No multi-turn suite found. Add a <span className="text-gray-300">MULTI_TURN_SUITE.md</span> to your digital twin folder to enable these tests.
- </div>
- ) : (
- <>
- {/* Results table */}
- {results.length > 0 && (
- <div className="overflow-x-auto -mx-4 sm:mx-0">
- <table className="w-full min-w-[500px]">
- <thead>
- <tr className="border-b border-port-border">
- <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Conversation</th>
- {results.map(r => (
- <th key={`${r.providerId}-${r.model}`} className="px-4 py-3 text-left text-sm font-medium text-gray-400">
- {r.model}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {scenarios.map(scenario => (
- <tr
- key={scenario.testId}
- className="border-b border-port-border last:border-b-0 hover:bg-port-border/30"
- >
- <td className="px-4 py-3">
- <button
- onClick={() => setExpanded(expanded === scenario.testId ? null : scenario.testId)}
- className="flex items-center gap-2 text-sm text-white text-left"
- >
- {expanded === scenario.testId ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
- {scenario.testId}. {scenario.testName}
- </button>
- </td>
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === scenario.testId);
- return (
- <td key={`${r.providerId}-${r.model}`} className="px-4 py-3">
- {tr ? (
- <div className="flex items-center gap-2">
- {getResultIcon(tr.result)}
- <span className={`text-sm ${MULTI_TURN_STATUS[tr.result]?.color?.split(' ')[1]}`}>
- {MULTI_TURN_STATUS[tr.result]?.label}
- </span>
- </div>
- ) : (
- <span className="text-gray-500">—</span>
- )}
- </td>
- );
- })}
- </tr>
- ))}
-
- {/* Summary row */}
- <tr className="bg-port-border/30">
- <td className="px-4 py-3 font-medium text-white">Consistency Score</td>
- {results.map(r => (
- <td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
- {r.error ? (
- <span className="text-sm text-port-error">{r.error}</span>
- ) : (
- <>
- <span className={`text-lg font-bold ${scoreToColor(r.score || 0)}`}>
- {Math.round((r.score || 0) * 100)}%
- </span>
- <span className="text-sm text-gray-500 ml-2">
- ({r.consistent || 0}/{r.total || 0})
- </span>
- </>
- )}
- </td>
- ))}
- </tr>
- </tbody>
- </table>
- </div>
- )}
-
- {/* Expanded scenario detail */}
- {expanded && (
- <div className="p-4 bg-port-bg border-t border-port-border">
- {(() => {
- const scenario = scenarios.find(s => s.testId === expanded);
- if (!scenario) return null;
- return (
- <div className="space-y-4">
- <div>
- <h4 className="text-sm font-medium text-gray-400 mb-1">User Turns</h4>
- <ol className="space-y-2 list-decimal list-inside">
- {scenario.turns?.map((turn, i) => (
- <li key={i} className="text-white bg-port-card p-3 rounded">{turn}</li>
- ))}
- </ol>
- </div>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
- <div>
- <div className="text-port-success text-xs mb-1">Consistent Trajectory</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.consistentTrajectory}</div>
- </div>
- <div>
- <div className="text-port-error text-xs mb-1">Inconsistent Trajectory</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{scenario.inconsistentTrajectory}</div>
- </div>
- </div>
-
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === expanded);
- if (!tr) return null;
- return (
- <div key={`${r.providerId}-${r.model}-resp`}>
- <h4 className="text-sm font-medium text-gray-400 mb-1 flex items-center gap-2">
- {r.model} Conversation {getResultIcon(tr.result)}
- </h4>
- <div className="bg-port-card p-3 rounded space-y-2">
- {(tr.transcript || []).map((msg, i) => (
- <div key={i} className={msg.role === 'twin' ? 'pl-3 border-l-2 border-port-accent' : ''}>
- <span className={`text-xs uppercase tracking-wide ${msg.role === 'twin' ? 'text-port-accent' : 'text-gray-500'}`}>
- {msg.role === 'twin' ? 'Twin' : 'User'}
- </span>
- <p className="text-white whitespace-pre-wrap">{msg.content}</p>
- </div>
- ))}
- {tr.reasoning && (
- <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
- Reasoning: {tr.reasoning}
- </p>
- )}
- </div>
- </div>
- );
- })}
- </div>
- );
- })()}
- </div>
- )}
+ <SuiteModelResponses item={scenario} label="Conversation" renderBody={renderTranscript} {...ctx} />
+ </div>
+);
- {/* History */}
- {history.length > 0 && (
- <div className="p-4 border-t border-port-border">
- <h4 className="font-semibold text-white mb-3 flex items-center gap-2 text-sm">
- <History size={16} />
- Recent Conversation Runs
- </h4>
- <div className="space-y-2">
- {history.map(run => (
- <div key={run.runId} className="flex items-center justify-between p-3 rounded bg-port-bg">
- <div className="flex items-center gap-4">
- <span className={`text-xl font-bold ${scoreToColor(run.score)}`}>
- {Math.round(run.score * 100)}%
- </span>
- <div>
- <div className="text-sm text-white flex items-center gap-2">
- {run.model}
- <PersonaBadge name={run.personaName} />
- </div>
- <div className="text-xs text-gray-500">
- {run.consistent}/{run.total} consistent • {timeAgo(run.timestamp)}
- </div>
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
- </>
- )}
- </div>
- );
+export default function MultiTurnPanel(props) {
+ return <TwinEvaluationSuitePanel suite={SUITE} renderDetail={renderDetail} {...props} />;
}
diff --git a/client/src/components/digital-twin/tabs/TwinEvaluationSuitePanel.jsx b/client/src/components/digital-twin/tabs/TwinEvaluationSuitePanel.jsx
new file mode 100644
index 0000000000..30bb28316d
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/TwinEvaluationSuitePanel.jsx
@@ -0,0 +1,279 @@
+import {
+ Play,
+ CheckCircle,
+ XCircle,
+ AlertCircle,
+ Clock,
+ ChevronDown,
+ ChevronRight,
+ History
+} from 'lucide-react';
+import BrailleSpinner from '../../BrailleSpinner';
+import PersonaBadge from '../PersonaBadge';
+import { scoreToColor } from '../constants';
+import { timeAgo } from '../../../utils/formatters';
+import { useTwinEvaluationSuite } from '../../../hooks/useTwinEvaluationSuite';
+
+/**
+ * The per-model result block shared by every suite's expanded detail: a
+ * `{model} {label}` heading with the run's result icon, then a body. The
+ * default body is the single-response + reasoning layout (Values / Adversarial);
+ * Multi-Turn passes a custom `renderBody` that lays out the full transcript.
+ */
+export function SuiteModelResponses({ item, results, resultIcon, label, renderBody }) {
+ const body = renderBody || (tr => (
+ <div className="bg-port-card p-3 rounded">
+ <p className="text-white whitespace-pre-wrap">{tr.response}</p>
+ {tr.reasoning && (
+ <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
+ Reasoning: {tr.reasoning}
+ </p>
+ )}
+ </div>
+ ));
+
+ return results.map(r => {
+ const tr = r.results?.find(x => x.testId === item.testId);
+ if (!tr) return null;
+ return (
+ <div key={`${r.providerId}-${r.model}-resp`}>
+ <h4 className="text-sm font-medium text-gray-400 mb-1 flex items-center gap-2">
+ {r.model} {label} {resultIcon(tr.result)}
+ </h4>
+ {body(tr)}
+ </div>
+ );
+ });
+}
+
+/**
+ * Shared presentation + lifecycle for the three Digital Twin evaluation-suite
+ * panels (Values-Alignment, Adversarial-Boundary, Multi-Turn). Everything the
+ * three suites share — loading, multi-provider run, history prepend, results
+ * table, and the recent-runs list — lives here; the caller supplies a `suite`
+ * descriptor (copy + status semantics + api calls) and a `renderDetail` fn for
+ * the one section that genuinely differs (the expanded per-test detail).
+ *
+ * @param {object} suite Suite descriptor (see the panel wrappers).
+ * @param {Function} renderDetail `(item, { results, resultIcon }) => ReactNode`.
+ * @param {Array} selectedProviders `[{ providerId, model }]` from TestTab.
+ * @param {string} personaId Selected persona id ('' = base twin).
+ * @param {Function} onPersonaNotFound Parent clears its picker on a stale persona.
+ * @param {Function} onRefresh Parent refresh after a run.
+ */
+export default function TwinEvaluationSuitePanel({
+ suite,
+ renderDetail,
+ selectedProviders = [],
+ personaId = '',
+ onPersonaNotFound,
+ onRefresh
+}) {
+ const {
+ HeaderIcon,
+ title,
+ description,
+ runLabel,
+ loadingText,
+ itemLabel,
+ emptyState,
+ scoreLabel,
+ countField,
+ historyTitle,
+ statusMap,
+ passResult,
+ failResult,
+ getTests,
+ getHistory,
+ runTests,
+ successToast
+ } = suite;
+
+ const {
+ items,
+ history,
+ loading,
+ running,
+ results,
+ expanded,
+ setExpanded,
+ run
+ } = useTwinEvaluationSuite({
+ selectedProviders,
+ personaId,
+ onPersonaNotFound,
+ onRefresh,
+ getTests,
+ getHistory,
+ runTests,
+ countField,
+ successToast
+ });
+
+ const resultIcon = (result) => {
+ if (result === passResult) return <CheckCircle className="w-5 h-5 text-port-success" />;
+ if (result === failResult) return <XCircle className="w-5 h-5 text-port-error" />;
+ if (result === 'partial') return <AlertCircle className="w-5 h-5 text-port-warning" />;
+ return <Clock className="w-5 h-5 text-gray-400" />;
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-32">
+ <BrailleSpinner text={loadingText} />
+ </div>
+ );
+ }
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <div className="p-4 border-b border-port-border flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div>
+ <h3 className="font-semibold text-white flex items-center gap-2">
+ <HeaderIcon className="w-5 h-5 text-port-accent" />
+ {title}
+ </h3>
+ <p className="text-xs text-gray-500 mt-1">{description}</p>
+ </div>
+ <button
+ onClick={run}
+ disabled={running || items.length === 0 || selectedProviders.length === 0}
+ className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {running ? (
+ <>
+ <BrailleSpinner />
+ Running...
+ </>
+ ) : (
+ <>
+ <Play className="w-4 h-4" />
+ {runLabel}
+ </>
+ )}
+ </button>
+ </div>
+
+ {items.length === 0 ? (
+ <div className="p-6 text-center text-sm text-gray-400">{emptyState}</div>
+ ) : (
+ <>
+ {/* Results table */}
+ {results.length > 0 && (
+ <div className="overflow-x-auto -mx-4 sm:mx-0">
+ <table className="w-full min-w-[500px]">
+ <thead>
+ <tr className="border-b border-port-border">
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">{itemLabel}</th>
+ {results.map(r => (
+ <th key={`${r.providerId}-${r.model}`} className="px-4 py-3 text-left text-sm font-medium text-gray-400">
+ {r.model}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {items.map(item => (
+ <tr
+ key={item.testId}
+ className="border-b border-port-border last:border-b-0 hover:bg-port-border/30"
+ >
+ <td className="px-4 py-3">
+ <button
+ onClick={() => setExpanded(expanded === item.testId ? null : item.testId)}
+ className="flex items-center gap-2 text-sm text-white text-left"
+ >
+ {expanded === item.testId ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ {item.testId}. {item.testName}
+ </button>
+ </td>
+ {results.map(r => {
+ const tr = r.results?.find(x => x.testId === item.testId);
+ return (
+ <td key={`${r.providerId}-${r.model}`} className="px-4 py-3">
+ {tr ? (
+ <div className="flex items-center gap-2">
+ {resultIcon(tr.result)}
+ <span className={`text-sm ${statusMap[tr.result]?.color?.split(' ')[1]}`}>
+ {statusMap[tr.result]?.label}
+ </span>
+ </div>
+ ) : (
+ <span className="text-gray-500">—</span>
+ )}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+
+ {/* Summary row */}
+ <tr className="bg-port-border/30">
+ <td className="px-4 py-3 font-medium text-white">{scoreLabel}</td>
+ {results.map(r => (
+ <td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
+ {r.error ? (
+ <span className="text-sm text-port-error">{r.error}</span>
+ ) : (
+ <>
+ <span className={`text-lg font-bold ${scoreToColor(r.score || 0)}`}>
+ {Math.round((r.score || 0) * 100)}%
+ </span>
+ <span className="text-sm text-gray-500 ml-2">
+ ({r[countField] || 0}/{r.total || 0})
+ </span>
+ </>
+ )}
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {/* Expanded detail */}
+ {expanded && (
+ <div className="p-4 bg-port-bg border-t border-port-border">
+ {(() => {
+ const item = items.find(i => i.testId === expanded);
+ if (!item) return null;
+ return renderDetail(item, { results, resultIcon });
+ })()}
+ </div>
+ )}
+
+ {/* History */}
+ {history.length > 0 && (
+ <div className="p-4 border-t border-port-border">
+ <h4 className="font-semibold text-white mb-3 flex items-center gap-2 text-sm">
+ <History size={16} />
+ {historyTitle}
+ </h4>
+ <div className="space-y-2">
+ {history.map(entry => (
+ <div key={entry.runId} className="flex items-center justify-between p-3 rounded bg-port-bg">
+ <div className="flex items-center gap-4">
+ <span className={`text-xl font-bold ${scoreToColor(entry.score)}`}>
+ {Math.round(entry.score * 100)}%
+ </span>
+ <div>
+ <div className="text-sm text-white flex items-center gap-2">
+ {entry.model}
+ <PersonaBadge name={entry.personaName} />
+ </div>
+ <div className="text-xs text-gray-500">
+ {entry[countField]}/{entry.total} {countField} • {timeAgo(entry.timestamp)}
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/tabs/ValuesAlignmentPanel.jsx b/client/src/components/digital-twin/tabs/ValuesAlignmentPanel.jsx
index 6d939f29a4..e850f919ff 100644
--- a/client/src/components/digital-twin/tabs/ValuesAlignmentPanel.jsx
+++ b/client/src/components/digital-twin/tabs/ValuesAlignmentPanel.jsx
@@ -1,314 +1,70 @@
-import { useState, useEffect } from 'react';
-import {
- Play,
- Scale,
- CheckCircle,
- XCircle,
- AlertCircle,
- Clock,
- ChevronDown,
- ChevronRight,
- History
-} from 'lucide-react';
-import BrailleSpinner from '../../BrailleSpinner';
+import { Scale } from 'lucide-react';
import * as api from '../../../services/api';
-import toast from '../../ui/Toast';
-
-import PersonaBadge from '../PersonaBadge';
-import { VALUES_STATUS, scoreToColor } from '../constants';
-import { timeAgo } from '../../../utils/formatters';
+import { VALUES_STATUS } from '../constants';
+import TwinEvaluationSuitePanel, { SuiteModelResponses } from './TwinEvaluationSuitePanel';
/**
* Values-Alignment testing (M34 P6). Poses ethical dilemmas to the embodied
* twin and grades each answer against the user's ranked values hierarchy.
* Reuses the provider/model selection from the parent TestTab via the
- * `selectedProviders` prop so the two suites share one configuration.
+ * `selectedProviders` prop so the suites share one configuration. Lifecycle +
+ * shared presentation live in `TwinEvaluationSuitePanel`; this file only
+ * declares the Values suite descriptor and its expanded-detail renderer.
*/
-export default function ValuesAlignmentPanel({ selectedProviders = [], personaId = '', onPersonaNotFound, onRefresh }) {
- const [dilemmas, setDilemmas] = useState([]);
- const [history, setHistory] = useState([]);
- const [loading, setLoading] = useState(true);
- const [running, setRunning] = useState(false);
- const [results, setResults] = useState([]);
- const [expanded, setExpanded] = useState(null);
-
- useEffect(() => {
- loadData();
- }, []);
-
- const loadData = async () => {
- setLoading(true);
- const [dilemmaData, historyData] = await Promise.all([
- api.getValuesAlignmentTests().catch(() => []),
- api.getValuesAlignmentTestHistory(5).catch(() => [])
- ]);
- setDilemmas(dilemmaData);
- setHistory(historyData);
- setLoading(false);
- };
-
- const runTests = async () => {
- if (selectedProviders.length === 0) {
- toast.error('Select at least one provider/model above');
- return;
- }
-
- setRunning(true);
- setResults([]);
-
- // These calls own their error UI below (and one path delegates to the
- // parent), so silence the helper's default toast to avoid double-toasting.
- const runResults = await Promise.all(
- selectedProviders.map(({ providerId, model }) =>
- api.runValuesAlignmentTests(providerId, model, null, personaId || null, { silent: true })
- .then(result => ({ providerId, model, ...result }))
- .catch(err => ({ providerId, model, error: err.message, code: err?.code }))
- )
- );
-
- setResults(runResults);
- // The run response already carries each run's history entry — prepend it
- // to the local list instead of refetching (reactive-update convention).
- const fresh = runResults
- .filter(r => !r.error && r.runId)
- .map(({ runId, score, aligned, total, timestamp, model, personaName }) => ({ runId, score, aligned, total, timestamp, model, personaName }));
- if (fresh.length) setHistory(prev => [...fresh, ...prev].slice(0, 5));
- setRunning(false);
-
- // A stale/deleted persona is rejected by the same route guard the
- // behavioral runner hits; ask the parent (which owns the picker) to clear
- // it, and show a persona-specific message instead of the generic one.
- if (runResults.some(r => r.code === 'NOT_FOUND')) {
- onPersonaNotFound?.();
- toast.error('That persona no longer exists — switched to the base twin. Try again.');
- } else if (runResults.some(r => r.error)) {
- toast.error('Some runs failed — check provider availability');
- } else {
- toast.success('Values-alignment tests completed');
- }
- onRefresh?.();
- };
-
- const getResultIcon = (result) => {
- switch (result) {
- case 'aligned':
- return <CheckCircle className="w-5 h-5 text-port-success" />;
- case 'misaligned':
- return <XCircle className="w-5 h-5 text-port-error" />;
- case 'partial':
- return <AlertCircle className="w-5 h-5 text-port-warning" />;
- default:
- return <Clock className="w-5 h-5 text-gray-400" />;
- }
- };
-
- if (loading) {
- return (
- <div className="flex items-center justify-center h-32">
- <BrailleSpinner text="Loading values suite" />
+const SUITE = {
+ HeaderIcon: Scale,
+ title: 'Values-Alignment Tests',
+ description: 'Ethical dilemmas scored against your ranked values hierarchy (Identity tab).',
+ runLabel: 'Run Dilemmas',
+ loadingText: 'Loading values suite',
+ itemLabel: 'Dilemma',
+ emptyState: (
+ <>
+ No values-alignment suite found. Add a <span className="text-gray-300">VALUES_ALIGNMENT_SUITE.md</span> to your digital twin folder to enable these tests.
+ </>
+ ),
+ scoreLabel: 'Alignment Score',
+ countField: 'aligned',
+ historyTitle: 'Recent Values Runs',
+ statusMap: VALUES_STATUS,
+ passResult: 'aligned',
+ failResult: 'misaligned',
+ getTests: api.getValuesAlignmentTests,
+ getHistory: api.getValuesAlignmentTestHistory,
+ runTests: api.runValuesAlignmentTests,
+ successToast: 'Values-alignment tests completed'
+};
+
+const renderDetail = (dilemma, ctx) => (
+ <div className="space-y-4">
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Scenario</h4>
+ <p className="text-white bg-port-card p-3 rounded">{dilemma.scenario}</p>
+ </div>
+ {dilemma.valuesTested?.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {dilemma.valuesTested.map(v => (
+ <span key={v} className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent">
+ {v}
+ </span>
+ ))}
</div>
- );
- }
-
- return (
- <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
- <div className="p-4 border-b border-port-border flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="font-semibold text-white flex items-center gap-2">
- <Scale className="w-5 h-5 text-port-accent" />
- Values-Alignment Tests
- </h3>
- <p className="text-xs text-gray-500 mt-1">
- Ethical dilemmas scored against your ranked values hierarchy (Identity tab).
- </p>
- </div>
- <button
- onClick={runTests}
- disabled={running || dilemmas.length === 0 || selectedProviders.length === 0}
- className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
- >
- {running ? (
- <>
- <BrailleSpinner />
- Running...
- </>
- ) : (
- <>
- <Play className="w-4 h-4" />
- Run Dilemmas
- </>
- )}
- </button>
+ )}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
+ <div>
+ <div className="text-port-success text-xs mb-1">Aligned Response</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{dilemma.alignedResponse}</div>
</div>
+ <div>
+ <div className="text-port-error text-xs mb-1">Misaligned Response</div>
+ <div className="text-gray-400 bg-port-card p-3 rounded">{dilemma.misalignedResponse}</div>
+ </div>
+ </div>
- {dilemmas.length === 0 ? (
- <div className="p-6 text-center text-sm text-gray-400">
- No values-alignment suite found. Add a <span className="text-gray-300">VALUES_ALIGNMENT_SUITE.md</span> to your digital twin folder to enable these tests.
- </div>
- ) : (
- <>
- {/* Results table */}
- {results.length > 0 && (
- <div className="overflow-x-auto -mx-4 sm:mx-0">
- <table className="w-full min-w-[500px]">
- <thead>
- <tr className="border-b border-port-border">
- <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Dilemma</th>
- {results.map(r => (
- <th key={`${r.providerId}-${r.model}`} className="px-4 py-3 text-left text-sm font-medium text-gray-400">
- {r.model}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {dilemmas.map(dilemma => (
- <tr
- key={dilemma.testId}
- className="border-b border-port-border last:border-b-0 hover:bg-port-border/30"
- >
- <td className="px-4 py-3">
- <button
- onClick={() => setExpanded(expanded === dilemma.testId ? null : dilemma.testId)}
- className="flex items-center gap-2 text-sm text-white text-left"
- >
- {expanded === dilemma.testId ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
- {dilemma.testId}. {dilemma.testName}
- </button>
- </td>
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === dilemma.testId);
- return (
- <td key={`${r.providerId}-${r.model}`} className="px-4 py-3">
- {tr ? (
- <div className="flex items-center gap-2">
- {getResultIcon(tr.result)}
- <span className={`text-sm ${VALUES_STATUS[tr.result]?.color?.split(' ')[1]}`}>
- {VALUES_STATUS[tr.result]?.label}
- </span>
- </div>
- ) : (
- <span className="text-gray-500">—</span>
- )}
- </td>
- );
- })}
- </tr>
- ))}
-
- {/* Summary row */}
- <tr className="bg-port-border/30">
- <td className="px-4 py-3 font-medium text-white">Alignment Score</td>
- {results.map(r => (
- <td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
- {r.error ? (
- <span className="text-sm text-port-error">{r.error}</span>
- ) : (
- <>
- <span className={`text-lg font-bold ${scoreToColor(r.score || 0)}`}>
- {Math.round((r.score || 0) * 100)}%
- </span>
- <span className="text-sm text-gray-500 ml-2">
- ({r.aligned || 0}/{r.total || 0})
- </span>
- </>
- )}
- </td>
- ))}
- </tr>
- </tbody>
- </table>
- </div>
- )}
-
- {/* Expanded dilemma detail */}
- {expanded && (
- <div className="p-4 bg-port-bg border-t border-port-border">
- {(() => {
- const dilemma = dilemmas.find(d => d.testId === expanded);
- if (!dilemma) return null;
- return (
- <div className="space-y-4">
- <div>
- <h4 className="text-sm font-medium text-gray-400 mb-1">Scenario</h4>
- <p className="text-white bg-port-card p-3 rounded">{dilemma.scenario}</p>
- </div>
- {dilemma.valuesTested?.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {dilemma.valuesTested.map(v => (
- <span key={v} className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent">
- {v}
- </span>
- ))}
- </div>
- )}
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
- <div>
- <div className="text-port-success text-xs mb-1">Aligned Response</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{dilemma.alignedResponse}</div>
- </div>
- <div>
- <div className="text-port-error text-xs mb-1">Misaligned Response</div>
- <div className="text-gray-400 bg-port-card p-3 rounded">{dilemma.misalignedResponse}</div>
- </div>
- </div>
-
- {results.map(r => {
- const tr = r.results?.find(x => x.testId === expanded);
- if (!tr) return null;
- return (
- <div key={`${r.providerId}-${r.model}-resp`}>
- <h4 className="text-sm font-medium text-gray-400 mb-1 flex items-center gap-2">
- {r.model} Response {getResultIcon(tr.result)}
- </h4>
- <div className="bg-port-card p-3 rounded">
- <p className="text-white whitespace-pre-wrap">{tr.response}</p>
- {tr.reasoning && (
- <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
- Reasoning: {tr.reasoning}
- </p>
- )}
- </div>
- </div>
- );
- })}
- </div>
- );
- })()}
- </div>
- )}
+ <SuiteModelResponses item={dilemma} label="Response" {...ctx} />
+ </div>
+);
- {/* History */}
- {history.length > 0 && (
- <div className="p-4 border-t border-port-border">
- <h4 className="font-semibold text-white mb-3 flex items-center gap-2 text-sm">
- <History size={16} />
- Recent Values Runs
- </h4>
- <div className="space-y-2">
- {history.map(run => (
- <div key={run.runId} className="flex items-center justify-between p-3 rounded bg-port-bg">
- <div className="flex items-center gap-4">
- <span className={`text-xl font-bold ${scoreToColor(run.score)}`}>
- {Math.round(run.score * 100)}%
- </span>
- <div>
- <div className="text-sm text-white flex items-center gap-2">
- {run.model}
- <PersonaBadge name={run.personaName} />
- </div>
- <div className="text-xs text-gray-500">
- {run.aligned}/{run.total} aligned • {timeAgo(run.timestamp)}
- </div>
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
- </>
- )}
- </div>
- );
+export default function ValuesAlignmentPanel(props) {
+ return <TwinEvaluationSuitePanel suite={SUITE} renderDetail={renderDetail} {...props} />;
}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 3d86c0a0a7..2f393342f4 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -145,6 +145,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. |
| `useSongTraining` | Drives a song training run over one scope (whole song or a sliced section) on top of `useColorMatch`: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (`songProgress.recordAttempt`) and surfaces the next aggregate via `onProgress`. Supports looping (auto-restart after a run) and keeps a `lastSummary`. Exposes `{ running, countingIn, noteColors, activeIndex, lastSummary, start, stop }`; cancels pending loop relaunches on stop/unmount. | The Song editor's Training panel. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
+| `useTwinEvaluationSuite` | Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. `countField` names the suite's pass-count key so history stays generic. Returns `{ items, history, loading, running, results, expanded, setExpanded, run, reload }`. | The Digital Twin `TwinEvaluationSuitePanel` presentation shell — don't re-roll the load/run/history dance per suite. |
| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
| `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 0f1d3817a3..05a847612b 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -128,5 +128,6 @@ export * from './useGoalDetail.js';
export * from './usePostSession.js';
export * from './useRecordMerge.js';
export * from './useSyncIntegrity.js';
+export * from './useTwinEvaluationSuite.js';
export * from './useUniverseNav.js';
export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/useTwinEvaluationSuite.js b/client/src/hooks/useTwinEvaluationSuite.js
new file mode 100644
index 0000000000..c3df0fef76
--- /dev/null
+++ b/client/src/hooks/useTwinEvaluationSuite.js
@@ -0,0 +1,112 @@
+import { useState, useEffect } from 'react';
+import toast from '../components/ui/Toast';
+
+/**
+ * Shared lifecycle for the Digital Twin evaluation-suite panels (M34 P6) —
+ * Values-Alignment, Adversarial-Boundary, and Multi-Turn. All three panels load
+ * a suite + recent history, run every selected provider/model in parallel,
+ * prepend fresh runs to the history list, and handle the stale-persona /
+ * partial-failure toast fan-out identically. This hook owns that lifecycle so
+ * the panels only differ in their suite descriptor + detail renderer.
+ *
+ * The three run responses each carry a suite-specific pass-count field
+ * (`aligned` / `held` / `consistent`); `countField` names it so the fresh
+ * history entry preserves it without the hook knowing which suite it serves.
+ *
+ * @param {object} cfg
+ * @param {Array} cfg.selectedProviders `[{ providerId, model }]` from TestTab.
+ * @param {string} cfg.personaId Selected persona id ('' = base twin).
+ * @param {Function} [cfg.onPersonaNotFound] Parent clears its picker on a stale persona.
+ * @param {Function} [cfg.onRefresh] Parent refresh after a run.
+ * @param {Function} cfg.getTests `(options) => Promise<item[]>`.
+ * @param {Function} cfg.getHistory `(limit, options) => Promise<run[]>`.
+ * @param {Function} cfg.runTests `(providerId, model, testIds, personaId, options) => Promise<run>`.
+ * @param {string} cfg.countField Suite pass-count key to preserve in history.
+ * @param {string} cfg.successToast Copy for the all-succeeded toast.
+ */
+export function useTwinEvaluationSuite({
+ selectedProviders = [],
+ personaId = '',
+ onPersonaNotFound,
+ onRefresh,
+ getTests,
+ getHistory,
+ runTests,
+ countField,
+ successToast,
+}) {
+ const [items, setItems] = useState([]);
+ const [history, setHistory] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [running, setRunning] = useState(false);
+ const [results, setResults] = useState([]);
+ const [expanded, setExpanded] = useState(null);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ // These loads own their fallback ([]) so silence the helper's default toast.
+ const [itemData, historyData] = await Promise.all([
+ getTests({ silent: true }).catch(() => []),
+ getHistory(5, { silent: true }).catch(() => [])
+ ]);
+ setItems(itemData);
+ setHistory(historyData);
+ setLoading(false);
+ };
+
+ const run = async () => {
+ if (selectedProviders.length === 0) {
+ toast.error('Select at least one provider/model above');
+ return;
+ }
+
+ setRunning(true);
+ setResults([]);
+
+ // These calls own their error UI below (and one path delegates to the
+ // parent), so silence the helper's default toast to avoid double-toasting.
+ const runResults = await Promise.all(
+ selectedProviders.map(({ providerId, model }) =>
+ runTests(providerId, model, null, personaId || null, { silent: true })
+ .then(result => ({ providerId, model, ...result }))
+ .catch(err => ({ providerId, model, error: err.message, code: err?.code }))
+ )
+ );
+
+ setResults(runResults);
+ // The run response already carries each run's history entry — prepend it
+ // to the local list instead of refetching (reactive-update convention).
+ const fresh = runResults
+ .filter(r => !r.error && r.runId)
+ .map(r => ({
+ runId: r.runId,
+ score: r.score,
+ total: r.total,
+ timestamp: r.timestamp,
+ model: r.model,
+ personaName: r.personaName,
+ [countField]: r[countField]
+ }));
+ if (fresh.length) setHistory(prev => [...fresh, ...prev].slice(0, 5));
+ setRunning(false);
+
+ // A stale/deleted persona is rejected by the same route guard the
+ // behavioral runner hits; ask the parent (which owns the picker) to clear
+ // it, and show a persona-specific message instead of the generic one.
+ if (runResults.some(r => r.code === 'NOT_FOUND')) {
+ onPersonaNotFound?.();
+ toast.error('That persona no longer exists — switched to the base twin. Try again.');
+ } else if (runResults.some(r => r.error)) {
+ toast.error('Some runs failed — check provider availability');
+ } else {
+ toast.success(successToast);
+ }
+ onRefresh?.();
+ };
+
+ return { items, history, loading, running, results, expanded, setExpanded, run, reload: loadData };
+}
diff --git a/client/src/hooks/useTwinEvaluationSuite.test.js b/client/src/hooks/useTwinEvaluationSuite.test.js
new file mode 100644
index 0000000000..710b3f1a77
--- /dev/null
+++ b/client/src/hooks/useTwinEvaluationSuite.test.js
@@ -0,0 +1,169 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+vi.mock('../components/ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() }
+}));
+
+import toast from '../components/ui/Toast';
+import { useTwinEvaluationSuite } from './useTwinEvaluationSuite';
+
+// Extracted from the three Digital Twin evaluation-suite panels (#2372). These
+// tests pin the behaviors the three panels used to duplicate: silenced loads,
+// parallel provider runs, reactive history prepend that preserves the suite's
+// pass-count field, and the stale-persona / partial-failure toast fan-out.
+
+const baseCfg = (overrides = {}) => ({
+ selectedProviders: [{ providerId: 'p1', model: 'm1' }],
+ personaId: '',
+ countField: 'aligned',
+ successToast: 'done',
+ getTests: vi.fn().mockResolvedValue([{ testId: 1, testName: 'T1' }]),
+ getHistory: vi.fn().mockResolvedValue([]),
+ runTests: vi.fn().mockResolvedValue({
+ runId: 'r1', score: 0.9, aligned: 9, total: 10, timestamp: 1, model: 'm1', personaName: null
+ }),
+ ...overrides
+});
+
+describe('useTwinEvaluationSuite', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('loads items + history with silent options and clears loading', async () => {
+ const cfg = baseCfg();
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ expect(cfg.getTests).toHaveBeenCalledWith({ silent: true });
+ expect(cfg.getHistory).toHaveBeenCalledWith(5, { silent: true });
+ expect(result.current.items).toHaveLength(1);
+ });
+
+ it('falls back to empty arrays when a load rejects (no crash, no toast)', async () => {
+ const cfg = baseCfg({
+ getTests: vi.fn().mockRejectedValue(new Error('boom')),
+ getHistory: vi.fn().mockRejectedValue(new Error('boom'))
+ });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.items).toEqual([]);
+ expect(result.current.history).toEqual([]);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('runs every selected provider in parallel and silences each call', async () => {
+ const cfg = baseCfg({
+ selectedProviders: [
+ { providerId: 'p1', model: 'm1' },
+ { providerId: 'p2', model: 'm2' }
+ ]
+ });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(cfg.runTests).toHaveBeenCalledTimes(2);
+ expect(cfg.runTests).toHaveBeenCalledWith('p1', 'm1', null, null, { silent: true });
+ expect(result.current.results).toHaveLength(2);
+ expect(toast.success).toHaveBeenCalledWith('done');
+ });
+
+ it('passes personaId through when set (null when empty)', async () => {
+ const cfg = baseCfg({ personaId: 'persona-7' });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+ expect(cfg.runTests).toHaveBeenCalledWith('p1', 'm1', null, 'persona-7', { silent: true });
+ });
+
+ it('prepends a fresh run to history preserving the suite count field', async () => {
+ const cfg = baseCfg({ countField: 'held', getHistory: vi.fn().mockResolvedValue([]) });
+ cfg.runTests = vi.fn().mockResolvedValue({
+ runId: 'r9', score: 0.7, held: 7, total: 10, timestamp: 42, model: 'm1', personaName: 'Alt'
+ });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(result.current.history[0]).toMatchObject({
+ runId: 'r9', score: 0.7, held: 7, total: 10, personaName: 'Alt'
+ });
+ });
+
+ it('caps prepended history at 5 entries', async () => {
+ const existing = Array.from({ length: 5 }, (_, i) => ({ runId: `old-${i}`, score: 0.5, aligned: 1, total: 2 }));
+ const cfg = baseCfg({ getHistory: vi.fn().mockResolvedValue(existing) });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(result.current.history).toHaveLength(5);
+ expect(result.current.history[0].runId).toBe('r1');
+ });
+
+ it('errors and does not run when no providers are selected', async () => {
+ const cfg = baseCfg({ selectedProviders: [] });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(cfg.runTests).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith('Select at least one provider/model above');
+ });
+
+ it('calls onPersonaNotFound + persona toast when a run reports NOT_FOUND', async () => {
+ const onPersonaNotFound = vi.fn();
+ const cfg = baseCfg({
+ onPersonaNotFound,
+ runTests: vi.fn().mockRejectedValue(Object.assign(new Error('gone'), { code: 'NOT_FOUND' }))
+ });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(onPersonaNotFound).toHaveBeenCalledTimes(1);
+ expect(toast.error).toHaveBeenCalledWith(
+ 'That persona no longer exists — switched to the base twin. Try again.'
+ );
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('shows a partial-failure toast (not success) when some runs error without NOT_FOUND', async () => {
+ const cfg = baseCfg({
+ selectedProviders: [
+ { providerId: 'p1', model: 'm1' },
+ { providerId: 'p2', model: 'm2' }
+ ]
+ });
+ cfg.runTests = vi.fn()
+ .mockResolvedValueOnce({ runId: 'r1', score: 0.9, aligned: 9, total: 10, timestamp: 1, model: 'm1' })
+ .mockRejectedValueOnce(new Error('provider down'));
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+
+ expect(toast.error).toHaveBeenCalledWith('Some runs failed — check provider availability');
+ expect(toast.success).not.toHaveBeenCalled();
+ // The one good run still lands in history; the failed one is filtered out.
+ expect(result.current.history).toHaveLength(1);
+ });
+
+ it('fires onRefresh after every completed run', async () => {
+ const onRefresh = vi.fn();
+ const cfg = baseCfg({ onRefresh });
+ const { result } = renderHook(() => useTwinEvaluationSuite(cfg));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => { await result.current.run(); });
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index bb067fdd2e..812b180e92 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -29,13 +29,13 @@ export const runDigitalTwinMultiTests = (providers, testIds = null, personaId =
export const getDigitalTwinTestHistory = (limit = 10) => request(`/digital-twin/tests/history?limit=${limit}`);
// Digital Twin - Values-Alignment Testing (M34 P6)
-export const getValuesAlignmentTests = () => request('/digital-twin/values-tests');
+export const getValuesAlignmentTests = (options = {}) => request('/digital-twin/values-tests', options);
export const runValuesAlignmentTests = (providerId, model, testIds = null, personaId = null, options = {}) => request('/digital-twin/values-tests/run', {
method: 'POST',
body: JSON.stringify({ providerId, model, testIds, personaId }),
...options
});
-export const getValuesAlignmentTestHistory = (limit = 10) => request(`/digital-twin/values-tests/history?limit=${limit}`);
+export const getValuesAlignmentTestHistory = (limit = 10, options = {}) => request(`/digital-twin/values-tests/history?limit=${limit}`, options);
// Digital Twin - Adversarial Boundary Testing (M34 P6)
export const getAdversarialTests = (options = {}) => request('/digital-twin/adversarial-tests', options);