Skip to content

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.

fix(compare): A/B Compare bucht die lokale Spur, zwei lokale Modelle laufen nacheinander

purplea14f329c7529
diff --git a/src/hooks/__tests__/ab-compare-bucht-lokale-spur.test.ts b/src/hooks/__tests__/ab-compare-bucht-lokale-spur.test.ts
new file mode 100644
index 00000000..af4cc194
--- /dev/null
+++ b/src/hooks/__tests__/ab-compare-bucht-lokale-spur.test.ts
@@ -0,0 +1,189 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 5 Nachtrag (review-lanes.md Runde 2, Grep-Audit dieser Runde,
+ * David's Nachtrag danach): `useABCompare.ts` fires two genuine
+ * `provider.chatStream` calls per round, one per model, with NO reference
+ * to `run-lanes.ts` at all. Confirmed by reading the file: both `streamA`
+ * and `streamB` call `getProviderForModel(...).provider.chatStream(...)`
+ * directly.
+ *
+ * Two models that BOTH resolve to the local lane would have fired at the
+ * same one-slot built-in engine at once (`Promise.all([streamA(), streamB()])`),
+ * the same VRAM-swap Blocker A and B this round were about. Even with only
+ * ONE local side, the round still needs to book the lane, or it can race an
+ * unrelated local conversation running elsewhere in the app.
+ *
+ * Fix: the whole round now runs inside `runInLane`. If EITHER side is local,
+ * the round holds the local lane. If BOTH sides are local, they run one
+ * after another under that SAME held booking (not queued behind each other,
+ * which would just lock the round out against itself). A mixed or all-cloud
+ * pairing keeps the original parallel behaviour, since at most one side ever
+ * touches the shared engine.
+ *
+ * Run: npx vitest run src/hooks/__tests__/ab-compare-bucht-lokale-spur.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: (model: string) => (model.startsWith('cloud::') ? 'cloud' : 'local'),
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+
+/** A hand-controlled `provider.chatStream`-shaped async generator. */
+function controllableChatStream() {
+ const chunks: Array<{ content: string; done: boolean }> = []
+ let notify: (() => void) | null = null
+ const push = (content: string) => { chunks.push({ content, done: false }); notify?.(); notify = null }
+ const done = () => { chunks.push({ content: '', done: true }); notify?.(); notify = null }
+ async function* gen() {
+ for (;;) {
+ if (chunks.length === 0) await new Promise<void>((res) => { notify = res })
+ while (chunks.length) {
+ const c = chunks.shift()!
+ yield c
+ if (c.done) return
+ }
+ }
+ }
+ return { stream: gen(), push, done }
+}
+
+let chatStreamCalls: string[] = []
+let streams: Record<string, ReturnType<typeof controllableChatStream>> = {}
+vi.mock('../../api/providers', () => ({
+ getProviderForModel: (model: string) => ({
+ provider: {
+ chatStream: (_modelId: string, _messages: unknown, _opts: unknown) => {
+ chatStreamCalls.push(model)
+ return streams[model].stream
+ },
+ },
+ modelId: model,
+ }),
+ getProviderIdFromModel: (model: string) => (model.startsWith('cloud::') ? 'lu-cloud' : 'openai'),
+}))
+
+import { useABCompare } from '../useABCompare'
+import { useCompareStore } from '../../stores/compareStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { __resetRunLanesForTests, localLaneHolder, queuedRunIds } from '../../lib/run-lanes'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+
+const LOCAL_A = 'local::model-a'
+const LOCAL_B = 'local::model-b'
+const CLOUD_A = 'cloud::model-a'
+const CLOUD_B = 'cloud::model-b'
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ chatStreamCalls = []
+ streams = {}
+ useCompareStore.setState({
+ isComparing: true, modelA: '', modelB: '',
+ messagesA: [], messagesB: [], statsA: null, statsB: null,
+ isStreamingA: false, isStreamingB: false,
+ })
+ // contextDecay: false steers chat-send-budget's notaus, so sendCompare
+ // never calls the async getModelMaxTokens at all, keeping this test's
+ // provider mock small and deterministic.
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, contextDecay: false },
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+function seed(modelA: string, modelB: string, streamA = controllableChatStream(), streamB = controllableChatStream()) {
+ useCompareStore.setState({ modelA, modelB })
+ streams[modelA] = streamA
+ streams[modelB] = streamB
+ return { streamA, streamB }
+}
+
+describe('A/B Compare bucht die lokale Spur', () => {
+ it('zwei lokale Modelle laufen NACHEINANDER unter EINER gehaltenen Buchung, nicht gleichzeitig', async () => {
+ const { streamA, streamB } = seed(LOCAL_A, LOCAL_B)
+ const { result } = renderHook(() => useABCompare())
+
+ let round: Promise<void> = Promise.resolve()
+ await act(async () => {
+ round = result.current.sendCompare('same prompt to both')
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+ })
+
+ // Only A has been asked so far: B waits for A to finish, same booking.
+ expect(chatStreamCalls).toEqual([LOCAL_A])
+ expect(localLaneHolder()).toBe('lib:ab-compare')
+ // Not a queued SEPARATE run: B is part of the SAME held round.
+ expect(queuedRunIds()).toEqual([])
+
+ // A different, genuinely separate local conversation must queue while
+ // the round holds the lane.
+ const otherAdmit = await import('../../lib/run-lanes').then((m) => m.admit('local', 'conv-elsewhere', () => {}))
+ expect(otherAdmit).toBe('queued')
+
+ await act(async () => {
+ streamA.push('answer-a')
+ streamA.done()
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+ })
+
+ // A is done, B now runs.
+ expect(chatStreamCalls).toEqual([LOCAL_A, LOCAL_B])
+
+ await act(async () => {
+ streamB.push('answer-b')
+ streamB.done()
+ await round
+ })
+
+ expect(useCompareStore.getState().messagesA.at(-1)?.content).toBe('answer-a')
+ expect(useCompareStore.getState().messagesB.at(-1)?.content).toBe('answer-b')
+ expect(localLaneHolder()).toBe('conv-elsewhere')
+ expect(queuedRunIds()).toEqual([])
+ })
+
+ it('gemischtes Paar (ein lokales, ein Cloud-Modell) laeuft weiterhin PARALLEL, haelt aber die lokale Spur', async () => {
+ const { streamA, streamB } = seed(LOCAL_A, CLOUD_B)
+ const { result } = renderHook(() => useABCompare())
+
+ let round: Promise<void> = Promise.resolve()
+ await act(async () => {
+ round = result.current.sendCompare('same prompt to both')
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+ })
+
+ // Both fired at once: only ONE side touches the shared local engine.
+ expect(chatStreamCalls.sort()).toEqual([CLOUD_B, LOCAL_A].sort())
+ expect(localLaneHolder()).toBe('lib:ab-compare')
+
+ await act(async () => {
+ streamA.push('answer-a'); streamA.done()
+ streamB.push('answer-b'); streamB.done()
+ await round
+ })
+
+ expect(localLaneHolder()).toBeNull()
+ })
+
+ it('GEGENPROBE: zwei Cloud-Modelle buchen gar keine lokale Spur', async () => {
+ const { streamA, streamB } = seed(CLOUD_A, CLOUD_B)
+ const { result } = renderHook(() => useABCompare())
+
+ let round: Promise<void> = Promise.resolve()
+ await act(async () => {
+ round = result.current.sendCompare('same prompt to both')
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+ })
+
+ expect(chatStreamCalls.sort()).toEqual([CLOUD_A, CLOUD_B].sort())
+ expect(localLaneHolder()).toBeNull()
+
+ await act(async () => {
+ streamA.push('answer-a'); streamA.done()
+ streamB.push('answer-b'); streamB.done()
+ await round
+ })
+ })
+})
diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.ts
index 47c1f2fa..3dfaeeb4 100644
--- a/src/hooks/useABCompare.ts
+++ b/src/hooks/useABCompare.ts
@@ -16,6 +16,28 @@ import type { Message } from '../types/chat'
import { createThinkStreamSplitter } from '../lib/hermes-stream'
import { settleThinking } from '../lib/thinking-stripper'
import { isThinkingCompatible } from '../lib/model-compatibility'
+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 5 (review-lanes.md Runde 2, Nachtrag nach dem Grep-Audit dieser
+ * Runde): A/B Compare fires two genuine `provider.chatStream` calls per
+ * round, one per model, entirely outside `run-lanes.ts`. If both sides
+ * resolve to the local lane (the same shared, one-slot built-in engine),
+ * `Promise.all([streamA(), streamB()])` sent both at once against that one
+ * slot, the exact VRAM-swap this module exists to prevent, just triggered
+ * from the Compare pane instead of the composer. Even with only ONE local
+ * side, the round needs to book the lane so it does not race a separate,
+ * unrelated local conversation running elsewhere in the app. A fixed,
+ * single id is enough, the same reasoning as `useBenchmark.ts`'s
+ * `BENCHMARK_LANE_ID`: the Compare pane disables its own Send button while
+ * a round is in flight (`isStreaming`), so this id is never held by two
+ * Compare rounds at once.
+ */
+export const COMPARE_LANE_ID = 'lib:ab-compare'
export function useABCompare() {
const store = useCompareStore()
@@ -177,13 +199,46 @@ export function useABCompare() {
})
}
- // Run both in parallel
- await Promise.all([streamA(), streamB()])
+ // Runde 5: the round holds the local lane whenever either side touches
+ // it. Two models that BOTH resolve to local would otherwise fire at the
+ // one-slot built-in engine at the same time; those two run one after the
+ // other, still under the SAME held booking (not queued behind each
+ // other, which would just lock the round out against itself). A mixed
+ // or all-cloud pairing keeps the original parallel behaviour, since at
+ // most one side ever touches the shared engine.
+ const facts = currentLaneFacts()
+ const laneA = laneOf(modelA, facts)
+ const laneB = laneOf(modelB, facts)
+ const bothLocal = laneA === 'local' && laneB === 'local'
+ const lane = laneA === 'local' || laneB === 'local' ? 'local' : 'cloud'
+
+ await runInLane(
+ {
+ conversationId: COMPARE_LANE_ID,
+ lane,
+ abort: () => { abortA.current?.abort(); abortB.current?.abort() },
+ },
+ async () => {
+ if (bothLocal) {
+ await streamA()
+ await streamB()
+ } else {
+ await Promise.all([streamA(), streamB()])
+ }
+ },
+ )
}, [settings, store])
const stopCompare = useCallback(() => {
abortA.current?.abort()
abortB.current?.abort()
+ // Reaches a round still queued on the local lane behind a running
+ // conversation: at that point neither stream has started, so the two
+ // lines above alone do nothing. `abortConversation` calls the abort
+ // callback `runInLane` registered at admission time, which for a
+ // queued run dequeues it instead of aborting streams that do not exist
+ // yet (see run-slot.ts).
+ useGenerationStore.getState().abortConversation(COMPARE_LANE_ID)
store.setStreamingA(false)
store.setStreamingB(false)
}, [store])