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: Agent Mode (Beta) — tool calling, memory system, UI redesign

PurpleDoubleD55cc3fd59e07
diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rs
index fcd0e80f..30241834 100644
--- a/src-tauri/src/commands/search.rs
+++ b/src-tauri/src/commands/search.rs
@@ -50,7 +50,7 @@ async fn try_searxng(query: &str, count: usize) -> Result<Vec<SearchResult>, Str
async fn try_ddg(query: &str, count: usize) -> Result<Vec<SearchResult>, String> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
- .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
+ .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
.build()
.map_err(|e| e.to_string())?;
@@ -62,22 +62,43 @@ async fn try_ddg(query: &str, count: usize) -> Result<Vec<SearchResult>, String>
let html = resp.text().await.map_err(|e| e.to_string())?;
- // Parse results from HTML using regex
- let title_re = regex::Regex::new(r#"class="result__a"[^>]*>([^<]+)</a>"#).unwrap();
- let url_re = regex::Regex::new(r#"class="result__url"[^>]*href="([^"]+)">"#).unwrap();
- let snippet_re = regex::Regex::new(r#"class="result__snippet"[^>]*>([^<]+)"#).unwrap();
-
- let titles: Vec<String> = title_re.captures_iter(&html).map(|c| c[1].to_string()).collect();
- let urls: Vec<String> = url_re.captures_iter(&html).map(|c| c[1].to_string()).collect();
- let snippets: Vec<String> = snippet_re.captures_iter(&html).map(|c| c[1].to_string()).collect();
+ // Parse results — capture full inner HTML then strip tags
+ let title_re = regex::Regex::new(r#"class="result__a"[^>]*>(.*?)</a>"#).unwrap();
+ let url_re = regex::Regex::new(r#"class="result__url"[^>]*?href="([^"]*)"#).unwrap();
+ let snippet_re = regex::Regex::new(r#"class="result__snippet"[^>]*>([\s\S]*?)</(?:td|div|a\s)"#).unwrap();
+
+ let titles: Vec<String> = title_re.captures_iter(&html)
+ .map(|c| html_decode(&strip_html(&c[1])))
+ .collect();
+ let urls: Vec<String> = url_re.captures_iter(&html)
+ .map(|c| {
+ let raw = &c[1];
+ // DDG wraps URLs — extract actual URL from redirect
+ if let Some(pos) = raw.find("uddg=") {
+ let after = &raw[pos + 5..];
+ urlencoding::decode(after.split('&').next().unwrap_or(after))
+ .unwrap_or_else(|_| after.into())
+ .to_string()
+ } else {
+ raw.to_string()
+ }
+ })
+ .collect();
+ let snippets: Vec<String> = snippet_re.captures_iter(&html)
+ .map(|c| html_decode(&strip_html(&c[1])).trim().to_string())
+ .collect();
let mut results = Vec::new();
for i in 0..titles.len().min(count) {
- results.push(SearchResult {
- title: html_decode(&titles[i]),
- url: urls.get(i).cloned().unwrap_or_default(),
- snippet: snippets.get(i).map(|s| html_decode(s)).unwrap_or_default(),
- });
+ let url = urls.get(i).cloned().unwrap_or_default();
+ let snippet = snippets.get(i).cloned().unwrap_or_default();
+ if !url.is_empty() {
+ results.push(SearchResult {
+ title: titles[i].clone(),
+ url,
+ snippet,
+ });
+ }
}
if results.is_empty() {
diff --git a/src/api/backend.ts b/src/api/backend.ts
index cfa58936..6af3c533 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -183,6 +183,51 @@ export function comfyuiWsUrl(): string {
return "ws://localhost:8188/ws";
}
+/** Download a ComfyUI output file — works in both dev and Tauri mode */
+export async function downloadComfyFile(filename: string, subfolder: string = '', type: string = 'output'): Promise<void> {
+ const params = new URLSearchParams({ filename, subfolder, type })
+ const url = comfyuiUrl(`/view?${params.toString()}`)
+
+ if (!isTauri()) {
+ // Dev mode: direct anchor download
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ return
+ }
+
+ // Tauri mode: fetch bytes through proxy, create blob URL
+ const invoke = await getInvoke()
+ try {
+ const bytes = await invoke('proxy_localhost_stream', {
+ url,
+ method: 'GET',
+ body: null,
+ }) as number[]
+ const blob = new Blob([new Uint8Array(bytes)])
+ const blobUrl = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = blobUrl
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(blobUrl)
+ } catch (err) {
+ console.error('[downloadComfyFile] Failed:', err)
+ // Fallback: try direct link
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ }
+}
+
/** Fetch an external URL as text — works in both Tauri and dev mode */
export async function fetchExternal(url: string): Promise<string> {
if (isTauri()) {
diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.ts
new file mode 100644
index 00000000..81da8541
--- /dev/null
+++ b/src/api/comfyui-ws.ts
@@ -0,0 +1,146 @@
+/**
+ * ComfyUI WebSocket client for real-time generation progress.
+ *
+ * Connects to ws://localhost:8188/ws and provides events for:
+ * - Model loading (CheckpointLoaderSimple, UNETLoader, CLIPLoader, VAELoader)
+ * - Sampling progress (KSampler step value/max)
+ * - Execution completion / errors
+ */
+
+import { v4 as uuid } from 'uuid'
+
+export type ComfyWSEvent =
+ | { type: 'status'; data: { queue_remaining: number } }
+ | { type: 'execution_start'; data: { prompt_id: string } }
+ | { type: 'executing'; data: { node: string | null; prompt_id: string } }
+ | { type: 'progress'; data: { value: number; max: number; prompt_id: string } }
+ | { type: 'executed'; data: { node: string; prompt_id: string } }
+ | { type: 'execution_complete'; data: { prompt_id: string } }
+ | { type: 'execution_error'; data: { prompt_id: string; exception_message?: string; node_type?: string } }
+ | { type: 'execution_cached'; data: { prompt_id: string; nodes: string[] } }
+
+export type ComfyWSListener = (event: ComfyWSEvent) => void
+
+// Loader node class types that indicate model loading
+export const LOADER_NODES = new Set([
+ 'CheckpointLoaderSimple', 'UNETLoader', 'CheckpointLoader',
+])
+export const CLIP_LOADER_NODES = new Set([
+ 'CLIPLoader', 'DualCLIPLoader', 'TripleCLIPLoader', 'CLIPVisionLoader',
+])
+export const VAE_LOADER_NODES = new Set([
+ 'VAELoader',
+])
+export const SAMPLER_NODES = new Set([
+ 'KSampler', 'KSamplerAdvanced', 'SamplerCustom', 'SamplerCustomAdvanced',
+])
+export const DECODE_NODES = new Set([
+ 'VAEDecode', 'VAEDecodeTiled',
+])
+
+/** Shared client ID used for both WS connection and workflow submission */
+export const CLIENT_ID = uuid()
+
+class ComfyWSClient {
+ private ws: WebSocket | null = null
+ private listeners = new Set<ComfyWSListener>()
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null
+ private reconnectDelay = 1000
+ private maxReconnectDelay = 30000
+ private _connected = false
+ private connectPromise: Promise<void> | null = null
+
+ get connected() { return this._connected }
+
+ /** Connect and return a promise that resolves when the WS is open */
+ connect(timeoutMs = 3000): Promise<void> {
+ if (this._connected && this.ws?.readyState === WebSocket.OPEN) {
+ return Promise.resolve()
+ }
+ if (this.connectPromise) return this.connectPromise
+
+ this.connectPromise = new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.connectPromise = null
+ reject(new Error('WebSocket connect timeout'))
+ }, timeoutMs)
+
+ try {
+ this.ws = new WebSocket(`ws://localhost:8188/ws?clientId=${CLIENT_ID}`)
+
+ this.ws.onopen = () => {
+ clearTimeout(timer)
+ this._connected = true
+ this.reconnectDelay = 1000
+ this.connectPromise = null
+ console.log('[ComfyWS] Connected')
+ resolve()
+ }
+
+ this.ws.onmessage = (ev) => {
+ try {
+ const msg = JSON.parse(ev.data)
+ if (msg.type && msg.data) {
+ const event = msg as ComfyWSEvent
+ for (const listener of this.listeners) {
+ listener(event)
+ }
+ }
+ } catch { /* ignore non-JSON messages */ }
+ }
+
+ this.ws.onclose = () => {
+ this._connected = false
+ this.ws = null
+ this.connectPromise = null
+ this.scheduleReconnect()
+ }
+
+ this.ws.onerror = () => {
+ clearTimeout(timer)
+ this._connected = false
+ this.connectPromise = null
+ // onclose will fire after onerror
+ }
+ } catch {
+ clearTimeout(timer)
+ this.connectPromise = null
+ reject(new Error('WebSocket creation failed'))
+ }
+ })
+
+ return this.connectPromise
+ }
+
+ private scheduleReconnect() {
+ if (this.reconnectTimer) return
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = null
+ this.connect().catch(() => {
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay)
+ })
+ }, this.reconnectDelay)
+ }
+
+ on(listener: ComfyWSListener) {
+ this.listeners.add(listener)
+ return () => { this.listeners.delete(listener) }
+ }
+
+ disconnect() {
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer)
+ this.reconnectTimer = null
+ }
+ if (this.ws) {
+ this.ws.onclose = null
+ this.ws.close()
+ this.ws = null
+ }
+ this._connected = false
+ this.connectPromise = null
+ }
+}
+
+/** Singleton WebSocket client */
+export const comfyWS = new ComfyWSClient()
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index ce6982cc..93c79c1b 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -372,10 +372,12 @@ async function findAnimateDiffModel(): Promise<string> {
// ─── Workflow Submission ───
-export async function submitWorkflow(workflow: Record<string, any>): Promise<string> {
+export async function submitWorkflow(workflow: Record<string, any>, clientId?: string): Promise<string> {
+ const payload: Record<string, any> = { prompt: workflow }
+ if (clientId) payload.client_id = clientId
const res = await localFetch(comfyuiUrl('/prompt'), {
method: 'POST',
- body: JSON.stringify({ prompt: workflow }),
+ body: JSON.stringify(payload),
})
if (!res.ok) {
const rawText = await res.text().catch(() => '')
diff --git a/src/api/discover.ts b/src/api/discover.ts
index a2f6522a..ee37265d 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -12,6 +12,9 @@ export interface DiscoverModel {
filename?: string
subfolder?: string // ComfyUI models subfolder: checkpoints, diffusion_models, vae, text_encoders
sizeGB?: number
+ // Discovery flags
+ hot?: boolean // Featured/trending model
+ agent?: boolean // Supports Agent Mode tool calling
}
export interface DownloadProgress {
@@ -125,8 +128,18 @@ export const COMPONENT_REGISTRY: Record<ModelType, ComponentRequirements> = {
// ─── Ollama Text Models ───
+/** Get featured HOT models (always shown at top of discover) */
+export function getHotTextModels(): DiscoverModel[] {
+ return getCuratedTextModels().filter(m => m.hot)
+}
+
export async function fetchAbliteratedModels(): Promise<DiscoverModel[]> {
- return searchOllamaModels('abliterated')
+ const hotModels = getHotTextModels()
+ const searchResults = await searchOllamaModels('abliterated')
+ // Merge: HOT first, then search results (deduplicated)
+ const hotNames = new Set(hotModels.map(m => m.name))
+ const deduped = searchResults.filter(m => !hotNames.has(m.name))
+ return [...hotModels, ...deduped]
}
/** Search Ollama registry — works in both Tauri and dev mode */
@@ -194,9 +207,15 @@ function parseOllamaSearchHTML(html: string): DiscoverModel[] {
function getCuratedTextModels(): DiscoverModel[] {
return [
+ // ── HOT: Agent Mode + Uncensored ──
+ { name: 'hermes3', description: 'NousResearch Hermes 3 — uncensored + native tool calling. THE agent model.', pulls: '500K+', tags: ['3B', '8B', '70B', '405B'], updated: 'Hot', hot: true, agent: true },
+ { name: 'dolphin3', description: 'Dolphin 3 — uncensored from training. Coding, math, general purpose.', pulls: '3.7M', tags: ['8B'], updated: 'Hot', hot: true },
+ { name: 'huihui_ai/qwen3.5-abliterated', description: 'Qwen 3.5 abliterated — newest, strongest reasoning + coding.', pulls: '10K+', tags: ['8B', '14B', '32B'], updated: 'Hot', hot: true },
+ // ── Popular Uncensored ──
{ name: 'huihui_ai/qwen3-abliterated', description: 'Qwen3 abliterated — best overall. Exceptional reasoning, coding, multilingual.', pulls: '30K+', tags: ['8B', '30B'], updated: 'Popular' },
{ name: 'mannix/llama3.1-8b-abliterated', description: 'Llama 3.1 8B — fast, reliable, great entry point.', pulls: '200K+', tags: ['8B', 'Q5_K_M'], updated: 'Popular' },
{ name: 'huihui_ai/deepseek-r1-abliterated', description: 'DeepSeek R1 — chain-of-thought reasoning. Scales to your hardware.', pulls: '40K+', tags: ['8B', '14B', '32B', '70B'], updated: 'Popular' },
+ { name: 'huihui_ai/gpt-oss-abliterated', description: 'OpenAI GPT-OSS — abliterated open-source GPT model.', pulls: '15K+', tags: ['8B', '32B'], updated: 'Hot', hot: true },
{ name: 'huihui_ai/glm4.6-abliterated', description: 'GLM 4.6 abliterated — newest model, strong coding and reasoning.', pulls: '5K+', tags: ['9B'], updated: 'New' },
{ name: 'huihui_ai/gemma3-abliterated', description: 'Google Gemma 3 — vision support, great quality.', pulls: '20K+', tags: ['4B', '12B', '27B'], updated: 'Popular' },
{ name: 'richardyoung/qwen3-14b-abliterated', description: 'Qwen3 14B — sweet spot of speed and intelligence.', pulls: '4K+', tags: ['14B', 'Q4_K_M'], updated: 'Recent' },
@@ -252,6 +271,7 @@ export function getImageBundles(): ModelBundle[] {
name: 'FLUX.1 [schnell] FP8 (Fast & Modern)',
description: 'State-of-the-art image gen. 1-4 steps for fast results. Complete package with all required encoders.',
tags: ['FLUX', 'Fast', 'FP8', '1024px'],
+ hot: true,
totalSizeGB: 16,
vramRequired: '8-10 GB',
workflow: 'wan',
@@ -330,6 +350,7 @@ export function getImageBundles(): ModelBundle[] {
name: 'FLUX 2 Klein 4B (Next-Gen)',
description: 'Latest FLUX architecture. Fastest FLUX model with stunning quality. Includes Qwen 3 text encoder.',
tags: ['FLUX 2', 'Fast', '1024px'],
+ hot: true,
totalSizeGB: 8,
vramRequired: '8-10 GB',
workflow: 'wan',
@@ -387,6 +408,7 @@ export interface ModelBundle {
workflow: 'wan' | 'hunyuan' | 'animatediff'
files: DiscoverModel[]
url?: string
+ hot?: boolean
}
export function getVideoBundles(): ModelBundle[] {
@@ -395,6 +417,7 @@ export function getVideoBundles(): ModelBundle[] {
name: 'Wan 2.1 — 1.3B (Lightweight)',
description: 'Best for 8-10 GB VRAM GPUs. Generates 480p video. Fast and lightweight.',
tags: ['Wan 2.1', '480p', 'Fast'],
+ hot: true,
totalSizeGB: 7.6,
vramRequired: '8-10 GB',
workflow: 'wan',
diff --git a/src/api/hermes-tool-calling.ts b/src/api/hermes-tool-calling.ts
new file mode 100644
index 00000000..dcaae16b
--- /dev/null
+++ b/src/api/hermes-tool-calling.ts
@@ -0,0 +1,114 @@
+/**
+ * Hermes XML-Tag Tool Calling — Prompt-Based Fallback
+ *
+ * Works with ANY model (abliterated, uncensored, standard, small, large).
+ * Uses the Hermes/NousResearch format:
+ * - Tools described in <tools></tools> XML block in system prompt
+ * - Model responds with <tool_call>{"name": ..., "arguments": ...}</tool_call>
+ * - Results injected as <tool_response>...</tool_response>
+ *
+ * Reference: https://github.com/NousResearch/Hermes-Function-Calling
+ */
+
+import type { AgentToolDef } from '../types/agent-mode'
+
+// ── Build System Prompt with Tool Definitions ───────────────────
+
+export function buildHermesToolPrompt(tools: AgentToolDef[]): string {
+ const toolDefs = tools.map((t) => JSON.stringify({
+ type: 'function',
+ function: {
+ name: t.name,
+ description: t.description,
+ parameters: t.parameters,
+ },
+ })).join('\n')
+
+ return `You are a function calling AI model. You are provided with function signatures within <tools></tools> XML tags. You may call one or more functions to assist with the user query. Don't make assumptions about what values to plug into functions. Ask for clarification if needed.
+
+<tools>
+${toolDefs}
+</tools>
+
+For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
+<tool_call>
+{"name": <function-name>, "arguments": <args-json-object>}
+</tool_call>
+
+IMPORTANT: web_search returns ONLY short snippets, NOT real data. You MUST ALWAYS call web_fetch on the best URL to read actual page content before answering.
+
+Workflow: web_search → get URLs → web_fetch → read page → answer based on real data.
+Other tools: file_read, file_write, code_execute, image_generate.
+Respond in the same language the user uses.`
+}
+
+// ── Build Tool Result Message ───────────────────────────────────
+
+export function buildHermesToolResult(toolName: string, result: string): string {
+ return `<tool_response>
+{"name": "${toolName}", "content": ${JSON.stringify(result)}}
+</tool_response>`
+}
+
+// ── Parse Tool Calls from Model Output ──────────────────────────
+
+export interface ParsedToolCall {
+ name: string
+ arguments: Record<string, any>
+}
+
+/**
+ * Parse Hermes-format tool calls from model output.
+ * Looks for <tool_call>...</tool_call> XML tags containing JSON.
+ * Returns array of parsed tool calls (can be 0 or more).
+ */
+export function parseHermesToolCalls(output: string): ParsedToolCall[] {
+ const calls: ParsedToolCall[] = []
+
+ // Match all <tool_call>...</tool_call> blocks
+ const regex = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g
+ let match: RegExpExecArray | null
+
+ while ((match = regex.exec(output)) !== null) {
+ const jsonStr = match[1].trim()
+ try {
+ const parsed = JSON.parse(jsonStr)
+ if (parsed.name) {
+ calls.push({
+ name: parsed.name,
+ arguments: parsed.arguments || parsed.parameters || {},
+ })
+ }
+ } catch {
+ // Try to extract name and arguments with regex fallback
+ const nameMatch = jsonStr.match(/"name"\s*:\s*"([^"]+)"/)
+ const argsMatch = jsonStr.match(/"arguments"\s*:\s*(\{[^}]*\})/)
+ if (nameMatch) {
+ let args = {}
+ if (argsMatch) {
+ try { args = JSON.parse(argsMatch[1]) } catch { /* ignore */ }
+ }
+ calls.push({ name: nameMatch[1], arguments: args })
+ }
+ }
+ }
+
+ return calls
+}
+
+/**
+ * Strip tool call tags from model output to get clean content.
+ */
+export function stripToolCallTags(output: string): string {
+ return output
+ .replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '')
+ .replace(/<tool_response>[\s\S]*?<\/tool_response>/g, '')
+ .trim()
+}
+
+/**
+ * Check if model output contains any tool call tags.
+ */
+export function hasToolCallTags(output: string): boolean {
+ return /<tool_call>/.test(output)
+}
diff --git a/src/api/model-template-fix.ts b/src/api/model-template-fix.ts
new file mode 100644
index 00000000..a05909cd
--- /dev/null
+++ b/src/api/model-template-fix.ts
@@ -0,0 +1,235 @@
+/**
+ * Model Template Fix for Agent Mode
+ *
+ * Abliterated/uncensored models lose their tool-calling template during modification.
+ * This module can "fix" them by creating a new Ollama model variant with the correct
+ * tool-calling template re-applied. The model weights are the same — only the template changes.
+ *
+ * Flow:
+ * 1. Detect model family (llama, qwen, etc.) via `ollama show`
+ * 2. Look up the correct tool-calling template for that family
+ * 3. Create a new model via `ollama create` with: FROM <original> + TEMPLATE <tool-template>
+ * 4. The new model name is: <original>-agent (e.g. "mannix/llama3.1-8b-abliterated:agent")
+ */
+
+import { localFetch, localFetchStream, ollamaUrl } from './backend'
+
+// ── Tool-Calling Templates per Model Family ───────────────────────
+
+const LLAMA31_TOOL_TEMPLATE = `{{ if .Messages }}
+{{- if or .System .Tools }}<|start_header_id|>system<|end_header_id|>
+{{- if .System }}
+{{ .System }}
+{{- end }}
+{{- if .Tools }}
+You are a helpful assistant with tool calling capabilities. When you receive a tool call response, use the output to format an answer to the orginal use question.
+{{- end }}<|eot_id|>
+{{- end }}
+{{- range $i, $_ := .Messages }}
+{{- $last := eq (len (slice $.Messages $i)) 1 }}
+{{- if eq .Role "user" }}<|start_header_id|>user<|end_header_id|>
+{{- if and $.Tools $last }}
+Given the following functions, please respond with a JSON for a function call with its proper arguments that best answers the given prompt.
+Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. Do not use variables.
+{{ $.Tools }}
+{{- end }}
+{{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|>
+{{ end }}
+{{- else if eq .Role "assistant" }}<|start_header_id|>assistant<|end_header_id|>
+{{- if .ToolCalls }}
+{{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "parameters": {{ .Function.Arguments }}}{{ end }}
+{{- else }}
+{{ .Content }}{{ if not $last }}<|eot_id|>{{ end }}
+{{- end }}
+{{- else if eq .Role "tool" }}<|start_header_id|>ipython<|end_header_id|>
+{{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|>
+{{ end }}
+{{- end }}
+{{- end }}
+{{- else }}
+{{- if .System }}<|start_header_id|>system<|end_header_id|>
+{{ .System }}<|eot_id|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|>
+{{ .Prompt }}<|eot_id|>{{ end }}<|start_header_id|>assistant<|end_header_id|>
+{{ end }}{{ .Response }}{{ if .Response }}<|eot_id|>{{ end }}`
+
+const QWEN_TOOL_TEMPLATE = `{{- if .Messages }}
+{{- if or .System .Tools }}<|im_start|>system
+{{- if .System }}
+{{ .System }}
+{{- end }}
+{{- if .Tools }}
+
+# Tools
+
+You may call one or more functions to assist with the user query.
+
+You are provided with function signatures within <tools></tools> XML tags:
+<tools>
+{{- range .Tools }}
+{"type": "function", "function": {{ .Function }}}
+{{- end }}
+</tools>
+
+For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
+<tool_call>
+{"name": <function-name>, "arguments": <args-json-object>}
+</tool_call>
+{{- end }}<|im_end|>
+{{ end }}
+{{- range $i, $_ := .Messages }}
+{{- $last := eq (len (slice $.Messages $i)) 1 }}
+{{- if eq .Role "user" }}<|im_start|>user
+{{ .Content }}<|im_end|>
+{{ if $last }}<|im_start|>assistant
+{{ end }}
+{{- else if eq .Role "assistant" }}<|im_start|>assistant
+{{- if .ToolCalls }}
+{{- range .ToolCalls }}
+<tool_call>
+{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}}
+</tool_call>
+{{- end }}
+{{- else }}
+{{ .Content }}
+{{- end }}{{ if not $last }}<|im_end|>
+{{ end }}
+{{- else if eq .Role "tool" }}<|im_start|>user
+<tool_response>
+{{ .Content }}
+</tool_response><|im_end|>
+{{ if $last }}<|im_start|>assistant
+{{ end }}
+{{- end }}
+{{- end }}
+{{- else }}
+{{- if .System }}<|im_start|>system
+{{ .System }}<|im_end|>
+{{ end }}{{ if .Prompt }}<|im_start|>user
+{{ .Prompt }}<|im_end|>
+{{ end }}<|im_start|>assistant
+{{ end }}{{ .Response }}{{ if .Response }}<|im_end|>{{ end }}`
+
+const MISTRAL_TOOL_TEMPLATE = `{{- if .Messages }}
+{{- range $index, $_ := .Messages }}
+{{- if eq .Role "user" }}[INST] {{ if and $.Tools (eq (len (slice $.Messages $index)) 1) }}[AVAILABLE_TOOLS] {{ $.Tools }} [/AVAILABLE_TOOLS] {{ end }}{{ .Content }} [/INST]
+{{- else if eq .Role "assistant" }}
+{{- if .ToolCalls }} [TOOL_CALLS] [
+{{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}}
+{{- end }}]
+{{- else }} {{ .Content }}
+{{- end }}</s>
+{{- else if eq .Role "tool" }}[TOOL_RESULTS] {{ .Content }} [/TOOL_RESULTS]
+{{- end }}
+{{- end }}
+{{- else }}[INST] {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }} [/INST] {{ end }}{{ .Response }}</s>`
+
+// Map model families to their tool templates
+const FAMILY_TEMPLATES: Record<string, string> = {
+ llama: LLAMA31_TOOL_TEMPLATE,
+ qwen2: QWEN_TOOL_TEMPLATE,
+ qwen3: QWEN_TOOL_TEMPLATE,
+ mistral: MISTRAL_TOOL_TEMPLATE,
+}
+
+// ── Public API ────────────────────────────────────────────────────
+
+/**
+ * Get the agent-variant model name for a given model.
+ * e.g., "mannix/llama3.1-8b-abliterated:q5_K_M" → "mannix/llama3.1-8b-abliterated:agent"
+ */
+export function getAgentModelName(originalName: string): string {
+ // Strip the tag and add :agent
+ const baseName = originalName.replace(/:.*$/, '')
+ return `${baseName}:agent`
+}
+
+/**
+ * Check if a model family has a known tool template we can apply.
+ */
+export async function canFixModel(modelName: string): Promise<{ fixable: boolean; family: string }> {
+ try {
+ const res = await localFetch(ollamaUrl('/show'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: modelName }),
+ })
+ if (!res.ok) return { fixable: false, family: 'unknown' }
+ const data = await res.json()
+ const family = data.details?.family || ''
+
+ // Check if we have a template for this family
+ const hasTemplate = Object.keys(FAMILY_TEMPLATES).some(f => family.startsWith(f))
+ return { fixable: hasTemplate, family }
+ } catch {
+ return { fixable: false, family: 'unknown' }
+ }
+}
+
+/**
+ * Check if the agent variant already exists.
+ */
+export async function agentVariantExists(modelName: string): Promise<boolean> {
+ const agentName = getAgentModelName(modelName)
+ try {
+ const res = await localFetch(ollamaUrl('/show'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: agentName }),
+ })
+ return res.ok
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Create an agent variant of a model by applying the correct tool-calling template.
+ * This uses `ollama create` with a Modelfile that re-applies the template.
+ *
+ * Returns the new model name on success, or throws on failure.
+ */
+export async function createAgentVariant(
+ modelName: string,
+ onProgress?: (status: string) => void
+): Promise<string> {
+ // 1. Get model family
+ const { fixable, family } = await canFixModel(modelName)
+ if (!fixable) {
+ throw new Error(`No tool template available for model family: ${family}`)
+ }
+
+ // 2. Find the right template
+ const templateKey = Object.keys(FAMILY_TEMPLATES).find(f => family.startsWith(f))
+ if (!templateKey) throw new Error(`No template for family: ${family}`)
+ const template = FAMILY_TEMPLATES[templateKey]
+
+ // 3. Create via new Ollama API format (model + from + template)
+ const agentName = getAgentModelName(modelName)
+
+ onProgress?.('Creating agent variant...')
+
+ // Use localFetchStream because /api/create returns NDJSON stream
+ const res = await localFetchStream(ollamaUrl('/create'), {
+ method: 'POST',
+ body: JSON.stringify({
+ model: agentName,
+ from: modelName,
+ template: template,
+ }),
+ })
+
+ if (!res.ok) {
+ const error = await res.text()
+ throw new Error(`Failed to create agent variant: ${error}`)
+ }
+
+ // Consume the stream to completion
+ const text = await res.text()
+ if (text.includes('"error"')) {
+ const match = text.match(/"error"\s*:\s*"([^"]+)"/)
+ if (match) throw new Error(match[1])
+ }
+
+ onProgress?.('Agent variant ready!')
+ return agentName
+}
diff --git a/src/api/ollama.ts b/src/api/ollama.ts
index d01ec36c..69fdc0fa 100644
--- a/src/api/ollama.ts
+++ b/src/api/ollama.ts
@@ -44,6 +44,59 @@ export async function chatStream(
return res
}
+// Agent Mode: chat with tool calling support
+export async function chatStreamWithTools(
+ model: string,
+ messages: { role: string; content: string; tool_calls?: any[] }[],
+ tools: { type: string; function: { name: string; description: string; parameters: any } }[],
+ options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},
+ signal?: AbortSignal
+): Promise<Response> {
+ const res = await localFetchStream(ollamaUrl("/chat"), {
+ method: "POST",
+ body: JSON.stringify({ model, messages, tools, options, stream: true }),
+ })
+ if (!res.ok) {
+ // Try to extract Ollama's error message
+ try {
+ const errorData = await res.json()
+ throw new Error(errorData.error || "Failed to start agent chat")
+ } catch (e) {
+ if (e instanceof Error && e.message !== "Failed to start agent chat") throw e
+ throw new Error("Failed to start agent chat")
+ }
+ }
+ return res
+}
+
+// Agent Mode: non-streaming tool call (more reliable for detecting tool calls)
+export async function chatWithTools(
+ model: string,
+ messages: { role: string; content: string; tool_calls?: any[] }[],
+ tools: { type: string; function: { name: string; description: string; parameters: any } }[],
+ options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},
+): Promise<{ content: string; tool_calls?: any[] }> {
+ const res = await localFetch(ollamaUrl("/chat"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, messages, tools, options, stream: false }),
+ })
+ if (!res.ok) {
+ try {
+ const errorData = await res.json()
+ throw new Error(errorData.error || "Failed to start agent chat")
+ } catch (e) {
+ if (e instanceof Error && e.message !== "Failed to start agent chat") throw e
+ throw new Error("Failed to start agent chat")
+ }
+ }
+ const data = await res.json()
+ return {
+ content: data.message?.content || '',
+ tool_calls: data.message?.tool_calls,
+ }
+}
+
export async function pullModel(name: string, signal?: AbortSignal): Promise<Response> {
const res = await localFetchStream(ollamaUrl("/pull"), {
method: "POST",
@@ -61,6 +114,32 @@ export async function deleteModel(name: string): Promise<void> {
if (!res.ok) throw new Error("Failed to delete model")
}
+export async function listRunningModels(): Promise<string[]> {
+ try {
+ const res = await localFetch(ollamaUrl("/ps"))
+ if (!res.ok) return []
+ const data = await res.json()
+ return (data.models || []).map((m: any) => m.name || m.model)
+ } catch {
+ return []
+ }
+}
+
+export async function unloadModel(name: string): Promise<void> {
+ await localFetch(ollamaUrl("/generate"), {
+ method: "POST",
+ body: JSON.stringify({ model: name, keep_alive: 0 }),
+ })
+}
+
+export async function unloadAllModels(): Promise<number> {
+ const running = await listRunningModels()
+ for (const name of running) {
+ try { await unloadModel(name) } catch { /* continue */ }
+ }
+ return running.length
+}
+
export async function checkConnection(): Promise<boolean> {
try {
await localFetch(ollamaUrl("/tags"))
diff --git a/src/api/tool-registry.ts b/src/api/tool-registry.ts
new file mode 100644
index 00000000..c54342af
--- /dev/null
+++ b/src/api/tool-registry.ts
@@ -0,0 +1,216 @@
+import type { AgentToolDef, OllamaTool } from '../types/agent-mode'
+import { executeTool } from './agents'
+import { fetchExternal } from './backend'
+import type { ToolName } from '../types/agents'
+
+// ── Tool Definitions ──────────────────────────────────────────────
+
+export const AGENT_TOOL_DEFS: AgentToolDef[] = [
+ {
+ name: 'web_search',
+ description: 'Search the web for current information. Returns titles, URLs, and short snippets. Use web_fetch on promising URLs to read full content.',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'The search query string' },
+ maxResults: { type: 'number', description: 'Maximum results to return (default: 5)' },
+ },
+ required: ['query'],
+ },
+ permission: 'auto',
+ },
+ {
+ name: 'web_fetch',
+ description: 'Fetch a web page URL and return its text content. Use this AFTER web_search to read the full content of a result. Returns cleaned text, not HTML.',
+ parameters: {
+ type: 'object',
+ properties: {
+ url: { type: 'string', description: 'The URL to fetch' },
+ maxLength: { type: 'number', description: 'Maximum characters to return (default: 4000)' },
+ },
+ required: ['url'],
+ },
+ permission: 'auto',
+ },
+ {
+ name: 'file_read',
+ description: 'Read the contents of a file from the local filesystem within the agent workspace.',
+ parameters: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to the file to read' },
+ },
+ required: ['path'],
+ },
+ permission: 'auto',
+ },
+ {
+ name: 'file_write',
+ description: 'Write content to a file. Creates the file if it does not exist, overwrites if it does.',
+ parameters: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to the file to write' },
+ content: { type: 'string', description: 'The content to write' },
+ },
+ required: ['path', 'content'],
+ },
+ permission: 'confirm',
+ },
+ {
+ name: 'code_execute',
+ description: 'Execute code in a sandboxed environment. Supports Python and shell commands. Returns stdout, stderr, and exit code.',
+ parameters: {
+ type: 'object',
+ properties: {
+ code: { type: 'string', description: 'The code to execute' },
+ language: { type: 'string', description: 'Programming language: "python" or "shell"', enum: ['python', 'shell'] },
+ },
+ required: ['code'],
+ },
+ permission: 'confirm',
+ },
+ {
+ name: 'image_generate',
+ description: 'Generate an image from a text description using the local ComfyUI image generation pipeline.',
+ parameters: {
+ type: 'object',
+ properties: {
+ prompt: { type: 'string', description: 'Text description of the image to generate' },
+ negativePrompt: { type: 'string', description: 'Things to avoid in the generated image' },
+ },
+ required: ['prompt'],
+ },
+ permission: 'confirm',
+ },
+]
+
+// ── Convert to Ollama Format ──────────────────────────────────────
+
+export function getOllamaTools(): OllamaTool[] {
+ return AGENT_TOOL_DEFS.map((tool) => ({
+ type: 'function' as const,
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.parameters,
+ },
+ }))
+}
+
+// ── Lookup Helpers ────────────────────────────────────────────────
+
+export function getToolByName(name: string): AgentToolDef | undefined {
+ return AGENT_TOOL_DEFS.find((t) => t.name === name)
+}
+
+export function getToolPermission(name: string): 'auto' | 'confirm' {
+ const tool = getToolByName(name)
+ return tool?.permission ?? 'confirm'
+}
+
+// ── Execute Tool (wraps errors as string results — never throws) ─
+
+export async function executeAgentTool(
+ name: string,
+ args: Record<string, any>
+): Promise<string> {
+ try {
+ // Handle web_fetch separately (not in legacy agents.ts)
+ if (name === 'web_fetch') {
+ return await executeWebFetch(args.url, args.maxLength)
+ }
+
+ // Reuse the existing executeTool from agents.ts for other tools
+ return await executeTool(name as ToolName, args)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ return `Error: ${message}`
+ }
+}
+
+// ── web_fetch: Fetch URL → Extract Text → Return ────────────────
+
+async function executeWebFetch(url: string, maxLength: number = 4000): Promise<string> {
+ if (!url) return 'Error: No URL provided'
+
+ try {
+ // Fetch the page content
+ const html = await fetchExternal(url)
+
+ // Convert HTML to readable text
+ const text = htmlToText(html)
+
+ // Truncate if needed
+ if (text.length > maxLength) {
+ return text.substring(0, maxLength) + '\n\n[...truncated]'
+ }
+
+ return text || 'Error: Page returned empty content'
+ } catch (err) {
+ return `Error fetching ${url}: ${err instanceof Error ? err.message : String(err)}`
+ }
+}
+
+/**
+ * Convert HTML to clean readable text.
+ * Strips tags, decodes entities, preserves structure.
+ */
+function htmlToText(html: string): string {
+ // Use DOMParser if available (browser environment)
+ if (typeof DOMParser !== 'undefined') {
+ const parser = new DOMParser()
+ const doc = parser.parseFromString(html, 'text/html')
+
+ // Remove script, style, nav, header, footer elements
+ const removeSelectors = 'script, style, nav, header, footer, .nav, .header, .footer, .sidebar, .menu, .ad, .advertisement, [role="navigation"], [role="banner"]'
+ doc.querySelectorAll(removeSelectors).forEach(el => el.remove())
+
+ // Try to find main content area
+ const main = doc.querySelector('main, article, [role="main"], .content, .article, .post, #content, #main')
+ const target = main || doc.body
+
+ if (!target) return ''
+
+ // Get text content with basic formatting
+ let text = ''
+ const walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT)
+ let node: Node | null = walker.nextNode()
+
+ while (node) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const t = node.textContent?.trim()
+ if (t) text += t + ' '
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
+ const tag = (node as Element).tagName.toLowerCase()
+ if (['p', 'div', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'tr'].includes(tag)) {
+ text += '\n'
+ }
+ if (['h1', 'h2', 'h3'].includes(tag)) {
+ text += '# '
+ }
+ }
+ node = walker.nextNode()
+ }
+
+ // Clean up whitespace
+ return text
+ .replace(/\n{3,}/g, '\n\n')
+ .replace(/ {2,}/g, ' ')
+ .trim()
+ }
+
+ // Fallback: simple regex-based HTML stripping
+ return html
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/&nbsp;/g, ' ')
+ .replace(/\s{2,}/g, ' ')
+ .trim()
+}
diff --git a/src/components/chat/AgentModeToggle.tsx b/src/components/chat/AgentModeToggle.tsx
new file mode 100644
index 00000000..3fc845b9
--- /dev/null
+++ b/src/components/chat/AgentModeToggle.tsx
@@ -0,0 +1,58 @@
+import { useState } from 'react'
+import { ToggleSwitch } from '../ui/ToggleSwitch'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { isAgentCompatible } from '../../lib/model-compatibility'
+import { FEATURE_FLAGS } from '../../lib/constants'
+import { AgentTutorial } from './AgentTutorial'
+
+export function AgentModeToggle() {
+ const [showTutorial, setShowTutorial] = useState(false)
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const activeModel = useModelStore((s) => s.activeModel)
+ const { agentModeActive, toggleAgentMode, tutorialCompleted } = useAgentModeStore()
+
+ if (!FEATURE_FLAGS.AGENT_MODE || !activeConversationId) return null
+
+ const isActive = agentModeActive[activeConversationId] ?? false
+ const isCompatible = activeModel ? isAgentCompatible(activeModel) : false
+
+ const handleToggle = () => {
+ if (!isCompatible) return
+ if (!isActive && !tutorialCompleted) {
+ setShowTutorial(true)
+ return
+ }
+ if (activeConversationId) {
+ toggleAgentMode(activeConversationId)
+ }
+ }
+
+ const handleTutorialComplete = () => {
+ setShowTutorial(false)
+ useAgentModeStore.getState().setTutorialCompleted()
+ if (activeConversationId) {
+ toggleAgentMode(activeConversationId)
+ }
+ }
+
+ return (
+ <>
+ <ToggleSwitch
+ enabled={isActive}
+ onChange={handleToggle}
+ disabled={!isCompatible}
+ size="sm"
+ />
+
+ {showTutorial && (
+ <AgentTutorial
+ open={showTutorial}
+ onClose={() => setShowTutorial(false)}
+ onComplete={handleTutorialComplete}
+ />
+ )}
+ </>
+ )
+}
diff --git a/src/components/chat/AgentTutorial.tsx b/src/components/chat/AgentTutorial.tsx
new file mode 100644
index 00000000..509061f9
--- /dev/null
+++ b/src/components/chat/AgentTutorial.tsx
@@ -0,0 +1,159 @@
+import { useState } from 'react'
+import { motion, AnimatePresence } from 'framer-motion'
+import { Bot, Search, FileText, Terminal, Shield, Zap, ChevronRight, ChevronLeft } from 'lucide-react'
+import { Modal } from '../ui/Modal'
+
+interface Props {
+ open: boolean
+ onClose: () => void
+ onComplete: () => void
+}
+
+const STEPS = [
+ {
+ icon: Bot,
+ title: 'Welcome to Agent Mode',
+ description: 'Your AI can now use tools to take action — search the web, read and write files, execute code, and generate images. All locally, all uncensored.',
+ tagline: 'No filters, no limits — your AI, your rules.',
+ color: 'text-green-400',
+ },
+ {
+ icon: Zap,
+ title: 'Available Tools',
+ description: 'Agent Mode gives your model access to powerful tools:',
+ tools: [
+ { icon: Search, name: 'Web Search', desc: 'Search the internet for current information' },
+ { icon: FileText, name: 'File Read/Write', desc: 'Read and create files on your system' },
+ { icon: Terminal, name: 'Code Execute', desc: 'Run Python or shell commands' },
+ ],
+ color: 'text-blue-400',
+ },
+ {
+ icon: Shield,
+ title: 'You Stay in Control',
+ description: 'Safe actions like searches run automatically. Risky actions like writing files or executing code always ask for your approval first. You can stop the agent at any time with the stop button.',
+ color: 'text-amber-400',
+ },
+ {
+ icon: Zap,
+ title: 'Model Recommendations',
+ description: 'Agent Mode requires models with native tool calling support. Recommended:',
+ models: [
+ { name: 'Hermes 3', desc: 'Uncensored + native tool calling. THE agent model.', hot: true },
+ { name: 'Qwen 2.5 / Llama 3.1', desc: 'Standard models with tool support' },
+ ],
+ color: 'text-purple-400',
+ },
+]
+
+export function AgentTutorial({ open, onClose, onComplete }: Props) {
+ const [step, setStep] = useState(0)
+ const current = STEPS[step]
+ const isLast = step === STEPS.length - 1
+ const Icon = current.icon
+
+ return (
+ <Modal open={open} onClose={onClose} title="">
+ <div className="space-y-4">
+ {/* Step indicator */}
+ <div className="flex items-center justify-center gap-1.5">
+ {STEPS.map((_, i) => (
+ <div
+ key={i}
+ className={`w-1.5 h-1.5 rounded-full transition-colors ${
+ i === step ? 'bg-green-400' : 'bg-white/10'
+ }`}
+ />
+ ))}
+ </div>
+
+ {/* Content */}
+ <AnimatePresence mode="wait">
+ <motion.div
+ key={step}
+ initial={{ opacity: 0, x: 20 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -20 }}
+ transition={{ duration: 0.2 }}
+ className="text-center space-y-3"
+ >
+ <div className="flex justify-center">
+ <div className={`p-3 rounded-xl bg-white/5 border border-white/10 ${current.color}`}>
+ <Icon size={28} />
+ </div>
+ </div>
+
+ <h3 className="text-base font-semibold text-white">{current.title}</h3>
+ <p className="text-[0.75rem] text-gray-400 leading-relaxed">{current.description}</p>
+
+ {current.tagline && (
+ <p className="text-[0.7rem] text-green-400/80 font-medium italic">{current.tagline}</p>
+ )}
+
+ {current.tools && (
+ <div className="space-y-2 pt-1">
+ {current.tools.map((tool) => (
+ <div key={tool.name} className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.06]">
+ <tool.icon size={14} className="text-blue-400 shrink-0" />
+ <div className="text-left">
+ <p className="text-[0.7rem] text-white font-medium">{tool.name}</p>
+ <p className="text-[0.6rem] text-gray-500">{tool.desc}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {(current as any).models && (
+ <div className="space-y-2 pt-1">
+ {(current as any).models.map((model: any) => (
+ <div key={model.name} className={`flex items-center gap-2 px-3 py-2 rounded-lg border ${
+ model.hot ? 'bg-green-500/[0.05] border-green-500/20' : 'bg-white/[0.03] border-white/[0.06]'
+ }`}>
+ <div className="text-left">
+ <div className="flex items-center gap-1.5">
+ {model.hot && <span className="text-[0.55rem] px-1 py-0.5 rounded bg-green-500/20 text-green-300 font-bold">HOT</span>}
+ <p className="text-[0.7rem] text-white font-medium">{model.name}</p>
+ </div>
+ <p className="text-[0.6rem] text-gray-500">{model.desc}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </motion.div>
+ </AnimatePresence>
+
+ {/* Navigation */}
+ <div className="flex items-center justify-between pt-2">
+ <button
+ onClick={() => setStep(Math.max(0, step - 1))}
+ disabled={step === 0}
+ className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-[0.7rem] text-gray-400 hover:text-white hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
+ >
+ <ChevronLeft size={14} />
+ Back
+ </button>
+
+ {isLast ? (
+ <button
+ onClick={onComplete}
+ className="flex items-center gap-1 px-4 py-1.5 rounded-lg text-[0.7rem] font-medium bg-green-500/15 border border-green-500/30 text-green-300 hover:bg-green-500/25 transition-colors"
+ >
+ Enable Agent Mode
+ <Zap size={14} />
+ </button>
+ ) : (
+ <button
+ onClick={() => setStep(step + 1)}
+ className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-[0.7rem] text-gray-300 hover:text-white hover:bg-white/10 transition-colors"
+ >
+ Next
+ <ChevronRight size={14} />
+ </button>
+ )}
+ </div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/src/components/chat/ApprovalDialog.tsx b/src/components/chat/ApprovalDialog.tsx
new file mode 100644
index 00000000..945d82d7
--- /dev/null
+++ b/src/components/chat/ApprovalDialog.tsx
@@ -0,0 +1,33 @@
+import { motion } from 'framer-motion'
+import { ShieldAlert } from 'lucide-react'
+import type { AgentToolCall } from '../../types/agent-mode'
+import { ToolCallBlock } from './ToolCallBlock'
+
+interface Props {
+ toolCall: AgentToolCall
+ onApprove: () => void
+ onReject: () => void
+}
+
+export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {
+ return (
+ <motion.div
+ className="px-3 pb-2"
+ initial={{ opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.2 }}
+ >
+ <div className="flex items-center gap-1.5 mb-1">
+ <ShieldAlert size={11} className="text-amber-400" />
+ <span className="text-[0.6rem] text-amber-400/80 font-medium">
+ Approval required
+ </span>
+ </div>
+ <ToolCallBlock
+ toolCall={toolCall}
+ onApprove={onApprove}
+ onReject={onReject}
+ />
+ </motion.div>
+ )
+}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index c6500c30..f0067924 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -2,20 +2,24 @@ import { useState, useRef, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Send, Square } from 'lucide-react'
import { VoiceButton } from './VoiceButton'
+import { ApprovalDialog } from './ApprovalDialog'
import { useVoiceStore } from '../../stores/voiceStore'
+import type { AgentToolCall } from '../../types/agent-mode'
interface Props {
onSend: (content: string) => void
onStop: () => void
isGenerating: boolean
+ pendingApproval?: AgentToolCall | null
+ onApprove?: () => void
+ onReject?: () => void
}
-export function ChatInput({ onSend, onStop, isGenerating }: Props) {
+export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApprove, onReject }: Props) {
const [input, setInput] = useState('')
const [isVoiceRecording, setIsVoiceRecording] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const isTranscribing = useVoiceStore((s) => s.isTranscribing)
-
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
@@ -28,9 +32,7 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
if (!trimmed || isGenerating) return
onSend(trimmed)
setInput('')
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto'
- }
+ if (textareaRef.current) textareaRef.current.style.height = 'auto'
}
const handleKeyDown = (e: React.KeyboardEvent) => {
@@ -41,62 +43,51 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
}
}
- const handleRecordingChange = (recording: boolean) => {
- setIsVoiceRecording(recording)
- }
-
- const handleVoiceTranscript = (text: string) => {
- setInput(text)
- // Force textarea height recalculation
- requestAnimationFrame(() => {
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto'
- textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'
- }
- })
- }
-
return (
- <div className="p-3 border-t border-gray-200 dark:border-white/5">
- <div className="flex items-end gap-2.5 glass-card rounded-xl px-3 py-2.5">
+ <div className="px-3 pb-2 pt-1">
+ {/* Approval dialog */}
+ {pendingApproval && onApprove && onReject && (
+ <ApprovalDialog toolCall={pendingApproval} onApprove={onApprove} onReject={onReject} />
+ )}
+
+ <div className="flex items-end gap-2 rounded-lg bg-white/[0.03] border border-white/[0.06] px-2.5 py-2">
<VoiceButton
- onTranscript={handleVoiceTranscript}
- onRecordingChange={handleRecordingChange}
+ onTranscript={(text) => { setInput(text); requestAnimationFrame(() => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px' } }) }}
+ onRecordingChange={(r) => setIsVoiceRecording(r)}
disabled={isGenerating}
/>
+
<textarea
ref={textareaRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
- placeholder={isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Type a message..."}
+ placeholder={isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Message..."}
rows={1}
- className="flex-1 bg-transparent resize-none text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none text-[0.8rem] leading-relaxed max-h-[200px]"
+ className="flex-1 bg-transparent resize-none text-gray-200 placeholder-gray-600 focus:outline-none text-[0.75rem] leading-relaxed max-h-[200px]"
/>
+
{isGenerating ? (
<motion.button
onClick={onStop}
- className="p-2 rounded-lg bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/40 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 transition-all shrink-0"
+ className="p-1.5 rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 transition-all shrink-0"
whileTap={{ scale: 0.9 }}
aria-label="Stop generation"
>
- <Square size={15} />
+ <Square size={13} />
</motion.button>
) : (
<motion.button
onClick={handleSend}
disabled={!input.trim() || isTranscribing}
- className="p-2 rounded-lg bg-gray-800 dark:bg-white/10 border border-gray-700 dark:border-white/15 text-white hover:bg-gray-700 dark:hover:bg-white/15 disabled:opacity-30 disabled:cursor-not-allowed transition-all shrink-0"
+ className="p-1.5 rounded-md bg-white/8 text-gray-300 hover:bg-white/12 disabled:opacity-20 disabled:cursor-not-allowed transition-all shrink-0"
whileTap={{ scale: 0.9 }}
aria-label="Send message"
>
- <Send size={15} />
+ <Send size={13} />
</motion.button>
)}
</div>
- <p className="text-[0.65rem] text-gray-400 dark:text-gray-600 mt-1.5 text-center">
- {isTranscribing ? 'Transcribing with local Whisper...' : isVoiceRecording ? 'Recording... click mic to stop' : 'Enter to send \u00b7 Shift+Enter for new line'}
- </p>
</div>
)
}
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 943419a7..274266b8 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -1,105 +1,177 @@
import { useState } from 'react'
-import { AnimatePresence } from 'framer-motion'
+import { motion, AnimatePresence } from 'framer-motion'
import { useChat } from '../../hooks/useChat'
import { useChatStore } from '../../stores/chatStore'
import { useModelStore } from '../../stores/modelStore'
import { useRAGStore } from '../../stores/ragStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
import { MessageList } from './MessageList'
import { ChatInput } from './ChatInput'
import { RAGPanel } from './RAGPanel'
-import { PersonaPanel } from '../personas/PersonaPanel'
+import { AgentModeToggle } from './AgentModeToggle'
import { ModelRecommendation } from '../models/ModelRecommendation'
import { ErrorBoundary } from '../ui/ErrorBoundary'
-import { Cpu, FileText } from 'lucide-react'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { FEATURE_FLAGS } from '../../lib/constants'
+import { isAgentCompatible } from '../../lib/model-compatibility'
+import { FileText, Bot, User, ChevronDown } from 'lucide-react'
export function ChatView() {
- const { sendMessage, stopGeneration, isGenerating } = useChat()
+ const { sendMessage, stopGeneration, isGenerating, isLoadingModel, pendingApproval, approveToolCall, rejectToolCall } = useChat()
const activeConversationId = useChatStore((s) => s.activeConversationId)
const activeModel = useModelStore((s) => s.activeModel)
const models = useModelStore((s) => s.models)
const [ragPanelOpen, setRagPanelOpen] = useState(false)
+ const [personaOpen, setPersonaOpen] = useState(false)
+ const { getActivePersona, setActivePersona } = useSettingsStore()
+ const activePersona = getActivePersona()
+ const allPersonas = useSettingsStore((s) => s.personas)
- // Document count badge for RAG button
const docCount = useRAGStore((s) =>
activeConversationId ? (s.documents[activeConversationId] || []).length : 0
)
const ragEnabled = useRAGStore((s) =>
activeConversationId ? s.ragEnabled[activeConversationId] ?? false : false
)
+ const isAgentActive = useAgentModeStore((s) =>
+ activeConversationId ? s.agentModeActive[activeConversationId] ?? false : false
+ )
- // Check if current conversation has user messages
- const conversation = useChatStore((s) => {
- if (!s.activeConversationId) return undefined
- return s.conversations.find((c) => c.id === s.activeConversationId)
- })
- const hasUserMessages = conversation?.messages.some((m) => m.role === 'user') ?? false
+ return (
+ <div className="h-full flex flex-col min-w-0">
+ <AnimatePresence mode="wait">
+ {!activeConversationId ? (
+ // ── Homepage: just logo, no prompt ──
+ <motion.div
+ key="home"
+ className="flex-1 flex flex-col items-center justify-center"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0, y: -20 }}
+ transition={{ duration: 0.2 }}
+ >
+ <img src="/LU-monogram-bw.png" alt="" width={32} height={32} className="dark:invert-0 invert opacity-20 mb-3" />
+ <h1 className="text-[0.8rem] font-semibold text-gray-400 mb-0.5 tracking-wide">LUncensored</h1>
+ <p className="text-[0.6rem] text-gray-600">No filters, no limits.</p>
- // Show welcome + personas only when no conversation is selected (homepage)
- if (!activeConversationId) {
- const hasModels = models.length > 0
+ {models.length === 0 && <div className="mt-4"><ModelRecommendation /></div>}
+ {models.length > 0 && !activeModel && (
+ <p className="text-[0.6rem] text-amber-500/60 mt-3">Select a model above.</p>
+ )}
+ </motion.div>
+ ) : (
+ // ── Active chat ──
+ <motion.div
+ key="chat"
+ className="flex-1 flex overflow-hidden"
+ initial={{ opacity: 0, y: 20 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, ease: 'easeOut' }}
+ >
+ <div className="flex-1 flex flex-col min-w-0">
+ {/* Top bar: Documents + Agent Mode */}
+ <div className="flex items-center justify-end gap-2 px-3 pt-1">
+ {/* Persona selector */}
+ <div className="relative">
+ <button
+ onClick={() => setPersonaOpen(!personaOpen)}
+ className="flex items-center gap-1.5 px-3 py-1 rounded-full border border-gray-300 dark:border-white/15 hover:border-gray-400 dark:hover:border-white/25 text-gray-500 dark:text-gray-400 transition-colors text-xs"
+ >
+ <User size={13} />
+ <span className="font-medium max-w-[80px] truncate">{activePersona?.name || 'No Persona'}</span>
+ <ChevronDown size={10} className={`transition-transform ${personaOpen ? 'rotate-180' : ''}`} />
+ </button>
+ {personaOpen && (
+ <>
+ <div className="fixed inset-0 z-40" onClick={() => setPersonaOpen(false)} />
+ <div className="absolute right-0 top-full mt-1 z-50 w-48 max-h-[250px] overflow-y-auto scrollbar-thin rounded-lg bg-[#1a1a1a] border border-white/10 shadow-xl py-1">
+ {/* Active persona pinned at top */}
+ {activePersona && (
+ <div className="px-2 pb-1 mb-1 border-b border-white/[0.06]">
+ <div className="px-2 py-1.5 rounded-md bg-white/[0.06] border border-white/10 text-[0.65rem] 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}
+ </div>
+ </div>
+ )}
+ {/* Other personas */}
+ {allPersonas.filter(p => p.id !== activePersona?.id).map(p => (
+ <button
+ key={p.id}
+ onClick={() => { setActivePersona(p.id); setPersonaOpen(false) }}
+ className="w-full text-left px-3 py-1.5 text-[0.65rem] text-gray-400 hover:bg-white/5 hover:text-gray-200 transition-colors"
+ >
+ {p.name}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
- return (
- <div className="h-full flex flex-col">
- <div className="flex-1 flex flex-col items-center justify-center p-8 overflow-y-auto scrollbar-thin">
- <div className="w-16 h-16 rounded-2xl bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 flex items-center justify-center mb-4">
- <Cpu size={32} className="text-gray-400" />
- </div>
- <h1 className="text-2xl font-bold mb-2 text-gray-900 dark:text-white">Locally Uncensored</h1>
- <p className="text-gray-500 mb-6 text-center max-w-md text-sm">
- Private, local AI. Choose a persona and start chatting.
- </p>
+ {/* Documents (RAG) */}
+ <button
+ onClick={() => setRagPanelOpen(!ragPanelOpen)}
+ className={
+ 'flex items-center gap-1.5 px-3 py-1 rounded-full border transition-colors text-xs ' +
+ (ragPanelOpen || ragEnabled
+ ? 'border-green-400 dark:border-green-500/40 text-green-600 dark:text-green-300'
+ : 'border-gray-300 dark:border-white/15 hover:border-gray-400 dark:hover:border-white/25 text-gray-500 dark:text-gray-400')
+ }
+ title="Document Chat (RAG)"
+ >
+ <FileText size={13} />
+ <span className="font-medium">Documents</span>
+ {docCount > 0 && (
+ <span className={
+ 'min-w-[16px] h-[16px] flex items-center justify-center rounded-full text-[0.55rem] font-bold ' +
+ (ragEnabled ? 'bg-green-500 text-white' : 'bg-gray-200 dark:bg-white/15 text-gray-600 dark:text-gray-300')
+ }>
+ {docCount}
+ </span>
+ )}
+ </button>
- {!hasModels && <ModelRecommendation />}
+ {/* Agent Mode (Beta) */}
+ {FEATURE_FLAGS.AGENT_MODE && (
+ <div className={
+ 'flex items-center gap-1.5 px-3 py-1 rounded-full border transition-colors text-xs ' +
+ (isAgentActive
+ ? 'border-green-400 dark:border-green-500/40 text-green-600 dark:text-green-300'
+ : activeModel && !isAgentCompatible(activeModel)
+ ? 'border-gray-300/50 dark:border-white/8 text-gray-400 dark:text-gray-600 opacity-50'
+ : 'border-gray-300 dark:border-white/15 text-gray-500 dark:text-gray-400')
+ }>
+ <Bot size={13} />
+ <div className="flex flex-col items-start leading-none">
+ <span className="text-[0.45rem] text-amber-400 font-bold uppercase tracking-widest">Beta</span>
+ <span className="font-medium">Agent</span>
+ </div>
+ <AgentModeToggle />
+ </div>
+ )}
+ </div>
- {hasModels && !activeModel && (
- <div className="text-sm text-yellow-600 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-200 dark:border-yellow-500/20 rounded-lg px-4 py-2 mb-6">
- Select a model from the dropdown above to start chatting.
+ <MessageList isGenerating={isGenerating} isLoadingModel={isLoadingModel} />
+ <ChatInput
+ onSend={sendMessage}
+ onStop={stopGeneration}
+ isGenerating={isGenerating}
+ pendingApproval={pendingApproval}
+ onApprove={approveToolCall}
+ onReject={rejectToolCall}
+ />
</div>
- )}
- <PersonaPanel />
- </div>
- <ChatInput onSend={sendMessage} onStop={stopGeneration} isGenerating={isGenerating} />
- </div>
- )
- }
-
- return (
- <div className="h-full flex">
- <div className="flex-1 flex flex-col min-w-0">
- <div className="flex items-center justify-end px-3 pt-1">
- <button
- onClick={() => setRagPanelOpen(!ragPanelOpen)}
- className={
- 'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg transition-colors text-xs ' +
- (ragPanelOpen || ragEnabled
- ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300'
- : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-400')
- }
- title="Document Chat (RAG)"
- >
- <FileText size={14} />
- <span className="font-medium">Documents</span>
- {docCount > 0 && (
- <span className={
- 'min-w-[18px] h-[18px] flex items-center justify-center rounded-full text-[0.6rem] font-bold ' +
- (ragEnabled
- ? 'bg-green-500 text-white'
- : 'bg-gray-200 dark:bg-white/15 text-gray-600 dark:text-gray-300')
- }>
- {docCount}
- </span>
- )}
- </button>
- </div>
- <MessageList isGenerating={isGenerating} />
- <ChatInput onSend={sendMessage} onStop={stopGeneration} isGenerating={isGenerating} />
- </div>
- <AnimatePresence>
- {ragPanelOpen && (
- <ErrorBoundary fallbackClassName="w-[280px] shrink-0 h-full border-l border-white/5 bg-[#2a2a2a] flex flex-col items-center justify-center p-6 gap-3">
- <RAGPanel conversationId={activeConversationId} />
- </ErrorBoundary>
+ {/* RAG Panel */}
+ <AnimatePresence>
+ {ragPanelOpen && (
+ <ErrorBoundary fallbackClassName="w-[280px] shrink-0 h-full border-l border-white/5 bg-[#2a2a2a] flex flex-col items-center justify-center p-6 gap-3">
+ <RAGPanel conversationId={activeConversationId} />
+ </ErrorBoundary>
+ )}
+ </AnimatePresence>
+ </motion.div>
)}
</AnimatePresence>
</div>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index ab7946b5..b262934b 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -3,6 +3,7 @@ import { User, Bot, Copy, Check } from 'lucide-react'
import { useState } from 'react'
import { MarkdownRenderer } from './MarkdownRenderer'
import { ThinkingBlock } from './ThinkingBlock'
+import { ToolCallBlock } from './ToolCallBlock'
import { SpeakerButton } from './SpeakerButton'
import type { Message } from '../../types/chat'
@@ -44,6 +45,17 @@ export function MessageBubble({ message }: Props) {
<ThinkingBlock thinking={message.thinking} />
)}
+ {/* Agent Mode: Tool call blocks */}
+ {!isUser && message.agentBlocks && message.agentBlocks.length > 0 && (
+ <>
+ {message.agentBlocks
+ .filter((b) => b.phase === 'tool_call' && b.toolCall)
+ .map((block) => (
+ <ToolCallBlock key={block.id} toolCall={block.toolCall!} />
+ ))}
+ </>
+ )}
+
{/* Main answer bubble */}
<div
className={
diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsx
index fe350b0e..489e8681 100644
--- a/src/components/chat/MessageList.tsx
+++ b/src/components/chat/MessageList.tsx
@@ -5,9 +5,10 @@ import { TypingIndicator } from './TypingIndicator'
interface Props {
isGenerating: boolean
+ isLoadingModel?: boolean
}
-export function MessageList({ isGenerating }: Props) {
+export function MessageList({ isGenerating, isLoadingModel }: Props) {
const conversation = useChatStore((s) => {
if (!s.activeConversationId) return undefined
return s.conversations.find((c) => c.id === s.activeConversationId)
@@ -26,7 +27,7 @@ export function MessageList({ isGenerating }: Props) {
<MessageBubble key={message.id} message={message} />
))}
{isGenerating && lastMessage?.role === 'assistant' && lastMessage.content === '' && (
- <TypingIndicator />
+ <TypingIndicator label={isLoadingModel ? 'Loading model...' : undefined} />
)}
</div>
)
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
new file mode 100644
index 00000000..e8219fce
--- /dev/null
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -0,0 +1,127 @@
+import { useState } from 'react'
+import { motion, AnimatePresence } from 'framer-motion'
+import { ChevronDown, Search, Globe, FileText, FileEdit, Terminal, Image, Loader2, Check, X, Clock, AlertCircle } from 'lucide-react'
+import type { AgentToolCall } from '../../types/agent-mode'
+
+interface Props {
+ toolCall: AgentToolCall
+ onApprove?: () => void
+ onReject?: () => void
+}
+
+const TOOL_ICONS: Record<string, typeof Search> = {
+ web_search: Search,
+ web_fetch: Globe,
+ file_read: FileText,
+ file_write: FileEdit,
+ code_execute: Terminal,
+ image_generate: Image,
+}
+
+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',
+ code_execute: 'text-green-400',
+ image_generate: 'text-purple-400',
+}
+
+const STATUS_ICONS = {
+ pending_approval: Clock,
+ running: Loader2,
+ completed: Check,
+ failed: AlertCircle,
+ rejected: X,
+}
+
+export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
+ const [open, setOpen] = useState(toolCall.status === 'pending_approval')
+
+ const ToolIcon = TOOL_ICONS[toolCall.toolName] || Terminal
+ const 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'
+
+ return (
+ <div className="mb-1">
+ {/* Inline tool call line — no box, just text */}
+ <button
+ onClick={() => 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'
+ } ${isRunning ? 'animate-spin' : ''}`} />
+ {toolCall.duration != null && (
+ <span className="text-[0.6rem] text-gray-500">
+ {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 */}
+ <AnimatePresence>
+ {open && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="overflow-hidden"
+ >
+ <div className="pl-5 pb-2 space-y-1.5">
+ {/* 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">
+ {JSON.stringify(toolCall.args, null, 2)}
+ </pre>
+
+ {/* 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-x-auto max-h-[150px]">
+ {toolCall.result.length > 500 ? toolCall.result.slice(0, 500) + '\n...' : toolCall.result}
+ </pre>
+ )}
+
+ {/* Error */}
+ {toolCall.error && (
+ <pre className="text-[0.62rem] leading-relaxed text-red-400/80 rounded px-2 py-1">
+ {toolCall.error}
+ </pre>
+ )}
+
+ {/* Approval buttons */}
+ {isPending && onApprove && onReject && (
+ <div className="flex items-center gap-2 pt-0.5">
+ <button
+ onClick={(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"
+ >
+ <Check size={11} /> Approve
+ </button>
+ <button
+ onClick={(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"
+ >
+ <X size={11} /> Reject
+ </button>
+ </div>
+ )}
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ )
+}
diff --git a/src/components/chat/TypingIndicator.tsx b/src/components/chat/TypingIndicator.tsx
index 911a5d87..b2d87ab3 100644
--- a/src/components/chat/TypingIndicator.tsx
+++ b/src/components/chat/TypingIndicator.tsx
@@ -1,16 +1,21 @@
import { motion } from 'framer-motion'
-export function TypingIndicator() {
+export function TypingIndicator({ label }: { label?: string }) {
return (
- <div className="flex gap-1 px-3 py-1.5">
- {[0, 1, 2].map((i) => (
- <motion.div
- key={i}
- className="w-1.5 h-1.5 rounded-full bg-gray-300"
- animate={{ opacity: [0.3, 1, 0.3], scale: [0.8, 1.2, 0.8] }}
- transition={{ duration: 1.2, repeat: Infinity, delay: i * 0.2 }}
- />
- ))}
+ <div className="flex flex-col gap-1 px-3 py-1.5">
+ <div className="flex gap-1">
+ {[0, 1, 2].map((i) => (
+ <motion.div
+ key={i}
+ className="w-1.5 h-1.5 rounded-full bg-gray-300"
+ animate={{ opacity: [0.3, 1, 0.3], scale: [0.8, 1.2, 0.8] }}
+ transition={{ duration: 1.2, repeat: Infinity, delay: i * 0.2 }}
+ />
+ ))}
+ </div>
+ {label && (
+ <span className="text-[10px] text-gray-400 dark:text-gray-500">{label}</span>
+ )}
</div>
)
}
diff --git a/src/components/create/Gallery.tsx b/src/components/create/Gallery.tsx
index fbcc55e0..086500f1 100644
--- a/src/components/create/Gallery.tsx
+++ b/src/components/create/Gallery.tsx
@@ -2,7 +2,9 @@ import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Trash2, Download, ChevronDown, ChevronUp } from 'lucide-react'
import { getImageUrl } from '../../api/comfyui'
+import { downloadComfyFile } from '../../api/backend'
import { useCreateStore, type GalleryItem } from '../../stores/createStore'
+import { MediaViewer } from './MediaViewer'
const PAGE_SIZE = 20
@@ -11,6 +13,7 @@ export function Gallery() {
const [expanded, setExpanded] = useState(true)
const [page, setPage] = useState(0)
const [selected, setSelected] = useState<GalleryItem | null>(null)
+ const [viewerIndex, setViewerIndex] = useState<number | null>(null)
if (gallery.length === 0) {
return (
@@ -24,13 +27,7 @@ export function Gallery() {
const visible = gallery.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)
const handleDownload = (item: GalleryItem) => {
- const url = getImageUrl(item.filename, item.subfolder)
- const a = document.createElement('a')
- a.href = url
- a.download = item.filename
- document.body.appendChild(a)
- a.click()
- document.body.removeChild(a)
+ downloadComfyFile(item.filename, item.subfolder)
}
return (
@@ -78,7 +75,11 @@ export function Gallery() {
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: i * 0.02 }}
- onClick={() => setSelected(selected?.id === item.id ? null : item)}
+ onClick={() => {
+ setSelected(selected?.id === item.id ? null : item)
+ // Double-click opens viewer (single click selects)
+ }}
+ onDoubleClick={() => setViewerIndex(page * PAGE_SIZE + i)}
>
{item.type === 'video' ? (
<video
@@ -151,6 +152,15 @@ export function Gallery() {
)}
</AnimatePresence>
</div>
+
+ {/* Media Viewer */}
+ {viewerIndex !== null && (
+ <MediaViewer
+ gallery={gallery}
+ initialIndex={viewerIndex}
+ onClose={() => setViewerIndex(null)}
+ />
+ )}
</>
)
}
diff --git a/src/components/create/MediaViewer.tsx b/src/components/create/MediaViewer.tsx
new file mode 100644
index 00000000..c661532b
--- /dev/null
+++ b/src/components/create/MediaViewer.tsx
@@ -0,0 +1,218 @@
+import { useState, useEffect, useRef, useCallback } from 'react'
+import { motion, AnimatePresence } from 'framer-motion'
+import { X, Download, ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Info } from 'lucide-react'
+import { getImageUrl } from '../../api/comfyui'
+import { downloadComfyFile } from '../../api/backend'
+import type { GalleryItem } from '../../stores/createStore'
+
+interface Props {
+ gallery: GalleryItem[]
+ initialIndex: number
+ onClose: () => void
+}
+
+export function MediaViewer({ gallery, initialIndex, onClose }: Props) {
+ const [index, setIndex] = useState(initialIndex)
+ const [zoom, setZoom] = useState(1)
+ const [pan, setPan] = useState({ x: 0, y: 0 })
+ const [dragging, setDragging] = useState(false)
+ const [showInfo, setShowInfo] = useState(false)
+ const dragStart = useRef({ x: 0, y: 0 })
+ const panStart = useRef({ x: 0, y: 0 })
+
+ const item = gallery[index]
+ if (!item) return null
+
+ const url = getImageUrl(item.filename, item.subfolder)
+
+ const resetView = () => { setZoom(1); setPan({ x: 0, y: 0 }) }
+
+ const navigate = useCallback((dir: 1 | -1) => {
+ const next = index + dir
+ if (next >= 0 && next < gallery.length) {
+ setIndex(next)
+ resetView()
+ }
+ }, [index, gallery.length])
+
+ // Keyboard handlers
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ switch (e.key) {
+ case 'Escape': onClose(); break
+ case 'ArrowLeft': navigate(-1); break
+ case 'ArrowRight': navigate(1); break
+ case '+': case '=': setZoom(z => Math.min(z + 0.5, 5)); break
+ case '-': setZoom(z => Math.max(z - 0.5, 1)); if (zoom <= 1.5) setPan({ x: 0, y: 0 }); break
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [onClose, navigate, zoom])
+
+ // Mouse wheel zoom
+ const handleWheel = (e: React.WheelEvent) => {
+ e.preventDefault()
+ const delta = e.deltaY > 0 ? -0.2 : 0.2
+ setZoom(z => {
+ const next = Math.max(1, Math.min(5, z + delta))
+ if (next <= 1) setPan({ x: 0, y: 0 })
+ return next
+ })
+ }
+
+ // Pan (drag) handlers
+ const handleMouseDown = (e: React.MouseEvent) => {
+ if (zoom <= 1) return
+ e.preventDefault()
+ setDragging(true)
+ dragStart.current = { x: e.clientX, y: e.clientY }
+ panStart.current = { ...pan }
+ }
+
+ const handleMouseMove = (e: React.MouseEvent) => {
+ if (!dragging) return
+ setPan({
+ x: panStart.current.x + (e.clientX - dragStart.current.x),
+ y: panStart.current.y + (e.clientY - dragStart.current.y),
+ })
+ }
+
+ const handleMouseUp = () => setDragging(false)
+
+ const handleDownload = () => downloadComfyFile(item.filename, item.subfolder)
+
+ return (
+ <AnimatePresence>
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ className="fixed inset-0 z-50 bg-black/95 flex flex-col"
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ onMouseLeave={handleMouseUp}
+ >
+ {/* Top bar */}
+ <div className="flex items-center justify-between px-4 py-3 z-10">
+ <div className="text-white/60 text-sm">
+ {index + 1} / {gallery.length}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setZoom(z => Math.max(1, z - 0.5))}
+ className="p-2 rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
+ title="Zoom out (-)"
+ >
+ <ZoomOut size={18} />
+ </button>
+ <span className="text-white/60 text-xs w-12 text-center">{Math.round(zoom * 100)}%</span>
+ <button
+ onClick={() => setZoom(z => Math.min(5, z + 0.5))}
+ className="p-2 rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
+ title="Zoom in (+)"
+ >
+ <ZoomIn size={18} />
+ </button>
+ <button
+ onClick={() => setShowInfo(!showInfo)}
+ className={`p-2 rounded-full transition-colors ${showInfo ? 'bg-white/25 text-white' : 'bg-white/10 text-white hover:bg-white/20'}`}
+ title="Info"
+ >
+ <Info size={18} />
+ </button>
+ <button
+ onClick={handleDownload}
+ className="p-2 rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
+ title="Download"
+ >
+ <Download size={18} />
+ </button>
+ <button
+ onClick={onClose}
+ className="p-2 rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
+ title="Close (Esc)"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ </div>
+
+ {/* Main content */}
+ <div
+ className="flex-1 flex items-center justify-center overflow-hidden relative"
+ onWheel={handleWheel}
+ >
+ {/* Nav arrows */}
+ {index > 0 && (
+ <button
+ onClick={(e) => { e.stopPropagation(); navigate(-1) }}
+ className="absolute left-4 z-10 p-3 rounded-full bg-black/50 text-white hover:bg-black/70 transition-colors"
+ >
+ <ChevronLeft size={24} />
+ </button>
+ )}
+ {index < gallery.length - 1 && (
+ <button
+ onClick={(e) => { e.stopPropagation(); navigate(1) }}
+ className="absolute right-4 z-10 p-3 rounded-full bg-black/50 text-white hover:bg-black/70 transition-colors"
+ >
+ <ChevronRight size={24} />
+ </button>
+ )}
+
+ {/* Media */}
+ {item.type === 'video' ? (
+ <video
+ key={item.id}
+ src={url}
+ controls
+ autoPlay
+ loop
+ className="max-w-[90vw] max-h-[80vh]"
+ onClick={(e) => e.stopPropagation()}
+ />
+ ) : (
+ <img
+ key={item.id}
+ src={url}
+ alt={item.prompt}
+ className="max-w-[90vw] max-h-[80vh] object-contain select-none"
+ style={{
+ transform: `scale(${zoom}) translate(${pan.x / zoom}px, ${pan.y / zoom}px)`,
+ cursor: zoom > 1 ? (dragging ? 'grabbing' : 'grab') : 'default',
+ transition: dragging ? 'none' : 'transform 0.15s ease-out',
+ }}
+ onMouseDown={handleMouseDown}
+ draggable={false}
+ />
+ )}
+ </div>
+
+ {/* Info panel */}
+ <AnimatePresence>
+ {showInfo && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ className="overflow-hidden border-t border-white/10"
+ >
+ <div className="px-6 py-3 flex flex-wrap gap-x-6 gap-y-1 text-xs text-white/60">
+ <span><b className="text-white/80">Prompt:</b> {item.prompt}</span>
+ {item.negativePrompt && <span><b className="text-white/80">Negative:</b> {item.negativePrompt}</span>}
+ <span><b className="text-white/80">Model:</b> {item.model}</span>
+ <span><b className="text-white/80">Size:</b> {item.width}x{item.height}</span>
+ <span><b className="text-white/80">Steps:</b> {item.steps}</span>
+ <span><b className="text-white/80">CFG:</b> {item.cfgScale}</span>
+ <span><b className="text-white/80">Sampler:</b> {item.sampler}/{item.scheduler}</span>
+ <span><b className="text-white/80">Seed:</b> {item.seed}</span>
+ {item.builderUsed && <span><b className="text-white/80">Builder:</b> {item.builderUsed}</span>}
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </motion.div>
+ </AnimatePresence>
+ )
+}
diff --git a/src/components/create/OutputDisplay.tsx b/src/components/create/OutputDisplay.tsx
index 4af61725..d5e8c28c 100644
--- a/src/components/create/OutputDisplay.tsx
+++ b/src/components/create/OutputDisplay.tsx
@@ -1,23 +1,19 @@
import { useState } from 'react'
-import { motion, AnimatePresence } from 'framer-motion'
-import { Download, Maximize2, X, Copy, Check, RefreshCw } from 'lucide-react'
+import { motion } from 'framer-motion'
+import { Download, Maximize2, Copy, Check, RefreshCw, HardDrive, Brain, Cpu, Zap } from 'lucide-react'
import { getImageUrl } from '../../api/comfyui'
+import { downloadComfyFile } from '../../api/backend'
import { useCreateStore, type GalleryItem } from '../../stores/createStore'
+import { MediaViewer } from './MediaViewer'
export function OutputDisplay() {
- const { isGenerating, progress, progressText, gallery, lastGenTime } = useCreateStore()
- const [fullscreen, setFullscreen] = useState<GalleryItem | null>(null)
+ const { isGenerating, progress, progressText, progressPhase, gallery, lastGenTime } = useCreateStore()
+ const [viewerIndex, setViewerIndex] = useState<number | null>(null)
const [copiedSeed, setCopiedSeed] = useState(false)
const latest = gallery[0]
const handleDownload = (item: GalleryItem) => {
- const url = getImageUrl(item.filename, item.subfolder)
- const a = document.createElement('a')
- a.href = url
- a.download = item.filename
- document.body.appendChild(a)
- a.click()
- document.body.removeChild(a)
+ downloadComfyFile(item.filename, item.subfolder)
}
const copySeed = (seed: number) => {
@@ -26,32 +22,93 @@ export function OutputDisplay() {
setTimeout(() => setCopiedSeed(false), 1500)
}
+ // Phase-aware icon
+ const phaseIcon = () => {
+ switch (progressPhase) {
+ case 'loading-model': return <HardDrive size={20} className="text-amber-400" />
+ case 'loading-clip': return <Brain size={20} className="text-blue-400" />
+ case 'loading-vae': return <Cpu size={20} className="text-purple-400" />
+ case 'sampling': return <Zap size={20} className="text-green-400" />
+ case 'decoding': return <RefreshCw size={20} className="text-cyan-400" />
+ default: return null
+ }
+ }
+
+ const isLoading = progressPhase === 'loading-model' || progressPhase === 'loading-clip' || progressPhase === 'loading-vae'
+
// Generating state
if (isGenerating) {
return (
<div className="flex-1 flex flex-col items-center justify-center p-8">
<div className="space-y-6 flex flex-col items-center">
- {/* Minimal pulse ring animation */}
+ {/* Phase-aware animation */}
<div className="relative w-16 h-16">
- <motion.div
- className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/20"
- animate={{ scale: [1, 1.8], opacity: [0.4, 0] }}
- transition={{ duration: 2, repeat: Infinity, ease: 'easeOut' }}
- />
- <motion.div
- className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/15"
- animate={{ scale: [1, 1.5], opacity: [0.3, 0] }}
- transition={{ duration: 2, repeat: Infinity, ease: 'easeOut', delay: 0.5 }}
- />
- <div className="absolute inset-0 rounded-full border border-gray-200 dark:border-white/10 flex items-center justify-center">
+ {isLoading ? (
+ /* Slower breathing animation for model loading */
+ <>
+ <motion.div
+ className="absolute inset-0 rounded-full border border-amber-400/30"
+ animate={{ scale: [1, 1.6], opacity: [0.5, 0] }}
+ transition={{ duration: 3, repeat: Infinity, ease: 'easeOut' }}
+ />
+ <div className="absolute inset-0 rounded-full border border-amber-400/20 flex items-center justify-center">
+ <motion.div animate={{ rotate: 360 }} transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}>
+ {phaseIcon()}
+ </motion.div>
+ </div>
+ </>
+ ) : progressPhase === 'sampling' ? (
+ /* Faster pulse for sampling */
+ <>
+ <motion.div
+ className="absolute inset-0 rounded-full border border-green-400/30"
+ animate={{ scale: [1, 1.8], opacity: [0.4, 0] }}
+ transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut' }}
+ />
+ <motion.div
+ className="absolute inset-0 rounded-full border border-green-400/20"
+ animate={{ scale: [1, 1.5], opacity: [0.3, 0] }}
+ transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut', delay: 0.3 }}
+ />
+ <div className="absolute inset-0 rounded-full border border-green-400/10 flex items-center justify-center">
+ {phaseIcon()}
+ </div>
+ </>
+ ) : (
+ /* Default pulse */
+ <>
+ <motion.div
+ className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/20"
+ animate={{ scale: [1, 1.8], opacity: [0.4, 0] }}
+ transition={{ duration: 2, repeat: Infinity, ease: 'easeOut' }}
+ />
+ <motion.div
+ className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/15"
+ animate={{ scale: [1, 1.5], opacity: [0.3, 0] }}
+ transition={{ duration: 2, repeat: Infinity, ease: 'easeOut', delay: 0.5 }}
+ />
+ <div className="absolute inset-0 rounded-full border border-gray-200 dark:border-white/10 flex items-center justify-center">
+ <motion.div
+ className="w-2 h-2 rounded-full bg-gray-400 dark:bg-white/40"
+ animate={{ opacity: [0.3, 0.8, 0.3] }}
+ transition={{ duration: 1.5, repeat: Infinity }}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ <p className="text-gray-500 text-xs tracking-wide">{progressText || 'Generating...'}</p>
+ {/* Progress bar for sampling */}
+ {progressPhase === 'sampling' && progress > 0 && (
+ <div className="w-48 h-1 bg-gray-200 dark:bg-white/10 rounded-full overflow-hidden">
<motion.div
- className="w-2 h-2 rounded-full bg-gray-400 dark:bg-white/40"
- animate={{ opacity: [0.3, 0.8, 0.3] }}
- transition={{ duration: 1.5, repeat: Infinity }}
+ className="h-full bg-green-400 rounded-full"
+ initial={{ width: 0 }}
+ animate={{ width: `${Math.min(progress, 100)}%` }}
+ transition={{ duration: 0.3 }}
/>
</div>
- </div>
- <p className="text-gray-500 text-xs tracking-wide">{progressText || 'Generating...'}</p>
+ )}
</div>
</div>
)
@@ -89,21 +146,22 @@ export function OutputDisplay() {
controls
autoPlay
loop
- className="max-w-full max-h-full rounded-xl border border-gray-200 dark:border-white/10 object-contain"
+ className="max-w-full max-h-full rounded-xl border border-gray-200 dark:border-white/10 object-contain cursor-pointer"
+ onClick={() => setViewerIndex(0)}
/>
) : (
<img
src={url}
alt={latest.prompt}
className="max-w-full max-h-full rounded-xl border border-gray-200 dark:border-white/10 object-contain cursor-pointer"
- onClick={() => setFullscreen(latest)}
+ onClick={() => setViewerIndex(0)}
/>
)}
{/* Hover controls */}
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
<button
- onClick={() => setFullscreen(latest)}
+ onClick={() => setViewerIndex(0)}
className="p-2 rounded-lg bg-black/50 text-white hover:bg-black/70 transition-colors"
title="Fullscreen"
>
@@ -141,48 +199,14 @@ export function OutputDisplay() {
</div>
</div>
- {/* Fullscreen overlay */}
- <AnimatePresence>
- {fullscreen && (
- <motion.div
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
- onClick={() => setFullscreen(null)}
- >
- <button
- className="absolute top-4 right-4 p-2 rounded-full bg-white/10 text-white hover:bg-white/20 z-50"
- onClick={() => setFullscreen(null)}
- >
- <X size={20} />
- </button>
- <button
- className="absolute top-4 right-14 p-2 rounded-full bg-white/10 text-white hover:bg-white/20 z-50"
- onClick={(e) => { e.stopPropagation(); handleDownload(fullscreen) }}
- >
- <Download size={20} />
- </button>
- {fullscreen.type === 'video' ? (
- <video
- src={getImageUrl(fullscreen.filename, fullscreen.subfolder)}
- controls
- autoPlay
- loop
- className="max-w-[95vw] max-h-[95vh]"
- onClick={(e) => e.stopPropagation()}
- />
- ) : (
- <img
- src={getImageUrl(fullscreen.filename, fullscreen.subfolder)}
- alt={fullscreen.prompt}
- className="max-w-[95vw] max-h-[95vh] object-contain"
- onClick={(e) => e.stopPropagation()}
- />
- )}
- </motion.div>
- )}
- </AnimatePresence>
+ {/* Media Viewer */}
+ {viewerIndex !== null && (
+ <MediaViewer
+ gallery={gallery}
+ initialIndex={viewerIndex}
+ onClose={() => setViewerIndex(null)}
+ />
+ )}
</>
)
}
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 01fe7484..f7633141 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -5,7 +5,6 @@ import { ChatView } from '../chat/ChatView'
import { ModelManager } from '../models/ModelManager'
import { SettingsPage } from '../settings/SettingsPage'
import { CreateView } from '../create/CreateView'
-import { AgentView } from '../agents/AgentView'
import { Onboarding } from '../onboarding/Onboarding'
import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
@@ -35,7 +34,6 @@ export function AppShell() {
{currentView === 'models' && <ModelManager />}
{currentView === 'settings' && <SettingsPage />}
{currentView === 'create' && <CreateView />}
- {currentView === 'agents' && <AgentView />}
</main>
</div>
</div>
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx
index b85c8bcb..ce50950d 100644
--- a/src/components/layout/Header.tsx
+++ b/src/components/layout/Header.tsx
@@ -1,4 +1,4 @@
-import { Menu, Settings, Sun, Moon, MessageSquare, Film, Layers, Bot } from 'lucide-react'
+import { Menu, Settings, Sun, Moon, MessageSquare, Film, Layers } from 'lucide-react'
import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useChatStore } from '../../stores/chatStore'
@@ -12,77 +12,59 @@ export function Header() {
updateSettings({ theme: settings.theme === 'dark' ? 'light' : 'dark' })
}
+ const navBtn = (view: string, icon: React.ReactNode, title: string) => (
+ <button
+ onClick={() => setView(view as any)}
+ className={`p-1.5 rounded-md transition-colors ${
+ currentView === view
+ ? 'bg-white/10 text-white'
+ : 'text-gray-500 hover:text-gray-200 hover:bg-white/5'
+ }`}
+ title={title}
+ >
+ {icon}
+ </button>
+ )
+
return (
- <header className="h-14 flex items-center justify-between px-4 border-b border-gray-200 dark:border-white/[0.06] bg-white dark:bg-[#111111] z-20">
+ <header className="h-10 flex items-center justify-between px-3 border-b border-white/[0.04] bg-[#0e0e0e] z-20">
{/* Left: Sidebar + Logo */}
- <div className="flex items-center gap-3">
+ <div className="flex items-center gap-2">
<button
onClick={toggleSidebar}
- className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
+ className="p-1 rounded-md hover:bg-white/5 text-gray-500 hover:text-white transition-colors"
aria-label="Toggle sidebar"
>
- <Menu size={20} />
+ <Menu size={15} />
</button>
<button
onClick={() => {
useChatStore.getState().setActiveConversation(null)
setView('chat')
}}
- className="flex items-center gap-2 text-gray-800 dark:text-gray-200 hover:opacity-80 transition"
+ className="flex items-center gap-1.5 text-gray-300 hover:text-white transition"
>
- <img src="/LU-monogram-bw.png" alt="" width={22} height={22} className="dark:invert-0 invert" />
- <span className="font-bold text-sm tracking-wider">LOCALLY UNCENSORED</span>
+ <img src="/LU-monogram-bw.png" alt="" width={16} height={16} className="dark:invert-0 invert opacity-70" />
+ <span className="font-semibold text-[0.7rem] tracking-wide">LUncensored</span>
</button>
</div>
{/* Center: Model Selector */}
<ModelSelector />
- {/* Right: Actions */}
- <div className="flex items-center gap-1">
+ {/* Right: Nav icons */}
+ <div className="flex items-center gap-0.5">
<button
onClick={toggleTheme}
- className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
+ className="p-1.5 rounded-md text-gray-500 hover:text-gray-200 hover:bg-white/5 transition-colors"
title={settings.theme === 'dark' ? 'Light Mode' : 'Dark Mode'}
- aria-label={settings.theme === 'dark' ? 'Light Mode' : 'Dark Mode'}
- >
- {settings.theme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
- </button>
- <button
- onClick={() => setView('chat')}
- className={`p-2 rounded-lg transition-colors ${currentView === 'chat' ? 'bg-blue-100 dark:bg-blue-500/15 text-blue-600 dark:text-blue-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}
- title="Text Chat"
- >
- <MessageSquare size={18} />
- </button>
- <button
- onClick={() => setView('create')}
- className={`p-2 rounded-lg transition-colors ${currentView === 'create' ? 'bg-purple-100 dark:bg-purple-500/15 text-purple-600 dark:text-purple-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}
- title="Create Images & Videos"
- >
- <Film size={18} />
- </button>
- <button
- onClick={() => setView('agents')}
- className={`p-2 rounded-lg transition-colors ${currentView === 'agents' ? 'bg-green-100 dark:bg-green-500/15 text-green-600 dark:text-green-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}
- title="AI Agents"
- >
- <Bot size={18} />
- </button>
- <button
- onClick={() => setView('models')}
- className={`p-2 rounded-lg transition-colors ${currentView === 'models' ? 'bg-blue-100 dark:bg-blue-500/15 text-blue-600 dark:text-blue-300' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}
- title="Model Manager"
- >
- <Layers size={18} />
- </button>
- <button
- onClick={() => setView('settings')}
- className={`p-2 rounded-lg transition-colors ${currentView === 'settings' ? 'bg-gray-200 dark:bg-white/15 text-gray-900 dark:text-white' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'}`}
- title="Settings"
>
- <Settings size={18} />
+ {settings.theme === 'dark' ? <Sun size={14} /> : <Moon size={14} />}
</button>
+ {navBtn('chat', <MessageSquare size={14} />, 'Chat')}
+ {navBtn('create', <Film size={14} />, 'Create')}
+ {navBtn('models', <Layers size={14} />, 'Models')}
+ {navBtn('settings', <Settings size={14} />, 'Settings')}
</div>
</header>
)
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
index 106df8a7..074ffeee 100644
--- a/src/components/layout/Sidebar.tsx
+++ b/src/components/layout/Sidebar.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { Plus, Search, MessageSquare, Trash2, Edit3, Check, X } from 'lucide-react'
+import { Plus, Search, Trash2, Edit3, Check, X } from 'lucide-react'
import { useChatStore } from '../../stores/chatStore'
import { useUIStore } from '../../stores/uiStore'
import { useModelStore } from '../../stores/modelStore'
@@ -43,49 +43,49 @@ export function Sidebar() {
<AnimatePresence>
{sidebarOpen && (
<motion.aside
- className="w-72 h-full border-r border-gray-200 dark:border-white/[0.06] bg-gray-50 dark:bg-[#0e0e0e] flex flex-col z-20 overflow-hidden"
+ className="w-56 h-full border-r border-white/[0.04] bg-[#0a0a0a] flex flex-col z-20 overflow-hidden"
initial={{ width: 0, opacity: 0 }}
- animate={{ width: 288, opacity: 1 }}
+ animate={{ width: 224, opacity: 1 }}
exit={{ width: 0, opacity: 0 }}
- transition={{ duration: 0.2 }}
+ transition={{ duration: 0.15 }}
>
- <div className="p-3 space-y-3">
+ {/* 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-2 px-3 py-2.5 rounded-lg bg-gray-200 dark:bg-white/[0.08] border border-gray-300 dark:border-white/[0.1] text-gray-800 dark:text-white hover:bg-gray-300 dark:hover:bg-white/[0.12] transition-all"
+ className="w-full flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.7rem] text-gray-400 hover:text-white hover:bg-white/[0.05] transition-all"
>
- <Plus size={18} />
- <span className="text-sm font-medium">New Chat</span>
+ <Plus size={13} />
+ <span>New Chat</span>
</button>
<div className="relative">
- <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <Search size={11} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-600" />
<input
type="text"
- placeholder="Search conversations..."
+ placeholder="Search..."
value={search}
onChange={(e) => setSearch(e.target.value)}
- className="w-full pl-9 pr-3 py-2 rounded-lg bg-gray-100 dark:bg-white/[0.04] border border-gray-300 dark:border-white/[0.08] text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:border-gray-400 dark:focus:border-white/20"
+ className="w-full pl-6 pr-2 py-1 rounded-md bg-transparent border border-white/[0.04] text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/10"
/>
</div>
</div>
- <div className="flex-1 overflow-y-auto px-2 space-y-0.5 scrollbar-thin">
+ {/* Conversations */}
+ <div className="flex-1 overflow-y-auto px-1.5 pt-1 space-y-px scrollbar-thin">
{filtered.map((conv) => (
- <motion.div
+ <div
key={conv.id}
- className={`group flex items-center gap-2 px-3 py-2.5 rounded-lg cursor-pointer transition-all ${
+ className={`group flex items-center gap-1.5 px-2 py-1.5 rounded-md cursor-pointer transition-all ${
conv.id === activeConversationId
- ? 'bg-gray-200 dark:bg-white/[0.08] border border-gray-300 dark:border-white/[0.1]'
- : 'hover:bg-gray-100 dark:hover:bg-white/[0.04] border border-transparent'
+ ? 'bg-white/[0.06] text-white'
+ : 'text-gray-400 hover:bg-white/[0.03] hover:text-gray-200'
}`}
onClick={() => {
setActiveConversation(conv.id)
setView('chat')
}}
- layout
>
- <MessageSquare size={16} className="text-gray-500 shrink-0" />
<div className="flex-1 min-w-0">
{editingId === conv.id ? (
<div className="flex items-center gap-1">
@@ -93,51 +93,42 @@ export function Sidebar() {
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleRename(conv.id)}
- className="w-full bg-white/10 rounded px-1 py-0.5 text-sm text-white focus:outline-none"
+ className="w-full bg-white/5 rounded px-1 py-0.5 text-[0.65rem] text-white focus:outline-none"
autoFocus
onClick={(e) => e.stopPropagation()}
/>
- <button onClick={(e) => { e.stopPropagation(); handleRename(conv.id) }} className="text-green-400" aria-label="Confirm rename"><Check size={14} /></button>
- <button onClick={(e) => { e.stopPropagation(); setEditingId(null) }} className="text-gray-400" aria-label="Cancel rename"><X size={14} /></button>
+ <button onClick={(e) => { e.stopPropagation(); handleRename(conv.id) }} className="text-green-400"><Check size={11} /></button>
+ <button onClick={(e) => { e.stopPropagation(); setEditingId(null) }} className="text-gray-500"><X size={11} /></button>
</div>
) : (
<>
- <p className="text-sm text-gray-800 dark:text-white truncate">{truncate(conv.title, 30)}</p>
- <p className="text-xs text-gray-500">{formatDate(conv.updatedAt)}</p>
+ <p className="text-[0.68rem] truncate">{truncate(conv.title, 28)}</p>
+ <p className="text-[0.55rem] text-gray-600">{formatDate(conv.updatedAt)}</p>
</>
)}
</div>
{editingId !== conv.id && (
- <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<button
- onClick={(e) => {
- e.stopPropagation()
- setEditingId(conv.id)
- setEditTitle(conv.title)
- }}
- className="p-1 rounded hover:bg-white/10 text-gray-400"
- aria-label="Rename conversation"
+ onClick={(e) => { e.stopPropagation(); setEditingId(conv.id); setEditTitle(conv.title) }}
+ className="p-0.5 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300"
>
- <Edit3 size={12} />
+ <Edit3 size={10} />
</button>
<button
- onClick={(e) => {
- e.stopPropagation()
- deleteConversation(conv.id)
- }}
- className="p-1 rounded hover:bg-red-500/20 text-gray-400 hover:text-red-400"
- aria-label="Delete conversation"
+ onClick={(e) => { e.stopPropagation(); deleteConversation(conv.id) }}
+ className="p-0.5 rounded hover:bg-red-500/20 text-gray-500 hover:text-red-400"
>
- <Trash2 size={12} />
+ <Trash2 size={10} />
</button>
</div>
)}
- </motion.div>
+ </div>
))}
{filtered.length === 0 && (
- <p className="text-center text-gray-500 text-sm py-8">
- {search ? 'No results found' : 'No conversations yet'}
+ <p className="text-center text-gray-600 text-[0.6rem] py-6">
+ {search ? 'No results' : 'No conversations'}
</p>
)}
</div>
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index 28ba03bf..7ca1a981 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -21,6 +21,73 @@ interface Props {
category: ModelCategory
}
+// Variant selector for text models with multiple sizes
+function VariantPullButton({ model, pullModel, isPulling, isInstalled }: {
+ model: DiscoverModel
+ pullModel: (name: string) => void
+ isPulling: boolean
+ isInstalled: (name: string) => boolean
+}) {
+ const [open, setOpen] = useState(false)
+ const tags = model.tags.filter(t => /^\d+B/.test(t) || /^Q\d/.test(t))
+
+ // If no size tags or only one, show simple button
+ if (tags.length <= 1) {
+ const fullName = tags.length === 1 ? `${model.name}:${tags[0].toLowerCase()}` : model.name
+ if (isInstalled(model.name)) {
+ return <span className="text-xs text-green-500 px-2 py-1">Installed</span>
+ }
+ return (
+ <button
+ onClick={() => pullModel(fullName)}
+ disabled={isPulling}
+ className="p-2 rounded-lg bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 text-gray-700 dark:text-white disabled:opacity-30 transition-all"
+ title={`Install ${fullName}`}
+ >
+ <Download size={14} />
+ </button>
+ )
+ }
+
+ // Multiple variants → dropdown
+ return (
+ <div className="relative">
+ <button
+ onClick={() => setOpen(!open)}
+ disabled={isPulling}
+ className="flex items-center gap-1 px-2 py-1.5 rounded-lg bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 text-gray-700 dark:text-white disabled:opacity-30 transition-all text-xs"
+ >
+ <Download size={12} />
+ <span>Install</span>
+ <svg className={`w-3 h-3 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
+ </button>
+ {open && (
+ <div className="absolute right-0 top-full mt-1 z-50 min-w-[120px] rounded-lg bg-gray-100 dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-lg overflow-hidden">
+ {tags.map(tag => {
+ const fullName = `${model.name}:${tag.toLowerCase()}`
+ const installed = isInstalled(fullName)
+ return (
+ <button
+ key={tag}
+ onClick={() => { if (!installed) pullModel(fullName); setOpen(false) }}
+ disabled={installed || isPulling}
+ className="w-full flex items-center justify-between gap-3 px-3 py-2 text-xs hover:bg-gray-200 dark:hover:bg-white/10 transition-colors disabled:opacity-50"
+ >
+ <span className="text-gray-800 dark:text-white font-medium">{tag}</span>
+ {installed ? (
+ <CheckCircle size={12} className="text-green-500" />
+ ) : (
+ <Download size={12} className="text-gray-400" />
+ )}
+ </button>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )
+}
+
export function DiscoverModels({ category }: Props) {
const [textModels, setTextModels] = useState<DiscoverModel[]>([])
const [civitaiResults, setCivitaiResults] = useState<CivitAIModelResult[]>([])
@@ -97,8 +164,11 @@ export function DiscoverModels({ category }: Props) {
return match ? parseInt(match[1]) : 99
}
- // Sort bundles: recommended first (fits in VRAM), then by size ascending
+ // Sort bundles: HOT first, then recommended (fits VRAM), then by size
const sortedBundles = [...bundles].sort((a, b) => {
+ // HOT models always first
+ if (a.hot && !b.hot) return -1
+ if (!a.hot && b.hot) return 1
if (systemVRAM) {
const aFits = parseVRAM(a.vramRequired) <= systemVRAM
const bFits = parseVRAM(b.vramRequired) <= systemVRAM
@@ -324,7 +394,10 @@ export function DiscoverModels({ category }: Props) {
<GlassCard className="p-4">
<div className="flex items-start justify-between gap-3 mb-3">
<div>
- <h3 className="text-sm font-semibold text-gray-900 dark:text-white">{bundle.name}</h3>
+ <h3 className="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-1.5">
+ {bundle.hot && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-500 font-bold border border-orange-500/30">HOT</span>}
+ {bundle.name}
+ </h3>
<p className="text-xs text-gray-500 mt-0.5">{bundle.description}</p>
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
{bundle.tags.map(t => (
@@ -528,7 +601,11 @@ export function DiscoverModels({ category }: Props) {
<GlassCard className="p-3">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
- <h3 className="text-sm font-medium text-gray-900 dark:text-white truncate">{model.name}</h3>
+ <h3 className="text-sm font-medium text-gray-900 dark:text-white truncate flex items-center gap-1.5">
+ {model.hot && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-orange-500/15 text-orange-500 font-bold border border-orange-500/30 shrink-0">HOT</span>}
+ {model.agent && <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-green-500/15 text-green-500 font-bold border border-green-500/30 shrink-0">AGENT</span>}
+ <span className="truncate">{model.name}</span>
+ </h3>
{model.description && (
<p className="text-xs text-gray-500 mt-0.5">{model.description}</p>
)}
@@ -565,19 +642,8 @@ export function DiscoverModels({ category }: Props) {
<div className="flex items-center gap-1 shrink-0">
{isText ? (
- // Ollama: direct install
- isInstalled(model.name) ? (
- <span className="text-xs text-green-500 px-2 py-1">Installed</span>
- ) : (
- <button
- onClick={() => pullModel(model.name)}
- disabled={isPulling}
- className="p-2 rounded-lg bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 text-gray-700 dark:text-white disabled:opacity-30 transition-all"
- title="Install model"
- >
- <Download size={14} />
- </button>
- )
+ // Ollama: variant selector for multi-size models
+ <VariantPullButton model={model} pullModel={pullModel} isPulling={isPulling} isInstalled={isInstalled} />
) : (
// ComfyUI models
<>
diff --git a/src/components/models/ModelCard.tsx b/src/components/models/ModelCard.tsx
index 62165752..cf22176d 100644
--- a/src/components/models/ModelCard.tsx
+++ b/src/components/models/ModelCard.tsx
@@ -1,5 +1,4 @@
import { Trash2, Info, MessageSquare, Image, Video } from 'lucide-react'
-import { GlassCard } from '../ui/GlassCard'
import { formatBytes } from '../../lib/formatters'
import type { AIModel } from '../../types/models'
@@ -12,9 +11,9 @@ interface Props {
}
const TYPE_CONFIG = {
- text: { label: 'Text', icon: MessageSquare, color: 'bg-blue-500/15 text-blue-300' },
- image: { label: 'Image', icon: Image, color: 'bg-purple-500/15 text-purple-300' },
- video: { label: 'Video', icon: Video, color: 'bg-green-500/15 text-green-300' },
+ text: { label: 'Text', icon: MessageSquare, color: 'text-blue-400' },
+ image: { label: 'Image', icon: Image, color: 'text-purple-400' },
+ video: { label: 'Video', icon: Video, color: 'text-green-400' },
}
export function ModelCard({ model, isActive, onSelect, onDelete, onInfo }: Props) {
@@ -22,49 +21,55 @@ export function ModelCard({ model, isActive, onSelect, onDelete, onInfo }: Props
const TypeIcon = typeInfo.icon
return (
- <GlassCard hover className={`cursor-pointer ${isActive ? 'border-white/15' : ''}`}>
- <div onClick={onSelect}>
- <div className="flex items-start justify-between mb-2">
- <h3 className="font-semibold text-gray-900 dark:text-white text-sm truncate flex-1">{model.name}</h3>
- {isActive && (
- <span className="text-xs bg-gray-200 dark:bg-white/10 text-gray-700 dark:text-white px-2 py-0.5 rounded-full ml-2 shrink-0">
- Active
- </span>
- )}
+ <div
+ onClick={onSelect}
+ className={`flex items-center gap-3 px-3 py-2 rounded-lg cursor-pointer transition-all group ${
+ isActive
+ ? 'bg-white/[0.04] border-l-2 border-l-blue-400'
+ : 'hover:bg-white/[0.02] border-l-2 border-l-transparent'
+ }`}
+ >
+ {/* Type icon */}
+ <TypeIcon size={13} className={`${typeInfo.color} shrink-0`} />
+
+ {/* Name + details */}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-[0.72rem] text-gray-200 font-medium truncate">{model.name}</span>
+ {isActive && <span className="text-[0.5rem] text-blue-400 font-medium uppercase">Active</span>}
</div>
- <div className="space-y-1 text-xs text-gray-500 dark:text-gray-400">
- <div className="flex items-center gap-1.5 mb-1">
- <span className={`text-[10px] px-1.5 py-0.5 rounded font-medium flex items-center gap-1 ${typeInfo.color}`}>
- <TypeIcon size={10} /> {typeInfo.label}
- </span>
- </div>
- {model.size > 0 && <p>Size: {formatBytes(model.size)}</p>}
+ <div className="flex items-center gap-2 text-[0.6rem] text-gray-500">
+ {model.size > 0 && <span>{formatBytes(model.size)}</span>}
{model.type === 'text' && 'details' in model && (
<>
- <p>Family: {model.details?.family || 'unknown'}</p>
- <p>Parameters: {model.details?.parameter_size || 'unknown'}</p>
- <p>Quantization: {model.details?.quantization_level || 'unknown'}</p>
+ {model.details?.family && <span>{model.details.family}</span>}
+ {model.details?.parameter_size && <span>{model.details.parameter_size}</span>}
+ {model.details?.quantization_level && <span>{model.details.quantization_level}</span>}
</>
)}
- {(model.type === 'image' || model.type === 'video') && 'architecture' in model && (
- <p>Format: {model.format || 'safetensors'}</p>
+ {(model.type === 'image' || model.type === 'video') && (
+ <span>{model.format || 'safetensors'}</span>
)}
</div>
</div>
- <div className="flex items-center gap-2 mt-3 pt-3 border-t border-gray-200 dark:border-white/5">
+
+ {/* Actions (visible on hover) */}
+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<button
onClick={(e) => { e.stopPropagation(); onInfo() }}
- className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
+ className="p-1 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300 transition-colors"
+ title="Details"
>
- <Info size={14} /> Details
+ <Info size={12} />
</button>
<button
onClick={(e) => { e.stopPropagation(); onDelete() }}
- className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-red-400 transition-colors ml-auto"
+ className="p-1 rounded hover:bg-red-500/20 text-gray-500 hover:text-red-400 transition-colors"
+ title="Delete"
>
- <Trash2 size={14} /> Delete
+ <Trash2 size={12} />
</button>
</div>
- </GlassCard>
+ </div>
)
}
diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsx
index 604c687f..c4362075 100644
--- a/src/components/models/ModelManager.tsx
+++ b/src/components/models/ModelManager.tsx
@@ -87,7 +87,7 @@ export function ModelManager() {
>
<ArrowLeft size={20} />
</button>
- <h1 className="text-xl font-bold text-gray-900 dark:text-white">Model Manager</h1>
+ <h1 className="text-[0.85rem] font-semibold text-gray-800 dark:text-gray-200">Model Manager</h1>
</div>
<div className="flex items-center gap-2">
<GlowButton variant="secondary" onClick={fetchModels}>
@@ -185,13 +185,13 @@ export function ModelManager() {
{tab === 'installed' && (
<>
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
+ <div className="space-y-0.5">
{filteredModels.map((model, i) => (
<motion.div
key={model.name}
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: i * 0.05 }}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ delay: i * 0.02 }}
>
<ModelCard
model={model}
diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsx
index 3e4082dd..b9cb9124 100644
--- a/src/components/models/ModelSelector.tsx
+++ b/src/components/models/ModelSelector.tsx
@@ -1,7 +1,8 @@
import { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { ChevronDown, Check, MessageSquare, Image, Video } from 'lucide-react'
+import { ChevronDown, Check, MessageSquare, Image, Video, Loader2, Power } from 'lucide-react'
import { useModels } from '../../hooks/useModels'
+import { unloadAllModels } from '../../api/ollama'
import { formatBytes } from '../../lib/formatters'
import type { AIModel } from '../../types/models'
@@ -14,6 +15,8 @@ const TYPE_BADGE: Record<string, { label: string; color: string }> = {
export function ModelSelector() {
const { models, activeModel, setActiveModel, fetchModels } = useModels()
const [open, setOpen] = useState(false)
+ const [unloading, setUnloading] = useState(false)
+ const [unloadDone, setUnloadDone] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -96,6 +99,32 @@ export function ModelSelector() {
</button>
)
})}
+
+ {/* Unload All text models button */}
+ {models.some(m => m.type === 'text') && (
+ <>
+ <div className="border-t border-gray-200 dark:border-white/10 my-1" />
+ <button
+ onClick={async (e) => {
+ e.stopPropagation()
+ if (unloading) return
+ setUnloading(true)
+ setUnloadDone(false)
+ try {
+ await unloadAllModels()
+ setUnloadDone(true)
+ setTimeout(() => setUnloadDone(false), 2000)
+ } catch { /* ignore */ }
+ finally { setUnloading(false) }
+ }}
+ disabled={unloading}
+ className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-left text-xs text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50"
+ >
+ {unloading ? <Loader2 size={14} className="animate-spin" /> : <Power size={14} />}
+ <span>{unloadDone ? 'Models unloaded!' : unloading ? 'Unloading...' : 'Unload all text models'}</span>
+ </button>
+ </>
+ )}
</div>
</motion.div>
)}
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
new file mode 100644
index 00000000..8dc33a00
--- /dev/null
+++ b/src/components/settings/MemorySettings.tsx
@@ -0,0 +1,171 @@
+import { useState, useRef } from 'react'
+import { Brain, Download, Upload, Trash2, Search, Tag } from 'lucide-react'
+import { useMemoryStore } from '../../stores/memoryStore'
+import { GlowButton } from '../ui/GlowButton'
+import type { MemoryCategory } from '../../types/agent-mode'
+
+const CATEGORY_LABELS: Record<MemoryCategory, string> = {
+ fact: 'Facts',
+ tool_result: 'Tool Results',
+ decision: 'Decisions',
+ context: 'Context',
+}
+
+const CATEGORY_COLORS: Record<MemoryCategory, string> = {
+ fact: 'bg-blue-500/15 text-blue-400 border-blue-500/30',
+ tool_result: 'bg-green-500/15 text-green-400 border-green-500/30',
+ decision: 'bg-purple-500/15 text-purple-400 border-purple-500/30',
+ context: 'bg-amber-500/15 text-amber-400 border-amber-500/30',
+}
+
+export function MemorySettings() {
+ const { entries, removeEntry, clearAll, exportAsMarkdown, importFromMarkdown } = useMemoryStore()
+ const [search, setSearch] = useState('')
+ const [activeCategory, setActiveCategory] = useState<MemoryCategory | 'all'>('all')
+ const [confirmClear, setConfirmClear] = useState(false)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const filtered = entries.filter(e => {
+ if (activeCategory !== 'all' && e.category !== activeCategory) return false
+ if (search) {
+ return e.content.toLowerCase().includes(search.toLowerCase())
+ }
+ return true
+ })
+
+ const handleExport = () => {
+ const md = exportAsMarkdown()
+ const blob = new Blob([md], { type: 'text/markdown' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = 'agent-memory.md'
+ a.click()
+ URL.revokeObjectURL(url)
+ }
+
+ const handleImport = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0]
+ if (!file) return
+ const reader = new FileReader()
+ reader.onload = (ev) => {
+ const content = ev.target?.result as string
+ if (content) importFromMarkdown(content)
+ }
+ reader.readAsText(file)
+ e.target.value = '' // reset
+ }
+
+ const handleClear = () => {
+ if (!confirmClear) {
+ setConfirmClear(true)
+ setTimeout(() => setConfirmClear(false), 3000)
+ return
+ }
+ clearAll()
+ setConfirmClear(false)
+ }
+
+ const categories: (MemoryCategory | 'all')[] = ['all', 'fact', 'tool_result', 'decision', 'context']
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Brain size={16} className="text-purple-400" />
+ <h2 className="text-sm font-semibold text-gray-900 dark:text-white uppercase tracking-wider">Agent Memory</h2>
+ </div>
+ <span className="text-[0.65rem] text-gray-500">
+ {entries.length} {entries.length === 1 ? 'entry' : 'entries'}
+ </span>
+ </div>
+
+ {/* Search */}
+ <div className="relative">
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search memory..."
+ className="w-full pl-8 pr-3 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-300 dark:border-white/10 text-sm text-gray-900 dark:text-white placeholder-gray-500 focus:outline-none focus:border-gray-400 dark:focus:border-white/20"
+ />
+ </div>
+
+ {/* Category tabs */}
+ <div className="flex gap-1 flex-wrap">
+ {categories.map(cat => (
+ <button
+ key={cat}
+ onClick={() => setActiveCategory(cat)}
+ className={`text-[0.65rem] px-2 py-1 rounded-full border transition-colors ${
+ activeCategory === cat
+ ? 'border-white/30 bg-white/10 text-white'
+ : 'border-white/10 text-gray-500 hover:text-gray-300 hover:border-white/20'
+ }`}
+ >
+ {cat === 'all' ? 'All' : CATEGORY_LABELS[cat]}
+ {cat !== 'all' && (
+ <span className="ml-1 text-gray-600">
+ {entries.filter(e => e.category === cat).length}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+
+ {/* Entries list */}
+ <div className="space-y-1 max-h-[300px] overflow-y-auto scrollbar-thin">
+ {filtered.length === 0 && (
+ <p className="text-[0.7rem] text-gray-500 text-center py-4">
+ {entries.length === 0 ? 'No memories yet. Agent Mode will auto-save tool results here.' : 'No matching entries.'}
+ </p>
+ )}
+ {filtered.map(entry => (
+ <div key={entry.id} className="flex items-start gap-2 px-2 py-1.5 rounded-lg hover:bg-white/[0.03] group">
+ <Tag size={10} className={`mt-1 shrink-0 ${
+ entry.category === 'fact' ? 'text-blue-400' :
+ entry.category === 'tool_result' ? 'text-green-400' :
+ entry.category === 'decision' ? 'text-purple-400' : 'text-amber-400'
+ }`} />
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.7rem] text-gray-300 break-words">{entry.content}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className={`text-[0.55rem] px-1 py-0.5 rounded border ${CATEGORY_COLORS[entry.category]}`}>
+ {CATEGORY_LABELS[entry.category]}
+ </span>
+ {entry.source && (
+ <span className="text-[0.55rem] text-gray-600">{entry.source}</span>
+ )}
+ </div>
+ </div>
+ <button
+ onClick={() => removeEntry(entry.id)}
+ className="opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-red-500/20 text-gray-500 hover:text-red-400 transition-all shrink-0"
+ aria-label="Delete entry"
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+ ))}
+ </div>
+
+ {/* Actions */}
+ <div className="flex gap-2">
+ <GlowButton variant="secondary" onClick={handleExport} className="flex-1 text-xs flex items-center justify-center gap-1.5">
+ <Download size={12} /> Export .md
+ </GlowButton>
+ <GlowButton variant="secondary" onClick={() => fileInputRef.current?.click()} className="flex-1 text-xs flex items-center justify-center gap-1.5">
+ <Upload size={12} /> Import .md
+ </GlowButton>
+ <GlowButton
+ variant={confirmClear ? 'danger' : 'secondary'}
+ onClick={handleClear}
+ className="text-xs flex items-center justify-center gap-1.5 px-3"
+ >
+ <Trash2 size={12} /> {confirmClear ? 'Confirm?' : 'Clear'}
+ </GlowButton>
+ <input ref={fileInputRef} type="file" accept=".md,.txt" onChange={handleImport} className="hidden" />
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 37663d41..bf3456c2 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -1,14 +1,73 @@
-import { useState, useEffect } from 'react'
-import { ArrowLeft, RotateCcw, Sun, Moon, Mic, Volume2, Check, X, Loader2 } from 'lucide-react'
+import { useState, useEffect, type ReactNode } from 'react'
+import { ArrowLeft, RotateCcw, Sun, Moon, Mic, Volume2, Check, X, Loader2, Bot, Shield, Terminal, Search, FileText, ChevronRight } from 'lucide-react'
+import { motion, AnimatePresence } from 'framer-motion'
import { useSettingsStore } from '../../stores/settingsStore'
import { useUIStore } from '../../stores/uiStore'
-import { GlassCard } from '../ui/GlassCard'
-import { GlowButton } from '../ui/GlowButton'
import { SliderControl } from './SliderControl'
import { ApiConfig } from './ApiConfig'
import { PersonaPanel } from '../personas/PersonaPanel'
import { useVoiceStore } from '../../stores/voiceStore'
import { checkWhisperAvailable } from '../../api/voice'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { FEATURE_FLAGS } from '../../lib/constants'
+import { AGENT_TOOL_DEFS } from '../../api/tool-registry'
+import { getRecommendedAgentModels } from '../../lib/model-compatibility'
+import { MemorySettings } from './MemorySettings'
+
+// ── Collapsible Section ─────────────────────────────────────────
+
+function Section({ title, children, defaultOpen = false }: { title: string; children: ReactNode; defaultOpen?: boolean }) {
+ const [open, setOpen] = useState(defaultOpen)
+ return (
+ <div className="border-b border-gray-100 dark:border-white/[0.04]">
+ <button
+ onClick={() => setOpen(!open)}
+ className="w-full flex items-center justify-between py-2.5 group"
+ >
+ <span className="text-[0.65rem] font-semibold uppercase tracking-[0.15em] text-gray-400 dark:text-gray-500 group-hover:text-gray-600 dark:group-hover:text-gray-300 transition-colors">
+ {title}
+ </span>
+ <ChevronRight size={12} className={`text-gray-400 transition-transform duration-200 ${open ? 'rotate-90' : ''}`} />
+ </button>
+ <AnimatePresence>
+ {open && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="overflow-hidden"
+ >
+ <div className="pb-3 space-y-2">
+ {children}
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ )
+}
+
+// ── Inline Toggle ───────────────────────────────────────────────
+
+function InlineToggle({ label, enabled, onChange, icon }: { label: string; enabled: boolean; onChange: () => void; icon?: ReactNode }) {
+ return (
+ <div className="flex items-center justify-between py-0.5">
+ <div className="flex items-center gap-1.5">
+ {icon}
+ <span className="text-[0.7rem] text-gray-500 dark:text-gray-400">{label}</span>
+ </div>
+ <button
+ onClick={onChange}
+ className={`relative w-7 h-3.5 rounded-full transition-colors ${enabled ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-700'}`}
+ >
+ <span className={`absolute top-0.5 left-0.5 w-2.5 h-2.5 rounded-full bg-white transition-transform ${enabled ? 'translate-x-3.5' : ''}`} />
+ </button>
+ </div>
+ )
+}
+
+// ── Main Component ──────────────────────────────────────────────
export function SettingsPage() {
const { settings, updateSettings, resetSettings } = useSettingsStore()
@@ -31,7 +90,6 @@ export function SettingsPage() {
return () => speechSynthesis.removeEventListener('voiceschanged', loadVoices)
}, [ttsSupported])
- // Check Whisper availability on mount
useEffect(() => {
setWhisperLoading(true)
checkWhisperAvailable()
@@ -40,199 +98,163 @@ export function SettingsPage() {
}, [])
return (
- <div className="h-full overflow-y-auto scrollbar-thin p-6">
- <div className="max-w-2xl mx-auto space-y-6">
- <div className="flex items-center gap-3 mb-6">
- <button
- onClick={() => setView('chat')}
- className="p-2 rounded-lg hover:bg-gray-200 dark:hover:bg-white/10 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
- >
- <ArrowLeft size={20} />
+ <div className="h-full overflow-y-auto scrollbar-thin">
+ <div className="max-w-lg mx-auto px-4 py-4">
+ {/* Header */}
+ <div className="flex items-center gap-2 mb-4">
+ <button onClick={() => setView('chat')} className="p-1 rounded hover:bg-white/5 text-gray-500 hover:text-white transition-colors">
+ <ArrowLeft size={16} />
</button>
- <h1 className="text-xl font-bold text-gray-900 dark:text-white">Settings</h1>
+ <h1 className="text-[0.8rem] font-semibold text-gray-800 dark:text-gray-200">Settings</h1>
</div>
- <GlassCard>
- <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">Appearance</h2>
- <div className="space-y-3">
- <label className="text-sm text-gray-600 dark:text-gray-300">Theme</label>
- <div className="flex gap-2">
- <GlowButton
- variant={settings.theme === 'light' ? 'primary' : 'secondary'}
+ {/* ── Appearance ─────────────────────────────── */}
+ <Section title="Appearance" defaultOpen>
+ <div className="flex items-center justify-between">
+ <span className="text-[0.7rem] text-gray-500 dark:text-gray-400">Theme</span>
+ <div className="flex gap-1">
+ <button
onClick={() => updateSettings({ theme: 'light' })}
- className="flex-1 flex items-center justify-center gap-2"
+ className={`flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] transition-colors ${
+ settings.theme === 'light' ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'
+ }`}
>
- <Sun size={16} /> Light
- </GlowButton>
- <GlowButton
- variant={settings.theme === 'dark' ? 'primary' : 'secondary'}
+ <Sun size={11} /> Light
+ </button>
+ <button
onClick={() => updateSettings({ theme: 'dark' })}
- className="flex-1 flex items-center justify-center gap-2"
+ className={`flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] transition-colors ${
+ settings.theme === 'dark' ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'
+ }`}
>
- <Moon size={16} /> Dark
- </GlowButton>
+ <Moon size={11} /> Dark
+ </button>
</div>
</div>
- </GlassCard>
-
- <GlassCard>
- <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">Generation Parameters</h2>
- <div className="space-y-5">
- <SliderControl
- label="Temperature"
- value={settings.temperature}
- min={0}
- max={2}
- step={0.1}
- onChange={(v) => updateSettings({ temperature: v })}
- />
- <SliderControl
- label="Top P"
- value={settings.topP}
+ </Section>
+
+ {/* ── Generation Parameters ──────────────────── */}
+ <Section title="Generation">
+ <SliderControl label="Temperature" value={settings.temperature} min={0} max={2} step={0.1} onChange={(v) => updateSettings({ temperature: v })} />
+ <SliderControl label="Top P" value={settings.topP} min={0} max={1} step={0.05} onChange={(v) => updateSettings({ topP: v })} />
+ <SliderControl label="Top K" value={settings.topK} min={1} max={100} step={1} onChange={(v) => updateSettings({ topK: v })} />
+ <div className="flex items-center justify-between">
+ <span className="text-[0.7rem] text-gray-500 dark:text-gray-400">Max Tokens</span>
+ <input
+ type="number"
+ value={settings.maxTokens}
+ onChange={(e) => updateSettings({ maxTokens: parseInt(e.target.value) || 0 })}
min={0}
- max={1}
- step={0.05}
- onChange={(v) => updateSettings({ topP: v })}
+ placeholder="0"
+ className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-right text-gray-300 font-mono focus:outline-none focus:border-white/20"
/>
- <SliderControl
- label="Top K"
- value={settings.topK}
- min={1}
- max={100}
- step={1}
- onChange={(v) => updateSettings({ topK: v })}
- />
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <label className="text-sm text-gray-600 dark:text-gray-300">Max Tokens</label>
- <span className="text-sm font-mono text-gray-600 dark:text-gray-300">{settings.maxTokens || 'Unlimited'}</span>
- </div>
- <input
- type="number"
- value={settings.maxTokens}
- onChange={(e) => updateSettings({ maxTokens: parseInt(e.target.value) || 0 })}
- min={0}
- placeholder="0 = unlimited"
- className="w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-300 dark:border-white/10 text-gray-900 dark:text-white text-sm focus:outline-none focus:border-gray-400 dark:focus:border-white/20 font-mono"
- />
- </div>
</div>
- </GlassCard>
+ </Section>
- <GlassCard>
- <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">API Configuration</h2>
+ {/* ── API ────────────────────────────────────── */}
+ <Section title="API">
<ApiConfig endpoint={settings.apiEndpoint} onChange={(v) => updateSettings({ apiEndpoint: v })} />
- </GlassCard>
-
- <GlassCard>
- <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">Voice</h2>
- <div className="space-y-4">
- {/* Local STT status */}
- <div className="flex items-center gap-4">
- <div className="flex items-center gap-1.5">
- {whisperLoading ? (
- <Loader2 size={14} className="animate-spin text-gray-400" />
- ) : whisperStatus?.available ? (
- <Check size={14} className="text-green-500" />
- ) : (
- <X size={14} className="text-red-500" />
- )}
- <span className="text-xs text-gray-600 dark:text-gray-300">
- Local STT{whisperStatus?.backend ? `: ${whisperStatus.backend}` : ''}
- </span>
- </div>
- <div className="flex items-center gap-1.5">
- {ttsSupported ? (
- <Check size={14} className="text-green-500" />
- ) : (
- <X size={14} className="text-red-500" />
- )}
- <span className="text-xs text-gray-600 dark:text-gray-300">Text-to-Speech</span>
- </div>
- </div>
+ </Section>
- {/* Whisper install hint */}
- {whisperStatus && !whisperStatus.available && (
- <div className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded-lg px-3 py-2">
- Whisper not installed. Run: <code className="font-mono bg-amber-100 dark:bg-amber-900/40 px-1 rounded">pip install faster-whisper</code>
- </div>
- )}
+ {/* ── Voice ──────────────────────────────────── */}
+ <Section title="Voice">
+ <div className="flex items-center gap-3 text-[0.65rem]">
+ <span className="flex items-center gap-1">
+ {whisperLoading ? <Loader2 size={10} className="animate-spin text-gray-500" /> : whisperStatus?.available ? <Check size={10} className="text-green-500" /> : <X size={10} className="text-red-500" />}
+ <span className="text-gray-500">STT</span>
+ </span>
+ <span className="flex items-center gap-1">
+ {ttsSupported ? <Check size={10} className="text-green-500" /> : <X size={10} className="text-red-500" />}
+ <span className="text-gray-500">TTS</span>
+ </span>
+ </div>
+ <InlineToggle label="TTS Enabled" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />
+ <div className="flex items-center justify-between">
+ <span className="text-[0.7rem] text-gray-500">Voice</span>
+ <select
+ value={voiceSettings.ttsVoice}
+ onChange={(e) => voiceSettings.updateVoiceSettings({ ttsVoice: e.target.value })}
+ className="max-w-[180px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none"
+ >
+ <option value="">Default</option>
+ {voices.map((v) => <option key={v.name} value={v.name}>{v.name}</option>)}
+ </select>
+ </div>
+ <SliderControl label="Rate" value={voiceSettings.ttsRate} min={0.5} max={2} step={0.1} onChange={(v) => voiceSettings.updateVoiceSettings({ ttsRate: v })} />
+ <SliderControl label="Pitch" value={voiceSettings.ttsPitch} min={0.5} max={2} step={0.1} onChange={(v) => voiceSettings.updateVoiceSettings({ ttsPitch: v })} />
+ <InlineToggle label="Auto-send on Transcribe" enabled={voiceSettings.autoSendOnTranscribe} onChange={() => voiceSettings.updateVoiceSettings({ autoSendOnTranscribe: !voiceSettings.autoSendOnTranscribe })} icon={<Mic size={11} className="text-gray-500" />} />
+ </Section>
- {/* TTS Enabled toggle */}
+ {/* ── Personas ───────────────────────────────── */}
+ <Section title="Personas">
+ <PersonaPanel />
+ </Section>
+
+ {/* ── Agent Mode ─────────────────────────────── */}
+ {FEATURE_FLAGS.AGENT_MODE && (
+ <Section title="Agent Mode (Beta)">
<div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Volume2 size={16} className="text-gray-500 dark:text-gray-400" />
- <label className="text-sm text-gray-600 dark:text-gray-300">TTS Enabled</label>
+ <span className="text-[0.7rem] text-gray-500">Sandbox</span>
+ <div className="flex gap-1">
+ {(['restricted', 'full'] as const).map(level => (
+ <button
+ key={level}
+ onClick={() => useAgentModeStore.getState().setSandboxLevel(level)}
+ className={`px-2 py-0.5 rounded text-[0.6rem] transition-colors ${
+ useAgentModeStore.getState().sandboxLevel === level ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'
+ }`}
+ >
+ {level === 'restricted' ? 'Restricted' : 'Full Access'}
+ </button>
+ ))}
</div>
- <button
- onClick={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })}
- className={`relative w-10 h-5 rounded-full transition-colors ${voiceSettings.ttsEnabled ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}
- >
- <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${voiceSettings.ttsEnabled ? 'translate-x-5' : ''}`} />
- </button>
</div>
-
- {/* TTS Voice dropdown */}
- <div className="space-y-1.5">
- <label className="text-sm text-gray-600 dark:text-gray-300">TTS Voice</label>
- <select
- value={voiceSettings.ttsVoice}
- onChange={(e) => voiceSettings.updateVoiceSettings({ ttsVoice: e.target.value })}
- className="w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-300 dark:border-white/10 text-gray-900 dark:text-white text-sm focus:outline-none focus:border-gray-400 dark:focus:border-white/20"
- >
- <option value="">System Default</option>
- {voices.map((v) => (
- <option key={v.name} value={v.name}>
- {v.name} ({v.lang})
- </option>
- ))}
- </select>
+ <div className="space-y-0.5">
+ <span className="text-[0.6rem] text-gray-500">Tools</span>
+ {AGENT_TOOL_DEFS.map((tool) => (
+ <div key={tool.name} className="flex items-center justify-between py-0.5">
+ <span className="text-[0.65rem] text-gray-400 font-mono">{tool.name}</span>
+ <span className={`text-[0.55rem] ${tool.permission === 'auto' ? 'text-green-500' : 'text-amber-400'}`}>
+ {tool.permission === 'auto' ? 'auto' : 'approval'}
+ </span>
+ </div>
+ ))}
</div>
-
- {/* TTS Rate slider */}
- <SliderControl
- label="TTS Rate"
- value={voiceSettings.ttsRate}
- min={0.5}
- max={2}
- step={0.1}
- onChange={(v) => voiceSettings.updateVoiceSettings({ ttsRate: v })}
- />
-
- {/* TTS Pitch slider */}
- <SliderControl
- label="TTS Pitch"
- value={voiceSettings.ttsPitch}
- min={0.5}
- max={2}
- step={0.1}
- onChange={(v) => voiceSettings.updateVoiceSettings({ ttsPitch: v })}
- />
-
- {/* Auto-send on transcribe toggle */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Mic size={16} className="text-gray-500 dark:text-gray-400" />
- <label className="text-sm text-gray-600 dark:text-gray-300">Auto-send on Transcribe</label>
- </div>
- <button
- onClick={() => voiceSettings.updateVoiceSettings({ autoSendOnTranscribe: !voiceSettings.autoSendOnTranscribe })}
- className={`relative w-10 h-5 rounded-full transition-colors ${voiceSettings.autoSendOnTranscribe ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}
- >
- <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${voiceSettings.autoSendOnTranscribe ? 'translate-x-5' : ''}`} />
- </button>
+ <div className="space-y-0.5">
+ <span className="text-[0.6rem] text-gray-500">Recommended Models</span>
+ {getRecommendedAgentModels().map((m) => (
+ <div key={m.name} className="flex items-center gap-1.5 py-0.5">
+ {m.hot && <span className="text-[0.5rem] text-orange-400 font-bold">HOT</span>}
+ <span className="text-[0.65rem] text-gray-300">{m.label}</span>
+ <span className="text-[0.55rem] text-gray-600">— {m.reason}</span>
+ </div>
+ ))}
</div>
- </div>
- </GlassCard>
+ <button
+ onClick={() => useAgentModeStore.getState().setTutorialCompleted()}
+ className="text-[0.6rem] text-gray-500 hover:text-gray-300 transition-colors"
+ >
+ Reset tutorial
+ </button>
+ </Section>
+ )}
- <GlassCard>
- <h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">Personas</h2>
- <PersonaPanel />
- </GlassCard>
+ {/* ── Memory ─────────────────────────────────── */}
+ {FEATURE_FLAGS.AGENT_MODE && (
+ <Section title="Agent Memory">
+ <MemorySettings />
+ </Section>
+ )}
- <GlowButton variant="secondary" onClick={resetSettings} className="w-full flex items-center justify-center gap-2">
- <RotateCcw size={16} /> Reset to Defaults
- </GlowButton>
+ {/* ── Reset ──────────────────────────────────── */}
+ <div className="pt-3 pb-6">
+ <button
+ onClick={resetSettings}
+ className="flex items-center gap-1.5 text-[0.65rem] text-gray-500 hover:text-red-400 transition-colors"
+ >
+ <RotateCcw size={11} /> Reset to Defaults
+ </button>
+ </div>
</div>
</div>
)
diff --git a/src/components/settings/SliderControl.tsx b/src/components/settings/SliderControl.tsx
index 8a2581c7..06964eda 100644
--- a/src/components/settings/SliderControl.tsx
+++ b/src/components/settings/SliderControl.tsx
@@ -9,11 +9,8 @@ interface Props {
export function SliderControl({ label, value, min, max, step, onChange }: Props) {
return (
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <label className="text-sm text-gray-300">{label}</label>
- <span className="text-sm font-mono text-gray-300">{value}</span>
- </div>
+ <div className="flex items-center gap-3">
+ <span className="text-[0.7rem] text-gray-500 dark:text-gray-400 w-20 shrink-0">{label}</span>
<input
type="range"
min={min}
@@ -21,12 +18,9 @@ export function SliderControl({ label, value, min, max, step, onChange }: Props)
step={step}
value={value}
onChange={(e) => onChange(parseFloat(e.target.value))}
- className="w-full accent-white cursor-pointer"
+ className="flex-1 h-0.5 accent-gray-400 cursor-pointer"
/>
- <div className="flex justify-between text-xs text-gray-600">
- <span>{min}</span>
- <span>{max}</span>
- </div>
+ <span className="text-[0.65rem] font-mono text-gray-400 dark:text-gray-500 w-8 text-right">{value}</span>
</div>
)
}
diff --git a/src/components/ui/ToggleSwitch.tsx b/src/components/ui/ToggleSwitch.tsx
new file mode 100644
index 00000000..986e49d7
--- /dev/null
+++ b/src/components/ui/ToggleSwitch.tsx
@@ -0,0 +1,44 @@
+import { motion } from 'framer-motion'
+
+interface Props {
+ enabled: boolean
+ onChange: (enabled: boolean) => void
+ label?: string
+ disabled?: boolean
+ size?: 'sm' | 'md'
+}
+
+export function ToggleSwitch({ enabled, onChange, label, disabled = false, size = 'sm' }: Props) {
+ const trackSize = size === 'sm' ? 'w-8 h-4' : 'w-10 h-5'
+ const dotSize = size === 'sm' ? 'w-3 h-3' : 'w-4 h-4'
+ const dotTravel = size === 'sm' ? 16 : 20
+
+ return (
+ <button
+ type="button"
+ onClick={() => !disabled && onChange(!enabled)}
+ disabled={disabled}
+ className={`flex items-center gap-2 ${disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
+ aria-label={label || 'Toggle'}
+ >
+ {label && (
+ <span className="text-[0.7rem] text-gray-500 dark:text-gray-400 select-none">{label}</span>
+ )}
+ <div
+ className={`${trackSize} rounded-full relative transition-colors duration-200 ${
+ enabled
+ ? 'bg-green-500/30 border border-green-500/50'
+ : 'bg-gray-300 dark:bg-white/10 border border-gray-400 dark:border-white/15'
+ }`}
+ >
+ <motion.div
+ className={`${dotSize} rounded-full absolute top-1/2 -translate-y-1/2 ${
+ enabled ? 'bg-green-400' : 'bg-gray-400 dark:bg-gray-500'
+ }`}
+ animate={{ left: enabled ? dotTravel : 2 }}
+ transition={{ type: 'spring', stiffness: 500, damping: 30 }}
+ />
+ </div>
+ </button>
+ )
+}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
new file mode 100644
index 00000000..323594cf
--- /dev/null
+++ b/src/hooks/useAgentChat.ts
@@ -0,0 +1,581 @@
+import { useRef, useState, useCallback } from 'react'
+import { v4 as uuid } from 'uuid'
+import { chatWithTools } from '../api/ollama'
+import { chatNonStreaming } from '../api/agents'
+import { useChatStore } from '../stores/chatStore'
+import { agentVariantExists, createAgentVariant, getAgentModelName, canFixModel } from '../api/model-template-fix'
+import { useModelStore } from '../stores/modelStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { useRAGStore } from '../stores/ragStore'
+import { useVoiceStore } from '../stores/voiceStore'
+import { retrieveContext } from '../api/rag'
+import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from '../api/voice'
+import { getOllamaTools, getToolPermission, executeAgentTool, AGENT_TOOL_DEFS } from '../api/tool-registry'
+import { getToolCallingStrategy, type ToolCallingStrategy } from '../lib/model-compatibility'
+import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
+import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
+import { useMemoryStore } from '../stores/memoryStore'
+import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
+
+// ── Approval promise management ───────────────────────────────────
+
+interface ApprovalResolver {
+ resolve: (approved: boolean) => void
+}
+
+// ── Hook ──────────────────────────────────────────────────────────
+
+export function useAgentChat() {
+ const [isAgentRunning, setIsAgentRunning] = useState(false)
+ const [pendingApproval, setPendingApproval] = useState<AgentToolCall | null>(null)
+
+ const abortRef = useRef<AbortController | null>(null)
+ const approvalRef = useRef<ApprovalResolver | null>(null)
+ const contentRef = useRef('')
+ const thinkingRef = useRef('')
+ const isThinkingRef = useRef(false)
+ const blocksRef = useRef<AgentBlock[]>([])
+ const runningRef = useRef(false)
+
+ // ── Approval callbacks ────────────────────────────────────────
+
+ const approveToolCall = useCallback(() => {
+ approvalRef.current?.resolve(true)
+ approvalRef.current = null
+ setPendingApproval(null)
+ }, [])
+
+ const rejectToolCall = useCallback(() => {
+ approvalRef.current?.resolve(false)
+ approvalRef.current = null
+ setPendingApproval(null)
+ }, [])
+
+ // ── Wait for user approval ────────────────────────────────────
+
+ function waitForApproval(toolCall: AgentToolCall): Promise<boolean> {
+ return new Promise((resolve) => {
+ approvalRef.current = { resolve }
+ setPendingApproval(toolCall)
+ })
+ }
+
+ // ── Add agent block and sync to store ─────────────────────────
+
+ function addBlock(
+ convId: string,
+ msgId: string,
+ block: AgentBlock
+ ) {
+ blocksRef.current = [...blocksRef.current, block]
+ useChatStore.getState().updateMessageAgentBlocks(convId, msgId, blocksRef.current)
+ }
+
+ function updateLastBlock(
+ convId: string,
+ msgId: string,
+ updates: Partial<AgentBlock>
+ ) {
+ const blocks = [...blocksRef.current]
+ const last = blocks[blocks.length - 1]
+ if (last) {
+ blocks[blocks.length - 1] = { ...last, ...updates }
+ blocksRef.current = blocks
+ useChatStore.getState().updateMessageAgentBlocks(convId, msgId, blocks)
+ }
+ }
+
+ // ── Stream a single LLM turn ──────────────────────────────────
+
+ async function streamOneTurn(
+ model: string,
+ messages: OllamaChatMessage[],
+ signal: AbortSignal
+ ): Promise<{ content: string; thinking: string; toolCalls: { name: string; arguments: Record<string, any> }[] }> {
+ const response = await chatStreamWithTools(
+ model,
+ messages,
+ getOllamaTools(),
+ {
+ temperature: useSettingsStore.getState().settings.temperature,
+ top_p: useSettingsStore.getState().settings.topP,
+ top_k: useSettingsStore.getState().settings.topK,
+ num_predict: useSettingsStore.getState().settings.maxTokens || undefined,
+ },
+ signal
+ )
+
+ let accContent = ''
+ let accThinking = ''
+ let isInThinking = false
+ let toolCalls: { name: string; arguments: Record<string, any> }[] = []
+
+ for await (const chunk of parseNDJSONStream<AgentChatChunk>(response)) {
+ if (signal.aborted) break
+
+ // Collect tool calls from the response
+ if (chunk.message?.tool_calls) {
+ for (const tc of chunk.message.tool_calls) {
+ toolCalls.push({
+ name: tc.function.name,
+ arguments: tc.function.arguments,
+ })
+ }
+ }
+
+ // Stream text content with <think> tag parsing
+ if (chunk.message?.content) {
+ for (const char of chunk.message.content) {
+ if (!isInThinking) {
+ accContent += char
+ if (accContent.endsWith('<think>')) {
+ accContent = accContent.slice(0, -7)
+ isInThinking = true
+ }
+ } else {
+ accThinking += char
+ if (accThinking.endsWith('</think>')) {
+ accThinking = accThinking.slice(0, -8)
+ isInThinking = false
+ }
+ }
+ }
+
+ // Update refs for UI batching
+ contentRef.current = accContent
+ thinkingRef.current = accThinking
+ }
+ }
+
+ return { content: accContent, thinking: accThinking, toolCalls }
+ }
+
+ // ── Main agent message handler ────────────────────────────────
+
+ const sendAgentMessage = useCallback(async (userContent: string) => {
+ const { activeModel } = useModelStore.getState()
+ const { settings } = useSettingsStore.getState()
+ const store = useChatStore.getState()
+ const persona = useSettingsStore.getState().getActivePersona()
+
+ if (!activeModel) return
+
+ // ── Pre-flight: determine tool calling strategy ──────────
+ let modelToUse = activeModel
+ let strategy: ToolCallingStrategy = getToolCallingStrategy(activeModel)
+
+ if (strategy === 'template_fix') {
+ // Try to use existing agent variant, or create one
+ const agentName = getAgentModelName(activeModel)
+ const exists = await agentVariantExists(activeModel)
+
+ if (exists) {
+ modelToUse = agentName
+ strategy = 'native' // template-fixed models use native API
+ } else {
+ const { fixable } = await canFixModel(activeModel)
+ if (fixable) {
+ try {
+ modelToUse = await createAgentVariant(activeModel)
+ strategy = 'native'
+ } catch {
+ strategy = 'hermes_xml' // fallback to prompt-based
+ }
+ } else {
+ strategy = 'hermes_xml'
+ }
+ }
+ }
+
+ // Create or get conversation
+ let convId = store.activeConversationId
+ if (!convId) {
+ convId = store.createConversation(activeModel, persona?.systemPrompt || '')
+ }
+
+ // Add user message
+ const userMessage = {
+ id: uuid(),
+ role: 'user' as const,
+ content: userContent,
+ timestamp: Date.now(),
+ }
+ useChatStore.getState().addMessage(convId, userMessage)
+
+ // Add empty assistant message (will be updated with streaming content + blocks)
+ const assistantMessage = {
+ id: uuid(),
+ role: 'assistant' as const,
+ content: '',
+ thinking: '',
+ timestamp: Date.now(),
+ agentBlocks: [],
+ }
+ useChatStore.getState().addMessage(convId, assistantMessage)
+
+ // Build conversation context
+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)
+ if (!conv) return
+
+ // RAG context injection (same as useChat)
+ let systemPrompt = conv.systemPrompt
+ const ragState = useRAGStore.getState()
+ const ragEnabled = ragState.ragEnabled[convId] ?? false
+
+ if (ragEnabled) {
+ await ragState.loadChunksFromDB(convId)
+ const chunks = ragState.getConversationChunks(convId)
+ if (chunks.length > 0) {
+ try {
+ const { context: ragContext } = await retrieveContext(
+ userContent, chunks, ragState.embeddingModel
+ )
+ if (ragContext.chunks.length > 0) {
+ const contextBlock = ragContext.chunks
+ .map((c: any, i: number) => `[Source ${i + 1}]\n${c.content}`)
+ .join('\n\n')
+ systemPrompt = `Use the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---\n\n${systemPrompt || ''}`
+ }
+ } catch (err) {
+ console.error('RAG retrieval failed:', err)
+ }
+ }
+ }
+
+ // Memory context injection
+ const memoryContext = useMemoryStore.getState().getMemoryForPrompt(userContent, 2000)
+ if (memoryContext) {
+ systemPrompt = (systemPrompt || '') + `\n\n## Remembered Context\n${memoryContext}`
+ }
+
+ // Build the agent system prompt — Hermes XML mode gets tool defs in the prompt
+ const agentSystemPrompt = strategy === 'hermes_xml'
+ ? buildHermesToolPrompt(AGENT_TOOL_DEFS) + (systemPrompt ? `\n\n${systemPrompt}` : '')
+ : buildAgentSystemPrompt(systemPrompt)
+
+ // Build messages array for Ollama (internal, includes tool messages)
+ let ollamaMessages: OllamaChatMessage[] = [
+ ...(agentSystemPrompt ? [{ role: 'system', content: agentSystemPrompt }] : []),
+ ...conv.messages
+ .filter((m) => m.role !== 'system' && m.content.trim() !== '')
+ .map((m) => ({ role: m.role, content: m.content })),
+ ]
+
+ // Setup
+ const abort = new AbortController()
+ abortRef.current = abort
+ runningRef.current = true
+ setIsAgentRunning(true)
+ contentRef.current = ''
+ thinkingRef.current = ''
+ blocksRef.current = []
+
+ let frameScheduled = false
+
+ // Schedule UI updates via requestAnimationFrame
+ function scheduleUIUpdate() {
+ if (!frameScheduled) {
+ frameScheduled = true
+ requestAnimationFrame(() => {
+ const cId = convId!
+ const mId = assistantMessage.id
+ useChatStore.getState().updateMessageContent(cId, mId, contentRef.current)
+ if (thinkingRef.current) {
+ useChatStore.getState().updateMessageThinking(cId, mId, thinkingRef.current)
+ }
+ frameScheduled = false
+ })
+ }
+ }
+
+ try {
+ // ── Agent Loop ──────────────────────────────────────────
+ while (runningRef.current && !abort.signal.aborted) {
+ let toolCalls: { name: string; arguments: Record<string, any> }[] = []
+ let turnContent = ''
+ let turnThinking = ''
+
+ const chatOptions = {
+ temperature: useSettingsStore.getState().settings.temperature,
+ top_p: useSettingsStore.getState().settings.topP,
+ top_k: useSettingsStore.getState().settings.topK,
+ num_predict: useSettingsStore.getState().settings.maxTokens || undefined,
+ }
+
+ // Context compaction — prevent "Failed to fetch" from context overflow
+ const maxCtx = await getModelMaxTokens(modelToUse)
+ ollamaMessages = compactMessages(ollamaMessages, Math.floor(maxCtx * 0.8))
+
+ if (strategy === 'native') {
+ // ── Native Ollama tool calling (non-streaming for reliability) ──
+ const turn = await chatWithTools(
+ modelToUse, ollamaMessages, getOllamaTools(), chatOptions,
+ )
+
+ toolCalls = (turn.tool_calls || []).map((tc: any) => ({
+ name: tc.function.name,
+ arguments: tc.function.arguments,
+ }))
+ turnContent = turn.content || ''
+
+ } else {
+ // ── Hermes XML prompt-based tool calling ──
+ // Tools are already in the system prompt, just do a normal chat
+ const rawContent = await chatNonStreaming(
+ modelToUse,
+ ollamaMessages.map(m => ({ role: m.role, content: m.content })),
+ )
+
+ // Parse <tool_call> tags from output
+ if (hasToolCallTags(rawContent)) {
+ toolCalls = parseHermesToolCalls(rawContent)
+ turnContent = stripToolCallTags(rawContent)
+ } else {
+ turnContent = rawContent
+ }
+ }
+
+ // Parse think tags from content (both strategies)
+ const thinkMatch = turnContent.match(/<think>([\s\S]*?)<\/think>/)
+ if (thinkMatch) {
+ turnThinking = thinkMatch[1]
+ turnContent = turnContent.replace(/<think>[\s\S]*?<\/think>/, '').trim()
+ }
+
+ // Update UI
+ contentRef.current = turnContent
+ thinkingRef.current = turnThinking
+ scheduleUIUpdate()
+
+ // If no tool calls, the model is done
+ if (toolCalls.length === 0) {
+ break
+ }
+
+ // Process each tool call
+ for (const tc of toolCalls) {
+ if (!runningRef.current || abort.signal.aborted) break
+
+ const toolCallId = uuid()
+ const agentToolCall: AgentToolCall = {
+ id: toolCallId,
+ toolName: tc.name,
+ args: tc.arguments,
+ status: 'running',
+ timestamp: Date.now(),
+ }
+
+ // Check permission
+ const permission = getToolPermission(tc.name)
+
+ if (permission === 'confirm') {
+ // Needs user approval
+ agentToolCall.status = 'pending_approval'
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'tool_call',
+ content: `Requesting approval: ${tc.name}`,
+ toolCall: agentToolCall,
+ timestamp: Date.now(),
+ })
+
+ const approved = await waitForApproval(agentToolCall)
+
+ if (!approved) {
+ // User rejected
+ agentToolCall.status = 'rejected'
+ updateLastBlock(convId!, assistantMessage.id, {
+ toolCall: { ...agentToolCall, status: 'rejected' },
+ content: `Rejected: ${tc.name}`,
+ })
+
+ // Feed rejection back to model
+ if (strategy === 'native') {
+ ollamaMessages.push({
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ function: { name: tc.name, arguments: tc.arguments } }],
+ })
+ ollamaMessages.push({
+ role: 'tool',
+ content: 'User rejected this action. Try a different approach.',
+ })
+ } else {
+ ollamaMessages.push({
+ role: 'assistant',
+ content: `<tool_call>\n{"name": "${tc.name}", "arguments": ${JSON.stringify(tc.arguments)}}\n</tool_call>`,
+ })
+ ollamaMessages.push({
+ role: 'user',
+ content: buildHermesToolResult(tc.name, 'User rejected this action. Try a different approach.'),
+ })
+ }
+ continue
+ }
+
+ // Approved — mark as running
+ agentToolCall.status = 'running'
+ updateLastBlock(convId!, assistantMessage.id, {
+ toolCall: { ...agentToolCall, status: 'running' },
+ content: `Running: ${tc.name}`,
+ })
+ } else {
+ // Auto-approved
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'tool_call',
+ content: `Running: ${tc.name}`,
+ toolCall: agentToolCall,
+ timestamp: Date.now(),
+ })
+ }
+
+ // Execute the tool
+ const startTime = Date.now()
+ const result = await executeAgentTool(tc.name, tc.arguments)
+ const duration = Date.now() - startTime
+
+ // Update block with result
+ const isError = result.startsWith('Error:')
+ agentToolCall.status = isError ? 'failed' : 'completed'
+ agentToolCall.result = isError ? undefined : result
+ agentToolCall.error = isError ? result : undefined
+ agentToolCall.duration = duration
+
+ updateLastBlock(convId!, assistantMessage.id, {
+ toolCall: { ...agentToolCall },
+ content: isError ? `Failed: ${tc.name}` : `Completed: ${tc.name}`,
+ })
+
+ // Auto-save tool result to memory
+ if (!isError) {
+ const argsShort = JSON.stringify(tc.arguments).substring(0, 100)
+ const resultShort = result.substring(0, 200)
+ useMemoryStore.getState().addEntry(
+ 'tool_result',
+ `${tc.name}(${argsShort}) → ${resultShort}`,
+ `agent:${tc.name}`
+ )
+ }
+
+ // Append tool call + result to messages for next iteration
+ if (strategy === 'native') {
+ ollamaMessages.push({
+ role: 'assistant',
+ content: turnContent || '',
+ tool_calls: [{ function: { name: tc.name, arguments: tc.arguments } }],
+ })
+ ollamaMessages.push({
+ role: 'tool',
+ content: result,
+ })
+ } else {
+ // Hermes XML: assistant had <tool_call> tags, result goes as user <tool_response>
+ ollamaMessages.push({
+ role: 'assistant',
+ content: `<tool_call>\n{"name": "${tc.name}", "arguments": ${JSON.stringify(tc.arguments)}}\n</tool_call>`,
+ })
+ ollamaMessages.push({
+ role: 'user',
+ content: buildHermesToolResult(tc.name, result),
+ })
+ }
+ }
+
+ // Reset content for next iteration (model will produce new content)
+ contentRef.current = ''
+ thinkingRef.current = ''
+ }
+
+ // Final store update
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id, contentRef.current
+ )
+ if (thinkingRef.current) {
+ useChatStore.getState().updateMessageThinking(
+ convId!, assistantMessage.id, thinkingRef.current
+ )
+ }
+
+ } catch (err) {
+ if ((err as Error).name !== 'AbortError') {
+ const errorMsg = (err as Error).message || 'Connection failed'
+
+ if (errorMsg.includes('does not support tools')) {
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ `⚠️ This model does not support tool calling.\n\nThe auto-fix could not be applied. Try pulling a standard model like:\n• qwen2.5:7b\n• llama3.1:8b\n• mistral:7b`
+ )
+ } else {
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ contentRef.current + '\n\n⚠️ Agent error: ' + errorMsg
+ )
+ }
+ }
+ } finally {
+ setIsAgentRunning(false)
+ runningRef.current = false
+ abortRef.current = null
+ setPendingApproval(null)
+ approvalRef.current = null
+
+ // Auto-speak if TTS enabled
+ const voiceState = useVoiceStore.getState()
+ if (voiceState.ttsEnabled && isSpeechSynthesisSupported() && contentRef.current.trim()) {
+ try {
+ let voice: SpeechSynthesisVoice | undefined
+ if (voiceState.ttsVoice) {
+ const voices = await getVoicesAsync()
+ voice = voices.find((v) => v.name === voiceState.ttsVoice)
+ }
+ voiceState.setSpeaking(true)
+ await speakStreaming(contentRef.current, voice, voiceState.ttsRate, voiceState.ttsPitch)
+ } catch { /* TTS errors non-critical */ }
+ finally { voiceState.setSpeaking(false) }
+ }
+ }
+ }, [])
+
+ // ── Stop the agent ────────────────────────────────────────────
+
+ const stopAgent = useCallback(() => {
+ runningRef.current = false
+ abortRef.current?.abort()
+ // Also resolve any pending approval to unblock the loop
+ approvalRef.current?.resolve(false)
+ approvalRef.current = null
+ setPendingApproval(null)
+ }, [])
+
+ return {
+ sendAgentMessage,
+ stopAgent,
+ approveToolCall,
+ rejectToolCall,
+ isAgentRunning,
+ pendingApproval,
+ }
+}
+
+// ── Agent System Prompt Builder ─────────────────────────────────
+
+function buildAgentSystemPrompt(basePrompt: string): string {
+ const agentInstructions = `You are an autonomous AI agent. You MUST use tools — NEVER answer from memory.
+
+IMPORTANT: web_search returns ONLY short snippets, NOT real data. You MUST ALWAYS call web_fetch on the best URL to read the actual page content before answering.
+
+Workflow:
+1. web_search → get URLs
+2. web_fetch → read actual page content from the best URL
+3. Answer based on real data from web_fetch
+
+Other tools: file_read, file_write, code_execute, image_generate.
+Chain multiple tools as needed. If a tool fails, try a different approach.
+Respond in the same language the user uses.`
+
+ if (basePrompt) {
+ return `${agentInstructions}\n\n${basePrompt}`
+ }
+ return agentInstructions
+}
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 13841962..aa9c1c57 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -9,6 +9,8 @@ import { useRAGStore } from "../stores/ragStore"
import { useVoiceStore } from "../stores/voiceStore"
import { retrieveContext } from "../api/rag"
import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from "../api/voice"
+import { useAgentChat } from "./useAgentChat"
+import { useAgentModeStore } from "../stores/agentModeStore"
interface ChatChunk {
message?: { content: string }
@@ -17,17 +19,26 @@ interface ChatChunk {
export function useChat() {
const [isGenerating, setIsGenerating] = useState(false)
+ const [isLoadingModel, setIsLoadingModel] = useState(false)
const abortRef = useRef<AbortController | null>(null)
const contentRef = useRef("")
const thinkingRef = useRef("")
const isThinkingRef = useRef(false)
+ // Agent mode composition
+ const agentChat = useAgentChat()
+
const sendMessage = useCallback(async (content: string) => {
const { activeModel } = useModelStore.getState()
const { settings } = useSettingsStore.getState()
const store = useChatStore.getState()
const persona = useSettingsStore.getState().getActivePersona()
+ // Agent mode delegation: if active for this conversation, use agent chat
+ if (store.activeConversationId && useAgentModeStore.getState().isActive(store.activeConversationId)) {
+ return agentChat.sendAgentMessage(content)
+ }
+
if (!activeModel) return
let convId = store.activeConversationId
@@ -99,6 +110,7 @@ export function useChat() {
const abort = new AbortController()
abortRef.current = abort
setIsGenerating(true)
+ setIsLoadingModel(true)
contentRef.current = ""
thinkingRef.current = ""
isThinkingRef.current = false
@@ -117,7 +129,12 @@ export function useChat() {
)
let frameScheduled = false
+ let firstChunk = true
for await (const chunk of parseNDJSONStream<ChatChunk>(response)) {
+ if (firstChunk) {
+ firstChunk = false
+ setIsLoadingModel(false)
+ }
if (chunk.message?.content) {
const text = chunk.message.content
@@ -171,6 +188,7 @@ export function useChat() {
}
} finally {
setIsGenerating(false)
+ setIsLoadingModel(false)
abortRef.current = null
// Auto-speak response if TTS is enabled
@@ -194,5 +212,15 @@ export function useChat() {
abortRef.current?.abort()
}, [])
- return { sendMessage, stopGeneration, isGenerating }
+ return {
+ sendMessage,
+ stopGeneration: agentChat.isAgentRunning ? agentChat.stopAgent : stopGeneration,
+ isGenerating: isGenerating || agentChat.isAgentRunning,
+ isLoadingModel,
+ // Agent mode additions
+ isAgentRunning: agentChat.isAgentRunning,
+ pendingApproval: agentChat.pendingApproval,
+ approveToolCall: agentChat.approveToolCall,
+ rejectToolCall: agentChat.rejectToolCall,
+ }
}
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 18060590..139c260b 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -17,6 +17,11 @@ import {
type ComfyUIOutput,
type VideoBackend,
} from '../api/comfyui'
+import {
+ comfyWS, CLIENT_ID,
+ LOADER_NODES, CLIP_LOADER_NODES, VAE_LOADER_NODES, SAMPLER_NODES, DECODE_NODES,
+ type ComfyWSEvent,
+} from '../api/comfyui-ws'
import { buildDynamicWorkflow } from '../api/dynamic-workflow'
import { getAllNodeInfo } from '../api/comfyui-nodes'
import { useCreateStore, type GalleryItem } from '../stores/createStore'
@@ -202,7 +207,7 @@ export function useCreate() {
setProgress(10, 'Submitting to ComfyUI...')
let promptId: string
try {
- promptId = await submitWorkflow(workflow)
+ promptId = await submitWorkflow(workflow, CLIENT_ID)
} catch (err) {
setError(`Failed to submit: ${err instanceof Error ? err.message : String(err)}`)
setIsGenerating(false)
@@ -211,113 +216,240 @@ export function useCreate() {
setCurrentPromptId(promptId)
addToPromptHistory(prompt)
- // Poll for completion — video gets 60min timeout, image 20min
+ // Build node ID → class_type map from workflow for phase detection
+ const nodeClassMap = new Map<string, string>()
+ for (const [nodeId, node] of Object.entries(workflow)) {
+ if (node && typeof node === 'object' && 'class_type' in node) {
+ nodeClassMap.set(nodeId, (node as any).class_type)
+ }
+ }
+
+ // Try WebSocket-driven progress, fall back to polling
const maxTime = mode === 'video' ? 60 * 60 * 1000 : 20 * 60 * 1000
- await new Promise<void>((resolve, reject) => {
- let attempts = 0
- let comfyCheckCounter = 0
- const startTime = Date.now()
-
- pollRef.current = setInterval(async () => {
- if (abortRef.current?.signal.aborted) {
- if (pollRef.current) clearInterval(pollRef.current)
- reject(new Error('Cancelled'))
- return
- }
+ let useWS = false
+ try {
+ await comfyWS.connect(3000)
+ useWS = true
+ } catch {
+ console.warn('[useCreate] WebSocket unavailable, using polling fallback')
+ }
+
+ if (useWS) {
+ // ── WebSocket-driven progress ──
+ await new Promise<void>((resolve, reject) => {
+ const startTime = Date.now()
+ const store = useCreateStore.getState()
+ store.setProgressPhase('queued')
+ setProgress(10, 'Queued...')
- const elapsed = Date.now() - startTime
- if (elapsed > maxTime) {
- if (pollRef.current) clearInterval(pollRef.current)
+ const timeoutTimer = setTimeout(() => {
+ cleanup()
reject(new Error(`Generation timed out after ${Math.round(maxTime / 60000)} minutes`))
- return
+ }, maxTime)
+
+ // Heartbeat: check ComfyUI every 30s
+ const heartbeat = setInterval(async () => {
+ const alive = await checkComfyConnection()
+ if (!alive) { cleanup(); reject(new Error('ComfyUI stopped responding during generation')) }
+ }, 30000)
+
+ let abortCheck: ReturnType<typeof setInterval> | null = null
+
+ const cleanup = () => {
+ clearTimeout(timeoutTimer)
+ clearInterval(heartbeat)
+ if (abortCheck) clearInterval(abortCheck)
+ removeListener()
}
- attempts++
- comfyCheckCounter++
+ const removeListener = comfyWS.on((event: ComfyWSEvent) => {
+ // Only handle events for our prompt
+ if ('prompt_id' in event.data && event.data.prompt_id !== promptId) return
- // Heartbeat: every 30 polls, check if ComfyUI is still alive
- if (comfyCheckCounter >= 30) {
- comfyCheckCounter = 0
- const alive = await checkComfyConnection()
- if (!alive) {
+ const elapsed = Math.round((Date.now() - startTime) / 1000)
+ const st = useCreateStore.getState()
+
+ switch (event.type) {
+ case 'executing': {
+ const nodeId = event.data.node
+ if (nodeId === null) {
+ // null node means execution finished for this prompt
+ break
+ }
+ const classType = nodeClassMap.get(nodeId) || ''
+ if (LOADER_NODES.has(classType)) {
+ st.setProgressPhase('loading-model')
+ setProgress(15, `Loading model... ${elapsed}s`)
+ } else if (CLIP_LOADER_NODES.has(classType)) {
+ st.setProgressPhase('loading-clip')
+ setProgress(25, `Loading text encoder... ${elapsed}s`)
+ } else if (VAE_LOADER_NODES.has(classType)) {
+ st.setProgressPhase('loading-vae')
+ setProgress(30, `Loading VAE... ${elapsed}s`)
+ } else if (SAMPLER_NODES.has(classType)) {
+ st.setProgressPhase('sampling')
+ setProgress(35, `Sampling... ${elapsed}s`)
+ } else if (DECODE_NODES.has(classType)) {
+ st.setProgressPhase('decoding')
+ setProgress(90, `Decoding... ${elapsed}s`)
+ }
+ break
+ }
+ case 'progress': {
+ const { value, max } = event.data
+ const stepPct = 35 + (value / max) * 55 // 35% to 90%
+ st.setProgressPhase('sampling')
+ setProgress(Math.round(stepPct), `Sampling step ${value}/${max}... ${elapsed}s`)
+ break
+ }
+ case 'execution_complete': {
+ cleanup()
+ st.setProgressPhase('complete')
+ setProgress(95, 'Fetching results...')
+ // Fetch history to get output files
+ getHistory(promptId).then(history => {
+ if (!history) { setError('No history found after completion.'); resolve(); return }
+ const messages: [string, any][] = history.status?.messages ?? []
+ const startMsg = messages.find(([t]) => t === 'execution_start')
+ const endMsg = messages.find(([t]) => t === 'execution_success')
+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp
+ ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : null
+ setProgress(100, 'Complete!')
+ useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)
+ const outputs = history.outputs ?? {}
+ let found = false
+ for (const nodeId of Object.keys(outputs)) {
+ const nodeOutput = outputs[nodeId]
+ const files: ComfyUIOutput[] = [
+ ...(nodeOutput.images ?? []), ...(nodeOutput.gifs ?? []), ...(nodeOutput.videos ?? []),
+ ]
+ for (const file of files) {
+ found = true
+ addToGallery({
+ id: uuid(), type: mode,
+ filename: file.filename, subfolder: file.subfolder ?? '',
+ prompt, negativePrompt, model: activeModel,
+ modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
+ seed: seed === -1 ? 0 : seed,
+ steps, cfgScale, sampler, scheduler, width, height, batchSize,
+ createdAt: Date.now(), builderUsed,
+ })
+ }
+ }
+ if (!found) setError('Generation completed but no output was produced. Check ComfyUI logs.')
+ resolve()
+ }).catch(() => { resolve() })
+ break
+ }
+ case 'execution_error': {
+ cleanup()
+ const msg = event.data.exception_message || 'Unknown ComfyUI error'
+ const nodeType = event.data.node_type ? ` (${event.data.node_type})` : ''
+ reject(new Error(msg.trim() + nodeType))
+ break
+ }
+ }
+ })
+
+ // Also check abort
+ abortCheck = setInterval(() => {
+ if (abortRef.current?.signal.aborted) {
+ cleanup()
+ reject(new Error('Cancelled'))
+ }
+ }, 500)
+ })
+ } else {
+ // ── Polling fallback (original approach) ──
+ await new Promise<void>((resolve, reject) => {
+ let attempts = 0
+ let comfyCheckCounter = 0
+ const startTime = Date.now()
+
+ pollRef.current = setInterval(async () => {
+ if (abortRef.current?.signal.aborted) {
if (pollRef.current) clearInterval(pollRef.current)
- reject(new Error('ComfyUI stopped responding during generation'))
+ reject(new Error('Cancelled'))
+ return
+ }
+
+ const elapsed = Date.now() - startTime
+ if (elapsed > maxTime) {
+ if (pollRef.current) clearInterval(pollRef.current)
+ reject(new Error(`Generation timed out after ${Math.round(maxTime / 60000)} minutes`))
return
}
- }
- const elapsedSec = Math.round(elapsed / 1000)
- // Video progress: slower, more conservative estimate
- const expectedSteps = mode === 'video' ? steps * frames * 0.5 : steps * 2
- const pct = Math.min(10 + (attempts / expectedSteps * 85), 95)
+ attempts++
+ comfyCheckCounter++
- try {
- const history = await getHistory(promptId)
+ if (comfyCheckCounter >= 30) {
+ comfyCheckCounter = 0
+ const alive = await checkComfyConnection()
+ if (!alive) {
+ if (pollRef.current) clearInterval(pollRef.current)
+ reject(new Error('ComfyUI stopped responding during generation'))
+ return
+ }
+ }
- // Always update elapsed time
- setProgress(pct, `Generating... ${elapsedSec}s elapsed`)
+ const elapsedSec = Math.round(elapsed / 1000)
+ const expectedSteps = mode === 'video' ? steps * frames * 0.5 : steps * 2
+ const pct = Math.min(10 + (attempts / expectedSteps * 85), 95)
- if (!history) return
+ try {
+ const history = await getHistory(promptId)
+ setProgress(pct, `Generating... ${elapsedSec}s elapsed`)
+ if (!history) return
- if (history.status?.completed) {
- if (pollRef.current) clearInterval(pollRef.current)
- // Calculate real generation time from ComfyUI timestamps
- const messages: [string, any][] = history.status?.messages ?? []
- const startMsg = messages.find(([t]) => t === 'execution_start')
- const endMsg = messages.find(([t]) => t === 'execution_success')
- const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp
- ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1)
- : null
- setProgress(100, 'Complete!')
- useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)
-
- const outputs = history.outputs ?? {}
- let found = false
- for (const nodeId of Object.keys(outputs)) {
- const nodeOutput = outputs[nodeId]
- const files: ComfyUIOutput[] = [
- ...(nodeOutput.images ?? []),
- ...(nodeOutput.gifs ?? []),
- ...(nodeOutput.videos ?? []),
- ]
- for (const file of files) {
- found = true
- const galleryItem: GalleryItem = {
- id: uuid(),
- type: mode,
- filename: file.filename,
- subfolder: file.subfolder ?? '',
- prompt, negativePrompt,
- model: activeModel,
- modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
- seed: seed === -1 ? 0 : seed,
- steps, cfgScale, sampler, scheduler, width, height,
- batchSize,
- createdAt: Date.now(),
- builderUsed,
+ if (history.status?.completed) {
+ if (pollRef.current) clearInterval(pollRef.current)
+ const messages: [string, any][] = history.status?.messages ?? []
+ const startMsg = messages.find(([t]) => t === 'execution_start')
+ const endMsg = messages.find(([t]) => t === 'execution_success')
+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp
+ ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : null
+ setProgress(100, 'Complete!')
+ useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)
+ const outputs = history.outputs ?? {}
+ let found = false
+ for (const nodeId of Object.keys(outputs)) {
+ const nodeOutput = outputs[nodeId]
+ const files: ComfyUIOutput[] = [
+ ...(nodeOutput.images ?? []), ...(nodeOutput.gifs ?? []), ...(nodeOutput.videos ?? []),
+ ]
+ for (const file of files) {
+ found = true
+ addToGallery({
+ id: uuid(), type: mode,
+ filename: file.filename, subfolder: file.subfolder ?? '',
+ prompt, negativePrompt, model: activeModel,
+ modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),
+ seed: seed === -1 ? 0 : seed,
+ steps, cfgScale, sampler, scheduler, width, height, batchSize,
+ createdAt: Date.now(), builderUsed,
+ })
}
- addToGallery(galleryItem)
}
+ if (!found) setError('Generation completed but no output was produced. Check ComfyUI logs.')
+ resolve()
+ } else if (history.status?.status_str === 'error') {
+ if (pollRef.current) clearInterval(pollRef.current)
+ const messages: [string, any][] = history.status?.messages ?? []
+ const errorEntry = messages.find(([t]) => t === 'execution_error')
+ const errMsg = errorEntry?.[1]?.exception_message
+ || errorEntry?.[1]?.message
+ || messages[messages.length - 1]?.[1]?.message
+ || 'Unknown ComfyUI error'
+ const nodeType = errorEntry?.[1]?.node_type ? ` (${errorEntry[1].node_type})` : ''
+ reject(new Error(errMsg.trim() + nodeType))
}
- if (!found) setError('Generation completed but no output was produced. Check ComfyUI logs.')
- resolve()
- } else if (history.status?.status_str === 'error') {
- if (pollRef.current) clearInterval(pollRef.current)
- // Find the execution_error message which has the actual error details
- const messages: [string, any][] = history.status?.messages ?? []
- const errorEntry = messages.find(([t]) => t === 'execution_error')
- const errMsg = errorEntry?.[1]?.exception_message
- || errorEntry?.[1]?.message
- || messages[messages.length - 1]?.[1]?.message
- || 'Unknown ComfyUI error'
- const nodeType = errorEntry?.[1]?.node_type ? ` (${errorEntry[1].node_type})` : ''
- reject(new Error(errMsg.trim() + nodeType))
+ } catch (err) {
+ console.warn('[useCreate] Poll error:', err)
}
- } catch (err) {
- console.warn('[useCreate] Poll error:', err)
- }
- }, 1000)
- })
+ }, 1000)
+ })
+ }
} catch (err) {
if (err instanceof Error && err.message === 'Cancelled') {
// User cancelled, not an error
diff --git a/src/index.css b/src/index.css
index bbd29145..06734a47 100644
--- a/src/index.css
+++ b/src/index.css
@@ -18,19 +18,24 @@ body {
height: 100vh;
}
-/* Light mode glass card */
+/* Light mode glass card — Linear/Arc: near-invisible */
.light .glass-card {
- background: #ffffff;
- border: 1px solid #e5e5e5;
- border-radius: 12px;
- box-shadow: 0 1px 3px rgba(0,0,0,0.06);
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.06);
+ border-radius: 0;
+ padding-bottom: 0.75rem;
+ margin-bottom: 0.25rem;
}
-/* Dark mode glass card */
+/* Dark mode glass card — Linear/Arc: near-invisible */
.dark .glass-card {
- background: #2f2f2f;
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 12px;
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ border-radius: 0;
+ padding-bottom: 0.75rem;
+ margin-bottom: 0.25rem;
}
/* Custom scrollbar */
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 14acf6ce..3e25d492 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -1,5 +1,10 @@
import type { Persona, Settings } from '../types/settings'
+// Feature flags — flip to true when ready to ship
+export const FEATURE_FLAGS = {
+ AGENT_MODE: true,
+} as const
+
export const DEFAULT_SETTINGS: Settings = {
apiEndpoint: 'http://localhost:11434',
temperature: 0.7,
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
new file mode 100644
index 00000000..43bc080d
--- /dev/null
+++ b/src/lib/context-compaction.ts
@@ -0,0 +1,174 @@
+/**
+ * Context Compaction — prevents "Failed to fetch" from context window exhaustion.
+ *
+ * Strategy (from Claude Code / Claw Code pattern):
+ * - Keep the last N messages intact (recent context matters most)
+ * - Summarize older messages into compact one-liners
+ * - Tool call + result pairs become: "Used tool_name('args') → result_snippet"
+ * - Token estimation via heuristic: text.length / 4
+ */
+
+import { getModelContext } from '../api/ollama'
+import type { OllamaChatMessage } from '../types/agent-mode'
+
+// ── Token Estimation ────────────────────────────────────────────
+
+/**
+ * Rough token estimate. Ollama models typically tokenize ~4 chars per token.
+ */
+export function estimateTokens(text: string): number {
+ return Math.ceil(text.length / 4) + 1
+}
+
+/**
+ * Estimate total tokens in a message array.
+ */
+export function estimateMessageTokens(messages: OllamaChatMessage[]): number {
+ return messages.reduce((sum, m) => {
+ let tokens = estimateTokens(m.content)
+ // Tool calls add overhead
+ if (m.tool_calls) {
+ tokens += estimateTokens(JSON.stringify(m.tool_calls))
+ }
+ // Role tag overhead (~4 tokens)
+ tokens += 4
+ return sum + tokens
+ }, 0)
+}
+
+// ── Model Context Lookup ────────────────────────────────────────
+
+/**
+ * Get the max context window for a model. Falls back to 4096 if unknown.
+ */
+export async function getModelMaxTokens(modelName: string): Promise<number> {
+ try {
+ return await getModelContext(modelName)
+ } catch {
+ return 4096
+ }
+}
+
+// ── Message Compaction ──────────────────────────────────────────
+
+const KEEP_RECENT = 4 // Always keep the last N messages untouched
+
+/**
+ * Compact a message array to fit within a token budget.
+ *
+ * - If already within budget, returns messages unchanged.
+ * - Otherwise, keeps the system prompt + last KEEP_RECENT messages,
+ * and summarizes everything in between.
+ */
+export function compactMessages(
+ messages: OllamaChatMessage[],
+ maxTokens: number
+): OllamaChatMessage[] {
+ const currentTokens = estimateMessageTokens(messages)
+
+ // Already within budget
+ if (currentTokens <= maxTokens) return messages
+
+ // Separate system prompt (always kept)
+ const systemMsg = messages[0]?.role === 'system' ? messages[0] : null
+ const nonSystem = systemMsg ? messages.slice(1) : [...messages]
+
+ // If we have fewer messages than KEEP_RECENT, can't compact further
+ if (nonSystem.length <= KEEP_RECENT) return messages
+
+ // Split: old messages (to compact) + recent messages (to keep)
+ const oldMessages = nonSystem.slice(0, -KEEP_RECENT)
+ const recentMessages = nonSystem.slice(-KEEP_RECENT)
+
+ // Summarize old messages
+ const summary = summarizeMessages(oldMessages)
+
+ // Build compacted array
+ const compacted: OllamaChatMessage[] = []
+
+ if (systemMsg) compacted.push(systemMsg)
+
+ // Insert summary as a system-level context message
+ if (summary) {
+ compacted.push({
+ role: 'system',
+ content: `[Previous conversation summary]\n${summary}`,
+ })
+ }
+
+ // Keep recent messages intact
+ compacted.push(...recentMessages)
+
+ return compacted
+}
+
+// ── Message Summarization ───────────────────────────────────────
+
+/**
+ * Summarize a sequence of messages into a compact string.
+ * Tool call + result pairs become one-liners.
+ */
+function summarizeMessages(messages: OllamaChatMessage[]): string {
+ const lines: string[] = []
+ let i = 0
+
+ while (i < messages.length) {
+ const msg = messages[i]
+
+ if (msg.role === 'user') {
+ // User message → short summary
+ const content = msg.content.trim()
+ if (content.length > 0 && !content.startsWith('<tool_response>')) {
+ lines.push(`User asked: ${truncate(content, 80)}`)
+ }
+ } else if (msg.role === 'assistant') {
+ // Check if this is a tool call (next message might be 'tool' or contains tool_response)
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
+ // Native tool call
+ for (const tc of msg.tool_calls) {
+ const toolName = tc.function?.name || 'unknown'
+ const args = JSON.stringify(tc.function?.arguments || {})
+ const argsShort = truncate(args, 60)
+
+ // Look ahead for the tool result
+ const nextMsg = messages[i + 1]
+ if (nextMsg && (nextMsg.role === 'tool' || nextMsg.role === 'user')) {
+ const resultShort = truncate(nextMsg.content, 80)
+ lines.push(`Used ${toolName}(${argsShort}) → ${resultShort}`)
+ i++ // skip the result message
+ } else {
+ lines.push(`Called ${toolName}(${argsShort})`)
+ }
+ }
+ } else if (msg.content.includes('<tool_call>')) {
+ // Hermes XML tool call
+ const match = msg.content.match(/"name"\s*:\s*"([^"]+)"/)
+ const toolName = match?.[1] || 'tool'
+ const nextMsg = messages[i + 1]
+ if (nextMsg?.content?.includes('<tool_response>')) {
+ const resultShort = truncate(nextMsg.content.replace(/<\/?tool_response>/g, ''), 80)
+ lines.push(`Used ${toolName} → ${resultShort}`)
+ i++
+ } else {
+ lines.push(`Called ${toolName}`)
+ }
+ } else if (msg.content.trim().length > 0) {
+ // Regular assistant message
+ lines.push(`Assistant: ${truncate(msg.content, 100)}`)
+ }
+ } else if (msg.role === 'tool') {
+ // Standalone tool result (shouldn't happen if paired above, but just in case)
+ lines.push(`Tool result: ${truncate(msg.content, 80)}`)
+ }
+
+ i++
+ }
+
+ return lines.join('\n')
+}
+
+function truncate(text: string, maxLen: number): string {
+ const cleaned = text.replace(/\n/g, ' ').trim()
+ if (cleaned.length <= maxLen) return cleaned
+ return cleaned.slice(0, maxLen - 3) + '...'
+}
diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.ts
new file mode 100644
index 00000000..fcc9f71d
--- /dev/null
+++ b/src/lib/model-compatibility.ts
@@ -0,0 +1,59 @@
+/**
+ * Model Compatibility for Agent Mode
+ *
+ * Agent Mode ONLY works with models that have native Ollama tool calling.
+ * No workarounds, no fallbacks — if Ollama says no tools, no agent mode.
+ *
+ * Face of Agent Mode: Hermes 3 (uncensored + native tool calling)
+ */
+
+const AGENT_COMPATIBLE = [
+ // ── Hermes: THE uncensored agent model ──
+ 'hermes3', 'hermes-3', 'hermes',
+ // ── Standard models with native tool calling ──
+ 'qwen3', 'qwen2.5',
+ 'llama3.1', 'llama3.2', 'llama3.3', 'llama4',
+ 'mistral', 'mistral-nemo', 'mistral-small', 'mistral-large',
+ 'command-r',
+ 'phi-4', 'phi4',
+ 'deepseek-v2.5', 'deepseek-v3',
+ 'glm4', 'glm-4',
+ 'gemma3',
+ 'nemotron',
+]
+
+/**
+ * Check if a model supports Agent Mode.
+ * Must have native Ollama tool calling. No abliterated, no uncensored.
+ */
+export function isAgentCompatible(modelName: string): boolean {
+ const name = modelName.toLowerCase()
+ if (name.includes('abliterated') || name.includes('uncensored')) return false
+ const baseName = name.replace(/^[^/]+\//, '').replace(/-instruct/g, '').replace(/-chat/g, '').replace(/:.*$/, '')
+ return AGENT_COMPATIBLE.some((f) => baseName.startsWith(f))
+}
+
+export const isToolCallingModel = isAgentCompatible
+export const hasNativeToolCalling = isAgentCompatible
+
+export type ToolCallingStrategy = 'native' | 'template_fix' | 'hermes_xml'
+
+export function getToolCallingStrategy(modelName: string): ToolCallingStrategy {
+ return isAgentCompatible(modelName) ? 'native' : 'hermes_xml'
+}
+
+export interface RecommendedModel {
+ name: string
+ label: string
+ reason: string
+ hot?: boolean
+}
+
+export function getRecommendedAgentModels(): RecommendedModel[] {
+ return [
+ { name: 'hermes3:8b', label: 'Hermes 3 8B', reason: 'Uncensored + native tool calling. THE agent model.', hot: true },
+ { name: 'hermes3:70b', label: 'Hermes 3 70B', reason: 'Maximum power uncensored agent. Needs 48GB+.', hot: true },
+ { name: 'qwen2.5:7b', label: 'Qwen 2.5 7B', reason: 'Fast, reliable tool calling' },
+ { name: 'llama3.1:8b', label: 'Llama 3.1 8B', reason: 'Proven tool calling all-rounder' },
+ ]
+}
diff --git a/src/stores/agentModeStore.ts b/src/stores/agentModeStore.ts
new file mode 100644
index 00000000..2ca5d4cb
--- /dev/null
+++ b/src/stores/agentModeStore.ts
@@ -0,0 +1,54 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import type { SandboxLevel } from '../types/agent-mode'
+
+interface AgentModeState {
+ // Per-conversation agent mode toggle
+ agentModeActive: Record<string, boolean>
+
+ // Settings
+ sandboxLevel: SandboxLevel
+ tutorialCompleted: boolean
+
+ // Actions
+ toggleAgentMode: (conversationId: string) => void
+ setAgentModeActive: (conversationId: string, active: boolean) => void
+ setSandboxLevel: (level: SandboxLevel) => void
+ setTutorialCompleted: () => void
+ isActive: (conversationId: string) => boolean
+}
+
+export const useAgentModeStore = create<AgentModeState>()(
+ persist(
+ (set, get) => ({
+ agentModeActive: {},
+ sandboxLevel: 'restricted',
+ tutorialCompleted: false,
+
+ toggleAgentMode: (conversationId) =>
+ set((state) => ({
+ agentModeActive: {
+ ...state.agentModeActive,
+ [conversationId]: !state.agentModeActive[conversationId],
+ },
+ })),
+
+ setAgentModeActive: (conversationId, active) =>
+ set((state) => ({
+ agentModeActive: {
+ ...state.agentModeActive,
+ [conversationId]: active,
+ },
+ })),
+
+ setSandboxLevel: (level) => set({ sandboxLevel: level }),
+
+ setTutorialCompleted: () => set({ tutorialCompleted: true }),
+
+ isActive: (conversationId) => {
+ return get().agentModeActive[conversationId] ?? false
+ },
+ }),
+ { name: 'locally-uncensored-agent-mode' }
+ )
+)
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 595351a8..55429b78 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -2,6 +2,7 @@ import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
import type { Conversation, Message } from '../types/chat'
+import type { AgentBlock } from '../types/agent-mode'
interface ChatState {
conversations: Conversation[]
@@ -13,6 +14,7 @@ interface ChatState {
addMessage: (conversationId: string, message: Message) => void
updateMessageContent: (conversationId: string, messageId: string, content: string) => void
updateMessageThinking: (conversationId: string, messageId: string, thinking: string) => void
+ updateMessageAgentBlocks: (conversationId: string, messageId: string, blocks: AgentBlock[]) => void
getActiveConversation: () => Conversation | undefined
searchConversations: (query: string) => Conversation[]
}
@@ -100,6 +102,19 @@ export const useChatStore = create<ChatState>()(
),
})),
+ updateMessageAgentBlocks: (conversationId, messageId, agentBlocks) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) =>
+ c.id === conversationId
+ ? {
+ ...c,
+ messages: c.messages.map((m) => (m.id === messageId ? { ...m, agentBlocks } : m)),
+ updatedAt: Date.now(),
+ }
+ : c
+ ),
+ })),
+
getActiveConversation: () => {
const { conversations, activeConversationId } = get()
return conversations.find((c) => c.id === activeConversationId)
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index 0835a759..c8f56eb5 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -5,6 +5,8 @@ import { classifyModel } from '../api/comfyui'
import type { PreflightError } from '../api/preflight'
// ModelType includes: flux, flux2, sdxl, sd15, wan, hunyuan, unknown
+export type ProgressPhase = 'idle' | 'queued' | 'loading-model' | 'loading-clip' | 'loading-vae' | 'sampling' | 'decoding' | 'complete'
+
// ─── Optimal defaults per model type (research-backed: Draw Things, Fooocus, ComfyUI) ───
export const MODEL_TYPE_DEFAULTS: Record<ModelType, {
@@ -64,6 +66,7 @@ interface CreateState {
isGenerating: boolean
progress: number
progressText: string
+ progressPhase: ProgressPhase
currentPromptId: string | null
error: string | null
lastGenTime: string | null
@@ -90,6 +93,7 @@ interface CreateState {
setFps: (fps: number) => void
setIsGenerating: (generating: boolean) => void
setProgress: (progress: number, text?: string) => void
+ setProgressPhase: (phase: ProgressPhase) => void
setCurrentPromptId: (id: string | null) => void
setError: (error: string | null) => void
setLastGenTime: (time: string | null) => void
@@ -121,6 +125,7 @@ export const useCreateStore = create<CreateState>()(
isGenerating: false,
progress: 0,
progressText: '',
+ progressPhase: 'idle' as ProgressPhase,
currentPromptId: null,
error: null,
lastGenTime: null,
@@ -167,8 +172,9 @@ export const useCreateStore = create<CreateState>()(
setBatchSize: (batchSize) => set({ batchSize: Math.max(1, Math.min(8, Math.floor(batchSize))) }),
setFrames: (frames) => set({ frames: Math.max(1, Math.min(120, Math.floor(frames))) }),
setFps: (fps) => set({ fps: Math.max(1, Math.min(60, Math.floor(fps))) }),
- setIsGenerating: (generating) => set({ isGenerating: generating }),
+ setIsGenerating: (generating) => set({ isGenerating: generating, ...(generating ? {} : { progressPhase: 'idle' as ProgressPhase }) }),
setProgress: (progress, text) => set({ progress, progressText: text ?? '' }),
+ setProgressPhase: (phase) => set({ progressPhase: phase }),
setCurrentPromptId: (id) => set({ currentPromptId: id }),
setError: (error) => set({ error }),
setLastGenTime: (time) => set({ lastGenTime: time }),
diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.ts
new file mode 100644
index 00000000..32e4f4a4
--- /dev/null
+++ b/src/stores/memoryStore.ts
@@ -0,0 +1,174 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import { v4 as uuid } from 'uuid'
+import type { MemoryEntry, MemoryCategory } from '../types/agent-mode'
+
+interface MemoryState {
+ entries: MemoryEntry[]
+ lastSynced: number
+
+ // Actions
+ addEntry: (category: MemoryCategory, content: string, source?: string) => void
+ removeEntry: (id: string) => void
+ clearAll: () => void
+ searchMemory: (query: string) => MemoryEntry[]
+ getMemoryForPrompt: (query: string, maxChars?: number) => string
+ exportAsMarkdown: () => string
+ importFromMarkdown: (markdown: string) => void
+}
+
+export const useMemoryStore = create<MemoryState>()(
+ persist(
+ (set, get) => ({
+ entries: [],
+ lastSynced: 0,
+
+ addEntry: (category, content, source) => {
+ const trimmed = content.trim()
+ if (!trimmed) return
+
+ // Deduplicate: don't add if exact same content already exists
+ const existing = get().entries
+ if (existing.some(e => e.content === trimmed && e.category === category)) return
+
+ set((state) => ({
+ entries: [
+ ...state.entries,
+ {
+ id: uuid(),
+ category,
+ content: trimmed,
+ timestamp: Date.now(),
+ source,
+ },
+ ],
+ lastSynced: Date.now(),
+ }))
+ },
+
+ removeEntry: (id) =>
+ set((state) => ({
+ entries: state.entries.filter((e) => e.id !== id),
+ lastSynced: Date.now(),
+ })),
+
+ clearAll: () => set({ entries: [], lastSynced: Date.now() }),
+
+ searchMemory: (query) => {
+ const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2)
+ if (words.length === 0) return get().entries.slice(-20) // return recent
+
+ return get().entries
+ .map((entry) => {
+ const text = entry.content.toLowerCase()
+ const score = words.reduce((s, w) => s + (text.includes(w) ? 1 : 0), 0)
+ return { entry, score }
+ })
+ .filter(({ score }) => score > 0)
+ .sort((a, b) => b.score - a.score)
+ .map(({ entry }) => entry)
+ },
+
+ getMemoryForPrompt: (query, maxChars = 2000) => {
+ const relevant = get().searchMemory(query)
+ if (relevant.length === 0) return ''
+
+ const categoryLabels: Record<MemoryCategory, string> = {
+ fact: 'Known fact',
+ tool_result: 'Previous result',
+ decision: 'Decision',
+ context: 'Context',
+ }
+
+ let result = ''
+ for (const entry of relevant) {
+ const line = `- [${categoryLabels[entry.category]}] ${entry.content}\n`
+ if (result.length + line.length > maxChars) break
+ result += line
+ }
+
+ return result
+ },
+
+ exportAsMarkdown: () => {
+ const entries = get().entries
+ if (entries.length === 0) return '# Agent Memory\n\nNo entries yet.\n'
+
+ const categoryOrder: MemoryCategory[] = ['fact', 'tool_result', 'decision', 'context']
+ const categoryTitles: Record<MemoryCategory, string> = {
+ fact: 'Facts',
+ tool_result: 'Tool Results',
+ decision: 'Decisions',
+ context: 'Context',
+ }
+
+ let md = '# Agent Memory\n\n'
+
+ for (const cat of categoryOrder) {
+ const catEntries = entries.filter(e => e.category === cat)
+ if (catEntries.length === 0) continue
+
+ md += `## ${categoryTitles[cat]}\n\n`
+ for (const entry of catEntries) {
+ const date = new Date(entry.timestamp).toLocaleDateString()
+ md += `- ${entry.content}`
+ if (entry.source) md += ` *(${entry.source})*`
+ md += ` — ${date}\n`
+ }
+ md += '\n'
+ }
+
+ return md
+ },
+
+ importFromMarkdown: (markdown) => {
+ const lines = markdown.split('\n')
+ const newEntries: MemoryEntry[] = []
+ let currentCategory: MemoryCategory = 'fact'
+
+ const categoryMap: Record<string, MemoryCategory> = {
+ 'facts': 'fact',
+ 'tool results': 'tool_result',
+ 'decisions': 'decision',
+ 'context': 'context',
+ }
+
+ for (const line of lines) {
+ // Detect category headers
+ const headerMatch = line.match(/^##\s+(.+)/)
+ if (headerMatch) {
+ const header = headerMatch[1].toLowerCase().trim()
+ if (categoryMap[header]) {
+ currentCategory = categoryMap[header]
+ }
+ continue
+ }
+
+ // Parse list items
+ const itemMatch = line.match(/^-\s+(.+?)(?:\s+\*\((.+?)\)\*)?(?:\s+—\s+.+)?$/)
+ if (itemMatch) {
+ const content = itemMatch[1].trim()
+ const source = itemMatch[2] || 'import'
+ if (content) {
+ newEntries.push({
+ id: uuid(),
+ category: currentCategory,
+ content,
+ timestamp: Date.now(),
+ source,
+ })
+ }
+ }
+ }
+
+ if (newEntries.length > 0) {
+ set((state) => ({
+ entries: [...state.entries, ...newEntries],
+ lastSynced: Date.now(),
+ }))
+ }
+ },
+ }),
+ { name: 'locally-uncensored-memory' }
+ )
+)
diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.ts
index 579f21c5..5f5d0eaa 100644
--- a/src/stores/uiStore.ts
+++ b/src/stores/uiStore.ts
@@ -1,6 +1,6 @@
import { create } from 'zustand'
-export type View = 'chat' | 'models' | 'settings' | 'create' | 'agents'
+export type View = 'chat' | 'models' | 'settings' | 'create'
interface UIState {
currentView: View
diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.ts
new file mode 100644
index 00000000..de7ebb8c
--- /dev/null
+++ b/src/types/agent-mode.ts
@@ -0,0 +1,102 @@
+// Agent Mode — Type Definitions
+// Part of the Agent Mode feature (coding-orch branch)
+
+// Permission tiers (Claude Code pattern)
+export type ToolPermission = 'auto' | 'confirm'
+
+// Tool definition for internal use
+export interface AgentToolDef {
+ name: string
+ description: string
+ parameters: {
+ type: 'object'
+ properties: Record<string, {
+ type: string
+ description: string
+ enum?: string[]
+ }>
+ required: string[]
+ }
+ permission: ToolPermission
+}
+
+// Ollama tool format (sent in API request)
+export interface OllamaTool {
+ type: 'function'
+ function: {
+ name: string
+ description: string
+ parameters: {
+ type: 'object'
+ properties: Record<string, any>
+ required: string[]
+ }
+ }
+}
+
+// What Ollama returns when the model calls a tool
+export interface OllamaToolCall {
+ function: {
+ name: string
+ arguments: Record<string, any>
+ }
+}
+
+// Ollama chat message format (extended for tool calling)
+export interface OllamaChatMessage {
+ role: string
+ content: string
+ tool_calls?: OllamaToolCall[]
+}
+
+// Streaming chunk format for agent chat
+export interface AgentChatChunk {
+ message?: {
+ content: string
+ role?: string
+ tool_calls?: OllamaToolCall[]
+ }
+ done?: boolean
+}
+
+// Tool call lifecycle status
+export type ToolCallStatus = 'pending_approval' | 'running' | 'completed' | 'failed' | 'rejected'
+
+// Internal tracking of a tool call
+export interface AgentToolCall {
+ id: string
+ toolName: string
+ args: Record<string, any>
+ status: ToolCallStatus
+ result?: string
+ error?: string
+ duration?: number
+ timestamp: number
+}
+
+// Phases rendered as distinct UI blocks in chat
+export type AgentPhase = 'thinking' | 'planning' | 'tool_call' | 'reflection' | 'answer'
+
+// A block in the agent's response (tool call, thinking, etc.)
+export interface AgentBlock {
+ id: string
+ phase: AgentPhase
+ content: string
+ toolCall?: AgentToolCall
+ timestamp: number
+}
+
+// Sandbox configuration
+export type SandboxLevel = 'restricted' | 'full'
+
+// ── Memory System ─────────────────────────────────────────────
+
+export type MemoryCategory = 'fact' | 'tool_result' | 'decision' | 'context'
+
+export interface MemoryEntry {
+ id: string
+ category: MemoryCategory
+ content: string
+ timestamp: number
+ source?: string // e.g. "agent:web_search", "user:manual", "auto:extraction"
+}
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 6194363f..50fead6a 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -1,4 +1,6 @@
-export type Role = 'user' | 'assistant' | 'system'
+import type { AgentBlock } from './agent-mode'
+
+export type Role = 'user' | 'assistant' | 'system' | 'tool'
export interface Message {
id: string
@@ -7,6 +9,9 @@ export interface Message {
thinking?: string
timestamp: number
sources?: { documentName: string; chunkIndex: number; preview: string }[]
+ // Agent Mode fields
+ agentBlocks?: AgentBlock[]
+ toolCallSummary?: string
}
export interface Conversation {