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): runBenchmark bucht jetzt die lokale Spur
purple88ce7d271b0e
diff --git a/src/hooks/__tests__/benchmark-bucht-lokale-spur.test.ts b/src/hooks/__tests__/benchmark-bucht-lokale-spur.test.tsnew file mode 100644index 00000000..81f0d100--- /dev/null+++ b/src/hooks/__tests__/benchmark-bucht-lokale-spur.test.ts@@ -0,0 +1,124 @@+/**+ * @vitest-environment jsdom+ *+ * Runde 4 (review-lanes.md Blocker 1+6, Schritt 1 "andere Verbraucher der+ * lokalen Spur"): `useBenchmark`'s `runBenchmark` fires the same+ * `provider.chatStream` a visible chat turn does, prompt after prompt,+ * straight against the model under test. Before this it was invisible to+ * `lib/run-lanes.ts`: a local chat conversation running at the same time as+ * a benchmark of a local model raced it for the same engine, the VRAM-swap+ * race the lane exists to prevent, just triggered from Settings instead of+ * the composer.+ *+ * This file proves the fix against the real `lib/run-lanes.ts` module+ * (nothing about admit/release/queue is mocked): a benchmark of a local+ * model queues behind an already-running local conversation and only starts+ * once that conversation releases; a benchmark of a cloud model starts+ * immediately, same as any other cloud run; and Stop on a still-queued+ * benchmark dequeues it instead of leaving it to fire later, unattended,+ * once its turn eventually comes.+ *+ * NEGATIVE CONTROL (run by hand on 18.09., reverted after, confirmed green+ * again): removed the `runInLane(...)` wrap and called the loop directly.+ * "a benchmark of a local model queues behind a running local conversation"+ * went red with `expected 'started' to be 'queued'` (the second admit no+ * longer had anything to queue behind, because the benchmark's own call+ * never registered with run-lanes.ts at all).+ *+ * Run: npx vitest run src/hooks/__tests__/benchmark-bucht-lokale-spur.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { renderHook, act } from '@testing-library/react'+import { useBenchmark, BENCHMARK_LANE_ID } from '../useBenchmark'+import { useBenchmarkStore } from '../../stores/benchmarkStore'+import { admit, release, localLaneHolder, queuedRunIds, __resetRunLanesForTests } from '../../lib/run-lanes'+import { __resetRunSlotsForTests } from '../../lib/run-slot'++const chatStream = vi.fn(() => (async function* () {})())+let resolveMeasure: ((v: unknown) => void) | null = null++vi.mock('../../api/providers', () => ({+ getProviderForModel: (name: string) => ({+ provider: { chatStream },+ modelId: name.includes('::') ? name.split('::')[1] : name,+ }),+}))++vi.mock('../../lib/benchmark-run', () => ({+ measureRun: vi.fn(() => new Promise((resolve) => { resolveMeasure = resolve })),+}))++beforeEach(() => {+ __resetRunLanesForTests()+ __resetRunSlotsForTests()+ useBenchmarkStore.setState({ results: {}, isRunning: false, currentModel: null, currentStep: 0, totalSteps: 0, error: null })+ chatStream.mockClear()+ resolveMeasure = null+})++describe('runBenchmark bucht die lokale Spur', () => {+ it('ein lokales Modell wartet, waehrend eine echte Unterhaltung die Spur haelt', async () => {+ // A real chat conversation holds the local lane already.+ admit('local', 'conv-chat', () => {})+ expect(localLaneHolder()).toBe('conv-chat')++ const { result } = renderHook(() => useBenchmark())+ let laufend: Promise<void> | undefined+ act(() => {+ laufend = result.current.runBenchmark('qwen3:8b')+ })+ await Promise.resolve()++ // The benchmark's own call queued instead of racing the running chat.+ expect(queuedRunIds()).toContain(BENCHMARK_LANE_ID)+ expect(chatStream).not.toHaveBeenCalled()++ // The chat finishes; the benchmark is promoted and starts firing prompts.+ // `release` only returns the next run's `start` thunk, the caller (here:+ // this test, standing in for the chat's own `runInLane`) has to call it.+ act(() => { release('conv-chat')?.() })+ for (let i = 0; i < 10; i++) await Promise.resolve()++ expect(chatStream).toHaveBeenCalled()+ resolveMeasure?.({ tokensPerSec: 1, timeToFirstToken: 1, totalTime: 1, totalTokens: 1, thinkTokens: 0, finishReason: 'stop', correct: true })+ act(() => { result.current.stopBenchmark() })+ await laufend+ })++ it('ein Cloud-Modell startet sofort, ohne auf die lokale Spur zu warten', async () => {+ admit('local', 'conv-chat', () => {})++ const { result } = renderHook(() => useBenchmark())+ let laufend: Promise<void> | undefined+ act(() => {+ laufend = result.current.runBenchmark('lu-cloud::some/model')+ })+ await Promise.resolve()+ await Promise.resolve()++ expect(chatStream).toHaveBeenCalled()+ resolveMeasure?.({ tokensPerSec: 1, timeToFirstToken: 1, totalTime: 1, totalTokens: 1, thinkTokens: 0, finishReason: 'stop', correct: true })+ act(() => { result.current.stopBenchmark() })+ await laufend+ release('conv-chat')+ })++ it('Stop auf einem noch wartenden Benchmark nimmt ihn aus der Warteschlange', async () => {+ admit('local', 'conv-chat', () => {})++ const { result } = renderHook(() => useBenchmark())+ let laufend: Promise<void> | undefined+ act(() => {+ laufend = result.current.runBenchmark('qwen3:8b')+ })+ await Promise.resolve()+ expect(queuedRunIds()).toContain(BENCHMARK_LANE_ID)++ act(() => { result.current.stopBenchmark() })+ await laufend++ expect(queuedRunIds()).not.toContain(BENCHMARK_LANE_ID)+ expect(chatStream).not.toHaveBeenCalled()+ release('conv-chat')+ })+})diff --git a/src/hooks/useBenchmark.ts b/src/hooks/useBenchmark.tsindex ec3d7361..18d01a58 100644--- a/src/hooks/useBenchmark.ts+++ b/src/hooks/useBenchmark.ts@@ -8,6 +8,25 @@ import { getProviderForModel } from '../api/providers'import { BENCHMARK_PROMPTS } from '../lib/benchmark-prompts'import { measureRun } from '../lib/benchmark-run'import type { ChatMessage } from '../api/providers/types'+import { runInLane } from '../lib/run-slot'+import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'+import { useGenerationStore } from '../stores/generationStore'++/**+ * Booking identity for the local lane, standing in for a `conversationId`.+ *+ * Runde 4 (review-lanes.md Blocker 1+6, Schritt 1 "andere Verbraucher der+ * lokalen Spur"): a benchmark run fires the exact same `provider.chatStream`+ * a visible chat turn does, against the model under test, prompt after+ * prompt. Before this it was invisible to `lib/run-lanes.ts`: a local chat+ * running at the same time raced it for the same engine, the VRAM-swap this+ * whole module exists to prevent, just triggered from Settings instead of+ * the composer. A fixed, single id is enough (unlike the memory-extraction+ * case in `useMemory.ts`): `runBenchmark` already refuses to start a second+ * run while one is active (`runningRef`), so this id is never held by two+ * benchmark runs at once.+ */+export const BENCHMARK_LANE_ID = 'lib:benchmark-run'export function useBenchmark() {const store = useBenchmarkStore()@@ -31,59 +50,75 @@ export function useBenchmark() {store.setError(null)try {- for (let i = 0; i < BENCHMARK_PROMPTS.length; i++) {- if (stoppedRef.current) break- const prompt = BENCHMARK_PROMPTS[i]- store.setStep(i + 1)+ // A local model under test books the same lane a chat turn would; a+ // cloud model starts immediately, same as `admit` decides everywhere+ // else. If the lane is held by a running chat, this call queues here+ // and the whole prompt loop below starts only once its turn comes.+ // `abort` only matters for that queued wait (see run-slot.ts): once+ // the loop itself is running, Stop already reaches it through+ // `abortRef`.+ await runInLane(+ { conversationId: BENCHMARK_LANE_ID, lane: laneOf(modelName, currentLaneFacts()), abort: () => abortRef.current?.abort() },+ async () => {+ 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 (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- }- }+ 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+ }+ },+ )} finally {- abortRef.current = nullrunningRef.current = falsestore.setRunning(false)}@@ -96,6 +131,13 @@ export function useBenchmark() {// winding down and a second loop could start on the same GPU.stoppedRef.current = trueabortRef.current?.abort()+ // Reaches a benchmark that has not started yet, still queued on the local+ // lane behind a running chat: `abortRef` is still null at that point (the+ // loop above has not run once), so the line above alone does nothing.+ // `abortConversation` calls the abort callback `runInLane` registered at+ // admission time, which for a still-queued run dequeues it instead of+ // aborting a stream that does not exist yet (see run-slot.ts).+ useGenerationStore.getState().abortConversation(BENCHMARK_LANE_ID)}, [])return { runBenchmark, stopBenchmark }