Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix: v2.4.2 regression fixes from Agent Overhaul v24

PurpleDoubleD47f41caceee1
diff --git a/package.json b/package.json
index b1bb16e8..14796d3a 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "locally-uncensored",
- "version": "2.4.0",
+ "version": "2.4.2",
"private": false,
"description": "Generate anything — text, images, video. Locally. Uncensored.",
"license": "AGPL-3.0",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f0a3376d..cb70d0ea 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2508,7 +2508,7 @@ dependencies = [
[[package]]
name = "locally-uncensored"
-version = "2.3.3"
+version = "2.4.2"
dependencies = [
"axum",
"base64 0.22.1",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 57ea743a..764cc98a 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "locally-uncensored"
-version = "2.4.0"
+version = "2.4.2"
description = "Private, local AI chat & image/video generation"
authors = ["purpledoubled"]
edition = "2021"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index f4def254..bc550d6a 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
"productName": "Locally Uncensored",
- "version": "2.4.0",
+ "version": "2.4.2",
"identifier": "com.purpledoubled.locally-uncensored",
"build": {
"beforeBuildCommand": "npm run build",
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 773bf394..f007b854 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -74,29 +74,53 @@ export async function localFetch(
}
/**
- * Streaming fetch for localhost — returns raw bytes in Tauri, normal Response in dev.
+ * Streaming fetch for localhost — real token-by-token streaming via direct
+ * fetch when CORS permits (Ollama on 11434 has CORS open), Rust proxy as
+ * fallback (collects all bytes first — no real streaming but keeps things
+ * working if direct fetch is blocked).
+ *
* Used for Ollama streaming endpoints (pull, chat).
*/
export async function localFetchStream(
url: string,
options?: { method?: string; body?: string; signal?: AbortSignal }
): Promise<Response> {
- if (!isTauri()) {
- return fetch(url, {
- method: options?.method || "GET",
- body: options?.body,
- headers: options?.body ? { "Content-Type": "application/json" } : undefined,
+ const method = options?.method || "GET";
+ const body = options?.body;
+ const headers = body ? { "Content-Type": "application/json" } : undefined;
+
+ // Direct fetch first — Ollama has CORS open on localhost, so this gives
+ // us true chunked streaming. Works in both dev mode and Tauri .exe.
+ try {
+ const res = await fetch(url, {
+ method,
+ headers,
+ body,
signal: options?.signal,
});
+ // Guard: some Tauri WebView setups still reject — if the Response is
+ // malformed (no body at all), fall through to the proxy.
+ if (res.body || res.ok || res.status >= 400) {
+ return res;
+ }
+ } catch (directErr) {
+ if (options?.signal?.aborted) throw directErr;
+ console.warn('[localFetchStream] Direct fetch failed, trying Rust proxy:', String(directErr));
+ }
+
+ // Fallback in Tauri: Rust proxy collects all bytes (loses streaming).
+ if (!isTauri()) {
+ // Re-throw the original direct-fetch error if we are not in Tauri,
+ // since there is no proxy to fall back to.
+ return new Response(JSON.stringify({ error: 'Network error' }), { status: 500 });
}
- // In Tauri: get all bytes at once through Rust proxy (no true streaming, but works)
const invoke = await getInvoke();
try {
const bytes = await invoke("proxy_localhost_stream", {
url,
- method: options?.method || "GET",
- body: options?.body || null,
+ method,
+ body: body || null,
}) as number[];
const uint8 = new Uint8Array(bytes);
diff --git a/src/components/chat/ApprovalDialog.tsx b/src/components/chat/ApprovalDialog.tsx
index 945d82d7..4c24a363 100644
--- a/src/components/chat/ApprovalDialog.tsx
+++ b/src/components/chat/ApprovalDialog.tsx
@@ -1,5 +1,6 @@
-import { motion } from 'framer-motion'
-import { ShieldAlert } from 'lucide-react'
+import { motion, AnimatePresence } from 'framer-motion'
+import { ShieldAlert, Check, X } from 'lucide-react'
+import { useEffect } from 'react'
import type { AgentToolCall } from '../../types/agent-mode'
import { ToolCallBlock } from './ToolCallBlock'
@@ -9,25 +10,82 @@ interface Props {
onReject: () => void
}
+/**
+ * Agent tool-call approval prompt. Before v2.4 this was a small inline
+ * strip above the ChatInput and users missed it. It's now a centred modal
+ * with a dimmed backdrop so the approval gate is impossible to overlook.
+ *
+ * Keyboard shortcuts: Enter → approve, Escape → reject.
+ */
export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ onApprove()
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ onReject()
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [onApprove, onReject])
+
return (
- <motion.div
- className="px-3 pb-2"
- initial={{ opacity: 0, y: 6 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.2 }}
- >
- <div className="flex items-center gap-1.5 mb-1">
- <ShieldAlert size={11} className="text-amber-400" />
- <span className="text-[0.6rem] text-amber-400/80 font-medium">
- Approval required
- </span>
- </div>
- <ToolCallBlock
- toolCall={toolCall}
- onApprove={onApprove}
- onReject={onReject}
- />
- </motion.div>
+ <AnimatePresence>
+ <motion.div
+ key="backdrop"
+ className="fixed inset-0 z-[200] bg-black/50 backdrop-blur-sm flex items-center justify-center p-6"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ onClick={onReject}
+ >
+ <motion.div
+ key="dialog"
+ className="w-full max-w-[480px] rounded-xl bg-white dark:bg-[#1a1a1a] border border-amber-500/30 shadow-2xl overflow-hidden"
+ initial={{ opacity: 0, scale: 0.95, y: 10 }}
+ animate={{ opacity: 1, scale: 1, y: 0 }}
+ exit={{ opacity: 0, scale: 0.95, y: 10 }}
+ transition={{ duration: 0.18, ease: 'easeOut' }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Header */}
+ <div className="flex items-center gap-2 px-4 py-2.5 bg-amber-500/10 border-b border-amber-500/20">
+ <ShieldAlert size={14} className="text-amber-400" />
+ <span className="text-[0.75rem] text-amber-400 font-semibold">
+ Tool approval required
+ </span>
+ <span className="ml-auto text-[0.5rem] text-amber-400/50 font-mono">
+ Enter ✓ · Esc ✕
+ </span>
+ </div>
+
+ {/* Tool details */}
+ <div className="px-4 py-3">
+ <ToolCallBlock toolCall={toolCall} />
+ </div>
+
+ {/* Prominent action row */}
+ <div className="flex items-center gap-2 px-4 pb-3">
+ <button
+ onClick={onApprove}
+ autoFocus
+ className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md bg-green-500/15 border border-green-500/40 text-green-400 hover:bg-green-500/25 hover:border-green-500/60 transition-all text-[0.7rem] font-medium"
+ >
+ <Check size={12} /> Approve
+ </button>
+ <button
+ onClick={onReject}
+ className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md bg-red-500/10 border border-red-500/30 text-red-400 hover:bg-red-500/20 hover:border-red-500/50 transition-all text-[0.7rem] font-medium"
+ >
+ <X size={12} /> Reject
+ </button>
+ </div>
+ </motion.div>
+ </motion.div>
+ </AnimatePresence>
)
}
diff --git a/src/components/chat/FileTree.tsx b/src/components/chat/FileTree.tsx
index ed32e29c..b03b2000 100644
--- a/src/components/chat/FileTree.tsx
+++ b/src/components/chat/FileTree.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useRef } from 'react'
import { FolderOpen, Folder, FileText, ArrowLeft, RefreshCw } from 'lucide-react'
import { useCodexStore } from '../../stores/codexStore'
import { toolRegistry } from '../../api/mcp'
@@ -8,6 +8,7 @@ import type { FileTreeNode } from '../../types/codex'
export function FileTree() {
const workingDirectory = useCodexStore((s) => s.workingDirectory)
const fileTree = useCodexStore((s) => s.fileTree)
+ const fileTreeVersion = useCodexStore((s) => s.fileTreeVersion)
const setFileTree = useCodexStore((s) => s.setFileTree)
const setWorkingDirectory = useCodexStore((s) => s.setWorkingDirectory)
const [loading, setLoading] = useState(false)
@@ -73,8 +74,22 @@ export function FileTree() {
if (workingDirectory && fileTree.length === 0) {
loadDirectory(workingDirectory)
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // Auto-refresh when Codex writes / executes in the working directory.
+ // fileTreeVersion is bumped by codexStore.addEvent for file_change /
+ // terminal_output events. Skip the first mount (already handled above).
+ const isFirstRender = useRef(true)
+ useEffect(() => {
+ if (isFirstRender.current) {
+ isFirstRender.current = false
+ return
+ }
+ if (workingDirectory) loadDirectory(workingDirectory)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fileTreeVersion])
+
return (
<div className="h-full flex flex-col border-l border-gray-200 dark:border-white/[0.04] bg-gray-50 dark:bg-white/[0.01]">
{/* Directory picker — click to open native dialog */}
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index cddb5d38..f71b4fc1 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { ChevronDown, Search, Globe, FileText, FileEdit, Terminal, Image, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch } from 'lucide-react'
+import { ChevronDown, Search, Globe, FileText, FileEdit, Terminal, Image, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, Database } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
interface Props {
@@ -31,6 +31,8 @@ const STATUS_ICONS = {
completed: Check,
failed: AlertCircle,
rejected: X,
+ // Phase 6 (v2.4.0): cached result from in-turn cache, no re-execution.
+ cached: Database,
}
export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6d270d2c..2ca11316 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -32,6 +32,7 @@ import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '.
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
+import { finalStripThinkingTags } from '../lib/thinking-stripper'
// ── Standalone memory extraction (usable outside React hooks) ──
@@ -60,8 +61,15 @@ async function extractMemories(userMsg: string, assistantMsg: string, conversati
}
// ── Approval promise management ───────────────────────────────
-
-interface ApprovalResolver {
+//
+// Phase 5 introduced parallel tool execution via executeParallel — which
+// means multiple tools can request approval in the same batch. A single
+// `approvalRef` slot would get OVERWRITTEN by the second caller,
+// deadlocking the first. We keep a FIFO queue instead: the UI shows the
+// head of the queue, and approve/reject pops it so the next one surfaces.
+
+interface ApprovalEntry {
+ toolCall: AgentToolCall
resolve: (approved: boolean) => void
}
@@ -72,7 +80,7 @@ export function useAgentChat() {
const [pendingApproval, setPendingApproval] = useState<AgentToolCall | null>(null)
const abortRef = useRef<AbortController | null>(null)
- const approvalRef = useRef<ApprovalResolver | null>(null)
+ const approvalQueueRef = useRef<ApprovalEntry[]>([])
const contentRef = useRef('')
const thinkingRef = useRef('')
const blocksRef = useRef<AgentBlock[]>([])
@@ -80,24 +88,30 @@ export function useAgentChat() {
// ── Approval callbacks ────────────────────────────────────
- const approveToolCall = useCallback(() => {
- approvalRef.current?.resolve(true)
- approvalRef.current = null
- setPendingApproval(null)
+ const advanceApprovalQueue = useCallback(() => {
+ const next = approvalQueueRef.current[0]
+ setPendingApproval(next ? next.toolCall : null)
}, [])
+ const approveToolCall = useCallback(() => {
+ const entry = approvalQueueRef.current.shift()
+ if (entry) entry.resolve(true)
+ advanceApprovalQueue()
+ }, [advanceApprovalQueue])
+
const rejectToolCall = useCallback(() => {
- approvalRef.current?.resolve(false)
- approvalRef.current = null
- setPendingApproval(null)
- }, [])
+ const entry = approvalQueueRef.current.shift()
+ if (entry) entry.resolve(false)
+ advanceApprovalQueue()
+ }, [advanceApprovalQueue])
- // ── Wait for user approval ────────────────────────────────
+ // ── Wait for user approval (enqueues; UI shows head of queue) ──
function waitForApproval(toolCall: AgentToolCall): Promise<boolean> {
return new Promise((resolve) => {
- approvalRef.current = { resolve }
- setPendingApproval(toolCall)
+ const wasEmpty = approvalQueueRef.current.length === 0
+ approvalQueueRef.current.push({ toolCall, resolve })
+ if (wasEmpty) setPendingApproval(toolCall)
})
}
@@ -496,7 +510,11 @@ export function useAgentChat() {
: inner
}
return ''
- }).trim()
+ })
+ // Strip non-canonical thinking markers (Gemma channel tags,
+ // `<thought>`, `<reasoning>`, etc.) that the canonical regex above
+ // doesn't catch. These never belong in the assistant bubble.
+ turnContent = finalStripThinkingTags(turnContent, keepThinking)
// Also drop any orphan native-thinking that leaked through when the
// toggle is OFF (e.g. provider returned `turn.thinking` anyway).
if (!keepThinking) turnThinking = ''
@@ -568,7 +586,11 @@ export function useAgentChat() {
explainError: (toolName, err) => explainToolError(toolName, err),
awaitApproval: async (req) => {
const entry = batch.find((e) => e.ac.id === req.id)
- if (!entry) return false
+ if (!entry) return true
+ // Phase 12 — tools whose AC was marked 'running' at batch
+ // creation (permission level 'auto') bypass the approval
+ // gate entirely. Only 'pending_approval' tools enqueue.
+ if (entry.ac.status !== 'pending_approval') return true
const approved = await waitForApproval(entry.ac)
if (approved) {
entry.ac.status = 'running'
@@ -737,8 +759,10 @@ export function useAgentChat() {
setIsAgentRunning(false)
runningRef.current = false
abortRef.current = null
+ // Reject any pending approvals so their promises don't hang forever
+ for (const entry of approvalQueueRef.current) entry.resolve(false)
+ approvalQueueRef.current = []
setPendingApproval(null)
- approvalRef.current = null
// Auto-speak if TTS enabled
const voiceState = useVoiceStore.getState()
@@ -769,8 +793,8 @@ export function useAgentChat() {
runningRef.current = false
abortRef.current?.abort()
abortRef.current = null
- approvalRef.current?.resolve(false)
- approvalRef.current = null
+ for (const entry of approvalQueueRef.current) entry.resolve(false)
+ approvalQueueRef.current = []
setPendingApproval(null)
setIsAgentRunning(false)
}, [])
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index b5e60429..f09b3e6b 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -14,6 +14,7 @@ import { useMemory } from "./useMemory"
import { useAgentModeStore } from "../stores/agentModeStore"
import { getProviderForModel, getProviderIdFromModel } from "../api/providers"
import { isThinkingCompatible } from "../lib/model-compatibility"
+import { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-stripper"
import type { ChatStreamChunk } from "../api/providers/types"
import type { ImageAttachment } from "../types/chat"
@@ -253,7 +254,13 @@ export function useChat() {
requestAnimationFrame(() => {
const cId = convId!
const mId = assistantMessage.id
- useChatStore.getState().updateMessageContent(cId, mId, contentRef.current)
+ // Always strip non-canonical thinking markers (Gemma channel
+ // tags, `<thought>`, `<reasoning>`, `<reflect>`, `<deepthink>`)
+ // from the streaming bubble. The canonical `<think>…</think>`
+ // is already handled by the char-by-char state-machine above,
+ // so we leave those alone here.
+ const displayContent = stripNonCanonicalTags(contentRef.current)
+ useChatStore.getState().updateMessageContent(cId, mId, displayContent)
if (keepThinking && thinkingRef.current) {
useChatStore.getState().updateMessageThinking(cId, mId, thinkingRef.current)
}
@@ -263,12 +270,9 @@ export function useChat() {
}
if (chunk.done) {
- // Strip Gemma 4 channel tags
- contentRef.current = contentRef.current
- .replace(/<\|?channel>?\s*thought\s*/gi, '')
- .replace(/<\|?channel\|?>/gi, '')
- .replace(/<channel\|>/gi, '')
- .trim()
+ // Final safety pass — catches any orphan tags that leaked through
+ // mid-stream (partial chunks, provider restarts, etc.).
+ contentRef.current = finalStripThinkingTags(contentRef.current, keepThinking)
useChatStore
.getState()
.updateMessageContent(convId!, assistantMessage.id, contentRef.current)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 629c11b2..0fadd151 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -20,22 +20,31 @@ import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
import { budgetFromSettings } from '../api/agents/budget'
-
-const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks by reading files, writing code, and running shell commands. You MUST use tools to interact with the filesystem — never guess file contents.
-
-Workflow:
-1. Understand the task
-2. Explore the codebase (file_list, file_read, file_search)
-3. Plan your changes
-4. Implement changes (file_write)
-5. Verify your work (shell_execute to run tests, lint, or build)
+import { finalStripThinkingTags } from '../lib/thinking-stripper'
+
+const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.
+
+AUTONOMY CONTRACT (read carefully):
+- You are expected to COMPLETE multi-step tasks without the user prompting between steps.
+- NEVER say "Now I will create X" or "Next I'll write Y" as plain text and then stop. That is a FAILURE.
+- When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call.
+- The ONLY reasons to finish without calling another tool are:
+ (a) the task is 100% complete AND verified, or
+ (b) you hit an error you cannot recover from after trying.
+- Narrative "I'm about to do X" text with no tool call after it = premature stop. Don't do it.
+
+Workflow per task:
+1. Understand the task (optional brief sentence)
+2. Explore the codebase — file_list / file_read / file_search
+3. Implement ALL required changes — file_write, as many calls as needed in one go
+4. Verify — shell_execute to run tests, lint, or build
+5. Only THEN write a short summary of what you did
Rules:
- Always read a file before modifying it
-- Explain what you are doing before each action
-- After writing files, show a summary of changes made
-- If a command fails, diagnose the issue and try a different approach
-- Be concise — show results, not verbose explanations`
+- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool
+- If a command fails, diagnose and retry with a different approach — don't hand back to the user unless truly stuck
+- Be concise in text. All the work happens in tool calls.`
// Coding-relevant tool categories
const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web'] as const
@@ -243,17 +252,10 @@ export function useCodex() {
}
}
- // Strip Gemma 4 channel tags from content
- turnContent = turnContent
- .replace(/<\|?channel>?\s*thought\s*/gi, '')
- .replace(/<\|?channel\|?>/gi, '')
- .replace(/<channel\|>/gi, '')
-
- // Inline <think>…</think> tags — always remove from content so the
- // assistant bubble never shows raw tags. Route the inner text into
- // the thinking block only when the toggle is ON (QwQ / DeepSeek-R1
- // emit these unconditionally; we must not leak them when the user
- // asked for thinking to be OFF).
+ // Inline <think>…</think> tags — route inner text into thinking
+ // block when toggle is ON, else discard. Non-canonical markers
+ // (Gemma channel tags, <thought>, <reasoning>, etc.) are always
+ // stripped — they are never user-facing content.
{
const keepThinking = settings.thinkingEnabled === true && isThinkingCompatible(activeModel)
turnContent = turnContent.replace(/<think>([\s\S]*?)<\/think>/g, (_m, inner) => {
@@ -263,8 +265,8 @@ export function useCodex() {
}
return ''
})
+ turnContent = finalStripThinkingTags(turnContent, keepThinking)
}
- turnContent = turnContent.trim()
if (turnContent) {
fullContent += (fullContent ? '\n\n' : '') + turnContent
diff --git a/src/lib/thinking-stripper.ts b/src/lib/thinking-stripper.ts
new file mode 100644
index 00000000..39bb2305
--- /dev/null
+++ b/src/lib/thinking-stripper.ts
@@ -0,0 +1,106 @@
+/**
+ * Universal thinking-tag stripper — runs during streaming so raw tags never
+ * reach the user bubble, regardless of what the model emits.
+ *
+ * Different model families encode their "internal reasoning" differently:
+ * - Qwen3 / DeepSeek-R1 / QwQ / Hermes3 / Llama / Mistral / GLM / Nemotron
+ * → `<think>…</think>` (inline)
+ * - Gemma 3 / Gemma 4
+ * → `<|?channel|?>\s*thought\s*…` channel tags (inline, often without
+ * a closing tag — Ollama sometimes truncates mid-stream)
+ * - Some abliterated variants or older model cards
+ * → `<thought>…</thought>` / `<reasoning>…</reasoning>` / `<reflect>…</reflect>`
+ *
+ * The user-visible contract: once the Thinking toggle is OFF, **no** reasoning
+ * markup may appear in the assistant bubble. The state-machine in useChat.ts
+ * handles the canonical `<think>` case char-by-char; this module handles the
+ * non-canonical formats that don't fit that pattern (channel tags, alt names,
+ * orphan open-tags without matching close).
+ */
+
+// ── Patterns, ordered most specific first ─────────────────────────────
+//
+// Every pattern must use the `g` (global) flag. `stripInline` loops them
+// across the full content on every emitted chunk.
+
+const BLOCK_PATTERNS: RegExp[] = [
+ // Gemma channel tag with full block (open + close, sometimes the close uses
+ // a different pipe shape).
+ /<\|?channel\|?>\s*thought\b[\s\S]*?<\/\|?channel\|?>/gi,
+ // Alt thinking-tag names that a small fraction of model cards emit.
+ /<thought>[\s\S]*?<\/thought>/gi,
+ /<reasoning>[\s\S]*?<\/reasoning>/gi,
+ /<reflect>[\s\S]*?<\/reflect>/gi,
+ /<deepthink>[\s\S]*?<\/deepthink>/gi,
+]
+
+// Orphan opening tags — channel tag that never closes in the stream, or an
+// opening `<|channel|>thought` / `<thought>` when the close is still arriving.
+// We remove the opening marker aggressively so the user never sees "thought"
+// mid-stream; if a closing marker later arrives it gets stripped by the
+// BLOCK_PATTERNS on the full-content pass.
+const ORPHAN_OPENERS: RegExp[] = [
+ /<\|?channel\|?>\s*thought\b/gi,
+ /<\|?channel\|?>/gi,
+ /<channel\|>/gi,
+]
+
+/**
+ * Strip every recognised thinking-tag format from `content`. Safe to call
+ * on an in-progress stream buffer — blocks are only removed when both ends
+ * are present; orphan openers are removed eagerly so unclosed channel tags
+ * don't leak into the UI.
+ *
+ * This is the FULL strip — use when thinking is toggled OFF.
+ */
+export function stripAllThinkingTags(content: string): string {
+ if (!content) return content
+ let out = content
+ for (const pat of BLOCK_PATTERNS) {
+ out = out.replace(pat, '')
+ }
+ for (const pat of ORPHAN_OPENERS) {
+ out = out.replace(pat, '')
+ }
+ return out
+}
+
+/**
+ * Strip non-canonical thinking tags (channel tags, alt names, orphan openers)
+ * but leave the canonical `<think>…</think>` alone — useChat.ts state-machine
+ * handles those char-by-char and needs to see the raw `<think>` marker to
+ * detect the transition.
+ *
+ * Use this inside the char-by-char state-machine path.
+ */
+export function stripNonCanonicalTags(content: string): string {
+ if (!content) return content
+ let out = content
+ for (const pat of BLOCK_PATTERNS) {
+ out = out.replace(pat, '')
+ }
+ for (const pat of ORPHAN_OPENERS) {
+ out = out.replace(pat, '')
+ }
+ return out
+}
+
+/**
+ * Apply a final safety pass on the complete assistant content after the
+ * stream finishes. Catches any orphan closing `</think>` that leaked through
+ * (e.g. provider restarted mid-stream, first `<think>` lost).
+ */
+export function finalStripThinkingTags(content: string, keepCanonicalThink = false): string {
+ if (!content) return content
+ let out = stripAllThinkingTags(content)
+ if (!keepCanonicalThink) {
+ // Canonical `<think>` block — strip if still present (shouldn't be,
+ // the state-machine handles it, but belt-and-braces).
+ out = out.replace(/<think>[\s\S]*?<\/think>/gi, '')
+ // Orphan closer alone.
+ out = out.replace(/<\/think>/gi, '')
+ // Orphan opener alone.
+ out = out.replace(/<think>/gi, '')
+ }
+ return out.trim()
+}
diff --git a/src/stores/codexStore.ts b/src/stores/codexStore.ts
index 6ffc1324..0c486728 100644
--- a/src/stores/codexStore.ts
+++ b/src/stores/codexStore.ts
@@ -7,10 +7,18 @@ interface CodexState {
threads: Record<string, CodexThread>
workingDirectory: string
fileTree: FileTreeNode[]
+ /**
+ * Bump counter — incremented every time a Codex run mutates the working
+ * directory (file_write, file_change, terminal commands that can modify
+ * files). FileTree subscribes to this and reloads when it changes, so
+ * new/deleted files appear without a manual refresh.
+ */
+ fileTreeVersion: number
setChatMode: (mode: ChatMode) => void
setWorkingDirectory: (dir: string) => void
setFileTree: (tree: FileTreeNode[]) => void
+ bumpFileTreeVersion: () => void
getThread: (conversationId: string) => CodexThread | undefined
initThread: (conversationId: string, workingDir: string) => string
@@ -25,10 +33,12 @@ export const useCodexStore = create<CodexState>()(
threads: {},
workingDirectory: '',
fileTree: [],
+ fileTreeVersion: 0,
setChatMode: (mode) => set({ chatMode: mode }),
setWorkingDirectory: (dir) => set({ workingDirectory: dir }),
setFileTree: (tree) => set({ fileTree: tree }),
+ bumpFileTreeVersion: () => set((state) => ({ fileTreeVersion: state.fileTreeVersion + 1 })),
getThread: (conversationId) => get().threads[conversationId],
@@ -53,6 +63,11 @@ export const useCodexStore = create<CodexState>()(
set((state) => {
const thread = state.threads[conversationId]
if (!thread) return state
+ // Auto-bump fileTreeVersion for events that can mutate the working
+ // directory. FileTree watches this and re-reads the directory.
+ const mutatesFs =
+ event.type === 'file_change' ||
+ event.type === 'terminal_output' // shell/code execution can touch files
return {
threads: {
...state.threads,
@@ -61,6 +76,7 @@ export const useCodexStore = create<CodexState>()(
events: [...thread.events, event],
},
},
+ fileTreeVersion: mutatesFs ? state.fileTreeVersion + 1 : state.fileTreeVersion,
}
}),