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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: update assessment sweeps live without polling (#8542)
[._.]/ Adam Eivybe2c4e48624a
diff --git a/client/src/components/settings/AssessmentSweepPanel.jsx b/client/src/components/settings/AssessmentSweepPanel.jsxindex 041fe54948..d0be4de544 100644--- a/client/src/components/settings/AssessmentSweepPanel.jsx+++ b/client/src/components/settings/AssessmentSweepPanel.jsx@@ -31,7 +31,7 @@ import toast from '../ui/Toast';import socket from '../../services/socket';import useMounted from '../../hooks/useMounted';import { useAsyncAction } from '../../hooks/useAsyncAction';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { useVisibilityEvent } from '../../hooks/useVisibilityEvent';import { formatContextTokens, throughputLabel, timeAgo } from '../../utils/formatters';import {getLocalLlmAssessmentSweep, startLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,@@ -46,7 +46,6 @@ const SCOPES = [// How often to re-read the queue while it runs. Socket frames drive the live// message; this is the reload-safe backstop that also catches the transition to// finished when the last frame is missed.-const POLL_MS = 5000;const isRunning = (status) => status?.status === 'running';@@ -299,32 +298,60 @@ export default function AssessmentSweepPanel({const [message, setMessage] = useState('');const mountedRef = useMounted();- const refresh = useCallback(async () => {- const next = await getLocalLlmAssessmentSweep({ silent: true }).catch(() => null);- if (!next || !mountedRef.current) return null;+ // Every read/mutation captures a generation. A later event or request owns+ // the state, so a slow HTTP response cannot restore an older queue snapshot.+ const generationRef = useRef(0);+ const statusRef = useRef(null);+ const finishedRef = useRef(onSweepFinished);+ finishedRef.current = onSweepFinished;+ const finishNotifiedRef = useRef(false);++ const applyStatus = useCallback((next, notify = true) => {+ if (!next || !mountedRef.current) return;+ const previous = statusRef.current;+ statusRef.current = next;setStatus(next);- return next;+ if (previous?.current?.modelId !== next.current?.modelId+ || previous?.current?.tuningLabel !== next.current?.tuningLabel+ || !isRunning(next)) setMessage('');+ if (isRunning(next) || next.settled === false || previous?.startedAt !== next.startedAt) {+ finishNotifiedRef.current = false;+ }+ // Cancellation is not completion until the runtime restore has finished.+ if (next.status !== 'idle' && !isRunning(next) && next.settled !== false) {+ if (notify && !finishNotifiedRef.current) finishedRef.current?.();+ finishNotifiedRef.current = true;+ }}, [mountedRef]);- // A sweep that started in another tab (or before a reload) has to show up here- // — the queue is server state, not this component's.- useEffect(() => { refresh(); }, [refresh]);+ const refresh = useCallback(async (notify = true) => {+ const generation = ++generationRef.current;+ const next = await getLocalLlmAssessmentSweep({ silent: true }).catch(() => null);+ if (generation !== generationRef.current) return;+ applyStatus(next, notify);+ }, [applyStatus]);- const running = isRunning(status);- // `onSweepFinished` is a fresh closure on every parent render, so keeping it in- // a ref stops the poll callback from re-registering on each one.- const finishedRef = useRef(onSweepFinished);- finishedRef.current = onSweepFinished;+ useVisibilityEvent((visibility) => {+ if (visibility === 'visible') refresh();+ });- // `onSweepFinished` re-reads the whole assessment report, which probes every- // runtime — expensive enough that firing it twice for one finish (a poll tick- // racing the terminal socket frame) is worth latching out.- const finishNotifiedRef = useRef(false);- const notifyFinished = useCallback(() => {- if (finishNotifiedRef.current) return;- finishNotifiedRef.current = true;- finishedRef.current?.();- }, []);+ useEffect(() => {+ const handleChange = (next) => {+ generationRef.current += 1;+ applyStatus(next);+ };+ const reconcile = () => { refresh(); };+ socket.on('localLlm:sweep:changed', handleChange);+ socket.on('connect', reconcile);+ refresh(false);+ return () => {+ generationRef.current += 1;+ socket.off('localLlm:sweep:changed', handleChange);+ socket.off('connect', reconcile);+ };+ }, [applyStatus, refresh]);++ const running = isRunning(status);// A single-model run started mid-sweep would contend with the model the queue// is measuring, and BOTH readings would describe that contention. Tell the@@ -337,31 +364,6 @@ export default function AssessmentSweepPanel({const holdsMachine = running || status?.settled === false;useEffect(() => { onRunningChange?.(holdsMachine); }, [holdsMachine, onRunningChange]);- // Re-arm the latch for every queue that starts, not only one started from this- // tab: a sweep launched in another tab (or before a reload) would otherwise- // finish with the latch still set from a previous run, and this page would- // never re-read the ranking it just earned.- useEffect(() => { if (running) finishNotifiedRef.current = false; }, [running]);-- // Poll only while something is running, and only while the tab is visible —- // `useAutoRefetch` gives both, which matters for a queue deliberately left- // running in a background tab all night.- useAutoRefetch(async () => {- const next = await refresh();- // The report is only worth re-reading once the queue is done — mid-sweep it- // would re-rank on partial evidence every five seconds. "Done" means the- // sweep has LET GO, not merely that it stopped queuing: a cancelled tuning- // sweep is still restoring the launch line, and a report read then describes- // a daemon mid-relaunch.- if (next && !isRunning(next) && next.settled !== false) notifyFinished();- // Keeps polling through the WIND-DOWN, past the point the status stops- // saying `running`: a stopped sweep is still aborting and still restoring,- // and the only other thing that clears that state in a live tab is the- // terminal socket frame. Lose that frame to a reconnect and `holdsMachine`- // would stay true forever, leaving every per-model button disabled with no- // way back but a reload.- }, POLL_MS, { enabled: holdsMachine, immediate: false, pollOnly: true });-// Per-sample frames from the model in flight, on the same channel the// single-model run and model pulls use — hence the scope filter, or a// background model download would drive this line.@@ -369,34 +371,19 @@ export default function AssessmentSweepPanel({const handleProgress = (frame) => {if (!mountedRef.current) return;if (frame?.scope !== 'assessment' && frame?.scope !== 'assessment-sweep') return;- if (frame.event === 'complete' && frame.scope === 'assessment-sweep') {- // Terminal frame for the QUEUE (not for one model): pull the final- // snapshot and let the parent re-read the now-complete report.- setMessage('');- refresh().then(notifyFinished);- return;- }+ // Queue snapshots own counters, results and terminal state. This stream+ // carries only the human-readable message for the current measurement.+ if (frame.event === 'complete') return;if (frame.message) setMessage(frame.message);- // The counter moves when a model starts — and the frame already carries the- // new numbers, so take them from it rather than paying a round-trip per- // model for data we were just handed.- if (frame.event === 'model-start') {- setStatus((prev) => (prev ? {- ...prev,- completed: frame.completed ?? prev.completed,- total: frame.total ?? prev.total,- current: { backend: frame.backend, modelId: frame.modelId, tuningLabel: frame.tuningLabel ?? null },- } : prev));- }};socket.on('localLlm:progress', handleProgress);return () => socket.off('localLlm:progress', handleProgress);- }, [mountedRef, refresh, notifyFinished]);+ }, [mountedRef]);const [start, starting] = useAsyncAction(async () => {- finishNotifiedRef.current = false;+ const generation = ++generationRef.current;const next = await startLocalLlmAssessmentSweep({ scope });- setStatus(next);+ if (generation === generationRef.current) applyStatus(next);setShowConsent(false);toast.success(`Sweep started — ${next.total} model${next.total === 1 ? '' : 's'} queued`);return next;@@ -405,24 +392,26 @@ export default function AssessmentSweepPanel({// Same queue, same latch, same toast — the only difference from `start` is// which dimension the server is told to vary.const [startTuning, startingTuning] = useAsyncAction(async () => {- finishNotifiedRef.current = false;+ const generation = ++generationRef.current;const next = await startLocalLlmAssessmentSweep({backend: tuningRequest.backend,modelId: tuningRequest.modelId,tunings: true,});- setStatus(next);+ if (generation === generationRef.current) applyStatus(next);onTuningRequestClose?.();toast.success(`Tuning sweep started — ${next.total} configuration${next.total === 1 ? '' : 's'} queued`);return next;}, { errorMessage: 'Could not start the tuning sweep' });const [stop, stopping] = useAsyncAction(async () => {- setStatus(await cancelLocalLlmAssessmentSweep());+ const generation = ++generationRef.current;+ const next = await cancelLocalLlmAssessmentSweep();+ if (generation === generationRef.current) applyStatus(next, false);// Whatever it measured before stopping is real evidence, so the report has// to catch up rather than waiting for the next mount.//- // Deliberately NOT through `notifyFinished`: latching here would swallow the+ // The unsettled snapshot does not latch completion: that would swallow the// refresh that matters more — the one after the wind-down, once the launch// configuration is back and the runtime state on the page is the real one.// A cancel is worth two reads.diff --git a/client/src/components/settings/AssessmentSweepPanel.test.jsx b/client/src/components/settings/AssessmentSweepPanel.test.jsxindex 4d7eaeb034..f2d93decf8 100644--- a/client/src/components/settings/AssessmentSweepPanel.test.jsx+++ b/client/src/components/settings/AssessmentSweepPanel.test.jsx@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -26,6 +26,12 @@ const renderPanel = (props = {}) => render(<AssessmentSweepPanel counts={counts} contextTokens={[512, 4096, 16384]} onSweepFinished={vi.fn()} {...props} />);+const receive = (event, frame) => act(async () => {+ socket.on.mock.calls.find(([name]) => name === event)[1](frame);+});++afterEach(() => vi.useRealTimers());+beforeEach(() => {vi.clearAllMocks();getLocalLlmAssessmentSweep.mockResolvedValue(idle);@@ -171,13 +177,81 @@ describe('AssessmentSweepPanel', () => {renderPanel({ onSweepFinished });await screen.findByText(/1\/2 models measured/);- getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'complete', total: 2, completed: 2 });- const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')[1];- await act(async () => handler({ scope: 'assessment-sweep', event: 'complete', status: 'complete' }));+ await receive('localLlm:sweep:changed', { ...idle, status: 'complete', total: 2, completed: 2 });+ await receive('localLlm:sweep:changed', { ...idle, status: 'complete', total: 2, completed: 2 });await waitFor(() => expect(onSweepFinished).toHaveBeenCalledTimes(1));});+ it('renders another tab’s queue transitions without any recurring fetch', async () => {+ vi.useFakeTimers();+ const onSweepFinished = vi.fn();+ const onRunningChange = vi.fn();+ const { unmount } = renderPanel({ onSweepFinished, onRunningChange });+ await act(async () => {});+ const running = { ...idle, status: 'running', settled: false, total: 2, startedAt: '2026-01-01T00:00:00Z' };+ await receive('localLlm:sweep:changed', running);+ expect(screen.getByRole('button', { name: /stop sweep/i })).toBeInTheDocument();+ await receive('localLlm:sweep:changed', {+ ...running, completed: 1,+ results: [{ backend: 'ollama', modelId: 'example-model', verdict: 'fits', meanTokensPerSecond: 42 }],+ });+ expect(screen.getByText(/1\/2 models measured/)).toBeInTheDocument();+ expect(screen.getByText('example-model')).toBeInTheDocument();+ await receive('localLlm:sweep:changed', { ...running, status: 'cancelled' });+ expect(screen.getByRole('button', { name: 'Measure all models' })).toBeDisabled();+ expect(onRunningChange).toHaveBeenLastCalledWith(true);+ await act(async () => { await vi.advanceTimersByTimeAsync(20000); });+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(1);+ expect(onSweepFinished).not.toHaveBeenCalled();+ await receive('localLlm:sweep:changed', { ...running, status: 'cancelled', settled: true });+ expect(screen.getByRole('button', { name: 'Measure all models' })).toBeEnabled();+ expect(onRunningChange).toHaveBeenLastCalledWith(false);+ expect(onSweepFinished).toHaveBeenCalledTimes(1);+ unmount();+ for (const event of ['localLlm:sweep:changed', 'connect', 'localLlm:progress']) {+ const handler = socket.on.mock.calls.find(([name]) => name === event)[1];+ expect(socket.off).toHaveBeenCalledWith(event, handler);+ }+ });++ it('reconciles once on tab re-show and ignores a read superseded by an event', async () => {+ const visibility = vi.spyOn(document, 'visibilityState', 'get');+ visibility.mockReturnValue('visible');+ const { unmount } = renderPanel();+ await act(async () => {});+ let resolveRead;+ getLocalLlmAssessmentSweep.mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));+ visibility.mockReturnValue('hidden');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(1);+ visibility.mockReturnValue('visible');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(2);+ await receive('localLlm:sweep:changed', { ...idle, status: 'running', settled: false, total: 3 });+ await act(async () => { resolveRead(idle); });+ expect(screen.getByRole('button', { name: /stop sweep/i })).toBeInTheDocument();+ unmount();+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(2);+ visibility.mockRestore();+ });++ it('does not roll back a completed event when the start response arrives late', async () => {+ const user = userEvent.setup();+ let resolveStart;+ startLocalLlmAssessmentSweep.mockImplementationOnce(() => new Promise((resolve) => { resolveStart = resolve; }));+ const onSweepFinished = vi.fn();+ renderPanel({ onSweepFinished });+ await user.click(await screen.findByRole('button', { name: 'Measure all models' }));+ await user.click(screen.getByRole('button', { name: /start sweep/i }));+ await receive('localLlm:sweep:changed', { ...idle, status: 'complete', settled: true, total: 2, completed: 2 });+ await act(async () => { resolveStart({ ...idle, status: 'running', settled: false, total: 2 }); });+ expect(screen.queryByRole('button', { name: /stop sweep/i })).not.toBeInTheDocument();+ expect(screen.getByText(/Last sweep complete/)).toBeInTheDocument();+ expect(onSweepFinished).toHaveBeenCalledTimes(1);+ });+it('offers nothing to press when no runtime lists a model to measure', async () => {renderPanel({ counts: { unmeasured: 0, stale: 0, all: 0 } });expect(await screen.findByRole('button', { name: 'Measure all models' })).toBeDisabled();@@ -394,7 +468,7 @@ describe('AssessmentSweepPanel — tuning sweep', () => {// The terminal socket frame is not the only way out of the wind-down: lose it// to a reconnect and every per-model button would stay disabled forever.- it('keeps polling through the wind-down so a lost terminal frame cannot wedge it', async () => {+ it('reconciles a lost terminal frame once on reconnect without polling through wind-down', async () => {vi.useFakeTimers();getLocalLlmAssessmentSweep.mockResolvedValue({...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,@@ -407,7 +481,10 @@ describe('AssessmentSweepPanel — tuning sweep', () => {...idle, status: 'cancelled', mode: 'tunings', settled: true, total: 3, completed: 1,});await act(async () => { await vi.advanceTimersByTimeAsync(6000); });-+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(1);+ expect(onRunningChange).toHaveBeenLastCalledWith(true);+ await receive('connect');+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(2);expect(onRunningChange).toHaveBeenLastCalledWith(false);vi.useRealTimers();});@@ -434,11 +511,12 @@ describe('AssessmentSweepPanel — tuning sweep', () => {});expect(onSweepFinished).toHaveBeenCalledTimes(1);- // The restore finishes; the poll is what observes it.- getLocalLlmAssessmentSweep.mockResolvedValue({+ // The restore finishes; its state event owns the final report refresh.+ await receive('localLlm:sweep:changed', {...idle, status: 'cancelled', mode: 'tunings', settled: true, total: 3, completed: 1,});await act(async () => { await vi.advanceTimersByTimeAsync(6000); });+ expect(getLocalLlmAssessmentSweep).toHaveBeenCalledTimes(1);expect(onSweepFinished).toHaveBeenCalledTimes(2);vi.useRealTimers();diff --git a/server/lib/README.md b/server/lib/README.mdindex 5c4850ea1a..67d0c55696 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -27,7 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. || `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |-| `socketEventContracts.js` | Runtime-backed payload contracts for modeled inbound Socket.IO events, reusing the same Zod schemas as live validation. |+| `socketEventContracts.js` | Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots. || `socketEventInventory.js` | Cached source-derived Socket.IO event inventory: event names and directions only, with no checked-in manifest or positional source metadata. || `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. || `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 498a65fe7a..49edec6a7e 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -1,4 +1,4 @@-/** Runtime-backed payload contracts for modeled client-to-server Socket.IO events. */+/** Runtime-backed payload contracts for modeled Socket.IO events. */import { zodToOpenApiSchema } from './apiContractSchemas.js';import {@@ -34,6 +34,41 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({'iterm:attach': input(itermSessionRefSchema, 'Start viewing one live iTerm2 session.'),'iterm:detach': input(itermSessionRefSchema, 'Stop viewing one live iTerm2 session.'),'iterm:input': input(itermInputSchema, 'Type bytes into one live iTerm2 session.'),+ 'localLlm:sweep:changed': Object.freeze({+ direction: 'server-to-client',+ summary: 'Public assessment sweep snapshot after a queue state change, including cancellation and final runtime restoration.',+ payloadSchema: {+ type: 'object',+ required: ['status', 'settled', 'total', 'completed', 'results', 'cancelRequested'],+ properties: {+ status: { type: 'string', enum: ['idle', 'running', 'cancelled', 'failed', 'complete'] },+ mode: { type: 'string', nullable: true, enum: ['models', 'tunings'] },+ scope: { type: 'string', nullable: true },+ target: { type: 'object', nullable: true, properties: { backend: { type: 'string' }, modelId: { type: 'string' } } },+ settled: { type: 'boolean' },+ startedAt: { type: 'string', nullable: true },+ finishedAt: { type: 'string', nullable: true },+ total: { type: 'integer' },+ completed: { type: 'integer' },+ current: { type: 'object', nullable: true, properties: {+ backend: { type: 'string' }, modelId: { type: 'string' },+ tuningLabel: { type: 'string', nullable: true }, startedAt: { type: 'string' },+ } },+ results: { type: 'array', items: { type: 'object', properties: {+ backend: { type: 'string' }, modelId: { type: 'string' },+ tuningLabel: { type: 'string', nullable: true }, finishedAt: { type: 'string' },+ verdict: { type: 'string', nullable: true }, error: { type: 'string', nullable: true },+ meanTokensPerSecond: { type: 'number', nullable: true }, meanCharsPerSecond: { type: 'number', nullable: true },+ tokensEstimated: { type: 'boolean', nullable: true }, tuningApplied: { type: 'boolean', nullable: true },+ tuningNotApplied: { type: 'string', nullable: true },+ } } },+ cancelRequested: { type: 'boolean' },+ error: { type: 'string', nullable: true },+ restoreError: { type: 'string', nullable: true },+ },+ additionalProperties: false,+ },+ }),'logs:subscribe': input(logsSubscribeSchema, 'Subscribe to a bounded process-log tail.'),'logs:unsubscribe': input(logsUnsubscribeSchema, 'Release one process-log subscription or all legacy subscriptions.'),'shell:attach': input(shellAttachSchema, 'Attach this socket to an existing terminal session.'),diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex f46f546aff..4773fcf435 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -807,6 +807,7 @@ router.post('/assessments/sweep', asyncHandler(async (req, res) => {const status = await startSweep({scope, contextTokens, backend, modelId, tunings,onProgress: (frame) => io?.emit('localLlm:progress', frame),+ onChange: (state) => io?.emit('localLlm:sweep:changed', state),})// A refused start (one already running, or nothing to measure) is a 409, not a// silent no-op that would leave the page waiting for progress that never comes.@@ -815,7 +816,7 @@ router.post('/assessments/sweep', asyncHandler(async (req, res) => {}))// GET /api/local-llm/assessments/sweep — queue status. Module state only, zero-// LLM calls, so the page can poll it and a reload can pick a running sweep back up.+// LLM calls; mount, reconnect and tab re-show reconcile missed state events here.router.get('/assessments/sweep', asyncHandler(async (_req, res) => {res.json(getSweepStatus())}))diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex 840977da62..b2ead68c29 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -680,9 +680,10 @@ describe('measured assessments wiring', () => {expect(res.status).toBe(409);});- it('forwards sweep progress to the shared localLlm:progress socket event', async () => {- startSweep.mockImplementation(async ({ onProgress }) => {+ it('forwards sweep progress and public queue snapshots to their socket events', async () => {+ startSweep.mockImplementation(async ({ onProgress, onChange }) => {onProgress({ scope: 'assessment-sweep', event: 'start', total: 2, completed: 0 });+ onChange({ status: 'running', settled: false, total: 2, completed: 0, results: [], cancelRequested: false });return { status: 'running', total: 2, completed: 0 };});const app = makeApp();@@ -691,6 +692,9 @@ describe('measured assessments wiring', () => {expect(app.get('io').emit).toHaveBeenCalledWith('localLlm:progress', {scope: 'assessment-sweep', event: 'start', total: 2, completed: 0,});+ expect(app.get('io').emit).toHaveBeenCalledWith('localLlm:sweep:changed', {+ status: 'running', settled: false, total: 2, completed: 0, results: [], cancelRequested: false,+ });});// `tunings` is the ASK, not the grid — the service decides which knob sets adiff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.jsindex 02b57c0557..0c61b2c355 100644--- a/server/services/localModelAssessmentSweep.js+++ b/server/services/localModelAssessmentSweep.js@@ -33,7 +33,7 @@* - `startSweep()` is reachable only from `POST /api/local-llm/assessments/sweep`,* behind a consent gate that names the exact measurement count (models, or* tuning variants) and the total generation count.- * - `getSweepStatus()` reads module state only. Zero LLM calls, safe to poll.+ * - `getSweepStatus()` reads module state only. Zero LLM calls, safe to reconcile.** The prohibition the single-model service states — "no scheduler, no boot hook,* no background sweep" — is about work the user did not ask for. This IS the ask:@@ -131,8 +131,8 @@ function snapshot() {completed: sweep.results.length,// Which model is being measured right now — `null` between models and once// the sweep ends.- current: sweep.current,- results: sweep.results,+ current: sweep.current ? { ...sweep.current } : null,+ results: sweep.results.map((result) => ({ ...result })),cancelRequested: sweep.cancelRequested,error: sweep.error || null,// A sweep whose MEASUREMENTS all landed but whose daemon could not be put@@ -218,6 +218,7 @@ export function cancelSweep() {// screen for a queue that is already winding down. The `finally` re-affirms// `cancelled` (it reads the same flag), so the two cannot disagree.sweep.status = 'cancelled';+ sweep.notifyChange();console.log(`🛑 Local LLM: assessment sweep cancelled after ${sweep.results.length}/${sweep.total}`);return snapshot();}@@ -245,6 +246,7 @@ async function runSweepLoop(run, targets, contextTokens, emit) {for (const target of targets) {if (run.cancelRequested) break;run.current = { backend: target.backend, modelId: target.modelId, tuningLabel: target.tuningLabel, startedAt: nowIso() };+ run.notifyChange();emit({scope: 'assessment-sweep',event: 'model-start',@@ -289,7 +291,10 @@ async function runSweepLoop(run, targets, contextTokens, emit) {run.current = null;// A cancelled run recorded nothing, so it is not a result — recording it as// one would make a stopped sweep look like it measured what it abandoned.- if (result?.cancelled) break;+ if (result?.cancelled) {+ run.notifyChange();+ break;+ }run.results.push({backend: target.backend,modelId: target.modelId,@@ -311,6 +316,7 @@ async function runSweepLoop(run, targets, contextTokens, emit) {tuningApplied: typeof result?.tuningApplied === 'boolean' ? result.tuningApplied : null,tuningNotApplied: result?.tuningNotApplied || null,});+ run.notifyChange();}}@@ -338,10 +344,11 @@ async function runSweepLoop(run, targets, contextTokens, emit) {* of measuring it under the tuning it already carries* @param {number[]} [options.contextTokens] passed through to each measurement* @param {(frame: object) => void} [options.onProgress] forwarded to the socket+ * @param {(state: object) => void} [options.onChange] public queue snapshots on state changes* @returns {Promise<object>} the initial snapshot, or `{ rejected }` when a* sweep is already running or the request covers nothing*/-export async function startSweep({ scope = 'unmeasured', backend, modelId, tunings = false, contextTokens, onProgress } = {}) {+export async function startSweep({ scope = 'unmeasured', backend, modelId, tunings = false, contextTokens, onProgress, onChange } = {}) {if (sweep?.status === 'running' || startingSweep) return { ...snapshot(), rejected: 'a sweep is already running' };// A CANCELLED sweep is not finished with the machine: its last measurement is// still aborting and it may have a launch configuration to put back. Starting@@ -355,13 +362,13 @@ export async function startSweep({ scope = 'unmeasured', backend, modelId, tunin// was refused and the slot is free again.startingSweep = true;try {- return await beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress });+ return await beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress, onChange });} finally {startingSweep = false;}}-async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress }) {+async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress, onChange }) {const resolvedScope = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';const named = backend && modelId ? { backend, modelId } : null;@@ -479,8 +486,15 @@ async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onPsettled: false,launchStates,controller: new AbortController(),+ notifyChange: () => {+ if (sweep !== run || typeof onChange !== 'function') return;+ // Socket delivery must not abort the user's running measurements.+ try { onChange(snapshot()); }+ catch (err) { console.error(`❌ Local LLM: sweep state listener failed: ${err.message}`); }+ },};sweep = run;+ run.notifyChange();// A tuning sweep measures ONE thing many ways, so counting "models" would be// wrong in exactly the place the user is reading for reassurance.@@ -526,6 +540,7 @@ async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onP// A queue the user already replaced has nothing to report — emitting its// terminal frame would tell the page the CURRENT sweep just finished.if (sweep !== run) return;+ run.notifyChange();emit({scope: 'assessment-sweep',event: 'complete',diff --git a/server/services/localModelAssessmentSweep.test.js b/server/services/localModelAssessmentSweep.test.jsindex 9973ccee05..fb4b11dad1 100644--- a/server/services/localModelAssessmentSweep.test.js+++ b/server/services/localModelAssessmentSweep.test.js@@ -57,7 +57,8 @@ describe('startSweep', () => {}));runAssessment.mockResolvedValue(measured());- const started = await startSweep({ scope: 'unmeasured' });+ const changes = [];+ const started = await startSweep({ scope: 'unmeasured', onChange: (state) => changes.push(state) });expect(started.status).toBe('running');expect(started.total).toBe(2);@@ -68,6 +69,20 @@ describe('startSweep', () => {expect(status.results[0].meanTokensPerSecond).toBe(42);// Sequential by design — two models at once would measure the contention.expect(runAssessment).toHaveBeenCalledTimes(2);+ expect(changes.map((state) => [state.status, state.completed, state.current?.modelId ?? null, state.settled])).toEqual([+ ['running', 0, null, false],+ ['running', 0, 'a', false],+ ['running', 1, null, false],+ ['running', 1, 'b', false],+ ['running', 2, null, false],+ ['complete', 2, null, true],+ ]);+ expect(changes[0].results).toEqual([]);+ for (const state of changes) {+ expect(state).not.toHaveProperty('controller');+ expect(state).not.toHaveProperty('notifyChange');+ expect(state).not.toHaveProperty('launchStates');+ }});it('passes each target\'s recorded tuning through, so a re-measure reproduces it', async () => {@@ -212,7 +227,7 @@ describe('startSweep', () => {getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));runAssessment.mockResolvedValue(measured());- await startSweep({ scope: 'unmeasured', onProgress: () => { throw new Error('socket closed'); } });+ await startSweep({ scope: 'unmeasured', onProgress: () => { throw new Error('socket closed'); }, onChange: () => { throw new Error('socket closed'); } });await settle();expect(getSweepStatus().status).toBe('complete');});@@ -600,19 +615,25 @@ describe('startSweep — the tuning dimension', () => {// `settled` outlasts `status`: the page keeps its per-model actions disabled// while a stopped sweep is still aborting and still restoring.- it('reports itself unsettled until the queue and the restore are both done', async () => {+ it('pushes cancellation immediately and settlement only after restoring the runtime', async () => {onlyTarget();let releaseRun;+ let releaseRestore;+ const changes = [];runAssessment.mockImplementationOnce(() => new Promise((resolve) => { releaseRun = resolve; }));+ restoreLaunchState.mockImplementationOnce(() => new Promise((resolve) => { releaseRestore = resolve; }));- await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await startSweep({ backend: 'llama', modelId: 'target', tunings: true, onChange: (state) => changes.push(state) });cancelSweep();- expect(getSweepStatus().status).toBe('cancelled');- expect(getSweepStatus().settled).toBe(false);-+ expect(changes.at(-1)).toMatchObject({ status: 'cancelled', settled: false, cancelRequested: true });releaseRun({ cancelled: true });await settle();- expect(getSweepStatus().settled).toBe(true);+ expect(restoreLaunchState).toHaveBeenCalled();+ expect(changes.at(-1).settled).toBe(false);+ releaseRestore({ restored: true });+ await settle();+ expect(changes.at(-1)).toMatchObject({ status: 'cancelled', settled: true, current: null });+ expect(changes.filter((state) => state.settled)).toHaveLength(1);});// The measurements all landed, so the sweep did not fail — but the runtime is