The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(benchmark): stop stops the run, and a failure is not silence
David6e9056dd4125
diff --git a/src/components/models/BenchmarkView.tsx b/src/components/models/BenchmarkView.tsxindex 785fba93..e62079c2 100644--- a/src/components/models/BenchmarkView.tsx+++ b/src/components/models/BenchmarkView.tsx@@ -16,6 +16,7 @@ export function BenchmarkView() {const { models } = useModels()const results = useBenchmarkStore((s) => s.results)const isRunning = useBenchmarkStore((s) => s.isRunning)+ const benchError = useBenchmarkStore((s) => s.error)const currentModel = useBenchmarkStore((s) => s.currentModel)const currentStep = useBenchmarkStore((s) => s.currentStep)const totalSteps = useBenchmarkStore((s) => s.totalSteps)@@ -32,11 +33,15 @@ export function BenchmarkView() {const stale = staleModels(results, names)/** Measure everything that has no run yet, one after another. The models- * share one GPU, so this is a queue, not a fan-out (M0j0Risin, D#21). */+ * share one GPU, so this is a queue, not a fan-out (M0j0Risin, D#21).+ * It also stops at the first failure: without that, a dead backend meant+ * every remaining model marched past in silence. */const runPending = async () => {+ useBenchmarkStore.getState().setError(null)for (const name of pending) {if (useBenchmarkStore.getState().isRunning) breakawait runBenchmark(name)+ if (useBenchmarkStore.getState().error) break}}@@ -53,6 +58,17 @@ export function BenchmarkView() {return (<div className="h-full overflow-y-auto scrollbar-thin"><div className="max-w-2xl mx-auto px-4 py-4">+ {benchError && (+ <div className="mb-3 px-3 py-2 rounded-md bg-red-500/10 border border-red-500/25 text-[0.6rem] text-red-300 flex items-start gap-2">+ <span className="flex-1">{benchError}</span>+ <button+ onClick={() => useBenchmarkStore.getState().setError(null)}+ className="text-red-400 hover:text-red-200 transition-colors"+ >+ Dismiss+ </button>+ </div>+ )}{/* Header */}<div className="flex items-center gap-2 mb-4"><button onClick={() => setView('models')} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/5 text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors">diff --git a/src/hooks/__tests__/benchmark-stop-and-errors.test.ts b/src/hooks/__tests__/benchmark-stop-and-errors.test.tsnew file mode 100644index 00000000..09ac5f1a--- /dev/null+++ b/src/hooks/__tests__/benchmark-stop-and-errors.test.ts@@ -0,0 +1,108 @@+/**+ * Stop has to stop the whole benchmark, and a failure has to be visible.+ *+ * Found reviewing the C1 fix (2026-08-14). The brake ElBiggus asked for+ * (issue #106) aborts the request in flight, and that part works. But+ * stopBenchmark only aborted the controller: the loop had no stop check, so+ * the next iteration opened a fresh controller and kept measuring the same+ * model. Stop read as "skip this prompt". Worse, it also called+ * setRunning(false), which re-enabled Run while the loop was still going, so a+ * second loop could start on the same GPU.+ *+ * The second half: every failure went into a bare `catch {}`. A model that+ * could not be reached at all produced a run with no results and no message,+ * indistinguishable from one that finished.+ *+ * Run: npx vitest run src/hooks/__tests__/benchmark-stop-and-errors.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'+import { toMarkdownReport } from '../../stores/benchmarkStore'+import type { BenchmarkResult } from '../../lib/benchmark-prompts'++const here = dirname(fileURLToPath(import.meta.url))+const hook = readFileSync(resolve(here, '../useBenchmark.ts'), 'utf8')+const store = readFileSync(resolve(here, '../../stores/benchmarkStore.ts'), 'utf8')+const view = readFileSync(resolve(here, '../../components/models/BenchmarkView.tsx'), 'utf8')++describe('stop reaches the loop, not just the request', () => {+ it('the loop checks the stop flag before every prompt', () => {+ const loop = hook.slice(hook.indexOf('for (let i = 0'), hook.indexOf('} finally {'))+ expect(loop).toContain('if (stoppedRef.current) break')+ // The check sits at the TOP of the body, ahead of opening a controller.+ expect(loop.indexOf('if (stoppedRef.current) break'))+ .toBeLessThan(loop.indexOf('new AbortController()'))+ })++ it('stopBenchmark sets the flag before it aborts', () => {+ const stop = hook.slice(hook.indexOf('const stopBenchmark'))+ expect(stop.indexOf('stoppedRef.current = true')).toBeLessThan(stop.indexOf('abort()'))+ })++ it('stopBenchmark does not re-enable Run, the run owns that', () => {+ const stop = hook.slice(hook.indexOf('const stopBenchmark'), hook.indexOf('return { runBenchmark'))+ expect(stop).not.toContain('store.setRunning')+ expect(hook).toContain(' store.setRunning(false)\n }')+ })++ it('the re-entry guard is a ref, so two clicks in one frame cannot both pass', () => {+ expect(hook).toContain('if (runningRef.current) return')+ expect(hook).not.toContain('if (store.isRunning) return')+ })+})++describe('a failure says so', () => {+ it('the catch records the model and the message instead of swallowing it', () => {+ expect(hook).toContain('store.setError(')+ expect(hook).not.toMatch(/\} catch \{\s*\n\s*\/\/ Aborted or error/)+ })++ it('a stopped prompt is not reported as a failure', () => {+ const c = hook.slice(hook.indexOf('} catch (e) {'))+ expect(c.indexOf('if (stoppedRef.current || abortRef.current?.signal.aborted) break'))+ .toBeLessThan(c.indexOf('store.setError('))+ })++ it('the store carries the field and the view renders it', () => {+ expect(store).toContain('setError: (message) => set({ error: message })')+ expect(view).toContain('const benchError = useBenchmarkStore((s) => s.error)')+ expect(view).toContain('{benchError && (')+ })++ it('run state is not persisted, a crash must not grey out Run forever', () => {+ expect(store).toContain('partialize: (s) => ({ results: s.results })')+ })++ it('the queue stops at the first failure instead of marching on in silence', () => {+ expect(view).toContain('if (useBenchmarkStore.getState().error) break')+ })+})++describe('the exported report matches the board it claims to be', () => {+ const run = (over: Partial<BenchmarkResult>): BenchmarkResult => ({+ modelName: 'm', promptId: 'p1', tokensPerSec: 20, timeToFirstToken: 100,+ totalTime: 1000, totalTokens: 400, thinkTokens: 0, finishReason: 'stop',+ correct: true, timestamp: 1, ...over,+ })++ it('prints the score it is sorted by', () => {+ const md = toMarkdownReport({ fast: [run({ modelName: 'fast' })] }, 'now')+ expect(md).toContain('| Score |')+ expect(md).toMatch(/\| 1 \| fast \| \d/)+ })++ it('marks a run the brake stopped, not only one cut off by the budget', () => {+ const md = toMarkdownReport({+ wild: [run({ modelName: 'wild', finishReason: 'runaway' }), run({ modelName: 'wild' })],+ }, 'now')+ expect(md).toContain('stopped by the brake')+ })++ it('says both in the footer, so the marks are explained', () => {+ const md = toMarkdownReport({ m: [run({})] }, 'now')+ expect(md).toContain('stopped by the brake is marked')+ expect(md).toContain('Score is what the')+ })+})diff --git a/src/hooks/useBenchmark.ts b/src/hooks/useBenchmark.tsindex e135e5de..ec3d7361 100644--- a/src/hooks/useBenchmark.ts+++ b/src/hooks/useBenchmark.ts@@ -12,61 +12,91 @@ import type { ChatMessage } from '../api/providers/types'export function useBenchmark() {const store = useBenchmarkStore()const abortRef = useRef<AbortController | null>(null)+ // Stop has to reach the LOOP, not just the request in flight. Aborting the+ // stream only ended the current prompt; the next iteration opened a fresh+ // controller and carried on against the same model, so Stop looked like+ // "skip this one" (review 2026-08-14).+ const stoppedRef = useRef(false)+ // The guard cannot read store.isRunning: that value is captured when the+ // hook renders, so two clicks in the same frame both saw false and started+ // two loops on one GPU.+ const runningRef = useRef(false)const runBenchmark = useCallback(async (modelName: string) => {- if (store.isRunning) return+ if (runningRef.current) return+ runningRef.current = true+ stoppedRef.current = falsestore.setRunning(true, modelName, BENCHMARK_PROMPTS.length)+ store.setError(null)- for (let i = 0; i < BENCHMARK_PROMPTS.length; i++) {- const prompt = BENCHMARK_PROMPTS[i]- store.setStep(i + 1)+ try {+ for (let i = 0; i < BENCHMARK_PROMPTS.length; i++) {+ if (stoppedRef.current) break+ const prompt = BENCHMARK_PROMPTS[i]+ store.setStep(i + 1)- abortRef.current = new AbortController()+ abortRef.current = new AbortController()- try {- const { provider, modelId } = getProviderForModel(modelName)- const messages: ChatMessage[] = [- { role: 'user', content: prompt.prompt },- ]+ try {+ const { provider, modelId } = getProviderForModel(modelName)+ const messages: ChatMessage[] = [+ { role: 'user', content: prompt.prompt },+ ]- const stream = provider.chatStream(modelId, messages, {- temperature: 0.7,- signal: abortRef.current.signal,- })+ const stream = provider.chatStream(modelId, messages, {+ temperature: 0.7,+ signal: abortRef.current.signal,+ })- // The brake aborts the request itself, not just our reading of it:- // dropping the stream would leave the model generating into nothing,- // still holding the GPU (ElBiggus, issue #106).- const controller = abortRef.current- const m = await measureRun(stream, prompt.check, {- onLimit: () => controller.abort(),- })+ // The brake aborts the request itself, not just our reading of it:+ // dropping the stream would leave the model generating into nothing,+ // still holding the GPU (ElBiggus, issue #106).+ const controller = abortRef.current+ const m = await measureRun(stream, prompt.check, {+ onLimit: () => controller.abort(),+ })- store.addResult({- modelName,- promptId: prompt.id,- tokensPerSec: m.tokensPerSec,- timeToFirstToken: m.timeToFirstToken,- totalTime: m.totalTime,- totalTokens: m.totalTokens,- thinkTokens: m.thinkTokens,- finishReason: m.finishReason,- correct: m.correct,- timestamp: Date.now(),- })- } catch {- // Aborted or error — skip this prompt+ store.addResult({+ modelName,+ promptId: prompt.id,+ tokensPerSec: m.tokensPerSec,+ timeToFirstToken: m.timeToFirstToken,+ totalTime: m.totalTime,+ totalTokens: m.totalTokens,+ thinkTokens: m.thinkTokens,+ finishReason: m.finishReason,+ correct: m.correct,+ timestamp: Date.now(),+ })+ } catch (e) {+ // A prompt the user stopped is not a failure. Anything else is, and+ // it used to vanish into a bare catch: a model that could not be+ // reached at all produced an empty run that read exactly like a+ // finished one, with no message anywhere.+ if (stoppedRef.current || abortRef.current?.signal.aborted) break+ store.setError(+ `${modelName}: ${e instanceof Error ? e.message : String(e)}. ` ++ 'Nothing was recorded for this run.',+ )+ break+ }}+ } finally {+ abortRef.current = null+ runningRef.current = false+ store.setRunning(false)}-- store.setRunning(false)}, [store])const stopBenchmark = useCallback(() => {+ // Order matters: the flag first, so the loop cannot start the next prompt+ // between the abort and the check. setRunning stays out of here, the run's+ // own finally owns it, or Stop would re-enable Run while the loop is still+ // winding down and a second loop could start on the same GPU.+ stoppedRef.current = trueabortRef.current?.abort()- store.setRunning(false)- }, [store])+ }, [])return { runBenchmark, stopBenchmark }}diff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.tsindex 4a8864b7..ce53b037 100644--- a/src/stores/benchmarkStore.ts+++ b/src/stores/benchmarkStore.ts@@ -8,7 +8,11 @@ interface BenchmarkState {currentModel: string | nullcurrentStep: numbertotalSteps: number+ /** Why the last run stopped early, or null. A benchmark that cannot start at+ * all used to be indistinguishable from one that finished. */+ error: string | nulladdResult: (result: BenchmarkResult) => void+ setError: (message: string | null) => voidsetRunning: (running: boolean, model?: string, total?: number) => voidsetStep: (step: number) => void/** Drop every recorded run. */@@ -29,6 +33,9 @@ export const useBenchmarkStore = create<BenchmarkState>()(currentModel: null,currentStep: 0,totalSteps: 0,+ error: null,++ setError: (message) => set({ error: message }),addResult: (result) => set((s) => {const existing = s.results[result.modelName] || []@@ -65,7 +72,14 @@ export const useBenchmarkStore = create<BenchmarkState>()(}}),}),- { name: 'lu-benchmark-store' }+ {+ name: 'lu-benchmark-store',+ // Only the measurements are worth keeping. Run state is about the run+ // that is happening now: a persisted isRunning left over from a crash+ // greys out the Run button forever, and a persisted error greets the+ // user with a complaint about a run from last week.+ partialize: (s) => ({ results: s.results }),+ }))@@ -104,17 +118,27 @@ export function toMarkdownReport(return lines.join('\n')}const pct = (v: number | null): string => (v === null ? '-' : `${Math.round(v * 100)}%`)+ // The columns follow the on-screen board, including the score it is ranked+ // by. Exporting a table sorted by score while printing only speed made the+ // order look wrong to anyone reading the file (review 2026-08-14).lines.push(- '| # | Model | Average t/s | Latest t/s | Avg tokens | Think | Correct | Runs |',- '| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |',+ '| # | Model | Score | Average t/s | Latest t/s | Avg tokens | Think | Correct | Runs |',+ '| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |',)board.forEach((entry, i) => {const latest = getLatestSpeed(results, entry.model)+ // A run the brake stopped is not a measurement either, and the footer+ // promises cut-off runs are marked. Counting only `truncated` left the+ // capped token count of a runaway sitting in the table unmarked.+ const flags = [+ entry.truncated > 0 ? `${entry.truncated} cut off` : '',+ entry.runaway > 0 ? `${entry.runaway} stopped by the brake` : '',+ ].filter(Boolean).join(', ')const tokens = entry.avgTokens === null? '-'- : `${entry.avgTokens}${entry.truncated > 0 ? ` (${entry.truncated} cut off)` : ''}`+ : `${entry.avgTokens}${flags ? ` (${flags})` : ''}`lines.push(- `| ${i + 1} | ${entry.model} | ${entry.avgTps} | ${latest ?? '-'} | ${tokens} | ${pct(entry.thinkShare)} | ${pct(entry.accuracy)} | ${entry.runs} |`,+ `| ${i + 1} | ${entry.model} | ${entry.score} | ${entry.avgTps} | ${latest ?? '-'} | ${tokens} | ${pct(entry.thinkShare)} | ${pct(entry.accuracy)} | ${entry.runs} |`,)})lines.push(@@ -124,8 +148,10 @@ export function toMarkdownReport('Average is every recorded run. Latest is the most recent benchmark pass.','Avg tokens is the whole output including reasoning; a lower count for the','same answers is the cheaper model. Think is the share of that output spent',- 'reasoning. Correct is how often the answer matched. A run cut off by the',- 'token budget is marked, and its token count is a floor, not a measurement.',+ 'reasoning. Correct is how often the answer matched. Score is what the',+ 'table is ranked by, speed weighed against correctness. A run cut off by',+ 'the token budget or stopped by the brake is marked, and its token count is',+ 'a floor, not a measurement.','',)return lines.join('\n')