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

feat: show each Digital Twin model's results as its tests finish (#10063)

[._.]/ Adam Eivy143a4b4d43df
diff --git a/client/src/components/digital-twin/tabs/TestTab.jsx b/client/src/components/digital-twin/tabs/TestTab.jsx
index c1a5411e08..2d04b2de79 100644
--- a/client/src/components/digital-twin/tabs/TestTab.jsx
+++ b/client/src/components/digital-twin/tabs/TestTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import {Play,
CheckCircle,
XCircle,
@@ -15,6 +15,8 @@ import {Play,
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
import toast from '../../ui/Toast';
+import socket from '../../../services/socket';
+import { uuidv4 } from '../../../lib/uuid';
import ValuesAlignmentPanel from './ValuesAlignmentPanel';
import AdversarialBoundaryPanel from './AdversarialBoundaryPanel';
@@ -23,12 +25,18 @@ import PersonaBadge from '../PersonaBadge';
import { TEST_STATUS } from '../constants';
import { timeAgo } from '../../../utils/formatters';
+const pairKey = (providerId, model) => `${providerId}:${model}`;
+
export default function TestTab({ onRefresh }) {
const [tests, setTests] = useState([]);
const [providers, setProviders] = useState([]);
const [history, setHistory] = useState([]);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState(false);
+ // The in-flight multi-model batch: { id, order: [pairKey…], received: Map<pairKey, entry> }.
+ // null when nothing is running, so a late/duplicate/foreign frame is dropped.
+ const activeBatchRef = useRef(null);
+ const [batchProgress, setBatchProgress] = useState(null); // { completed, total } | null
// Test configuration
const [selectedProviders, setSelectedProviders] = useState([]);
@@ -53,6 +61,27 @@ export default function TestTab({ onRefresh }) {
loadData();
}, []);
+ // Merge each provider/model result into the visible set as the server reports
+ // it, instead of waiting for the slowest model's HTTP response. Frames are
+ // matched on the batch id this tab minted, each pair is accepted once, and
+ // the visible rows stay in selected-model order regardless of finish order.
+ useEffect(() => {
+ const onProgress = (payload) => {
+ const batch = activeBatchRef.current;
+ if (!batch || payload?.requestId !== batch.id) return;
+ const key = pairKey(payload.providerId, payload.model);
+ if (!batch.order.includes(key) || batch.received.has(key)) return;
+ batch.received.set(key, { providerId: payload.providerId, model: payload.model, ...payload.result });
+ setResults(batch.order.filter(k => batch.received.has(k)).map(k => batch.received.get(k)));
+ setBatchProgress({ completed: batch.received.size, total: batch.order.length });
+ };
+ socket.on('digital-twin:test-progress', onProgress);
+ return () => {
+ socket.off('digital-twin:test-progress', onProgress);
+ activeBatchRef.current = null;
+ };
+ }, []);
+
const loadData = async () => {
setLoading(true);
const [testsData, providersData, historyData, fbStats, personaData] = await Promise.all([
@@ -134,6 +163,7 @@ export default function TestTab({ onRefresh }) {
setRunning(true);
setResults([]);
+ setBatchProgress(null);
const testIds = selectedTests.length > 0 ? selectedTests : null;
const personaId = selectedPersonaId || null;
@@ -145,8 +175,20 @@ export default function TestTab({ onRefresh }) {
const result = await api.runSoulTests(providerId, model, testIds, personaId);
setResults([{ providerId, model, ...result }]);
} else {
- // Multi-provider test
- const multiResults = await api.runSoulMultiTests(selectedProviders, testIds, personaId);
+ // Multi-provider test. The listener is always mounted, so arming the
+ // batch before dispatch is enough to catch the fastest model's frame.
+ const batch = {
+ id: uuidv4(),
+ order: selectedProviders.map(p => pairKey(p.providerId, p.model)),
+ received: new Map()
+ };
+ activeBatchRef.current = batch;
+ setBatchProgress({ completed: 0, total: batch.order.length });
+ const multiResults = await api.runSoulMultiTests(selectedProviders, testIds, personaId, batch.id);
+ // Settle the batch BEFORE installing the final array: a progress frame
+ // can still arrive after the HTTP response and must not overwrite it.
+ // The final array is authoritative (one entry per selected pair).
+ activeBatchRef.current = null;
setResults(multiResults);
}
@@ -161,6 +203,8 @@ export default function TestTab({ onRefresh }) {
handlePersonaNotFound();
}
} finally {
+ activeBatchRef.current = null;
+ setBatchProgress(null);
// Always clear the spinner — without this an error (e.g. the 404 above)
// would strand the tab on "Running Tests...".
setRunning(false);
@@ -331,7 +375,7 @@ export default function TestTab({ onRefresh }) {
{running ? (
<>
<BrailleSpinner />
- Running Tests...
+ Running Tests...{batchProgress ? ` ${batchProgress.completed} of ${batchProgress.total} models done` : ''}
</>
) : (
<>
@@ -487,15 +531,23 @@ export default function TestTab({ onRefresh }) {
<td className="px-4 py-3 font-medium text-white">Total Score</td>
{results.map(r => (
<td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
- <span className={`text-lg font-bold ${
- r.score >= 0.8 ? 'text-port-success' :
- r.score >= 0.5 ? 'text-port-warning' : 'text-port-error'
- }`}>
- {Math.round((r.score || 0) * 100)}%
- </span>
- <span className="text-sm text-gray-500 ml-2">
- ({r.passed || 0}/{r.total || 0})
- </span>
+ {r.error ? (
+ <span className="text-sm font-medium text-port-error" title={r.error}>
+ Failed: {r.error}
+ </span>
+ ) : (
+ <>
+ <span className={`text-lg font-bold ${
+ r.score >= 0.8 ? 'text-port-success' :
+ r.score >= 0.5 ? 'text-port-warning' : 'text-port-error'
+ }`}>
+ {Math.round((r.score || 0) * 100)}%
+ </span>
+ <span className="text-sm text-gray-500 ml-2">
+ ({r.passed || 0}/{r.total || 0})
+ </span>
+ </>
+ )}
</td>
))}
</tr>
diff --git a/client/src/components/digital-twin/tabs/TestTab.test.jsx b/client/src/components/digital-twin/tabs/TestTab.test.jsx
new file mode 100644
index 0000000000..dcb81c23c3
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/TestTab.test.jsx
@@ -0,0 +1,136 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, act, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// A tiny in-memory emitter standing in for the shared socket so a test can
+// deliver `digital-twin:test-progress` frames in any order, any number of times.
+const bus = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ handlers,
+ on: (event, fn) => { handlers.set(event, [...(handlers.get(event) || []), fn]); },
+ off: (event, fn) => { handlers.set(event, (handlers.get(event) || []).filter(h => h !== fn)); },
+ emit: (event, payload) => (handlers.get(event) || []).forEach(h => h(payload)),
+ count: (event) => (handlers.get(event) || []).length,
+ };
+});
+
+vi.mock('../../../services/socket', () => ({ default: { on: bus.on, off: bus.off } }));
+vi.mock('../../../services/api', () => ({
+ getDigitalTwinTests: vi.fn(),
+ getProviders: vi.fn(),
+ getDigitalTwinTestHistory: vi.fn(),
+ getBehavioralFeedbackStats: vi.fn(),
+ getDigitalTwinPersonas: vi.fn(),
+ runSoulTests: vi.fn(),
+ runSoulMultiTests: vi.fn(),
+ submitBehavioralFeedback: vi.fn(),
+ generateSoulTests: vi.fn(),
+}));
+vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('./ValuesAlignmentPanel', () => ({ default: () => null }));
+vi.mock('./AdversarialBoundaryPanel', () => ({ default: () => null }));
+vi.mock('./MultiTurnPanel', () => ({ default: () => null }));
+
+import TestTab from './TestTab';
+import * as api from '../../../services/api';
+
+const PROGRESS = 'digital-twin:test-progress';
+const passed = (model) => ({ score: 1, passed: 1, total: 1, results: [{ testId: 1, result: 'passed' }], model });
+
+let finalResponse;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ bus.handlers.clear();
+ api.getDigitalTwinTests.mockResolvedValue([{ testId: 1, testName: 'Honesty', prompt: 'p', expectedBehavior: 'e', failureSignals: 'f' }]);
+ api.getProviders.mockResolvedValue({ providers: [{ id: 'p1', name: 'P1', enabled: true, models: ['alpha', 'beta'] }] });
+ api.getDigitalTwinTestHistory.mockResolvedValue([]);
+ api.getBehavioralFeedbackStats.mockResolvedValue(null);
+ api.getDigitalTwinPersonas.mockResolvedValue([]);
+ api.runSoulMultiTests.mockImplementation(() => new Promise((resolve) => { finalResponse = resolve; }));
+});
+
+// Start a two-model batch and return the request id the tab minted for it.
+async function startBatch(user) {
+ render(<TestTab onRefresh={vi.fn()} />);
+ await user.click(await screen.findByRole('button', { name: 'alpha' }));
+ await user.click(screen.getByRole('button', { name: 'beta' }));
+ await user.click(screen.getByRole('button', { name: /Run Selected Tests/ }));
+ await waitFor(() => expect(api.runSoulMultiTests).toHaveBeenCalled());
+ return api.runSoulMultiTests.mock.calls[0][3];
+}
+
+const frame = (requestId, model, result) => ({ requestId, providerId: 'p1', model, result });
+
+describe('TestTab multi-model progress (#10063)', () => {
+ it('shows the first finished model with 1-of-2 status while the final response is still pending', async () => {
+ const user = userEvent.setup();
+ const requestId = await startBatch(user);
+ expect(requestId).toEqual(expect.any(String));
+
+ act(() => bus.emit(PROGRESS, frame(requestId, 'alpha', passed('alpha'))));
+
+ const table = await screen.findByRole('table');
+ expect(within(table).getByText('alpha')).toBeInTheDocument();
+ expect(within(table).queryByText('beta')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /1 of 2 models done/ })).toBeInTheDocument();
+ });
+
+ it('ignores duplicate, other-batch, and settled-batch frames and keeps selected-model order', async () => {
+ const user = userEvent.setup();
+ const requestId = await startBatch(user);
+
+ // A frame for someone else's batch arrives first and must be dropped.
+ act(() => bus.emit(PROGRESS, frame('another-batch', 'alpha', { score: 0, passed: 0, total: 1, results: [] })));
+ // beta finishes first, alpha second — rows must still read alpha, beta.
+ act(() => bus.emit(PROGRESS, frame(requestId, 'beta', passed('beta'))));
+ act(() => bus.emit(PROGRESS, frame(requestId, 'alpha', passed('alpha'))));
+ // Duplicate delivery must not overwrite the accepted result.
+ act(() => bus.emit(PROGRESS, frame(requestId, 'alpha', { score: 0, passed: 0, total: 1, results: [] })));
+
+ const headers = within(await screen.findByRole('table')).getAllByRole('columnheader').map(h => h.textContent);
+ expect(headers).toEqual(['Test', 'alpha', 'beta']);
+ expect(screen.getAllByText('100%')).toHaveLength(2);
+
+ // Final array reconciles to one entry per pair and settles the batch.
+ await act(async () => {
+ finalResponse([
+ { providerId: 'p1', model: 'alpha', ...passed('alpha') },
+ { providerId: 'p1', model: 'beta', ...passed('beta') },
+ ]);
+ });
+ await waitFor(() => expect(screen.getByRole('button', { name: /Run Selected Tests/ })).toBeInTheDocument());
+
+ // A late frame from the settled batch cannot touch the final result set.
+ act(() => bus.emit(PROGRESS, frame(requestId, 'alpha', { score: 0, passed: 0, total: 1, results: [] })));
+ expect(screen.getAllByText('100%')).toHaveLength(2);
+ });
+
+ it('renders a provider failure as a failure, not a completed success', async () => {
+ const user = userEvent.setup();
+ const requestId = await startBatch(user);
+
+ act(() => bus.emit(PROGRESS, frame(requestId, 'alpha', { providerId: 'p1', model: 'alpha', error: 'quota exceeded' })));
+
+ expect(await screen.findByText(/Failed: quota exceeded/)).toBeInTheDocument();
+ expect(screen.queryByText('100%')).not.toBeInTheDocument();
+ });
+
+ it('releases the socket listener on unmount', async () => {
+ const { unmount } = render(<TestTab onRefresh={vi.fn()} />);
+ await waitFor(() => expect(bus.count(PROGRESS)).toBe(1));
+ unmount();
+ expect(bus.count(PROGRESS)).toBe(0);
+ });
+
+ it('leaves single-model runs on the single-provider endpoint', async () => {
+ const user = userEvent.setup();
+ api.runSoulTests.mockResolvedValue(passed('alpha'));
+ render(<TestTab onRefresh={vi.fn()} />);
+ await user.click(await screen.findByRole('button', { name: 'alpha' }));
+ await user.click(screen.getByRole('button', { name: /Run Selected Tests/ }));
+ await waitFor(() => expect(api.runSoulTests).toHaveBeenCalled());
+ expect(api.runSoulMultiTests).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index 5ea038b62e..dab761bee8 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -24,9 +24,9 @@ const runDigitalTwinTests = (providerId, model, testIds = null, personaId = null
method: 'POST',
body: JSON.stringify({ providerId, model, testIds, personaId })
});
-const runDigitalTwinMultiTests = (providers, testIds = null, personaId = null) => request('/digital-twin/tests/run-multi', {
+const runDigitalTwinMultiTests = (providers, testIds = null, personaId = null, requestId = undefined) => request('/digital-twin/tests/run-multi', {
method: 'POST',
- body: JSON.stringify({ providers, testIds, personaId })
+ body: JSON.stringify({ providers, testIds, personaId, requestId })
});
export const getDigitalTwinTestHistory = (limit = 10) => request(`/digital-twin/tests/history?limit=${limit}`);
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index db6c9a4564..064bc04db9 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -353,6 +353,14 @@ export const runTestsInputSchema = z.object({
personaId: optionalPersonaId
});
+// Optional client-minted batch id, echoed on every `digital-twin:test-progress`
+// frame so a run can tell its own progress from another run's. Absent for
+// callers that only read the final response array.
+const optionalRequestId = z.preprocess(
+ v => (v == null || v === '') ? undefined : v,
+ z.string().min(1).max(100).optional()
+);
+
// Run multi-model tests input
export const runMultiTestsInputSchema = z.object({
providers: z.array(z.object({
@@ -360,7 +368,8 @@ export const runMultiTestsInputSchema = z.object({
model: z.string().min(1)
})).min(1).max(10),
testIds: optionalTestIds,
- personaId: optionalPersonaId
+ personaId: optionalPersonaId,
+ requestId: optionalRequestId
});
// Enrichment question input
diff --git a/server/routes/digital-twin/index.test.js b/server/routes/digital-twin/index.test.js
index d8041e1398..7d4e39fa5c 100644
--- a/server/routes/digital-twin/index.test.js
+++ b/server/routes/digital-twin/index.test.js
@@ -172,6 +172,86 @@ describe('Digital Twin Routes', () => {
});
});
+ describe('POST /tests/run-multi progress delivery (#10063)', () => {
+ const pairs = [
+ { providerId: 'p1', model: 'fast' },
+ { providerId: 'p2', model: 'slow' },
+ ];
+
+ const deferred = () => {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+ };
+
+ it('emits the first model\'s result, tagged with the batch id, before the slow model finishes', async () => {
+ const io = { emit: vi.fn() };
+ app.set('io', io);
+ const slow = deferred();
+ digitalTwinService.runTests.mockImplementation((providerId) => (
+ providerId === 'p1' ? Promise.resolve({ score: 1 }) : slow.promise
+ ));
+
+ let settled = false;
+ const pending = request(app)
+ .post('/api/digital-twin/tests/run-multi')
+ .send({ providers: pairs, requestId: 'batch-1' })
+ .then((res) => { settled = true; return res; });
+
+ await vi.waitFor(() => expect(io.emit).toHaveBeenCalledTimes(1));
+ expect(io.emit).toHaveBeenCalledWith('digital-twin:test-progress', {
+ requestId: 'batch-1', providerId: 'p1', model: 'fast', result: { score: 1 },
+ });
+ expect(settled).toBe(false);
+
+ slow.resolve({ score: 0.5 });
+ const res = await pending;
+ expect(res.status).toBe(200);
+ // Final response keeps its array contract: one entry per selected pair.
+ expect(res.body).toEqual([
+ { providerId: 'p1', model: 'fast', score: 1 },
+ { providerId: 'p2', model: 'slow', score: 0.5 },
+ ]);
+ });
+
+ it('reports a provider failure as an error frame and entry, not a success', async () => {
+ const io = { emit: vi.fn() };
+ app.set('io', io);
+ digitalTwinService.runTests.mockImplementation((providerId) => (
+ providerId === 'p1' ? Promise.reject(new Error('quota exceeded')) : Promise.resolve({ score: 1 })
+ ));
+
+ const res = await request(app)
+ .post('/api/digital-twin/tests/run-multi')
+ .send({ providers: pairs, requestId: 'batch-2' });
+
+ expect(res.body[0]).toEqual({ providerId: 'p1', model: 'fast', error: 'quota exceeded' });
+ expect(io.emit).toHaveBeenCalledWith('digital-twin:test-progress', expect.objectContaining({
+ requestId: 'batch-2', providerId: 'p1', result: { providerId: 'p1', model: 'fast', error: 'quota exceeded' },
+ }));
+ });
+
+ it('still serves callers that send no requestId with the same final array', async () => {
+ const io = { emit: vi.fn() };
+ app.set('io', io);
+ digitalTwinService.runTests.mockResolvedValue({ score: 1 });
+
+ const res = await request(app).post('/api/digital-twin/tests/run-multi').send({ providers: pairs });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveLength(2);
+ expect(io.emit.mock.calls[0][1].requestId).toBeUndefined();
+ });
+
+ it('400s on an over-long requestId', async () => {
+ const res = await request(app)
+ .post('/api/digital-twin/tests/run-multi')
+ .send({ providers: pairs, requestId: 'x'.repeat(101) });
+ expect(res.status).toBe(400);
+ expect(digitalTwinService.runTests).not.toHaveBeenCalled();
+ });
+ });
+
describe('export', () => {
it('POST /export 400s on an invalid format', async () => {
const res = await request(app).post('/api/digital-twin/export').send({ format: 'invalid-format' });
diff --git a/server/routes/digital-twin/tests.js b/server/routes/digital-twin/tests.js
index 494728d56b..c959f275b8 100644
--- a/server/routes/digital-twin/tests.js
+++ b/server/routes/digital-twin/tests.js
@@ -48,7 +48,7 @@ router.post('/tests/run', asyncHandler(async (req, res) => {
* Run behavioral tests against multiple providers/models
*/
router.post('/tests/run-multi', asyncHandler(async (req, res) => {
- const { providers, testIds, personaId } = validateRequest(runMultiTestsInputSchema, req.body);
+ const { providers, testIds, personaId, requestId } = validateRequest(runMultiTestsInputSchema, req.body);
await assertPersonaExists(personaId);
const io = req.app.get('io');
@@ -61,9 +61,11 @@ router.post('/tests/run-multi', asyncHandler(async (req, res) => {
error: err.message
}));
- // Emit progress via Socket.IO
+ // Emit progress via Socket.IO. `requestId` (when the caller sent one) lets
+ // the client attribute the frame to its own batch; the final response
+ // below stays the same array for callers that don't listen.
if (io) {
- io.emit('digital-twin:test-progress', { providerId, model, result });
+ io.emit('digital-twin:test-progress', { requestId, providerId, model, result });
}
return { providerId, model, ...result };