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
v2.5.5: chat-loop fixes + community-scan fixes (#67, Claude import, LM Studio, imports)
purple728c500ad531
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 5bff0556..60a4fd5b 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -235,6 +235,19 @@ export class OpenAIProvider implements ProviderClient {continue}+ // LM Studio (and some OpenAI-compat servers) report a mid-stream failure+ // as a 200 response carrying an SSE error chunk ({ error: { message } } or+ // a bare { error: "..." }) instead of a non-2xx status, so the !res.ok+ // guard above never fires. Such a chunk has no `choices`, so the old loop+ // just skipped it → the user got a SILENT EMPTY reply. Surface it as a+ // thrown error so the chat layer can map it to a friendly message (e.g.+ // the #67 image-on-text-model case). Verified live: LM Studio + image on a+ // text-only model returns `event: error` with HTTP 200 (2026-06-21).+ const streamErr = (chunk as { error?: { message?: string } | string }).error+ if (streamErr) {+ throw new Error(typeof streamErr === 'string' ? streamErr : (streamErr.message || 'Streaming error'))+ }+// Real token usage — the include_usage final chunk carries `usage` with// an empty choices[], so capture it BEFORE the choice guard below.const u = (chunk as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usagediff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex b2e7f241..5654a07d 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -6,7 +6,7 @@ import { VoiceButton } from './VoiceButton'import { useVoiceStore } from '../../stores/voiceStore'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'-import { isThinkingCompatible } from '../../lib/model-compatibility'+import { isThinkingCompatible, isVisionCompatible } from '../../lib/model-compatibility'import type { AgentToolCall } from '../../types/agent-mode'import type { ImageAttachment } from '../../types/chat'@@ -58,6 +58,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppconst updateSettings = useSettingsStore((s) => s.updateSettings)const activeModel = useModelStore((s) => s.activeModel)const canThink = isThinkingCompatible(activeModel)+ const canSeeImages = isVisionCompatible(activeModel)useEffect(() => {if (textareaRef.current) {@@ -92,9 +93,18 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp})}+ // Synchronous double-fire guard (David 2026-06-20: "ok generiere jetzt" landed+ // twice in one chat). The `isGenerating` prop and the cleared input only update+ // on the NEXT render, so two Enter keydowns in the same tick (key-repeat / IME+ // / a held Enter) both pass the checks below and send the identical message+ // twice. A short monotonic lock closes that window.+ const sendLockRef = useRef(0)const handleSend = () => {const trimmed = input.trim()if ((!trimmed && images.length === 0) || isGenerating || disabled) return+ const now = Date.now()+ if (now - sendLockRef.current < 700) return+ sendLockRef.current = nowonSend(trimmed || '(image)', images.length > 0 ? images : undefined)setInput('')setImages([])@@ -250,6 +260,16 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp</div>)}+ {/* Vision hint — a text-only model can't read the attached image.+ Non-blocking (send still works); the runtime error is also mapped+ to friendly copy. gthvidsten, GH Discussion #67. */}+ {images.length > 0 && activeModel && !canSeeImages && (+ <div className="flex items-start gap-1.5 mb-1.5 px-1 text-[0.55rem] leading-relaxed text-amber-600 dark:text-amber-400">+ <span className="shrink-0">⚠</span>+ <span>This model can't read images. Switch to a vision model (Gemma 4, LLaVA, Qwen-VL) to use the attachment.</span>+ </div>+ )}+{/* Input row */}<div className="flex items-end gap-2">{/* Clip button */}diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsxindex 9f600ca9..40b908a6 100644--- a/src/components/chat/TokenCounter.tsx+++ b/src/components/chat/TokenCounter.tsx@@ -19,7 +19,21 @@ export function TokenCounter() {// promptTokens already includes the system prompt, tools, RAG and the full// history, so totalTokens is the TRUE current context fill. The char/4// estimate is only a fallback until the first real reply lands.- const lastUsage = [...messages].reverse().find((m) => m.usage && m.usage.totalTokens > 0)?.usage+ // The counter must not visibly "jump" between turns (David 2026-06-20: "3.5k+ // springt auf 1.9k", especially after an image/video gen). The model-reported+ // usage is the size of the COMPACTED prompt that turn — and that legitimately+ // swings: a turn that feeds the generated image back for vision costs ~3k, the+ // next turn (image trimmed by compaction, or a regenerate that reuses the prior+ // args) costs ~1k. Both are "real", so showing the latest made the bar bounce.+ // Use the conversation's HIGH-WATER real usage instead: it reflects the largest+ // context this chat has actually reached and never dips just because one turn+ // compacted harder. A live provisional estimate can still push it higher.+ const reversed = [...messages].reverse()+ const realMax = messages.reduce(+ (mx, m) => (m.usage && !m.usage.estimated && m.usage.totalTokens > mx ? m.usage.totalTokens : mx),+ 0,+ )+ const lastUsage = reversed.find((m) => m.usage && m.usage.totalTokens > 0)?.usageconst estimated = messages.reduce((sum, m) => {let tokens = estimateTokens(m.content)if (m.thinking) tokens += estimateTokens(m.thinking)@@ -27,12 +41,13 @@ export function TokenCounter() {tokens += 4 // role overheadreturn sum + tokens}, 0)- const usedTokens = lastUsage ? lastUsage.totalTokens : estimated- // "Real" = the model reported it. A provisional estimate the agent loop sets- // before the first reply (so the bar reflects the system prompt + tools, not a- // char/4 guess of the visible messages) carries `estimated:true` — show it, but- // don't claim it's the model's exact count.- const isReal = !!lastUsage && !lastUsage.estimated+ const usedTokens = realMax > 0+ ? Math.max(realMax, lastUsage?.totalTokens ?? 0)+ : (lastUsage ? lastUsage.totalTokens : estimated)+ // "Real" = the model reported it AND that's the number we're showing. If a+ // larger provisional estimate is on top we display it but don't claim it's the+ // model's exact count.+ const isReal = realMax > 0 && usedTokens === realMaxif (!activeConversationId || messages.length === 0) return nulldiff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex e6502035..fa3e7ef2 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1013,7 +1013,7 @@ export function SettingsPage() {ChatGPT / Claude / Gemini export JSON (or .zip), pre-selectsevery conversation, feeds the chosen ones into the activechat's RAG store. */}- <Section title="Import past chatbot conversations">+ <Section title="Import from other chatbots"><ChatbotImporter /></Section>diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 223ca23a..acf600c9 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -18,6 +18,7 @@ import { toolRegistry } from '../api/mcp'import { usePermissionStore } from '../stores/permissionStore'import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'import { getToolCallingStrategy, type ToolCallingStrategy } from '../lib/model-compatibility'+import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from '../lib/ollama-errors'import { log } from '../lib/logger'import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'@@ -167,7 +168,16 @@ export function useAgentChat() {// unset, this is the normal autonomous-agent path (full tool catalog).// displayContent: a slash command shows the raw "/commit" the user typed// while `userContent` carries the expanded instruction the model receives.- opts?: { curatedTools?: readonly string[]; chatToolsMode?: boolean; displayContent?: string },+ opts?: {+ curatedTools?: readonly string[]+ chatToolsMode?: boolean+ displayContent?: string+ // Chat-tools router hint (David 2026-06-20): when a bare follow-up like+ // "nochmal"/"ok generiere jetzt" continues an in-progress media task, the+ // router passes the task kind + the prior generation's exact args so a weak+ // model that can't emit the call still gets the SAME media synthesized.+ mediaHint?: { kind: 'image' | 'video'; args?: Record<string, unknown> }+ },) => {const { activeModel } = useModelStore.getState()const { settings } = useSettingsStore.getState()@@ -535,8 +545,13 @@ export function useAgentChat() {// skipped. Caps derive from the user's actual request.const userPromptText =[...agentMessages].reverse().find((m) => m.role === 'user')?.content || ''- const wantsImage = /\b(bild|bilder|foto|image|picture|pic|draw|zeichne|mal(e|en)?|grafik|illustration|render)\b/i.test(userPromptText)- const wantsVideo = /\b(video|clip|animier\w*|animate|film|gif|bewegt|motion|mp4|webm)\b/i.test(userPromptText)+ // Seed the media intent from the router's continuation hint too (David+ // 2026-06-20): "ok generiere jetzt" carries no noun, so detecting wants from+ // the last message alone left wantsVideo=false and the synth fallback never+ // fired on a "regenerate the clip" follow-up. The hint says it's a video task.+ const hintKind = opts?.mediaHint?.kind+ const wantsImage = hintKind === 'image' || /\b(bild|bilder|foto|image|picture|pic|draw|zeichne|mal(e|en)?|grafik|illustration|render)\b/i.test(userPromptText)+ const wantsVideo = hintKind === 'video' || /\b(video|clip|animier\w*|animate|film|gif|bewegt|motion|mp4|webm)\b/i.test(userPromptText)const maxImageGen = wantsVideo && !wantsImage ? 0 : 1// Video generation is turned OFF in the chat tools (video defaults to// 'blocked' + locked toggle, David 2026-06-04). Respect that here so the@@ -959,34 +974,61 @@ export function useAgentChat() {}let isFinalTurn = toolCalls.length === 0- // Dud turn (David 2026-06-04): the model produced empty content + no tool- // call → the user used to see ONLY a thinking bubble, no answer.- if (isFinalTurn && !turnContent.trim() && executedCallKeys.size === 0) {- // 1st dud → retry once with thinking OFF (gemma4 dumps its whole- // response into the thinking channel and emits nothing usable).- if (!dudRetried && canThinkAgent && !forceNoThink) {+ // Recovery for a final turn that emitted NO tool call on a media request.+ // A weak model (gemma4:e4b) fails this two ways (David 2026-06-20, live+ // chat):+ // 1. EMPTY content — it dumped everything into the thinking channel and+ // emitted nothing usable (the classic "dud turn").+ // 2. FAKE-GEN PROSE — it WROTE "(generating the video…)" / "the video+ // has been generated" as plain text and never called the tool, so the+ // user got a confident lie and no media. Every "regenerate" after the+ // first clip did exactly this.+ const mediaPending =+ (wantsImage && maxImageGen > 0 && imageGenDone === 0) ||+ (wantsVideo && maxVideoGen > 0 && videoGenDone === 0)+ const emptyTurn = !turnContent.trim()+ const fakeGenProse = mediaPending && !emptyTurn && FAKE_MEDIA_GEN_RE.test(turnContent)+ if (isFinalTurn && executedCallKeys.size === 0 && (emptyTurn || fakeGenProse)) {+ // 1st EMPTY dud → retry once with thinking OFF (gemma4 dumps its whole+ // response into the thinking channel). Fake-gen prose is non-empty, so it+ // skips the retry and goes straight to synthesis.+ if (emptyTurn && !dudRetried && canThinkAgent && !forceNoThink) {dudRetried = trueforceNoThink = truelog.info('agent.dud_turn_retry_no_think', { model: activeModel })continue}- // Still nothing AND the user clearly asked for media → a weak model- // (gemma4:e4b) often can't emit the tool call at all. Deliver what was- // asked by SYNTHESIZING the generation call from the user's prompt, so- // "mach mir ein bild von X" works even when the model flakes.- if (!mediaSynthesized &&- ((wantsImage && maxImageGen > 0 && imageGenDone === 0) ||- (wantsVideo && maxVideoGen > 0 && videoGenDone === 0))) {+ // The user clearly asked for media but the model couldn't emit the call.+ // SYNTHESIZE it. Prefer the EXACT args of the media being re-made (passed+ // as mediaHint by the chat-tools router — same prompt, inputImage,+ // duration) so "nochmal"/"again" reproduces it faithfully; else extract a+ // prompt from the user's text.+ if (!mediaSynthesized && mediaPending) {mediaSynthesized = trueconst useVideo = wantsVideo && maxVideoGen > 0 && videoGenDone === 0+ const hintArgs =+ opts?.mediaHint && opts.mediaHint.kind === (useVideo ? 'video' : 'image')+ ? opts.mediaHint.args+ : undefined+ const synthArgs =+ hintArgs && Object.keys(hintArgs).length > 0+ ? hintArgs+ : { prompt: extractMediaPrompt(userPromptText) }toolCalls = [{function: {name: useVideo ? 'video_generate' : 'image_generate',- arguments: { prompt: extractMediaPrompt(userPromptText) },+ arguments: synthArgs,},}] as ToolCall[]isFinalTurn = false- log.info('agent.media_fallback_synthesized', { tool: toolCalls[0].function.name })+ // Drop the hallucinated "(generating…)" prose so it never renders above+ // the real media that is about to be produced.+ if (fakeGenProse) turnContent = ''+ log.info('agent.media_fallback_synthesized', {+ tool: toolCalls[0].function.name,+ fromHint: !!(hintArgs && Object.keys(hintArgs).length),+ fakeGenProse,+ })}}if (isFinalTurn) {@@ -1313,7 +1355,12 @@ export function useAgentChat() {if ((err as Error).name !== 'AbortError') {const errorMsg = (err as Error).message || 'Connection failed'- if (errorMsg.includes('does not support tools')) {+ if (isMultimodalUnsupportedError(errorMsg)) {+ useChatStore.getState().updateMessageContent(+ convId!, assistantMessage.id,+ MULTIMODAL_UNSUPPORTED_MESSAGE+ )+ } else if (errorMsg.includes('does not support tools')) {useChatStore.getState().updateMessageContent(convId!, assistantMessage.id,`This model does not support tool calling.\n\nThe auto-fix could not be applied. Try pulling a standard model like:\n• qwen2.5:7b\n• llama3.1:8b\n• mistral:7b`@@ -1412,6 +1459,17 @@ export function useAgentChat() {* (DE + EN). Used by the dud-turn media fallback when a weak model can't emit* the tool call itself. Falls back to the full text if nothing strips.*/+/**+ * Detects a model "pretending" to generate media in plain prose without ever+ * calling the tool (David 2026-06-20: gemma4 wrote "(Generating 2-second+ * zoom-in video…)", "the video has been successfully generated", "I am+ * initiating the generation process" — and produced nothing). Only consulted on+ * a final, tool-call-less turn where media is still pending, so legitimate+ * mid-loop narration (which precedes a real tool call) is never affected.+ */+export const FAKE_MEDIA_GEN_RE =+ /\b(generating|regenerat\w*|i('|\s+a)m\s+(now\s+)?(generating|creating|initiat\w*)|i\s+(will|have)\s+(now\s+)?(re)?generat\w*|i\s+am\s+initiat\w*|video\s+generation|image\s+generation|in\s+progress|has\s+been\s+(successfully\s+)?(generated|created|regenerated)|wird\s+(gerade\s+)?(erstellt|generiert)|generiere\s+(jetzt|das|es)|in\s+arbeit)\b|\(\s*(generat|re-?generat|video\s+generat|image\s+generat)/i+export function extractMediaPrompt(text: string): string {const p = String(text || '').trim()const stripped = p.replace(diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex dbaedd09..a6f00ff6 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -14,14 +14,35 @@ import { useAgentChat } from "./useAgentChat"import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"import { useGenerationStore } from "../stores/generationStore"-import { detectChatToolIntent, CHAT_TOOLS } from "../lib/chat-tool-intent"+import { resolveChatToolRoute, CHAT_TOOLS, type ChatToolRouteMsg } from "../lib/chat-tool-intent"import { getProviderForModel, getProviderIdFromModel } from "../api/providers"import { syncOllamaHealthFromError } from "../lib/sync-ollama-health"import { isThinkingCompatible, isPlainTextPlanner } from "../lib/model-compatibility"import { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-stripper"-import type { ImageAttachment } from "../types/chat"+import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from "../lib/ollama-errors"+import type { ImageAttachment, Message } from "../types/chat"import { log } from "../lib/logger"+/**+ * Pull the most recent media generation (image/video) out of an assistant+ * message's agent blocks, with the exact args used. Lets the chat-tools router+ * reproduce the SAME media for a bare "nochmal"/"again" follow-up. Reads both+ * the v2.4+ `toolCalls` array and the legacy singular `toolCall`.+ */+function lastMediaFromBlocks(m: Message): { kind: 'image' | 'video'; args?: Record<string, unknown> } | null {+ if (!m.agentBlocks?.length) return null+ for (let i = m.agentBlocks.length - 1; i >= 0; i--) {+ const b = m.agentBlocks[i]+ const calls = b.toolCalls?.length ? b.toolCalls : (b.toolCall ? [b.toolCall] : [])+ for (let j = calls.length - 1; j >= 0; j--) {+ const name = calls[j].toolName+ if (name === 'video_generate') return { kind: 'video', args: calls[j].args }+ if (name === 'image_generate') return { kind: 'image', args: calls[j].args }+ }+ }+ return null+}+export function useChat() {const [isGenerating, setIsGenerating] = useState(false)const [isLoadingModel, setIsLoadingModel] = useState(false)@@ -55,21 +76,32 @@ export function useChat() {}// Chat-Tools routing (David 2026-06-11): web/file/image/video should work- // in PLAIN chat without flipping to full Agent mode. When the message- // clearly needs one of those capabilities, run THIS turn through the agent- // executor with a curated 5-tool allow-list + a chat-style prompt. Pure- // conversation falls through to the fast plain path below, untouched — so- // normal chatting (and the rikki/thought-only fixes) never regress. (Agent- // mode already returned above, so reaching here means Agent is off.)- if (- activeModel- && settings.chatToolsEnabled !== false- && detectChatToolIntent(content, !!images?.length)- ) {- return agentChat.sendAgentMessage(content, images, {- curatedTools: CHAT_TOOLS,- chatToolsMode: true,- })+ // in PLAIN chat without flipping to full Agent mode. We route a turn through+ // the chat-tools executor when it needs one of those capabilities — either+ // DIRECTLY (verb+noun in this message) or as a CONTINUATION of a recent+ // image/video task (David 2026-06-20: "ok go" / "2 seconds zoom" / "nochmal+ // neu" / "ok generiere jetzt" used to miss and drop to plain chat, where the+ // tool is absent → the model planned in circles or faked "(generating…)" and+ // the token counter halved as the prompt lost its tools+image). For a+ // continuation we pass the prior generation's args so a bare "nochmal" / "go"+ // reproduces the SAME media. Pure conversation still falls through to the fast+ // plain path below, untouched. (Agent mode already returned above.)+ if (activeModel && settings.chatToolsEnabled !== false) {+ const activeConv = store.conversations.find((c) => c.id === store.activeConversationId)+ const recent: ChatToolRouteMsg[] = (activeConv?.messages ?? [])+ .slice(-12)+ .map((m) => {+ const media = m.role === 'assistant' ? lastMediaFromBlocks(m) : null+ return { role: m.role, content: m.content, mediaKind: media?.kind, mediaArgs: media?.args }+ })+ const route = resolveChatToolRoute(content, !!images?.length, recent)+ if (route) {+ return agentChat.sendAgentMessage(content, images, {+ curatedTools: CHAT_TOOLS,+ chatToolsMode: true,+ mediaHint: route.mediaHint,+ })+ }}if (!activeModel) return@@ -392,10 +424,26 @@ export function useChat() {// leaving the user staring at silent dead air forever.if (!abort.signal.aborted && contentRef.current.trim() === "") {const captured = (thinkingRef.current || finalStripThinkingTags(hiddenThinking, false)).trim()- if (captured) {+ if (captured && useThinking === true) {+ // Thinking ON: surface the reasoning so the empty bubble explains+ // itself (MessageBubble renders it + a nudge) instead of dead air.useChatStore.getState().updateMessageThinking(convId!, assistantMessage.id, captured)+ } else if (captured) {+ // Thinking OFF but the model still reasoned (Gemma keeps reasoning when+ // we pass `think:undefined`) and produced no visible answer. David+ // 2026-06-20: OFF must mean NO reasoning shown — never leak the hidden+ // thinking into the bubble. Leave a short honest note so it isn't+ // silent dead air. (Media follow-ups now route to the tool path and+ // won't reach here; this covers a plain Q&A that thought itself out.)+ useChatStore+ .getState()+ .updateMessageContent(+ convId!,+ assistantMessage.id,+ "I didn't return a visible answer that time — please try again.",+ )}}} catch (err) {@@ -412,8 +460,16 @@ export function useChat() {? (err as Error).message: `Error: ${(err as Error).message || 'Connection failed'}`+ // Image attached to a non-vision model → friendly guidance instead of+ // the raw 400 JSON (gthvidsten, GH Discussion #67).+ if (isMultimodalUnsupportedError(errorMsg)) {+ useChatStore.getState().updateMessageContent(+ convId!,+ assistantMessage.id,+ MULTIMODAL_UNSUPPORTED_MESSAGE+ )// Show user-friendly message for thinking errors- if (errorMsg.includes('does not support thinking')) {+ } else if (errorMsg.includes('does not support thinking')) {useChatStore.getState().updateMessageContent(convId!,assistantMessage.id,diff --git a/src/lib/__tests__/chat-tool-intent.test.ts b/src/lib/__tests__/chat-tool-intent.test.tsindex 47e1ed3d..24805b98 100644--- a/src/lib/__tests__/chat-tool-intent.test.ts+++ b/src/lib/__tests__/chat-tool-intent.test.ts@@ -1,5 +1,12 @@import { describe, it, expect } from 'vitest'-import { detectChatToolCapability, detectChatToolIntent, CHAT_TOOLS } from '../chat-tool-intent'+import {+ detectChatToolCapability,+ detectChatToolIntent,+ isMediaContinuation,+ resolveChatToolRoute,+ CHAT_TOOLS,+ type ChatToolRouteMsg,+} from '../chat-tool-intent'describe('detectChatToolCapability', () => {it('exposes exactly the five curated tools', () => {@@ -94,3 +101,88 @@ describe('detectChatToolCapability', () => {expect(detectChatToolIntent('')).toBe(false)})})++// David 2026-06-20 — the real "football" chat: every media FOLLOW-UP missed the+// single-message detector and dropped to plain chat, so the model planned in+// circles or faked "(generating…)" and produced nothing.+describe('isMediaContinuation', () => {+ for (const p of [+ 'ok go', 'go', 'do it', 'yes', 'jetzt', 'los',+ '2 seconds just zoom in', '2 seconds', '3s',+ 'nochmal neu', 'noch mal', 'neu', 'again', 'regenerate', 'redo',+ 'geberuere das video neu', // typo'd "generiere" — caught via "neu"+ 'ok generiere jetzt', 'du generierst nix.',+ 'make it longer', 'spin it', 'länger bitte',+ ]) {+ it(`continuation: "${p}"`, () => expect(isMediaContinuation(p)).toBe(true))+ }+ for (const p of [+ 'thanks', 'thank you', 'danke', 'perfekt', 'cool', 'nice', 'super',+ 'danke das war super', 'stop', 'cancel',+ 'now tell me about cats', // "now" but too long → not a bare continuation+ 'what is the capital of France', 'tell me a joke', 'explain recursion',+ ]) {+ it(`not a continuation: "${p}"`, () => expect(isMediaContinuation(p)).toBe(false))+ }+})++describe('resolveChatToolRoute — context-aware media continuation', () => {+ const videoBlock: ChatToolRouteMsg = {+ role: 'assistant', content: 'Here is your clip',+ mediaKind: 'video', mediaArgs: { prompt: 'a football, zoom in', inputImage: 'football.png', duration: 2 },+ }++ it('a direct verb+noun request still routes', () => {+ expect(resolveChatToolRoute('generate an image of a football', false, [])?.capability).toBe('image')+ expect(resolveChatToolRoute('make a short video of waves', false, [])?.capability).toBe('video')+ })++ it('a bare "ok generiere jetzt" reuses the prior video block ARGS (faithful regenerate)', () => {+ const recent: ChatToolRouteMsg[] = [+ { role: 'user', content: 'now make a video out of that image' },+ videoBlock,+ { role: 'user', content: 'nochmal neu' },+ { role: 'assistant', content: '(Generating the video…)' }, // the fake-gen turn, no block+ ]+ const r = resolveChatToolRoute('ok generiere jetzt', false, recent)+ expect(r?.capability).toBe('video')+ expect(r?.mediaHint?.kind).toBe('video')+ expect(r?.mediaHint?.args).toEqual({ prompt: 'a football, zoom in', inputImage: 'football.png', duration: 2 })+ })++ it('a continuation infers the kind from an earlier user request when no block exists yet', () => {+ const recent: ChatToolRouteMsg[] = [+ { role: 'user', content: 'now make a video out of that image' },+ { role: 'assistant', content: 'How long should it be, and what motion?' },+ ]+ const r = resolveChatToolRoute('2 seconds just zoom in', false, recent)+ expect(r?.capability).toBe('video')+ expect(r?.mediaHint?.kind).toBe('video')+ })++ it('does NOT route a bare continuation with no recent media context', () => {+ const recent: ChatToolRouteMsg[] = [+ { role: 'user', content: 'explain recursion' },+ { role: 'assistant', content: 'Recursion is when a function calls itself…' },+ ]+ expect(resolveChatToolRoute('ok go', false, recent)).toBeNull()+ })++ it('praise after a media turn does NOT re-trigger the tool', () => {+ expect(resolveChatToolRoute('perfekt danke', false, [videoBlock])).toBeNull()+ })++ it('a NEW explicit web request after media routes to web, not the sticky media', () => {+ expect(+ resolveChatToolRoute('search the web for the weather in Berlin', false, [videoBlock])?.capability,+ ).toBe('web')+ })++ it('only looks back a bounded window (stale media far in the past is ignored)', () => {+ const recent: ChatToolRouteMsg[] = [+ videoBlock, // oldest+ ...Array.from({ length: 14 }, (_, i): ChatToolRouteMsg => ({ role: i % 2 ? 'assistant' : 'user', content: `chit chat ${i}` })),+ ]+ expect(resolveChatToolRoute('ok go', false, recent)).toBeNull()+ })+})diff --git a/src/lib/__tests__/chatbot-export.test.ts b/src/lib/__tests__/chatbot-export.test.tsindex 309584cc..d24bf5cc 100644--- a/src/lib/__tests__/chatbot-export.test.ts+++ b/src/lib/__tests__/chatbot-export.test.ts@@ -122,6 +122,64 @@ describe('parseJsonText — Claude', () => {})})+// Modern Claude export: the body lives in a typed content[] block array and the+// flat `text` field is empty. The old m.text-only read imported these as+// 0-message conversations and dropped them entirely (aldrich, Discord+// 2026-06-20 "how do i import chats from claude"). Also exercises an+// attachment + non-text blocks (thinking / tool_use) that must be skipped.+const claudeContentBlocksFixture = JSON.stringify([+ {+ uuid: 'cb-1',+ name: 'Content block chat',+ created_at: '2026-06-01T10:00:00Z',+ updated_at: '2026-06-01T10:05:00Z',+ chat_messages: [+ {+ uuid: 'm1', sender: 'human', text: '',+ content: [{ type: 'text', text: 'summarize the attached file' }],+ attachments: [{ file_name: 'notes.txt', extracted_content: 'Q3 revenue rose 12 percent.' }],+ },+ {+ uuid: 'm2', sender: 'assistant', text: '',+ content: [+ { type: 'thinking', thinking: 'internal reasoning, no text field' },+ { type: 'tool_use', name: 'calc', input: { a: 1 } },+ { type: 'text', text: 'Revenue grew 12 percent in Q3.' },+ ],+ },+ ],+ },+])++describe('parseJsonText — Claude content[] blocks (modern export)', () => {+ it('imports messages whose text lives in content[] with an empty flat text field', () => {+ const r = parseJsonText(claudeContentBlocksFixture)+ expect(r.detectedPlatform).toBe('claude')+ expect(r.conversations).toHaveLength(1)+ const c = r.conversations[0]+ expect(c.messageCount).toBe(2) // would have been 0 before the content[] fix+ expect(c.markdown).toContain('summarize the attached file')+ expect(c.markdown).toContain('Revenue grew 12 percent in Q3.')+ })+ it('appends extracted attachment content with its filename', () => {+ const r = parseJsonText(claudeContentBlocksFixture)+ const md = r.conversations[0].markdown+ expect(md).toContain('[attachment: notes.txt]')+ expect(md).toContain('Q3 revenue rose 12 percent.')+ })+ it('skips non-text blocks (thinking / tool_use) without leaking them', () => {+ const r = parseJsonText(claudeContentBlocksFixture)+ const md = r.conversations[0].markdown+ expect(md).not.toContain('internal reasoning')+ expect(md).not.toContain('tool_use')+ })+ it('still handles the legacy flat-text shape', () => {+ const r = parseJsonText(claudeFixture)+ expect(r.conversations[0].messageCount).toBe(2)+ expect(r.conversations[0].markdown).toContain('Explain map vs forEach')+ })+})+describe('parseJsonText — Gemini', () => {it('extracts the messages array when present', () => {const result = parseJsonText(geminiFixture)@@ -292,4 +350,31 @@ describe('parseExportFile — ChatGPT .zip with dated top-level folder', () => {expect(titles).toContain('Shard one chat')expect(titles).toContain('Shard two chat')})++ it('merges shards when zip entries use BACKSLASH separators (Windows-rezipped export)', async () => {+ // Windows tools (Explorer "Compressed folder", PowerShell Compress-Archive)+ // write backslash-separated entry names. The old basename split on '/' only,+ // so none matched conversations-NNN.json → fallback picked ONE file (~100+ // chats). Verified live 2026-06-21 with a 10-shard 1000-chat zip → 100.+ const folder = '1716800000-winshard'+ const oneChat = (title: string, part: string) => JSON.stringify([{+ title,+ create_time: 1700000000.0,+ mapping: {+ root: { id: 'root', message: null, parent: null, children: ['u1'] },+ u1: { id: 'u1', message: { id: 'u1', author: { role: 'user' }, content: { content_type: 'text', parts: [part] } }, parent: 'root', children: [] },+ },+ }])+ const file = await makeZipFile({+ [`${folder}\\conversations-000.json`]: oneChat('Win shard one', 'hi one'),+ [`${folder}\\conversations-001.json`]: oneChat('Win shard two', 'hi two'),+ [`${folder}\\user.json`]: JSON.stringify({ id: 'user-1' }),+ }, 'win-rezipped.zip')+ const res = await parseExportFile(file)+ expect(res.detectedPlatform).toBe('chatgpt')+ expect(res.conversations).toHaveLength(2)+ const titles = res.conversations.map((c) => c.title)+ expect(titles).toContain('Win shard one')+ expect(titles).toContain('Win shard two')+ })})diff --git a/src/lib/__tests__/vision-multimodal.test.ts b/src/lib/__tests__/vision-multimodal.test.tsnew file mode 100644index 00000000..28c9bb73--- /dev/null+++ b/src/lib/__tests__/vision-multimodal.test.ts@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest'+import { isVisionCompatible } from '../model-compatibility'+import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from '../ollama-errors'++// #67 (gthvidsten, GH Discussion) — attaching an image to a text-only model.+// Two layers: a name-heuristic gate for a proactive composer hint, and a+// runtime error mapper that catches whatever slips through.++describe('isVisionCompatible', () => {+ it('accepts known local vision families', () => {+ expect(isVisionCompatible('gemma4:e4b')).toBe(true)+ expect(isVisionCompatible('gemma3:12b')).toBe(true)+ expect(isVisionCompatible('llava:13b')).toBe(true)+ expect(isVisionCompatible('llama3.2-vision:11b')).toBe(true)+ expect(isVisionCompatible('qwen2.5-vl:7b')).toBe(true)+ expect(isVisionCompatible('minicpm-v:8b')).toBe(true)+ expect(isVisionCompatible('moondream:latest')).toBe(true)+ })+ it('accepts dashed / community gemma variants via normalizeFamily', () => {+ expect(isVisionCompatible('hf.co/mradermacher/Gemma-4-31B-it-abliterated-GGUF:Q4_K_M')).toBe(true)+ })+ it('rejects text-only local models', () => {+ expect(isVisionCompatible('llama3.1:8b')).toBe(false)+ expect(isVisionCompatible('mistral:7b')).toBe(false)+ expect(isVisionCompatible('qwen2.5:7b')).toBe(false)+ expect(isVisionCompatible('deepseek-r1:8b')).toBe(false)+ })+ it('stays lenient for cloud providers (never false-warn a cloud vision model)', () => {+ expect(isVisionCompatible('anthropic::claude-opus-4-20250514')).toBe(true)+ })+ it('returns false for null', () => {+ expect(isVisionCompatible(null)).toBe(false)+ })+})++describe('isMultimodalUnsupportedError', () => {+ it('matches the OpenAI-style multimodal-unsupported 400 (gthvidsten #67)', () => {+ const raw = '{"error":{"code":400,"message":"Multimodal data provided, but model does not support multimodal requests.","type":"invalid_request_error"}}'+ expect(isMultimodalUnsupportedError(raw)).toBe(true)+ })+ it('matches native-style phrasings', () => {+ expect(isMultimodalUnsupportedError('this model does not support image input')).toBe(true)+ expect(isMultimodalUnsupportedError('model is not multimodal')).toBe(true)+ })+ it('matches the exact LM Studio 400 wording (verified live 2026-06-21)', () => {+ // LM Studio returns this bare-string error for an image on a text-only model.+ expect(isMultimodalUnsupportedError('Model does not support images. Please use a model that does.')).toBe(true)+ })+ it('does not match unrelated errors', () => {+ expect(isMultimodalUnsupportedError('model does not support thinking')).toBe(false)+ expect(isMultimodalUnsupportedError('connection refused')).toBe(false)+ expect(isMultimodalUnsupportedError(null)).toBe(false)+ expect(isMultimodalUnsupportedError(undefined)).toBe(false)+ })+ it('exposes actionable, vision-oriented copy', () => {+ expect(MULTIMODAL_UNSUPPORTED_MESSAGE).toMatch(/vision/i)+ })+})diff --git a/src/lib/chat-tool-intent.ts b/src/lib/chat-tool-intent.tsindex 337af5f6..14a22be9 100644--- a/src/lib/chat-tool-intent.ts+++ b/src/lib/chat-tool-intent.ts@@ -105,3 +105,102 @@ export function detectChatToolCapability(text: string, hasImages = false): ChatTexport function detectChatToolIntent(text: string, hasImages = false): boolean {return detectChatToolCapability(text, hasImages) !== null}++// ── Context-aware media continuation (David 2026-06-20) ────────────────+//+// The single-message detector above is blind to conversation context: once a+// media task is underway, the natural FOLLOW-UPS a user types carry no+// verb+noun and so DON'T match — "ok go", "2 seconds just zoom in", "nochmal+// neu", "ok generiere jetzt". Those then fell through to the plain chat path+// where the image/video tool isn't available, so the model either reasoned in+// circles ("plan stuck in thinking") or wrote a confident "(generating…)" lie+// and produced nothing. The helpers below let the router recognise such a+// follow-up AS a continuation of the in-progress media task and route it (with+// the original generation's args) back through the tool executor.++// Praise / thanks / explicit stop — these END a media exchange and must NEVER+// be treated as "do it again".+const CONT_EXIT_RE = /\b(thanks|thank\s*you|danke|thx|bye|tsch[üu]ss|cool|nice|great|super|perfekt|perfect|stop|stopp|cancel|abbrechen|nevermind|egal|vergiss\s+es)\b/i++// STRONG signals push a media task forward at ANY length (redo / motion / a bare+// create verb without a noun).+const STRONG_CONT_RE = /\b(re-?generate|regenerier\w*|nochmal|noch\s*mal|neu|erneut|redo|again|zoom|spin|rotate|\bpan\b|animate|animier\w*|longer|shorter|faster|slower|l[äa]nger|k[üu]rzer|schneller|langsamer|generier\w*|generate)\b/i+// WEAK signals (confirmations / "now") only count in a SHORT message, so "now"+// inside "now tell me about cats" never hijacks the media tool.+const WEAK_CONT_RE = /\b(go|do\s*it|yes|yep|yeah|sure|ok(ay)?|los|mach(\s*(es|mal|schon))?|tu\s*es|proceed|continue|weiter|jetzt|now|please|bitte|create|erstell\w*|render|produce|produzier\w*)\b/i+// Bare duration like "2 seconds" / "3s" — only sensible as a clip follow-up.+const BARE_DURATION_RE = /^\s*\d+\s*(s|sec|secs|seconds?|sek|sekunden?|min|minuten?)?\s*$/i+// A short complaint that nothing was produced should re-trigger the task.+const CONT_COMPLAINT_RE = /\b(nix|nichts|nicht|kein\w*|nothing|didn'?t|doesn'?t|won'?t)\b/i++/**+ * True when `text`, ON ITS OWN, is a follow-up that should advance an+ * already-running media task (caller must confirm there IS one — see+ * resolveChatToolRoute). Deliberately conservative for weak signals.+ */+export function isMediaContinuation(text: string): boolean {+ const t = lower(text).trim()+ if (!t) return false+ if (CONT_EXIT_RE.test(t)) return false+ if (BARE_DURATION_RE.test(t)) return true+ if (STRONG_CONT_RE.test(t)) return true+ const wordCount = t.split(/\s+/).length+ if (WEAK_CONT_RE.test(t) && wordCount <= 4) return true+ if (CONT_COMPLAINT_RE.test(t) && wordCount <= 6) return true+ return false+}++/** A recent message, reduced to what the router needs (decoupled from Message). */+export interface ChatToolRouteMsg {+ role: string+ content: string+ /** Set on assistant turns that produced media — the tool kind + its exact args+ * so a bare "nochmal"/"again" can reproduce the SAME media deterministically. */+ mediaKind?: 'image' | 'video'+ mediaArgs?: Record<string, unknown>+}++export interface ChatToolRoute {+ capability: ChatToolCapability+ /** Present for media routes; `args` carries the prior generation's parameters+ * (prompt, inputImage, duration…) for a faithful regenerate. */+ mediaHint?: { kind: 'image' | 'video'; args?: Record<string, unknown> }+}++/** How far back to look for the in-progress media task. */+const MEDIA_CONTEXT_WINDOW = 12++/**+ * Decide whether a plain-chat message should run through the chat-tools+ * executor — directly (verb+noun in this message) OR as a continuation of a+ * recent image/video task. `recent` is the conversation history BEFORE this+ * message (oldest→newest); the most recent entry is last.+ */+export function resolveChatToolRoute(+ text: string,+ hasImages: boolean,+ recent: ChatToolRouteMsg[],+): ChatToolRoute | null {+ const direct = detectChatToolCapability(text, hasImages)+ if (direct) {+ return direct === 'image' || direct === 'video'+ ? { capability: direct, mediaHint: { kind: direct } }+ : { capability: direct }+ }+ if (!isMediaContinuation(text)) return null++ const window = recent.slice(-MEDIA_CONTEXT_WINDOW)+ for (let i = window.length - 1; i >= 0; i--) {+ const m = window[i]+ // A prior assistant turn that actually produced media wins — reuse its args.+ if (m.role === 'assistant' && (m.mediaKind === 'image' || m.mediaKind === 'video')) {+ return { capability: m.mediaKind, mediaHint: { kind: m.mediaKind, args: m.mediaArgs } }+ }+ // Otherwise an earlier user message that asked for media establishes the kind.+ if (m.role === 'user') {+ const cap = detectChatToolCapability(m.content)+ if (cap === 'image' || cap === 'video') return { capability: cap, mediaHint: { kind: cap } }+ }+ }+ return null+}diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.tsindex ceb46351..6fddf4cb 100644--- a/src/lib/model-compatibility.ts+++ b/src/lib/model-compatibility.ts@@ -162,6 +162,40 @@ export function isThinkingCompatible(modelName: string | null): boolean {return THINKING_COMPATIBLE.some(f => containsFamily(f, baseName))}+/**+ * Model families that accept image input (multimodal / vision). Same+ * name-heuristic approach as THINKING_COMPATIBLE — Ollama exposes no cheap+ * synchronous capability flag, so we match known vision families and stay+ * lenient for cloud / OpenAI-compatible endpoints (return true → never+ * false-warn an LM Studio or cloud vision model). The runtime error mapper+ * (`isMultimodalUnsupportedError`) is the real safety net for anything that+ * slips through. gthvidsten (GH Discussion #67) attached an image to a+ * text-only Ollama build and got a raw 400 with no guidance.+ */+const VISION_COMPATIBLE = [+ 'gemma3', 'gemma4', // Gemma 3/4 are natively multimodal+ 'llava', 'bakllava',+ 'llama3.2-vision', 'llama4', // Llama 3.2 Vision, Llama 4+ 'qwen2.5-vl', 'qwen3-vl', 'qwen-vl', 'qwen3.6',+ 'minicpm-v', 'moondream', 'pixtral',+ 'mistral-small3.1', 'mistral-small3.2',+ 'granite3.2-vision', 'internvl', 'glm-4v',+]++/**+ * Check whether a model can take image input. Cloud + OpenAI-compatible+ * endpoints return true (lenient). Ollama text-only families return false so+ * the composer can show a non-blocking "this model can't read images" hint.+ */+export function isVisionCompatible(modelName: string | null): boolean {+ if (!modelName) return false+ const providerId = getProviderIdFromModel(modelName)+ if (providerId === 'openai' || providerId === 'anthropic') return true++ const baseName = normalizeFamily(modelName)+ return VISION_COMPATIBLE.some(f => containsFamily(f, baseName))+}+/*** Gemma 3/4 are thinking-compatible but their `think: false` path produces* plain-text structured planning (`Plan:`, `Constraint Checklist:`,diff --git a/src/lib/ollama-errors.ts b/src/lib/ollama-errors.tsindex 5276d2a4..e3c2882f 100644--- a/src/lib/ollama-errors.ts+++ b/src/lib/ollama-errors.ts@@ -155,3 +155,21 @@ export function chatStyleMessage(parsed: ParsedOllamaError): string {}return parsed.message}++/**+ * True when an error means the user attached an image to a model with no+ * vision/multimodal support. Native Ollama and OpenAI-compatible backends word+ * this differently — gthvidsten (GH Discussion #67, batiai/qwen3.6-27b:q6) saw+ * the raw OpenAI-style "Multimodal data provided, but model does not support+ * multimodal requests." with no guidance. Match the common phrasings.+ */+const MULTIMODAL_UNSUPPORTED_RE =+ /multimodal data provided|does not support multimodal|not multimodal|does not support image|image input is not supported|no vision support|vision is not supported/i++export function isMultimodalUnsupportedError(raw: string | null | undefined): boolean {+ return typeof raw === 'string' && MULTIMODAL_UNSUPPORTED_RE.test(raw)+}++/** Friendly, actionable copy shown when the chat hits the multimodal-unsupported error. */+export const MULTIMODAL_UNSUPPORTED_MESSAGE =+ "This model can't read images. Switch to a vision-capable model (e.g. Gemma 4, LLaVA, Qwen-VL, or Llama 3.2 Vision), or remove the attached image and send again."diff --git a/src/lib/parsers/chatbot-export.ts b/src/lib/parsers/chatbot-export.tsindex 0f7bca2a..f5c513d1 100644--- a/src/lib/parsers/chatbot-export.ts+++ b/src/lib/parsers/chatbot-export.ts@@ -229,13 +229,47 @@ function parseChatGpt(raw: unknown): NormalisedConversation[] {// "chat_messages": [// {// "uuid": "...",-// "text": "...",+// "text": "...", // legacy flat copy, often "" in modern exports+// "content": [{ "type": "text", "text": "..." }], // modern message body (preferred)// "sender": "human" | "assistant",+// "attachments": [{ "file_name": "...", "extracted_content": "..." }],// "created_at": "..."// }// ]// }// ]+// Modern Claude exports carry the message body in a typed `content[]` block+// array ([{ type:'text', text:'…' }, { type:'tool_use', … }]) and frequently+// leave the flat `text` field EMPTY — so the old `m.text`-only read imported+// those conversations as 0 messages and dropped them entirely (aldrich,+// Discord 2026-06-20 "how do i import chats from claude"). Prefer the text+// blocks, fall back to the flat field, and append any extracted attachment+// text (mikes_pp also asked for uploaded-file content). Non-text blocks+// (tool_use / tool_result / thinking) carry no `text` string and are skipped.+function extractClaudeText(m: any): string {+ const chunks: string[] = []+ if (Array.isArray(m?.content)) {+ for (const blk of m.content) {+ if (blk && typeof blk === 'object' && typeof blk.text === 'string' && blk.text.trim()) {+ chunks.push(blk.text.trim())+ }+ }+ }+ if (chunks.length === 0 && typeof m?.text === 'string' && m.text.trim()) {+ chunks.push(m.text.trim())+ }+ // Pasted / uploaded file contents Claude extracted at chat time.+ const attachments = Array.isArray(m?.attachments) ? m.attachments : []+ for (const a of attachments) {+ const extracted = typeof a?.extracted_content === 'string' ? a.extracted_content.trim() : ''+ if (extracted) {+ const fname = typeof a?.file_name === 'string' && a.file_name ? `[attachment: ${a.file_name}]\n` : ''+ chunks.push(fname + extracted)+ }+ }+ return chunks.join('\n\n').trim()+}+function parseClaude(raw: unknown): NormalisedConversation[] {if (!Array.isArray(raw)) return []const out: NormalisedConversation[] = []@@ -253,7 +287,7 @@ function parseClaude(raw: unknown): NormalisedConversation[] {let messageCount = 0for (const m of messages as any[]) {const sender = String(m?.sender || 'unknown')- const text = String(m?.text || '').trim()+ const text = extractClaudeText(m)if (!text) continueconst heading = sender === 'human' ? '**You**' : (sender === 'assistant' ? '**Assistant**' : `**${sender}**`)lines.push(heading, '', text, '')@@ -363,7 +397,13 @@ export async function parseExportFile(file: File): Promise<ParseResult> {// user saw "no conversation file found" (mikes_pp, Discord 2026-06-07).const entries: Array<{ path: string; entry: JSZip.JSZipObject }> = []zip.forEach((path, entry) => { if (!entry.dir) entries.push({ path, entry }) })- const basename = (p: string) => (p.split('/').pop() || '').toLowerCase()+ // Split on BOTH separators. Standard zips use '/', but Windows tools+ // (Explorer "Send to > Compressed folder", PowerShell Compress-Archive)+ // emit BACKSLASH-separated entry names. Without this a Windows-rezipped+ // export fails the conversations-NNN.json match, drops to the parse-and-pick+ // fallback, and only ONE shard (~100 chats) imports (verified 2026-06-21+ // with a 10-shard 1000-chat zip).+ const basename = (p: string) => (p.split(/[\\/]/).pop() || '').toLowerCase()const isJson = (p: string) => p.toLowerCase().endsWith('.json')// 1) Conversations live in one or more files named conversations.json or,