The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): currency stays text, cut answers say so, groups stop impersonating
purple2c6378f9cb28
diff --git a/src/components/chat/MarkdownRenderer.tsx b/src/components/chat/MarkdownRenderer.tsxindex 6dbd4242..dd888aa7 100644--- a/src/components/chat/MarkdownRenderer.tsx+++ b/src/components/chat/MarkdownRenderer.tsx@@ -3,6 +3,7 @@ import remarkGfm from 'remark-gfm'import remarkMath from 'remark-math'import rehypeKatex from 'rehype-katex'import 'katex/dist/katex.min.css'+import { MATH_OPTIONS } from '../../lib/markdown-math'import { CodeBlock } from './CodeBlock'import { codeBlockText } from '../../lib/markdown-code'import { openExternal } from '../../api/backend'@@ -126,7 +127,7 @@ const components: Components = {export function MarkdownRenderer({ content }: Props) {return (<div className="markdown-content text-gray-800 dark:text-gray-200">- <ReactMarkdown remarkPlugins={[remarkGfm, remarkMath]} rehypePlugins={[rehypeKatex]} components={components}>+ <ReactMarkdown remarkPlugins={[remarkGfm, [remarkMath, MATH_OPTIONS]]} rehypePlugins={[rehypeKatex]} components={components}>{content}</ReactMarkdown></div>diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex e50b7d2f..eafbdfb1 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -1,5 +1,5 @@import { motion } from 'framer-motion'-import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2 } from 'lucide-react'+import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2, Scissors } from 'lucide-react'import { useState, useRef, useEffect, useMemo, memo } from 'react'import { MarkdownRenderer } from './MarkdownRenderer'import { ThinkingBlock } from './ThinkingBlock'@@ -11,6 +11,7 @@ import { SpeakerButton } from './SpeakerButton'import { ChatArtifactCard } from './ChatArtifactCard'import type { Message } from '../../types/chat'import { stripModelNoise } from '../../lib/strip-model-noise'+import { truncationNotice } from '../../lib/answer-notes'import { useAgentModeStore } from '../../stores/agentModeStore'import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'@@ -370,6 +371,16 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, oreturn (<div className="text-[0.78rem] leading-relaxed"><MarkdownRenderer content={cleanContent} />+ {/* Cut-off marker: a turn the model did not finish on its own+ terms (length budget / dropped connection). The benchmark+ screen has always flagged cut-offs; the chat did not, so a+ truncated answer read as complete (David 2026-08-08). */}+ {truncationNotice(message.finishReason) && (+ <div className="mt-1 inline-flex items-center gap-1 text-[0.6rem] text-amber-600/80 dark:text-amber-300/70">+ <Scissors size={9} className="shrink-0" />+ <span>{truncationNotice(message.finishReason)}</span>+ </div>+ )}{/* A reasoning-only reply used to print a stand-in sentencehere ("The model only produced internal reasoning and noanswer"). That is our text in the model's mouth (G14-3,diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex db5453ea..6f3a5442 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -27,7 +27,8 @@ import { isThinkingCompatible, isPlainTextPlanner } from "../lib/model-compatibiimport { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-stripper"import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from "../lib/ollama-errors"import type { ImageAttachment, Message } from "../types/chat"-import { isGroupChat, groupSystemPrompt, groupHistory } from "../lib/group-chat"+import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers } from "../lib/group-chat"+import { emptyAnswerExplanation } from "../lib/answer-notes"import { log } from "../lib/logger"/**@@ -85,6 +86,10 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],let inThink = falselet discardBuf = ''let frameScheduled = false+ let groupFinish: string | undefined+ // A model's own lines are untagged; a "[other-model]" tag in its OWN reply is+ // it speaking for someone else, which v1 must not show.+ const others = allModels.filter((m) => m !== model)try {const { provider, modelId } = getProviderForModel(model)@@ -134,7 +139,7 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],if ((chunk.content || (chunk.thinking && keepThinking)) && !frameScheduled) {frameScheduled = truerequestAnimationFrame(() => {- useChatStore.getState().updateMessageContent(convId, assistantMessage.id, stripNonCanonicalTags(contentAcc))+ useChatStore.getState().updateMessageContent(convId, assistantMessage.id, stripImpersonatedSpeakers(stripNonCanonicalTags(contentAcc), others))if (keepThinking && thinkingAcc) {useChatStore.getState().updateMessageThinking(convId, assistantMessage.id, thinkingAcc)}@@ -142,11 +147,13 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],})}if (chunk.done) {- contentAcc = finalStripThinkingTags(contentAcc, keepThinking)+ if (chunk.finishReason) groupFinish = chunk.finishReason+ contentAcc = stripImpersonatedSpeakers(finalStripThinkingTags(contentAcc, keepThinking), others)useChatStore.getState().updateMessageContent(convId, assistantMessage.id, contentAcc)if (keepThinking && thinkingAcc) {useChatStore.getState().updateMessageThinking(convId, assistantMessage.id, thinkingAcc)}+ if (groupFinish) useChatStore.getState().updateMessageFinishReason(convId, assistantMessage.id, groupFinish)if (chunk.promptEvalCount || chunk.evalCount) {const promptTokens = chunk.promptEvalCount || 0const completionTokens = chunk.evalCount || 0@@ -159,10 +166,12 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],}}if (!abort.signal.aborted && !contentAcc.trim()) {+ // Empty turn: say WHY, length-aware, not a flat "didn't return an answer".+ // The bubble already labels the speaker, so no model prefix here.useChatStore.getState().updateMessageContent(convId,assistantMessage.id,- `${model} didn't return a visible answer that time.`,+ emptyAnswerExplanation({ finishReason: groupFinish, captured: !!thinkingAcc.trim(), keepThinking }),)}} catch (err) {@@ -645,7 +654,10 @@ export function useChat() {}if (chunk.done) {- if (chunk.finishReason) finishReason = chunk.finishReason+ if (chunk.finishReason) {+ finishReason = chunk.finishReason+ useChatStore.getState().updateMessageFinishReason(convId!, assistantMessage.id, chunk.finishReason)+ }// Final safety pass — catches any orphan tags that leaked through// mid-stream (partial chunks, provider restarts, etc.).contentRef.current = finalStripThinkingTags(contentRef.current, keepThinking)@@ -688,16 +700,7 @@ export function useChat() {// content EMPTY — the user saw a collapsed Thinking pill and nothing// else, which reads as a hang/crash (David, cloud Qwen3.6 2026-07-12:// 40k chars of looped reasoning, token budget gone, zero answer).- const explanation =- finishReason === 'length'- ? (captured- ? 'The model spent its entire token budget thinking and never wrote the answer. Try again, reasoning is not deterministic, or turn Thinking off for this question.'- : 'The model hit its token limit before writing an answer. Try again, or raise Max Tokens in Settings.')- : finishReason === 'disconnect'- ? 'The connection dropped before the model finished its answer. Check your network and try again.'- : captured && keepThinking- ? 'The model finished thinking but never wrote an answer. Try again, or turn Thinking off for this question.'- : "I didn't return a visible answer that time, please try again."+ const explanation = emptyAnswerExplanation({ finishReason, captured: !!captured, keepThinking })if (captured && keepThinking) {// Thinking ON: surface the reasoning AND say why there's no answer// (the collapsed thinking pill alone reads as dead air).diff --git a/src/lib/__tests__/answer-notes.test.ts b/src/lib/__tests__/answer-notes.test.tsnew file mode 100644index 00000000..c7917a17--- /dev/null+++ b/src/lib/__tests__/answer-notes.test.ts@@ -0,0 +1,65 @@+// Cut-off notice + empty-answer wording, and the guards that both chat paths+// persist finishReason and the bubble renders the marker (no render harness).+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, it, expect } from 'vitest'+import { truncationNotice, emptyAnswerExplanation } from '../answer-notes'++describe('truncationNotice', () => {+ it('flags a length cut and a dropped connection', () => {+ expect(truncationNotice('length')).toBe('Cut off at the length limit')+ expect(truncationNotice('disconnect')).toBe('Connection dropped before the end')+ })++ it('says nothing for a clean stop or an absent reason (negative control)', () => {+ expect(truncationNotice('stop')).toBeNull()+ expect(truncationNotice('tool_calls')).toBeNull()+ expect(truncationNotice(undefined)).toBeNull()+ })+})++describe('emptyAnswerExplanation', () => {+ it('length + reasoning: budget spent thinking', () => {+ expect(emptyAnswerExplanation({ finishReason: 'length', captured: true, keepThinking: true }))+ .toContain('spent its entire token budget thinking')+ })++ it('length + nothing: hit the token limit', () => {+ expect(emptyAnswerExplanation({ finishReason: 'length', captured: false, keepThinking: false }))+ .toContain('hit its token limit')+ })++ it('disconnect wins over the generic note', () => {+ expect(emptyAnswerExplanation({ finishReason: 'disconnect', captured: true, keepThinking: true }))+ .toContain('connection dropped')+ })++ it('clean stop with reasoning: finished thinking, no answer', () => {+ expect(emptyAnswerExplanation({ finishReason: 'stop', captured: true, keepThinking: true }))+ .toContain('finished thinking but never wrote an answer')+ })++ it('clean stop, nothing captured: plain retry note (negative control)', () => {+ expect(emptyAnswerExplanation({ finishReason: 'stop', captured: false, keepThinking: false }))+ .toBe("I didn't return a visible answer that time, please try again.")+ })+})++describe('wiring (source guards)', () => {+ const useChatSrc = readFileSync(join(__dirname, '../../hooks/useChat.ts'), 'utf8')+ const bubbleSrc = readFileSync(join(__dirname, '../../components/chat/MessageBubble.tsx'), 'utf8')++ it('both chat paths persist the finish reason onto the message', () => {+ // single-model path and group path each call the store setter+ const hits = useChatSrc.split('updateMessageFinishReason(').length - 1+ expect(hits).toBeGreaterThanOrEqual(2)+ })++ it('both paths route empty turns through the shared explanation', () => {+ expect(useChatSrc).toContain('emptyAnswerExplanation(')+ })++ it('the bubble renders the cut-off marker from finishReason', () => {+ expect(bubbleSrc).toContain('truncationNotice(message.finishReason)')+ })+})diff --git a/src/lib/__tests__/group-chat.test.ts b/src/lib/__tests__/group-chat.test.tsindex c5bbe3dc..89d6d822 100644--- a/src/lib/__tests__/group-chat.test.ts+++ b/src/lib/__tests__/group-chat.test.ts@@ -3,7 +3,7 @@import { readFileSync } from 'node:fs'import { join } from 'node:path'import { describe, it, expect, beforeEach } from 'vitest'-import { isGroupChat, groupSystemPrompt, groupHistory, GROUP_CHAT_MAX } from '../group-chat'+import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers, GROUP_CHAT_MAX } from '../group-chat'import { useChatStore } from '../../stores/chatStore'import type { Message } from '../../types/chat'@@ -68,6 +68,46 @@ describe('groupHistory', () => {})})+describe('stripImpersonatedSpeakers', () => {+ const others = ['phi-4-mini', 'granite-4.0-micro', 'hf.co/Qwen/Qwen3-4B-GGUF']++ it('cuts a fabricated next-speaker line and everything after it', () => {+ const out = stripImpersonatedSpeakers(+ 'I disagree, because the topic is fresh.\n[phi-4-mini] Actually it is not.',+ others,+ )+ expect(out).toBe('I disagree, because the topic is fresh.')+ })++ it('cuts a whole impersonated multi-turn tail', () => {+ const out = stripImpersonatedSpeakers(+ 'My take.\n\n[granite-4.0-micro] no\n[phi-4-mini] yes',+ others,+ )+ expect(out).toBe('My take.')+ })++ it('matches an id even when it contains regex metacharacters', () => {+ const out = stripImpersonatedSpeakers('Real.\n[hf.co/Qwen/Qwen3-4B-GGUF] fake', others)+ expect(out).toBe('Real.')+ })++ it('leaves an inline mention of another model untouched (negative control)', () => {+ const t = 'I agree with [phi-4-mini] on this one.'+ expect(stripImpersonatedSpeakers(t, others)).toBe(t)+ })++ it('leaves an ordinary bracketed word untouched (negative control)', () => {+ const t = 'See the note [1] and the label [draft] below.'+ expect(stripImpersonatedSpeakers(t, others)).toBe(t)+ })++ it('returns the text unchanged when there are no other models', () => {+ const t = 'solo answer'+ expect(stripImpersonatedSpeakers(t, [])).toBe(t)+ })+})+describe('chatStore.setGroupModels', () => {beforeEach(() => {useChatStore.setState({ conversations: [], activeConversationId: null })diff --git a/src/lib/__tests__/markdown-math.test.ts b/src/lib/__tests__/markdown-math.test.tsnew file mode 100644index 00000000..6b61b5cc--- /dev/null+++ b/src/lib/__tests__/markdown-math.test.ts@@ -0,0 +1,47 @@+// Currency must not be eaten by KaTeX. MarkdownRenderer feeds MATH_OPTIONS to+// remark-math; here we run the same remark pipeline headless and assert what it+// parses. unified/remark-parse are remark-math's own peer stack (transitive via+// react-markdown); if that ever stops resolving, this test fails loudly, which+// is the point.+import { describe, it, expect } from 'vitest'+import { unified } from 'unified'+import remarkParse from 'remark-parse'+import remarkMath from 'remark-math'+import { MATH_OPTIONS } from '../markdown-math'++function nodeTypes(md: string, opts: unknown): Set<string> {+ const tree = unified().use(remarkParse).use(remarkMath, opts as never).parse(md)+ const types = new Set<string>()+ ;(function walk(n: { type?: string; children?: unknown[] }) {+ if (n.type) types.add(n.type)+ for (const c of (n.children ?? []) as { type?: string; children?: unknown[] }[]) walk(c)+ })(tree as never)+ return types+}++const CURRENCY = 'Split the $30 bill. Each of the 3 pays $10.'++describe('MATH_OPTIONS (single-dollar off)', () => {+ it('does not turn a dollar amount into inline math', () => {+ expect(nodeTypes(CURRENCY, MATH_OPTIONS).has('inlineMath')).toBe(false)+ })++ it('still parses real block math ($$ on their own lines)', () => {+ expect(nodeTypes('$$\na^2 + b^2 = c^2\n$$', MATH_OPTIONS).has('math')).toBe(true)+ })++ it('still parses double-dollar inline math', () => {+ expect(nodeTypes('the identity $$e^{i\\pi}=-1$$ holds', MATH_OPTIONS).has('inlineMath')).toBe(true)+ })+})++describe('negative control: the default WOULD eat currency', () => {+ it('single-dollar on parses the same text as inline math', () => {+ // remark-math default is singleDollarTextMath: true — exactly the bug.+ expect(nodeTypes(CURRENCY, { singleDollarTextMath: true }).has('inlineMath')).toBe(true)+ })++ it('our option object is what disables it', () => {+ expect(MATH_OPTIONS.singleDollarTextMath).toBe(false)+ })+})diff --git a/src/lib/answer-notes.ts b/src/lib/answer-notes.tsnew file mode 100644index 00000000..b2b5df81--- /dev/null+++ b/src/lib/answer-notes.ts@@ -0,0 +1,35 @@+// One source of truth for what the UI says when an assistant turn did NOT end+// on the model's own terms. Both the single-model path and the group path go+// through here so the wording never drifts (David 2026-08-08: a length-cut in a+// group turn used to show a generic "didn't return a visible answer", with no+// hint that the token budget ran out; and a cut answer carried no marker at all,+// while the benchmark screen has always flagged cut-offs).++/** Short badge label for a turn the model did not finish on its own terms.+ * null for a clean stop, so the caller renders nothing. */+export function truncationNotice(finishReason?: string): string | null {+ if (finishReason === 'length') return 'Cut off at the length limit'+ if (finishReason === 'disconnect') return 'Connection dropped before the end'+ return null+}++/** Explanation to place in an assistant bubble that produced no visible answer.+ * `captured` = some reasoning was kept; `keepThinking` = Thinking is on. */+export function emptyAnswerExplanation(opts: {+ finishReason?: string+ captured: boolean+ keepThinking: boolean+}): string {+ const { finishReason, captured, keepThinking } = opts+ if (finishReason === 'length') {+ return captured+ ? 'The model spent its entire token budget thinking and never wrote the answer. Try again, reasoning is not deterministic, or turn Thinking off for this question.'+ : 'The model hit its token limit before writing an answer. Try again, or raise Max Tokens in Settings.'+ }+ if (finishReason === 'disconnect') {+ return 'The connection dropped before the model finished its answer. Check your network and try again.'+ }+ return captured && keepThinking+ ? 'The model finished thinking but never wrote an answer. Try again, or turn Thinking off for this question.'+ : "I didn't return a visible answer that time, please try again."+}diff --git a/src/lib/group-chat.ts b/src/lib/group-chat.tsindex 2f692133..9074ebb6 100644--- a/src/lib/group-chat.ts+++ b/src/lib/group-chat.ts@@ -32,6 +32,27 @@ export interface GroupWireMessage {images?: { data: string; mimeType: string }[]}+function escapeRegExp(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+}++/** A model's OWN lines go over the wire untagged; the other speakers arrive+ * tagged "[model-id] …". So a "[other-model] …" line in a model's own reply can+ * only be fabrication: a weak model (two Phi-4-mini in one group, Discord+ * 2026-08-08) copies the format and appends a line pretending to BE the next+ * speaker. v1 let that through. Cut from the first line that starts with another+ * participant's exact tag to the end. Line-anchored and exact-id-only, so an+ * inline mention ("I agree with [other]") or an ordinary "[note]" in prose is+ * untouched; only a fabricated turn header is removed. */+export function stripImpersonatedSpeakers(text: string, otherModels: string[]): string {+ const ids = otherModels.filter((m) => m.trim()).map(escapeRegExp)+ if (!ids.length) return text+ const tag = new RegExp(`^[ \\t>]*\\[(?:${ids.join('|')})\\]`)+ const lines = text.split('\n')+ const cut = lines.findIndex((l) => tag.test(l))+ return cut === -1 ? text : lines.slice(0, cut).join('\n').trim()+}+/** The shared history as one model sees it: other speakers tagged, own turns* clean, empty placeholders dropped. */export function groupHistory(messages: Message[], model: string): GroupWireMessage[] {diff --git a/src/lib/markdown-math.ts b/src/lib/markdown-math.tsnew file mode 100644index 00000000..ede51826--- /dev/null+++ b/src/lib/markdown-math.ts@@ -0,0 +1,6 @@+// remark-math options for chat rendering. singleDollarTextMath OFF means a lone+// `$` is treated as currency, not a math delimiter, so "$30. Each pays $10"+// renders as written instead of being swallowed into KaTeX and glued together+// (David 2026-08-08, seen in the thinking stream). Block math ($$…$$) still+// renders, which is what an actual formula uses in this app.+export const MATH_OPTIONS = { singleDollarTextMath: false } as constdiff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 2c40ad85..92a0b806 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -49,6 +49,7 @@ interface ChatState {updateMessageContent: (conversationId: string, messageId: string, content: string) => voidupdateMessageThinking: (conversationId: string, messageId: string, thinking: string) => voidupdateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }) => void+ updateMessageFinishReason: (conversationId: string, messageId: string, finishReason: string) => voidupdateMessageAgentBlocks: (conversationId: string, messageId: string, blocks: AgentBlock[]) => voidupdateMessageArtifacts: (conversationId: string, messageId: string, artifacts: ChatArtifact[]) => voiddeleteMessagesAfter: (conversationId: string, messageId: string) => void@@ -270,6 +271,19 @@ export const useChatStore = create<ChatState>()(),})),+ updateMessageFinishReason: (conversationId, messageId, finishReason) =>+ set((state) => ({+ conversations: state.conversations.map((c) =>+ c.id === conversationId+ ? {+ ...c,+ messages: c.messages.map((m) => (m.id === messageId ? { ...m, finishReason } : m)),+ updatedAt: Date.now(),+ }+ : c+ ),+ })),+updateMessageAgentBlocks: (conversationId, messageId, agentBlocks) =>set((state) => ({conversations: state.conversations.map((c) =>diff --git a/src/types/chat.ts b/src/types/chat.tsindex 230ea404..212f447d 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -72,6 +72,11 @@ export interface Message {// of only the visible messages); it flips to false once the model reports the// exact prompt_eval_count / usage.prompt_tokens.usage?: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }+ /** Why generation ended, when the model did NOT stop on its own terms:+ * 'length' (token budget) or 'disconnect'. Drives the small cut-off badge so+ * a truncated answer is not shown as if it were complete (parity with the+ * benchmark screen). Absent or 'stop' on a clean finish. */+ finishReason?: string}export interface Conversation {