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.

feat(generation): pre-VRAM-swap model picker with save + Change Model

purpleb43de0fd2732
diff --git a/src/api/__tests__/model-pick.test.ts b/src/api/__tests__/model-pick.test.ts
new file mode 100644
index 00000000..64b8bb48
--- /dev/null
+++ b/src/api/__tests__/model-pick.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Model-Picker gate (v2.5.3) — executor-side behaviour of
+ * pickModelForGeneration: explicit model wins, saved preference is silent,
+ * otherwise the pick request goes through useModelPickStore and the save
+ * icon persists the choice. Filtering mirrors the decide phase (I2V vs T2V).
+ *
+ * Run: npx vitest run src/api/__tests__/model-pick.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../comfyui', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../comfyui')>()
+ return { ...actual, getImageModels: vi.fn(), getVideoModels: vi.fn() }
+})
+
+import { pickModelForGeneration } from '../model-pick'
+import { getImageModels, getVideoModels } from '../comfyui'
+import { useModelPickStore } from '../../stores/modelPickStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+
+const IMAGE_MODELS = [
+ { name: 'Juggernaut-XL_v9.safetensors', type: 'sdxl', source: 'checkpoint' },
+ { name: 'RealVisXL_V5.safetensors', type: 'sdxl', source: 'checkpoint' },
+] as never
+
+const VIDEO_MODELS = [
+ { name: 'svd_xt_1_1.safetensors', type: 'svd', source: 'checkpoint' },
+ { name: 'wan2.1_t2v_1.3B_bf16.safetensors', type: 'wan', source: 'diffusion_model' },
+ { name: 'FramePackI2V_HY_fp8_e4m3fn.safetensors', type: 'framepack', source: 'diffusion_model' },
+] as never
+
+/** Resolve the pending pick from the "UI side" as soon as it appears. */
+async function answerPick(choice: { model: string; save: boolean } | null) {
+ await vi.waitFor(() => {
+ if (!useModelPickStore.getState().pending) throw new Error('no pending pick yet')
+ })
+ if (choice) useModelPickStore.getState().choose(choice)
+ else useModelPickStore.getState().cancel()
+}
+
+beforeEach(() => {
+ vi.mocked(getImageModels).mockResolvedValue(IMAGE_MODELS)
+ vi.mocked(getVideoModels).mockResolvedValue(VIDEO_MODELS)
+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS } })
+ // No pending pick leaks between tests.
+ if (useModelPickStore.getState().pending) useModelPickStore.getState().cancel()
+})
+
+describe('pickModelForGeneration — image', () => {
+ it('explicit model arg wins: no picker, returns null', async () => {
+ const result = await pickModelForGeneration('image', { model: 'RealVisXL_V5.safetensors' })
+ expect(result).toBeNull()
+ expect(useModelPickStore.getState().pending).toBeNull()
+ })
+
+ it('saved + installed preference is used silently (no picker)', async () => {
+ useSettingsStore.getState().updateSettings({ preferredImageModel: 'RealVisXL_V5.safetensors' })
+ const result = await pickModelForGeneration('image', {})
+ expect(result).toBe('RealVisXL_V5.safetensors')
+ expect(useModelPickStore.getState().pending).toBeNull()
+ })
+
+ it('no saved preference → picker; choice without save is NOT persisted', async () => {
+ const p = pickModelForGeneration('image', {})
+ await answerPick({ model: 'RealVisXL_V5.safetensors', save: false })
+ expect(await p).toBe('RealVisXL_V5.safetensors')
+ expect(useSettingsStore.getState().settings.preferredImageModel).toBe('')
+ })
+
+ it('save icon persists the choice for future prompts', async () => {
+ const p = pickModelForGeneration('image', {})
+ await answerPick({ model: 'Juggernaut-XL_v9.safetensors', save: true })
+ expect(await p).toBe('Juggernaut-XL_v9.safetensors')
+ expect(useSettingsStore.getState().settings.preferredImageModel).toBe('Juggernaut-XL_v9.safetensors')
+ })
+
+ it('saved-but-uninstalled preference re-opens the picker', async () => {
+ useSettingsStore.getState().updateSettings({ preferredImageModel: 'gone.safetensors' })
+ const p = pickModelForGeneration('image', {})
+ await answerPick({ model: 'Juggernaut-XL_v9.safetensors', save: false })
+ expect(await p).toBe('Juggernaut-XL_v9.safetensors')
+ })
+
+ it('timeout/cancel falls back to the pre-selection (first installed)', async () => {
+ const p = pickModelForGeneration('image', {})
+ await answerPick(null)
+ expect(await p).toBe('Juggernaut-XL_v9.safetensors')
+ })
+
+ it('ComfyUI unreachable → null (existing pipeline reports)', async () => {
+ vi.mocked(getImageModels).mockRejectedValue(new Error('ECONNREFUSED'))
+ expect(await pickModelForGeneration('image', {})).toBeNull()
+ })
+
+ it('no models installed → null (existing no-model error path)', async () => {
+ vi.mocked(getImageModels).mockResolvedValue([] as never)
+ expect(await pickModelForGeneration('image', {})).toBeNull()
+ })
+})
+
+describe('pickModelForGeneration — video T2V vs I2V', () => {
+ it('text-to-video offers ONLY non-I2V models and uses the T2V pref key', async () => {
+ const p = pickModelForGeneration('video', {})
+ await vi.waitFor(() => {
+ if (!useModelPickStore.getState().pending) throw new Error('no pending')
+ })
+ const pending = useModelPickStore.getState().pending!
+ expect(pending.kind).toBe('video-t2v')
+ expect(pending.models).toEqual(['wan2.1_t2v_1.3B_bf16.safetensors'])
+ useModelPickStore.getState().choose({ model: 'wan2.1_t2v_1.3B_bf16.safetensors', save: true })
+ expect(await p).toBe('wan2.1_t2v_1.3B_bf16.safetensors')
+ expect(useSettingsStore.getState().settings.preferredVideoT2VModel).toBe('wan2.1_t2v_1.3B_bf16.safetensors')
+ expect(useSettingsStore.getState().settings.preferredVideoI2VModel).toBe('')
+ })
+
+ it('image-to-video offers ONLY I2V models (SVD/FramePack) and the I2V pref key', async () => {
+ const p = pickModelForGeneration('video', { inputImage: 'ComfyUI_0001.png' })
+ await vi.waitFor(() => {
+ if (!useModelPickStore.getState().pending) throw new Error('no pending')
+ })
+ const pending = useModelPickStore.getState().pending!
+ expect(pending.kind).toBe('video-i2v')
+ expect(pending.models.sort()).toEqual(['FramePackI2V_HY_fp8_e4m3fn.safetensors', 'svd_xt_1_1.safetensors'])
+ useModelPickStore.getState().choose({ model: 'svd_xt_1_1.safetensors', save: true })
+ expect(await p).toBe('svd_xt_1_1.safetensors')
+ expect(useSettingsStore.getState().settings.preferredVideoI2VModel).toBe('svd_xt_1_1.safetensors')
+ })
+
+ it('the snake_case input_image alias classifies as I2V too', async () => {
+ const p = pickModelForGeneration('video', { input_image: 'x.png' })
+ await vi.waitFor(() => {
+ if (!useModelPickStore.getState().pending) throw new Error('no pending')
+ })
+ expect(useModelPickStore.getState().pending!.kind).toBe('video-i2v')
+ useModelPickStore.getState().cancel()
+ await p
+ })
+
+ it('separate saved T2V/I2V preferences never cross', async () => {
+ useSettingsStore.getState().updateSettings({
+ preferredVideoT2VModel: 'wan2.1_t2v_1.3B_bf16.safetensors',
+ preferredVideoI2VModel: 'svd_xt_1_1.safetensors',
+ })
+ expect(await pickModelForGeneration('video', {})).toBe('wan2.1_t2v_1.3B_bf16.safetensors')
+ expect(await pickModelForGeneration('video', { inputImage: 'a.png' })).toBe('svd_xt_1_1.safetensors')
+ })
+})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index b1a05789..3dc14091 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1001,6 +1001,13 @@ async function executeImageGenerate(args: Record<string, any>): Promise<string>
const flat: Record<string, any> = {}
for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+ // Model-Picker gate (v2.5.3): BEFORE the VRAM swap, let the user pick the
+ // ComfyUI model in the tool call (or silently use the saved preference).
+ // Returns null when an explicit model arg exists / nothing is installed /
+ // ComfyUI is unreachable — the existing pipeline then behaves as before.
+ const { pickModelForGeneration } = await import('../model-pick')
+ const picked = await pickModelForGeneration('image', merged)
+ if (picked) merged.model = picked
const { vramHandoffGenerate } = await import('../vram-handoff')
return vramHandoffGenerate('image', merged)
}
@@ -1021,6 +1028,11 @@ async function executeVideoGenerate(args: Record<string, any>): Promise<string>
const flat: Record<string, any> = {}
for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+ // Model-Picker gate (v2.5.3) — see executeImageGenerate. T2V and I2V keep
+ // separate saved preferences (disjoint capability sets).
+ const { pickModelForGeneration } = await import('../model-pick')
+ const picked = await pickModelForGeneration('video', merged)
+ if (picked) merged.model = picked
const { vramHandoffGenerate } = await import('../vram-handoff')
return vramHandoffGenerate('video', merged)
}
diff --git a/src/api/model-pick.ts b/src/api/model-pick.ts
new file mode 100644
index 00000000..db8e6ca6
--- /dev/null
+++ b/src/api/model-pick.ts
@@ -0,0 +1,63 @@
+import { getImageModels, getVideoModels, isI2VModel } from './comfyui'
+import type { ModelPickKind } from '../stores/modelPickStore'
+
+/**
+ * Model-Picker gate (v2.5.3). Runs inside executeImageGenerate /
+ * executeVideoGenerate BEFORE vramHandoffGenerate — i.e. before the VRAM
+ * swap — and returns the model name the generation should use, or null to
+ * leave the existing auto-selection untouched. The pick is OURS (LU UI),
+ * not the LLM's:
+ *
+ * - explicit `model` arg from the user/LLM → no picker (intent wins)
+ * - saved preference installed → silent use (Change-Model
+ * affordance shows in the tool call instead)
+ * - nothing saved (or saved got uninstalled) → ModelPickerCard renders in
+ * the running tool call; save icon persists the choice for next prompts
+ * - ComfyUI unreachable / no models → null (the existing decide
+ * phase reports its own actionable error — UX identical to before)
+ *
+ * Model filtering mirrors vram-handoff's decide phase exactly: image =
+ * getImageModels; video splits by inputImage into I2V (isI2VModel) vs T2V
+ * (the rest). The preference keys are per-kind because the sets are
+ * disjoint (SVD can't T2V, Wan 1.3B can't I2V).
+ */
+export async function pickModelForGeneration(
+ kind: 'image' | 'video',
+ args: Record<string, any>,
+): Promise<string | null> {
+ if (typeof args.model === 'string' && args.model) return null
+
+ // Same alias normalization as runHandoff — the pick must classify the call
+ // the same way the decide phase will (input_image / image → inputImage).
+ const inputImage = args.inputImage ?? args.input_image ?? args.image
+ const wantI2V = kind === 'video' && typeof inputImage === 'string' && !!inputImage
+ const pickKind: ModelPickKind = kind === 'image' ? 'image' : wantI2V ? 'video-i2v' : 'video-t2v'
+
+ let names: string[]
+ try {
+ const models = kind === 'image' ? await getImageModels() : await getVideoModels()
+ const eligible = kind === 'image'
+ ? models
+ : models.filter((m) => (wantI2V ? isI2VModel(m.name) : !isI2VModel(m.name)))
+ names = eligible.map((m) => m.name)
+ } catch {
+ return null
+ }
+ if (names.length === 0) return null
+
+ const { useSettingsStore } = await import('../stores/settingsStore')
+ const prefKey =
+ pickKind === 'image' ? 'preferredImageModel'
+ : pickKind === 'video-t2v' ? 'preferredVideoT2VModel'
+ : 'preferredVideoI2VModel'
+ const saved = useSettingsStore.getState().settings[prefKey]
+ if (saved && names.includes(saved)) return saved
+
+ const { useModelPickStore } = await import('../stores/modelPickStore')
+ const choice = await useModelPickStore.getState().request(pickKind, names, names[0])
+ if (!choice) return names[0]
+ if (choice.save) {
+ useSettingsStore.getState().updateSettings({ [prefKey]: choice.model })
+ }
+ return choice.model
+}
diff --git a/src/components/chat/ModelPickerCard.tsx b/src/components/chat/ModelPickerCard.tsx
new file mode 100644
index 00000000..edd403ef
--- /dev/null
+++ b/src/components/chat/ModelPickerCard.tsx
@@ -0,0 +1,209 @@
+import { useEffect, useRef, useState } from 'react'
+import { Save, Check, Loader2, Settings2, X } from 'lucide-react'
+import { useModelPickStore, MODEL_PICK_TIMEOUT_MS, type ModelPickKind, type ModelPickRequest } from '../../stores/modelPickStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { getImageModels, getVideoModels, isI2VModel } from '../../api/comfyui'
+import type { AgentToolCall } from '../../types/agent-mode'
+
+/**
+ * Model-Picker UI (v2.5.3, David 2026-06-10). Two faces of one feature:
+ *
+ * <ModelPickerCard/> — the BLOCKING pick rendered inside a running
+ * image_generate / video_generate tool call BEFORE the VRAM swap. LU
+ * (not the LLM) lists the installed ComfyUI models; Continue resolves
+ * the executor's promise; the save icon persists the choice for future
+ * prompts. A live countdown auto-continues with the on-screen selection
+ * so an AFK user still gets their generation (pre-picker behaviour).
+ *
+ * <ChangeModelInline/> — the mini "Change model" affordance shown on
+ * generation tool calls once a preference is saved. Opens the same
+ * list; a click rewrites the saved preference (applies from the next
+ * generation on).
+ */
+
+export const PICK_KIND_LABEL: Record<ModelPickKind, string> = {
+ image: 'image model',
+ 'video-t2v': 'video model · text-to-video',
+ 'video-i2v': 'video model · image-to-video',
+}
+
+export const PICK_PREF_KEY: Record<ModelPickKind, 'preferredImageModel' | 'preferredVideoT2VModel' | 'preferredVideoI2VModel'> = {
+ image: 'preferredImageModel',
+ 'video-t2v': 'preferredVideoT2VModel',
+ 'video-i2v': 'preferredVideoI2VModel',
+}
+
+/** Which pick-kind a generation tool call belongs to (null = not a gen tool).
+ * Mirrors the executor's alias normalization so the card and the gate
+ * classify identically. Exported for tests. */
+export function pickKindForToolCall(toolCall: Pick<AgentToolCall, 'toolName' | 'args'>): ModelPickKind | null {
+ if (toolCall.toolName === 'image_generate') return 'image'
+ if (toolCall.toolName !== 'video_generate') return null
+ const a = (toolCall.args ?? {}) as Record<string, any>
+ const s = (a.settings && typeof a.settings === 'object' ? a.settings : {}) as Record<string, any>
+ const inputImage = a.inputImage ?? a.input_image ?? a.image ?? s.inputImage ?? s.input_image ?? s.image
+ return typeof inputImage === 'string' && inputImage ? 'video-i2v' : 'video-t2v'
+}
+
+/** Strip the extension for compact display ("Juggernaut-XL_v9"). */
+const shortName = (n: string) => n.replace(/\.(safetensors|ckpt|pt|gguf|bin)$/i, '')
+
+function ModelList({ models, selected, onPick }: { models: string[]; selected: string; onPick: (m: string) => void }) {
+ return (
+ <div className="space-y-0.5 max-h-40 overflow-y-auto scrollbar-thin pr-0.5">
+ {models.map((m) => (
+ <button
+ key={m}
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onPick(m) }}
+ className={`w-full text-left px-2 py-1 rounded border text-[0.6rem] transition-colors truncate ${
+ m === selected
+ ? 'border-blue-400/40 bg-blue-500/10 text-gray-900 dark:text-gray-100'
+ : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.03] text-gray-600 dark:text-gray-400 hover:border-gray-300 dark:hover:border-white/20'
+ }`}
+ title={m}
+ >
+ {m === selected ? '● ' : ''}{shortName(m)}
+ </button>
+ ))}
+ </div>
+ )
+}
+
+// ── Blocking pick (pre-VRAM-swap) ─────────────────────────────────
+
+export function ModelPickerCard({ request }: { request: ModelPickRequest }) {
+ const choose = useModelPickStore((s) => s.choose)
+ const [selected, setSelected] = useState(request.current)
+ const [save, setSave] = useState(false)
+ // Auto-continue 5s before the store's headless fallback so the countdown
+ // resolves with the user's ON-SCREEN selection, not just the default.
+ const [secondsLeft, setSecondsLeft] = useState(Math.max(5, Math.floor((MODEL_PICK_TIMEOUT_MS - 5000) / 1000)))
+ const stateRef = useRef({ selected, save })
+ stateRef.current = { selected, save }
+
+ useEffect(() => {
+ const t = setInterval(() => {
+ setSecondsLeft((s) => {
+ if (s <= 1) {
+ clearInterval(t)
+ choose({ model: stateRef.current.selected, save: stateRef.current.save })
+ return 0
+ }
+ return s - 1
+ })
+ }, 1000)
+ return () => clearInterval(t)
+ }, [choose, request.id])
+
+ return (
+ <div className="mt-1 ml-5 rounded-md border border-blue-400/25 bg-blue-500/[0.04] px-2.5 py-2 space-y-1.5" data-testid="model-picker-card">
+ <div className="text-[0.6rem] font-medium text-gray-700 dark:text-gray-300">
+ Pick the {PICK_KIND_LABEL[request.kind]}
+ <span className="ml-1 font-normal text-gray-500 dark:text-gray-500">— runs before the VRAM swap</span>
+ </div>
+ <ModelList models={request.models} selected={selected} onPick={setSelected} />
+ <div className="flex items-center gap-2 pt-0.5">
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); choose({ model: selected, save }) }}
+ className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium text-blue-700 dark:text-blue-300 bg-blue-500/10 hover:bg-blue-500/15 border border-blue-500/25 transition-colors"
+ >
+ <Check size={10} /> Continue
+ </button>
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); setSave(!save) }}
+ title="Remember this model for future prompts"
+ className={`flex items-center gap-1 px-2 py-1 rounded text-[0.55rem] border transition-colors ${
+ save
+ ? 'text-emerald-700 dark:text-emerald-300 bg-emerald-500/10 border-emerald-500/25'
+ : 'text-gray-500 dark:text-gray-500 border-gray-200 dark:border-white/10 hover:border-gray-300 dark:hover:border-white/20'
+ }`}
+ >
+ <Save size={10} /> {save ? 'Will remember' : 'Remember'}
+ </button>
+ <span className="ml-auto text-[0.5rem] text-gray-400 dark:text-gray-600">
+ auto-continues with {shortName(selected)} in {secondsLeft}s
+ </span>
+ </div>
+ </div>
+ )
+}
+
+// ── "Change model" mini affordance (saved preference active) ──────
+
+export function ChangeModelInline({ kind }: { kind: ModelPickKind }) {
+ const prefKey = PICK_PREF_KEY[kind]
+ const preferred = useSettingsStore((s) => s.settings[prefKey])
+ const updateSettings = useSettingsStore((s) => s.updateSettings)
+ const [open, setOpen] = useState(false)
+ const [models, setModels] = useState<string[] | null>(null)
+ const [loadError, setLoadError] = useState(false)
+ const [savedFlash, setSavedFlash] = useState(false)
+
+ useEffect(() => {
+ if (!open || models !== null) return
+ let cancelled = false
+ ;(async () => {
+ try {
+ const all = kind === 'image' ? await getImageModels() : await getVideoModels()
+ const eligible = kind === 'image'
+ ? all
+ : all.filter((m) => (kind === 'video-i2v' ? isI2VModel(m.name) : !isI2VModel(m.name)))
+ if (!cancelled) setModels(eligible.map((m) => m.name))
+ } catch {
+ if (!cancelled) { setLoadError(true); setModels([]) }
+ }
+ })()
+ return () => { cancelled = true }
+ }, [open, models, kind])
+
+ if (!preferred) return null
+
+ return (
+ <div className="ml-5 mt-0.5" data-testid="change-model-inline">
+ {!open ? (
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); setOpen(true) }}
+ className="flex items-center gap-1 text-[0.5rem] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors"
+ title={`Saved model: ${preferred}`}
+ >
+ <Settings2 size={8} /> {shortName(preferred)} · Change model
+ </button>
+ ) : (
+ <div className="rounded-md border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.03] px-2.5 py-2 space-y-1.5 max-w-sm">
+ <div className="flex items-center justify-between">
+ <span className="text-[0.55rem] font-medium text-gray-600 dark:text-gray-400">
+ Saved {PICK_KIND_LABEL[kind]} — applies from the next generation
+ </span>
+ <button type="button" onClick={(e) => { e.stopPropagation(); setOpen(false) }} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
+ <X size={9} />
+ </button>
+ </div>
+ {models === null && (
+ <div className="flex items-center gap-1 text-[0.55rem] text-gray-500"><Loader2 size={9} className="animate-spin" /> loading models…</div>
+ )}
+ {loadError && (
+ <div className="text-[0.55rem] text-amber-500">Could not reach ComfyUI — model list unavailable.</div>
+ )}
+ {models !== null && models.length > 0 && (
+ <ModelList
+ models={models}
+ selected={preferred}
+ onPick={(m) => {
+ updateSettings({ [prefKey]: m })
+ setSavedFlash(true)
+ setTimeout(() => { setSavedFlash(false); setOpen(false) }, 1200)
+ }}
+ />
+ )}
+ {savedFlash && (
+ <div className="flex items-center gap-1 text-[0.55rem] text-emerald-500"><Check size={9} /> Saved — next generation uses it.</div>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index 04e83fc6..ad3db0e9 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -3,6 +3,8 @@ import { motion, AnimatePresence } from 'framer-motion'
import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, Database } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
import { getComfyHost, getComfyPort } from '../../api/backend'
+import { useModelPickStore } from '../../stores/modelPickStore'
+import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './ModelPickerCard'
// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)
// — when image_generate / video_generate / screenshot produce a ComfyUI output,
@@ -98,6 +100,14 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
// without the user having to expand the block — konata's "and no image".
const previewUrl = comfyViewUrlFromResult(toolCall.result)
+ // Model-Picker (v2.5.3): while a generation tool call is RUNNING and the
+ // executor's pre-VRAM-swap gate is waiting, render the picker inside this
+ // block. Once a preference is saved (no picker shows), a mini "Change
+ // model" line takes its place so the choice stays one click away.
+ const pendingPick = useModelPickStore((s) => s.pending)
+ const genKind = pickKindForToolCall(toolCall)
+ const showPicker = !!genKind && !!pendingPick && pendingPick.kind === genKind && isRunning
+
// Proxy-independent loading (konata 2026-06-08). In browser/dev the tool
// result carries the RELATIVE `/comfyui/view?…` Vite-proxy path, which loads
// fine under `npm run dev` (verified E2E). But a built frontend served
@@ -138,6 +148,12 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
)}
</button>
+ {/* Model-Picker (v2.5.3) — LU's own pre-VRAM-swap model choice, shown
+ while the executor gate awaits the pick. Falls back to the mini
+ "Change model" line once a preference is saved. */}
+ {showPicker && pendingPick && <ModelPickerCard request={pendingPick} />}
+ {!showPicker && genKind && <ChangeModelInline kind={genKind} />}
+
{/* Inline media preview — ALWAYS visible for a completed image/video
generation, even while the tool block stays collapsed. Before the
konata 2026-06-07 fix this lived inside the collapsed details, so a
diff --git a/src/components/chat/__tests__/model-picker-kind.test.ts b/src/components/chat/__tests__/model-picker-kind.test.ts
new file mode 100644
index 00000000..1e265e17
--- /dev/null
+++ b/src/components/chat/__tests__/model-picker-kind.test.ts
@@ -0,0 +1,39 @@
+/**
+ * pickKindForToolCall — the ToolCallBlock-side classification must mirror
+ * the executor gate (image vs video-t2v vs video-i2v incl. aliases), or the
+ * picker card would attach to the wrong tool call.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/model-picker-kind.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { pickKindForToolCall, PICK_PREF_KEY } from '../ModelPickerCard'
+
+const tc = (toolName: string, args: Record<string, unknown> = {}) => ({ toolName, args }) as never
+
+describe('pickKindForToolCall', () => {
+ it('image_generate → image', () => {
+ expect(pickKindForToolCall(tc('image_generate'))).toBe('image')
+ })
+
+ it('video_generate without input image → video-t2v', () => {
+ expect(pickKindForToolCall(tc('video_generate', { prompt: 'waves' }))).toBe('video-t2v')
+ })
+
+ it('video_generate with inputImage → video-i2v (flat, snake_case, image, nested settings)', () => {
+ expect(pickKindForToolCall(tc('video_generate', { inputImage: 'a.png' }))).toBe('video-i2v')
+ expect(pickKindForToolCall(tc('video_generate', { input_image: 'a.png' }))).toBe('video-i2v')
+ expect(pickKindForToolCall(tc('video_generate', { image: 'a.png' }))).toBe('video-i2v')
+ expect(pickKindForToolCall(tc('video_generate', { settings: { inputImage: 'a.png' } }))).toBe('video-i2v')
+ })
+
+ it('non-generation tools → null', () => {
+ expect(pickKindForToolCall(tc('file_read', { path: 'x' }))).toBeNull()
+ expect(pickKindForToolCall(tc('web_search', { query: 'x' }))).toBeNull()
+ })
+
+ it('pref keys map 1:1 to the settings fields', () => {
+ expect(PICK_PREF_KEY.image).toBe('preferredImageModel')
+ expect(PICK_PREF_KEY['video-t2v']).toBe('preferredVideoT2VModel')
+ expect(PICK_PREF_KEY['video-i2v']).toBe('preferredVideoI2VModel')
+ })
+})
diff --git a/src/lib/__tests__/tool-selection-web.test.ts b/src/lib/__tests__/tool-selection-web.test.ts
index 36ac7c76..398c6943 100644
--- a/src/lib/__tests__/tool-selection-web.test.ts
+++ b/src/lib/__tests__/tool-selection-web.test.ts
@@ -7,7 +7,7 @@ import { DEFAULT_PERMISSIONS } from '../../api/mcp/types'
const T = (name: string, category: MCPToolDefinition['category']): MCPToolDefinition => ({
name,
description: name,
- inputSchema: { type: 'object', properties: {} },
+ inputSchema: { type: 'object', properties: {}, required: [] },
category,
source: 'builtin',
})
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 895d5472..d7c7ade3 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -58,6 +58,11 @@ export const DEFAULT_SETTINGS: Settings = {
defaultWorkspace: null,
// v8: user-uploaded profile picture (base64 data URL, ≤256px). '' = default icon.
userAvatarDataUrl: '',
+ // v9: model-picker preferences (saved via the in-tool-call picker's save
+ // icon). '' = no saved choice → picker shows before the VRAM swap.
+ preferredImageModel: '',
+ preferredVideoT2VModel: '',
+ preferredVideoI2VModel: '',
}
/** Caveman mode system prompt prefixes — credit: github.com/JuliusBrussee/caveman (MIT) */
diff --git a/src/stores/__tests__/modelPickStore.test.ts b/src/stores/__tests__/modelPickStore.test.ts
new file mode 100644
index 00000000..5c820ed7
--- /dev/null
+++ b/src/stores/__tests__/modelPickStore.test.ts
@@ -0,0 +1,78 @@
+/**
+ * Model-Picker store (v2.5.3) — promise rendezvous between the tool
+ * executor (request) and the picker UI (choose/cancel), with a headless
+ * auto-continue timeout and serialized overlapping requests.
+ *
+ * Run: npx vitest run src/stores/__tests__/modelPickStore.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { useModelPickStore, MODEL_PICK_TIMEOUT_MS } from '../modelPickStore'
+
+afterEach(() => {
+ // Never leak a pending pick (or its timeout) into the next test.
+ if (useModelPickStore.getState().pending) useModelPickStore.getState().cancel()
+ vi.useRealTimers()
+})
+
+describe('modelPickStore', () => {
+ it('request exposes pending with kind/models/current', async () => {
+ const p = useModelPickStore.getState().request('image', ['a.safetensors', 'b.safetensors'], 'a.safetensors')
+ const pending = useModelPickStore.getState().pending
+ expect(pending).toBeTruthy()
+ expect(pending!.kind).toBe('image')
+ expect(pending!.models).toEqual(['a.safetensors', 'b.safetensors'])
+ expect(pending!.current).toBe('a.safetensors')
+ useModelPickStore.getState().choose({ model: 'b.safetensors', save: false })
+ expect(await p).toEqual({ model: 'b.safetensors', save: false })
+ })
+
+ it('choose resolves the promise and clears pending', async () => {
+ const p = useModelPickStore.getState().request('video-t2v', ['wan.safetensors'], 'wan.safetensors')
+ useModelPickStore.getState().choose({ model: 'wan.safetensors', save: true })
+ expect(await p).toEqual({ model: 'wan.safetensors', save: true })
+ expect(useModelPickStore.getState().pending).toBeNull()
+ })
+
+ it('cancel resolves null (caller falls back to the pre-selection)', async () => {
+ const p = useModelPickStore.getState().request('video-i2v', ['svd.safetensors'], 'svd.safetensors')
+ useModelPickStore.getState().cancel()
+ expect(await p).toBeNull()
+ expect(useModelPickStore.getState().pending).toBeNull()
+ })
+
+ it('choose/cancel without a pending request are no-ops', () => {
+ expect(() => {
+ useModelPickStore.getState().choose({ model: 'x', save: false })
+ useModelPickStore.getState().cancel()
+ }).not.toThrow()
+ })
+
+ it('a second request waits until the first resolves (serialized)', async () => {
+ const first = useModelPickStore.getState().request('image', ['a'], 'a')
+ let secondPendingSeen = false
+ const second = useModelPickStore.getState().request('image', ['b'], 'b').then((c) => {
+ secondPendingSeen = useModelPickStore.getState().pending === null
+ return c
+ })
+ // While the first is pending, the second has NOT replaced it.
+ expect(useModelPickStore.getState().pending!.models).toEqual(['a'])
+ useModelPickStore.getState().choose({ model: 'a', save: false })
+ expect(await first).toEqual({ model: 'a', save: false })
+ // Now the second surfaces.
+ await vi.waitFor(() => {
+ if (useModelPickStore.getState().pending?.models[0] !== 'b') throw new Error('second not pending yet')
+ })
+ useModelPickStore.getState().choose({ model: 'b', save: false })
+ expect(await second).toEqual({ model: 'b', save: false })
+ expect(secondPendingSeen).toBe(true)
+ })
+
+ it('headless timeout auto-resolves null after MODEL_PICK_TIMEOUT_MS', async () => {
+ vi.useFakeTimers()
+ const p = useModelPickStore.getState().request('image', ['a'], 'a')
+ expect(useModelPickStore.getState().pending).toBeTruthy()
+ await vi.advanceTimersByTimeAsync(MODEL_PICK_TIMEOUT_MS + 1000)
+ expect(await p).toBeNull()
+ expect(useModelPickStore.getState().pending).toBeNull()
+ })
+})
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index fcc10d20..d0098cfe 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -262,7 +262,10 @@ export const useCreateStore = create<CreateState>()(
setFrames: (frames) => set({ frames: Math.max(1, Math.min(120, Math.floor(frames))) }),
setFps: (fps) => set({ fps: Math.max(1, Math.min(60, Math.floor(fps))) }),
setDenoise: (denoise) => set({ denoise: Math.max(0, Math.min(1, denoise)) }),
- toggleLora: (name) => set((s) => {
+ // Explicit param types: this file's creator lost contextual typing long
+ // ago (pre-existing TS2740 on MODEL_TYPE_DEFAULTS) — without these the
+ // params would be implicit-any like the older setters around them.
+ toggleLora: (name: string) => set((s: CreateState) => {
if (!name) return {}
const exists = s.selectedLoras.some((l) => l.name === name)
return {
@@ -271,7 +274,7 @@ export const useCreateStore = create<CreateState>()(
: [...s.selectedLoras, { name, strength: 0.8 }],
}
}),
- setLoraStrengthFor: (name, strength) => set((s) => ({
+ setLoraStrengthFor: (name: string, strength: number) => set((s: CreateState) => ({
selectedLoras: s.selectedLoras.map((l) =>
l.name === name ? { ...l, strength: Math.max(0, Math.min(2, strength)) } : l,
),
diff --git a/src/stores/modelPickStore.ts b/src/stores/modelPickStore.ts
new file mode 100644
index 00000000..b65d59ec
--- /dev/null
+++ b/src/stores/modelPickStore.ts
@@ -0,0 +1,88 @@
+import { create } from 'zustand'
+
+/**
+ * Model-Picker (v2.5.3, David 2026-06-10): before the VRAM swap of an
+ * image/video generation, LU itself (not the LLM) shows the installed
+ * ComfyUI models inside the tool call so the user can pick one — with a
+ * save icon to persist the choice for future prompts ("für nächste Prompts
+ * übernommen"). This store is the rendezvous between the tool executor
+ * (which awaits `request()`) and the ModelPickerCard UI (which resolves it
+ * via `choose()` / `cancel()`). Same promise-gate pattern as the agent
+ * approval queue in useAgentChat.
+ *
+ * Not persisted — a pending pick never survives a reload (the generation it
+ * gates is gone too). The SAVED preference lives in settingsStore (v9 keys).
+ */
+
+export type ModelPickKind = 'image' | 'video-t2v' | 'video-i2v'
+
+export interface ModelPickChoice {
+ model: string
+ /** True = persist as the preferred model for this kind (the save icon). */
+ save: boolean
+}
+
+export interface ModelPickRequest {
+ id: string
+ kind: ModelPickKind
+ /** Installed, kind-eligible ComfyUI model names (decide-phase filtering). */
+ models: string[]
+ /** Pre-selected entry (saved preference fallback or first installed). */
+ current: string
+}
+
+/** Auto-continue with the pre-selection when nobody clicks — keeps the
+ * pre-picker behaviour ("it just generates") for AFK users. The card shows
+ * a live countdown and fires slightly earlier with the user's on-screen
+ * selection; this store timeout is the headless fallback. */
+export const MODEL_PICK_TIMEOUT_MS = 90_000
+
+interface ModelPickState {
+ pending: ModelPickRequest | null
+ /** Executor side: returns the user's choice, or null on timeout/cancel
+ * (caller falls back to `current`). Serializes overlapping requests. */
+ request: (kind: ModelPickKind, models: string[], current: string) => Promise<ModelPickChoice | null>
+ /** UI side: resolve the pending request with a concrete pick. */
+ choose: (choice: ModelPickChoice) => void
+ /** UI side / timeout: resolve with null (use the pre-selection). */
+ cancel: () => void
+}
+
+let resolver: ((choice: ModelPickChoice | null) => void) | null = null
+let timeoutHandle: ReturnType<typeof setTimeout> | null = null
+let seq = 0
+
+export const useModelPickStore = create<ModelPickState>()((set, get) => {
+ const settle = (choice: ModelPickChoice | null) => {
+ if (!get().pending) return
+ if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null }
+ const r = resolver
+ resolver = null
+ set({ pending: null })
+ r?.(choice)
+ }
+
+ return {
+ pending: null,
+
+ request: async (kind, models, current) => {
+ // Serialize: a second generation's pick waits until the first resolves
+ // (tool calls are effectively sequential anyway; this is a safety net).
+ while (get().pending) {
+ await new Promise((r) => setTimeout(r, 250))
+ }
+ return new Promise<ModelPickChoice | null>((resolve) => {
+ resolver = resolve
+ const req: ModelPickRequest = { id: `pick-${++seq}`, kind, models, current }
+ set({ pending: req })
+ timeoutHandle = setTimeout(() => {
+ // Headless fallback — the card usually auto-continues first.
+ if (get().pending?.id === req.id) settle(null)
+ }, MODEL_PICK_TIMEOUT_MS)
+ })
+ },
+
+ choose: (choice) => settle(choice),
+ cancel: () => settle(null),
+ }
+})
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 36565b30..c1b69550 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -17,7 +17,11 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'
// while preserving every existing user value — existing users get it OFF.
// v8: added settings.userAvatarDataUrl (user profile picture, default ''),
// backfilled by the same additive merge — existing users keep the default icon.
-const STORE_VERSION = 8
+// v9 (v2.5.3): added the model-picker preferences preferredImageModel /
+// preferredVideoT2VModel / preferredVideoI2VModel (all default '' = "ask
+// before the VRAM swap"). Same additive merge path — existing users simply
+// see the picker on their next generation.
+const STORE_VERSION = 9
interface SettingsState {
settings: Settings
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 782805af..84130012 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -140,6 +140,18 @@ export interface Settings {
* messages. The AI's avatar is always the LU monogram (not user-settable).
*/
userAvatarDataUrl: string
+ // ── v9 (v2.5.3) — Model-Picker preferences ────────────────────────
+ // Saved via the in-tool-call model picker's save icon ("für nächste
+ // Prompts übernommen"). '' = nothing saved → the picker shows before the
+ // VRAM swap on the next generation. Video keeps two slots because the
+ // capability sets are disjoint: SVD/FramePack can't do T2V, Wan 1.3B
+ // can't do I2V — one shared slot would silently mismatch.
+ /** Preferred ComfyUI checkpoint for image generation ('' = ask). */
+ preferredImageModel: string
+ /** Preferred text-to-video model ('' = ask). */
+ preferredVideoT2VModel: string
+ /** Preferred image-to-video model ('' = ask). */
+ preferredVideoI2VModel: string
}
export interface Persona {