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): a long run reads like work, not like noise
purpledd8199639e61
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex c26c5a3a..292826c8 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -16,6 +16,7 @@ import { FileText, ChevronDown, Download, Wrench, Radio, RefreshCw, X } from 'luimport { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'import { GoalBar } from './GoalBar'+import { PlanBar } from './PlanBar'import { LoopBar } from './LoopBar'import { MemoryDebugToggle } from './MemoryDebugPanel'import { TokenCounter } from './TokenCounter'@@ -25,7 +26,6 @@ import { ABCompare } from './ABCompare'import { useCompareStore } from '../../stores/compareStore'import { exportConversation } from '../../lib/chat-export'import { PermissionOverrideBar } from './PermissionOverrideBar'-import { RealtimeCounter } from './RealtimeCounter'import { CodexView } from './CodexView'import { useCodexStore } from '../../stores/codexStore'import { useGenerationStore } from '../../stores/generationStore'@@ -248,7 +248,6 @@ export function ChatView() {onApprove={approveToolCall}onReject={rejectToolCall}/>- <RealtimeCounter isRunning={activeGenerating} />{/* Remote session banners */}{isThisRemoteActive && (@@ -340,7 +339,7 @@ export function ChatView() {slashCommands={isAgentActive}onAttachDocs={appMode !== 'cloud' ? () => setRagPanelOpen(true) : undefined}composerModel={<ModelSelector openUpward />}- composerAbove={<><LoopBar onStop={stopGeneration} /><GoalBar /></>}+ composerAbove={<><LoopBar onStop={stopGeneration} /><GoalBar /><PlanBar /></>}composerActions={<>{/* Documents (RAG) — local-embeddings only, so hide indiff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 6a939800..9c6935d6 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -1,4 +1,5 @@import { useCodex } from '../../hooks/useCodex'+import { useAutoScroll } from '../../hooks/useAutoScroll'import { useCodexStore } from '../../stores/codexStore'import { useChatStore } from '../../stores/chatStore'import { useGenerationStore } from '../../stores/generationStore'@@ -11,18 +12,19 @@ import { MarkdownRenderer } from './MarkdownRenderer'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'import { SmallModelModeToggle } from './SmallModelModeToggle'-import { RealtimeCounter } from './RealtimeCounter'+import { WorkingAnchor } from './WorkingAnchor'+import { useCodexConfirmStore } from '../../stores/codexConfirmStore'import { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'import { GoalBar } from './GoalBar'+import { PlanBar } from './PlanBar'import { LoopBar } from './LoopBar'-import { TypingIndicator } from './TypingIndicator'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'import { StagedChangesPanel } from './StagedChangesPanel'import { SlashStepsBlock } from './SlashStepsBlock'-import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, X } from 'lucide-react'-import { useEffect, useRef, useState } from 'react'+import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder } from 'lucide-react'+import { useEffect, useState } from 'react'import { checkGitInstalled, openExternal, type GitStatus } from '../../api/backend'import { CodexConfirmDialog } from './CodexConfirmDialog'import { stripModelNoise } from '../../lib/strip-model-noise'@@ -41,7 +43,6 @@ export function CodexView() {const activeConversationId = useChatStore((s) => s.activeConversationId)const conversations = useChatStore((s) => s.conversations)const thread = useCodexStore((s) => activeConversationId ? s.threads[activeConversationId] : undefined)- const scrollRef = useRef<HTMLDivElement>(null)const conversation = conversations.find(c => c.id === activeConversationId)const messages = conversation?.messages || []@@ -53,27 +54,24 @@ export function CodexView() {// refs); the visual bits below read this conversation-scoped flag instead.const generatingMap = useGenerationStore((s) => s.generating)const codexGenerating = !!activeConversationId && !!generatingMap[activeConversationId]+ const pendingConfirm = useCodexConfirmStore((s) => s.pending)- // Smart auto-scroll (David 2026-06-12: "kann nicht scrollen, bin locked, jumpt- // zurück auf ganz unten"). A scroll listener records whether the user is at the- // bottom; we only auto-pin when they are — so scrolling UP to read earlier- // output is never yanked back down, even when a chunky tool-call block streams- // in. Mirrors the normal chat's useAutoScroll, which already behaves this way.- const shouldAutoScroll = useRef(true)- useEffect(() => {- const el = scrollRef.current- if (!el) return- const onScroll = () => {- shouldAutoScroll.current = el.scrollHeight - el.scrollTop - el.clientHeight < 100- }- el.addEventListener('scroll', onScroll)- return () => el.removeEventListener('scroll', onScroll)- }, [])- useEffect(() => {- if (shouldAutoScroll.current && scrollRef.current) {- scrollRef.current.scrollTop = scrollRef.current.scrollHeight- }- }, [messages, thread?.events])+ // G8-3 (David): "sobald er fertig gedacht hat, hakt das so komisch ab und+ // zoomt irgendwo ganz anders hin." The hand-rolled pin here only fired on+ // [messages, events] changes, so the height SWAP when a thinking round ends+ // (live bubble cleared above, ThinkingBlock added below, preview collapses)+ // landed between triggers and left the view parked mid-transcript. Same+ // mechanism as G33 on the chat list, same cure: the shared useAutoScroll+ // hook re-pins through a ResizeObserver on EVERY content-height change,+ // growth and collapse alike, while the user is following. Scrolling up to+ // read stays possible (same <100px disengage), and sending an instruction+ // re-engages via the last user message id.+ const lastMessage = messages[messages.length - 1]+ const lastUserMessage = messages.filter((m) => m.role === 'user').at(-1)+ const { ref: scrollRef, contentRef } = useAutoScroll(+ `${lastMessage?.content ?? ''}|${thread?.events?.length ?? 0}`,+ lastUserMessage?.id,+ )const codexReviewMode = useSettingsStore((s) => s.settings.codexReviewMode)const userAvatarDataUrl = useSettingsStore((s) => s.settings.userAvatarDataUrl)@@ -206,7 +204,7 @@ export function CodexView() {)}</div>) : (- <div className="py-1">+ <div ref={contentRef} className="py-1">{messages.filter(msg => !msg.hidden).map((msg) => {// Slash commands: the user typed "/review", but msg.content holds// the expanded instruction the model ran on, show displayContent.@@ -277,7 +275,9 @@ export function CodexView() {.filter((b) =>(b.phase === 'tool_call' && b.toolCall) ||- (b.phase === 'answer' && stripChannelTags(b.content)),+ (b.phase === 'answer' && stripChannelTags(b.content)) ||+ // G21-2: per-round thoughts, chronological+ (b.phase === 'thinking' && b.content.trim()),).sort((a, b) => a.timestamp - b.timestamp)// Render EVERY answer normally + visible@@ -301,9 +301,32 @@ export function CodexView() {// collapses to "N steps" when done// (David 2026-07-31).if (group.kind === 'tools') {- return <ToolCallBand key={group.blocks[0].id} calls={group.calls} />+ return (+ <ToolCallBand+ key={group.blocks[0].id}+ calls={group.calls}+ notes={group.notes}+ renderNote={(block) => {+ if (block.phase === 'thinking') {+ return <ThinkingBlock thinking={block.content} />+ }+ const note = stripChannelTags(block.content)+ if (!note) return null+ return (+ <div className="px-1 py-0.5 text-[0.7rem] leading-relaxed text-gray-500 dark:text-gray-400">+ <MarkdownRenderer content={note} />+ </div>+ )+ }}+ />+ )}const block = group.block+ if (block.phase === 'thinking') {+ // Trailing thought before the final+ // answer, in its collapsed G14-7 bubble.+ return <ThinkingBlock key={block.id} thinking={block.content} />+ }if (block.phase === 'answer') {const answer = stripChannelTags(block.content)if (!answer || skippedAnswers.has(block.id)) return null@@ -439,16 +462,17 @@ export function CodexView() {"ich hätte das gerne im chat, wie ein tool call"). Rendersnothing while no request is pending. */}<CodexConfirmDialog />- {codexGenerating && (- <TypingIndicator />- )}+ {/* G14-6: one anchor with shimmer + clock, no dots, no floating+ counter. It also names an approval wait for what it is, so a+ blocked run never looks like a working one (G15b). */}+ <WorkingAnchor+ isRunning={codexGenerating}+ label={pendingConfirm ? 'Waiting for your approval' : undefined}+ /></div>)}</div>- {/* Realtime counter */}- <RealtimeCounter isRunning={codexGenerating} />-{/* One-time "/" hint, directly above the prompt (Code view only). */}{/* Input */}@@ -463,7 +487,7 @@ export function CodexView() {isGenerating={isRunning || codexGenerating}slashCommandscomposerModel={<ModelSelector openUpward surface="code" />}- composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /></>}+ composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /><PlanBar /></>}composerActions={<PluginsDropdown openUpward />}/></div>diff --git a/src/components/chat/MarkdownRenderer.tsx b/src/components/chat/MarkdownRenderer.tsxindex 4ac861e7..6dbd4242 100644--- a/src/components/chat/MarkdownRenderer.tsx+++ b/src/components/chat/MarkdownRenderer.tsx@@ -4,6 +4,7 @@ import remarkMath from 'remark-math'import rehypeKatex from 'rehype-katex'import 'katex/dist/katex.min.css'import { CodeBlock } from './CodeBlock'+import { codeBlockText } from '../../lib/markdown-code'import { openExternal } from '../../api/backend'import type { Components } from 'react-markdown'@@ -42,7 +43,12 @@ const components: Components = {const isBlock = match || (typeof children === 'string' && children.includes('\n'))if (isBlock) {- return <CodeBlock code={String(children).replace(/\n$/, '')} language={match?.[1]} />+ // Coerce through the helper, never through a bare cast: an empty fence+ // arrives as undefined and used to print the word "undefined" in a code+ // box, which is what every code block looks like for the moment between+ // its opening fence and its first character. Live capture and the shapes+ // it has to survive are in lib/markdown-code.ts.+ return <CodeBlock code={codeBlockText(children)} language={match?.[1]} />}return (diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex 1e7f02f8..f69ef93a 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -208,7 +208,12 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o(b) =>b.phase === 'tool_call' ||b.phase === 'reflection' ||- (b.phase === 'answer' && b.content.trim()),+ (b.phase === 'answer' && b.content.trim()) ||+ // G21-2: per-round thoughts render chronologically between+ // the calls. The transient "Analyzing..." placeholder is a+ // thinking block too and shows as a live bubble until the+ // round's first token replaces it.+ (b.phase === 'thinking' && b.content.trim()),).sort((a, b) => a.timestamp - b.timestamp),)@@ -221,6 +226,18 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o<ToolCallBandkey={group.blocks[0].id}calls={group.calls}+ notes={group.notes}+ renderNote={(block) =>+ block.phase === 'thinking' ? (+ <ThinkingBlock thinking={block.content} />+ ) : block.phase === 'reflection' ? (+ <ReflectionBlock content={block.content} />+ ) : (+ <div className="px-1 py-0.5 text-[0.7rem] leading-relaxed text-gray-500 dark:text-gray-400">+ <MarkdownRenderer content={cleanBlocks.get(block.id) ?? block.content} />+ </div>+ )+ }pendingApprovalId={pendingApprovalId}onApprove={onApprove}onReject={onReject}@@ -228,6 +245,11 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o)}const block = group.block+ if (block.phase === 'thinking') {+ // Trailing thought (after the last call, before the final+ // answer) in its G14-7 bubble, collapsed, chronological.+ return <ThinkingBlock key={block.id} thinking={block.content} />+ }if (block.phase === 'reflection') {return <ReflectionBlock key={block.id} content={block.content} />}@@ -325,26 +347,28 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, oreturn (<div className="text-[0.78rem] leading-relaxed"><MarkdownRenderer content={cleanContent} />- {thoughtOnly && (- thoughtOnlyToolIntent && activeModel && isAgentCompatible(activeModel) ? (- <div className="mt-1 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">- <Wrench size={11} className="mt-0.5 shrink-0" />- <div className="flex-1">- <p className="font-medium">The model spent its whole reply deciding to call a tool, but Agent Mode is off, so it never said anything.</p>- <p className="opacity-80 mt-0.5">Turn Agent Mode on and ask again to let it actually run the tool (search the web, generate media, read files). Its reasoning is in the thinking block above.</p>- </div>- <button- onClick={() => activeConversationId && toggleAgentMode(activeConversationId)}- className="shrink-0 px-2 py-0.5 rounded border border-amber-400/40 hover:bg-amber-500/20 transition-colors font-medium"- >- Enable Agent- </button>+ {/* A reasoning-only reply used to print a stand-in sentence+ here ("The model only produced internal reasoning and no+ answer"). That is our text in the model's mouth (G14-3,+ David 2026-08-07), and on an agent surface the loop's job+ is to CONTINUE past such a round (G17), not to explain+ it. The thinking block above already shows what happened.+ The amber card below survives because it is a labelled+ app hint with an action, not prose posing as an answer. */}+ {thoughtOnly && thoughtOnlyToolIntent && activeModel && isAgentCompatible(activeModel) && (+ <div className="mt-1 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">+ <Wrench size={11} className="mt-0.5 shrink-0" />+ <div className="flex-1">+ <p className="font-medium">The model spent its whole reply deciding to call a tool, but Agent Mode is off, so it never said anything.</p>+ <p className="opacity-80 mt-0.5">Turn Agent Mode on and ask again to let it actually run the tool (search the web, generate media, read files). Its reasoning is in the thinking block above.</p></div>- ) : (- <p className="mt-1 text-[0.65rem] italic text-gray-500 dark:text-gray-400">- The model only produced internal reasoning and no answer. See the thinking block above, or rephrase and try again.- </p>- )+ <button+ onClick={() => activeConversationId && toggleAgentMode(activeConversationId)}+ className="shrink-0 px-2 py-0.5 rounded border border-amber-400/40 hover:bg-amber-500/20 transition-colors font-medium"+ >+ Enable Agent+ </button>+ </div>)}{suggestAgent && (<div className="mt-2 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex fc4bc8a8..75fd1d1c 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -2,7 +2,7 @@ import { useCallback, useRef } from 'react'import { useChatStore } from '../../stores/chatStore'import { useAutoScroll } from '../../hooks/useAutoScroll'import { MessageBubble } from './MessageBubble'-import { TypingIndicator } from './TypingIndicator'+import { WorkingAnchor } from './WorkingAnchor'interface Props {/** GLOBAL generating flag — guards regenerate/edit so a second concurrent@@ -31,7 +31,17 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel})const lastMessage = conversation?.messages[conversation.messages.length - 1]- const scrollRef = useAutoScroll(lastMessage?.content)+ // The approval id is part of the scroll trigger (G31): a run waiting for a+ // decision often adds NO content, so the list stood still while the inline+ // Approve/Reject grew in below the fold. Growth WITHOUT a trigger (Working+ // anchor mounting, a thinking block streaming while content stays empty) is+ // covered by the hook's ResizeObserver (G33). The resumeKey is the last+ // USER message: sending jumps all the way down even after scrolling away.+ const lastUserMessage = conversation?.messages.filter((m) => m.role === 'user').at(-1)+ const { ref: scrollRef, contentRef } = useAutoScroll(+ `${lastMessage?.content ?? ''}|${pendingApprovalId ?? ''}`,+ lastUserMessage?.id,+ )// MessageBubble is memoised, so its handlers have to keep the same identity// across renders. Binding the conversation id and the parent's callbacks@@ -65,31 +75,34 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelmaskImage: 'linear-gradient(to bottom, transparent 0, #000 28px)',}}>- {visibleMessages- .map((message) => (- <MessageBubble- key={message.id}- message={message}- isLast={message.id === lastVisibleId}- onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating- ? handleRegenerate- : undefined}- onEdit={message.role === 'user' && onEdit && !isGenerating- ? handleEdit- : undefined}- pendingApprovalId={pendingApprovalId}- onApprove={onApprove}- onReject={onReject}- />- ))}- {/* 3-dot loading indicator stays visible the entire time the agent- is still working — including between tool calls and while the- final answer is streaming. Previously it only showed when the- last assistant message was empty, which made multi-turn agent- runs look frozen between iterations (per user feedback). */}- {showTyping && lastMessage?.role === 'assistant' && (- <TypingIndicator label={isLoadingModel ? 'Loading model...' : undefined} />- )}+ {/* Single wrapper so the hook's ResizeObserver sees ALL content height,+ anchor included (G33). */}+ <div ref={contentRef}>+ {visibleMessages+ .map((message) => (+ <MessageBubble+ key={message.id}+ message={message}+ isLast={message.id === lastVisibleId}+ onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating+ ? handleRegenerate+ : undefined}+ onEdit={message.role === 'user' && onEdit && !isGenerating+ ? handleEdit+ : undefined}+ pendingApprovalId={pendingApprovalId}+ onApprove={onApprove}+ onReject={onReject}+ />+ ))}+ {/* The run anchor stays visible the entire time the agent is still+ working, including between tool calls and while the final answer+ streams. G14-6: one shimmering "Working" with the clock beside it,+ instead of three dots here and a floating counter elsewhere. */}+ {showTyping && lastMessage?.role === 'assistant' && (+ <WorkingAnchor isRunning label={isLoadingModel ? 'Loading model' : undefined} />+ )}+ </div></div>)}diff --git a/src/components/chat/RealtimeCounter.tsx b/src/components/chat/RealtimeCounter.tsxdeleted file mode 100644index b6e405d3..00000000--- a/src/components/chat/RealtimeCounter.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { useEffect, useRef, useState } from 'react'--interface Props {- isRunning: boolean-}--export function RealtimeCounter({ isRunning }: Props) {- const [elapsed, setElapsed] = useState(0)- const startRef = useRef(Date.now())-- useEffect(() => {- if (!isRunning) { setElapsed(0); return }- startRef.current = Date.now()- const interval = setInterval(() => {- setElapsed(Math.floor((Date.now() - startRef.current) / 1000))- }, 100)- return () => clearInterval(interval)- }, [isRunning])-- if (!isRunning || elapsed < 1) return null-- const mins = Math.floor(elapsed / 60)- const secs = elapsed % 60-- return (- <div className="absolute bottom-14 right-2 flex items-center gap-1.5 px-2 py-0.5 rounded bg-gray-100/80 dark:bg-white/5 backdrop-blur-sm z-10">- <div className="w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-gray-500 animate-pulse" />- <span className="text-[0.5rem] text-gray-500 dark:text-gray-500 font-mono tabular-nums">- {mins > 0 ? `${mins}m ` : ''}{secs}s- </span>- </div>- )-}diff --git a/src/components/chat/ThinkingBlock.tsx b/src/components/chat/ThinkingBlock.tsxindex 829eb14b..b7343c6d 100644--- a/src/components/chat/ThinkingBlock.tsx+++ b/src/components/chat/ThinkingBlock.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useMemo } from 'react'+import { useState, useRef, useEffect, useMemo } from 'react'import { motion, AnimatePresence } from 'framer-motion'import { ChevronDown, Brain } from 'lucide-react'import { MarkdownRenderer } from './MarkdownRenderer'@@ -6,18 +6,29 @@ import { stripModelNoise } from '../../lib/strip-model-noise'interface Props {thinking: string- /** True while the model is actively producing this turn. Auto-expands the- * block so the reasoning is visible STREAMING in real time (David 2026-06-04),- * then auto-collapses once the turn finishes. The user can still toggle. */+ /** True while the model is actively producing this turn. While it is,+ * the COLLAPSED block shows a bounded, self-scrolling live peek of the+ * reasoning (G14-7, David 2026-08-07: thinking stays folded everywhere+ * and streams inside a 3-4 line window; supersedes the 2026-06-04+ * auto-expand). The user can still expand for the full text. */streaming?: boolean}+// Four lines of the 0.65rem / leading-relaxed reasoning text.+const PREVIEW_MAX_H = 'max-h-[68px]'+export function ThinkingBlock({ thinking, streaming }: Props) {- // null = follow `streaming` automatically; true/false = user override.- const [userToggled, setUserToggled] = useState<boolean | null>(null)- const open = userToggled !== null ? userToggled : !!streaming- // When the turn ends, drop the manual override so the NEXT turn auto-expands.- useEffect(() => { if (!streaming) setUserToggled(null) }, [streaming])+ const [open, setOpen] = useState(false)+ const previewRef = useRef<HTMLDivElement>(null)++ // Keep the live peek pinned to the newest reasoning. No dep array on+ // purpose: the text grows every streaming frame, so this runs each render+ // and the window tracks the bottom, same pattern as SlashStepsBlock.+ useEffect(() => {+ if (streaming && !open && previewRef.current) {+ previewRef.current.scrollTop = previewRef.current.scrollHeight+ }+ })// Strip orchestration out of the reasoning too (2.5.9): Qwen3-32B writes// its planned call as a raw <tool_call> tag inside the thought, and that@@ -30,18 +41,32 @@ export function ThinkingBlock({ thinking, streaming }: Props) {return (<div className="mb-0.5"><button- onClick={() => setUserToggled(!open)}+ onClick={() => setOpen((o) => !o)}className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity"aria-label="Toggle thinking details"><Brain size={10} className="text-blue-400/70 shrink-0" />- <span className="text-[0.6rem] text-blue-400/70">Thinking</span>+ <span className={`text-[0.6rem] text-blue-400/70 ${streaming ? 'lu-tool-shimmer' : ''}`}>Thinking</span><ChevronDownsize={9}className={`text-blue-400/50 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}/></button>+ {!open && streaming && (+ // Collapsed + streaming: bounded live peek. The top fades so+ // older reasoning scrolls up out of view; clicks fall through+ // to the header toggle.+ <div+ ref={previewRef}+ className={`pl-4 pb-1 pt-0.5 ${PREVIEW_MAX_H} overflow-hidden pointer-events-none [mask-image:linear-gradient(to_bottom,transparent,#000_20px)]`}+ >+ <div className="text-[0.65rem] leading-relaxed italic text-blue-200/40">+ <MarkdownRenderer content={cleaned} />+ </div>+ </div>+ )}+<AnimatePresence>{open && (<motion.divdiff --git a/src/components/chat/ToolCallBand.tsx b/src/components/chat/ToolCallBand.tsxindex b8c15926..c497b126 100644--- a/src/components/chat/ToolCallBand.tsx+++ b/src/components/chat/ToolCallBand.tsx@@ -1,7 +1,7 @@-import { useState } from 'react'+import { Fragment, useState, type ReactNode } from 'react'import { AnimatePresence, motion } from 'framer-motion'import { AlertCircle, Check, ChevronDown, Wrench } from 'lucide-react'-import type { AgentToolCall } from '../../types/agent-mode'+import type { AgentBlock, AgentToolCall } from '../../types/agent-mode'import {ToolCallBlock,comfyViewUrlFromResult,@@ -11,10 +11,16 @@ import {activeToolCall,groupDurationLabel,groupIsLive,+ type BandNote,} from '../../lib/tool-call-groups'interface Props {calls: AgentToolCall[]+ /** G14-4: narration the grouping absorbed from between the calls. Rendered+ * inside the EXPANDED view at its original position; folded away with the+ * rest while collapsed, which is the whole point of the band. */+ notes?: BandNote[]+ renderNote?: (block: AgentBlock) => ReactNodependingApprovalId?: string | nullonApprove?: () => voidonReject?: () => void@@ -33,7 +39,7 @@ interface Props {* pending_approval), and completed media results (konata 2026-06-07 "and no* image") — those calls keep rendering below the band whatever its state.*/-export function ToolCallBand({ calls, pendingApprovalId, onApprove, onReject }: Props) {+export function ToolCallBand({ calls, notes, renderNote, pendingApprovalId, onApprove, onReject }: Props) {const [userToggled, setUserToggled] = useState<boolean | null>(null)const expanded = userToggled ?? falseconst live = groupIsLive(calls)@@ -74,7 +80,16 @@ export function ToolCallBand({ calls, pendingApprovalId, onApprove, onReject }:expandedonToggle={() => setUserToggled(false)}/>- <div className="space-y-0.5 pl-1">{calls.map(blockFor)}</div>+ <div className="space-y-0.5 pl-1">+ {calls.map((tc, i) => (+ <Fragment key={tc.id}>+ {blockFor(tc)}+ {renderNote && (notes ?? []).filter((n) => n.afterCall === i).map((n) => (+ <Fragment key={n.block.id}>{renderNote(n.block)}</Fragment>+ ))}+ </Fragment>+ ))}+ </div></div>)}diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 6449c9b2..76240e92 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -9,6 +9,7 @@ import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './Modelimport { DiffView } from './DiffView'import { requestGenerationCancel } from '../../api/vram-handoff'import { fileUrlToPath, readLocalFileAsBlobUrl } from '../../lib/local-media-url'+import { hiddenFromTranscript } from '../../lib/transcript-visibility'// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)// — when image_generate / video_generate / screenshot produce a ComfyUI output,@@ -196,7 +197,15 @@ const STATUS_ICONS = {// memo (audit D2): the Codex/Agent transcript re-renders on every streamed// frame, and each un-memoised block re-rendered with it. Block updates// replace the toolCall object, so reference equality is the right check.-export const ToolCallBlock = memo(ToolCallBlockImpl)+//+// The gate sits OUTSIDE the implementation on purpose: a tool that another+// surface already owns must not mount the block at all, and an early return+// inside ToolCallBlockImpl would have to come after its hooks. See+// lib/transcript-visibility.ts for which calls those are and why.+export const ToolCallBlock = memo(function ToolCallBlockGate(props: Props) {+ if (hiddenFromTranscript(props.toolCall)) return null+ return <ToolCallBlockImpl {...props} />+})function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// Default: collapsed (closed)diff --git a/src/components/chat/TypingIndicator.tsx b/src/components/chat/TypingIndicator.tsxdeleted file mode 100644index b2d87ab3..00000000--- a/src/components/chat/TypingIndicator.tsx+++ /dev/null@@ -1,21 +0,0 @@-import { motion } from 'framer-motion'--export function TypingIndicator({ label }: { label?: string }) {- return (- <div className="flex flex-col gap-1 px-3 py-1.5">- <div className="flex gap-1">- {[0, 1, 2].map((i) => (- <motion.div- key={i}- className="w-1.5 h-1.5 rounded-full bg-gray-300"- animate={{ opacity: [0.3, 1, 0.3], scale: [0.8, 1.2, 0.8] }}- transition={{ duration: 1.2, repeat: Infinity, delay: i * 0.2 }}- />- ))}- </div>- {label && (- <span className="text-[10px] text-gray-400 dark:text-gray-500">{label}</span>- )}- </div>- )-}diff --git a/src/components/chat/WorkingAnchor.tsx b/src/components/chat/WorkingAnchor.tsxnew file mode 100644index 00000000..964d8b13--- /dev/null+++ b/src/components/chat/WorkingAnchor.tsx@@ -0,0 +1,46 @@+import { useEffect, useRef, useState } from 'react'+import { formatElapsed } from '../../lib/format-elapsed'++interface Props {+ isRunning: boolean+ /** What the run is actually doing right now. Defaults to "Working"; pass+ * something specific ("Waiting for your approval", "Generating image")+ * whenever the surface knows better, because a wait that looks like work+ * is how a nine minute approval stall got mistaken for progress (G15b). */+ label?: string+}++/**+ * THE bottom-of-run status line (G14-6, David 2026-08-07): the word "Working"+ * carrying the same shimmer as a live tool name, with the elapsed clock+ * beside it. It replaces the three bouncing dots AND the floating+ * bottom-right counter on every surface (Chat, Agent, Code), so a run has+ * exactly one anchor that says the app is alive, what it is doing, and for+ * how long. Reference is the Claude desktop app.+ */+export function WorkingAnchor({ isRunning, label }: Props) {+ const [elapsed, setElapsed] = useState(0)+ const startRef = useRef(Date.now())++ useEffect(() => {+ if (!isRunning) { setElapsed(0); return }+ startRef.current = Date.now()+ const interval = setInterval(() => {+ setElapsed(Math.floor((Date.now() - startRef.current) / 1000))+ }, 250)+ return () => clearInterval(interval)+ }, [isRunning])++ if (!isRunning) return null++ return (+ <div className="flex items-center gap-2 px-3 py-1.5" data-testid="working-anchor">+ <span className="lu-tool-shimmer text-[0.7rem] font-medium">{label ?? 'Working'}</span>+ {elapsed >= 1 && (+ <span className="text-[0.6rem] text-gray-500 dark:text-gray-500 font-mono tabular-nums">+ {formatElapsed(elapsed)}+ </span>+ )}+ </div>+ )+}diff --git a/src/components/chat/__tests__/scroll-pins-bottom.test.ts b/src/components/chat/__tests__/scroll-pins-bottom.test.tsnew file mode 100644index 00000000..25e3518d--- /dev/null+++ b/src/components/chat/__tests__/scroll-pins-bottom.test.ts@@ -0,0 +1,94 @@+/**+ * G33 (David 2026-08-07): "wenn ein Text abgeschickt wird, soll der Chat nach+ * ganz unten springen, wo Working dann zu sehen ist; momentan springt er+ * runter, aber nie ganz."+ *+ * The old pin fired only when the trigger STRING changed. Two kinds of height+ * appear below the fold without it: the Working anchor mounts on a prop flip,+ * and a reasoning model streams into a thinking block while the message+ * content stays empty. The view then parks one anchor-height short of the+ * bottom for the entire thinking phase, which is exactly the report.+ *+ * Run: npx vitest run src/components/chat/__tests__/scroll-pins-bottom.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const hook = read('../../../hooks/useAutoScroll.ts')+const messageList = read('../MessageList.tsx')++describe('the list follows every growth, not just anticipated triggers', () => {+ it('a ResizeObserver on the content wrapper re-pins on growth', () => {+ expect(hook).toContain('new ResizeObserver(')+ expect(hook).toContain('ro.observe(content)')+ })++ it('MessageList wraps ALL content, anchor included, in that wrapper', () => {+ // The anchor must sit INSIDE the observed wrapper or its mount is+ // invisible to the observer and the original bug returns.+ const wrapperOpen = messageList.indexOf('ref={contentRef}')+ const anchor = messageList.indexOf('<WorkingAnchor')+ expect(wrapperOpen).toBeGreaterThan(-1)+ expect(anchor).toBeGreaterThan(wrapperOpen)+ })++ it('sending re-engages following and jumps fully down', () => {+ // The resumeKey is the last USER message id: a send is an explicit+ // "take me to the newest", whatever the scroll position was.+ expect(messageList).toContain('lastUserMessage?.id')+ expect(hook).toContain('shouldScroll.current = true')+ })++ // ── Negative controls ────────────────────────────────────────────────────++ it('reading history during a run stays possible', () => {+ // The observer pin is gated on the follow flag, and the scroll listener+ // that clears the flag is still wired. Without both, the observer would+ // yank the user back down on every streamed token.+ expect(hook).toMatch(/if \(shouldScroll\.current && el\) el\.scrollTop = el\.scrollHeight/)+ expect(hook).toContain("el.addEventListener('scroll', handleScroll)")+ })++ it('an assistant answer does NOT re-engage following', () => {+ // Only the user message id feeds resumeKey. If the whole message list or+ // the assistant id fed it, streaming would fight the user's scrollback.+ expect(messageList).not.toContain('resumeKey={lastMessage')+ expect(messageList).toContain("messages.filter((m) => m.role === 'user')")+ })++ it('the plain streaming trigger still exists alongside the observer', () => {+ // Environments without ResizeObserver (jsdom in tests) keep the old+ // dependency-driven pin as the fallback path.+ expect(hook).toContain("typeof ResizeObserver === 'undefined'")+ expect(hook).toMatch(/\}, \[dependency\]\)/)+ })++ // G8-3 (#28): "sobald er fertig gedacht hat, hakt das ab und zoomt irgendwo+ // ganz anders hin." The Code tab's hand-rolled pin only fired on+ // [messages, events]; the height swap when a thinking round ends fell+ // between triggers. It now shares this hook, so the observer re-pins on+ // every height change, the collapse included.+ it('the Code tab shares the hook instead of its own partial pin', () => {+ const codex = read('../CodexView.tsx')+ expect(codex).toContain('useAutoScroll(')+ expect(codex).not.toContain('shouldAutoScroll')+ })++ it('Codex wraps the whole list, anchor included, in the observed wrapper', () => {+ const codex = read('../CodexView.tsx')+ const wrapperOpen = codex.indexOf('ref={contentRef}')+ const anchor = codex.indexOf('<WorkingAnchor')+ expect(wrapperOpen).toBeGreaterThan(-1)+ expect(anchor).toBeGreaterThan(wrapperOpen)+ })++ it('Codex re-engages following on the user instruction, not the answer', () => {+ const codex = read('../CodexView.tsx')+ expect(codex).toContain('lastUserMessage?.id')+ expect(codex).toContain("messages.filter((m) => m.role === 'user')")+ })+})diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 75b206eb..03b3e89b 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -21,6 +21,7 @@ import { useRemoteStore } from '../../stores/remoteStore'import { useModelHealthStore } from '../../stores/modelHealthStore'import { extractMemoriesFromPair } from '../../hooks/useMemory'import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'+import { whenRunsIdle } from '../../lib/run-idle'import { backendCall, isTauri } from '../../api/backend'import { idbStorage } from '../../lib/idbStorage'import type { AIModel } from '../../types/models'@@ -776,8 +777,14 @@ export function AppShell() {// Multiple backends detected → show selection dialog so the user can// change which one is the primary openai-compat provider if they want.- setDetectedBackends(backends)- setShowSelector(true)+ // G25: never mid-run. Detection lands seconds after startup, and when a+ // run was already streaming by then the modal stood over the chat for+ // the rest of a 20 minute agent run (R17c). Wait until every surface+ // (chat, agent, coding) is idle before opening it.+ whenRunsIdle(() => {+ setDetectedBackends(backends)+ setShowSelector(true)+ })})}, [onboardingDone])diff --git a/src/hooks/useAutoScroll.ts b/src/hooks/useAutoScroll.tsindex db41cac4..3412f2ad 100644--- a/src/hooks/useAutoScroll.ts+++ b/src/hooks/useAutoScroll.ts@@ -1,7 +1,25 @@import { useEffect, useRef } from 'react'-export function useAutoScroll(dependency: unknown) {+/**+ * Keep a chat list pinned to its bottom edge while the user is following.+ *+ * G33 (David 2026-08-07): on send the list jumped down "but never all the+ * way". Two mechanisms, both height that appears BELOW the fold without the+ * `dependency` string changing: the Working anchor mounts on a prop flip+ * (isGenerating), and a reasoning model streams into a thinking BLOCK while+ * `lastMessage.content` stays empty, so the trigger never fires and the view+ * parks one anchor-height short of the bottom for the whole thinking phase.+ *+ * So the pin no longer depends on guessing every trigger: a ResizeObserver on+ * the content wrapper re-pins whenever the content grows, as long as the user+ * is following. Scrolling up more than the threshold disengages following+ * (reading history during a run stays possible); `resumeKey` re-engages it —+ * the caller passes the last USER message id, because sending a message is an+ * explicit "take me to the newest", whatever the scroll position was.+ */+export function useAutoScroll(dependency: unknown, resumeKey?: unknown) {const ref = useRef<HTMLDivElement>(null)+ const contentRef = useRef<HTMLDivElement>(null)const shouldScroll = useRef(true)useEffect(() => {@@ -17,11 +35,31 @@ export function useAutoScroll(dependency: unknown) {return () => el.removeEventListener('scroll', handleScroll)}, [])+ // Follow every content-height change, not just the ones a trigger string+ // anticipated. Pinning inside the observer cannot loop: setting scrollTop+ // does not resize the content.+ useEffect(() => {+ const content = contentRef.current+ if (!content || typeof ResizeObserver === 'undefined') return+ const ro = new ResizeObserver(() => {+ const el = ref.current+ if (shouldScroll.current && el) el.scrollTop = el.scrollHeight+ })+ ro.observe(content)+ return () => ro.disconnect()+ }, [])++ useEffect(() => {+ if (resumeKey === undefined) return+ shouldScroll.current = true+ if (ref.current) ref.current.scrollTop = ref.current.scrollHeight+ }, [resumeKey])+useEffect(() => {if (shouldScroll.current && ref.current) {ref.current.scrollTop = ref.current.scrollHeight}}, [dependency])- return ref+ return { ref, contentRef }}diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex eab9984a..40aa011b 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -15,6 +15,7 @@ import { effectiveContextWindow } from "../lib/context-window"import { useAgentChat } from "./useAgentChat"import { parseAgentCommand, parseLoopSpec } from '../lib/agent-commands'import { planResend } from '../lib/resend-plan'+import { isOrphanRun } from '../lib/orphan-run'import { applyGoalCommand } from '../lib/goal-command'import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"@@ -63,6 +64,20 @@ export function useChat() {const agentChat = useAgentChat()const { extractAndSave } = useMemory()+ // G29: a run outlives this hook instance when the chat view unmounts on a+ // view switch, so the conversation's own flag is the only honest source for+ // "is something still in flight here". Without it the composer showed Send+ // next to a running clock and the user had no way to end the run.+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const storeGenerating = useGenerationStore((s) => !!s.generating[activeConversationId ?? ''])+ const orphanRun = isOrphanRun(storeGenerating, isGenerating, agentChat.isAgentRunning)++ /** End a run this instance does not own: the aborter the run registered is+ * a closure over its own controller, so it still reaches it. */+ const stopOrphanRun = useCallback(() => {+ useGenerationStore.getState().abortConversation(useChatStore.getState().activeConversationId)+ }, [])+const sendMessage = useCallback(async (content: string, images?: ImageAttachment[]) => {const { activeModel } = useModelStore.getState()const { settings } = useSettingsStore.getState()@@ -646,8 +661,10 @@ export function useChat() {return {sendMessage,- stopGeneration: agentChat.isAgentRunning ? agentChat.stopAgent : stopGeneration,- isGenerating: isGenerating || agentChat.isAgentRunning,+ stopGeneration: agentChat.isAgentRunning+ ? agentChat.stopAgent+ : orphanRun ? stopOrphanRun : stopGeneration,+ isGenerating: isGenerating || agentChat.isAgentRunning || orphanRun,isLoadingModel,regenerateMessage,editAndResend,diff --git a/src/lib/__tests__/hermes-stream.test.ts b/src/lib/__tests__/hermes-stream.test.tsindex 71274423..8954f307 100644--- a/src/lib/__tests__/hermes-stream.test.ts+++ b/src/lib/__tests__/hermes-stream.test.ts@@ -75,3 +75,97 @@ describe('hermes display filter', () => {expect(shown + f.flush()).toBe('after')})})++// ── G35 (David 2026-08-07): the thought streams in the bounded ThinkingBlock+// window on the hermes path too, never full-height into the bubble. The+// splitter routes <think> spans into the thinking channel per delta; the+// turn-end parse on the full raw text stays authoritative.+import { createThinkStreamSplitter } from '../hermes-stream'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++function splitRun(deltas: string[], startInThink = false) {+ const s = createThinkStreamSplitter({ startInThink })+ let prose = ''+ let thinking = ''+ for (const d of deltas) {+ const r = s.feed(d)+ prose += r.prose+ thinking += r.thinking+ }+ const end = s.flush()+ return { prose: prose + end.prose, thinking: thinking + end.thinking, s }+}++describe('think stream splitter', () => {+ it('routes an explicit think span into the thinking channel', () => {+ const r = splitRun(['<think>I should list files</think>', 'Here we go.'])+ expect(r.thinking).toBe('I should list files')+ expect(r.prose).toBe('Here we go.')+ })++ it('R18b witness: the Qwen3 template pre-opens the thought, only the closer arrives', () => {+ // The live screenshot showed the whole thought streaming full-height and+ // ending in a raw </think>. With startInThink everything before the+ // closer belongs to the thinking channel from the first token.+ const r = splitRun(['So after completing step 5, ', 'the next step is 6. </thi', 'nk>Done with step 6.'], true)+ expect(r.thinking).toBe('So after completing step 5, the next step is 6. ')+ expect(r.prose).toBe('Done with step 6.')+ })++ it('handles tags cut across delta boundaries', () => {+ const r = splitRun(['pre <th', 'ink>hidden', ' thought</t', 'hink> post'])+ expect(r.prose).toBe('pre post')+ expect(r.thinking).toBe('hidden thought')+ })++ it('a stream cut off mid-thought flushes the rest as thinking', () => {+ const r = splitRun(['<think>never closed because the turn died'])+ expect(r.thinking).toBe('never closed because the turn died')+ expect(r.prose).toBe('')+ })++ // ── Negative controls ──────────────────────────────────────────────────++ it('plain prose without tags is untouched, token by token', () => {+ const r = splitRun(['Hello ', 'world, ', 'no thinking here.'])+ expect(r.prose).toBe('Hello world, no thinking here.')+ expect(r.thinking).toBe('')+ })++ it('a lone angle bracket or false prefix stays prose', () => {+ const r = splitRun(['a < b and <thin air'])+ expect(r.prose).toBe('a < b and <thin air')+ expect(r.thinking).toBe('')+ })++ it('without startInThink an orphan closer does not eat the prose', () => {+ // A non-reasoning hermes model never opens a thought; a stray closer in+ // its prose must not reclassify everything before it. The literal tag+ // passes through untouched here — cleaning it up is the job of the+ // end-of-turn parse (splitOrphanCloser), which sees the full text.+ const r = splitRun(['Answer text </think> more text'])+ expect(r.prose).toBe('Answer text </think> more text')+ expect(r.thinking).toBe('')+ })+})++describe('the agent hermes branch is wired through the splitter', () => {+ const src = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../../hooks/useAgentChat.ts'), 'utf8')++ it('display filter output feeds the splitter, gated on keepThinking', () => {+ expect(src).toContain('createThinkStreamSplitter({ startInThink: keepThinking })')+ expect(src).toContain('feedUI(splitter.feed(display.feed(delta)))')+ })++ it('flush order: held prose still passes the splitter before the final flush', () => {+ expect(src).toContain('feedUI(splitter.feed(display.flush()))')+ expect(src).toContain('feedUI(splitter.flush())')+ })++ it('NEGATIVE CONTROL: the authoritative end-of-turn parse still runs on the raw text', () => {+ expect(src).toContain('const rawContent = hermesTurn.content')+ expect(src).toMatch(/turnContent = turnContent\.replace\(\/<think>/)+ })+})diff --git a/src/lib/__tests__/markdown-code.test.ts b/src/lib/__tests__/markdown-code.test.tsnew file mode 100644index 00000000..f3bb114b--- /dev/null+++ b/src/lib/__tests__/markdown-code.test.ts@@ -0,0 +1,85 @@+/**+ * A streaming code block must never print the word "undefined".+ *+ * Captured on the installed 2.6.2 Windows build, 2026-08-06, during a Coding+ * run on the Ollama transport. The model opened a ```json fence and the+ * transcript rendered, for over three minutes:+ *+ * json+ * Copy+ * undefined+ *+ * Read straight off the page over CDP: two <pre> elements, innerText+ * "json\nCopy\nundefined" and "undefined". The cause was `String(children)` in+ * MarkdownRenderer, and react-markdown passes `children: undefined` for a fence+ * with no content yet.+ *+ * This is not an edge case that needs a broken model to reach. Every code block+ * any model streams passes through the empty state on its way to the first+ * character.+ *+ * Run: npx vitest run src/lib/__tests__/markdown-code.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { codeBlockText } from '../markdown-code'++describe('the empty fence that started this', () => {+ it('renders nothing for the shape react-markdown actually sends', () => {+ expect(codeBlockText(undefined)).toBe('')+ })++ it('renders nothing for null', () => {+ expect(codeBlockText(null)).toBe('')+ })++ it('never produces the literal word', () => {+ for (const empty of [undefined, null, '', []]) {+ expect(codeBlockText(empty)).not.toContain('undefined')+ }+ })+})++describe('NEGATIVE CONTROL: real content is untouched', () => {+ it('keeps a normal block exactly as it was', () => {+ expect(codeBlockText('const a = 1\nconst b = 2')).toBe('const a = 1\nconst b = 2')+ })++ it('strips the fence its own trailing newline, and only one', () => {+ expect(codeBlockText('line\n')).toBe('line')+ expect(codeBlockText('line\n\n')).toBe('line\n')+ })++ it('joins the array form react-markdown uses for multi-part children', () => {+ expect(codeBlockText(['const a', ' = 1'])).toBe('const a = 1')+ })++ it('does not swallow content that merely LOOKS empty', () => {+ // A block of whitespace is content the user wrote. Only null/undefined is+ // the absent case.+ expect(codeBlockText(' ')).toBe(' ')+ expect(codeBlockText('0')).toBe('0')+ })++ it('keeps a block whose text genuinely contains the word', () => {+ expect(codeBlockText('let x = undefined')).toBe('let x = undefined')+ })+})++describe('the renderer asks instead of stringifying', () => {+ const src = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../components/chat/MarkdownRenderer.tsx'),+ 'utf8',+ )++ it('calls the helper', () => {+ expect(src).toMatch(/code=\{codeBlockText\(children\)\}/)+ })++ it('the raw String(children) is gone', () => {+ expect(src).not.toMatch(/String\(children\)/)+ })+})diff --git a/src/lib/__tests__/orphan-closer.test.ts b/src/lib/__tests__/orphan-closer.test.tsnew file mode 100644index 00000000..760c3f7b--- /dev/null+++ b/src/lib/__tests__/orphan-closer.test.ts@@ -0,0 +1,82 @@+/**+ * Reasoning that closes a tag it never opened.+ *+ * Ollama's chat templates for the Qwen3 family put the opening `<think>` in the+ * PROMPT. The model therefore never emits one: the wire carries the thought,+ * then `</think>`, then the answer. The char-by-char state machine switches on+ * seeing `<think>`, so it never switches, and with the Thinking toggle ON+ * `finalStripThinkingTags` deliberately leaves canonical markers alone. Result:+ * the raw closer and the entire thought sat in the answer bubble.+ *+ * Captured on the installed 2.6.2 build 2026-08-06, Coding + Ollama + hermes,+ * hf.co/DevQuasar/huihui-ai.Qwen3-4B-abliterated-GGUF, read off the page:+ *+ * "…without stopping. Let's start with the first step. </think>"+ *+ * David has been describing exactly this: a visible think between the steps+ * that is not rendered as thinking.+ *+ * Run: npx vitest run src/lib/__tests__/orphan-closer.test.ts+ */+import { describe, it, expect } from 'vitest'+import { splitOrphanCloser, splitUnclosedThink } from '../thinking-stripper'++const LIVE = "I should work through the plan without stopping. Let's start with the first step. </think>\n\nStep 1 done."++describe('the shape that was measured', () => {+ it('takes the closer out of the answer', () => {+ expect(splitOrphanCloser(LIVE).content).not.toContain('</think>')+ })++ it('keeps the answer that came after it', () => {+ expect(splitOrphanCloser(LIVE).content.trim()).toBe('Step 1 done.')+ })++ it('routes the thought to the thinking side instead of deleting it', () => {+ const { thinking } = splitOrphanCloser(LIVE)+ expect(thinking).toContain("Let's start with the first step")+ expect(thinking).not.toContain('</think>')+ })+})++describe('NEGATIVE CONTROL: a balanced block is left to the paths that own it', () => {+ it('does nothing when an opener precedes the closer', () => {+ const balanced = '<think>reasoning</think>answer'+ expect(splitOrphanCloser(balanced)).toEqual({ content: balanced, thinking: '' })+ })++ it('does nothing to plain prose', () => {+ const plain = 'Just an answer, no tags at all.'+ expect(splitOrphanCloser(plain)).toEqual({ content: plain, thinking: '' })+ })++ it('does nothing to an empty string', () => {+ expect(splitOrphanCloser('')).toEqual({ content: '', thinking: '' })+ })++ it('leaves an UNCLOSED opener alone, that is the other function', () => {+ const unclosed = 'answer<think>still thinking'+ expect(splitOrphanCloser(unclosed)).toEqual({ content: unclosed, thinking: '' })+ expect(splitUnclosedThink(unclosed).thinking).toBe('still thinking')+ })+})++describe('the two halves compose, in the order the loops call them', () => {+ it('a reply that both starts mid-thought AND is cut off mid-thought', () => {+ // Orphan closer first (it is at the front), unclosed opener second.+ const both = 'opening thought</think>the answer<think>a second thought that never closed'+ const first = splitOrphanCloser(both)+ expect(first.thinking).toBe('opening thought')+ const second = splitUnclosedThink(first.content)+ expect(second.thinking).toBe('a second thought that never closed')+ expect(second.content).toBe('the answer')+ })++ it('the first closer wins when the model emits several', () => {+ // Everything before the FIRST closer is the thought. A later stray closer+ // is content the answer paths strip, not a second block to split on.+ const { content, thinking } = splitOrphanCloser('thought</think>answer</think>tail')+ expect(thinking).toBe('thought')+ expect(content).toBe('answer</think>tail')+ })+})diff --git a/src/lib/__tests__/thinking-chronology.test.ts b/src/lib/__tests__/thinking-chronology.test.tsnew file mode 100644index 00000000..fcb461e9--- /dev/null+++ b/src/lib/__tests__/thinking-chronology.test.ts@@ -0,0 +1,86 @@+/**+ * Thoughts sit chronologically between the tool calls (G21-2, David live at+ * R19, 2026-08-07): "Die Denkblase ist immer ganz oben ueber den Tool Calls.+ * Es kommen ja immer mehrere Denkblasen, die muessen zwischen den Tool Calls+ * dann genau da kommen, in der richtigen Reihenfolge." The Agent loop now+ * emits each round's thought as its own phase:'thinking' block before that+ * round's calls, and the one top-of-bubble thinking field is cleared so the+ * same thought never renders twice.+ *+ * Run: npx vitest run src/lib/__tests__/thinking-chronology.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const agent = read('../../hooks/useAgentChat.ts')+const bubble = read('../../components/chat/MessageBubble.tsx')++describe('the Agent loop emits per-round thinking blocks', () => {+ it('a continuing round writes its thought as a block and clears the top field', () => {+ expect(agent).toContain("phase: 'thinking'")+ const emit = agent.indexOf('// G21-2 (David 2026-08-07)')+ expect(emit).toBeGreaterThan(-1)+ const after = agent.slice(emit, emit + 1400)+ expect(after).toContain("thinkingRef.current = ''")+ expect(after).toContain("updateMessageThinking(convId!, assistantMessage.id, '')")+ })++ it('the closing thought after tool activity lands in the sequence too', () => {+ expect(agent).toContain('executedCallKeys.size > 0 && turnThinking.trim()')+ })++ it('NEGATIVE CONTROL: a run with no tool activity keeps the classic bubble', () => {+ // The final turn falls back to the top-of-bubble field, which the+ // tool-intent hint in MessageBubble reads.+ expect(agent).toContain('thinkingRef.current = turnThinking')+ })++ it('NEGATIVE CONTROL: thoughts are only emitted when thinking is enabled', () => {+ expect(agent.match(/settings\.thinkingEnabled === true\) \{\n\s+addBlock/g)?.length).toBeGreaterThanOrEqual(1)+ })+})++describe('the Codex loop, same contract', () => {+ const codex = read('../../hooks/useCodex.ts')++ it('emits the round thought as a block and clears both fields', () => {+ const emit = codex.indexOf('// G21-2 parity with the Agent loop')+ expect(emit).toBeGreaterThan(-1)+ const after = codex.slice(emit, emit + 1200)+ expect(after).toContain("phase: 'thinking'")+ expect(after).toContain("thinkingContent = ''")+ expect(after).toContain("updateMessageThinking(convId!, assistantMsg.id, '')")+ })++ it('gates on tool work: this round calls tools or earlier ones did', () => {+ expect(codex).toContain('toolCalls.length > 0 || anyToolExecuted')+ expect(codex).toContain('anyToolExecuted = true')+ })++ it('CodexView renders the thought blocks chronologically, band notes included', () => {+ const view = read('../../components/chat/CodexView.tsx')+ expect(view).toContain("(b.phase === 'thinking' && b.content.trim())")+ expect(view).toContain("if (block.phase === 'thinking') {")+ expect(view).toContain('<ThinkingBlock thinking={block.content} />')+ })+})++describe('rendering', () => {+ it('MessageBubble lets thinking blocks through the filter and renders the G14-7 bubble', () => {+ expect(bubble).toContain("(b.phase === 'thinking' && b.content.trim())")+ expect(bubble).toContain("block.phase === 'thinking' ? (")+ expect(bubble).toContain('<ThinkingBlock thinking={block.content} />')+ })++ it('a trailing thought renders as its own collapsed bubble before the answer', () => {+ expect(bubble).toContain('<ThinkingBlock key={block.id} thinking={block.content} />')+ })++ it('NEGATIVE CONTROL: the top-level bubble for plain chat turns is untouched', () => {+ expect(bubble).toContain('<ThinkingBlock thinking={message.thinking} streaming=')+ })+})diff --git a/src/lib/__tests__/thinking-preview.test.ts b/src/lib/__tests__/thinking-preview.test.tsnew file mode 100644index 00000000..281e579b--- /dev/null+++ b/src/lib/__tests__/thinking-preview.test.ts@@ -0,0 +1,73 @@+/**+ * Thinking stays folded, streaming shows a bounded window (G14-7, David+ * 2026-08-07): the thinking bubble is collapsed by default everywhere and+ * while the model is reasoning a 3-4 line self-scrolling peek streams inside+ * the collapsed block. Supersedes the 2026-06-04 auto-expand rule.+ *+ * Run: npx vitest run src/lib/__tests__/thinking-preview.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const block = read('../../components/chat/ThinkingBlock.tsx')++describe('collapsed by default, everywhere', () => {+ it('open starts false and never follows the streaming flag', () => {+ expect(block).toContain('useState(false)')+ // the old auto-expand mechanics are gone, not just bypassed+ expect(block).not.toContain('userToggled')+ expect(block).not.toMatch(/open\s*=[^=].*streaming/)+ })++ it('both surfaces still mount it with a streaming flag', () => {+ for (const f of ['MessageBubble', 'CodexView']) {+ const src = read(`../../components/chat/${f}.tsx`)+ expect(src, f).toContain('<ThinkingBlock')+ expect(src, f).toContain('streaming=')+ }+ })+})++describe('the streaming peek', () => {+ it('is bounded to a few lines and clips the rest', () => {+ expect(block).toMatch(/PREVIEW_MAX_H = 'max-h-\[\d+px\]'/)+ const px = Number(block.match(/max-h-\[(\d+)px\]/)![1])+ // 3-4 lines of 0.65rem leading-relaxed text, not a full transcript+ expect(px).toBeGreaterThanOrEqual(48)+ expect(px).toBeLessThanOrEqual(80)+ expect(block).toContain('overflow-hidden pointer-events-none')+ })++ it('self-scrolls to the newest reasoning while streaming and collapsed', () => {+ expect(block).toContain('if (streaming && !open && previewRef.current)')+ expect(block).toContain('previewRef.current.scrollTop = previewRef.current.scrollHeight')+ })++ it('fades the top so old lines scroll out of view, like SlashStepsBlock', () => {+ expect(block).toContain('[mask-image:linear-gradient(to_bottom,transparent,#000_20px)]')+ expect(read('../../components/chat/SlashStepsBlock.tsx')).toContain('mask-image:linear-gradient(to_bottom,transparent')+ })++ it('NEGATIVE CONTROL: no peek once the turn is over or the block is open', () => {+ expect(block).toContain('{!open && streaming && (')+ })++ it('NEGATIVE CONTROL: expanding still yields the full unbounded text', () => {+ const expanded = block.slice(block.indexOf('<AnimatePresence>'))+ expect(expanded).toContain('<MarkdownRenderer content={cleaned} />')+ expect(expanded).not.toContain('max-h-')+ })++ it('NEGATIVE CONTROL: the empty-thought guard survived the rewrite', () => {+ expect(block).toContain('if (!cleaned) return null')+ })++ it('the header shimmers like a live tool name, only while still thinking', () => {+ expect(block).toContain("${streaming ? 'lu-tool-shimmer' : ''}")+ expect(read('../../index.css')).toContain('.lu-tool-shimmer')+ })+})diff --git a/src/lib/__tests__/tool-call-groups.test.ts b/src/lib/__tests__/tool-call-groups.test.tsindex 7955ce69..a3197640 100644--- a/src/lib/__tests__/tool-call-groups.test.ts+++ b/src/lib/__tests__/tool-call-groups.test.ts@@ -28,14 +28,74 @@ describe('groupAgentBlocks', () => {expect((groups[0] as any).calls.map((c: AgentToolCall) => c.toolName)).toEqual(['file_read', 'file_write'])})- it('splits groups at interleaved answers, keeping order', () => {+ // G14-4 (David 2026-08-07): this test used to assert the OPPOSITE, that an+ // interleaved answer splits the band. That split is exactly the stack he+ // was looking at ("die Toolcalls kommen alle untereinander"), because any+ // model that narrates between calls produced band(1), note, band(1). The+ // documented behaviour is now: interior narration is absorbed as a note.+ it('absorbs narration between calls into ONE band, anchored to its call', () => {const t1 = toolBlock(call('file_read', 'completed'))- const ans = answerBlock('found it')+ const ans = answerBlock('Step 1 done, proceeding to step 2.')const t2 = toolBlock(call('file_write', 'completed'))const t3 = toolBlock(call('shell_execute', 'completed'))const groups = groupAgentBlocks([t1, ans, t2, t3])- expect(groups.map(g => g.kind)).toEqual(['tools', 'single', 'tools'])- expect((groups[2] as any).calls).toHaveLength(2)+ expect(groups.map(g => g.kind)).toEqual(['tools'])+ const band = groups[0] as any+ expect(band.calls).toHaveLength(3)+ expect(band.notes).toEqual([{ afterCall: 0, block: ans }])+ })++ it('NEGATIVE CONTROL: the trailing answer stays OUTSIDE the band', () => {+ // The final answer is the model's actual reply. Swallowing it into a+ // collapsed band would hide the one thing David asked to see (G14-2).+ const t1 = toolBlock(call('file_read', 'completed'))+ const t2 = toolBlock(call('file_write', 'completed'))+ const fin = answerBlock('All done, results above.')+ const groups = groupAgentBlocks([t1, t2, fin])+ expect(groups.map(g => g.kind)).toEqual(['tools', 'single'])+ expect((groups[0] as any).notes).toEqual([])+ })++ it('NEGATIVE CONTROL: narration before the FIRST call is not band content', () => {+ const intro = answerBlock('Let me start by reading the file.')+ const t1 = toolBlock(call('file_read', 'completed'))+ const t2 = toolBlock(call('file_write', 'completed'))+ const groups = groupAgentBlocks([intro, t1, t2])+ expect(groups.map(g => g.kind)).toEqual(['single', 'tools'])+ })++ it('G21-2: an interior thinking block is absorbed as a note, band unbroken', () => {+ // Until 2026-08-07 this case asserted the SPLIT ('tools','single','tools').+ // David, live at R19: "die Denkblasen muessen zwischen den Tool Calls dann+ // genau da kommen, in der richtigen Reihenfolge" AND the band must stay+ // one row (G14-4), so round k's thought anchors after round k-1's call.+ const t1 = toolBlock(call('file_read', 'completed'))+ const think: AgentBlock = { id: `th-${++ts}`, phase: 'thinking', content: 'hm', timestamp: ts }+ const t2 = toolBlock(call('file_write', 'completed'))+ const groups = groupAgentBlocks([t1, think, t2])+ expect(groups.map(g => g.kind)).toEqual(['tools'])+ const band = groups[0] as any+ expect(band.notes.map((n: any) => [n.afterCall, n.block.phase])).toEqual([[0, 'thinking']])+ })++ it('G21-2 NEGATIVE CONTROL: a TRAILING thought stays a single after the band', () => {+ const t1 = toolBlock(call('file_read', 'completed'))+ const think: AgentBlock = { id: `th-${++ts}`, phase: 'thinking', content: 'closing thought', timestamp: ts }+ const groups = groupAgentBlocks([t1, think])+ expect(groups.map(g => g.kind)).toEqual(['tools', 'single'])+ expect((groups[1] as any).block.phase).toBe('thinking')+ })++ it('multiple notes between two calls all anchor to the earlier call, in order', () => {+ const t1 = toolBlock(call('file_read', 'completed'))+ const n1 = answerBlock('first note')+ const n2 = answerBlock('second note')+ const t2 = toolBlock(call('file_write', 'completed'))+ const band = groupAgentBlocks([t1, n1, n2, t2])[0] as any+ expect(band.notes.map((n: any) => [n.afterCall, n.block.content])).toEqual([+ [0, 'first note'],+ [0, 'second note'],+ ])})it('keeps a lone tool call as a group of one', () => {@@ -51,6 +111,56 @@ describe('groupAgentBlocks', () => {})})+// ── G34 (David 2026-08-07, R17d) ──────────────────────────────────────────+// "die tools sind nicht im call band alle untereinander." The screenshots+// showed 15+ loose chips with loose Thinking rows between them. Replaying the+// REAL persisted R17d sequence (47 rounds of thinking+call pairs, each pair+// sharing one timestamp, pulled from the app's IndexedDB) proves the grouping+// itself is correct: ONE band, every interior thought absorbed. The loose+// chips were the band EXPANDED BY THE HARNESS: __luTools clicks every+// "N steps" header once a minute to count the trail and left them open, and+// ToolCallBand renders `expanded` above `live`. Fixed in the harness+// (__luTools collapses what it opened); this test pins the app side down.+describe('G34: the real R17d shape groups into one band', () => {+ function r17dSequence(rounds: number): AgentBlock[] {+ // Exactly the persisted shape: per round one thinking block and one call+ // block with the SAME millisecond timestamp (round end writes both).+ const blocks: AgentBlock[] = []+ for (let round = 0; round < rounds; round++) {+ const at = 1_000 + round * 15_000+ blocks.push({ id: `th-${round}`, phase: 'thinking', content: `thought ${round}`, timestamp: at })+ const tc: AgentToolCall = { id: `tc-${round}`, toolName: `tool_${round}`, args: {}, status: 'completed', timestamp: at }+ blocks.push({ id: `bl-${round}`, phase: 'tool_call', content: '', toolCall: tc, toolCalls: [tc], timestamp: at })+ }+ return blocks+ }++ it('47 thinking+call rounds produce one leading thought and ONE band of 47', () => {+ const groups = groupAgentBlocks(r17dSequence(47))+ expect(groups).toHaveLength(2)+ expect(groups[0].kind).toBe('single')+ expect((groups[0] as any).block.phase).toBe('thinking')+ const band = groups[1] as any+ expect(band.kind).toBe('tools')+ expect(band.calls).toHaveLength(47)+ // Every per-round thought except the leading one is an interior note.+ expect(band.notes).toHaveLength(46)+ expect(band.notes.every((n: any) => n.block.phase === 'thinking')).toBe(true)+ })++ it('NEGATIVE CONTROL: a trailing thought stays outside the band (G21-2)', () => {+ const blocks = r17dSequence(3)+ blocks.push({ id: 'th-final', phase: 'thinking', content: 'closing thought', timestamp: 99_000 })+ const groups = groupAgentBlocks(blocks)+ const last = groups[groups.length - 1] as any+ expect(last.kind).toBe('single')+ expect(last.block.id).toBe('th-final')+ const band = groups.find((g) => g.kind === 'tools') as any+ expect(band.calls).toHaveLength(3)+ expect(band.notes).toHaveLength(2)+ })+})+describe('band state helpers', () => {it('is live while any call runs or awaits approval, done otherwise', () => {expect(groupIsLive([call('a', 'completed'), call('b', 'running')])).toBe(true)diff --git a/src/lib/__tests__/transcript-visibility.test.ts b/src/lib/__tests__/transcript-visibility.test.tsnew file mode 100644index 00000000..9ad08c5e--- /dev/null+++ b/src/lib/__tests__/transcript-visibility.test.ts@@ -0,0 +1,92 @@+/**+ * The plan belongs in the PlanBar, not thirty times in the transcript.+ *+ * David, 2026-08-06, having said it before: "Du solltest auch die+ * Planbenachrichtigung und den Planfortschritt nicht im Transfer haben."+ *+ * Captured on the installed 2.6.2 build during a 30 step Coding run, reading+ * the transcript over CDP: plan items were sitting between the steps, e.g.+ * "Generate video with valid sampler and model", because every `todo_write`+ * dropped a card carrying the whole list. An agent that revises its plan each+ * step writes that list thirty times.+ *+ * Run: npx vitest run src/lib/__tests__/transcript-visibility.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { hiddenFromTranscript } from '../transcript-visibility'++describe('todo_write is owned by the PlanBar', () => {+ it('a completed plan write leaves no card behind', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'completed' })).toBe(true)+ })++ it('and neither does one still running, so no card flashes up and vanishes', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'running' })).toBe(true)+ })++ it('or one served from the in-turn cache', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'cached' })).toBe(true)+ })+})++describe('NEGATIVE CONTROL: it stays visible when the user needs to know', () => {+ // The whole point of hiding it is that the PlanBar says the same thing+ // better. When the write FAILED the PlanBar says nothing at all, so the card+ // is the only evidence the plan was never recorded.+ it('a failed plan write is still shown', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'failed' })).toBe(false)+ })++ it('a rejected one is still shown', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'rejected' })).toBe(false)+ })++ it('one waiting for approval is still shown, or it could never be approved', () => {+ expect(hiddenFromTranscript({ toolName: 'todo_write', status: 'pending_approval' })).toBe(false)+ })+})++describe('NEGATIVE CONTROL: nothing else is touched', () => {+ it('every other tool renders in every state', () => {+ const others = ['file_read', 'shell_execute', 'git_commit', 'web_search', 'image_generate']+ const states = ['completed', 'running', 'cached', 'failed', 'rejected', 'pending_approval']+ for (const toolName of others) {+ for (const status of states) {+ expect(hiddenFromTranscript({ toolName, status })).toBe(false)+ }+ }+ })++ it('an unknown tool name is never hidden by accident', () => {+ expect(hiddenFromTranscript({ toolName: 'some_mcp_server__thing', status: 'completed' })).toBe(false)+ })++ it('a tool whose name merely CONTAINS todo_write is not hidden', () => {+ expect(hiddenFromTranscript({ toolName: 'not_todo_write', status: 'completed' })).toBe(false)+ expect(hiddenFromTranscript({ toolName: 'todo_write_v2', status: 'completed' })).toBe(false)+ })+})++describe('the gate runs before the block mounts', () => {+ const src = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../components/chat/ToolCallBlock.tsx'),+ 'utf8',+ )++ it('ToolCallBlock asks the rule', () => {+ expect(src).toMatch(/hiddenFromTranscript\(props\.toolCall\)/)+ })++ it('and the check sits outside the implementation, so no hook order changes', () => {+ // An early return inside ToolCallBlockImpl would have to come after its+ // useState/useEffect calls, which is exactly the shape that rots later.+ const gate = src.indexOf('hiddenFromTranscript(props.toolCall)')+ const impl = src.indexOf('function ToolCallBlockImpl')+ expect(gate).toBeGreaterThan(-1)+ expect(gate).toBeLessThan(impl)+ })+})diff --git a/src/lib/__tests__/unclosed-think.test.ts b/src/lib/__tests__/unclosed-think.test.tsnew file mode 100644index 00000000..91e460b1--- /dev/null+++ b/src/lib/__tests__/unclosed-think.test.ts@@ -0,0 +1,100 @@+/**+ * A `<think>` without its closer must never render as the answer.+ *+ * Found on the installed 2.6.2 Windows build, Coding surface, Ollama with the+ * hermes schema: stopping a run mid-turn left the bubble reading+ * "<think> Okay, let's see. The user is working through a plan to" as if that+ * were the model's reply.+ *+ * The asymmetry is what made it survive. `finalStripThinkingTags` removes an+ * orphan opener only when `keepCanonicalThink` is false, so the bug appears+ * exactly when the user has Thinking ON, which is the default for a model that+ * can think. And the fix cannot simply be "strip it too": with thinking ON that+ * text is real reasoning the user asked to see, so it belongs in the thinking+ * panel rather than in the bin.+ *+ * Run: npx vitest run src/lib/__tests__/unclosed-think.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { splitUnclosedThink, finalStripThinkingTags } from '../thinking-stripper'++const read = (p: string) =>+ readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), 'utf8')++describe('splitUnclosedThink', () => {+ it('pulls a dangling opener out of the answer', () => {+ const cut = "<think> Okay, let's see. The user is working through a plan to"+ const r = splitUnclosedThink(cut)+ expect(r.content).toBe('')+ expect(r.thinking).toBe(" Okay, let's see. The user is working through a plan to")+ })++ it('keeps the answer that came before the dangling opener', () => {+ const r = splitUnclosedThink('Here is step 4.\n\n<think> now I need to')+ expect(r.content).toBe('Here is step 4.\n\n')+ expect(r.thinking).toBe(' now I need to')+ })++ it('leaves a balanced block alone, that is the other regex job', () => {+ const s = '<think>reasoning</think>the answer'+ expect(splitUnclosedThink(s)).toEqual({ content: s, thinking: '' })+ })++ it('leaves content with no think tag untouched', () => {+ expect(splitUnclosedThink('plain answer')).toEqual({ content: 'plain answer', thinking: '' })+ })++ it('only the LAST opener counts, an earlier balanced one is not re-cut', () => {+ const s = '<think>first</think>answer<think>cut off here'+ const r = splitUnclosedThink(s)+ expect(r.content).toBe('<think>first</think>answer')+ expect(r.thinking).toBe('cut off here')+ })++ it('survives the empty string', () => {+ expect(splitUnclosedThink('')).toEqual({ content: '', thinking: '' })+ })+})++describe('the hole this closes', () => {+ it('NEGATIVE CONTROL: finalStripThinkingTags alone still leaks it with thinking ON', () => {+ const cut = "<think> Okay, let's see"+ // This is the old behaviour and it must stay this way: the function is+ // documented to leave canonical markers to the state machine.+ expect(finalStripThinkingTags(cut, true)).toContain('<think>')+ // With thinking OFF it was never a problem, which is why nobody saw it.+ expect(finalStripThinkingTags(cut, false)).not.toContain('<think>')+ })++ it('and the two together leave nothing behind', () => {+ const cut = "answer so far<think> Okay, let's see"+ const split = splitUnclosedThink(cut)+ expect(finalStripThinkingTags(split.content, true)).toBe('answer so far')+ })+})++describe('both agent loops call it', () => {+ it('the coding surface routes the orphan into the thinking panel', () => {+ const src = read('../../hooks/useCodex.ts')+ expect(src).toMatch(/splitUnclosedThink\(turnContent\)/)+ expect(src).toMatch(/updateMessageThinking\(convId!, assistantMsg\.id, thinkingContent\)/)+ })++ it('the agent surface does the same', () => {+ const src = read('../../hooks/useAgentChat.ts')+ expect(src).toMatch(/splitUnclosedThink\(turnContent\)/)+ expect(src).toMatch(/orphanThink\.thinking/)+ })++ it('and both do it BEFORE the final strip, or the strip would hide it', () => {+ for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {+ const src = read(f)+ expect(src.indexOf('splitUnclosedThink(turnContent)'))+ .toBeLessThan(src.indexOf('finalStripThinkingTags(turnContent, keepThinking)'))+ }+ })+})diff --git a/src/lib/__tests__/working-anchor.test.ts b/src/lib/__tests__/working-anchor.test.tsnew file mode 100644index 00000000..11fcc5e1--- /dev/null+++ b/src/lib/__tests__/working-anchor.test.ts@@ -0,0 +1,74 @@+/**+ * One run, one anchor (G14-6, David 2026-08-07): "anstatt wir diese drei+ * langweiligen Punkte haben … möchte ich Working mit derselben Animation, die+ * wir in unseren Toolcalls haben, außerdem daneben die Zeit … die soll immer+ * der Anker sein für alles, ganz unten, bis der Agent fertig ist. Dann kannst+ * Du die drei Doppelpunkte wegnehmen, überall in Chat, Agent, Code, überall."+ *+ * Run: npx vitest run src/lib/__tests__/working-anchor.test.ts+ */+import { describe, it, expect } from 'vitest'+import { existsSync, readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { formatElapsed } from '../format-elapsed'++const here = dirname(fileURLToPath(import.meta.url))+const p = (rel: string) => resolve(here, rel)+const read = (rel: string) => readFileSync(p(rel), 'utf8')++describe('the clock next to the word', () => {+ it('formats like the run header, minutes only when there are minutes', () => {+ expect(formatElapsed(0)).toBe('0s')+ expect(formatElapsed(47)).toBe('47s')+ expect(formatElapsed(65)).toBe('1m 05s')+ expect(formatElapsed(723)).toBe('12m 03s')+ })++ it('never renders a negative clock', () => {+ expect(formatElapsed(-5)).toBe('0s')+ })+})++describe('the dots are gone, everywhere', () => {+ it('TypingIndicator no longer exists', () => {+ expect(existsSync(p('../../components/chat/TypingIndicator.tsx'))).toBe(false)+ })++ it('the floating bottom-right counter no longer exists', () => {+ expect(existsSync(p('../../components/chat/RealtimeCounter.tsx'))).toBe(false)+ })++ it('no chat surface imports either of them', () => {+ for (const f of ['MessageList', 'CodexView', 'ChatView']) {+ const src = read(`../../components/chat/${f}.tsx`)+ expect(src, f).not.toContain('TypingIndicator')+ expect(src, f).not.toContain('RealtimeCounter')+ }+ })+})++describe('the anchor is wired on every surface', () => {+ const anchor = read('../../components/chat/WorkingAnchor.tsx')++ it('carries the SAME shimmer class as a live tool name', () => {+ expect(anchor).toContain('lu-tool-shimmer')+ // and that class really is the tool shimmer, not a lookalike+ expect(read('../../index.css')).toContain('.lu-tool-shimmer')+ })++ it('MessageList (Chat + Agent) renders it while the run lives', () => {+ expect(read('../../components/chat/MessageList.tsx')).toContain('<WorkingAnchor')+ })++ it('CodexView (Code) renders it and names an approval wait for what it is', () => {+ const src = read('../../components/chat/CodexView.tsx')+ expect(src).toContain('<WorkingAnchor')+ expect(src).toContain("'Waiting for your approval'")+ })++ it('NEGATIVE CONTROL: the anchor renders nothing once the run is over', () => {+ expect(anchor).toContain('if (!isRunning) return null')+ })+})diff --git a/src/lib/format-elapsed.ts b/src/lib/format-elapsed.tsnew file mode 100644index 00000000..caab3454--- /dev/null+++ b/src/lib/format-elapsed.ts@@ -0,0 +1,8 @@+/** "47s", "1m 05s", "12m 03s". The run anchor's clock (G14-6). */+export function formatElapsed(totalSeconds: number): string {+ const s = Math.max(0, Math.floor(totalSeconds))+ const mins = Math.floor(s / 60)+ const secs = s % 60+ if (mins === 0) return `${secs}s`+ return `${mins}m ${String(secs).padStart(2, '0')}s`+}diff --git a/src/lib/hermes-stream.ts b/src/lib/hermes-stream.tsindex 6b0e5611..6a46e8b1 100644--- a/src/lib/hermes-stream.ts+++ b/src/lib/hermes-stream.ts@@ -89,3 +89,81 @@ export function createHermesDisplayFilter(): HermesDisplayFilter {},}}++const THINK_OPEN = '<think>'+const THINK_CLOSE = '</think>'++export interface ThinkStreamSplitter {+ /** Feed one display-safe delta; returns what goes where RIGHT NOW. */+ feed(delta: string): { prose: string; thinking: string }+ /** Stream over: classify whatever is still held back. */+ flush(): { prose: string; thinking: string }+ inThink(): boolean+}++/**+ * Route `<think>` spans out of a live stream and into the thinking channel+ * (G35, David 2026-08-07: the thought must stream inside the same bounded+ * 3-line window everywhere, never full-height into the bubble).+ *+ * `startInThink` exists because the Qwen3 chat templates put the OPENING+ * `<think>` into the prompt: the reply begins mid-thought and only ever sends+ * the closer, so a splitter that waits for an opener would classify the whole+ * thought as prose. Callers pass their keep-thinking gate here. If the model+ * then answers without any think tags after all, everything streamed into the+ * thinking channel and the authoritative end-of-turn parse (which reruns on+ * the FULL raw text) puts it back into content: the UI self-heals at turn+ * end, the failure mode is cosmetic and transient.+ *+ * Like the tool-call filter this is UI-only: callers still accumulate the+ * full raw text and the turn-end parse decides what counts.+ */+export function createThinkStreamSplitter(opts?: { startInThink?: boolean }): ThinkStreamSplitter {+ let pending = ''+ let inThink = opts?.startInThink === true++ return {+ feed(delta: string): { prose: string; thinking: string } {+ pending += delta+ let prose = ''+ let thinking = ''+ while (true) {+ if (inThink) {+ const close = pending.indexOf(THINK_CLOSE)+ if (close === -1) {+ const keep = cutTagSuffix(pending, THINK_CLOSE)+ thinking += pending.slice(0, pending.length - keep)+ pending = keep > 0 ? pending.slice(pending.length - keep) : ''+ return { prose, thinking }+ }+ thinking += pending.slice(0, close)+ pending = pending.slice(close + THINK_CLOSE.length)+ inThink = false+ continue+ }+ const open = pending.indexOf(THINK_OPEN)+ if (open !== -1) {+ prose += pending.slice(0, open)+ pending = pending.slice(open + THINK_OPEN.length)+ inThink = true+ continue+ }+ const hold = cutTagSuffix(pending, THINK_OPEN)+ prose += pending.slice(0, pending.length - hold)+ pending = pending.slice(pending.length - hold)+ return { prose, thinking }+ }+ },++ flush(): { prose: string; thinking: string } {+ const res = inThink ? { prose: '', thinking: pending } : { prose: pending, thinking: '' }+ pending = ''+ inThink = false+ return res+ },++ inThink(): boolean {+ return inThink+ },+ }+}diff --git a/src/lib/markdown-code.ts b/src/lib/markdown-code.tsnew file mode 100644index 00000000..076ba58d--- /dev/null+++ b/src/lib/markdown-code.ts@@ -0,0 +1,28 @@+/**+ * What a fenced code block actually renders as text.+ *+ * Leaf module so it can be tested without pulling react-markdown and the katex+ * stylesheet into a `node` test environment.+ *+ * The reason it exists: react-markdown hands the `code` component+ * `children: undefined` for a fence with nothing inside it, and the renderer+ * used to do `String(children)`, which is the string "undefined". A user sees+ * the word printed in a code box.+ *+ * That is not a rare shape. It is EVERY streamed code block, for as long as it+ * takes the opening fence to be followed by a first character. Measured on the+ * installed build 2026-08-06 during a Coding run: the model opened a ```json+ * fence, and the transcript showed+ *+ * json+ * Copy+ * undefined+ *+ * for over three minutes while the rest of the answer was still arriving.+ */+export function codeBlockText(children: unknown): string {+ if (children == null) return ''+ const text = Array.isArray(children) ? children.join('') : String(children)+ // One trailing newline is the fence's own, not content.+ return text.replace(/\n$/, '')+}diff --git a/src/lib/thinking-stripper.ts b/src/lib/thinking-stripper.tsindex 39bb2305..81a2026e 100644--- a/src/lib/thinking-stripper.ts+++ b/src/lib/thinking-stripper.ts@@ -90,6 +90,68 @@ export function stripNonCanonicalTags(content: string): string {* stream finishes. Catches any orphan closing `</think>` that leaked through* (e.g. provider restarted mid-stream, first `<think>` lost).*/+/**+ * Split off a `<think>` that never got its closer.+ *+ * A turn can end mid-thought: the user pressed Stop, the stream died, or the+ * model walked into the context wall. The balanced `<think>…</think>` regex in+ * the agent loops cannot see that, and `finalStripThinkingTags` deliberately+ * leaves canonical markers alone while the Thinking toggle is ON — so the raw+ * opener plus the entire reasoning text landed in the answer bubble, but only+ * with thinking ON. Found on the installed 2.6.2 build, Coding + Ollama ++ * hermes, after stopping a run mid-turn.+ *+ * Returns the answer without the dangling block, and the reasoning that was in+ * it, so the caller can route it into the thinking panel instead of dropping+ * text the model actually produced.+ */+export function splitUnclosedThink(content: string): { content: string; thinking: string } {+ if (!content) return { content, thinking: '' }+ const open = content.lastIndexOf('<think>')+ if (open === -1) return { content, thinking: '' }+ // A closer after the last opener means the block is balanced, not orphaned.+ if (content.indexOf('</think>', open) !== -1) return { content, thinking: '' }+ return {+ content: content.slice(0, open),+ thinking: content.slice(open + '<think>'.length),+ }+}++/**+ * Split off reasoning that arrived with a closer but no opener.+ *+ * The mirror image of `splitUnclosedThink`, and the commoner of the two. Ollama+ * chat templates for the Qwen3 family put the opening `<think>` in the PROMPT,+ * so the model never emits one: what comes back over the wire is the reasoning+ * text, then `</think>`, then the answer. The char-by-char state machine keys+ * on seeing `<think>`, so it never switches, and everything runs through as+ * ordinary content. With the Thinking toggle ON, `finalStripThinkingTags`+ * deliberately leaves canonical markers alone, and the raw `</think>` lands in+ * the answer bubble with the whole thought in front of it.+ *+ * Measured on the installed 2.6.2 build 2026-08-06, Coding + Ollama + hermes,+ * hf.co/DevQuasar/huihui-ai.Qwen3-4B-abliterated-GGUF. Read off the page:+ * "…without stopping. Let's start with the first step. </think>". David has+ * been reporting exactly this: a visible think between the steps that is not+ * styled as thinking.+ *+ * Returns the answer after the closer, and the reasoning that preceded it, so+ * the caller routes it to the thinking panel rather than deleting text the+ * model produced.+ */+export function splitOrphanCloser(content: string): { content: string; thinking: string } {+ if (!content) return { content, thinking: '' }+ const close = content.indexOf('</think>')+ if (close === -1) return { content, thinking: '' }+ // An opener anywhere before it means the block is balanced, not orphaned,+ // and the existing paths own it.+ if (content.lastIndexOf('<think>', close) !== -1) return { content, thinking: '' }+ return {+ content: content.slice(close + '</think>'.length),+ thinking: content.slice(0, close),+ }+}+export function finalStripThinkingTags(content: string, keepCanonicalThink = false): string {if (!content) return contentlet out = stripAllThinkingTags(content)diff --git a/src/lib/tool-call-groups.ts b/src/lib/tool-call-groups.tsindex d139e993..d6e35dd5 100644--- a/src/lib/tool-call-groups.ts+++ b/src/lib/tool-call-groups.ts@@ -2,35 +2,84 @@* Grouping for the tool-call band (David 2026-07-31): consecutive tool_call* blocks in a message render as ONE band that morphs from tool to tool while* running and collapses to an expandable "N steps" row when done, instead of- * stacking a chip per call and flooding the chat. Any non-tool block- * (reflection, answer) ends the current run, so interleaved commentary keeps- * its position in the transcript.+ * stacking a chip per call and flooding the chat.+ *+ * G14-4 (David 2026-08-07): narration BETWEEN tool calls no longer ends the+ * band. Any model that talks between calls ("Step 3 done, proceeding…", and+ * gpt-oss does it on every turn) used to shatter the run into band(1), note,+ * band(1), note, which is exactly the stack this module exists to prevent.+ * Interior reflection/answer blocks are now absorbed into the band as `notes`,+ * anchored after the call they followed, and render inside the expanded view.+ * A note is interior only when another tool call comes LATER; the message's+ * trailing answer always stands alone, because that is the model's actual+ * reply and must never disappear into a collapse.+ *+ * G21-2 (David 2026-08-07): per-round thinking blocks are interior notes too.+ * "Die Denkblasen muessen zwischen den Tool Calls dann genau da kommen, in der+ * richtigen Reihenfolge." Round k's thought sits anchored after the last call+ * of round k-1, inside the band, rendered as its own collapsed ThinkingBlock+ * (the G14-7 bubble). A TRAILING thought stays a single, in chronological+ * position before the final answer.** Pure helpers, shared by MessageBubble (Agent) and CodexView (Code tab).*/import type { AgentBlock, AgentToolCall } from '../types/agent-mode'+export interface BandNote {+ /** Index into `calls` of the call this note followed. */+ afterCall: number+ block: AgentBlock+}+export type AgentBlockGroup =- | { kind: 'tools'; blocks: AgentBlock[]; calls: AgentToolCall[] }+ | { kind: 'tools'; blocks: AgentBlock[]; calls: AgentToolCall[]; notes: BandNote[] }| { kind: 'single'; block: AgentBlock }+const INTERIOR_NOTE_PHASES = new Set<AgentBlock['phase']>(['reflection', 'answer', 'thinking'])+/** Blocks must already be filtered + timestamp-sorted by the caller. */export function groupAgentBlocks(blocks: AgentBlock[]): AgentBlockGroup[] {+ let lastCallAt = -1+ for (let i = 0; i < blocks.length; i++) {+ if (blocks[i].phase === 'tool_call' && blocks[i].toolCall) lastCallAt = i+ }+const groups: AgentBlockGroup[] = []- for (const block of blocks) {+ // Notes seen since the last call, held back until we know whether the band+ // continues (absorbed) or ends here (rendered as singles, in order).+ let held: AgentBlock[] = []+ const flushHeld = () => {+ for (const b of held) groups.push({ kind: 'single', block: b })+ held = []+ }++ for (let i = 0; i < blocks.length; i++) {+ const block = blocks[i]+ const last = groups[groups.length - 1]if (block.phase === 'tool_call' && block.toolCall) {- const last = groups[groups.length - 1]if (last && last.kind === 'tools') {+ for (const b of held) last.notes.push({ afterCall: last.calls.length - 1, block: b })+ held = []last.blocks.push(block)last.calls.push(block.toolCall)} else {- groups.push({ kind: 'tools', blocks: [block], calls: [block.toolCall] })+ flushHeld()+ groups.push({ kind: 'tools', blocks: [block], calls: [block.toolCall], notes: [] })}+ } else if (+ INTERIOR_NOTE_PHASES.has(block.phase) &&+ i < lastCallAt &&+ last &&+ last.kind === 'tools'+ ) {+ held.push(block)} else {+ flushHeld()groups.push({ kind: 'single', block })}}+ flushHeld()return groups}diff --git a/src/lib/transcript-visibility.ts b/src/lib/transcript-visibility.tsnew file mode 100644index 00000000..e305498b--- /dev/null+++ b/src/lib/transcript-visibility.ts@@ -0,0 +1,35 @@+/**+ * Which tool calls do NOT belong in the transcript.+ *+ * Leaf module so the rule is testable without the icon set, framer-motion and+ * the Tauri backend that ToolCallBlock pulls in.+ *+ * David has now said this several times, most recently 2026-08-06: "Du solltest+ * auch die Planbenachrichtigung und den Planfortschritt nicht im Transfer+ * haben."+ *+ * `todo_write` is the agent maintaining its own plan, and the plan already has+ * a home: PlanBar, pinned above the composer, always current, one glance. Every+ * card the tool ALSO drops into the transcript repeats that list in full.+ * Captured on the installed build during a 30 step run: the plan text was+ * sitting in the transcript between the steps, and on a run that revises its+ * list every step that is thirty copies of the same thing pushing the actual+ * work off screen.+ *+ * Hidden only when it WORKED. A failed, rejected or not-yet-approved call still+ * renders, because then the card is the only place the user could learn that+ * the agent's plan never got written.+ */+export interface TranscriptToolCall {+ toolName: string+ status: string+}++const OWNED_BY_ANOTHER_SURFACE: Record<string, true> = {+ todo_write: true, // PlanBar+}++export function hiddenFromTranscript(toolCall: TranscriptToolCall): boolean {+ if (!OWNED_BY_ANOTHER_SURFACE[toolCall.toolName]) return false+ return toolCall.status === 'completed' || toolCall.status === 'cached' || toolCall.status === 'running'+}