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
feat: Codex coding agent, realtime counter, light mode, UI polish
PurpleDoubleD5382d831145b
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex ac08d194..3ec25736 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -117,7 +117,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppclassName={`flex flex-col rounded-lg border px-2.5 py-2 transition-colors ${isDragOver? 'bg-blue-500/5 border-blue-500/30'- : 'bg-white/[0.03] border-white/[0.06]'+ : 'bg-gray-50 dark:bg-white/[0.03] border-gray-200 dark:border-white/[0.06]'}`}onDragOver={handleDragOver}onDragLeave={handleDragLeave}@@ -181,7 +181,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApponPaste={handlePaste}placeholder={isDragOver ? "Drop images here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Message..."}rows={1}- className="flex-1 bg-transparent resize-none text-gray-200 placeholder-gray-600 focus:outline-none text-[0.75rem] leading-relaxed max-h-[200px]"+ className="flex-1 bg-transparent resize-none text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[0.75rem] leading-relaxed max-h-[200px]"/>{isGenerating ? (diff --git a/src/components/chat/ChatModeTabs.tsx b/src/components/chat/ChatModeTabs.tsxnew file mode 100644index 00000000..dca89b36--- /dev/null+++ b/src/components/chat/ChatModeTabs.tsx@@ -0,0 +1,40 @@+import { MessageSquare, Code, Bot } from 'lucide-react'+import { useCodexStore } from '../../stores/codexStore'+import type { ChatMode } from '../../types/codex'++const TABS: { mode: ChatMode; label: string; icon: typeof Code; disabled?: boolean; tag?: string }[] = [+ { mode: 'lu', label: 'LU', icon: MessageSquare },+ { mode: 'codex', label: 'Codex', icon: Code },+ { mode: 'openclaw', label: 'OpenClaw', icon: Bot, disabled: true, tag: 'Soon' },+]++export function ChatModeTabs() {+ const chatMode = useCodexStore((s) => s.chatMode)+ const setChatMode = useCodexStore((s) => s.setChatMode)++ return (+ <div className="flex items-center gap-0.5 px-2 py-0.5">+ {TABS.map(({ mode, label, icon: Icon, disabled, tag }) => {+ const isActive = chatMode === mode+ return (+ <button+ key={mode}+ onClick={() => !disabled && setChatMode(mode)}+ disabled={disabled}+ className={`flex items-center gap-1 px-2 py-0.5 rounded text-[0.55rem] font-medium transition-all ${+ isActive+ ? 'bg-white/10 text-white border border-white/15'+ : disabled+ ? 'text-gray-700 cursor-default'+ : 'text-gray-500 hover:text-gray-300 hover:bg-white/5 border border-transparent'+ }`}+ >+ <Icon size={9} />+ <span>{label}</span>+ {tag && <span className="text-[0.4rem] text-gray-600 ml-0.5">{tag}</span>}+ </button>+ )+ })}+ </div>+ )+}diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex a8aa5bde..6caf644e 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -21,6 +21,9 @@ 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'export function ChatView() {const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()@@ -37,6 +40,7 @@ export function ChatView() {const allPersonas = useSettingsStore((s) => s.personas)const thinkingEnabled = useSettingsStore((s) => s.settings.thinkingEnabled)const updateSettings = useSettingsStore((s) => s.updateSettings)+ const chatMode = useCodexStore((s) => s.chatMode)const docCount = useRAGStore((s) =>activeConversationId ? (s.documents[activeConversationId] || []).length : 0@@ -85,15 +89,23 @@ export function ChatView() {animate={{ opacity: 1, y: 0 }}transition={{ duration: 0.25, ease: 'easeOut' }}>- <div className="flex-1 flex flex-col min-w-0">- {/* Top bar — compact */}+ <div className="flex-1 flex flex-col min-w-0 relative">+ {/* Codex mode */}+ {chatMode === 'codex' ? (+ <CodexView />+ ) : chatMode === 'openclaw' ? (+ <div className="flex-1 flex items-center justify-center">+ <p className="text-[0.7rem] text-gray-600">OpenClaw — Coming Soon</p>+ </div>+ ) : (<>+ {/* Top bar — compact (LU mode) */}<div className="flex items-center gap-1.5 px-2 pt-0.5">{/* Left: Tools Active dropdown (only when agent is active) */}{isAgentActive && (<div className="relative"><buttononClick={() => setToolsDropdownOpen(!toolsDropdownOpen)}- className="flex items-center gap-1 px-2 py-0.5 rounded border border-white/[0.06] text-gray-500 hover:border-white/15 transition-colors text-[0.55rem]"+ className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] text-gray-500 hover:border-gray-400 dark:hover:border-white/15 transition-colors text-[0.55rem]"><Wrench size={9} className="text-green-400" /><span>Tools</span>@@ -102,7 +114,7 @@ export function ChatView() {{toolsDropdownOpen && (<><div className="fixed inset-0 z-40" onClick={() => setToolsDropdownOpen(false)} />- <div className="absolute left-0 top-full mt-0.5 z-50 w-28 rounded-md bg-[#1a1a1a] border border-white/10 shadow-xl py-0.5 px-0.5">+ <div className="absolute left-0 top-full mt-0.5 z-50 w-28 rounded-md bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-0.5 px-0.5"><PermissionOverrideBar /></div></>@@ -116,7 +128,7 @@ export function ChatView() {className={`flex items-center gap-1 px-2 py-0.5 rounded border transition-colors text-[0.55rem] ${thinkingEnabled? 'border-blue-500/30 text-blue-400'- : 'border-white/[0.06] text-gray-600'+ : 'border-gray-200 dark:border-white/[0.06] text-gray-600'}`}title="Toggle thinking mode — model reasons before answering">@@ -137,7 +149,7 @@ export function ChatView() {<div className="relative"><buttononClick={() => setExportOpen(!exportOpen)}- className="flex items-center gap-1 px-2 py-0.5 rounded border border-white/[0.06] hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"+ className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"title="Export chat"><Download size={10} />@@ -145,7 +157,7 @@ export function ChatView() {{exportOpen && (<><div className="fixed inset-0 z-40" onClick={() => setExportOpen(false)} />- <div className="absolute right-0 top-full mt-1 z-50 w-32 rounded-lg bg-[#1a1a1a] border border-white/10 shadow-xl py-1">+ <div className="absolute right-0 top-full mt-1 z-50 w-32 rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1">{(['markdown', 'json'] as const).map(fmt => (<buttonkey={fmt}@@ -168,7 +180,7 @@ export function ChatView() {<div className="relative"><buttononClick={() => setPersonaOpen(!personaOpen)}- className="flex items-center gap-1 px-2 py-0.5 rounded border border-white/[0.06] hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"+ className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"><User size={10} /><span className="max-w-[60px] truncate">{activePersona?.name || 'No Filter'}</span>@@ -177,9 +189,9 @@ export function ChatView() {{personaOpen && (<><div className="fixed inset-0 z-40" onClick={() => setPersonaOpen(false)} />- <div className="absolute right-0 top-full mt-1 z-50 w-44 max-h-[220px] overflow-y-auto scrollbar-thin rounded-lg bg-[#1a1a1a] border border-white/10 shadow-xl py-1">+ <div className="absolute right-0 top-full mt-1 z-50 w-44 max-h-[220px] overflow-y-auto scrollbar-thin rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1">{activePersona && (- <div className="px-2 pb-1 mb-1 border-b border-white/[0.06]">+ <div className="px-2 pb-1 mb-1 border-b border-gray-200 dark:border-white/[0.06]"><div className="px-2 py-1 rounded-md bg-white/[0.06] border border-white/10 text-[0.55rem] text-white font-medium flex items-center gap-1.5"><div className="w-1 h-1 rounded-full bg-green-400 shrink-0" />{activePersona.name}@@ -207,7 +219,7 @@ export function ChatView() {'flex items-center gap-1 px-2 py-0.5 rounded border transition-colors text-[0.55rem] ' +(ragPanelOpen || ragEnabled? 'border-green-500/30 text-green-400'- : 'border-white/[0.06] hover:border-white/15 text-gray-500')+ : 'border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500')}title="Document Chat (RAG)">@@ -231,7 +243,7 @@ export function ChatView() {? 'border-green-500/30 text-green-400': activeModel && !isAgentCompatible(activeModel)? 'border-white/[0.04] text-gray-600 opacity-50'- : 'border-white/[0.06] text-gray-500')+ : 'border-gray-200 dark:border-white/[0.06] text-gray-500')}><Bot size={10} /><div className="flex flex-col items-start leading-none">@@ -249,6 +261,7 @@ export function ChatView() {onRegenerate={regenerateMessage}onEdit={editAndResend}/>+ <RealtimeCounter isRunning={isGenerating} /><ChatInputonSend={sendMessage}onStop={stopGeneration}@@ -257,6 +270,7 @@ export function ChatView() {onApprove={approveToolCall}onReject={rejectToolCall}/>+ </>)}</div>{/* RAG Panel */}diff --git a/src/components/chat/CodeBlock.tsx b/src/components/chat/CodeBlock.tsxindex 2a616a15..9ae23cb7 100644--- a/src/components/chat/CodeBlock.tsx+++ b/src/components/chat/CodeBlock.tsx@@ -1,15 +1,20 @@import { useState } from 'react'import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism'-import { Copy, Check } from 'lucide-react'+import { Copy, Check, ChevronDown } from 'lucide-react'interface Props {code: stringlanguage?: string}+const COLLAPSE_THRESHOLD = 4 // lines — always start collapsed unless very short+export function CodeBlock({ code, language }: Props) {const [copied, setCopied] = useState(false)+ const lineCount = code.split('\n').length+ const isLong = lineCount > COLLAPSE_THRESHOLD+ const [expanded, setExpanded] = useState(!isLong)const handleCopy = () => {navigator.clipboard.writeText(code)@@ -17,16 +22,18 @@ export function CodeBlock({ code, language }: Props) {setTimeout(() => setCopied(false), 2000)}+ const displayCode = expanded ? code : code.split('\n').slice(0, COLLAPSE_THRESHOLD).join('\n')+return (- <div className="relative group rounded-lg overflow-hidden my-3 border border-white/5">- <div className="flex items-center justify-between px-4 py-1.5 bg-white/5 border-b border-white/5">- <span className="text-xs text-gray-400 font-mono">{language || 'code'}</span>+ <div className="relative group rounded-lg overflow-hidden my-1.5 border border-gray-200 dark:border-white/5">+ <div className="flex items-center justify-between px-3 py-1 bg-gray-50 dark:bg-white/5 border-b border-gray-200 dark:border-white/5">+ <span className="text-[0.6rem] text-gray-400 font-mono">{language || 'code'}</span><buttononClick={handleCopy}- className="flex items-center gap-1 text-xs text-gray-400 hover:text-white transition-colors"+ className="flex items-center gap-1 text-[0.6rem] text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors"aria-label="Copy code">- {copied ? <Check size={14} /> : <Copy size={14} />}+ {copied ? <Check size={11} /> : <Copy size={11} />}{copied ? 'Copied' : 'Copy'}</button></div>@@ -35,13 +42,22 @@ export function CodeBlock({ code, language }: Props) {style={oneDark}customStyle={{margin: 0,- padding: '1rem',+ padding: '0.75rem',background: 'rgba(0, 0, 0, 0.3)',- fontSize: '0.85rem',+ fontSize: '0.75rem',}}>- {code}+ {displayCode}</SyntaxHighlighter>+ {isLong && (+ <button+ onClick={() => setExpanded(!expanded)}+ className="w-full flex items-center justify-center gap-1 py-1 bg-gray-50 dark:bg-white/5 text-[0.55rem] text-gray-400 hover:text-gray-700 dark:hover:text-white border-t border-gray-200 dark:border-white/5 transition-colors"+ >+ <ChevronDown size={9} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />+ {expanded ? 'Collapse' : `Show all ${lineCount} lines`}+ </button>+ )}</div>)}diff --git a/src/components/chat/CodexEventBlock.tsx b/src/components/chat/CodexEventBlock.tsxnew file mode 100644index 00000000..b8dc44ca--- /dev/null+++ b/src/components/chat/CodexEventBlock.tsx@@ -0,0 +1,67 @@+import { Terminal, FileEdit, Brain, AlertCircle, CheckCircle, ChevronDown } from 'lucide-react'+import { useState } from 'react'+import type { CodexEvent } from '../../types/codex'++interface Props {+ event: CodexEvent+}++export function CodexEventBlock({ event }: Props) {+ const [open, setOpen] = useState(event.type === 'error')++ if (event.type === 'instruction' || event.type === 'done') return null++ const icons = {+ file_change: FileEdit,+ terminal_output: Terminal,+ reasoning: Brain,+ error: AlertCircle,+ }++ const colors = {+ file_change: 'text-amber-400',+ terminal_output: 'text-green-400',+ reasoning: 'text-blue-400',+ error: 'text-red-400',+ }++ const labels = {+ file_change: event.filePath || 'File changed',+ terminal_output: 'Terminal',+ reasoning: 'Thinking',+ error: 'Error',+ }++ const Icon = icons[event.type as keyof typeof icons] || CheckCircle+ const color = colors[event.type as keyof typeof colors] || 'text-gray-400'+ const label = labels[event.type as keyof typeof labels] || event.type++ return (+ <div className="mb-0.5">+ <button+ onClick={() => setOpen(!open)}+ className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity w-full"+ >+ <Icon size={10} className={color} />+ <span className={`text-[0.6rem] ${color}`}>{label}</span>+ <ChevronDown size={8} className={`text-gray-600 ml-auto transition-transform ${open ? 'rotate-180' : ''}`} />+ </button>++ {open && (+ <div className="pl-4 pb-1">+ <pre className={`text-[0.58rem] leading-relaxed rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[250px] ${+ event.type === 'terminal_output'+ ? 'bg-black/20 text-green-300/70'+ : event.type === 'error'+ ? 'bg-red-500/5 text-red-400/80'+ : event.type === 'reasoning'+ ? 'text-blue-200/40 italic'+ : 'bg-white/[0.02] text-gray-400'+ }`}>+ {event.content}+ </pre>+ </div>+ )}+ </div>+ )+}diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxnew file mode 100644index 00000000..030c6b05--- /dev/null+++ b/src/components/chat/CodexView.tsx@@ -0,0 +1,155 @@+import { useCodex } from '../../hooks/useCodex'+import { useCodexStore } from '../../stores/codexStore'+import { useChatStore } from '../../stores/chatStore'+import { ChatInput } from './ChatInput'+import { ToolCallBlock } from './ToolCallBlock'+import { ThinkingBlock } from './ThinkingBlock'+import { MarkdownRenderer } from './MarkdownRenderer'+import { TokenCounter } from './TokenCounter'+import { MemoryDebugToggle } from './MemoryDebugPanel'+import { RealtimeCounter } from './RealtimeCounter'+import { useSettingsStore } from '../../stores/settingsStore'+import { User, Code, Brain } from 'lucide-react'+import { useEffect, useRef } from 'react'++function stripChannelTags(text: string): string {+ return text+ .replace(/<\|?channel>?\s*thought\s*/gi, '')+ .replace(/<\|?channel\|?>/gi, '')+ .replace(/<channel\|>/gi, '')+ .trim()+}++export function CodexView() {+ const { sendInstruction, stopCodex, isRunning } = useCodex()+ 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 || []++ useEffect(() => {+ if (scrollRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight+ }+ }, [messages, thread?.events])++ const thinkingEnabled = useSettingsStore((s) => s.settings.thinkingEnabled)+ const updateSettings = useSettingsStore((s) => s.updateSettings)++ return (+ <div className="flex-1 flex overflow-hidden">+ {/* Main panel */}+ <div className="flex-1 flex flex-col min-w-0 relative">+ {/* Codex header */}+ <div className="flex items-center gap-1.5 px-2 py-0.5 border-b border-gray-200 dark:border-white/[0.04]">+ <Code size={9} className="text-gray-500" />+ <span className="text-[0.55rem] text-gray-600 dark:text-gray-400 font-medium">Codex</span>+ <button+ onClick={() => updateSettings({ thinkingEnabled: !thinkingEnabled })}+ className={`flex items-center gap-1 px-2 py-0.5 rounded border transition-colors text-[0.5rem] ${+ thinkingEnabled+ ? 'border-blue-500/30 text-blue-400'+ : 'border-gray-200 dark:border-white/[0.06] text-gray-400 dark:text-gray-600'+ }`}+ title={thinkingEnabled ? 'Thinking ON — model reasons before answering' : 'Thinking OFF'}+ >+ <Brain size={8} />+ <span>Think</span>+ </button>+ <div className="flex-1" />+ <TokenCounter />+ <MemoryDebugToggle />+ </div>++ {/* Messages */}+ <div ref={scrollRef} className="flex-1 overflow-y-auto scrollbar-thin">+ {messages.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-full text-center">+ <Code size={24} className="text-gray-300 dark:text-gray-700 mb-2" />+ <p className="text-[0.7rem] text-gray-500 font-medium">Codex Coding Agent</p>+ <p className="text-[0.55rem] text-gray-400 dark:text-gray-600 mt-0.5 max-w-[300px]">+ Send a coding instruction. Codex will read your codebase, write code, and run commands.+ </p>+ </div>+ ) : (+ <div className="py-1">+ {messages.map((msg) => {+ const cleanContent = msg.content ? stripChannelTags(msg.content) : ''+ return (+ <div+ key={msg.id}+ className={`flex gap-2 px-3 py-1 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}+ >+ <div className={`w-5 h-5 rounded flex items-center justify-center shrink-0 ${+ msg.role === 'user'+ ? 'bg-gray-100 dark:bg-white/8'+ : 'bg-gray-50 dark:bg-white/5'+ }`}>+ {msg.role === 'user'+ ? <User size={9} className="text-gray-400" />+ : <Code size={9} className="text-gray-500" />+ }+ </div>+ <div className="max-w-[85%] space-y-0.5">+ {/* Thinking */}+ {msg.role === 'assistant' && msg.thinking && (+ <ThinkingBlock thinking={msg.thinking} />+ )}+ {/* Tool call blocks */}+ {msg.role === 'assistant' && msg.agentBlocks && msg.agentBlocks.length > 0 && (+ <div className="space-y-0">+ {msg.agentBlocks+ .filter(b => b.phase === 'tool_call' && b.toolCall)+ .map(block => (+ <ToolCallBlock key={block.id} toolCall={block.toolCall!} />+ ))}+ </div>+ )}++ {/* Text content */}+ {cleanContent && (+ <div className={`rounded-lg px-2.5 py-1.5 ${+ msg.role === 'user'+ ? 'bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'+ : 'bg-white dark:bg-white/[0.02] border border-gray-100 dark:border-white/[0.03]'+ }`}>+ <div className="text-[0.75rem] leading-relaxed">+ {msg.role === 'user' ? (+ <p className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{cleanContent}</p>+ ) : (+ <MarkdownRenderer content={cleanContent} />+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ )+ })}+ </div>+ )}+ </div>++ {/* Realtime counter */}+ <RealtimeCounter isRunning={isRunning} />++ {/* Input */}+ <ChatInput+ onSend={(content) => sendInstruction(content)}+ onStop={stopCodex}+ isGenerating={isRunning}+ />+ </div>++ {/* Right sidebar: File Tree */}+ <div className="w-48 shrink-0">+ <FileTree />+ </div>+ </div>+ )+}++import { FileTree } from './FileTree'diff --git a/src/components/chat/FileTree.tsx b/src/components/chat/FileTree.tsxnew file mode 100644index 00000000..c37c7769--- /dev/null+++ b/src/components/chat/FileTree.tsx@@ -0,0 +1,153 @@+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'+import type { FileTreeNode } from '../../types/codex'++export function FileTree() {+ const workingDirectory = useCodexStore((s) => s.workingDirectory)+ const fileTree = useCodexStore((s) => s.fileTree)+ const setFileTree = useCodexStore((s) => s.setFileTree)+ const setWorkingDirectory = useCodexStore((s) => s.setWorkingDirectory)+ const [loading, setLoading] = useState(false)+ const folderInputRef = useRef<HTMLInputElement>(null)++ const loadDirectory = async (dir: string) => {+ if (!dir.trim()) return+ setLoading(true)+ try {+ const result = await toolRegistry.execute('file_list', { path: dir })+ const lines = result.split('\n').filter(Boolean)+ const nodes: FileTreeNode[] = lines.map(line => {+ const isDir = line.startsWith('[DIR]')+ const parts = line.replace('[DIR] ', '').split(' ')+ const nameSize = parts[0]?.trim() || ''+ const path = parts[1]?.trim() || ''+ const name = nameSize.split(' (')[0]?.trim() || ''+ return { name, path, isDirectory: isDir }+ }).filter(n => n.name)++ setFileTree(nodes)+ setWorkingDirectory(dir)+ } catch {+ setFileTree([])+ } finally {+ setLoading(false)+ }+ }++ // Go to parent directory — always works as long as there's a path+ const goBack = () => {+ if (!workingDirectory) return+ const normalized = workingDirectory.replace(/\\/g, '/')+ const parts = normalized.split('/').filter(Boolean)+ if (parts.length <= 1) {+ // Already at root (e.g. "C:")+ loadDirectory(parts[0] + '/')+ } else {+ const parent = parts.slice(0, -1).join('/')+ loadDirectory(parent)+ }+ }++ // Native folder picker via hidden input with webkitdirectory+ const handleFolderSelect = (e: React.ChangeEvent<HTMLInputElement>) => {+ const files = e.target.files+ if (!files || files.length === 0) return+ // Extract directory path from the first file's webkitRelativePath+ const relativePath = (files[0] as any).webkitRelativePath || ''+ const folderName = relativePath.split('/')[0]+ if (folderName) {+ // We can't get the full absolute path from browser file input+ // So we use the folder name and ask the user to confirm+ // In Tauri mode this would use the native dialog+ const fullPath = window.prompt(+ `Selected folder: "${folderName}"\nEnter the full path to this folder:`,+ workingDirectory ? workingDirectory.replace(/\\/g, '/').replace(/\/[^/]*$/, '/' + folderName) : folderName+ )+ if (fullPath) loadDirectory(fullPath)+ }+ e.target.value = ''+ }++ // Simpler approach: just let them type the path on click+ const handlePickClick = () => {+ const dir = window.prompt('Enter folder path:', workingDirectory || 'C:\\Users')+ if (dir) loadDirectory(dir)+ }++ useEffect(() => {+ if (workingDirectory && fileTree.length === 0) {+ loadDirectory(workingDirectory)+ }+ }, [])++ 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 prompt */}+ <div className="p-1.5 border-b border-gray-200 dark:border-white/[0.04]">+ <button+ onClick={handlePickClick}+ className="w-full flex items-center gap-1 px-1.5 py-1 rounded bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 transition-colors text-left"+ >+ <FolderOpen size={10} className="text-gray-500 shrink-0" />+ {workingDirectory ? (+ <span className="text-[0.5rem] text-gray-700 dark:text-gray-300 font-mono truncate flex-1">{workingDirectory}</span>+ ) : (+ <span className="text-[0.5rem] text-gray-400 dark:text-gray-600 flex-1">Select folder...</span>+ )}+ </button>+ </div>++ {/* File list */}+ <div className="flex-1 overflow-y-auto scrollbar-thin p-1">+ {loading ? (+ <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Loading...</p>+ ) : fileTree.length === 0 ? (+ <p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">+ {workingDirectory ? 'Empty directory' : 'Click above to set a folder'}+ </p>+ ) : (+ fileTree.map((node, i) => (+ <button+ key={i}+ onClick={() => node.isDirectory && loadDirectory(node.path)}+ className={`flex items-center gap-1 w-full px-1 py-[2px] text-[0.5rem] rounded transition-colors text-left ${+ node.isDirectory+ ? 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 cursor-pointer'+ : 'text-gray-400 dark:text-gray-600'+ }`}+ >+ {node.isDirectory ? (+ <Folder size={8} className="text-gray-500 shrink-0" />+ ) : (+ <FileText size={8} className="text-gray-400 dark:text-gray-600 shrink-0" />+ )}+ <span className="truncate">{node.name}</span>+ </button>+ ))+ )}+ </div>++ {/* Bottom nav */}+ <div className="flex items-center justify-center gap-1 px-1.5 py-1 border-t border-gray-200 dark:border-white/[0.04]">+ <button+ onClick={goBack}+ disabled={!workingDirectory}+ className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 disabled:opacity-30 transition-colors"+ title="Parent directory"+ >+ <ArrowLeft size={10} />+ </button>+ <button+ onClick={() => workingDirectory && loadDirectory(workingDirectory)}+ disabled={!workingDirectory}+ className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/5 text-gray-400 dark:text-gray-600 disabled:opacity-30 transition-colors"+ title="Refresh"+ >+ <RefreshCw size={10} />+ </button>+ </div>+ </div>+ )+}diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex cc657863..4619cb50 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -63,8 +63,8 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {className={'w-6 h-6 rounded-md flex items-center justify-center shrink-0 ' +(isUser- ? 'bg-white/8 border border-white/10'- : 'bg-white/5 border border-white/[0.06]')+ ? 'bg-gray-100 dark:bg-white/8 border border-gray-200 dark:border-white/10'+ : 'bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/[0.06]')}>{isUser ? <User size={11} className="text-gray-400" /> : <Bot size={11} className="text-gray-500" />}@@ -112,8 +112,8 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {className={'rounded-lg px-2.5 py-1.5 relative ' +(isUser- ? 'bg-white/[0.06] border border-white/[0.08]'- : 'bg-white/[0.03] border border-white/[0.04]')+ ? 'bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'+ : 'bg-white dark:bg-white/[0.03] border border-gray-100 dark:border-white/[0.04]')}>{isUser && isEditing ? (@@ -130,7 +130,7 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); confirmEdit() }if (e.key === 'Escape') cancelEdit()}}- className="w-full bg-transparent text-[0.78rem] leading-relaxed text-gray-200 resize-none focus:outline-none"+ className="w-full bg-transparent text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 resize-none focus:outline-none"/><div className="flex items-center gap-1 justify-end"><button onClick={confirmEdit} className="p-0.5 rounded hover:bg-green-500/20 text-green-500 transition-colors"><Check size={11} /></button>@@ -138,7 +138,7 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {</div></div>) : isUser ? (- <p className="text-[0.78rem] leading-relaxed text-gray-200 whitespace-pre-wrap">{message.content}</p>+ <p className="text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{message.content}</p>) : (<div className="text-[0.78rem] leading-relaxed"><MarkdownRenderer content={message.content} />diff --git a/src/components/chat/PermissionOverrideBar.tsx b/src/components/chat/PermissionOverrideBar.tsxindex 784796c5..c20dddcd 100644--- a/src/components/chat/PermissionOverrideBar.tsx+++ b/src/components/chat/PermissionOverrideBar.tsx@@ -41,10 +41,10 @@ export function PermissionOverrideBar() {disabled={isLocked}className={`flex items-center gap-1.5 w-full px-1.5 py-[3px] text-[0.5rem] transition-colors ${isLocked- ? 'text-gray-700 cursor-default'+ ? 'text-gray-400 dark:text-gray-700 cursor-default': isOn- ? 'text-gray-300 hover:bg-white/5'- : 'text-gray-600 hover:bg-white/5'+ ? 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5'+ : 'text-gray-400 dark:text-gray-600 hover:bg-gray-100 dark:hover:bg-white/5'}`}>{isLocked ? (diff --git a/src/components/chat/RealtimeCounter.tsx b/src/components/chat/RealtimeCounter.tsxnew file mode 100644index 00000000..b6e405d3--- /dev/null+++ b/src/components/chat/RealtimeCounter.tsx@@ -0,0 +1,33 @@+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/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 5a11ed5d..cddb5d38 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -25,22 +25,6 @@ const TOOL_ICONS: Record<string, typeof Search> = {run_workflow: GitBranch,}-const TOOL_COLORS: Record<string, string> = {- web_search: 'text-blue-400',- web_fetch: 'text-cyan-400',- file_read: 'text-gray-400',- file_write: 'text-amber-400',- file_list: 'text-gray-400',- file_search: 'text-gray-400',- code_execute: 'text-green-400',- shell_execute: 'text-green-400',- system_info: 'text-purple-400',- process_list: 'text-purple-400',- screenshot: 'text-pink-400',- image_generate: 'text-purple-400',- run_workflow: 'text-amber-400',-}-const STATUS_ICONS = {pending_approval: Clock,running: Loader2,@@ -50,39 +34,35 @@ const STATUS_ICONS = {}export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {+ // Default: collapsed (closed)const [open, setOpen] = useState(toolCall.status === 'pending_approval')const ToolIcon = TOOL_ICONS[toolCall.toolName] || Terminalconst StatusIcon = STATUS_ICONS[toolCall.status]- const toolColor = TOOL_COLORS[toolCall.toolName] || 'text-gray-400'const isRunning = toolCall.status === 'running'const isPending = toolCall.status === 'pending_approval'+ const isFailed = toolCall.status === 'failed' || toolCall.status === 'rejected'return (- <div className="mb-1">- {/* Inline tool call line */}+ <div className="mb-0.5">+ {/* Header line — monochrome, only status icon has subtle color */}<buttononClick={() => setOpen(!open)}className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity w-full">- <ToolIcon size={12} className={`${toolColor} shrink-0`} />- <span className={`text-[0.72rem] font-medium ${toolColor}`}>{toolCall.toolName}</span>- <StatusIcon size={11} className={`shrink-0 ${- toolCall.status === 'completed' ? 'text-green-500' :- toolCall.status === 'failed' ? 'text-red-400' :- toolCall.status === 'rejected' ? 'text-red-400' :- isPending ? 'text-amber-400' :- 'text-gray-400'+ <ToolIcon size={10} className="text-gray-500 dark:text-gray-500 shrink-0" />+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">{toolCall.toolName}</span>+ <StatusIcon size={9} className={`shrink-0 ${+ toolCall.status === 'completed' ? 'text-gray-400 dark:text-gray-500' :+ isFailed ? 'text-red-400/60' :+ isPending ? 'text-amber-400/60' :+ 'text-gray-500'} ${isRunning ? 'animate-spin' : ''}`} />{toolCall.duration != null && (- <span className="text-[0.6rem] text-gray-500">+ <span className="text-[0.5rem] text-gray-500 dark:text-gray-600">{toolCall.duration < 1000 ? `${toolCall.duration}ms` : `${(toolCall.duration / 1000).toFixed(1)}s`}</span>)}- <ChevronDown- size={10}- className={`text-gray-500 ml-auto transition-transform duration-200 ${open ? 'rotate-180' : ''}`}- /></button>{/* Expandable details */}@@ -95,22 +75,22 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {transition={{ duration: 0.15 }}className="overflow-hidden">- <div className="pl-5 pb-2 space-y-1.5">+ <div className="pl-5 pb-1.5 space-y-1">{/* Arguments */}- <pre className="text-[0.62rem] leading-relaxed text-gray-500 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-x-auto scrollbar-thin">+ <pre className="text-[0.55rem] leading-relaxed text-gray-500 dark:text-gray-500 bg-gray-50 dark:bg-white/[0.02] rounded px-2 py-1 overflow-x-auto scrollbar-thin">{JSON.stringify(toolCall.args, null, 2)}</pre>- {/* Result — full content, scrollable */}+ {/* Result */}{toolCall.result && (- <pre className="text-[0.62rem] leading-relaxed text-gray-400 bg-black/[0.02] dark:bg-white/[0.02] rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[300px]">+ <pre className="text-[0.55rem] leading-relaxed text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-white/[0.02] rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[300px]">{toolCall.result}</pre>)}{/* Error */}{toolCall.error && (- <pre className="text-[0.62rem] leading-relaxed text-red-400/80 rounded px-2 py-1">+ <pre className="text-[0.55rem] leading-relaxed text-gray-500 dark:text-gray-500 bg-gray-50 dark:bg-white/[0.02] rounded px-2 py-1">{toolCall.error}</pre>)}@@ -120,15 +100,15 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {<div className="flex items-center gap-2 pt-0.5"><buttononClick={(e) => { e.stopPropagation(); onApprove() }}- className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.65rem] font-medium bg-green-500/10 text-green-400 hover:bg-green-500/20 transition-colors"+ className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium bg-gray-100 dark:bg-white/5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">- <Check size={11} /> Approve+ <Check size={10} /> Approve</button><buttononClick={(e) => { e.stopPropagation(); onReject() }}- className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.65rem] font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors"+ className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium bg-gray-100 dark:bg-white/5 text-gray-500 dark:text-gray-500 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">- <X size={11} /> Reject+ <X size={10} /> Reject</button></div>)}diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsxindex b5dd3f43..f3472576 100644--- a/src/components/layout/Sidebar.tsx+++ b/src/components/layout/Sidebar.tsx@@ -1,33 +1,46 @@import { useState } from 'react'import { motion, AnimatePresence } from 'framer-motion'-import { Plus, Search, Trash2, Edit3, Check, X } from 'lucide-react'+import { Plus, Search, Trash2, Edit3, Check, X, MessageSquare, Code, Bot } from 'lucide-react'import { useChatStore } from '../../stores/chatStore'import { useUIStore } from '../../stores/uiStore'import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'+import { useCodexStore } from '../../stores/codexStore'import { formatDate, truncate } from '../../lib/formatters'+import type { ChatMode } from '../../types/codex'++const MODE_TABS: { mode: ChatMode; label: string; icon: typeof Code; disabled?: boolean; tag?: string }[] = [+ { mode: 'lu', label: 'LU', icon: MessageSquare },+ { mode: 'codex', label: 'Codex', icon: Code },+ { mode: 'openclaw', label: 'OpenClaw', icon: Bot, disabled: true, tag: 'Soon' },+]export function Sidebar() {const { conversations, activeConversationId, createConversation, deleteConversation, renameConversation, setActiveConversation } = useChatStore()const { sidebarOpen, setView } = useUIStore()const { activeModel } = useModelStore()const { getActivePersona } = useSettingsStore()+ const chatMode = useCodexStore((s) => s.chatMode)+ const setChatMode = useCodexStore((s) => s.setChatMode)const [search, setSearch] = useState('')const [editingId, setEditingId] = useState<string | null>(null)const [editTitle, setEditTitle] = useState('')+ // Filter conversations by current mode+ const modeConversations = conversations.filter(c => (c.mode || 'lu') === chatMode)+const filtered = search- ? conversations.filter(+ ? modeConversations.filter((c) =>c.title.toLowerCase().includes(search.toLowerCase()) ||c.messages.some((m) => m.content.toLowerCase().includes(search.toLowerCase())))- : conversations+ : modeConversationsconst handleNewChat = () => {const persona = getActivePersona()if (activeModel) {- createConversation(activeModel, persona?.systemPrompt || '')+ createConversation(activeModel, persona?.systemPrompt || '', chatMode)setView('chat')}}@@ -49,16 +62,35 @@ export function Sidebar() {exit={{ width: 0, opacity: 0 }}transition={{ duration: 0.15 }}>- {/* New Chat + Search */}- <div className="px-2 pt-2 pb-1 space-y-1.5">- <button- onClick={handleNewChat}- className="w-full flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.7rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-white/[0.05] transition-all"- >- <Plus size={13} />- <span>New Chat</span>- </button>+ {/* Mode Tabs (LU | Codex | OpenClaw) */}+ <div className="flex items-center gap-0.5 px-2 pt-2 pb-1">+ {MODE_TABS.map(({ mode, label, icon: Icon, disabled, tag }) => {+ const isActive = chatMode === mode+ return (+ <button+ key={mode}+ onClick={() => { if (!disabled) { setChatMode(mode); setActiveConversation(null); setView('chat') } }}+ disabled={disabled}+ className={`flex items-center gap-1 px-2 py-1 rounded text-[0.6rem] font-medium transition-all flex-1 justify-center ${+ isActive+ ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white border border-gray-300 dark:border-white/15'+ : disabled+ ? 'text-gray-400 dark:text-gray-700 cursor-default'+ : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 border border-transparent'+ }`}+ >+ <Icon size={9} />+ <span className="relative">+ {label}+ {tag && <span className="absolute inset-0 flex items-center justify-center text-[0.4rem] text-red-500 dark:text-red-400 font-bold bg-gray-50/80 dark:bg-[#0a0a0a]/80">{tag}</span>}+ </span>+ </button>+ )+ })}+ </div>+ {/* Search */}+ <div className="px-2 pb-1"><div className="relative"><Search size={11} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-600" /><input@@ -132,6 +164,17 @@ export function Sidebar() {</p>)}</div>++ {/* New Chat — bottom */}+ <div className="px-2 pb-2 pt-1 border-t border-white/[0.04]">+ <button+ onClick={handleNewChat}+ className="w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.65rem] text-gray-500 hover:text-white hover:bg-white/[0.05] border border-dashed border-white/[0.08] hover:border-white/15 transition-all"+ >+ <Plus size={12} />+ <span>New Chat</span>+ </button>+ </div></motion.aside>)}</AnimatePresence>diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex d3f60fb1..e1d09905 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -12,7 +12,7 @@ import { getModelMaxTokens } from "../lib/context-compaction"import { useAgentChat } from "./useAgentChat"import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"-import { getProviderForModel } from "../api/providers"+import { getProviderForModel, getProviderIdFromModel } from "../api/providers"import type { ChatStreamChunk } from "../api/providers/types"import type { ImageAttachment } from "../types/chat"@@ -112,6 +112,12 @@ export function useChat() {// Memory injection is non-critical}+ // For non-Ollama providers, inject thinking via system prompt+ const providerId = getProviderIdFromModel(activeModel)+ if (settings.thinkingEnabled && providerId !== 'ollama') {+ systemPrompt = (systemPrompt || '') + '\n\nBefore answering, reason through your thinking inside <think></think> tags. Your thinking will be hidden from the user. After thinking, provide your answer outside the tags.'+ }+const messages = [...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),...conv.messages@@ -198,6 +204,12 @@ 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()useChatStore.getState().updateMessageContent(convId!, assistantMessage.id, contentRef.current)diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsnew file mode 100644index 00000000..3aa66b67--- /dev/null+++ b/src/hooks/useCodex.ts@@ -0,0 +1,299 @@+import { useRef, useState, useCallback } from 'react'+import { v4 as uuid } from 'uuid'+import { useCodexStore } from '../stores/codexStore'+import { useModelStore } from '../stores/modelStore'+import { useSettingsStore } from '../stores/settingsStore'+import { useChatStore } from '../stores/chatStore'+import { getProviderForModel, getProviderIdFromModel } from '../api/providers'+import { toolRegistry } from '../api/mcp'+import { usePermissionStore } from '../stores/permissionStore'+import { getToolCallingStrategy } from '../lib/model-compatibility'+import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'+import { chatNonStreaming } from '../api/agents'+import type { CodexEvent } from '../types/codex'+import type { AgentBlock, AgentToolCall } from '../types/agent-mode'+import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'++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)++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`++// Coding-relevant tool categories+const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web'] as const++export function useCodex() {+ const [isRunning, setIsRunning] = useState(false)+ const abortRef = useRef<AbortController | null>(null)+ const runningRef = useRef(false)++ const sendInstruction = useCallback(async (instruction: string) => {+ const { activeModel } = useModelStore.getState()+ if (!activeModel) return++ const store = useChatStore.getState()+ const codexStore = useCodexStore.getState()+ const { settings } = useSettingsStore.getState()+ const persona = useSettingsStore.getState().getActivePersona()++ // Ensure conversation exists+ let convId = store.activeConversationId+ if (!convId) {+ convId = store.createConversation(activeModel, persona?.systemPrompt || '', 'codex')+ }++ // Init codex thread if needed+ if (!codexStore.getThread(convId)) {+ codexStore.initThread(convId, codexStore.workingDirectory || '.')+ }++ const thread = codexStore.getThread(convId)!+ const workDir = thread.workingDirectory || codexStore.workingDirectory || '.'++ // Add instruction event+ codexStore.addEvent(convId, {+ id: uuid(), type: 'instruction', content: instruction, timestamp: Date.now(),+ })++ // Add user message to chat store+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'user', content: instruction, timestamp: Date.now(),+ })++ // Add empty assistant message+ const assistantMsg = {+ id: uuid(), role: 'assistant' as const, content: '', thinking: '', timestamp: Date.now(), agentBlocks: [],+ }+ useChatStore.getState().addMessage(convId, assistantMsg)+ let thinkingContent = ''++ const blocks: AgentBlock[] = []+ function addBlock(block: AgentBlock) {+ blocks.push(block)+ useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])+ }++ // Resolve provider+ const { provider, modelId } = getProviderForModel(activeModel)+ const providerId = getProviderIdFromModel(activeModel)+ const strategy = providerId === 'ollama'+ ? getToolCallingStrategy(activeModel)+ : 'native'+ const modelToUse = activeModel.includes('::') ? activeModel.split('::')[1] : activeModel++ // Build permissions — auto-approve reads, confirm writes+ const permissions = usePermissionStore.getState().getEffectivePermissions(convId)++ // System prompt with working directory+ let systemPrompt = `${CODEX_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`++ // For non-Ollama providers, inject thinking via system prompt+ if (settings.thinkingEnabled && providerId !== 'ollama') {+ systemPrompt += '\n\nBefore answering, reason through your thinking inside <think></think> tags. Your thinking will be hidden from the user. After thinking, provide your answer outside the tags.'+ }++ // Build message history+ const conv = useChatStore.getState().conversations.find(c => c.id === convId)+ if (!conv) return++ let messages: ChatMessage[] = [+ { role: 'system', content: systemPrompt },+ ...conv.messages+ .filter(m => m.role !== 'system' && m.content.trim())+ .map(m => ({ role: m.role as 'user' | 'assistant' | 'tool', content: m.content })),+ ]++ // Setup+ const abort = new AbortController()+ abortRef.current = abort+ runningRef.current = true+ setIsRunning(true)+ codexStore.setThreadStatus(convId, 'running')++ let fullContent = ''++ try {+ // Agent loop — max 20 iterations+ for (let i = 0; i < 20 && runningRef.current && !abort.signal.aborted; i++) {+ let toolCalls: ToolCall[] = []+ let turnContent = ''++ const chatOptions = {+ temperature: 0.1, // Low temp for coding precision+ maxTokens: settings.maxTokens || undefined,+ thinking: settings.thinkingEnabled === true ? true : false,+ signal: abort.signal,+ }++ if (strategy === 'native') {+ const tools: ToolDefinition[] = toolRegistry.toOpenAITools(permissions)+ const turn = await provider.chatWithTools(modelToUse, messages, tools, chatOptions)+ toolCalls = turn.toolCalls+ turnContent = turn.content || ''+ if ((turn as any).thinking) {+ thinkingContent += (thinkingContent ? '\n\n' : '') + (turn as any).thinking+ useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)+ }+ } else {+ const hermesTools = toolRegistry.toHermesToolDefs(permissions)+ const hermesSystem = buildHermesToolPrompt(hermesTools) + `\n\n${systemPrompt}`+ messages[0] = { role: 'system', content: hermesSystem }+ const raw = await chatNonStreaming(+ modelToUse,+ messages.map(m => ({ role: m.role, content: m.content })),+ abort.signal,+ )+ if (hasToolCallTags(raw)) {+ toolCalls = parseHermesToolCalls(raw).map(tc => ({+ function: { name: tc.name, arguments: tc.arguments },+ }))+ turnContent = stripToolCallTags(raw)+ } else {+ turnContent = raw+ }+ }++ // Strip Gemma 4 channel tags from content+ turnContent = turnContent+ .replace(/<\|?channel>?\s*thought\s*/gi, '')+ .replace(/<\|?channel\|?>/gi, '')+ .replace(/<channel\|>/gi, '')+ .trim()++ if (turnContent) {+ fullContent += (fullContent ? '\n\n' : '') + turnContent+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)+ }++ // No tool calls → done+ if (toolCalls.length === 0) break++ // Execute tool calls+ for (const tc of toolCalls) {+ if (!runningRef.current || abort.signal.aborted) break++ const toolName = tc.function.name+ const toolArgs = { ...tc.function.arguments }++ // Inject working directory for file/shell tools+ if (toolName === 'shell_execute' && !toolArgs.cwd) {+ toolArgs.cwd = workDir+ }+ if (toolName === 'code_execute' && !toolArgs.cwd) {+ toolArgs.cwd = workDir+ }+ // Resolve relative file paths against working directory+ if ((toolName === 'file_read' || toolName === 'file_write' || toolName === 'file_list' || toolName === 'file_search') && toolArgs.path) {+ const p = toolArgs.path+ if (!p.startsWith('/') && !p.startsWith('C:') && !p.startsWith('\\\\') && workDir) {+ toolArgs.path = workDir.replace(/\\/g, '/') + '/' + p+ }+ }++ // Create tool call block (visible in chat)+ const toolCallId = uuid()+ const agentToolCall: AgentToolCall = {+ id: toolCallId, toolName, args: toolArgs,+ status: 'running', timestamp: Date.now(),+ }+ addBlock({+ id: uuid(), phase: 'tool_call', content: `Running: ${toolName}`,+ toolCall: agentToolCall, timestamp: Date.now(),+ })++ // Execute+ const startTime = Date.now()+ const result = await toolRegistry.execute(toolName, toolArgs)+ const duration = Date.now() - startTime+ const isError = result.startsWith('Error:')++ // Update block with result+ agentToolCall.status = isError ? 'failed' : 'completed'+ agentToolCall.result = isError ? undefined : result+ agentToolCall.error = isError ? result : undefined+ agentToolCall.duration = duration+ const lastBlock = blocks[blocks.length - 1]+ if (lastBlock) {+ lastBlock.toolCall = { ...agentToolCall }+ lastBlock.content = isError ? `Failed: ${toolName}` : `Completed: ${toolName}`+ useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])+ }++ // Also add codex event for the event log+ if (toolName === 'shell_execute' || toolName === 'code_execute') {+ codexStore.addEvent(convId, {+ id: uuid(), type: 'terminal_output', content: result, timestamp: Date.now(),+ })+ } else if (toolName === 'file_write') {+ codexStore.addEvent(convId, {+ id: uuid(), type: 'file_change', content: result,+ filePath: toolArgs.path, timestamp: Date.now(),+ })+ } else if (isError) {+ codexStore.addEvent(convId, {+ id: uuid(), type: 'error', content: result, timestamp: Date.now(),+ })+ }++ // Append to message history+ if (providerId === 'openai' || providerId === 'anthropic') {+ messages.push({ role: 'assistant', content: turnContent || '', tool_calls: [tc] })+ messages.push({ role: 'tool', content: result, tool_call_id: tc.id })+ } else if (strategy === 'native') {+ messages.push({+ role: 'assistant', content: turnContent || '',+ tool_calls: [{ function: { name: toolName, arguments: toolArgs } }],+ })+ messages.push({ role: 'tool', content: result })+ } else {+ messages.push({+ role: 'assistant',+ content: `<tool_call>\n{"name": "${toolName}", "arguments": ${JSON.stringify(toolArgs)}}\n</tool_call>`,+ })+ messages.push({ role: 'user', content: buildHermesToolResult(toolName, result) })+ }+ }+ }++ // Final update+ codexStore.addEvent(convId, {+ id: uuid(), type: 'done', content: 'Task completed.', timestamp: Date.now(),+ })++ } catch (err) {+ if ((err as Error).name !== 'AbortError') {+ const msg = (err as Error).message || 'Codex error'+ fullContent += `\n\nError: ${msg}`+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)+ codexStore.addEvent(convId, {+ id: uuid(), type: 'error', content: msg, timestamp: Date.now(),+ })+ }+ } finally {+ setIsRunning(false)+ runningRef.current = false+ abortRef.current = null+ codexStore.setThreadStatus(convId, 'idle')+ }+ }, [])++ const stopCodex = useCallback(() => {+ runningRef.current = false+ abortRef.current?.abort()+ abortRef.current = null+ setIsRunning(false)+ }, [])++ return { sendInstruction, stopCodex, isRunning }+}diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex b9b149c9..e659bab6 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -8,7 +8,7 @@ import { createSafeStorage } from '../lib/storage-quota'interface ChatState {conversations: Conversation[]activeConversationId: string | null- createConversation: (model: string, systemPrompt: string) => string+ createConversation: (model: string, systemPrompt: string, mode?: 'lu' | 'codex' | 'openclaw') => stringdeleteConversation: (id: string) => voidrenameConversation: (id: string, title: string) => voidsetActiveConversation: (id: string | null) => void@@ -27,14 +27,15 @@ export const useChatStore = create<ChatState>()(conversations: [],activeConversationId: null,- createConversation: (model, systemPrompt) => {+ createConversation: (model, systemPrompt, mode) => {const id = uuid()const conversation: Conversation = {id,- title: 'New Chat',+ title: mode === 'codex' ? 'Codex Chat' : 'New Chat',messages: [],model,systemPrompt,+ mode: mode || 'lu',createdAt: Date.now(),updatedAt: Date.now(),}diff --git a/src/stores/codexStore.ts b/src/stores/codexStore.tsnew file mode 100644index 00000000..6ffc1324--- /dev/null+++ b/src/stores/codexStore.ts@@ -0,0 +1,87 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import type { ChatMode, CodexThread, CodexEvent, FileTreeNode } from '../types/codex'++interface CodexState {+ chatMode: ChatMode+ threads: Record<string, CodexThread>+ workingDirectory: string+ fileTree: FileTreeNode[]++ setChatMode: (mode: ChatMode) => void+ setWorkingDirectory: (dir: string) => void+ setFileTree: (tree: FileTreeNode[]) => void++ getThread: (conversationId: string) => CodexThread | undefined+ initThread: (conversationId: string, workingDir: string) => string+ addEvent: (conversationId: string, event: CodexEvent) => void+ setThreadStatus: (conversationId: string, status: CodexThread['status']) => void+}++export const useCodexStore = create<CodexState>()(+ persist(+ (set, get) => ({+ chatMode: 'lu',+ threads: {},+ workingDirectory: '',+ fileTree: [],++ setChatMode: (mode) => set({ chatMode: mode }),+ setWorkingDirectory: (dir) => set({ workingDirectory: dir }),+ setFileTree: (tree) => set({ fileTree: tree }),++ getThread: (conversationId) => get().threads[conversationId],++ initThread: (conversationId, workingDir) => {+ const id = `codex-${Date.now()}`+ set((state) => ({+ threads: {+ ...state.threads,+ [conversationId]: {+ id,+ conversationId,+ events: [],+ status: 'idle',+ workingDirectory: workingDir,+ },+ },+ }))+ return id+ },++ addEvent: (conversationId, event) =>+ set((state) => {+ const thread = state.threads[conversationId]+ if (!thread) return state+ return {+ threads: {+ ...state.threads,+ [conversationId]: {+ ...thread,+ events: [...thread.events, event],+ },+ },+ }+ }),++ setThreadStatus: (conversationId, status) =>+ set((state) => {+ const thread = state.threads[conversationId]+ if (!thread) return state+ return {+ threads: {+ ...state.threads,+ [conversationId]: { ...thread, status },+ },+ }+ }),+ }),+ {+ name: 'locally-uncensored-codex',+ partialize: (state) => ({+ chatMode: state.chatMode,+ workingDirectory: state.workingDirectory,+ }),+ }+ )+)diff --git a/src/types/chat.ts b/src/types/chat.tsindex fc1c7f17..1f038b63 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -27,6 +27,7 @@ export interface Conversation {messages: Message[]model: stringsystemPrompt: string+ mode?: 'lu' | 'codex' | 'openclaw'createdAt: numberupdatedAt: number}diff --git a/src/types/codex.ts b/src/types/codex.tsnew file mode 100644index 00000000..6e89ecf8--- /dev/null+++ b/src/types/codex.ts@@ -0,0 +1,28 @@+export type ChatMode = 'lu' | 'codex' | 'openclaw'++export type CodexEventType = 'instruction' | 'file_change' | 'terminal_output' | 'reasoning' | 'error' | 'done'++export interface CodexEvent {+ id: string+ type: CodexEventType+ content: string+ timestamp: number+ filePath?: string+ diff?: string+}++export interface CodexThread {+ id: string+ conversationId: string+ events: CodexEvent[]+ status: 'idle' | 'running' | 'error'+ workingDirectory: string+}++export interface FileTreeNode {+ name: string+ path: string+ isDirectory: boolean+ size?: number+ children?: FileTreeNode[]+}