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
feat: sweep one local model across a grid of tunings and rank the winner (#4745)
[._.]/ Adam Eivy7cdac92846a2
diff --git a/client/src/components/settings/AssessmentSweepPanel.jsx b/client/src/components/settings/AssessmentSweepPanel.jsxindex bdcb4d7aea..932e1f18e9 100644--- a/client/src/components/settings/AssessmentSweepPanel.jsx+++ b/client/src/components/settings/AssessmentSweepPanel.jsx@@ -1,5 +1,5 @@/**- * "Measure every model" — the overnight sweep control.+ * "Measure every model" / "Sweep tunings" — the sweep controls.** Measuring one model takes minutes, so measuring all of them is something you* start at the end of the day. Two consequences shape this component:@@ -11,12 +11,18 @@* 2. **Consent names real numbers.** The AI Provider Usage Policy (root* CLAUDE.md) requires that a batch of provider calls be preceded by a gate* that says exactly what will run. The counts come from the server's own- * target selector, not from a client-side estimate, so the number shown is- * the number that executes.+ * target selector and its own tuning grid, not from a client-side estimate,+ * so the number shown is the number that executes.+ *+ * Both sweeps live here rather than one each next to its trigger: the server+ * runs ONE queue, so two panels would each render a Stop button for a run the+ * other one started. The tuning sweep is therefore requested through a prop+ * (`tuningRequest`) from wherever its button sits, and this component owns the+ * consent gate, the progress, and the results for both.*/import { useCallback, useEffect, useRef, useState } from 'react';-import { PlayCircle, Square, AlertTriangle, CheckCircle2 } from 'lucide-react';+import { PlayCircle, Square, AlertTriangle, CheckCircle2, SlidersHorizontal } from 'lucide-react';import Modal from '../ui/Modal';import ProgressBar from '../ui/ProgressBar';import BrailleSpinner from '../BrailleSpinner';@@ -43,17 +49,72 @@ const POLL_MS = 5000;const isRunning = (status) => status?.status === 'running';-function SweepConsentModal({ scope, onScopeChange, counts, contextTokens, onCancel, onConfirm, starting }) {- const count = counts?.[scope] ?? 0;- const generations = count * Math.max(1, contextTokens.length);+// A tuning sweep measures ONE model many ways, so "3/5 models measured" is wrong+// in exactly the place the user is reading for reassurance. The server says+// which dimension it is varying; this is not inferable from the counts.+const measuredUnit = (status) => (status?.mode === 'tunings' ? 'tuning' : 'model');++/**+ * The consent gate both sweeps share: the card, the heading, and the+ * Cancel/Start footer.+ *+ * The AI Provider Usage Policy (root CLAUDE.md) demands the same three things of+ * either sweep — say what will run, say how many generations that is, and let+ * the user decline — so the parts that differ are only which middle the caller+ * fills in and which numbers it names. Two copies of this shell would drift, and+ * the half that drifted would be the half stating the cost.+ */+function SweepConsentShell({ icon, title, ariaLabel, children, onCancel, onConfirm, starting, confirmDisabled }) {return (- <Modal open onClose={onCancel} size="sm" ariaLabel="Measure every local model">+ <Modal open onClose={onCancel} size="sm" ariaLabel={ariaLabel}><div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4"><div className="flex items-center gap-2">- <PlayCircle size={18} className="text-port-accent" />- <h3 className="text-white font-medium">Measure every model?</h3>+ {icon}+ <h3 className="text-white font-medium">{title}</h3></div>+ {children}++ <div className="flex gap-3 pt-1">+ <button+ onClick={onCancel}+ disabled={starting}+ className="flex-1 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ Cancel+ </button>+ <button+ onClick={onConfirm}+ disabled={starting || confirmDisabled}+ className="flex-1 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-port-on-accent text-sm font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"+ >+ {starting ? <><BrailleSpinner /> Starting…</> : <>Start sweep</>}+ </button>+ </div>+ </div>+ </Modal>+ );+}++// How many generations a sweep of N measurements runs: one per context length,+// per measurement. The consent copy leads with this number, so both gates+// compute it the same way.+const generationsFor = (count, contextTokens) => count * Math.max(1, contextTokens.length);++function SweepConsentModal({ scope, onScopeChange, counts, contextTokens, onCancel, onConfirm, starting }) {+ const count = counts?.[scope] ?? 0;+ const generations = generationsFor(count, contextTokens);+ return (+ <SweepConsentShell+ icon={<PlayCircle size={18} className="text-port-accent" />}+ title="Measure every model?"+ ariaLabel="Measure every local model"+ starting={starting}+ confirmDisabled={count === 0}+ onCancel={onCancel}+ onConfirm={onConfirm}+ >+ <><fieldset className="space-y-2"><legend className="text-xs text-gray-400 mb-1">What to measure</legend>{SCOPES.map((option) => {@@ -92,25 +153,61 @@ function SweepConsentModal({ scope, onScopeChange, counts, contextTokens, onCancthis a job for overnight — expect several minutes per model. It keeps running with this tab closed,and you can stop it at any point; everything measured up to then is kept.</p>+ </>+ </SweepConsentShell>+ );+}- <div className="flex gap-3 pt-1">- <button- onClick={onCancel}- disabled={starting}- className="flex-1 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- Cancel- </button>- <button- onClick={onConfirm}- disabled={starting || count === 0}- className="flex-1 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-port-on-accent text-sm font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"- >- {starting ? <><BrailleSpinner /> Starting…</> : <>Start sweep</>}- </button>+/**+ * Consent for a TUNING sweep: one model, many launch configurations.+ *+ * The copy has to carry three numbers the user cannot see anywhere else — how+ * many variants, how many generations in total, and that the runtime is+ * restarted between each one, which is what makes a tuning sweep slower per+ * measurement than a model sweep.+ */+function TuningSweepConsentModal({ target, contextTokens, onCancel, onConfirm, starting }) {+ const variants = target.variants;+ const count = variants.length;+ const generations = generationsFor(count, contextTokens);+ return (+ <SweepConsentShell+ icon={<SlidersHorizontal size={18} className="text-port-accent" />}+ title="Sweep tunings?"+ ariaLabel={`Sweep tunings for ${target.modelId}`}+ starting={starting}+ // The baseline alone is one measurement with nothing to compare it to —+ // the server refuses that, and the gate must not offer it either.+ confirmDisabled={count < 2}+ onCancel={onCancel}+ onConfirm={onConfirm}+ >+ <>+ <p className="text-sm text-gray-400">+ PortOS will measure <span className="text-gray-200 font-mono break-all">{target.modelId}</span> under{' '}+ <span className="text-gray-200">{count}</span> configuration{count === 1 ? '' : 's'} —{' '}+ <span className="text-gray-200">{generations}</span> short generation{generations === 1 ? '' : 's'} in+ total, one at each of {contextTokens.map(formatContextTokens).join(', ')} tokens of context per+ configuration.+ </p>++ <div className="border border-port-border rounded-lg divide-y divide-port-border">+ {variants.map((variant) => (+ <p key={variant.key} className="px-2.5 py-1.5 text-[11px] text-gray-300">+ {/* An unlabelled variant is the baseline, and saying so matters:+ it is the reading every other one is compared against. */}+ {variant.label || 'Backend defaults'}+ </p>+ ))}</div>- </div>- </Modal>++ <p className="text-xs text-gray-500">+ One configuration at a time, and {target.runtimeLabel} is restarted between each one so the new flags+ actually take effect — expect several minutes per configuration. It keeps running with this tab closed,+ and you can stop it at any point; everything measured up to then is kept and ranked.+ </p>+ </>+ </SweepConsentShell>);}@@ -118,16 +215,33 @@ function SweepConsentModal({ scope, onScopeChange, counts, contextTokens, onCancfunction SweepResultRow({ result }) {const failed = Boolean(result.error) || result.verdict === 'does-not-fit' || result.verdict === 'incompatible';return (- <div className="flex items-center gap-2 text-[11px] flex-wrap">- {failed- ? <AlertTriangle size={11} className="text-port-warning shrink-0" />- : <CheckCircle2 size={11} className="text-emerald-400 shrink-0" />}- <span className="text-gray-300 font-mono break-all min-w-0">{result.modelId}</span>- {/* The tokens/s figure is the headline of a sweep, so it leads where the- runtime reported one; chars/s is the fallback, never both. */}- <span className="text-gray-500">- {result.error || [result.verdict, throughputLabel(result)].filter(Boolean).join(' — ')}- </span>+ <div className="text-[11px]">+ <div className="flex items-center gap-2 flex-wrap">+ {failed+ ? <AlertTriangle size={11} className="text-port-warning shrink-0" />+ : <CheckCircle2 size={11} className="text-emerald-400 shrink-0" />}+ <span className="text-gray-300 font-mono break-all min-w-0">{result.modelId}</span>+ {/* Every row of a TUNING sweep names the same model, so the+ configuration is what tells two measurements apart. Shown for a model+ sweep too: "backend defaults" is a real answer, and leaving it out+ would read as an unknown configuration. */}+ <span className="px-1.5 py-0.5 rounded border border-port-border text-gray-500 shrink-0">+ {result.tuningLabel || 'backend defaults'}+ </span>+ {/* The tokens/s figure is the headline of a sweep, so it leads where the+ runtime reported one; chars/s is the fallback, never both. */}+ <span className="text-gray-500">+ {result.error || [result.verdict, throughputLabel(result)].filter(Boolean).join(' — ')}+ </span>+ </div>+ {/* The numbers above describe SOME OTHER configuration when the knobs+ never reached the daemon — say so rather than filing them under the+ tuning the row is labelled with. */}+ {result.tuningApplied === false && result.tuningNotApplied && (+ <p className="text-port-warning mt-0.5">+ Tuning not applied — {result.tuningNotApplied}. These numbers describe the configuration that was running.+ </p>+ )}</div>);}@@ -140,8 +254,15 @@ function SweepResultRow({ result }) {* @param {(running: boolean) => void} [props.onRunningChange] lets the parent* disable its own per-model Measure buttons while the queue holds the provider* @param {boolean} props.disabled a single-model run is already occupying the provider+ * @param {{backend:string, modelId:string, runtimeLabel:string, variants:Array<{key:string,label:string|null}>}|null} [props.tuningRequest]+ * a "sweep tunings" request raised elsewhere on the page — opens this panel's+ * tuning consent gate. `null` closes it.+ * @param {() => void} [props.onTuningRequestClose] clears that request, whether+ * it was confirmed or cancelled*/-export default function AssessmentSweepPanel({ counts, contextTokens = [], onSweepFinished, onRunningChange, disabled }) {+export default function AssessmentSweepPanel({+ counts, contextTokens = [], onSweepFinished, onRunningChange, disabled, tuningRequest, onTuningRequestClose,+}) {const [status, setStatus] = useState(null);const [showConsent, setShowConsent] = useState(false);const [scope, setScope] = useState('unmeasured');@@ -180,7 +301,13 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe// 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// parent so its per-model buttons go quiet for the duration.- useEffect(() => { onRunningChange?.(running); }, [running, onRunningChange]);+ //+ // `settled: false` outlasts `running`: a STOPPED sweep is still aborting its+ // last measurement and, for a tuning sweep, still has a launch configuration+ // to put back — which bounces the daemon. Re-enabling Measure the moment Stop+ // is pressed would let a reading start into that relaunch and record it.+ 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@@ -194,9 +321,18 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSweuseAutoRefetch(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.- if (next && !isRunning(next)) notifyFinished();- }, POLL_MS, { enabled: running, immediate: false, pollOnly: true });+ // 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@@ -221,7 +357,7 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe...prev,completed: frame.completed ?? prev.completed,total: frame.total ?? prev.total,- current: { backend: frame.backend, modelId: frame.modelId },+ current: { backend: frame.backend, modelId: frame.modelId, tuningLabel: frame.tuningLabel ?? null },} : prev));}};@@ -238,11 +374,31 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwereturn next;}, { errorMessage: 'Could not start the sweep' });+ // 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 next = await startLocalLlmAssessmentSweep({+ backend: tuningRequest.backend,+ modelId: tuningRequest.modelId,+ tunings: true,+ });+ setStatus(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());// Whatever it measured before stopping is real evidence, so the report has// to catch up rather than waiting for the next mount.- notifyFinished();+ //+ // Deliberately NOT through `notifyFinished`: latching here 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.+ finishedRef.current?.();return true;}, { errorMessage: 'Could not stop the sweep' });@@ -271,8 +427,16 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe) : (<buttononClick={openConsent}- disabled={disabled || totalTargets === 0}- title={totalTargets === 0 ? 'No models are listable to measure right now' : 'Measure every installed model, one after another'}+ // The server refuses a sweep while the last one is winding down, so+ // an enabled button here would just collect a 409. Stop replaces+ // itself with this button several minutes before the machine is+ // actually free.+ disabled={disabled || holdsMachine || totalTargets === 0}+ title={+ holdsMachine ? 'The last sweep is still winding down — putting the runtime back the way it was'+ : totalTargets === 0 ? 'No models are listable to measure right now'+ : 'Measure every installed model, one after another'+ }className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent hover:bg-port-accent/80 text-port-on-accent font-medium transition-colors disabled:opacity-50"><PlayCircle size={13} /> Measure all models@@ -281,13 +445,20 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe{running && (<span className="text-[11px] text-gray-400 flex items-center gap-1.5" aria-live="polite"><BrailleSpinner />- {status.completed}/{status.total} measured- {status.current && <span className="text-gray-500 font-mono break-all">· {status.current.modelId}</span>}+ {status.completed}/{status.total} {measuredUnit(status)}s measured+ {status.current && (+ <span className="text-gray-500 font-mono break-all">+ {/* Every step of a tuning sweep names the same model, so the+ configuration is the only thing that moves. */}+ · {status.mode === 'tunings' ? (status.current.tuningLabel || 'backend defaults') : status.current.modelId}+ </span>+ )}</span>)}{finished && (<span className="text-[11px] text-gray-500">- Last sweep {status.status} — {status.completed}/{status.total} measured {timeAgo(status.finishedAt, '')}+ Last sweep {status.status} — {status.completed}/{status.total} {measuredUnit(status)}s measured{' '}+ {status.target ? `of ${status.target.modelId} ` : ''}{timeAgo(status.finishedAt, '')}</span>)}</div>@@ -298,7 +469,7 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe<ProgressBarpercent={(status.completed / status.total) * 100}track="border"- label={`Sweep progress: ${status.completed} of ${status.total} models measured`}+ label={`Sweep progress: ${status.completed} of ${status.total} ${measuredUnit(status)}s measured`}/>)}{message && <p className="text-[11px] text-gray-400 break-words" aria-live="polite">{message}</p>}@@ -329,6 +500,30 @@ export default function AssessmentSweepPanel({ counts, contextTokens = [], onSwe</p>)}+ {/* The measurements landed, so the sweep did not fail — but the launch+ configuration it started from is gone, and nothing else on this page+ would say so. Deliberately does NOT assert what the runtime is doing+ now: the daemon may be on the last variant, or stopped (a launch line a+ sweep tried can fail, and so can putting the old one back). Naming the+ reason and pointing at the page that shows the truth beats guessing. */}+ {status?.restoreError && (+ <p className="text-xs text-port-warning flex items-center gap-1.5" role="alert">+ <AlertTriangle size={12} />+ The sweep finished, but the launch configuration it started from was not restored:{' '}+ {status.restoreError}. Check the runtime on the LLMs page.+ </p>+ )}++ {tuningRequest && (+ <TuningSweepConsentModal+ target={tuningRequest}+ contextTokens={contextTokens}+ starting={startingTuning}+ onCancel={() => onTuningRequestClose?.()}+ onConfirm={startTuning}+ />+ )}+{showConsent && (<SweepConsentModalscope={scope}diff --git a/client/src/components/settings/AssessmentSweepPanel.test.jsx b/client/src/components/settings/AssessmentSweepPanel.test.jsxindex 2ee2af01df..230acf94db 100644--- a/client/src/components/settings/AssessmentSweepPanel.test.jsx+++ b/client/src/components/settings/AssessmentSweepPanel.test.jsx@@ -88,7 +88,7 @@ describe('AssessmentSweepPanel', () => {});renderPanel();- expect(await screen.findByText(/2\/5 measured/)).toBeInTheDocument();+ expect(await screen.findByText(/2\/5 models measured/)).toBeInTheDocument();expect(screen.getByText(/example-model:14b/)).toBeInTheDocument();expect(screen.getByRole('button', { name: /stop sweep/i })).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Measure all models' })).not.toBeInTheDocument();@@ -150,7 +150,7 @@ describe('AssessmentSweepPanel', () => {it('subscribes to the shared progress event and filters out unrelated frames', async () => {getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 2, completed: 0 });renderPanel();- await screen.findByText(/0\/2 measured/);+ await screen.findByText(/0\/2 models measured/);const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')[1];// A model PULL streams on the same event, in the shape the install route@@ -169,7 +169,7 @@ describe('AssessmentSweepPanel', () => {const onSweepFinished = vi.fn();getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 2, completed: 1 });renderPanel({ onSweepFinished });- await screen.findByText(/1\/2 measured/);+ 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];@@ -188,3 +188,284 @@ describe('AssessmentSweepPanel', () => {expect(await screen.findByRole('button', { name: 'Measure all models' })).toBeDisabled();});});++describe('AssessmentSweepPanel — tuning sweep', () => {+ const tuningRequest = {+ backend: 'llama',+ modelId: 'example-model.gguf',+ runtimeLabel: 'llama.cpp',+ variants: [+ { key: '', label: null },+ { key: 'flashAttn=true', label: 'Flash attention on' },+ { key: 'ubatchSize=1024', label: 'Micro-batch size 1024' },+ ],+ };++ // The AI Provider Usage Policy gate, in the shape a tuning sweep needs it: the+ // variant count and the total generation count are numbers the user cannot+ // read anywhere else before committing hours of GPU.+ it('names the variant count, the generation count, and every configuration', async () => {+ renderPanel({ tuningRequest });++ expect(await screen.findByText(/Sweep tunings\?/)).toBeInTheDocument();+ expect(startLocalLlmAssessmentSweep).not.toHaveBeenCalled();+ // 3 variants × 3 context lengths = 9 generations.+ expect(screen.getByText('3')).toBeInTheDocument();+ expect(screen.getByText('9')).toBeInTheDocument();+ expect(screen.getByText(/short generations in total/)).toBeInTheDocument();+ expect(screen.getByText('Flash attention on')).toBeInTheDocument();+ expect(screen.getByText('Micro-batch size 1024')).toBeInTheDocument();+ });++ // An unlabelled variant is the baseline, and saying so matters — it is the+ // reading every other one is compared against.+ it('names the unlabelled variant as the backend defaults', async () => {+ renderPanel({ tuningRequest });+ expect(await screen.findByText('Backend defaults')).toBeInTheDocument();+ });++ // Ollama and LM Studio bounce their daemon between variants. A user who does+ // not know that reads the restarts as the sweep crashing.+ it('warns that the runtime restarts between configurations', async () => {+ renderPanel({ tuningRequest });+ expect(await screen.findByText(/llama\.cpp is restarted between each one/)).toBeInTheDocument();+ });++ it('asks the server for the grid rather than posting one', async () => {+ const user = userEvent.setup();+ startLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 3 });+ const onTuningRequestClose = vi.fn();+ renderPanel({ tuningRequest, onTuningRequestClose });++ await user.click(await screen.findByRole('button', { name: /start sweep/i }));++ await waitFor(() => expect(startLocalLlmAssessmentSweep).toHaveBeenCalledWith({+ backend: 'llama', modelId: 'example-model.gguf', tunings: true,+ }));+ expect(onTuningRequestClose).toHaveBeenCalled();+ });++ it('clears the request on cancel without queueing anything', async () => {+ const user = userEvent.setup();+ const onTuningRequestClose = vi.fn();+ renderPanel({ tuningRequest, onTuningRequestClose });++ await user.click(await screen.findByRole('button', { name: /^cancel$/i }));+ expect(onTuningRequestClose).toHaveBeenCalled();+ expect(startLocalLlmAssessmentSweep).not.toHaveBeenCalled();+ });++ // The baseline alone is one measurement with nothing to compare it to — the+ // server refuses it, and the gate must not offer it either.+ it('will not start a sweep with only the baseline in the grid', async () => {+ renderPanel({ tuningRequest: { ...tuningRequest, variants: [{ key: '', label: null }] } });+ expect(await screen.findByRole('button', { name: /start sweep/i })).toBeDisabled();+ });++ // Every step names the same model, so counting models — or printing the model+ // as the thing in flight — would read as one measurement repeating.+ it('counts tunings, not models, while a tuning sweep runs', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle,+ status: 'running',+ mode: 'tunings',+ target: { backend: 'llama', modelId: 'example-model.gguf' },+ total: 3,+ completed: 1,+ current: { backend: 'llama', modelId: 'example-model.gguf', tuningLabel: 'Flash attention on' },+ });+ renderPanel();++ expect(await screen.findByText(/1\/3 tunings measured/)).toBeInTheDocument();+ expect(screen.getByText(/Flash attention on/)).toBeInTheDocument();+ });++ it('names the model a finished tuning sweep was measuring', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle,+ status: 'complete',+ mode: 'tunings',+ target: { backend: 'llama', modelId: 'example-model.gguf' },+ total: 3,+ completed: 3,+ finishedAt: '2026-01-01T00:00:00.000Z',+ });+ renderPanel();++ expect(await screen.findByText(/3\/3 tunings measured of example-model\.gguf/)).toBeInTheDocument();+ });++ // Every row of a tuning sweep names the same model, so without the+ // configuration the results list reads as one measurement repeated.+ it('names the configuration on every finished measurement', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle,+ status: 'complete',+ mode: 'tunings',+ total: 2,+ completed: 2,+ results: [+ { backend: 'llama', modelId: 'example-model.gguf', tuningLabel: null, verdict: 'fits', meanCharsPerSecond: 120 },+ { backend: 'llama', modelId: 'example-model.gguf', tuningLabel: 'Flash attention on', verdict: 'fits', meanCharsPerSecond: 150 },+ ],+ });+ renderPanel();++ expect(await screen.findByText('backend defaults')).toBeInTheDocument();+ expect(screen.getByText('Flash attention on')).toBeInTheDocument();+ });++ // Numbers taken under a tuning that never reached the daemon describe some+ // OTHER configuration — presenting them under the label the row carries is+ // what a tuning comparison must never do.+ it('flags a measurement whose tuning never reached the daemon', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle,+ status: 'complete',+ mode: 'tunings',+ total: 1,+ completed: 1,+ results: [{+ backend: 'llama',+ modelId: 'example-model.gguf',+ tuningLabel: 'Flash attention on',+ verdict: 'fits',+ meanCharsPerSecond: 120,+ tuningApplied: false,+ tuningNotApplied: 'llama-server rejected that tuning',+ }],+ });+ renderPanel();++ expect(await screen.findByText(/Tuning not applied — llama-server rejected that tuning/)).toBeInTheDocument();+ });++ // A stopped sweep still holds the machine: its last measurement is aborting+ // and, for a tuning sweep, its launch configuration is still being put back —+ // a relaunch. A reading started into that would record the restart.+ it("keeps the parent per-model actions disabled until the sweep has let go", async () => {+ const onRunningChange = vi.fn();+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ renderPanel({ onRunningChange });++ await waitFor(() => expect(onRunningChange).toHaveBeenCalledWith(true));+ });++ it('releases them once the sweep has settled', async () => {+ const onRunningChange = vi.fn();+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'complete', mode: 'tunings', settled: true, total: 3, completed: 3,+ });+ renderPanel({ onRunningChange });++ await waitFor(() => expect(onRunningChange).toHaveBeenLastCalledWith(false));+ });++ // Stop replaces itself with "Measure all models" several minutes before the+ // machine is free, and the server refuses a sweep while the last one is+ // winding down — so an enabled button here would just collect a 409.+ it('will not let another sweep start while the last one is winding down', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ renderPanel();++ const button = await screen.findByRole('button', { name: 'Measure all models' });+ expect(button).toBeDisabled();+ expect(button).toHaveAttribute('title', expect.stringContaining('winding down'));+ });++ // 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 () => {+ vi.useFakeTimers();+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ const onRunningChange = vi.fn();+ renderPanel({ onRunningChange });+ await act(async () => { await Promise.resolve(); });++ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: true, total: 3, completed: 1,+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(6000); });++ expect(onRunningChange).toHaveBeenLastCalledWith(false);+ vi.useRealTimers();+ });++ // Stopping refreshes the report immediately (what it measured is real+ // evidence) — but the refresh that matters more is the one AFTER the restore,+ // once the runtime state on the page is the real one rather than a daemon+ // caught mid-relaunch. Latching on the first would swallow the second.+ it('re-reads the report again once a stopped sweep has finished winding down', async () => {+ vi.useFakeTimers();+ const onSweepFinished = vi.fn();+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'running', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ cancelLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ renderPanel({ onSweepFinished });+ await act(async () => { await Promise.resolve(); });++ await act(async () => {+ screen.getByRole('button', { name: /stop sweep/i }).click();+ await Promise.resolve();+ });+ expect(onSweepFinished).toHaveBeenCalledTimes(1);++ // The restore finishes; the poll is what observes it.+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: true, total: 3, completed: 1,+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(6000); });++ expect(onSweepFinished).toHaveBeenCalledTimes(2);+ vi.useRealTimers();+ });++ // Mid-wind-down the runtime is being relaunched, so a report read then+ // describes a daemon that is not the one the user will end up with.+ it('does not re-read the report while the sweep is still restoring', async () => {+ vi.useFakeTimers();+ const onSweepFinished = vi.fn();+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle, status: 'cancelled', mode: 'tunings', settled: false, total: 3, completed: 1,+ });+ renderPanel({ onSweepFinished });+ await act(async () => { await Promise.resolve(); });+ await act(async () => { await vi.advanceTimersByTimeAsync(6000); });++ expect(onSweepFinished).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ // A sweep that measured everything but could not put the daemon back is not a+ // failed sweep — and the user has to be told, because the runtime is now+ // serving a configuration they did not choose.+ it('says so when the launch configuration was not restored', async () => {+ getLocalLlmAssessmentSweep.mockResolvedValue({+ ...idle,+ status: 'complete',+ mode: 'tunings',+ total: 2,+ completed: 2,+ restoreError: 'llama-server is no longer PortOS-managed',+ });+ renderPanel();++ expect(await screen.findByText(/was not restored: llama-server is no longer PortOS-managed/))+ .toBeInTheDocument();+ });++ it('shows no tuning gate until one is requested', async () => {+ renderPanel();+ await screen.findByRole('button', { name: 'Measure all models' });+ expect(screen.queryByText(/Sweep tunings\?/)).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex d9838b9ae3..d2ed65c152 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -65,6 +65,14 @@ const backendLabel = (report, id) =>const specsFor = (report, id) => report?.runtimes?.find((r) => r.id === id)?.tuningSpecs || [];+// The tuning grid a sweep of this runtime would run, straight from the server —+// so the consent gate's count is the count that executes. Fewer than two entries+// means a sweep is not on offer: either the runtime declares no sweepable knob,+// or PortOS cannot reset it and put it back afterwards, and the server says so+// by shipping an empty grid. Either way the button stays off rather than+// advertising a comparison that would not be valid.+const gridFor = (report, id) => report?.runtimes?.find((r) => r.id === id)?.tuningGrid || [];+// An empty field means "leave the daemon on its own default", so it is dropped// rather than sent as 0/false — the server applies the same rule.const compactTuning = (draft) => Object.fromEntries(@@ -273,7 +281,7 @@ function AssessmentConsentModal({);}-function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, busy }) {+function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings, sweepVariants, busy }) {const perf = entry.performance || {};return (<div className="border border-port-border rounded-lg p-3 space-y-2">@@ -324,6 +332,20 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, busy }) {><RefreshCw size={13} /></button>+ {/* Only offered where the runtime declares a knob worth varying —+ a one-entry grid is the baseline alone, which `compareTunings`+ cannot rank against anything. */}+ {sweepVariants > 1 && (+ <button+ onClick={() => onSweepTunings(entry)}+ disabled={busy}+ title={`Measure this model under ${sweepVariants} launch configurations and rank them`}+ aria-label={`Sweep tunings for ${entry.modelId}`}+ className="p-1.5 text-gray-400 hover:text-white transition-colors disabled:opacity-50"+ >+ <SlidersHorizontal size={13} />+ </button>+ )}<buttononClick={() => onDelete(entry)}disabled={busy}@@ -492,6 +514,10 @@ export function LocalModelAssessments() {// Whether the server-side sweep is working. Owned here rather than in the// sweep panel because it gates this panel's per-model buttons too.const [sweepRunning, setSweepRunning] = useState(false);+ // A "sweep tunings" request handed to the sweep panel, which owns the consent+ // gate and the progress for BOTH sweeps — there is only one server-side queue,+ // so there is only one place that renders it.+ const [tuningSweepRequest, setTuningSweepRequest] = useState(null);const load = useCallback(async (nextIntent) => {setLoading(true);@@ -628,6 +654,16 @@ export function LocalModelAssessments() {setPendingTarget(entry);};+ // Hands the model to the sweep panel's consent gate. The grid rides along so+ // the modal can list what it is about to run — it is the server's own grid,+ // shipped on the report, not a count derived here.+ const requestTuningSweep = (entry) => setTuningSweepRequest({+ backend: entry.backend,+ modelId: entry.modelId,+ runtimeLabel: backendLabel(report, entry.backend),+ variants: gridFor(report, entry.backend),+ });+// A sweep holds the provider for hours. A single-model run started on top of// it would measure the contention between the two, so every per-model action// goes quiet while the queue is working.@@ -685,6 +721,8 @@ export function LocalModelAssessments() {disabled={localBusy}onRunningChange={setSweepRunning}onSweepFinished={() => load(intent)}+ tuningRequest={tuningSweepRequest}+ onTuningRequestClose={() => setTuningSweepRequest(null)}/><div className="flex items-center gap-2 flex-wrap">@@ -727,8 +765,10 @@ export function LocalModelAssessments() {entry={entry}runtimeLabel={backendLabel(report, entry.backend)}busy={busy}+ sweepVariants={gridFor(report, entry.backend).length}onRemeasure={openTarget}onDelete={removeAssessment}+ onSweepTunings={requestTuningSweep}/>))}</div>diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex 0b27cec5f2..8d8abe395b 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -23,7 +23,7 @@ vi.mock('../../services/socket', () => ({import {getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,- getLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,+ getLocalLlmAssessmentSweep, startLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,} from '../../services/api';import toast from '../ui/Toast';import socket from '../../services/socket';@@ -51,14 +51,22 @@ const report = (overrides = {}) => ({// catalog all ride on the report, so the panel has no hardcoded backend list to// drift from.const RUNTIMES = [- { id: 'ollama', label: 'Ollama', managed: true, modelCount: 1, error: null, tuningSpecs: [+ // `tuningGrid` is the server's own sweep grid, shipped so the consent gate+ // names the count that will actually run. It is EMPTY for a runtime a sweep+ // may not drive — Ollama cannot be reset and put back yet (#4763) — which is+ // what turns its "Sweep tunings" button off.+ { id: 'ollama', label: 'Ollama', managed: true, modelCount: 1, error: null, tuningGrid: [], tuningSpecs: [{ id: 'numCtx', label: 'Context size', type: 'number', applies: 'launch', env: 'OLLAMA_CONTEXT_LENGTH', min: 512, max: 1048576, unit: 'tokens', hint: 'The window every model loads with.', note: 'PortOS restarts the server with OLLAMA_CONTEXT_LENGTH set.' },] },- { id: 'llama', label: 'llama.cpp', managed: false, modelCount: 3, error: null, tuningSpecs: [+ { id: 'llama', label: 'llama.cpp', managed: false, modelCount: 3, error: null, tuningGrid: [+ { key: '', label: null, tuning: {} },+ { key: 'ubatchSize=1024', label: 'Micro-batch size 1024', tuning: { ubatchSize: 1024 } },+ { key: 'flashAttn=true', label: 'Flash attention on', tuning: { flashAttn: true } },+ ], tuningSpecs: [{ id: 'ubatchSize', label: 'Micro-batch size', type: 'number', applies: 'launch', config: true, min: 1, max: 8192, hint: 'Physical micro-batch.', note: "PortOS puts this on the server's launch line and relaunches it." },{ id: 'flashAttn', label: 'Flash attention', type: 'boolean', applies: 'launch', config: true, hint: 'Fused attention kernel.', note: "PortOS puts this on the server's launch line and relaunches it." },] },- { id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningSpecs: [+ { id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningGrid: [], tuningSpecs: [{ id: 'depth', label: 'MTP depth', type: 'number', applies: 'launch', cli: '--depth', min: 1, max: 8, hint: 'Draft lookahead.', note: 'PortOS relaunches `mtplx serve` with `--depth` on its command line.' },{ id: 'kvQuant', label: 'KV cache quantization', type: 'enum', applies: 'launch', cli: '--kv-quant', options: ['off', 'q8', 'q4'], hint: 'Context length for a little quality.', note: 'PortOS relaunches `mtplx serve` with `--kv-quant` on its command line.' },] },@@ -614,3 +622,63 @@ describe('LocalModelAssessments — one row per tuning', () => {expect(await screen.findByText(/Tuning was not applied/)).toBeInTheDocument();});});++describe('LocalModelAssessments — sweep tunings', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ idleSweep();+ getLocalLlmAssessments.mockResolvedValue(report());+ });++ const llamaEntry = (overrides = {}) => rankedEntry({ backend: 'llama', modelId: 'example-model.gguf', ...overrides });++ it('opens the tuning consent gate for the model whose button was pressed', async () => {+ const user = userEvent.setup();+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [llamaEntry()] }));+ render(<LocalModelAssessments />);++ await user.click(await screen.findByRole('button', { name: 'Sweep tunings for example-model.gguf' }));++ expect(await screen.findByText(/Sweep tunings\?/)).toBeInTheDocument();+ // The grid the server shipped, not a count derived here.+ expect(screen.getByText('Micro-batch size 1024')).toBeInTheDocument();+ expect(screen.getByText('Flash attention on')).toBeInTheDocument();+ expect(startLocalLlmAssessmentSweep).not.toHaveBeenCalled();+ });++ // The server ships an empty grid for a runtime a sweep may not drive, so the+ // page offers the action exactly where the server would accept it.+ it('offers no sweep for a runtime the server will not sweep', async () => {+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [rankedEntry()] }));+ render(<LocalModelAssessments />);++ await screen.findByText('example-model:7b');+ expect(screen.queryByRole('button', { name: /Sweep tunings for/ })).not.toBeInTheDocument();+ });++ it('starts the sweep the gate described', async () => {+ const user = userEvent.setup();+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [llamaEntry()] }));+ startLocalLlmAssessmentSweep.mockResolvedValue({ status: 'running', total: 3, completed: 0, results: [] });+ render(<LocalModelAssessments />);++ await user.click(await screen.findByRole('button', { name: 'Sweep tunings for example-model.gguf' }));+ await user.click(screen.getByRole('button', { name: /start sweep/i }));++ await waitFor(() => expect(startLocalLlmAssessmentSweep).toHaveBeenCalledWith({+ backend: 'llama', modelId: 'example-model.gguf', tunings: true,+ }));+ });++ // Every per-model action goes quiet while the server-side queue holds the+ // provider — a run started on top of it would measure the contention.+ it('goes quiet while a sweep is already running', async () => {+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [llamaEntry()] }));+ getLocalLlmAssessmentSweep.mockResolvedValue({+ status: 'running', total: 3, completed: 1, current: { backend: 'llama', modelId: 'example-model.gguf' }, results: [],+ });+ render(<LocalModelAssessments />);++ await waitFor(() => expect(screen.getByRole('button', { name: 'Sweep tunings for example-model.gguf' })).toBeDisabled());+ });+});diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex eaae796767..bf330a3d13 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -254,6 +254,12 @@ export const getLocalLlmAssessmentSweep = (options) =>// `scope` is 'unmeasured' | 'stale' | 'all'. 409s when a sweep is already// running or the scope covers nothing.+//+// For a TUNING sweep the payload is `{ backend, modelId, tunings: true }` —+// one model across the knob grid its runtime declares. `tunings` is the ASK,+// never the grid: the server derives which knob sets that means, and+// `report.runtimes[].tuningGrid` is that same list shipped for the consent gate+// to count. 409s when the runtime has no knob PortOS can sweep.export const startLocalLlmAssessmentSweep = (payload, options) =>request('/local-llm/assessments/sweep', { method: 'POST', body: JSON.stringify(payload), ...options });diff --git a/server/lib/README.md b/server/lib/README.mdindex b3cd9a08b7..c87720ba5f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -315,8 +315,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. || `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. || `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |-| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner). Pure. |-| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |+| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner), and `tuningGridFor` (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a `sweep` value, capped by `maxVariants`; `sweepWith` carries a knob's documented prerequisite). Pure. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. || `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/local.js` (paired with `services/loras.js#readTriggerWordsByFilename` for the sidecar reads). The comic pipeline shares it rather than opting out — its own "<Name> (<trigger>)" clause uses the same token, so the weave adds nothing there except for the characters that clause drops. || `issueLength.js` | Per-issue size targets fed into text stages. || `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.jsindex 27f685b34d..d63afc7125 100644--- a/server/lib/localModelAssessment.js+++ b/server/lib/localModelAssessment.js@@ -521,6 +521,16 @@ const targetKey = (t) => `${t.backend}:${t.modelId}@${t.tuningKey || ''}`;* reproduce the same configuration, or the sweep would quietly replace every* tuned reading with a backend-defaults one.*+ * ## The second dimension+ *+ * `tunings` swaps that rule out: instead of each model keeping the tuning it+ * carries, every model is crossed with the supplied grid — one measurement per+ * (model, tuning) pair. That is what makes a TUNING sweep a case of this+ * function rather than a queue of its own, and it is why the dedupe below is+ * keyed on model AND tuning: two variants sharing a key are one measurement, and+ * running it twice would put the same configuration on both sides of the+ * comparison table.+ ** @param {object} options* @param {Array<object>} options.assessments stored records, already filtered to* models that are STILL INSTALLED — a sweep must not queue a model the runtime@@ -528,10 +538,19 @@ const targetKey = (t) => `${t.backend}:${t.modelId}@${t.tuningKey || ''}`;* @param {Array<{backend:string, modelId:string}>} options.unassessed models with* no evidence at all* @param {'unmeasured'|'stale'|'all'} options.scope+ * @param {{backend:string, modelId:string}|null} [options.only] restrict to one+ * model. Naming a model leaves the scope nothing to decide, so it implies+ * `all` — otherwise "sweep THIS model" would silently do nothing whenever the+ * model happened to fall outside the scope.+ * @param {Array<{tuning:object, key:string, label:string|null}>|null} [options.tunings]+ * knob sets to measure every selected model under. Entries are taken as+ * already-normalized (they come from `localModelTuning.js#tuningGridFor`), so+ * this module stays dependency-free.* @returns {Array<{backend:string, modelId:string, tuning:object, tuningKey:string, tuningLabel:string|null, reason:string}>}*/-export function selectSweepTargets({ assessments = [], unassessed = [], scope = 'unmeasured' } = {}) {- const resolved = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';+export function selectSweepTargets({ assessments = [], unassessed = [], scope = 'unmeasured', only = null, tunings = null } = {}) {+ const resolved = only ? 'all' : (SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured');+ const wanted = (m) => !only || (m?.backend === only.backend && m?.modelId === only.modelId);const stored = Array.isArray(assessments) ? assessments : [];const fresh = Array.isArray(unassessed) ? unassessed : [];const targets = [];@@ -549,6 +568,7 @@ export function selectSweepTargets({ assessments = [], unassessed = [], scope =// the measurements worth having got.if (resolved === 'unmeasured' || resolved === 'all') {for (const model of fresh) {+ if (!wanted(model)) continue;add({ backend: model?.backend, modelId: model?.modelId, tuning: {}, tuningKey: '', tuningLabel: null, reason: 'never measured' });}}@@ -556,6 +576,7 @@ export function selectSweepTargets({ assessments = [], unassessed = [], scope =if (resolved === 'stale' || resolved === 'all') {for (const assessment of stored) {if (resolved === 'stale' && !assessment?.staleness?.stale) continue;+ if (!wanted(assessment)) continue;add({backend: assessment?.backend,modelId: assessment?.modelId,@@ -567,6 +588,29 @@ export function selectSweepTargets({ assessments = [], unassessed = [], scope =}}+ if (!Array.isArray(tunings) || tunings.length === 0) return targets;++ // Cross the selected models with the grid. Re-running `add` rather than+ // pushing directly keeps ONE dedupe rule for both dimensions — a model that+ // reached this point under two stored tunings collapses back to one entry per+ // grid variant instead of measuring each variant twice.+ const models = targets.splice(0, targets.length);+ seen.clear();+ for (const model of models) {+ for (const variant of tunings) {+ add({+ backend: model.backend,+ modelId: model.modelId,+ tuning: variant?.tuning && typeof variant.tuning === 'object' ? variant.tuning : {},+ tuningKey: variant?.key || '',+ tuningLabel: variant?.label ?? null,+ // `''` is the baseline — the reading every other variant's throughput is+ // reported relative to, so it is named rather than left blank.+ reason: variant?.key ? 'tuning variant' : 'backend defaults',+ });+ }+ }+return targets;}diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.jsindex 6d141057a8..0bba314b82 100644--- a/server/lib/localModelAssessment.test.js+++ b/server/lib/localModelAssessment.test.js@@ -695,6 +695,65 @@ describe('selectSweepTargets', () => {const targets = selectSweepTargets({ assessments: [stale], unassessed, scope: 'everything-please' });expect(targets.map((t) => t.modelId)).toEqual(['new-model']);});++ // ---- the second dimension ------------------------------------------------+ // `tunings` is what makes a TUNING sweep a case of this selector rather than a+ // queue of its own: same dedupe, same ordering, same consent-count guarantee.+ const grid = [+ { tuning: {}, key: '', label: null },+ { tuning: { flashAttn: true }, key: 'flashAttn=true', label: 'Flash attention on' },+ ];++ it('restricts the queue to the named model, whatever the scope would have picked', () => {+ const targets = selectSweepTargets({+ assessments: [stale, fresh], unassessed, scope: 'unmeasured',+ only: { backend: 'ollama', modelId: 'fresh-model' },+ });+ expect(targets.map((t) => t.modelId)).toEqual(['fresh-model']);+ });++ it('returns nothing for a model no record or listing names', () => {+ const targets = selectSweepTargets({+ assessments: [stale], unassessed, scope: 'all',+ only: { backend: 'ollama', modelId: 'ghost' },+ });+ expect(targets).toEqual([]);+ });++ it('crosses every selected model with the grid, one measurement per pair', () => {+ const targets = selectSweepTargets({ assessments: [], unassessed, scope: 'unmeasured', tunings: grid });+ expect(targets.map((t) => `${t.modelId}@${t.tuningKey}`))+ .toEqual(['new-model@', 'new-model@flashAttn=true']);+ });++ // The grid REPLACES each record's own tuning — that is the whole point of the+ // dimension. Keeping the stored tuning would measure the same configuration+ // under every variant's label.+ it('replaces a record\'s stored tuning with the grid variant', () => {+ const [baseline, variant] = selectSweepTargets({+ assessments: [stale], unassessed: [], scope: 'stale', tunings: grid,+ });+ expect(baseline.tuning).toEqual({});+ expect(baseline.tuningLabel).toBeNull();+ expect(variant.tuning).toEqual({ flashAttn: true });+ expect(variant.tuningLabel).toBe('Flash attention on');+ });++ // A model that reached the cross under two stored tunings is still ONE model:+ // measuring each variant twice would put the same configuration on both sides+ // of the comparison table.+ it('crosses a model held under several stored tunings only once', () => {+ const other = { ...stale, tuningKey: 'ctx=4096', tuning: { numCtx: 4096 } };+ const targets = selectSweepTargets({+ assessments: [stale, other], unassessed: [], scope: 'stale', tunings: grid,+ });+ expect(targets).toHaveLength(2);+ });++ it('leaves the queue alone for an empty grid rather than emptying it', () => {+ const targets = selectSweepTargets({ assessments: [], unassessed, scope: 'unmeasured', tunings: [] });+ expect(targets.map((t) => t.modelId)).toEqual(['new-model']);+ });});describe('summarizeSweepScopes', () => {diff --git a/server/lib/localModelTuning.js b/server/lib/localModelTuning.jsindex 1b331befc6..0fc5dbba05 100644--- a/server/lib/localModelTuning.js+++ b/server/lib/localModelTuning.js@@ -50,6 +50,15 @@* is kept because a runtime that does honour per-request knobs (vLLM) is the* likely next entry.*+ * ## Sweepable knobs (`sweep` / `sweepWith`)+ *+ * A knob may also name the values a machine-driven sweep should TRY:+ * `sweep: [value, …]` are the candidates, and `sweepWith: { otherKnob: value }`+ * names co-knobs the runtime requires for a candidate to take effect at all.+ * `tuningGridFor` builds the candidate grid from those fields — see its comment+ * for why the grid is one knob at a time and what a missing `sweep` means. A+ * knob with no `sweep` is simply never varied by a sweep.+ ** vLLM therefore declares no knobs: PortOS does not start it — it is a container* from the shipped compose stack, so there is no launch line to put a flag on.* Add knobs there once PortOS manages that container's lifecycle.@@ -141,11 +150,14 @@ const RAW_SPECS = {{ id: 'ctxSize', label: 'Context size', type: 'number', config: true, min: 512, max: 1048576, unit: 'tokens', hint: 'KV cache is allocated for the whole window up front — a larger one costs memory even when prompts are short.' },{ id: 'nGpuLayers', label: 'GPU layers', type: 'number', config: true, min: 0, max: 999, hint: 'Layers offloaded to the GPU. Fewer layers frees VRAM for a bigger context at the cost of throughput.' },{ id: 'parallel', label: 'Parallel slots', type: 'number', config: true, min: 1, max: 16, hint: 'Request slots llama-server reserves VRAM for. It divides the context window across them — 1 is right for a TUI agent (one long session). Raising it shrinks per-request context.' },- { id: 'batchSize', label: 'Batch size', type: 'number', config: true, min: 1, max: 8192, hint: 'Logical prompt batch (-b). Raising it speeds up prefill on long prompts and raises peak memory.' },- { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', config: true, min: 1, max: 8192, hint: 'Physical micro-batch (-ub). The single knob that most often moves long-context throughput.' },+ { id: 'batchSize', label: 'Batch size', type: 'number', config: true, min: 1, max: 8192, sweep: [4096], hint: 'Logical prompt batch (-b). Raising it speeds up prefill on long prompts and raises peak memory.' },+ { id: 'ubatchSize', label: 'Micro-batch size', type: 'number', config: true, min: 1, max: 8192, sweep: [1024], hint: 'Physical micro-batch (-ub). The single knob that most often moves long-context throughput.' },{ id: 'threads', label: 'CPU threads', type: 'number', config: true, min: 1, max: 256, hint: 'Threads for the CPU-resident layers. More is not always faster once you pass the physical core count.' },- { id: 'flashAttn', label: 'Flash attention', type: 'boolean', config: true, hint: 'Fused attention kernel. Usually faster and lighter on memory, but not every build/GPU supports it.' },- { id: 'cacheTypeK', label: 'KV cache type (K)', type: 'enum', config: true, options: CACHE_TYPES, hint: 'Quantizing the key cache buys context length with a little quality.' },+ { id: 'flashAttn', label: 'Flash attention', type: 'boolean', config: true, sweep: [true], hint: 'Fused attention kernel. Usually faster and lighter on memory, but not every build/GPU supports it.' },+ { id: 'cacheTypeK', label: 'KV cache type (K)', type: 'enum', config: true, options: CACHE_TYPES, sweep: ['q8_0'], hint: 'Quantizing the key cache buys context length with a little quality.' },+ // No `sweep` on purpose: llama.cpp refuses a quantized V cache unless flash+ // attention is on, so a V-only variant would fail to launch rather than+ // measure anything. The `flashAttn` variant above is the honest single knob.{ id: 'cacheTypeV', label: 'KV cache type (V)', type: 'enum', config: true, options: CACHE_TYPES, hint: 'Quantizing the value cache buys context length with a little quality.' },{ id: 'draftMax', label: 'Draft tokens', type: 'number', config: true, min: 0, max: 64, hint: 'Speculative-decoding lookahead. Only does anything when a drafter model is loaded.' },],@@ -155,8 +167,11 @@ const RAW_SPECS = {// unknown fields, and the model still loads at the daemon default.ollama: [{ id: 'numCtx', label: 'Context size', type: 'number', env: 'OLLAMA_CONTEXT_LENGTH', min: 512, max: 1048576, unit: 'tokens', hint: 'The window every model loads with. Larger costs VRAM up front, and past what fits Ollama offloads to CPU instead of failing.' },- { id: 'flashAttention', label: 'Flash attention', type: 'boolean', env: 'OLLAMA_FLASH_ATTENTION', hint: 'Fused attention kernel. Usually faster and lighter on memory, and a prerequisite for a quantized KV cache.' },- { id: 'kvCacheType', label: 'KV cache type', type: 'enum', env: 'OLLAMA_KV_CACHE_TYPE', options: CACHE_TYPES, hint: 'Quantizing the KV cache buys context length with a little quality. Ollama honours it only with flash attention on.' },+ { id: 'flashAttention', label: 'Flash attention', type: 'boolean', env: 'OLLAMA_FLASH_ATTENTION', sweep: [true], hint: 'Fused attention kernel. Usually faster and lighter on memory, and a prerequisite for a quantized KV cache.' },+ // `sweepWith` rather than a bare `sweep`: Ollama honours OLLAMA_KV_CACHE_TYPE+ // ONLY with flash attention on, so a kv-only variant would re-measure the+ // baseline under a label claiming otherwise — see the grid note below.+ { id: 'kvCacheType', label: 'KV cache type', type: 'enum', env: 'OLLAMA_KV_CACHE_TYPE', options: CACHE_TYPES, sweep: ['q8_0'], sweepWith: { flashAttention: true }, hint: 'Quantizing the KV cache buys context length with a little quality. Ollama honours it only with flash attention on.' },{ id: 'numParallel', label: 'Parallel requests', type: 'number', env: 'OLLAMA_NUM_PARALLEL', min: 1, max: 16, hint: 'Request slots the daemon serves at once. Each slot claims its own share of the context window, so raising it shrinks the window per request.' },],// LM Studio's load-time settings, applied by reloading the model through@@ -164,7 +179,7 @@ const RAW_SPECS = {// no CLI flag, so they are not offered — see the transport rule above.lmstudio: [{ id: 'contextLength', label: 'Context length', type: 'number', cli: '--context-length', min: 512, max: 1048576, unit: 'tokens', hint: 'The window the model is loaded with. LM Studio refuses a load that does not fit rather than silently shrinking it.' },- { id: 'gpuOffload', label: 'GPU offload', type: 'number', cli: '--gpu', min: 0, max: 1, step: 0.05, hint: 'Fraction of layers on the GPU (0 = CPU only, 1 = full offload). Lower frees VRAM for a bigger context at the cost of throughput.' },+ { id: 'gpuOffload', label: 'GPU offload', type: 'number', cli: '--gpu', min: 0, max: 1, step: 0.05, sweep: [1], hint: 'Fraction of layers on the GPU (0 = CPU only, 1 = full offload). Lower frees VRAM for a bigger context at the cost of throughput.' },{ id: 'parallel', label: 'Parallel requests', type: 'number', cli: '--parallel', min: 1, max: 16, hint: 'Predictions the model runs at once. Higher total throughput, slower per prediction.' },],// `mtplx serve` flags, applied by relaunching the PM2 daemon on a new command@@ -287,6 +302,73 @@ export function describeTuning(runtimeId, tuning) {return parts.length ? parts.join(' · ') : null;}+/**+ * Default cap on how many tunings ONE sweep will queue, baseline included.+ *+ * Every variant is a full measurement — a daemon restart plus one bounded+ * generation per context size, so minutes of GPU each. Six is the point where a+ * sweep is still something you can start and read the same evening.+ */+export const DEFAULT_TUNING_GRID_VARIANTS = 6;++/**+ * The knob combinations worth measuring for one runtime: backend defaults first,+ * then ONE variant per knob that declares a `sweep` candidate.+ *+ * ## Why one knob at a time+ *+ * A full cross-product of the llama.cpp catalog is thousands of runs at minutes+ * each. A single-knob grid answers the question the comparison table actually+ * reports — "was that knob worth it?", via `compareTunings`'s `deltaPercent` —+ * and the user stacks winners by re-sweeping from the one that won.+ *+ * The ONE exception is a knob whose runtime documents a hard prerequisite:+ * `sweepWith` names the co-knobs that must be set for the candidate to take+ * effect (Ollama honours `OLLAMA_KV_CACHE_TYPE` only with flash attention on).+ * Without it that variant would re-measure the baseline under a label claiming+ * a quantized cache — a wrong answer, which is worse than a two-knob variant.+ *+ * A knob with no `sweep` is deliberately absent from the grid: `ctxSize` changes+ * what is being measured rather than how fast it runs, `threads`/`nGpuLayers`+ * have no machine-independent candidate, and a quantized V cache does not launch+ * without flash attention.+ *+ * The returned length IS the run count, so a caller can name it in a consent+ * gate before anything starts — which the AI Provider Usage Policy (root+ * CLAUDE.md) requires of any batch of provider calls. `maxVariants` truncates in+ * catalog order; nothing here reports the grid as exhaustive. It is an+ * in-process option only — there is no wire path that shrinks the grid, because+ * a request that could would run a different count than consent named.+ *+ * @param {string} runtimeId+ * @param {{ maxVariants?: number }} [options]+ * @returns {Array<{ key: string, label: string|null, tuning: object }>} always at+ * least the baseline — `key: ''`, `label: null`, meaning "backend defaults".+ * A runtime with no sweepable knobs returns exactly that one entry, which a+ * caller must read as "nothing to compare here", not as a one-variant sweep.+ */+export function tuningGridFor(runtimeId, { maxVariants = DEFAULT_TUNING_GRID_VARIANTS } = {}) {+ const cap = Number.isFinite(maxVariants) && maxVariants >= 1 ? Math.floor(maxVariants) : DEFAULT_TUNING_GRID_VARIANTS;+ // The baseline is not optional: without it every variant's `deltaPercent` is+ // relative to another variant, and "was that knob worth it?" has no answer.+ const grid = [{ key: '', label: null, tuning: {} }];+ const seen = new Set(['']);+ for (const spec of tuningSpecsFor(runtimeId)) {+ if (!Array.isArray(spec.sweep)) continue;+ for (const candidate of spec.sweep) {+ if (grid.length >= cap) return grid;+ // Through `normalizeTuning` like any other tuning, so a candidate that the+ // catalog would clamp or reject cannot enter the grid unvalidated.+ const tuning = normalizeTuning(runtimeId, { ...(spec.sweepWith || {}), [spec.id]: candidate });+ const key = tuningSignature(tuning);+ if (!key || seen.has(key)) continue;+ seen.add(key);+ grid.push({ key, label: describeTuning(runtimeId, tuning), tuning });+ }+ }+ return grid;+}+/*** The subset of a tuning set PortOS applies at LAUNCH — the daemon has to be* (re)started for these to take effect, whatever the transport.diff --git a/server/lib/localModelTuning.test.js b/server/lib/localModelTuning.test.jsindex 51102de880..d94ec96b8e 100644--- a/server/lib/localModelTuning.test.js+++ b/server/lib/localModelTuning.test.js@@ -9,6 +9,7 @@ import {launchTuning,normalizeTuning,requestBody,+ tuningGridFor,tuningSignature,tuningSpecsFor,} from './localModelTuning.js';@@ -308,3 +309,97 @@ describe('compareTunings', () => {expect(rows).toEqual([]);});});++describe('tuningGridFor', () => {+ // The baseline is the reading every variant's `deltaPercent` is measured+ // against — a grid without it compares variants to each other and answers a+ // different question than the one the table claims to answer.+ it('leads with backend defaults, keyed so it shares an untuned record', () => {+ const [baseline] = tuningGridFor('llama');+ expect(baseline).toEqual({ key: '', label: null, tuning: {} });+ });++ it('varies exactly one knob per variant, so deltaPercent attributes the change', () => {+ for (const variant of tuningGridFor('llama').slice(1)) {+ expect(Object.keys(variant.tuning)).toHaveLength(1);+ }+ });++ // Ollama honours OLLAMA_KV_CACHE_TYPE only with flash attention on, so the+ // kv variant carries its prerequisite. Without it the run would re-measure the+ // baseline under a label claiming a quantized cache — a wrong answer.+ it('carries a knob\'s declared prerequisite into the variant that needs it', () => {+ const kv = tuningGridFor('ollama').find((v) => v.tuning.kvCacheType);+ expect(kv.tuning).toEqual({ kvCacheType: 'q8_0', flashAttention: true });+ });++ it('labels every variant so a comparison row says which knob it describes', () => {+ for (const variant of tuningGridFor('llama').slice(1)) {+ expect(variant.label).toBeTruthy();+ expect(variant.key).toBe(tuningSignature(variant.tuning));+ }+ });++ it('never repeats a knob set — one measurement per configuration', () => {+ const keys = tuningGridFor('llama').map((v) => v.key);+ expect(new Set(keys).size).toBe(keys.length);+ });++ // The returned length IS the run count a consent gate names, so the cap has to+ // bound the whole grid, baseline included.+ it('truncates to maxVariants, counting the baseline', () => {+ expect(tuningGridFor('llama', { maxVariants: 3 })).toHaveLength(3);+ expect(tuningGridFor('llama', { maxVariants: 1 })).toHaveLength(1);+ });++ it('falls back to the default for a nonsense cap rather than emptying the grid', () => {+ const full = tuningGridFor('llama');+ expect(tuningGridFor('llama', { maxVariants: 0 })).toEqual(full);+ expect(tuningGridFor('llama', { maxVariants: Number.NaN })).toEqual(full);+ });++ // A runtime PortOS cannot pass flags to has nothing to sweep. One entry is the+ // signal for that — the caller must read it as "no comparison available",+ // never as a one-variant sweep worth minutes of GPU.+ it('returns the baseline alone for a runtime with no sweepable knob', () => {+ expect(tuningGridFor('mtplx')).toHaveLength(1);+ expect(tuningGridFor('vllm')).toHaveLength(1);+ expect(tuningGridFor('not-a-runtime')).toHaveLength(1);+ });++ // The grid is built from the catalog, so a candidate the catalog would reject+ // must not survive into a launch line.+ it('produces only knob sets the catalog would accept back', () => {+ for (const runtime of ['llama', 'ollama', 'lmstudio']) {+ for (const variant of tuningGridFor(runtime)) {+ expect(normalizeTuning(runtime, variant.tuning)).toEqual(variant.tuning);+ }+ }+ });++ // Every variant has to reach the daemon through some transport, or the sweep+ // measures the baseline several times under different names.+ it('renders every variant through a transport that reaches the daemon', () => {+ const rendered = (runtime, tuning) => ({+ ...launchConfig(runtime, tuning), ...launchEnv(runtime, tuning),+ ...launchArgs(runtime, tuning), ...requestBody(runtime, tuning),+ });+ for (const runtime of ['llama', 'ollama', 'lmstudio']) {+ for (const variant of tuningGridFor(runtime).slice(1)) {+ expect(Object.keys(rendered(runtime, variant.tuning)).length).toBeGreaterThan(0);+ }+ }+ });++ // The grid feeds `compareTunings`, whose ranking is by throughput — a variant+ // that changes what is being measured (a different context window) would make+ // the winner incomparable rather than faster.+ it('never sweeps a knob that changes what is being measured', () => {+ const changesTheMeasurement = ['ctxSize', 'numCtx', 'contextLength'];+ for (const runtime of ['llama', 'ollama', 'lmstudio']) {+ for (const variant of tuningGridFor(runtime)) {+ for (const knob of changesTheMeasurement) expect(variant.tuning[knob]).toBeUndefined();+ }+ }+ });+});diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex cebf644d72..aa0f1ff061 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -283,9 +283,24 @@ export const localLlmAssessmentRunSchema = z.object({// work. The scope decides WHICH models (see `selectSweepTargets`); the target// list itself is derived server-side rather than sent, so a client can't ask for// an arbitrary batch of models.+// A TUNING sweep names one model and sets `tunings: true`; the grid itself is+// derived server-side (`tuningGridFor`) rather than sent, for the same reason+// the model list is — a client must not be able to ask for an arbitrary batch of+// provider calls. There is deliberately no wire knob for the grid SIZE either:+// the consent gate names its count from the report's grid, so a request that+// could shrink the grid would run a different number than the one the user+// agreed to.export const localLlmAssessmentSweepSchema = z.object({scope: z.enum(SWEEP_SCOPES).optional().default('unmeasured'),contextTokens: z.array(z.coerce.number().int().min(64).max(131072)).min(1).max(5).optional(),+ backend: localLlmRuntimeSchema.optional(),+ modelId: localLlmModelIdSchema.optional(),+ tunings: z.boolean().optional().default(false),+}).refine((v) => Boolean(v.backend) === Boolean(v.modelId), {+ // Half a model reference would silently fall back to the scope and measure+ // every installed model — hours of work nobody asked for.+ message: 'backend and modelId must be given together',+ path: ['modelId'],});export const localLlmAssessmentIntentSchema = z.object({intent: z.enum(['balanced', 'smartest', 'fastest', 'lightweight']).optional().default('balanced'),diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 0387e9fc07..abd9bc723d 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -487,7 +487,9 @@ router.post('/assessments/run', asyncHandler(async (req, res) => {res.json(await runAssessment({ backend, modelId, contextTokens, tuning, signal: abortSignalFromResponse(res), onProgress }))}))-// POST /api/local-llm/assessments/sweep — measure EVERY model the scope covers.+// POST /api/local-llm/assessments/sweep — measure EVERY model the scope covers,+// or (with `tunings: true` plus a backend/modelId) ONE model across the tuning+// grid its runtime declares.// User-triggered only, same as the single-model run: the UI names the model and// generation count before this fires.//@@ -497,9 +499,16 @@ router.post('/assessments/run', asyncHandler(async (req, res) => {// `localLlm:progress` socket event under `scope: 'assessment-sweep'`, and the// GET below is the reload-safe source of truth.router.post('/assessments/sweep', asyncHandler(async (req, res) => {- const { scope, contextTokens } = validateRequest(localLlmAssessmentSweepSchema, req.body)+ const { scope, contextTokens, backend, modelId, tunings } = validateRequest(localLlmAssessmentSweepSchema, req.body)const io = req.app.get('io')- const status = await startSweep({ scope, contextTokens, onProgress: (frame) => io?.emit('localLlm:progress', frame) })+ // `tunings` is the ASK, not the grid: the client says "sweep this model's+ // tunings" and the service decides which knob sets that means. A client that+ // could post the grid could post an arbitrary batch of provider calls, and the+ // count the consent gate named would stop being the count that runs.+ const status = await startSweep({+ scope, contextTokens, backend, modelId, tunings,+ onProgress: (frame) => io?.emit('localLlm:progress', frame),+ })// 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.if (status.rejected) throw new ServerError(status.rejected, { status: 409, context: { scope } })diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex 07db8d7d8f..ed325f6867 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -561,6 +561,59 @@ describe('measured assessments wiring', () => {});});+ // `tunings` is the ASK, not the grid — the service decides which knob sets a+ // "tuning sweep of this model" means. A client that could post the grid could+ // ask for an arbitrary batch of provider calls.+ it('POST /assessments/sweep forwards a tuning-sweep request without a grid', async () => {+ const res = await request(makeApp())+ .post('/api/local-llm/assessments/sweep')+ .send({ backend: 'llama', modelId: 'example-model.gguf', tunings: true });++ expect(res.status).toBe(200);+ expect(startSweep).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'llama', modelId: 'example-model.gguf', tunings: true,+ }));+ });++ // The service's refusals ride the existing rejected → 409 path rather than a+ // second, hand-rolled one in the handler.+ it('POST /assessments/sweep 409s when the service refuses the tuning grid', async () => {+ startSweep.mockResolvedValueOnce({ status: 'idle', rejected: 'mtplx has no tuning knobs PortOS can sweep' });+ const res = await request(makeApp())+ .post('/api/local-llm/assessments/sweep')+ .send({ backend: 'mtplx', modelId: 'example-model', tunings: true });++ expect(res.status).toBe(409);+ });++ // Half a model reference would fall through to the scope and measure every+ // installed model — hours of work nobody asked for.+ it('POST /assessments/sweep rejects a backend with no modelId', async () => {+ const res = await request(makeApp())+ .post('/api/local-llm/assessments/sweep')+ .send({ backend: 'llama', tunings: true });++ expect(res.status).toBe(400);+ expect(startSweep).not.toHaveBeenCalled();+ });++ // No wire knob shrinks the grid: the consent gate names its count from the+ // report's grid, so a request that could shrink it would run a different+ // number than the user agreed to.+ it('POST /assessments/sweep rejects an attempt to size the grid from the wire', async () => {+ const res = await request(makeApp())+ .post('/api/local-llm/assessments/sweep')+ .send({ backend: 'llama', modelId: 'example-model.gguf', tunings: true, maxVariants: 2 });++ expect(res.status).toBe(200);+ expect(startSweep.mock.calls[0][0].maxVariants).toBeUndefined();+ });++ it('POST /assessments/sweep leaves a plain model sweep untuned', async () => {+ await request(makeApp()).post('/api/local-llm/assessments/sweep').send({ scope: 'all' });+ expect(startSweep.mock.calls[0][0].tunings).toBe(false);+ });+it('GET /assessments/sweep reports the queue without touching a provider', async () => {const res = await request(makeApp()).get('/api/local-llm/assessments/sweep');expect(res.status).toBe(200);diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex eff4b4a93a..98dad90b5d 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -17,6 +17,7 @@ import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { isPortInUse } from '../lib/platform.js';import { PORTS } from '../lib/ports.js';+import { tuningSpecsFor } from '../lib/localModelTuning.js';import { ServerError } from '../lib/errorHandler.js';import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';@@ -481,12 +482,110 @@ async function waitForEndpoint(endpoint) {* puts the PREVIOUS configuration back, because a tuning sweep is expected to* produce launch lines that don't work and must not leave the daemon down.*+ * `reset` makes the request the COMPLETE tuning rather than a patch: every+ * sweepable knob it omits goes back to off. A SWEEP needs that — merging onto+ * the previous launch line is what made its second variant inherit the first+ * variant's flags (`-b 4096` then `-ub 1024` launching with both, while the+ * record's label claimed one knob and `deltaPercent` credited an accumulated+ * line to a single change) — and with `reset` an EMPTY tuning becomes a real+ * instruction, "run backend defaults", which is the baseline every variant is+ * compared against.+ *+ * It is OPT-IN, and must stay that way. The user's launch flags live only in the+ * running process (the LLMs page seeds its form from hardcoded defaults, not+ * from what is running), so a reset the caller did not ask for destroys the only+ * copy of a configuration they chose. Only a sweep — which captures the+ * configuration first and puts it back afterwards — may request one.+ *+ * The reset covers the knobs llama-server leaves OFF the launch line when they+ * are absent. `ctxSize`, `nGpuLayers` and `parallel` are deliberately excluded:+ * every one of them is emitted unconditionally with a real launcher default+ * rather than having an unset state, the user picks them on the LLMs page, and+ * no sweep varies them — "clearing" them would just substitute the default and+ * silently resize the window (or the slot count) out from under a running+ * server.+ ** @param {object} tuning launch knobs from `lib/localModelTuning.js`+ * @param {{reset?: boolean}} [options] `reset` clears every sweepable knob the+ * tuning does not name. Never pass it from an ordinary measurement.* @returns {Promise<{applied: boolean, reason: string|null, config: object|null}>}*/-export async function relaunchLlamaServerWithTuning(tuning = {}) {- const knobs = Object.entries(tuning).filter(([, v]) => v !== null && v !== undefined);- if (knobs.length === 0) {+const LAUNCHER_OWNED_KNOBS = new Set(['ctxSize', 'nGpuLayers', 'parallel']);++// Derived from the catalog rather than listed again here, so a knob added to+// llama.cpp's spec list is reset by default instead of quietly persisting into+// the next variant of a sweep. The value each knob resets TO is the one+// `startLlamaServer` reads as "leave the flag off the launch line".+const CLEARED_TUNING = Object.freeze(Object.fromEntries(+ tuningSpecsFor('llama')+ .filter((spec) => spec.config && !LAUNCHER_OWNED_KNOBS.has(spec.id))+ .map((spec) => [spec.id, spec.type === 'boolean' ? false : null])+));++// `undefined`, `null`, and a false toggle all render the same launch line — the+// flag is simply absent — so they must compare equal, or every untuned run on an+// untuned server would look like a change and pay for a restart.+const asLaunched = (value) => (value === undefined || value === null || value === false ? null : value);++/**+ * The launch configuration currently in effect, or `null` when PortOS is not the+ * one running llama-server (nothing to put back, and nothing it may touch).+ *+ * Paired with `restoreLlamaServerConfig`: a tuning sweep relaunches the daemon+ * once per variant and would otherwise leave the last variant's flags in place+ * with the user's own flags cleared — and the running process is the only record+ * of what they chose.+ */+export async function captureLlamaServerConfig() {+ const status = await getLlamaServerStatus();+ return status.running && status.managed && status.config?.model ? status.config : null;+}++/**+ * Put a captured launch configuration back, exactly as it was.+ *+ * A no-op for `null` (nothing was captured) and for a configuration already in+ * effect, so a sweep that never actually changed anything costs no restart.+ *+ * A daemon that is DOWN is the case a restore matters most, not one to decline:+ * a sweep is expected to produce launch lines that do not work, and when the+ * failing one's own fallback could not get the previous configuration up either,+ * llama-server is stopped and the install's `llama` provider is dead until+ * somebody notices. The captured configuration is a known-good launch line and+ * nothing holds the port (`startLlamaServer` refuses if anything does), so it is+ * started rather than refused. Only a server that is running and NOT+ * PortOS-managed is off limits — that one belongs to somebody else.+ */+export async function restoreLlamaServerConfig(config) {+ if (!config?.model) return { restored: false, reason: 'nothing was captured' };+ const status = await getLlamaServerStatus();+ if (status.running && !status.managed) {+ return { restored: false, reason: 'llama-server is now running outside PortOS, so its launch line is not PortOS\'s to change' };+ }++ if (status.running) {+ const differs = Object.keys(CLEARED_TUNING).some((id) => asLaunched(status.config?.[id]) !== asLaunched(config[id]));+ if (!differs) return { restored: true, reason: null };+ await stopLlamaServer();+ }+ await waitForPortRelease(config.port ?? PORTS.LLAMA_SERVER);++ console.log('🦙 llama-server: restoring the launch configuration the sweep started from');+ const started = await startLlamaServer(config).catch((err) => {+ console.error(`❌ llama-server: could not restore the launch configuration: ${err.message}`);+ return null;+ });+ return {+ restored: Boolean(started),+ reason: started ? null : 'llama-server would not start with the captured configuration, and is now stopped',+ };+}++export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = false } = {}) {+ // Without a reset an empty tuning asks for nothing, so there is nothing to do+ // — and answering before touching PM2 keeps an ordinary untuned measurement+ // free of a status round trip.+ if (!reset && Object.values(tuning).every((v) => v === null || v === undefined)) {return { applied: false, reason: 'no launch knobs were requested', config: currentConfig };}@@ -503,8 +602,22 @@ export async function relaunchLlamaServerWithTuning(tuning = {}) {}const previous = status.config;- const next = { ...previous, ...tuning };- console.log(`🦙 llama-server: relaunching to apply tuning (${knobs.map(([k, v]) => `${k}=${v}`).join(', ')})`);+ const next = { ...previous, ...(reset ? CLEARED_TUNING : {}), ...tuning };+ // Nothing to do when the daemon is ALREADY running this exact tuning — the+ // common case for an untuned measurement on an untuned server, and the reason+ // making an empty tuning meaningful costs a plain assessment nothing.+ //+ // Compared across the cleared set UNION whatever the request names, not the+ // cleared set alone: a request for a launcher-owned knob (`ctxSize`,+ // `nGpuLayers`) changes nothing in the cleared set, and judging on that would+ // report a context-size change as applied while the server kept serving the+ // old window.+ const compared = new Set([...Object.keys(CLEARED_TUNING), ...Object.keys(tuning || {})]);+ const changed = [...compared].some((id) => asLaunched(next[id]) !== asLaunched(previous[id]));+ if (!changed) return { applied: true, reason: null, config: previous };++ const knobs = Object.entries(tuning).filter(([, v]) => v !== null && v !== undefined);+ console.log(`🦙 llama-server: relaunching to apply tuning (${knobs.length ? knobs.map(([k, v]) => `${k}=${v}`).join(', ') : 'backend defaults'})`);await stopLlamaServer();await waitForPortRelease(next.port ?? PORTS.LLAMA_SERVER);diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex 0a4caf3d7a..90c6d5dc5d 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -4,6 +4,8 @@ import {startLlamaServer,stopLlamaServer,relaunchLlamaServerWithTuning,+ captureLlamaServerConfig,+ restoreLlamaServerConfig,installLlamaServer,_resetLlamaServerStateForTests,LLAMA_APP,@@ -478,6 +480,18 @@ describe('llamaServerManager', () => {// probe instead: "reachable" has to track the fake PM2 process, or the// relaunch can never observe the server it just started answering — and the// new `online` check would report every success as not-applied.+ // The launch line of the most recent PM2 start — everything after the `--`+ // separator, which is what llama-server actually received.+ const launchArgs = () => {+ const start = [...execPm2Calls].reverse().find((c) => c[0] === 'start') || [];+ const dash = start.indexOf('--');+ return dash === -1 ? [] : start.slice(dash + 1);+ };++ // Did the daemon actually bounce? Reading the status tails PM2's logs, which+ // is not a restart — only a stop/start pair is.+ const restarted = () => execPm2Calls.some((c) => c[0] === 'start' || c[0] === 'delete');+const started = async () => {vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')@@ -492,12 +506,160 @@ describe('llamaServerManager', () => {expect(result.reason).toMatch(/not running/);});+ // The user's launch flags live only in the running process, so an ordinary+ // measurement must never reset them. Without `reset` an empty tuning asks+ // for nothing and is answered before PM2 is touched at all.it('refuses an empty tuning rather than restarting for no reason', async () => {await started();execPm2Calls = [];const result = await relaunchLlamaServerWithTuning({});expect(result.applied).toBe(false);- expect(execPm2Calls).toEqual([]);+ expect(restarted()).toBe(false);+ });++ // The regression this guards: a reset the caller did not ask for wipes the+ // only copy of a configuration the user chose on the LLMs page.+ it('keeps the flags a tuning does not name unless a reset was requested', async () => {+ await started();+ await relaunchLlamaServerWithTuning({ batchSize: 4096, flashAttn: true }, { reset: true });+ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 1024 });++ expect(result.config.ubatchSize).toBe(1024);+ expect(result.config.batchSize).toBe(4096);+ expect(result.config.flashAttn).toBe(true);+ });++ // The bug `reset` exists for: variants applied in sequence accumulated, so+ // the second launched with the first one's flags while its record's label+ // claimed a single knob — and `compareTunings` credited the change to it.+ it('clears the knobs a reset tuning does not name, so variants cannot accumulate', async () => {+ await started();+ await relaunchLlamaServerWithTuning({ batchSize: 4096 }, { reset: true });+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 1024 }, { reset: true });++ expect(result.applied).toBe(true);+ expect(result.config.ubatchSize).toBe(1024);+ expect(result.config.batchSize).toBeNull();+ expect(launchArgs()).not.toContain('4096');+ });++ // The baseline variant of a sweep: no knobs at all, which only means+ // something when the caller asked for a complete tuning.+ it('resets a tuned server back to backend defaults for an empty reset tuning', async () => {+ await started();+ await relaunchLlamaServerWithTuning({ ubatchSize: 1024, flashAttn: true }, { reset: true });+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({}, { reset: true });++ expect(result.applied).toBe(true);+ expect(result.config.ubatchSize).toBeNull();+ expect(result.config.flashAttn).toBe(false);+ expect(launchArgs()).not.toContain('--flash-attn');+ });++ it('reports a reset already in effect without restarting', async () => {+ await started();+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({}, { reset: true });+ expect(result.applied).toBe(true);+ expect(restarted()).toBe(false);+ });++ // A sweep rewrites the launch line once per variant, and the running daemon+ // is the only record of the flags the user chose.+ it('captures and restores the launch configuration a sweep started from', async () => {+ await started();+ await relaunchLlamaServerWithTuning({ ubatchSize: 512, flashAttn: true }, { reset: true });+ const captured = await captureLlamaServerConfig();++ await relaunchLlamaServerWithTuning({ batchSize: 4096 }, { reset: true });+ expect((await getLlamaServerStatus()).config.flashAttn).toBe(false);++ const result = await restoreLlamaServerConfig(captured);+ expect(result.restored).toBe(true);+ const back = (await getLlamaServerStatus()).config;+ expect(back.ubatchSize).toBe(512);+ expect(back.flashAttn).toBe(true);+ expect(back.batchSize).toBeNull();+ });++ // A sweep is EXPECTED to produce launch lines that do not work. When the+ // failing variant's own fallback could not get the previous configuration up+ // either, llama-server is stopped and the install's provider is dead —+ // which is when a restore matters most, not a reason to decline it.+ it('starts from the captured configuration when the daemon is down', async () => {+ await started();+ const captured = await captureLlamaServerConfig();+ await stopLlamaServer();+ expect((await getLlamaServerStatus()).running).toBe(false);++ const result = await restoreLlamaServerConfig(captured);+ expect(result.restored).toBe(true);+ expect((await getLlamaServerStatus()).running).toBe(true);+ });++ // A server somebody else started belongs to them.+ it('refuses a running server PortOS does not manage', async () => {+ await started();+ const captured = await captureLlamaServerConfig();+ pm2State = { name: 'someone-elses-llama', status: 'online', pid: 999, args: [] };+ execPm2Calls = [];++ const result = await restoreLlamaServerConfig(captured);+ expect(result.restored).toBe(false);+ expect(result.reason).toMatch(/outside PortOS/);+ expect(restarted()).toBe(false);+ });++ it('captures nothing when PortOS is not the one running llama-server', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');+ expect(await captureLlamaServerConfig()).toBeNull();+ });++ it('restoring nothing is a no-op rather than a restart', async () => {+ await started();+ execPm2Calls = [];+ const result = await restoreLlamaServerConfig(null);+ expect(result.restored).toBe(false);+ expect(restarted()).toBe(false);+ });++ // A launcher-owned knob is not in the cleared set, so judging 'did anything+ // change?' on that set alone would report a new context size as applied+ // while the server kept serving the old window.+ it('relaunches for a launcher-owned knob the cleared set does not cover', async () => {+ await started();+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({ ctxSize: 4096 });++ expect(result.applied).toBe(true);+ expect(result.config.ctxSize).toBe(4096);+ expect(launchArgs()).toContain('4096');+ });++ it('skips the relaunch when a named knob already matches what is running', async () => {+ await started();+ const running = (await getLlamaServerStatus()).config;+ execPm2Calls = [];+ const result = await relaunchLlamaServerWithTuning({ ctxSize: running.ctxSize });++ expect(result.applied).toBe(true);+ expect(restarted()).toBe(false);+ });++ // The model path, the port, and the window the user picked on the LLMs page+ // are not sweepable knobs — clearing them would resize the server out from+ // under them.+ it('leaves the model, port, and launcher-owned knobs alone', async () => {+ await started();+ const before = (await getLlamaServerStatus()).config;+ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 1024 });++ expect(result.config.model).toBe(before.model);+ expect(result.config.port).toBe(before.port);+ expect(result.config.ctxSize).toBe(before.ctxSize);+ expect(result.config.nGpuLayers).toBe(before.nGpuLayers);});it('puts the knobs on the new launch line, keeping the model it was serving', async () => {diff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.jsindex 41f0e27eb4..25f52d5f86 100644--- a/server/services/localModelAssessmentSweep.js+++ b/server/services/localModelAssessmentSweep.js@@ -1,5 +1,5 @@/**- * Measure every local model in one pass — the overnight sweep.+ * Measure a batch of local models in one pass — the overnight sweep.** Measuring one model takes minutes; measuring a machine's worth of them takes* hours. That is a job you start at the end of the day and read in the morning,@@ -9,13 +9,30 @@* and the page reads its progress from a status endpoint plus the existing* `localLlm:progress` socket event.*+ * ## Two dimensions, one queue+ *+ * The queue walks a list of (model, tuning) pairs, and which list it walks is+ * the only difference between the two sweeps this module serves:+ *+ * - **Model sweep** — every model a scope covers, each under the tuning it+ * already carries. Answers "which of my models is worth using?".+ * - **Tuning sweep** — one model across a grid of tunings+ * (`lib/localModelTuning.js#tuningGridFor`). Answers "which flags suit this+ * model here?", which is what `compareTunings` ranks.+ *+ * They deliberately share the queue rather than getting one each: cancellation,+ * progress, the accelerator claim, and the "one measurement at a time" rule are+ * identical, and a second queue could run concurrently with this one — which+ * would make every number either produced describe the contention.+ ** ## AI Provider Usage Policy (root CLAUDE.md) — read before editing*- * A sweep calls a provider once per model, so it is STRICTLY user-triggered, the- * same as the single-model run:+ * A sweep calls a provider once per queued measurement, so it is STRICTLY+ * user-triggered, the same as the single-model run:** - `startSweep()` is reachable only from `POST /api/local-llm/assessments/sweep`,- * behind a consent gate that names the exact model count and generation count.+ * 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.** The prohibition the single-model service states — "no scheduler, no boot hook,@@ -38,10 +55,24 @@* flight and nothing else, and re-running the sweep afterwards picks up exactly* what is still unmeasured. Persisting the queue would buy a resumable pointer* into a job that is cheap to restart and must never auto-resume on boot.+ *+ * One consequence is worth naming: a restart during a TUNING sweep also loses+ * the captured launch configuration, so llama-server stays on whichever variant+ * was in flight. That is visible and fixable on the LLMs page, and the+ * alternative — persisting it and relaunching a daemon at boot to put it back —+ * is exactly the boot-time work this module refuses to do.*/import { selectSweepTargets, SWEEP_SCOPES } from '../lib/localModelAssessment.js';-import { getAssessmentReport, runAssessment } from './localModelAssessments.js';+import { tuningGridFor } from '../lib/localModelTuning.js';+import {+ captureLaunchState,+ getAssessmentReport,+ isTuningSweepable,+ restoreLaunchState,+ runAssessment,+} from './localModelAssessments.js';+import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';// One sweep at a time. This is a re-entrancy guard, not a concurrency control:// PortOS serves one user, and the thing being prevented is a second click (or a@@ -77,11 +108,22 @@ function snapshot() {if (!sweep) {// `status: 'idle'` with a null run is the honest "nothing has been started",// distinct from a finished sweep whose results are still worth showing.- return { status: 'idle', scope: null, startedAt: null, finishedAt: null, total: 0, completed: 0, current: null, results: [], cancelRequested: false };+ return { status: 'idle', mode: null, scope: null, target: null, settled: true, startedAt: null, finishedAt: null, total: 0, completed: 0, current: null, results: [], cancelRequested: false, restoreError: null };}return {status: sweep.status,+ // 'models' = every model the scope covers, each under one tuning.+ // 'tunings' = ONE model across a grid of tunings. The page renders a+ // different sentence for each, so it cannot be inferred from the counts.+ mode: sweep.mode,scope: sweep.scope,+ // The single model a tuning sweep is measuring; null for a model sweep.+ target: sweep.target,+ // Whether the sweep has let go of the machine, which outlasts `status`: a+ // cancelled sweep is still aborting its last measurement and, for a tuning+ // sweep, still has a launch configuration to put back — a relaunch. The page+ // keeps its per-model actions disabled while this is false.+ settled: sweep.settled === true,startedAt: sweep.startedAt,finishedAt: sweep.finishedAt,total: sweep.total,@@ -92,6 +134,13 @@ function snapshot() {results: sweep.results,cancelRequested: sweep.cancelRequested,error: sweep.error || null,+ // A sweep whose MEASUREMENTS all landed but whose daemon could not be put+ // back is not a failed sweep — but the user has to be told, because their+ // runtime is now serving the last variant's launch line and nothing else on+ // the page would say so. Separate from `error` so neither one lies.+ restoreError: sweep.restoreError || null,+ // `launchState` is deliberately NOT exposed: it holds on-disk model paths,+ // and the page has no use for the configuration being put back.};}@@ -99,6 +148,39 @@ export function getSweepStatus() {return snapshot();}+/**+ * Put the captured launch configuration back, holding the machine-wide claim+ * while it happens.+ *+ * A restore STOPS and STARTS the daemon, which takes seconds to minutes for a+ * large GGUF — the same disruption the claim exists to keep away from a+ * measurement. `runAssessment` released it after the last variant, and a Stop+ * click re-enables the per-model Measure button immediately, so without a claim+ * of its own the restore can bounce llama-server in the middle of a reading+ * somebody started meanwhile (from the page, ⌘K, or curl) and that reading would+ * record the restart.+ *+ * A claim that cannot be had is NOT a reason to skip: the daemon would be left+ * on the sweep's last variant, which is the thing this exists to prevent. It+ * waits, bounded, then restores anyway and lets the reason be reported.+ */+async function restoreUnderClaim(run, backend) {+ if (!run.launchState) return { restored: false, reason: 'nothing to restore' };+ const claim = await claimHeavyLocalJob({+ kind: 'local-model assessment',+ id: `${backend} launch restore`,+ timeoutMs: CLAIM_WAIT_MS,+ });+ if (!claim.ok) {+ console.error(`⚠️ Local LLM: restoring the launch configuration without the accelerator claim — ${claim.message}`);+ }+ try {+ return await restoreLaunchState(backend, run.launchState);+ } finally {+ if (claim.ok) await claim.release();+ }+}+/*** Ask the running sweep to stop.*@@ -135,6 +217,11 @@ export function __resetSweep() {// queue is replaceable the moment it is cancelled, and a loop still winding down// its last model must not write its results into the sweep that succeeded it.async function runSweepLoop(run, targets, contextTokens, emit) {+ // A tuning sweep asks each variant to be the COMPLETE tuning, so the launch+ // line is exactly that variant's knobs and the baseline's is none of them.+ // `beginSweep` captured what was running first, and the `finally` below puts+ // it back — the running daemon is the only record of the flags the user chose.+ const resetTuning = run.mode === 'tunings';for (const target of targets) {if (run.cancelRequested) break;run.current = { backend: target.backend, modelId: target.modelId, tuningLabel: target.tuningLabel, startedAt: nowIso() };@@ -143,9 +230,13 @@ async function runSweepLoop(run, targets, contextTokens, emit) {event: 'model-start',backend: target.backend,modelId: target.modelId,+ // The label is what distinguishes one step of a TUNING sweep from the+ // next — every step names the same model, so a message without it reads+ // as one measurement repeating.+ tuningLabel: target.tuningLabel || null,completed: run.results.length,total: run.total,- message: `Sweep ${run.results.length + 1}/${run.total}: measuring ${target.modelId}…`,+ message: `Sweep ${run.results.length + 1}/${run.total}: measuring ${target.modelId}${target.tuningLabel ? ` (${target.tuningLabel})` : ''}…`,});// One model failing is a RESULT, not a reason to abandon the queue — the@@ -155,6 +246,7 @@ async function runSweepLoop(run, targets, contextTokens, emit) {modelId: target.modelId,contextTokens,tuning: target.tuning,+ resetTuning,signal: run.controller.signal,onProgress: emit,claimTimeoutMs: CLAIM_WAIT_MS,@@ -177,6 +269,13 @@ async function runSweepLoop(run, targets, contextTokens, emit) {// Travels WITH the rate it qualifies. Dropping it here would render a// frame-counted estimate as a tokenizer measurement in the results list.tokensEstimated: typeof result?.performance?.tokensEstimated === 'boolean' ? result.performance.tokensEstimated : null,+ // `false` means the knobs never reached the daemon, so these numbers+ // describe some OTHER configuration. The report already refuses to rank+ // such a record; without these the sweep's own list would still present it+ // as a clean reading for the tuning it names — which is exactly the row a+ // tuning sweep is read for.+ tuningApplied: typeof result?.tuningApplied === 'boolean' ? result.tuningApplied : null,+ tuningNotApplied: result?.tuningNotApplied || null,});}}@@ -189,44 +288,93 @@ async function runSweepLoop(run, targets, contextTokens, emit) {* request that started it can return, and so closing the browser does not stop* an overnight run.*+ * Set `tunings` and it measures ONE named model across the grid of launch+ * configurations its runtime declares — the tuning sweep. The grid is chosen+ * HERE, from `tuningGridFor`, rather than accepted from the caller: what a+ * "tuning sweep of this model" means is a domain decision, and deriving it in+ * one place is what keeps the count a consent gate names equal to the count that+ * runs.+ ** @param {object} options- * @param {'unmeasured'|'stale'|'all'} [options.scope]+ * @param {'unmeasured'|'stale'|'all'} [options.scope] which models, when no+ * explicit model is named+ * @param {string} [options.backend] measure only this model (with `modelId`)+ * @param {string} [options.modelId]+ * @param {boolean} [options.tunings] sweep the named model's tuning grid instead+ * 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* @returns {Promise<object>} the initial snapshot, or `{ rejected }` when a- * sweep is already running or the scope covers nothing+ * sweep is already running or the request covers nothing*/-export async function startSweep({ scope = 'unmeasured', contextTokens, onProgress } = {}) {+export async function startSweep({ scope = 'unmeasured', backend, modelId, tunings = false, contextTokens, onProgress } = {}) {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, for a tuning sweep, it has a launch configuration to put+ // back. Starting the next one on top of that would have the old sweep relaunch+ // the daemon partway through the new one's first measurement — and every+ // number the new sweep produced up to then would describe that relaunch.+ if (sweep && !sweep.settled) return { ...snapshot(), rejected: 'the previous sweep is still winding down' };// Reserved here, synchronously, so the check above and this claim cannot be// split by the await inside. Released in the `finally` — by which point either// `sweep` is published (and the `running` check covers the slot) or the start// was refused and the slot is free again.startingSweep = true;try {- return await beginSweep({ scope, contextTokens, onProgress });+ return await beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress });} finally {startingSweep = false;}}-async function beginSweep({ scope, contextTokens, onProgress }) {+async function beginSweep({ scope, backend, modelId, tunings, contextTokens, onProgress }) {const resolvedScope = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';+ const named = backend && modelId ? { backend, modelId } : null;++ // A tuning sweep varies the configuration of ONE model, so without a model+ // there is nothing to hold constant and the request is meaningless.+ if (tunings && !named) return { ...snapshot(), rejected: 'a tuning sweep needs a model to sweep' };+ // A runtime PortOS cannot reset and put back must not be swept: its baseline+ // would measure the previous variant's configuration, and the sweep would+ // leave its knobs set for good. See `LAUNCH_APPLIERS` and #4763.+ if (tunings && !isTuningSweepable(named.backend)) {+ return { ...snapshot(), rejected: `PortOS cannot sweep ${named.backend} tunings yet — it has no way to put the runtime back afterwards` };+ }+ const grid = named && tunings ? tuningGridFor(named.backend) : null;+ // A runtime PortOS cannot pass flags to yields the baseline alone — one+ // measurement with nothing to compare it to. Refuse rather than spend minutes+ // of GPU on a table `compareTunings` will not render.+ if (grid && grid.length < 2) {+ return { ...snapshot(), rejected: `${named.backend} has no tuning knobs PortOS can sweep` };+ }+ const mode = grid ? 'tunings' : 'models';// Read the report ONCE, here, rather than per model: it lists installed models// across every runtime and annotates staleness, which is exactly the input the// target selection needs. It is disk-plus-listing only — no LLM call.const report = await getAssessmentReport({ intent: 'balanced' });const uninstalledKeys = new Set(report.uninstalled.map((u) => `${u.backend}:${u.modelId}`));+ const installed = report.assessments.filter((a) => !uninstalledKeys.has(`${a?.backend}:${a?.modelId}`));+const targets = selectSweepTargets({// Records for models that are no longer installed cannot be re-measured, so// they never enter the queue.- assessments: report.assessments.filter((a) => !uninstalledKeys.has(`${a?.backend}:${a?.modelId}`)),+ assessments: installed,unassessed: report.unassessed,scope: resolvedScope,+ only: named,+ tunings: grid,});- if (!targets.length) return { ...snapshot(), rejected: 'nothing to measure for that scope' };+ // An empty list for a NAMED model means it is not installed — the selector+ // found neither a record nor a listing for it. Saying so beats queuing one+ // doomed measurement per variant and reporting the sweep as failed.+ if (!targets.length) {+ return {+ ...snapshot(),+ rejected: named ? `${named.modelId} is not installed on ${named.backend}` : 'nothing to measure for that scope',+ };+ }const emit = (frame) => {if (typeof onProgress !== 'function') return;@@ -236,9 +384,30 @@ async function beginSweep({ scope, contextTokens, onProgress }) {catch (err) { console.error(`❌ Local LLM: sweep progress listener failed: ${err.message}`); }};+ // Captured BEFORE the first variant relaunches anything. A sweep rewrites the+ // launch line once per variant, and the running daemon is the only record of+ // the flags the user chose — the LLMs page seeds its form from hardcoded+ // defaults, not from what is running.+ const launchState = grid ? await captureLaunchState(named.backend) : null;+ // Nothing to capture means the daemon is stopped, or someone else started it —+ // either way PortOS cannot put a tuning on its launch line, so every variant+ // would record `tuningApplied: false` and the comparison would rank a set of+ // configurations that never ran. Refusing costs a click; running costs the+ // whole sweep.+ if (grid && !launchState) {+ return {+ ...snapshot(),+ rejected: `PortOS is not running ${named.backend}, so it cannot vary the launch configuration — start it from the LLMs page first`,+ };+ }+const run = {status: 'running',- scope: resolvedScope,+ mode,+ // A tuning sweep of ONE named model did not consult the scope, so reporting+ // one would tell the page it measured a set it never looked at.+ scope: named ? null : resolvedScope,+ target: named,startedAt: nowIso(),finishedAt: null,total: targets.length,@@ -246,12 +415,24 @@ async function beginSweep({ scope, contextTokens, onProgress }) {results: [],cancelRequested: false,error: null,+ restoreError: null,+ // Flipped in the loop's `finally`, after the restore. `startSweep` refuses+ // while it is false, so a cancelled sweep cannot relaunch the daemon+ // underneath the sweep that replaced it.+ settled: false,+ launchState,controller: new AbortController(),};sweep = run;- console.log(`📏 Local LLM: assessment sweep started — ${targets.length} measurement${targets.length === 1 ? '' : 's'} (${resolvedScope})`);- emit({ scope: 'assessment-sweep', event: 'start', total: targets.length, completed: 0, message: `Measuring ${targets.length} model${targets.length === 1 ? '' : 's'}…` });+ // A tuning sweep measures ONE thing many ways, so counting "models" would be+ // wrong in exactly the place the user is reading for reassurance.+ const plural = targets.length === 1 ? '' : 's';+ const what = grid+ ? `${named.modelId} across ${targets.length} tuning${plural}`+ : `${targets.length} model${plural}`;+ console.log(`📏 Local LLM: assessment sweep started — ${targets.length} measurement${plural} (${named ? named.modelId : resolvedScope})`);+ emit({ scope: 'assessment-sweep', event: 'start', total: targets.length, completed: 0, message: `Measuring ${what}…` });// Detached on purpose: the caller is an HTTP handler that must return now.runSweepLoop(run, targets, contextTokens, emit)@@ -259,10 +440,31 @@ async function beginSweep({ scope, contextTokens, onProgress }) {run.error = err?.message || 'sweep failed';console.error(`❌ Local LLM: assessment sweep failed: ${run.error}`);})+ // Not in the `finally`: putting the daemon back is real work that can fail,+ // and it has to finish before the page is told the sweep is over — a user+ // reading "complete" must not still be racing a relaunch.+ .then(() => restoreUnderClaim(run, named?.backend)+ .then((result) => {+ // `restored: false` with a captured state means the daemon is still on+ // the last variant. Recording the reason is the only way the user finds+ // out; swallowing it leaves them running a configuration they did not+ // choose and cannot see.+ if (run.launchState && result?.restored === false) {+ run.restoreError = result.reason || 'the launch configuration could not be put back';+ console.error(`❌ Local LLM: sweep finished but the launch configuration was not restored — ${run.restoreError}`);+ }+ })+ .catch((err) => {+ run.restoreError = err?.message || 'the launch configuration could not be put back';+ console.error(`❌ Local LLM: could not restore the launch configuration after the sweep: ${run.restoreError}`);+ })).finally(() => {run.status = run.cancelRequested ? 'cancelled' : (run.error ? 'failed' : 'complete');run.finishedAt = nowIso();run.current = null;+ // Set LAST, once the queue and the restore are both done — this is what+ // lets the next sweep start.+ run.settled = true;console.log(`📏 Local LLM: assessment sweep ${run.status} — ${run.results.length}/${run.total} measured`);// A queue the user already replaced has nothing to report — emitting its// terminal frame would tell the page the CURRENT sweep just finished.diff --git a/server/services/localModelAssessmentSweep.test.js b/server/services/localModelAssessmentSweep.test.jsindex f0343c4e7a..1f11eff36c 100644--- a/server/services/localModelAssessmentSweep.test.js+++ b/server/services/localModelAssessmentSweep.test.js@@ -3,13 +3,29 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// The sweep's only two collaborators: the report (what to measure) and the// single-model runner (measure it). Both are mocked so the queue's own behavior// — order, cancellation, failure isolation — is what's under test.+// The restore stops and starts the daemon, so it takes the same machine-wide+// claim a measurement does — otherwise it can bounce llama-server underneath a+// reading somebody started the moment Stop re-enabled the button.+const claimHeavyLocalJob = vi.fn(async () => ({ ok: true, release: vi.fn(async () => {}) }));+vi.mock('../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: (...args) => claimHeavyLocalJob(...args) }));+vi.mock('./localModelAssessments.js', () => ({getAssessmentReport: vi.fn(),runAssessment: vi.fn(),+ // A sweep may only drive a runtime it can reset AND put back. llama.cpp can;+ // the default here mirrors that so the tests exercise the real gate.+ isTuningSweepable: vi.fn((backend) => backend === 'llama'),+ captureLaunchState: vi.fn(async () => ({ model: '/models/example.gguf' })),+ restoreLaunchState: vi.fn(async () => ({ restored: true, reason: null })),}));-import { getAssessmentReport, runAssessment } from './localModelAssessments.js';+import {+ captureLaunchState, getAssessmentReport, isTuningSweepable, restoreLaunchState, runAssessment,+} from './localModelAssessments.js';import { startSweep, getSweepStatus, cancelSweep, __resetSweep } from './localModelAssessmentSweep.js';+// Not mocked: the grid is pure catalog data, and asserting the queue against the+// real one is what proves the service runs the configurations it advertises.+import { tuningGridFor } from '../lib/localModelTuning.js';// Let the detached loop run to completion. The sweep deliberately does NOT// return a promise for its own queue (the HTTP handler must return immediately),@@ -26,6 +42,10 @@ const measured = (verdict = 'fits', meanTokensPerSecond = 42) => ({beforeEach(() => {vi.clearAllMocks();+ claimHeavyLocalJob.mockResolvedValue({ ok: true, release: vi.fn(async () => {}) });+ isTuningSweepable.mockImplementation((backend) => backend === 'llama');+ captureLaunchState.mockResolvedValue({ model: '/models/example.gguf' });+ restoreLaunchState.mockResolvedValue({ restored: true, reason: null });__resetSweep();});afterEach(() => __resetSweep());@@ -201,7 +221,11 @@ describe('cancelSweep', () => {// Cancelling frees the slot immediately, so a replacement sweep can start// while the abandoned one is still unwinding its last model. That loop must// not write its results (or its terminal frame) into the new queue.- it('does not let an abandoned queue write into the sweep that replaced it', async () => {+ // A cancelled sweep is not finished with the machine: its last measurement is+ // still aborting, and a tuning sweep still has a launch configuration to put+ // back. A replacement started on top of that would be measuring through the+ // old sweep's relaunch.+ it('refuses a replacement while the cancelled sweep is still winding down', async () => {getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'slow' }] }));let releaseFirst;runAssessment.mockImplementationOnce(() => new Promise((resolve) => { releaseFirst = resolve; }));@@ -209,19 +233,30 @@ describe('cancelSweep', () => {await startSweep({ scope: 'unmeasured' });cancelSweep();- // A fresh queue takes over before the abandoned model resolves.- getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'second' }] }));- runAssessment.mockResolvedValue(measured());- const frames = [];- await startSweep({ scope: 'unmeasured', onProgress: (f) => frames.push(f) });+ const refused = await startSweep({ scope: 'unmeasured' });+ expect(refused.rejected).toMatch(/winding down/);releaseFirst(measured('fits', 9));await settle();+ });- const status = getSweepStatus();- expect(status.results.map((r) => r.modelId)).toEqual(['second']);- // Exactly one terminal frame, and it belongs to the queue still standing.- expect(frames.filter((f) => f.event === 'complete')).toHaveLength(1);+ it('lets the next sweep start once the cancelled one has finished winding down', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'slow' }] }));+ let releaseFirst;+ runAssessment.mockImplementationOnce(() => new Promise((resolve) => { releaseFirst = resolve; }));++ await startSweep({ scope: 'unmeasured' });+ cancelSweep();+ releaseFirst({ cancelled: true });+ await settle();++ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'second' }] }));+ runAssessment.mockResolvedValue(measured());+ const started = await startSweep({ scope: 'unmeasured' });++ expect(started.rejected).toBeUndefined();+ await settle();+ expect(getSweepStatus().results.map((r) => r.modelId)).toEqual(['second']);});});@@ -237,3 +272,359 @@ describe('getSweepStatus', () => {expect(getSweepStatus().controller).toBeUndefined();});});++describe('startSweep — the tuning dimension', () => {+ // The llama.cpp grid the service derives: backend defaults plus one variant+ // per sweepable knob. Asserted against the real catalog rather than a fixture,+ // because "the queue is the grid" is exactly the claim under test.+ const llamaGrid = tuningGridFor('llama');++ const onlyTarget = () => getAssessmentReport.mockResolvedValue(+ report({ unassessed: [{ backend: 'llama', modelId: 'target' }] })+ );++ it('measures one named model once per tuning, baseline first', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ const started = await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ expect(started.total).toBe(llamaGrid.length);+ expect(started.mode).toBe('tunings');+ expect(started.target).toEqual({ backend: 'llama', modelId: 'target' });++ await settle();+ expect(runAssessment.mock.calls.map((c) => c[0].tuning)).toEqual(llamaGrid.map((v) => v.tuning));+ // Every variant is the same model, so the label is the only thing that+ // distinguishes one store record from the next.+ expect(getSweepStatus().results.map((r) => r.tuningLabel)).toEqual(llamaGrid.map((v) => v.label));+ });++ // A separate store record per variant is what `compareTunings` groups on — two+ // variants sharing a key would overwrite each other and leave nothing to rank.+ it('gives every variant a distinct tuning, so each lands as its own record', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ const keys = runAssessment.mock.calls.map((c) => JSON.stringify(c[0].tuning));+ expect(new Set(keys).size).toBe(keys.length);+ });++ // The grid is a domain decision, not a request parameter: a caller that could+ // hand one over could ask for an arbitrary batch of provider calls, and the+ // count the consent gate named would stop being the count that runs.+ it('derives the grid itself rather than accepting one', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ await startSweep({ backend: 'llama', modelId: 'target', tunings: [{ ubatchSize: 99999 }] });+ await settle();+ expect(runAssessment.mock.calls.map((c) => c[0].tuning)).toEqual(llamaGrid.map((v) => v.tuning));+ });++ // Queuing a grid against a model that is not there would burn one doomed+ // measurement per variant and report the sweep as failed, not as a bad request.+ it('refuses a model no runtime has installed', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'llama', modelId: 'other' }] }));++ const result = await startSweep({ backend: 'llama', modelId: 'ghost', tunings: true });+ expect(result.rejected).toMatch(/not installed/);+ expect(runAssessment).not.toHaveBeenCalled();+ });++ // Naming a model leaves the scope nothing to decide. Without that, "sweep THIS+ // model" would silently do nothing whenever the model fell outside the scope —+ // and an already-measured model falls outside 'unmeasured' by definition.+ it('sweeps a named model the scope would have excluded', async () => {+ getAssessmentReport.mockResolvedValue(report({+ assessments: [{ backend: 'llama', modelId: 'measured-before', staleness: { stale: false } }],+ }));+ runAssessment.mockResolvedValue(measured());++ const started = await startSweep({ scope: 'unmeasured', backend: 'llama', modelId: 'measured-before', tunings: true });+ expect(started.total).toBe(llamaGrid.length);+ });++ // A model with two stored tunings is still ONE model to cross with the grid;+ // measuring each variant twice would put the same configuration on both sides+ // of the comparison table.+ it('crosses the grid once for a model that holds several stored tunings', async () => {+ getAssessmentReport.mockResolvedValue(report({+ assessments: [+ { backend: 'llama', modelId: 'target', tuningKey: '', tuning: {} },+ { backend: 'llama', modelId: 'target', tuningKey: 'flashAttn=true', tuning: { flashAttn: true } },+ ],+ }));+ runAssessment.mockResolvedValue(measured());++ const started = await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ expect(started.total).toBe(llamaGrid.length);+ });++ // A runtime PortOS cannot pass flags to yields the baseline alone — one+ // measurement with nothing to compare it to.+ it('refuses a runtime with no sweepable knob instead of measuring the baseline alone', async () => {+ isTuningSweepable.mockReturnValue(true);+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'mtplx', modelId: 'target' }] }));++ const result = await startSweep({ backend: 'mtplx', modelId: 'target', tunings: true });+ expect(result.rejected).toMatch(/no tuning knobs/);+ expect(runAssessment).not.toHaveBeenCalled();+ });++ // A runtime whose knobs survive the sweep would leave them set for good AND+ // measure every later "backend defaults" reading under them — a comparison+ // that reads as valid and is not (#4763).+ it('refuses a runtime it cannot reset and put back', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'target' }] }));++ const result = await startSweep({ backend: 'ollama', modelId: 'target', tunings: true });+ expect(result.rejected).toMatch(/put the runtime back/);+ expect(runAssessment).not.toHaveBeenCalled();+ expect(getAssessmentReport).not.toHaveBeenCalled();+ });++ // Each variant's launch line has to be exactly that variant's knobs, and the+ // baseline's none of them — that is what the manager's reset does, and a+ // sweep that did not ask for it would measure accumulating launch lines.+ it('asks for a complete tuning on every variant, so none can accumulate', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ for (const [args] of runAssessment.mock.calls) expect(args.resetTuning).toBe(true);+ });++ // A plain model sweep re-measures each model under the tuning it already+ // carries. Resetting there would wipe launch flags the user chose.+ it('never asks a model sweep for a reset', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ runAssessment.mockResolvedValue(measured());++ await startSweep({ scope: 'unmeasured' });+ await settle();+ expect(runAssessment.mock.calls[0][0].resetTuning).toBe(false);+ expect(captureLaunchState).not.toHaveBeenCalled();+ });++ // The running daemon is the only record of the launch flags the user chose, so+ // a sweep that rewrote it has to put it back — however the queue ended.+ it('captures the launch configuration first and restores it when the queue ends', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ expect(captureLaunchState).toHaveBeenCalledWith('llama');+ await settle();+ expect(restoreLaunchState).toHaveBeenCalledWith('llama', { model: '/models/example.gguf' });+ });++ it('restores the launch configuration after a cancelled sweep too', async () => {+ onlyTarget();+ runAssessment.mockImplementationOnce(() => { cancelSweep(); return Promise.resolve({ cancelled: true }); });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(restoreLaunchState).toHaveBeenCalledWith('llama', { model: '/models/example.gguf' });+ });++ // A restore that throws must not take the process down or leave the page+ // waiting on a sweep that never reports finished.+ it('finishes the sweep even when the restore fails', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ restoreLaunchState.mockRejectedValue(new Error('llama-server would not come back'));++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(getSweepStatus().status).toBe('complete');+ });++ // A tuning sweep varies the configuration of ONE model, so without a model+ // there is nothing to hold constant.+ it('refuses a tuning sweep with no model to sweep', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'llama', modelId: 'a' }] }));++ const result = await startSweep({ scope: 'all', tunings: true });+ expect(result.rejected).toMatch(/needs a model/);+ expect(getAssessmentReport).not.toHaveBeenCalled();+ });++ // The queue is shared, so cancelling a tuning sweep has to behave exactly as+ // cancelling a model sweep does — stop after the measurement in flight, keep+ // what already landed.+ it('stops after the in-flight variant when cancelled mid-sweep', async () => {+ onlyTarget();+ runAssessment+ .mockResolvedValueOnce(measured())+ .mockImplementationOnce(() => { cancelSweep(); return Promise.resolve({ cancelled: true }); });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ const status = getSweepStatus();+ expect(status.status).toBe('cancelled');+ expect(status.results).toHaveLength(1);+ expect(runAssessment).toHaveBeenCalledTimes(2);+ });++ // Every step of a tuning sweep names the same model, so a frame without the+ // label reads as one measurement repeating.+ it('names the tuning in each progress frame', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ const frames = [];++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true, onProgress: (f) => frames.push(f) });+ await settle();+ const starts = frames.filter((f) => f.event === 'model-start');+ expect(starts.map((f) => f.tuningLabel)).toEqual(llamaGrid.map((v) => v.label));+ expect(starts[1].message).toContain(llamaGrid[1].label);+ });++ // The report already refuses to RANK a reading whose tuning never reached the+ // daemon. The sweep's own results list said nothing, so a variant that failed+ // to launch read as a clean measurement of the tuning it was labelled with —+ // the exact row a tuning sweep is opened for.+ it('carries an unapplied tuning through to the result, not just to the store', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue({+ ...measured(),+ tuningApplied: false,+ tuningNotApplied: 'llama-server rejected that tuning',+ });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(getSweepStatus().results[0]).toMatchObject({+ tuningApplied: false,+ tuningNotApplied: 'llama-server rejected that tuning',+ });+ });++ // Nothing to capture means llama-server is stopped or someone else started it.+ // PortOS cannot put a tuning on its launch line, so every variant would record+ // "tuning not applied" and the comparison would rank configurations that never+ // ran — minutes of GPU for an answer that is not one.+ it('refuses when there is no launch configuration to vary', async () => {+ onlyTarget();+ captureLaunchState.mockResolvedValue(null);++ const result = await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ expect(result.rejected).toMatch(/start it from the LLMs page/);+ expect(runAssessment).not.toHaveBeenCalled();+ });++ // A restore stops and starts the daemon, which is exactly the disruption the+ // machine-wide claim exists to keep away from a measurement — and by then+ // `runAssessment` has released it and the page has re-enabled Measure.+ it('holds the machine-wide claim while it puts the launch configuration back', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ const release = vi.fn(async () => {});+ claimHeavyLocalJob.mockResolvedValue({ ok: true, release });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(claimHeavyLocalJob).toHaveBeenCalledWith(expect.objectContaining({ kind: 'local-model assessment' }));+ expect(release).toHaveBeenCalled();+ });++ // A claim it cannot get is not a reason to skip: the daemon would stay on the+ // sweep's last variant, which is the thing the restore exists to prevent.+ it('restores anyway when the claim cannot be had', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ claimHeavyLocalJob.mockResolvedValue({ ok: false, message: 'busy' });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(restoreLaunchState).toHaveBeenCalledWith('llama', { model: '/models/example.gguf' });+ });++ // A model sweep captured nothing, so there is nothing to put back and no+ // reason to take the machine for it.+ it('claims nothing when there is nothing to restore', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ runAssessment.mockResolvedValue(measured());++ await startSweep({ scope: 'unmeasured' });+ await settle();+ expect(claimHeavyLocalJob).not.toHaveBeenCalled();+ });++ // `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 () => {+ onlyTarget();+ let releaseRun;+ runAssessment.mockImplementationOnce(() => new Promise((resolve) => { releaseRun = resolve; }));++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ cancelSweep();+ expect(getSweepStatus().status).toBe('cancelled');+ expect(getSweepStatus().settled).toBe(false);++ releaseRun({ cancelled: true });+ await settle();+ expect(getSweepStatus().settled).toBe(true);+ });++ // The measurements all landed, so the sweep did not fail — but the runtime is+ // now serving the last variant's launch line, and nothing else on the page+ // would say so.+ it('reports a restore that did not happen without calling the sweep failed', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ restoreLaunchState.mockResolvedValue({ restored: false, reason: 'llama-server is no longer PortOS-managed' });++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ const status = getSweepStatus();+ expect(status.status).toBe('complete');+ expect(status.error).toBeNull();+ expect(status.restoreError).toMatch(/no longer PortOS-managed/);+ });++ it('reports a restore that threw', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());+ restoreLaunchState.mockRejectedValue(new Error('llama-server would not come back'));++ await startSweep({ backend: 'llama', modelId: 'target', tunings: true });+ await settle();+ expect(getSweepStatus().restoreError).toMatch(/would not come back/);+ });++ // A model sweep captured nothing, so "not restored" is the honest no-op — not+ // something to alarm the user about.+ it('does not report a restore failure for a sweep that captured nothing', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ runAssessment.mockResolvedValue(measured());++ await startSweep({ scope: 'unmeasured' });+ await settle();+ expect(getSweepStatus().restoreError).toBeNull();+ });++ it('reports the model sweep as mode "models" with no named target', async () => {+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ runAssessment.mockResolvedValue(measured());++ const started = await startSweep({ scope: 'unmeasured' });+ expect(started.mode).toBe('models');+ expect(started.target).toBeNull();+ expect(started.scope).toBe('unmeasured');+ });++ // A tuning sweep of one named model never consulted the scope, so reporting+ // one would tell the page it measured a set it never looked at.+ it('reports no scope for a sweep of one named model', async () => {+ onlyTarget();+ runAssessment.mockResolvedValue(measured());++ const started = await startSweep({ scope: 'all', backend: 'llama', modelId: 'target', tunings: true });+ expect(started.scope).toBeNull();+ });+});diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex ee7b6f67ff..29b56fe2c6 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -79,6 +79,7 @@ import {launchTuning,normalizeTuning,requestBody,+ tuningGridFor,tuningSignature,tuningSpecsFor,} from '../lib/localModelTuning.js';@@ -87,7 +88,12 @@ import { ServerError } from '../lib/errorHandler.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { getAllProviders } from './providers.js';import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';-import { getLlamaServerEndpoint, relaunchLlamaServerWithTuning } from './llamaServerManager.js';+import {+ captureLlamaServerConfig,+ getLlamaServerEndpoint,+ relaunchLlamaServerWithTuning,+ restoreLlamaServerConfig,+} from './llamaServerManager.js';import { getMtplxServerEndpoint, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';import { listModels } from './localLlm.js';import {@@ -324,7 +330,7 @@ function describeVerdict(verdict, samples) {* THIS run apart from an unrelated model install streaming on the same event.* @returns {Promise<object>} the persisted assessment record*/-export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, tuning, signal, onProgress, claimTimeoutMs = 0 } = {}) {+export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, tuning, resetTuning = false, signal, onProgress, claimTimeoutMs = 0 } = {}) {const contexts = [...new Set(contextTokens)].filter((n) => Number.isFinite(n) && n > 0).sort((a, b) => a - b);// The listener runs outside the request lifecycle's error path in some callers// (a socket emit can throw on a closed io), and a broken progress consumer must@@ -362,7 +368,7 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_performance: summarizePerformance([]),};}- return await measureModel({ backend, modelId, contexts, tuning, signal, emit });+ return await measureModel({ backend, modelId, contexts, tuning, resetTuning, signal, emit });} finally {await claim.release();}@@ -398,24 +404,52 @@ const toApplication = (ok, error, fallbackReason) => ({* the flag is silently dropped on the way to a launch line that renders only* `cli`. Nothing fails at runtime, so `LAUNCH_TRANSPORTS` below is exported and* `localModelAssessments.test.js` asserts the catalog against it.+ *+ * ## `sweepable` — which runtimes a TUNING SWEEP may drive+ *+ * A sweep needs two things an ordinary measurement does not, and a manager that+ * cannot do BOTH must not be swept:+ *+ * 1. **A complete tuning.** Each variant's launch line has to be exactly that+ * variant's knobs, and the baseline's has to be none of them — otherwise+ * variants accumulate and `deltaPercent` credits an accumulated line to a+ * single change. That is the `reset` a sweep passes through.+ * 2. **A configuration that can be put back.** A sweep relaunches the daemon+ * once per variant, and the running process is the only record of the+ * launch flags the user chose. Without `capture`/`restore` a sweep would+ * silently replace them with its last variant's.+ *+ * Only llama.cpp offers both today. Ollama's environment is written into the+ * user's launchd domain / a systemd drop-in and survives a restart, LM Studio's+ * load settings survive a reload, and MTPLX has the reset but no capture pair —+ * so on those a sweep would leave its knobs set forever AND measure every later+ * "backend defaults" reading under them. #4763 is the work that makes them+ * sweepable; until it lands the button and the route refuse rather than+ * producing a comparison that reads as valid.*/const LAUNCH_APPLIERS = {llama: {transport: 'config',- apply: ({ launch }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch)),+ sweepable: true,+ apply: ({ launch, reset }) => relaunchLlamaServerWithTuning(launchConfig('llama', launch), { reset }),+ capture: captureLlamaServerConfig,+ restore: restoreLlamaServerConfig,},ollama: {transport: 'env',+ sweepable: false,apply: ({ launch }) => restartOllamaWithEnv(launchEnv('ollama', launch)).then((r) => toApplication(r.applied, r.error, `Ollama could not be restarted with that tuning (${r.reason})`)),},lmstudio: {transport: 'cli',+ sweepable: false,apply: ({ modelId, launch }) => loadLmStudioModelWithArgs(modelId, launchArgs('lmstudio', launch)).then((r) => toApplication(r.success, r.error, 'LM Studio could not reload the model with that tuning')),},mtplx: {transport: 'cli',+ sweepable: false,// Takes the knob set as-is rather than rendered flags: `mtplxServerManager`// renders it with the same catalog on the way to the launch line, and keeps// the ids so it can report back which tuning the daemon came up under.@@ -432,19 +466,32 @@ export const LAUNCH_TRANSPORTS = Object.freeze(Object.fromEntries(Object.entries(LAUNCH_APPLIERS).map(([runtime, { transport }]) => [runtime, transport])));-async function applyLaunchTuning({ backend, modelId, launch }) {+/** Whether a TUNING SWEEP may drive this runtime — see `sweepable` above. */+export const isTuningSweepable = (backend) => LAUNCH_APPLIERS[backend]?.sweepable === true;++/**+ * Remember a runtime's launch configuration so a sweep can put it back.+ * `null` for a runtime with nothing to capture — restoring it is then a no-op.+ */+export const captureLaunchState = (backend) => LAUNCH_APPLIERS[backend]?.capture?.() ?? Promise.resolve(null);++/** Put back what `captureLaunchState` returned. Safe to call with `null`. */+export const restoreLaunchState = (backend, state) =>+ (state ? LAUNCH_APPLIERS[backend]?.restore?.(state) : null) ?? Promise.resolve({ restored: false, reason: 'nothing to restore' });++async function applyLaunchTuning({ backend, modelId, launch, reset }) {const applier = LAUNCH_APPLIERS[backend];if (!applier) {return { applied: false, reason: `PortOS does not start the ${backend} runtime, so it cannot apply launch tuning`, config: null };}- return applier.apply({ backend, modelId, launch })+ return applier.apply({ backend, modelId, launch, reset }).catch((err) => ({ applied: false, reason: err?.message || 'relaunch failed', config: null }));}// The measurement itself, with the accelerator already claimed by the caller// above. Split out so the claim's release is one `finally` around one call// rather than wrapped around a 100-line body.-async function measureModel({ backend, modelId, contexts, tuning, signal, emit }) {+async function measureModel({ backend, modelId, contexts, tuning, resetTuning, signal, emit }) {const normalizedTuning = normalizeTuning(backend, tuning);const tuningKey = tuningSignature(normalizedTuning);const tuningLabel = describeTuning(backend, normalizedTuning);@@ -455,8 +502,14 @@ async function measureModel({ backend, modelId, contexts, tuning, signal, emit }// tuning PortOS could not apply must not be filed as evidence for that tuning.const launch = launchTuning(backend, normalizedTuning);const request = requestBody(backend, normalizedTuning);+ // `resetTuning` (a SWEEP, never an ordinary Measure) makes an empty launch+ // tuning meaningful: "no knobs" is the baseline every variant is compared+ // against, so it has to be applied rather than assumed. Without it an empty+ // tuning stays what it has always been — nothing was asked for, nothing is+ // touched — which is what keeps a plain measurement from relaunching, and from+ // recording `tuningApplied: false` for a run that requested no tuning at all.let tuningApplication;- if (Object.keys(launch).length > 0) {+ if (Object.keys(launch).length > 0 || resetTuning) {// Announced BEFORE the await, because applying a launch tuning stops and// restarts a daemon — and a cold MLX or GGUF checkpoint can take minutes to// load again. Without this the progress stream is silent for that whole@@ -465,9 +518,11 @@ async function measureModel({ backend, modelId, contexts, tuning, signal, emit }event: 'start',sampleIndex: 0,sampleCount: contexts.length,- message: `Restarting ${backend} with ${tuningLabel} before measuring…`,+ // A sweep's baseline variant has no label, and "restarting with null" is+ // not a sentence. It is a real configuration — say which one.+ message: `Restarting ${backend} with ${tuningLabel || 'backend defaults'} before measuring…`,});- tuningApplication = await applyLaunchTuning({ backend, modelId, launch });+ tuningApplication = await applyLaunchTuning({ backend, modelId, launch, reset: resetTuning });} else {// `null`, NOT `true`, when nothing was tuned. `true` when the only knobs set// ride on the request body, which needs no daemon restart to take effect.@@ -639,6 +694,16 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {modelCount: Array.isArray(listed[id].models) ? listed[id].models.length : null,error: listed[id].error,tuningSpecs: tuningSpecsFor(id),+ // The tuning grid a sweep of this runtime would run — literally the same+ // call `localModelAssessmentSweep.js` makes when one starts, so the count+ // and labels the consent gate names cannot differ from what executes. There+ // is deliberately no wire knob that resizes it (see the sweep schema).+ //+ // EMPTY for a runtime a sweep may not drive, so the page offers the action+ // exactly where the server would accept it. Shipping a grid for a runtime+ // PortOS cannot reset and put back would advertise a comparison that reads+ // as valid and is not — see `sweepable` on LAUNCH_APPLIERS and #4763.+ tuningGrid: isTuningSweepable(id) ? tuningGridFor(id) : [],}));const listErrors = ASSESSABLE_RUNTIMES.filter((id) => listed[id].error);diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 1697608378..53e0809460 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -38,9 +38,13 @@ vi.mock('./providers.js', () => ({ getAllProviders: (...args) => getAllProvidersconst getLlamaServerEndpoint = vi.fn();const relaunchLlamaServerWithTuning = vi.fn();+const captureLlamaServerConfig = vi.fn(async () => null);+const restoreLlamaServerConfig = vi.fn(async () => ({ restored: false, reason: 'nothing was captured' }));vi.mock('./llamaServerManager.js', () => ({getLlamaServerEndpoint: (...args) => getLlamaServerEndpoint(...args),relaunchLlamaServerWithTuning: (...args) => relaunchLlamaServerWithTuning(...args),+ captureLlamaServerConfig: (...args) => captureLlamaServerConfig(...args),+ restoreLlamaServerConfig: (...args) => restoreLlamaServerConfig(...args),}));// MTPLX's knobs are `mtplx serve` flags, so applying one relaunches the PM2@@ -793,7 +797,7 @@ describe('tuning', () => {const result = await svc.runAssessment({backend: 'llama', modelId: 'dflash', contextTokens: [512], tuning: { ubatchSize: 512 },});- expect(relaunchLlamaServerWithTuning).toHaveBeenCalledWith({ ubatchSize: 512 });+ expect(relaunchLlamaServerWithTuning).toHaveBeenCalledWith({ ubatchSize: 512 }, { reset: false });expect(result.tuningApplied).toBe(true);expect(result.tuningLabel).toBe('Micro-batch size 512');});@@ -863,6 +867,9 @@ describe('tuning', () => {expect(result.tuningNotApplied).toMatch(/unrecognized arguments/);});+ // The user's launch flags live only in the running llama-server process, so an+ // ordinary measurement must never touch them. A reset is something a SWEEP+ // asks for, and only a sweep, because only a sweep puts the configuration back.it('never relaunches llama-server for an untuned run', async () => {probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });runEndpointLlmTest.mockResolvedValue(okRun());@@ -870,6 +877,30 @@ describe('tuning', () => {expect(relaunchLlamaServerWithTuning).not.toHaveBeenCalled();});+ // The baseline variant of a tuning sweep: no knobs, which only means something+ // when the caller asked for a complete tuning.+ it('applies an empty tuning as a reset when the caller asked for one', async () => {+ probeOpenAiModels.mockResolvedValue({ reachable: true, models: ['dflash'], error: null });+ runEndpointLlmTest.mockResolvedValue(okRun());+ await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512], resetTuning: true });+ expect(relaunchLlamaServerWithTuning).toHaveBeenCalledWith({}, { reset: true });+ });++ // Only a runtime PortOS can reset AND put back may be swept — otherwise the+ // sweep leaves its knobs set for good and every later "backend defaults"+ // reading is taken under them (#4763).+ it('reports which runtimes a tuning sweep may drive', () => {+ expect(svc.isTuningSweepable('llama')).toBe(true);+ expect(svc.isTuningSweepable('ollama')).toBe(false);+ expect(svc.isTuningSweepable('lmstudio')).toBe(false);+ expect(svc.isTuningSweepable('mtplx')).toBe(false);+ });++ it('captures and restores nothing for a runtime with no launch state', async () => {+ expect(await svc.captureLaunchState('ollama')).toBeNull();+ expect(await svc.restoreLaunchState('ollama', null)).toEqual({ restored: false, reason: 'nothing to restore' });+ });+it('deletes one tuning of a model and leaves the others', async () => {runLocalLlmTest.mockResolvedValue(okRun());await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });