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.

feat(chat+codex): ChatGPT-style chat tools, slash commands → Coding Agent, real token counter

purpleeb3d7603fe37
diff --git a/src/api/__tests__/agent-context-artifacts.test.ts b/src/api/__tests__/agent-context-artifacts.test.ts
new file mode 100644
index 00000000..bc0cae5a
--- /dev/null
+++ b/src/api/__tests__/agent-context-artifacts.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ setChatArtifactMode,
+ isChatArtifactMode,
+ captureChatArtifact,
+ takeChatArtifacts,
+ clearActiveChatId,
+} from '../agent-context'
+
+// David 2026-06-12: in plain chat, file_write captures here (ChatGPT-style
+// in-chat artifact) instead of touching disk. These lock the capture/drain/reset
+// contract that useAgentChat + executeFileWrite rely on.
+describe('chat-tools artifact context', () => {
+ beforeEach(() => clearActiveChatId())
+
+ it('is off by default', () => {
+ expect(isChatArtifactMode()).toBe(false)
+ })
+
+ it('captures artifacts in order and drains them once', () => {
+ setChatArtifactMode(true)
+ expect(isChatArtifactMode()).toBe(true)
+ captureChatArtifact('a.md', '# A', 'text/markdown')
+ captureChatArtifact('b.txt', 'B', 'text/plain')
+ expect(takeChatArtifacts()).toEqual([
+ { name: 'a.md', content: '# A', mime: 'text/markdown' },
+ { name: 'b.txt', content: 'B', mime: 'text/plain' },
+ ])
+ // Drained — a second take is empty (so artifacts attach to exactly one turn).
+ expect(takeChatArtifacts()).toEqual([])
+ })
+
+ it('turning the mode OFF clears any pending captures', () => {
+ setChatArtifactMode(true)
+ captureChatArtifact('x.txt', 'x', 'text/plain')
+ setChatArtifactMode(false)
+ expect(isChatArtifactMode()).toBe(false)
+ expect(takeChatArtifacts()).toEqual([])
+ })
+
+ it('clearActiveChatId resets mode + captures (per-run cleanup)', () => {
+ setChatArtifactMode(true)
+ captureChatArtifact('y.txt', 'y', 'text/plain')
+ clearActiveChatId()
+ expect(isChatArtifactMode()).toBe(false)
+ expect(takeChatArtifacts()).toEqual([])
+ })
+})
diff --git a/src/api/agent-context.ts b/src/api/agent-context.ts
index 0dca964a..2b27b1e4 100644
--- a/src/api/agent-context.ts
+++ b/src/api/agent-context.ts
@@ -37,13 +37,23 @@ import type { AgentWorkspace } from '../types/agent-workspace'
* state on `globalThis` makes every bundled copy share one store, whatever
* the chunker decides. Do not "simplify" this back to module-level lets.
*/
+/** A file the model "wrote" in plain-chat artifact mode (never hit disk). */
+export interface CapturedArtifact {
+ name: string
+ content: string
+ mime: string
+}
interface AgentCtxState {
chatId: string | null
workspace: AgentWorkspace | null
model: ActiveAgentModel | null
+ /** Chat-tools artifact mode: when true, file_write captures instead of
+ * writing to disk, so plain chat shows files inline (ChatGPT-style). */
+ artifactMode: boolean
+ artifacts: CapturedArtifact[]
}
const _g = globalThis as typeof globalThis & { __LU_AGENT_CTX?: AgentCtxState }
-const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, workspace: null, model: null })
+const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, workspace: null, model: null, artifactMode: false, artifacts: [] })
/**
* The text model driving the current agent loop. Pinned by useAgentChat right
@@ -85,6 +95,37 @@ export function clearActiveChatId(): void {
ctx.chatId = null
ctx.workspace = null
ctx.model = null
+ ctx.artifactMode = false
+ ctx.artifacts = []
+}
+
+// ── Chat-tools artifact mode (David 2026-06-12) ────────────────
+//
+// In PLAIN chat, "file writes" must behave like ChatGPT: the content is shown
+// IN the chat with a preview + download, never silently dumped to a folder.
+// useChat flips this on for the chat-tools run; executeFileWrite then captures
+// {name, content, mime} here instead of calling fs_write, and useAgentChat
+// drains the captures into the assistant message as `artifacts`. The Coding
+// Agent and full Agent mode leave this OFF and keep writing to disk.
+
+export function setChatArtifactMode(on: boolean): void {
+ ctx.artifactMode = !!on
+ if (!on) ctx.artifacts = []
+}
+
+export function isChatArtifactMode(): boolean {
+ return ctx.artifactMode
+}
+
+export function captureChatArtifact(name: string, content: string, mime: string): void {
+ ctx.artifacts.push({ name, content, mime })
+}
+
+/** Return the captured artifacts and clear the buffer (drain). */
+export function takeChatArtifacts(): CapturedArtifact[] {
+ const out = ctx.artifacts
+ ctx.artifacts = []
+ return out
}
// ── Multi-Repo Agent (Sprint C #8 from uselu) ──────────────────
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 3dc14091..2cc42a34 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -3,7 +3,7 @@
import type { MCPToolDefinition } from './types'
import type { ToolRegistry } from './tool-registry'
import { backendCall, fetchExternal } from '../backend'
-import { getActiveChatId, getActiveWorkspace } from '../agent-context'
+import { getActiveChatId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact } from '../agent-context'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
@@ -670,8 +670,39 @@ async function executeFileRead(args: Record<string, any>): Promise<string> {
return data.content || ''
}
+/** Last path segment, defaulting to file.txt. */
+function artifactBaseName(p: any): string {
+ const raw = typeof p === 'string' && p.trim() ? p.trim() : 'file.txt'
+ return raw.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || 'file.txt'
+}
+
+/** MIME from a filename extension — drives the in-chat artifact preview. */
+function mimeForName(name: string): string {
+ const ext = (name.split('.').pop() || '').toLowerCase()
+ const map: Record<string, string> = {
+ md: 'text/markdown', markdown: 'text/markdown', txt: 'text/plain',
+ json: 'application/json', js: 'text/javascript', mjs: 'text/javascript',
+ ts: 'text/typescript', tsx: 'text/typescript', jsx: 'text/javascript',
+ py: 'text/x-python', html: 'text/html', htm: 'text/html', css: 'text/css',
+ csv: 'text/csv', yml: 'text/yaml', yaml: 'text/yaml', xml: 'application/xml',
+ sh: 'text/x-shellscript', sql: 'text/plain', toml: 'text/plain',
+ rs: 'text/x-rust', go: 'text/x-go', java: 'text/x-java', c: 'text/x-c', cpp: 'text/x-c++',
+ }
+ return map[ext] || 'text/plain'
+}
+
async function executeFileWrite(args: Record<string, any>): Promise<string> {
- const data = await backendCall('fs_write', { path: args.path, content: args.content, ...chatCtx() })
+ const content = typeof args.content === 'string' ? args.content : String(args.content ?? '')
+ // Plain-chat artifact mode (ChatGPT-style, David 2026-06-12): in the NORMAL
+ // chat, a "file write" must NOT touch disk — capture it so it renders inline
+ // with a preview + Download button. The Coding Agent / full Agent leave
+ // artifact mode OFF and fall through to the real fs_write below.
+ if (isChatArtifactMode()) {
+ const name = artifactBaseName(args.path)
+ captureChatArtifact(name, content, mimeForName(name))
+ return `Created "${name}" (${formatBytes(content.length)}). It is shown to the user right here in the chat with a preview and a Download button — nothing was written to disk. Do not call file_read on it; just tell the user it's ready.`
+ }
+ const data = await backendCall('fs_write', { path: args.path, content, ...chatCtx() })
// Rust returns {status: 'saved', path: <absolute>}. Surface the real path
// so the model (and the file-change event) knows WHERE the write landed —
// especially important when chatId is None and Rust routes a relative path
diff --git a/src/components/chat/ChatArtifactCard.tsx b/src/components/chat/ChatArtifactCard.tsx
new file mode 100644
index 00000000..ab3df47c
--- /dev/null
+++ b/src/components/chat/ChatArtifactCard.tsx
@@ -0,0 +1,97 @@
+import { useState } from 'react'
+import { FileText, Download, Check, Copy } from 'lucide-react'
+import type { ChatArtifact } from '../../types/chat'
+import { isTauri, backendCall } from '../../api/backend'
+import { downloadFile } from '../../lib/chat-export'
+
+/**
+ * In-chat file artifact (David 2026-06-12). In PLAIN chat a "file write" never
+ * touches disk — the model's file lands here and shows like a ChatGPT artifact:
+ * filename + a scrollable preview + a Download button (native Save-As in Tauri,
+ * blob-download in the browser).
+ */
+
+function extOf(name: string): string {
+ const e = name.split('.').pop()
+ return e && e !== name ? e : 'txt'
+}
+
+const PREVIEW_LINES = 200
+
+export function ChatArtifactCard({ artifact }: { artifact: ChatArtifact }) {
+ const [copied, setCopied] = useState(false)
+ const [saveState, setSaveState] = useState<'idle' | 'saving' | 'done'>('idle')
+
+ const lines = artifact.content.split('\n')
+ const preview = lines.slice(0, PREVIEW_LINES).join('\n')
+ const hiddenLines = lines.length - Math.min(lines.length, PREVIEW_LINES)
+ const sizeLabel =
+ artifact.content.length < 1024
+ ? `${artifact.content.length} B`
+ : `${(artifact.content.length / 1024).toFixed(1)} KB`
+
+ const handleDownload = async () => {
+ if (saveState === 'saving') return
+ setSaveState('saving')
+ // Tauri → native Save-As (returns the path, or null when the user cancels).
+ // If the command itself throws, fall back to a blob download. Browser → blob.
+ if (isTauri()) {
+ try {
+ await backendCall<string | null>('save_text_file_dialog', {
+ content: artifact.content,
+ defaultName: artifact.name,
+ extension: extOf(artifact.name),
+ extLabel: extOf(artifact.name).toUpperCase(),
+ })
+ } catch {
+ downloadFile(artifact.content, artifact.name, artifact.mime)
+ }
+ } else {
+ downloadFile(artifact.content, artifact.name, artifact.mime)
+ }
+ setSaveState('done')
+ setTimeout(() => setSaveState('idle'), 2000)
+ }
+
+ const handleCopy = () => {
+ navigator.clipboard.writeText(artifact.content)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ }
+
+ return (
+ <div className="my-1 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02] overflow-hidden">
+ {/* Header: filename + meta + actions */}
+ <div className="flex items-center gap-2 px-2.5 py-1.5 border-b border-gray-200 dark:border-white/[0.06]">
+ <FileText size={13} className="text-blue-500 shrink-0" />
+ <span className="text-[0.72rem] font-medium text-gray-800 dark:text-gray-100 truncate flex-1" title={artifact.name}>
+ {artifact.name}
+ </span>
+ <span className="text-[0.55rem] text-gray-400 dark:text-gray-500 shrink-0 whitespace-nowrap">
+ {lines.length} {lines.length === 1 ? 'line' : 'lines'} · {sizeLabel}
+ </span>
+ <button
+ onClick={handleCopy}
+ title={copied ? 'Copied' : 'Copy contents'}
+ className="p-1 rounded text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors shrink-0"
+ >
+ {copied ? <Check size={12} className="text-green-500" /> : <Copy size={12} />}
+ </button>
+ <button
+ onClick={handleDownload}
+ disabled={saveState === 'saving'}
+ title="Download / Save as…"
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-500 hover:bg-blue-500/25 border border-blue-500/30 transition-colors disabled:opacity-50 shrink-0"
+ >
+ {saveState === 'done' ? <Check size={11} /> : <Download size={11} />}
+ <span>{saveState === 'done' ? 'Saved' : saveState === 'saving' ? '…' : 'Download'}</span>
+ </button>
+ </div>
+ {/* Scrollable preview */}
+ <pre className="px-2.5 py-1.5 text-[0.65rem] leading-snug text-gray-700 dark:text-gray-300 font-mono overflow-auto max-h-64 scrollbar-thin whitespace-pre">
+ {preview}
+ {hiddenLines > 0 ? `\n\n… ${hiddenLines} more line${hiddenLines === 1 ? '' : 's'} — download for the full file` : ''}
+ </pre>
+ </div>
+ )
+}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 8b7cccdd..b2e7f241 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -18,6 +18,11 @@ interface Props {
onApprove?: () => void
onReject?: () => void
disabled?: boolean
+ /**
+ * Enable the "/command" typeahead. Only the Coding Agent (Code view) sets this
+ * — slash commands belong there, not in the normal chat (David 2026-06-12).
+ */
+ slashCommands?: boolean
}
function fileToImageAttachment(file: File): Promise<ImageAttachment> {
@@ -33,7 +38,7 @@ function fileToImageAttachment(file: File): Promise<ImageAttachment> {
})
}
-export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApprove, onReject, disabled }: Props) {
+export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApprove, onReject, disabled, slashCommands }: Props) {
const [input, setInput] = useState('')
const [images, setImages] = useState<ImageAttachment[]>([])
const [isDragOver, setIsDragOver] = useState(false)
@@ -97,10 +102,12 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp
if (textareaRef.current) textareaRef.current.style.height = 'auto'
}
- // Update the input + the slash-command typeahead together.
+ // Update the input + the slash-command typeahead together. The typeahead is
+ // Coding-Agent-only — in the normal chat (slashCommands unset) "/foo" is just
+ // text and no menu appears.
const updateInput = (value: string) => {
setInput(value)
- const matches = matchAgentCommands(value)
+ const matches = slashCommands ? matchAgentCommands(value) : []
setCmdMenu(matches)
setCmdIndex(0)
}
@@ -200,7 +207,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp
{cmdMenu.length > 0 && (
<div className="absolute bottom-full left-0 right-0 mb-1.5 z-50 max-h-64 overflow-y-auto scrollbar-thin rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1f1f1f] shadow-xl py-1">
<div className="px-2.5 py-1 flex items-center gap-1 text-[0.5rem] uppercase tracking-widest text-gray-400 dark:text-gray-600">
- <Terminal size={9} /> Agent commands
+ <Terminal size={9} /> Coding commands
</div>
{cmdMenu.map((cmd, i) => (
<button
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 77bdd507..4dd92d09 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -224,7 +224,10 @@ export function CodexView() {
) : (
<div className="py-1">
{messages.filter(msg => !msg.hidden).map((msg) => {
- const cleanContent = msg.content ? stripChannelTags(msg.content) : ''
+ // Slash commands: the user typed "/review", but msg.content holds
+ // the expanded instruction the model ran on — show displayContent.
+ const rawForDisplay = msg.role === 'user' ? (msg.displayContent || msg.content) : msg.content
+ const cleanContent = rawForDisplay ? stripChannelTags(rawForDisplay) : ''
return (
<div
key={msg.id}
@@ -385,6 +388,7 @@ export function CodexView() {
onSend={(content) => sendInstruction(content)}
onStop={stopCodex}
isGenerating={isRunning}
+ slashCommands
/>
</div>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index a9294437..ff3b5196 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -7,6 +7,7 @@ import { ToolCallBlock } from './ToolCallBlock'
import { ReflectionBlock } from './ReflectionBlock'
import { VramSwitchCard } from './VramSwitchCard'
import { SpeakerButton } from './SpeakerButton'
+import { ChatArtifactCard } from './ChatArtifactCard'
import type { Message } from '../../types/chat'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { useChatStore } from '../../stores/chatStore'
@@ -302,6 +303,16 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
</div>
+ {/* Chat-tools artifacts (David 2026-06-12): files the model "wrote" in
+ plain chat — rendered inline with preview + Download, never on disk. */}
+ {!isUser && message.artifacts && message.artifacts.length > 0 && (
+ <div className="space-y-1">
+ {message.artifacts.map((a) => (
+ <ChatArtifactCard key={a.id} artifact={a} />
+ ))}
+ </div>
+ )}
+
{/* Action bar UNDER the message (David 2026-06-06: "eigene Leiste unter
der Nachricht" instead of cramped hover-icons in the corner). Bigger
targets, always visible but subtle; assistant left, user right. */}
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
index 36f49919..9f600ca9 100644
--- a/src/components/chat/TokenCounter.tsx
+++ b/src/components/chat/TokenCounter.tsx
@@ -28,7 +28,11 @@ export function TokenCounter() {
return sum + tokens
}, 0)
const usedTokens = lastUsage ? lastUsage.totalTokens : estimated
- const isReal = !!lastUsage
+ // "Real" = the model reported it. A provisional estimate the agent loop sets
+ // before the first reply (so the bar reflects the system prompt + tools, not a
+ // char/4 guess of the visible messages) carries `estimated:true` — show it, but
+ // don't claim it's the model's exact count.
+ const isReal = !!lastUsage && !lastUsage.estimated
if (!activeConversationId || messages.length === 0) return null
@@ -49,7 +53,9 @@ export function TokenCounter() {
: 'model context'
const title = isReal
? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — real, reported by the model (includes system prompt + tools + RAG)`
- : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — estimate until the first reply`
+ : lastUsage
+ ? `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — includes the system prompt + tools; the exact count lands when the model replies`
+ : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — estimate until the first reply`
return (
<div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={title}>
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index ad3db0e9..e64737fa 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -1,8 +1,8 @@
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, Database } from 'lucide-react'
+import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, Database, Download } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
-import { getComfyHost, getComfyPort } from '../../api/backend'
+import { getComfyHost, getComfyPort, downloadComfyFile } from '../../api/backend'
import { useModelPickStore } from '../../stores/modelPickStore'
import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './ModelPickerCard'
@@ -51,6 +51,24 @@ export function isInlineVideoUrl(url: string): boolean {
}
}
+// David 2026-06-12 ("alle tools in chat, mit download"): pull the ComfyUI
+// filename/subfolder/type back out of a /view URL so the inline image/video
+// gets a Download button (downloadComfyFile fetches the real bytes → native
+// Save-As in Tauri / anchor download in the browser). Returns null if the URL
+// has no filename. Exported for unit testing.
+export function comfyViewParams(url: string | null | undefined): { filename: string; subfolder: string; type: string } | null {
+ if (!url) return null
+ try {
+ const q = url.includes('?') ? url.slice(url.indexOf('?') + 1) : ''
+ const p = new URLSearchParams(q)
+ const filename = p.get('filename')
+ if (!filename) return null
+ return { filename, subfolder: p.get('subfolder') || '', type: p.get('type') || 'output' }
+ } catch {
+ return null
+ }
+}
+
interface Props {
toolCall: AgentToolCall
onApprove?: () => void
@@ -162,7 +180,7 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
else — including animated .webp — in an <img>. URL is bounded to OUR
ComfyUI by comfyViewUrlFromResult (never auto-loads arbitrary URLs). */}
{previewUrl && effectivePreviewUrl && (
- <div className="pl-5 pt-0.5">
+ <div className="pl-5 pt-0.5 space-y-1">
{isInlineVideoUrl(effectivePreviewUrl) ? (
<video
src={effectivePreviewUrl}
@@ -182,6 +200,22 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
/>
</a>
)}
+ {/* Download (David 2026-06-12): generated media shows in the chat with
+ a Download button, ChatGPT-style — downloadComfyFile pulls the real
+ bytes and saves via the native dialog. */}
+ {(() => {
+ const p = comfyViewParams(effectivePreviewUrl)
+ if (!p) return null
+ return (
+ <button
+ onClick={() => { void downloadComfyFile(p.filename, p.subfolder, p.type) }}
+ title="Download"
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-500 hover:bg-blue-500/25 border border-blue-500/30 transition-colors"
+ >
+ <Download size={11} /> Download
+ </button>
+ )
+ })()}
</div>
)}
diff --git a/src/components/chat/__tests__/ToolCallBlock-image.test.ts b/src/components/chat/__tests__/ToolCallBlock-image.test.ts
index 3ae643f7..1ec66775 100644
--- a/src/components/chat/__tests__/ToolCallBlock-image.test.ts
+++ b/src/components/chat/__tests__/ToolCallBlock-image.test.ts
@@ -11,7 +11,7 @@
* Run: npx vitest run src/components/chat/__tests__/ToolCallBlock-image.test.ts
*/
import { describe, it, expect, afterEach } from 'vitest'
-import { comfyViewUrlFromResult, isInlineVideoUrl } from '../ToolCallBlock'
+import { comfyViewUrlFromResult, isInlineVideoUrl, comfyViewParams } from '../ToolCallBlock'
import { setComfyHost, getComfyHost } from '../../../api/backend'
describe('comfyViewUrlFromResult', () => {
@@ -130,3 +130,28 @@ describe('isInlineVideoUrl', () => {
expect(isInlineVideoUrl('/comfyui/view?filename=clip.mp4&subfolder=&type=output')).toBe(true)
})
})
+
+// David 2026-06-12: the inline image/video gets a Download button that pulls the
+// ComfyUI filename/subfolder/type back out of the /view URL.
+describe('comfyViewParams', () => {
+ it('parses an absolute /view URL (drops the cache-buster)', () => {
+ expect(comfyViewParams('http://localhost:8188/view?filename=apple.png&subfolder=&type=output&t=123'))
+ .toEqual({ filename: 'apple.png', subfolder: '', type: 'output' })
+ })
+
+ it('keeps a non-empty subfolder', () => {
+ expect(comfyViewParams('http://localhost:8188/view?filename=clip.mp4&subfolder=vids&type=output'))
+ .toEqual({ filename: 'clip.mp4', subfolder: 'vids', type: 'output' })
+ })
+
+ it('parses the relative /comfyui/view proxy path and defaults type to output', () => {
+ expect(comfyViewParams('/comfyui/view?filename=foo.webp&subfolder='))
+ .toEqual({ filename: 'foo.webp', subfolder: '', type: 'output' })
+ })
+
+ it('returns null without a filename or url', () => {
+ expect(comfyViewParams('http://localhost:8188/view?subfolder=&type=output')).toBeNull()
+ expect(comfyViewParams(null)).toBeNull()
+ expect(comfyViewParams('')).toBeNull()
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 1eaf7365..f78629c6 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,7 +1,7 @@
import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
import { chatNonStreaming } from '../api/agents'
-import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection } from '../api/agent-context'
+import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
@@ -20,7 +20,7 @@ import { log } from '../lib/logger'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'
import { buildVisionFeedback } from '../api/vision-feedback'
-import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
+import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { getModelContextCached } from '../api/ollama'
import { effectiveContextWindow } from '../lib/context-window'
import { useMemoryStore } from '../stores/memoryStore'
@@ -292,6 +292,11 @@ export function useAgentChat() {
})
setActiveWorkspace(resolvedWorkspace)
+ // Chat-tools (plain chat) → "file writes" become in-chat artifacts (preview
+ // + download), never disk writes (ChatGPT-style, David 2026-06-12). Full
+ // Agent mode keeps writing to disk, so this is ON only for chatToolsMode.
+ setChatArtifactMode(opts?.chatToolsMode === true)
+
// Feature EE (v2.5.0) — pin the text model driving this loop so the VRAM
// hand-off orchestrator (image/video generation) knows which model to
// evict-then-reload around a ComfyUI run. We use the already-resolved
@@ -612,6 +617,23 @@ export function useAgentChat() {
}))
let turn!: { content: string; toolCalls: ToolCall[]; thinking?: string; promptEvalCount?: number; evalCount?: number }
+
+ // Token counter (David 2026-06-12): reflect the REAL prompt size — system
+ // prompt + tool defs + history — immediately, not a char/4 guess of just
+ // the visible messages. Provisional estimate the model's exact count
+ // overwrites below; only set while no real count has landed yet.
+ {
+ const existingUsage = useChatStore.getState().conversations
+ .find((c) => c.id === convId)?.messages.find((m) => m.id === assistantMessage.id)?.usage
+ if (!existingUsage || existingUsage.estimated) {
+ const estPrompt =
+ estimateTokens(agentMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
+ estimateTokens(JSON.stringify(tools))
+ useChatStore.getState().updateMessageUsage(convId!, assistantMessage.id, {
+ promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
+ })
+ }
+ }
if (providerId === 'ollama') {
// Streaming path — parity with desktop Codex. Without this
// the user stared at a frozen chat for 30-90 s while Gemma
@@ -745,6 +767,7 @@ export function useAgentChat() {
promptTokens: turn.promptEvalCount || 0,
completionTokens: turn.evalCount || 0,
totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
+ estimated: false,
})
}
// Native thinking field from Ollama
@@ -1268,6 +1291,17 @@ export function useAgentChat() {
setIsAgentRunning(false)
runningRef.current = false
abortRef.current = null
+ // Chat-tools artifact mode: attach any files the model "wrote" (captured
+ // in-memory, NOT on disk) to the assistant message so they render inline
+ // with a preview + Download button. takeChatArtifacts drains the buffer;
+ // clearActiveChatId() then resets the mode for the next run.
+ const capturedArtifacts = takeChatArtifacts()
+ if (capturedArtifacts.length) {
+ useChatStore.getState().updateMessageArtifacts(
+ convId!, assistantMessage.id,
+ capturedArtifacts.map((a) => ({ id: uuid(), name: a.name, content: a.content, mime: a.mime })),
+ )
+ }
// Drop the per-run workspace scope so standalone tool calls from
// other tabs don't accidentally land in this chat's folder.
clearActiveChatId()
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index b5fd7b47..a2171182 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -13,7 +13,6 @@ import { useAgentChat } from "./useAgentChat"
import { useMemory } from "./useMemory"
import { useAgentModeStore } from "../stores/agentModeStore"
import { detectChatToolIntent, CHAT_TOOLS } from "../lib/chat-tool-intent"
-import { parseAgentCommand } from "../lib/agent-commands"
import { getProviderForModel, getProviderIdFromModel } from "../api/providers"
import { syncOllamaHealthFromError } from "../lib/sync-ollama-health"
import { isThinkingCompatible, isPlainTextPlanner } from "../lib/model-compatibility"
@@ -42,21 +41,11 @@ export function useChat() {
const store = useChatStore.getState()
const persona = useSettingsStore.getState().getActivePersona()
- // Agent slash commands (David 2026-06-11): "/review", "/commit", "/test",
- // … are shorthand for an AGENT task. Expand the template, enable agent mode
- // for this conversation (so the run has the full tool catalog + the agent
- // UI), and hand the expanded instruction to the agent executor. The raw
- // "/cmd args" the user typed is shown as their message; the expansion drives
- // the model. Unknown "/foo" returns null and falls through to normal chat.
- if (activeModel) {
- const slash = parseAgentCommand(content)
- if (slash) {
- let convId = store.activeConversationId
- if (!convId) convId = store.createConversation(activeModel, persona?.systemPrompt || "")
- useAgentModeStore.getState().setAgentModeActive(convId, true)
- return agentChat.sendAgentMessage(slash.expanded, images, { displayContent: content })
- }
- }
+ // NB: slash commands ("/review", "/commit", …) are NOT handled here — they
+ // belong to the Coding Agent (Code view), not the normal chat/agent (David
+ // 2026-06-12). useCodex.sendInstruction expands them there; in plain chat a
+ // "/cmd" is just ordinary text. The normal Agent gets its own commands later
+ // (slash loop / remember / scheduler).
// Agent mode delegation: if active for this conversation, use agent chat
if (store.activeConversationId && useAgentModeStore.getState().isActive(store.activeConversationId)) {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index b1abc2b3..4624b4f6 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -14,6 +14,7 @@ import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspa
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
import { loadLurules, renderRulesSection, type RulesReader } from '../lib/lurules'
+import { parseAgentCommand } from '../lib/agent-commands'
import { backendCall, isOllamaLocal } from '../api/backend'
import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'
import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'
@@ -35,7 +36,7 @@ import { extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair
import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
-import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
+import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { useMemoryStore } from '../stores/memoryStore'
import { extractMemoriesFromPair } from './useMemory'
import type { OllamaChatMessage } from '../types/agent-mode'
@@ -185,10 +186,21 @@ export function useCodex() {
const abortRef = useRef<AbortController | null>(null)
const runningRef = useRef(false)
- const sendInstruction = useCallback(async (instruction: string) => {
+ const sendInstruction = useCallback(async (rawInstruction: string, opts?: { displayContent?: string }) => {
const { activeModel } = useModelStore.getState()
if (!activeModel) return
+ // Coding-Agent slash commands (David 2026-06-12): "/review", "/commit",
+ // "/test", … live HERE, in the Code view — its full file_*/shell/git tools
+ // + working directory are exactly what these templates drive. Expand the
+ // command to the full instruction the model acts on; the raw "/cmd args" is
+ // shown as the user's message (displayContent). A non-command input passes
+ // through unchanged. (They were briefly wired into the normal chat — David
+ // moved them here, where they belong.)
+ const slash = parseAgentCommand(rawInstruction)
+ const instruction = slash ? slash.expanded : rawInstruction
+ const displayInstruction = slash ? rawInstruction : opts?.displayContent
+
const store = useChatStore.getState()
const codexStore = useCodexStore.getState()
const { settings } = useSettingsStore.getState()
@@ -244,9 +256,11 @@ export function useCodex() {
id: uuid(), type: 'instruction', content: instruction, timestamp: Date.now(),
})
- // Add user message to chat store
+ // Add user message to chat store. For a slash command the UI shows the raw
+ // "/cmd args" (displayContent) while the model receives the expansion.
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'user', content: instruction, timestamp: Date.now(),
+ ...(displayInstruction ? { displayContent: displayInstruction } : {}),
})
// Add empty assistant message
@@ -679,6 +693,23 @@ export function useCodex() {
if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return
useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c)
}
+ // Token counter (David 2026-06-12): reflect the REAL prompt size —
+ // system prompt + tool defs + repo map + history — immediately, not a
+ // char/4 guess of just the visible messages. Provisional estimate that
+ // the model's exact count overwrites below; only (re)set while no real
+ // count has landed yet, so a real value is never downgraded.
+ {
+ const existingUsage = useChatStore.getState().conversations
+ .find((c) => c.id === convId)?.messages.find((m) => m.id === assistantMsg.id)?.usage
+ if (!existingUsage || existingUsage.estimated) {
+ const estPrompt =
+ estimateTokens(messages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
+ estimateTokens(JSON.stringify(tools))
+ useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
+ promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
+ })
+ }
+ }
try {
void diagLog('streamWithTools-enter', { iter: i, messagesLen: messages.length, toolsCount: tools.length, thinking: chatOptions.thinking })
turn = await streamWithTools(
@@ -723,6 +754,7 @@ export function useCodex() {
promptTokens: turn.promptEvalCount || 0,
completionTokens: turn.evalCount || 0,
totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
+ estimated: false,
})
}
void diagLog('streamWithTools-return', {
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index bae67326..db09dbd8 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -1,7 +1,7 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
-import type { Conversation, Message } from '../types/chat'
+import type { Conversation, Message, ChatArtifact } from '../types/chat'
import type { AgentBlock } from '../types/agent-mode'
import { idbStorage } from '../lib/idbStorage'
import { migrateBlockInPlace } from '../api/agents/block-helpers'
@@ -42,8 +42,9 @@ interface ChatState {
insertMessageBefore: (conversationId: string, beforeId: string, message: Message) => void
updateMessageContent: (conversationId: string, messageId: string, content: string) => void
updateMessageThinking: (conversationId: string, messageId: string, thinking: string) => void
- updateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number }) => void
+ updateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }) => void
updateMessageAgentBlocks: (conversationId: string, messageId: string, blocks: AgentBlock[]) => void
+ updateMessageArtifacts: (conversationId: string, messageId: string, artifacts: ChatArtifact[]) => void
deleteMessagesAfter: (conversationId: string, messageId: string) => void
getActiveConversation: () => Conversation | undefined
searchConversations: (query: string) => Conversation[]
@@ -195,6 +196,19 @@ export const useChatStore = create<ChatState>()(
),
})),
+ updateMessageArtifacts: (conversationId, messageId, artifacts) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) =>
+ c.id === conversationId
+ ? {
+ ...c,
+ messages: c.messages.map((m) => (m.id === messageId ? { ...m, artifacts } : m)),
+ updatedAt: Date.now(),
+ }
+ : c
+ ),
+ })),
+
deleteMessagesAfter: (conversationId, messageId) =>
set((state) => ({
conversations: state.conversations.map((c) => {
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 2112668b..ad0eb3c2 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -8,6 +8,22 @@ export interface ImageAttachment {
name: string // filename
}
+/**
+ * A chat-tools "artifact": a file the model produced in PLAIN chat. In chat
+ * mode `file_write` does NOT touch disk (ChatGPT-style) — the content lands in
+ * the message and renders inline with a preview + Download button. (The Coding
+ * Agent still writes to its real working directory.)
+ */
+export interface ChatArtifact {
+ id: string
+ /** Filename the model chose, e.g. "report.md". */
+ name: string
+ /** The text content the model "wrote". */
+ content: string
+ /** MIME type, derived from the extension — drives the preview. */
+ mime: string
+}
+
export interface Message {
id: string
role: Role
@@ -24,6 +40,9 @@ export interface Message {
// Agent Mode fields
agentBlocks?: AgentBlock[]
toolCallSummary?: string
+ /** Chat-tools artifacts — files "written" in plain chat, rendered inline
+ * with preview + Download (never touch disk). See ChatArtifact. */
+ artifacts?: ChatArtifact[]
// Continue capability — tool-call history persisted between turns so
// the model sees what it did before (parity with original Codex CLI).
// Hidden messages are included in the API payload but not rendered.
@@ -33,7 +52,12 @@ export interface Message {
// OpenAI/LM-Studio usage.*). promptTokens = the FULL consumed context for that
// turn (system prompt + tools + RAG + history + input), so it powers a
// 100%-real context readout instead of a char/4 estimate.
- usage?: { promptTokens: number; completionTokens: number; totalTokens: number }
+ // promptTokens = the FULL consumed context (system prompt + tools + RAG +
+ // history + input). `estimated` is true for the provisional value the agent
+ // loop sets BEFORE the model replies (so the counter isn't a tiny char/4 guess
+ // of only the visible messages); it flips to false once the model reports the
+ // exact prompt_eval_count / usage.prompt_tokens.
+ usage?: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }
}
export interface Conversation {