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: Memory System + Agent Workflows — persistent AI memory with context-aware injection, multi-step workflow engine

PurpleDoubleD2245e0c804bc
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..9fdae2cb
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,71 @@
+# CLAUDE.md — Locally Uncensored
+
+## Project
+
+Local-first AI chat app with image/video generation. Tauri v2 (Rust) + React 19 + TypeScript + Vite + Zustand + TailwindCSS 4.
+
+## Commands
+
+```bash
+npm run dev # Vite dev server (localhost:5173)
+npm run build # Production build
+npx vitest run # Run all 416 tests
+npx tsc --noEmit # Type check
+```
+
+## Architecture
+
+### Frontend (src/)
+- **api/** — Backend clients (Ollama, ComfyUI, providers, RAG, voice, agents)
+- **api/providers/** — Multi-provider system (Ollama, OpenAI-compat, Anthropic)
+- **components/** — React components (chat, create, models, settings, onboarding, layout)
+- **hooks/** — useChat, useAgentChat, useModels, useCreate, useRAG, useVoice, useABCompare, useBenchmark, useKeyboardShortcuts, useMemory, useWorkflow
+- **stores/** — Zustand stores (chat, model, settings, provider, agentMode, memory, rag, voice, create, workflow, agentWorkflow, ui, compare, benchmark)
+- **lib/** — Utilities (formatters, model-compatibility, context-compaction, backend-detector, systemCheck, chat-export, benchmark-prompts, memory-extraction, workflow-engine, agent-strategy, built-in-workflows)
+- **types/** — TypeScript interfaces
+
+### Tauri Backend (src-tauri/)
+- **commands/** — Rust commands (proxy, download, process, search, agent, whisper)
+- Auto-starts Ollama and ComfyUI on launch
+- CORS proxy for localhost calls in production .exe
+
+### Key Patterns
+
+**Provider Interface:** All LLM backends implement `ProviderClient` (chatStream, chatWithTools, listModels, checkConnection, getContextLength). Never call `ollama.ts` directly for chat — go through the provider.
+
+**Model Name Prefixing:** Ollama models have no prefix (`llama3.1:8b`). Cloud models are prefixed (`openai::gpt-4o`, `anthropic::claude-sonnet-4-20250514`).
+
+**Streaming:** Ollama uses NDJSON (`stream.ts`), OpenAI/Anthropic use SSE (`sse.ts`). Both yield unified `ChatStreamChunk`.
+
+**Dev vs Prod Routing:** `backend.ts` routes via `isTauri()`. Dev: Vite proxy. Prod: Rust `invoke()`.
+
+**Agent Mode:** Per-conversation toggle. Strategy: native (Ollama/OpenAI/Anthropic) or hermes_xml (prompt-based fallback). Tools need `permission: 'auto' | 'confirm'`. Strategy resolution extracted to `agent-strategy.ts` (shared by useAgentChat + WorkflowEngine).
+
+**Memory System:** Claude Code-inspired persistent memory. 4 internal types (user/feedback/project/reference) but simplified UI (flat list, no type selection). Context-aware injection: auto-scales budget based on model context (0 at 2K, 300tok at 4K, 800tok at 8K+, 4000tok at 128K+). Auto-extraction via LLM after each turn (on by default). Types hidden from user, used internally for smart prioritization.
+
+**Agent Workflows:** Reusable multi-step agent chains. Step types: prompt, tool, condition, loop, user_input, memory_save. WorkflowEngine class executes steps with {{variable}} interpolation. 3 built-in workflows (Research Topic, Summarize URL, Code Review). `run_workflow` tool lets agent trigger workflows. "run workflow X" prefix detection in chat.
+
+**A/B Compare:** Separate view (ABCompare.tsx) with own store (compareStore). Parallel streaming via getProviderForModel(). Not persisted — session only.
+
+**Benchmark:** benchmarkStore (persisted). Standalone getAverageSpeed/getLeaderboard functions (not store methods — avoids React getSnapshot loops). BenchmarkButton on each ModelCard.
+
+**Search Providers:** Configurable in settings (auto/brave/tavily). Provider + API keys passed from agents.ts to vite middleware via backendCall("web_search"). Fallback chain: preferred > SearXNG > Brave > Tavily > DDG > Wikipedia.
+
+**Discover Models:** Split into Uncensored (getUncensoredTextModels) and Mainstream (getMainstreamTextModels) with clickable section-header tabs.
+
+## Rules
+
+- UI text sizes: `text-[0.6rem]` to `text-[0.75rem]`. Icons: 10-14px. No large text.
+- No emojis in code or UI. Use Lucide icons or CSS elements.
+- No amber/yellow colors in benchmark UI. Keep neutral grays. Only the trophy icon stays gold.
+- Every new API endpoint in vite.config.ts MUST also be implemented in Tauri Rust backend.
+- Provider changes go through `providerStore` and `registry.ts`, not direct API calls.
+- Ollama is default but deactivatable. Local backends and cloud are mutually exclusive.
+- Cloud providers show a privacy warning popup before activation.
+- Pull/Delete model only available when Ollama is the active provider.
+- Tests use Vitest. Run `npx vitest run` before pushing.
+- Zustand store methods that return derived data (getters) must be standalone functions, not store state — prevents React 19 getSnapshot infinite loop.
+
+## Branch
+
+`feature/multi-provider` — Multi-provider support + v2.0 features (A/B Compare, Benchmark, LaTeX, Token Counter, Chat Export, Keyboard Shortcuts, Search Providers, Gemma 4, Memory System, Agent Workflows). Not yet merged to master.
diff --git a/README.md b/README.md
index 83f86434..3226a025 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,8 @@ Tired of switching between Ollama for chat, ComfyUI for images, and another tool
| Image Generation | ✅ | ❌ | ❌ | ❌ |
| Video Generation | ✅ | ❌ | ❌ | ❌ |
| Uncensored by Default | ✅ | ❌ | ❌ | ⚠️ |
-| Memory System | ✅ | ❌ | ❌ | ❌ |
+| Memory System | ✅ | ⚠️ (plugin) | ❌ | ❌ |
+| **Agent Workflows** | **✅** | ❌ | ❌ | ❌ |
| LaTeX / Math Rendering | ✅ | ✅ | ❌ | ❌ |
| One-Click Setup | ✅ | ❌ (Docker) | ✅ | ❌ (Node.js) |
| 25+ Built-in Personas | ✅ | ❌ | ❌ | ⚠️ (manual) |
@@ -69,7 +70,8 @@ Tired of switching between Ollama for chat, ComfyUI for images, and another tool
- **Agent Mode (Beta)** — Give your AI tools: web search, web fetch, file I/O, code execution, image generation. It chains tools autonomously to answer questions with real data. Best with [Hermes 3](https://ollama.com/library/hermes3).
- **Model A/B Compare** — Send the same prompt to two models side by side. Compare speed, quality, and token usage in real-time with parallel streaming.
- **Local Benchmark** — One-click benchmark any model on your hardware. Measures tokens/sec, time-to-first-token. Leaderboard across all tested models.
-- **Memory System** — Agent Mode auto-saves tool results. Persistent across sessions. Export/import as .md.
+- **Memory System** — The AI remembers you across conversations. Context-aware injection scales with model size. Auto-extraction learns from every exchange. Export/import as .md or .json.
+- **Agent Workflows** — Reusable multi-step agent chains. 3 built-in workflows (Research Topic, Summarize URL, Code Review). Visual builder for custom workflows with prompt, tool, condition, and loop steps.
- **Image Generation** — Text-to-image via ComfyUI with full parameter control
- **Video Generation** — Text-to-video with Wan 2.1/2.2, HunyuanVideo, LTX support
- **Document Chat (RAG)** — Upload PDFs, DOCX, or TXT files and chat with your documents
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.ts
index 1caedfc8..0efbed0a 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -9,8 +9,8 @@ import {
// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────
describe('AGENT_TOOL_DEFS', () => {
- it('contains exactly 6 tool definitions', () => {
- expect(AGENT_TOOL_DEFS).toHaveLength(6)
+ it('contains exactly 7 tool definitions', () => {
+ expect(AGENT_TOOL_DEFS).toHaveLength(7)
})
const expectedTools = [
@@ -20,6 +20,7 @@ describe('AGENT_TOOL_DEFS', () => {
'file_write',
'code_execute',
'image_generate',
+ 'run_workflow',
]
it.each(expectedTools)('includes the "%s" tool', (name) => {
@@ -45,10 +46,10 @@ describe('AGENT_TOOL_DEFS', () => {
expect(autoNames).toEqual(['file_read', 'web_fetch', 'web_search'])
})
- it('confirm-permission tools are file_write, code_execute, image_generate', () => {
+ it('confirm-permission tools are file_write, code_execute, image_generate, run_workflow', () => {
const confirmTools = AGENT_TOOL_DEFS.filter((t) => t.permission === 'confirm')
const confirmNames = confirmTools.map((t) => t.name).sort()
- expect(confirmNames).toEqual(['code_execute', 'file_write', 'image_generate'])
+ expect(confirmNames).toEqual(['code_execute', 'file_write', 'image_generate', 'run_workflow'])
})
})
diff --git a/src/api/tool-registry.ts b/src/api/tool-registry.ts
index c54342af..828328b0 100644
--- a/src/api/tool-registry.ts
+++ b/src/api/tool-registry.ts
@@ -2,6 +2,9 @@ import type { AgentToolDef, OllamaTool } from '../types/agent-mode'
import { executeTool } from './agents'
import { fetchExternal } from './backend'
import type { ToolName } from '../types/agents'
+import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
+import { WorkflowEngine } from '../lib/workflow-engine'
+import type { StepResult } from '../types/agent-workflows'
// ── Tool Definitions ──────────────────────────────────────────────
@@ -83,6 +86,19 @@ export const AGENT_TOOL_DEFS: AgentToolDef[] = [
},
permission: 'confirm',
},
+ {
+ name: 'run_workflow',
+ description: 'Run a saved agent workflow by name. Available workflows: Research Topic, Summarize URL, Code Review, and any custom workflows.',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name of the workflow to run (e.g. "Research Topic", "Summarize URL", "Code Review")' },
+ input: { type: 'string', description: 'Initial input to provide to the workflow (e.g. a topic, URL, or file path)' },
+ },
+ required: ['name'],
+ },
+ permission: 'confirm',
+ },
]
// ── Convert to Ollama Format ──────────────────────────────────────
@@ -121,6 +137,11 @@ export async function executeAgentTool(
return await executeWebFetch(args.url, args.maxLength)
}
+ // Handle run_workflow
+ if (name === 'run_workflow') {
+ return await executeRunWorkflow(args.name, args.input)
+ }
+
// Reuse the existing executeTool from agents.ts for other tools
return await executeTool(name as ToolName, args)
} catch (err) {
@@ -214,3 +235,41 @@ function htmlToText(html: string): string {
.replace(/\s{2,}/g, ' ')
.trim()
}
+
+// ── run_workflow: Execute a workflow by name ────────────────────
+
+async function executeRunWorkflow(workflowName: string, input?: string): Promise<string> {
+ if (!workflowName) return 'Error: No workflow name provided'
+
+ const store = useAgentWorkflowStore.getState()
+ const workflow = store.workflows.find(
+ w => w.name.toLowerCase() === workflowName.toLowerCase()
+ )
+
+ if (!workflow) {
+ const available = store.workflows.map(w => w.name).join(', ')
+ return `Error: Workflow "${workflowName}" not found. Available: ${available}`
+ }
+
+ // Run the workflow with a simple callback collector
+ const results: StepResult[] = []
+ let finalOutput = ''
+
+ const callbacks = {
+ onStepStart: () => {},
+ onStepComplete: (_idx: number, result: StepResult) => { results.push(result) },
+ onStepError: () => {},
+ onWaitingForInput: () => {},
+ onComplete: () => {
+ const lastOutput = results.filter(r => r.output).pop()
+ finalOutput = lastOutput?.output || 'Workflow completed with no output.'
+ },
+ onError: (error: string) => { finalOutput = `Workflow error: ${error}` },
+ }
+
+ const initialVars = input ? { user_input: input, last_output: input } : {}
+ const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, initialVars)
+
+ await engine.run()
+ return finalOutput
+}
diff --git a/src/components/agents/WorkflowBuilder.tsx b/src/components/agents/WorkflowBuilder.tsx
new file mode 100644
index 00000000..f43be900
--- /dev/null
+++ b/src/components/agents/WorkflowBuilder.tsx
@@ -0,0 +1,258 @@
+import { useState } from 'react'
+import { v4 as uuid } from 'uuid'
+import { Plus, Trash2, ChevronUp, ChevronDown, Save, X, ArrowLeft } from 'lucide-react'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { AGENT_TOOL_DEFS } from '../../api/tool-registry'
+import { GlowButton } from '../ui/GlowButton'
+import type { WorkflowStep, WorkflowStepType, AgentWorkflow } from '../../types/agent-workflows'
+import type { MemoryType } from '../../types/agent-mode'
+
+const STEP_TYPE_LABELS: Record<WorkflowStepType, string> = {
+ prompt: 'Prompt',
+ tool: 'Tool',
+ condition: 'Condition',
+ loop: 'Loop',
+ user_input: 'User Input',
+ memory_save: 'Save to Memory',
+}
+
+const STEP_TYPE_COLORS: Record<WorkflowStepType, string> = {
+ prompt: 'border-blue-500/30 bg-blue-500/5',
+ tool: 'border-green-500/30 bg-green-500/5',
+ condition: 'border-amber-500/30 bg-amber-500/5',
+ loop: 'border-purple-500/30 bg-purple-500/5',
+ user_input: 'border-cyan-500/30 bg-cyan-500/5',
+ memory_save: 'border-pink-500/30 bg-pink-500/5',
+}
+
+function createEmptyStep(type: WorkflowStepType): WorkflowStep {
+ const base: WorkflowStep = { id: uuid(), type, label: STEP_TYPE_LABELS[type] }
+ switch (type) {
+ case 'prompt': return { ...base, prompt: '', allowedTools: [] }
+ case 'tool': return { ...base, toolName: '', toolArgTemplates: {} }
+ case 'condition': return { ...base, condition: { source: 'last_output', operator: 'contains', value: '', thenStepId: '', elseStepId: '' } }
+ case 'loop': return { ...base, loop: { maxIterations: 5, condition: { source: 'last_output', operator: 'truthy', value: '' }, bodyStepIds: [] } }
+ case 'user_input': return { ...base, userInputPrompt: '' }
+ case 'memory_save': return { ...base, memorySave: { type: 'reference', titleTemplate: '', contentTemplate: '{{last_output}}', tags: [] } }
+ default: return base
+ }
+}
+
+interface WorkflowBuilderProps {
+ workflowId?: string // undefined = create new
+ onSave: () => void
+ onCancel: () => void
+}
+
+export function WorkflowBuilder({ workflowId, onSave, onCancel }: WorkflowBuilderProps) {
+ const store = useAgentWorkflowStore()
+ const existing = workflowId ? store.getWorkflow(workflowId) : undefined
+
+ const [name, setName] = useState(existing?.name || '')
+ const [description, setDescription] = useState(existing?.description || '')
+ const [steps, setSteps] = useState<WorkflowStep[]>(existing?.steps || [])
+ const [expandedStep, setExpandedStep] = useState<string | null>(null)
+
+ const addStep = (type: WorkflowStepType) => {
+ const newStep = createEmptyStep(type)
+ setSteps([...steps, newStep])
+ setExpandedStep(newStep.id)
+ }
+
+ const removeStep = (id: string) => {
+ setSteps(steps.filter(s => s.id !== id))
+ if (expandedStep === id) setExpandedStep(null)
+ }
+
+ const moveStep = (index: number, direction: -1 | 1) => {
+ const newIndex = index + direction
+ if (newIndex < 0 || newIndex >= steps.length) return
+ const arr = [...steps]
+ ;[arr[index], arr[newIndex]] = [arr[newIndex], arr[index]]
+ setSteps(arr)
+ }
+
+ const updateStep = (id: string, updates: Partial<WorkflowStep>) => {
+ setSteps(steps.map(s => s.id === id ? { ...s, ...updates } : s))
+ }
+
+ const handleSave = () => {
+ if (!name.trim()) return
+
+ if (workflowId && existing) {
+ store.updateWorkflow(workflowId, { name, description, steps })
+ } else {
+ store.addWorkflow({
+ name,
+ description,
+ icon: 'Zap',
+ steps,
+ variables: {},
+ isBuiltIn: false,
+ })
+ }
+ onSave()
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Header */}
+ <div className="flex items-center gap-2">
+ <button onClick={onCancel} className="p-1 rounded hover:bg-white/10 text-gray-400">
+ <ArrowLeft size={14} />
+ </button>
+ <h3 className="text-[0.75rem] font-semibold text-white">
+ {workflowId ? 'Edit Workflow' : 'New Workflow'}
+ </h3>
+ </div>
+
+ {/* Name & Description */}
+ <div className="space-y-2">
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Workflow name"
+ className="w-full px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-[0.7rem] text-gray-200 placeholder-gray-600 focus:outline-none focus:border-white/20"
+ />
+ <input
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="Description"
+ className="w-full px-2.5 py-1.5 rounded-lg bg-white/5 border border-white/10 text-[0.7rem] text-gray-400 placeholder-gray-600 focus:outline-none focus:border-white/20"
+ />
+ </div>
+
+ {/* Steps */}
+ <div className="space-y-1.5">
+ <p className="text-[0.6rem] text-gray-500 uppercase tracking-wider">Steps</p>
+
+ {steps.map((step, index) => (
+ <div key={step.id} className={`rounded-lg border ${STEP_TYPE_COLORS[step.type]} transition-all`}>
+ {/* Step header */}
+ <div
+ className="flex items-center gap-2 px-2.5 py-1.5 cursor-pointer"
+ onClick={() => setExpandedStep(expandedStep === step.id ? null : step.id)}
+ >
+ <span className="text-[0.6rem] text-gray-500 w-4 text-center">{index + 1}</span>
+ <span className="text-[0.55rem] px-1.5 py-0.5 rounded bg-white/5 text-gray-400">
+ {STEP_TYPE_LABELS[step.type]}
+ </span>
+ <span className="text-[0.65rem] text-gray-300 flex-1 truncate">{step.label}</span>
+ <div className="flex items-center gap-0.5">
+ <button onClick={(e) => { e.stopPropagation(); moveStep(index, -1) }} className="p-0.5 rounded hover:bg-white/10 text-gray-600" disabled={index === 0}>
+ <ChevronUp size={10} />
+ </button>
+ <button onClick={(e) => { e.stopPropagation(); moveStep(index, 1) }} className="p-0.5 rounded hover:bg-white/10 text-gray-600" disabled={index === steps.length - 1}>
+ <ChevronDown size={10} />
+ </button>
+ <button onClick={(e) => { e.stopPropagation(); removeStep(step.id) }} className="p-0.5 rounded hover:bg-red-500/20 text-gray-600 hover:text-red-400">
+ <Trash2 size={10} />
+ </button>
+ </div>
+ </div>
+
+ {/* Expanded step editor */}
+ {expandedStep === step.id && (
+ <div className="px-2.5 pb-2.5 space-y-2 border-t border-white/5">
+ <input
+ value={step.label}
+ onChange={(e) => updateStep(step.id, { label: e.target.value })}
+ placeholder="Step label"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none mt-2"
+ />
+
+ {/* Type-specific fields */}
+ {step.type === 'prompt' && (
+ <textarea
+ value={step.prompt || ''}
+ onChange={(e) => updateStep(step.id, { prompt: e.target.value })}
+ placeholder="Prompt text (use {{variable}} for interpolation)"
+ rows={3}
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none resize-none"
+ />
+ )}
+
+ {step.type === 'tool' && (
+ <>
+ <select
+ value={step.toolName || ''}
+ onChange={(e) => updateStep(step.id, { toolName: e.target.value })}
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none"
+ >
+ <option value="">Select tool...</option>
+ {AGENT_TOOL_DEFS.map(t => (
+ <option key={t.name} value={t.name}>{t.name}</option>
+ ))}
+ </select>
+ <input
+ value={step.toolArgTemplates ? JSON.stringify(step.toolArgTemplates) : ''}
+ onChange={(e) => {
+ try { updateStep(step.id, { toolArgTemplates: JSON.parse(e.target.value) }) } catch {}
+ }}
+ placeholder='Args JSON: {"query": "{{user_input}}"}'
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none"
+ />
+ </>
+ )}
+
+ {step.type === 'user_input' && (
+ <input
+ value={step.userInputPrompt || ''}
+ onChange={(e) => updateStep(step.id, { userInputPrompt: e.target.value })}
+ placeholder="Prompt shown to user"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none"
+ />
+ )}
+
+ {step.type === 'memory_save' && (
+ <>
+ <select
+ value={step.memorySave?.type || 'reference'}
+ onChange={(e) => updateStep(step.id, { memorySave: { ...step.memorySave!, type: e.target.value as MemoryType } })}
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none"
+ >
+ <option value="user">User</option>
+ <option value="feedback">Feedback</option>
+ <option value="project">Project</option>
+ <option value="reference">Reference</option>
+ </select>
+ <input
+ value={step.memorySave?.titleTemplate || ''}
+ onChange={(e) => updateStep(step.id, { memorySave: { ...step.memorySave!, titleTemplate: e.target.value } })}
+ placeholder="Title template: Research: {{user_input}}"
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none"
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* Add step buttons */}
+ <div className="flex flex-wrap gap-1 pt-1">
+ {(['prompt', 'tool', 'user_input', 'memory_save', 'condition', 'loop'] as WorkflowStepType[]).map(type => (
+ <button
+ key={type}
+ onClick={() => addStep(type)}
+ className="text-[0.6rem] px-2 py-0.5 rounded border border-white/10 text-gray-500 hover:text-gray-300 hover:border-white/20 transition-colors"
+ >
+ <Plus size={8} className="inline mr-0.5" />
+ {STEP_TYPE_LABELS[type]}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Save / Cancel */}
+ <div className="flex gap-2 pt-2">
+ <GlowButton onClick={handleSave} className="flex-1 text-xs flex items-center justify-center gap-1.5" disabled={!name.trim()}>
+ <Save size={12} /> Save
+ </GlowButton>
+ <GlowButton variant="secondary" onClick={onCancel} className="flex-1 text-xs flex items-center justify-center gap-1.5">
+ <X size={12} /> Cancel
+ </GlowButton>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/agents/WorkflowList.tsx b/src/components/agents/WorkflowList.tsx
new file mode 100644
index 00000000..653ca70c
--- /dev/null
+++ b/src/components/agents/WorkflowList.tsx
@@ -0,0 +1,119 @@
+import { useState } from 'react'
+import { Play, Pencil, Trash2, Copy, Plus, Search, FileText, Code, Zap } from 'lucide-react'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { GlowButton } from '../ui/GlowButton'
+import type { AgentWorkflow } from '../../types/agent-workflows'
+
+// Map workflow icon names to Lucide components
+const ICON_MAP: Record<string, typeof Search> = {
+ Search, FileText, Code, Zap,
+}
+
+interface WorkflowListProps {
+ onRun: (workflowId: string) => void
+ onEdit: (workflowId: string) => void
+ onCreate: () => void
+}
+
+export function WorkflowList({ onRun, onEdit, onCreate }: WorkflowListProps) {
+ const { workflows, removeWorkflow, duplicateWorkflow } = useAgentWorkflowStore()
+ const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
+
+ const handleDelete = (id: string) => {
+ if (confirmDelete === id) {
+ removeWorkflow(id)
+ setConfirmDelete(null)
+ } else {
+ setConfirmDelete(id)
+ setTimeout(() => setConfirmDelete(null), 3000)
+ }
+ }
+
+ const builtIn = workflows.filter(w => w.isBuiltIn)
+ const custom = workflows.filter(w => !w.isBuiltIn)
+
+ const renderWorkflow = (workflow: AgentWorkflow) => {
+ const Icon = ICON_MAP[workflow.icon] || Zap
+ return (
+ <div
+ key={workflow.id}
+ className="flex items-center gap-2.5 px-2.5 py-2 rounded-lg hover:bg-white/[0.03] group border border-transparent hover:border-white/5 transition-all"
+ >
+ <div className="w-7 h-7 rounded-lg bg-white/5 flex items-center justify-center shrink-0">
+ <Icon size={13} className="text-gray-400" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.7rem] font-medium text-gray-200 truncate">{workflow.name}</p>
+ <p className="text-[0.6rem] text-gray-500 truncate">{workflow.description}</p>
+ <p className="text-[0.55rem] text-gray-600">{workflow.steps.length} steps</p>
+ </div>
+ <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
+ <button
+ onClick={() => onRun(workflow.id)}
+ className="p-1 rounded hover:bg-green-500/20 text-gray-500 hover:text-green-400"
+ title="Run"
+ >
+ <Play size={11} />
+ </button>
+ {!workflow.isBuiltIn && (
+ <button
+ onClick={() => onEdit(workflow.id)}
+ className="p-1 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300"
+ title="Edit"
+ >
+ <Pencil size={11} />
+ </button>
+ )}
+ <button
+ onClick={() => duplicateWorkflow(workflow.id)}
+ className="p-1 rounded hover:bg-white/10 text-gray-500 hover:text-gray-300"
+ title="Duplicate"
+ >
+ <Copy size={11} />
+ </button>
+ {!workflow.isBuiltIn && (
+ <button
+ onClick={() => handleDelete(workflow.id)}
+ className={`p-1 rounded text-gray-500 ${confirmDelete === workflow.id ? 'bg-red-500/20 text-red-400' : 'hover:bg-red-500/20 hover:text-red-400'}`}
+ title={confirmDelete === workflow.id ? 'Confirm delete' : 'Delete'}
+ >
+ <Trash2 size={11} />
+ </button>
+ )}
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-3">
+ {/* Built-in workflows */}
+ {builtIn.length > 0 && (
+ <div className="space-y-1">
+ <p className="text-[0.6rem] text-gray-500 uppercase tracking-wider px-1">Built-in</p>
+ {builtIn.map(renderWorkflow)}
+ </div>
+ )}
+
+ {/* Custom workflows */}
+ {custom.length > 0 && (
+ <div className="space-y-1">
+ <p className="text-[0.6rem] text-gray-500 uppercase tracking-wider px-1">Custom</p>
+ {custom.map(renderWorkflow)}
+ </div>
+ )}
+
+ {workflows.length === 0 && (
+ <p className="text-[0.7rem] text-gray-500 text-center py-4">No workflows yet.</p>
+ )}
+
+ {/* Create button */}
+ <button
+ onClick={onCreate}
+ className="w-full flex items-center justify-center gap-1 py-1.5 rounded-lg border border-dashed border-white/10 text-[0.65rem] text-gray-500 hover:text-gray-300 hover:border-white/20 transition-colors"
+ >
+ <Plus size={10} /> Create Workflow
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/agents/WorkflowRunner.tsx b/src/components/agents/WorkflowRunner.tsx
new file mode 100644
index 00000000..02515207
--- /dev/null
+++ b/src/components/agents/WorkflowRunner.tsx
@@ -0,0 +1,153 @@
+import { useState } from 'react'
+import { Loader2, Check, X, Circle, Send, Square } from 'lucide-react'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { GlowButton } from '../ui/GlowButton'
+import type { StepStatus } from '../../types/agent-workflows'
+
+const STATUS_ICONS: Record<StepStatus | 'waiting', typeof Check> = {
+ pending: Circle,
+ running: Loader2,
+ completed: Check,
+ failed: X,
+ skipped: Circle,
+ waiting: Loader2,
+}
+
+const STATUS_COLORS: Record<StepStatus | 'waiting', string> = {
+ pending: 'text-gray-600',
+ running: 'text-blue-400 animate-spin',
+ completed: 'text-green-400',
+ failed: 'text-red-400',
+ skipped: 'text-gray-600',
+ waiting: 'text-amber-400 animate-pulse',
+}
+
+interface WorkflowRunnerProps {
+ executionId: string
+ workflowSteps: Array<{ id: string; label: string; type: string }>
+ waitingForInput: string | null
+ currentStepLabel: string
+ onProvideInput: (input: string) => void
+ onCancel: () => void
+}
+
+export function WorkflowRunner({
+ executionId,
+ workflowSteps,
+ waitingForInput,
+ currentStepLabel,
+ onProvideInput,
+ onCancel,
+}: WorkflowRunnerProps) {
+ const execution = useAgentWorkflowStore((s) => s.executions.find(e => e.id === executionId))
+ const [inputValue, setInputValue] = useState('')
+
+ if (!execution) return null
+
+ const handleSubmitInput = () => {
+ if (!inputValue.trim()) return
+ onProvideInput(inputValue.trim())
+ setInputValue('')
+ }
+
+ const elapsed = execution.completedAt
+ ? Math.round((execution.completedAt - execution.startedAt) / 1000)
+ : Math.round((Date.now() - execution.startedAt) / 1000)
+
+ return (
+ <div className="space-y-3 p-3 rounded-lg border border-white/10 bg-white/[0.02]">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="text-[0.7rem] font-medium text-gray-200">{execution.workflowName}</p>
+ <p className="text-[0.6rem] text-gray-500">
+ {execution.status === 'running' || execution.status === 'waiting_input'
+ ? `Running... ${elapsed}s`
+ : execution.status === 'completed'
+ ? `Completed in ${elapsed}s`
+ : execution.status === 'failed'
+ ? `Failed after ${elapsed}s`
+ : execution.status === 'cancelled'
+ ? 'Cancelled'
+ : execution.status}
+ </p>
+ </div>
+ {(execution.status === 'running' || execution.status === 'waiting_input') && (
+ <button
+ onClick={onCancel}
+ className="p-1 rounded hover:bg-red-500/20 text-gray-500 hover:text-red-400"
+ title="Cancel"
+ >
+ <Square size={12} />
+ </button>
+ )}
+ </div>
+
+ {/* Step progress */}
+ <div className="space-y-1">
+ {workflowSteps.map((step, index) => {
+ const result = execution.stepResults.find(r => r.stepId === step.id)
+ let status: StepStatus | 'waiting' = 'pending'
+ if (result) {
+ status = result.status
+ } else if (index === execution.currentStepIndex && execution.status === 'waiting_input') {
+ status = 'waiting'
+ } else if (index === execution.currentStepIndex && execution.status === 'running') {
+ status = 'running'
+ }
+
+ const Icon = STATUS_ICONS[status]
+
+ return (
+ <div key={step.id} className="flex items-start gap-2">
+ <Icon size={11} className={`mt-0.5 shrink-0 ${STATUS_COLORS[status]}`} />
+ <div className="flex-1 min-w-0">
+ <p className={`text-[0.65rem] ${status === 'completed' || status === 'running' || status === 'waiting' ? 'text-gray-300' : 'text-gray-500'}`}>
+ {step.label}
+ </p>
+ {result?.output && status === 'completed' && (
+ <p className="text-[0.6rem] text-gray-500 truncate mt-0.5">
+ {result.output.substring(0, 100)}
+ </p>
+ )}
+ {result?.error && (
+ <p className="text-[0.6rem] text-red-400/70 mt-0.5">{result.error}</p>
+ )}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+
+ {/* User input prompt */}
+ {waitingForInput && (
+ <div className="space-y-1.5 pt-1 border-t border-white/5">
+ <p className="text-[0.65rem] text-amber-400">{waitingForInput}</p>
+ <div className="flex gap-1.5">
+ <input
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleSubmitInput()}
+ placeholder="Type your input..."
+ className="flex-1 px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.7rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"
+ autoFocus
+ />
+ <button
+ onClick={handleSubmitInput}
+ className="px-2 py-1 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors"
+ >
+ <Send size={11} />
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Error */}
+ {execution.error && (
+ <p className="text-[0.65rem] text-red-400 bg-red-500/5 rounded px-2 py-1 border border-red-500/20">
+ {execution.error}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
index 8dc33a00..59ef366f 100644
--- a/src/components/settings/MemorySettings.tsx
+++ b/src/components/settings/MemorySettings.tsx
@@ -1,50 +1,90 @@
-import { useState, useRef } from 'react'
-import { Brain, Download, Upload, Trash2, Search, Tag } from 'lucide-react'
-import { useMemoryStore } from '../../stores/memoryStore'
+import { useState, useRef, useEffect } from 'react'
+import { Brain, Download, Upload, Trash2, Search, Plus, X, Check, Pencil, Zap, FileJson } from 'lucide-react'
+import { useMemoryStore, getMemoryBudget } from '../../stores/memoryStore'
+import { useModelStore } from '../../stores/modelStore'
+import { getModelMaxTokens } from '../../lib/context-compaction'
import { GlowButton } from '../ui/GlowButton'
-import type { MemoryCategory } from '../../types/agent-mode'
+import type { MemoryType, MemoryFile } from '../../types/agent-mode'
-const CATEGORY_LABELS: Record<MemoryCategory, string> = {
- fact: 'Facts',
- tool_result: 'Tool Results',
- decision: 'Decisions',
- context: 'Context',
-}
+// ── Subtle type indicator (internal, not user-facing) ─────────
-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',
+const TYPE_DOT_COLORS: Record<MemoryType, string> = {
+ user: 'bg-blue-400',
+ feedback: 'bg-amber-400',
+ project: 'bg-purple-400',
+ reference: 'bg-green-400',
}
+// ── Component ─────────────────────────────────────────────────
+
export function MemorySettings() {
- const { entries, removeEntry, clearAll, exportAsMarkdown, importFromMarkdown } = useMemoryStore()
+ const { entries, removeMemory, updateMemory, clearAll, settings, updateMemorySettings, exportAsMarkdown, importFromMarkdown, exportAsJSON, importFromJSON } = useMemoryStore()
const [search, setSearch] = useState('')
- const [activeCategory, setActiveCategory] = useState<MemoryCategory | 'all'>('all')
const [confirmClear, setConfirmClear] = useState(false)
+ const [addingNew, setAddingNew] = useState(false)
+ const [editingId, setEditingId] = useState<string | null>(null)
+ const [contextBudgetLabel, setContextBudgetLabel] = useState('')
const fileInputRef = useRef<HTMLInputElement>(null)
+ const jsonInputRef = useRef<HTMLInputElement>(null)
+
+ // ── New memory form state ───────────────────────────────────
+ const [newTitle, setNewTitle] = useState('')
+ const [newContent, setNewContent] = useState('')
+
+ // ── Edit form state ─────────────────────────────────────────
+ const [editTitle, setEditTitle] = useState('')
+ const [editContent, setEditContent] = useState('')
+
+ // ── Context budget detection ────────────────────────────────
+ useEffect(() => {
+ const model = useModelStore.getState().activeModel
+ if (!model) {
+ setContextBudgetLabel('No model selected')
+ return
+ }
+ getModelMaxTokens(model).then((ctx) => {
+ const budget = getMemoryBudget(ctx)
+ if (budget.budgetTokens === 0) {
+ setContextBudgetLabel(`${Math.round(ctx / 1024)}K ctx — memory injection disabled`)
+ } else {
+ setContextBudgetLabel(`${Math.round(ctx / 1024)}K ctx — up to ${budget.maxMemories} memories injected`)
+ }
+ }).catch(() => setContextBudgetLabel(''))
+ }, [])
const filtered = entries.filter(e => {
- if (activeCategory !== 'all' && e.category !== activeCategory) return false
if (search) {
- return e.content.toLowerCase().includes(search.toLowerCase())
+ const q = search.toLowerCase()
+ return e.title.toLowerCase().includes(q) || e.content.toLowerCase().includes(q) || e.tags.some(t => t.toLowerCase().includes(q))
}
return true
})
- const handleExport = () => {
+ // ── Handlers ────────────────────────────────────────────────
+
+ const handleExportMd = () => {
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.download = 'memory.md'
a.click()
URL.revokeObjectURL(url)
}
- const handleImport = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const handleExportJSON = () => {
+ const json = exportAsJSON()
+ const blob = new Blob([json], { type: 'application/json' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = 'memory.json'
+ a.click()
+ URL.revokeObjectURL(url)
+ }
+
+ const handleImportMd = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
const reader = new FileReader()
@@ -53,7 +93,19 @@ export function MemorySettings() {
if (content) importFromMarkdown(content)
}
reader.readAsText(file)
- e.target.value = '' // reset
+ e.target.value = ''
+ }
+
+ const handleImportJSON = (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) importFromJSON(content)
+ }
+ reader.readAsText(file)
+ e.target.value = ''
}
const handleClear = () => {
@@ -66,105 +118,215 @@ export function MemorySettings() {
setConfirmClear(false)
}
- const categories: (MemoryCategory | 'all')[] = ['all', 'fact', 'tool_result', 'decision', 'context']
+ const handleAddMemory = () => {
+ if (!newTitle.trim() || !newContent.trim()) return
+ useMemoryStore.getState().addMemory({
+ type: 'user',
+ title: newTitle.trim().substring(0, 60),
+ description: newContent.trim().substring(0, 120),
+ content: newContent.trim(),
+ tags: [],
+ source: 'manual',
+ })
+ setNewTitle('')
+ setNewContent('')
+ setAddingNew(false)
+ }
+
+ const startEdit = (entry: MemoryFile) => {
+ setEditingId(entry.id)
+ setEditTitle(entry.title)
+ setEditContent(entry.content)
+ }
+
+ const saveEdit = () => {
+ if (!editingId || !editTitle.trim() || !editContent.trim()) return
+ updateMemory(editingId, {
+ title: editTitle.trim().substring(0, 60),
+ content: editContent.trim(),
+ description: editContent.trim().substring(0, 120),
+ })
+ setEditingId(null)
+ }
return (
- <div className="space-y-4">
+ <div className="space-y-3">
+ {/* Header */}
<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>
+ <Brain size={14} className="text-purple-400" />
+ <span className="text-[0.65rem] text-gray-500">
+ {entries.length} {entries.length === 1 ? 'memory' : 'memories'}
+ </span>
</div>
- <span className="text-[0.65rem] text-gray-500">
- {entries.length} {entries.length === 1 ? 'entry' : 'entries'}
- </span>
+ </div>
+
+ {/* Context budget indicator */}
+ {contextBudgetLabel && (
+ <div className="text-[0.6rem] text-gray-500 bg-gray-100 dark:bg-white/[0.03] rounded-lg px-2.5 py-1.5 border border-gray-200 dark:border-white/5">
+ {contextBudgetLabel}
+ </div>
+ )}
+
+ {/* Settings toggles */}
+ <div className="space-y-1.5 pb-2 border-b border-gray-200 dark:border-white/5">
+ <div className="flex items-center justify-between py-0.5">
+ <div className="flex items-center gap-1.5">
+ <Zap size={11} className="text-amber-400" />
+ <span className="text-[0.65rem] text-gray-400">Auto-extract memories</span>
+ <span className="text-[0.5rem] text-gray-600">(extra inference)</span>
+ </div>
+ <button
+ onClick={() => updateMemorySettings({ autoExtractEnabled: !settings.autoExtractEnabled })}
+ className={`relative w-7 h-3.5 rounded-full transition-colors ${settings.autoExtractEnabled ? '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 ${settings.autoExtractEnabled ? 'translate-x-3.5' : ''}`} />
+ </button>
+ </div>
+
+ {settings.autoExtractEnabled && (
+ <div className="flex items-center justify-between py-0.5 pl-4">
+ <span className="text-[0.6rem] text-gray-500">Also extract outside Agent Mode</span>
+ <button
+ onClick={() => updateMemorySettings({ autoExtractInAllModes: !settings.autoExtractInAllModes })}
+ className={`relative w-7 h-3.5 rounded-full transition-colors ${settings.autoExtractInAllModes ? '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 ${settings.autoExtractInAllModes ? 'translate-x-3.5' : ''}`} />
+ </button>
+ </div>
+ )}
</div>
{/* Search */}
<div className="relative">
- <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <Search size={12} className="absolute left-2.5 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"
+ placeholder="Search memories..."
+ className="w-full pl-7 pr-3 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-300 dark:border-white/10 text-[0.65rem] 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>
+ {/* Add new memory */}
+ {addingNew ? (
+ <div className="space-y-1.5 p-2.5 rounded-lg border border-white/10 bg-white/[0.02]">
+ <input
+ value={newTitle}
+ onChange={(e) => setNewTitle(e.target.value)}
+ placeholder="What should I remember?"
+ maxLength={60}
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"
+ autoFocus
+ />
+ <textarea
+ value={newContent}
+ onChange={(e) => setNewContent(e.target.value)}
+ placeholder="Details..."
+ rows={2}
+ className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none resize-none"
+ />
+ <div className="flex gap-1.5">
+ <button onClick={handleAddMemory} className="flex items-center gap-1 px-2 py-0.5 rounded bg-green-500/20 text-green-400 text-[0.6rem] hover:bg-green-500/30">
+ <Check size={10} /> Save
+ </button>
+ <button onClick={() => { setAddingNew(false); setNewTitle(''); setNewContent('') }} className="flex items-center gap-1 px-2 py-0.5 rounded bg-white/5 text-gray-400 text-[0.6rem] hover:bg-white/10">
+ <X size={10} /> Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ onClick={() => setAddingNew(true)}
+ className="w-full flex items-center justify-center gap-1 py-1.5 rounded-lg border border-dashed border-gray-300 dark:border-white/10 text-[0.6rem] text-gray-500 hover:text-gray-300 hover:border-white/20 transition-colors"
+ >
+ <Plus size={10} /> Add Memory
+ </button>
+ )}
{/* Entries list */}
- <div className="space-y-1 max-h-[300px] overflow-y-auto scrollbar-thin">
+ <div className="space-y-0.5 max-h-[280px] 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 className="text-[0.65rem] text-gray-500 text-center py-4">
+ {entries.length === 0 ? 'No memories yet. The AI will learn about you over time.' : 'No matches.'}
</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>
- )}
+ {filtered.map(entry => {
+ if (editingId === entry.id) {
+ return (
+ <div key={entry.id} className="space-y-1.5 p-2 rounded-lg border border-white/10 bg-white/[0.02]">
+ <input
+ value={editTitle}
+ onChange={(e) => setEditTitle(e.target.value)}
+ maxLength={60}
+ className="w-full px-2 py-0.5 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none"
+ />
+ <textarea
+ value={editContent}
+ onChange={(e) => setEditContent(e.target.value)}
+ rows={2}
+ className="w-full px-2 py-0.5 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none resize-none"
+ />
+ <div className="flex gap-1.5">
+ <button onClick={saveEdit} className="flex items-center gap-1 px-2 py-0.5 rounded bg-green-500/20 text-green-400 text-[0.6rem]">
+ <Check size={10} /> Save
+ </button>
+ <button onClick={() => setEditingId(null)} className="flex items-center gap-1 px-2 py-0.5 rounded bg-white/5 text-gray-400 text-[0.6rem]">
+ <X size={10} /> Cancel
+ </button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div key={entry.id} className="flex items-start gap-2 px-2 py-1.5 rounded-lg hover:bg-white/[0.03] group">
+ <div className={`w-1.5 h-1.5 rounded-full mt-1.5 shrink-0 ${TYPE_DOT_COLORS[entry.type]}`} />
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.65rem] font-medium text-gray-200">{entry.title}</p>
+ <p className="text-[0.6rem] text-gray-500 break-words line-clamp-2">{entry.content}</p>
+ </div>
+ <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
+ <button
+ onClick={() => startEdit(entry)}
+ className="p-0.5 rounded hover:bg-white/10 text-gray-600 hover:text-gray-300"
+ aria-label="Edit entry"
+ >
+ <Pencil size={10} />
+ </button>
+ <button
+ onClick={() => removeMemory(entry.id)}
+ className="p-0.5 rounded hover:bg-red-500/20 text-gray-600 hover:text-red-400"
+ aria-label="Delete entry"
+ >
+ <Trash2 size={10} />
+ </button>
</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
+ <div className="flex gap-1.5">
+ <GlowButton variant="secondary" onClick={handleExportMd} className="flex-1 text-[0.6rem] flex items-center justify-center gap-1">
+ <Download size={10} /> .md
+ </GlowButton>
+ <GlowButton variant="secondary" onClick={handleExportJSON} className="flex-1 text-[0.6rem] flex items-center justify-center gap-1">
+ <FileJson size={10} /> .json
</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 variant="secondary" onClick={() => fileInputRef.current?.click()} className="flex-1 text-[0.6rem] flex items-center justify-center gap-1">
+ <Upload size={10} /> Import
</GlowButton>
<GlowButton
variant={confirmClear ? 'danger' : 'secondary'}
onClick={handleClear}
- className="text-xs flex items-center justify-center gap-1.5 px-3"
+ className="text-[0.6rem] flex items-center justify-center gap-1 px-2.5"
>
- <Trash2 size={12} /> {confirmClear ? 'Confirm?' : 'Clear'}
+ <Trash2 size={10} /> {confirmClear ? 'Sure?' : 'Clear'}
</GlowButton>
- <input ref={fileInputRef} type="file" accept=".md,.txt" onChange={handleImport} className="hidden" />
+ <input ref={fileInputRef} type="file" accept=".md,.txt" onChange={handleImportMd} className="hidden" />
+ <input ref={jsonInputRef} type="file" accept=".json" onChange={handleImportJSON} className="hidden" />
</div>
</div>
)
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 66e1ca9e..c8172e56 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -4,7 +4,6 @@ import { motion, AnimatePresence } from 'framer-motion'
import { useSettingsStore } from '../../stores/settingsStore'
import { useUIStore } from '../../stores/uiStore'
import { SliderControl } from './SliderControl'
-import { ApiConfig } from './ApiConfig'
import { PersonaPanel } from '../personas/PersonaPanel'
import { useVoiceStore } from '../../stores/voiceStore'
import { checkWhisperAvailable } from '../../api/voice'
@@ -14,6 +13,8 @@ import { AGENT_TOOL_DEFS } from '../../api/tool-registry'
import { getRecommendedAgentModels } from '../../lib/model-compatibility'
import { MemorySettings } from './MemorySettings'
import { ProviderSettings } from './ProviderConfig'
+import { WorkflowList } from '../agents/WorkflowList'
+import { WorkflowBuilder } from '../agents/WorkflowBuilder'
// ── Collapsible Section ─────────────────────────────────────────
@@ -70,6 +71,31 @@ function InlineToggle({ label, enabled, onChange, icon }: { label: string; enabl
)
}
+// ── Workflow Section (inline, manages list/builder view) ────────
+
+function WorkflowSection() {
+ const [view, setWfView] = useState<'list' | 'builder'>('list')
+ const [editingId, setEditingId] = useState<string | undefined>()
+
+ if (view === 'builder') {
+ return (
+ <WorkflowBuilder
+ workflowId={editingId}
+ onSave={() => { setWfView('list'); setEditingId(undefined) }}
+ onCancel={() => { setWfView('list'); setEditingId(undefined) }}
+ />
+ )
+ }
+
+ return (
+ <WorkflowList
+ onRun={() => {}}
+ onEdit={(id) => { setEditingId(id); setWfView('builder') }}
+ onCreate={() => { setEditingId(undefined); setWfView('builder') }}
+ />
+ )
+}
+
// ── Main Component ──────────────────────────────────────────────
export function SettingsPage() {
@@ -159,11 +185,6 @@ export function SettingsPage() {
<ProviderSettings />
</Section>
- {/* ── API (Ollama legacy) ────────────────────── */}
- <Section title="Ollama Endpoint">
- <ApiConfig endpoint={settings.apiEndpoint} onChange={(v) => updateSettings({ apiEndpoint: v })} />
- </Section>
-
{/* ── Voice ──────────────────────────────────── */}
<Section title="Voice">
<div className="flex items-center gap-3 text-[0.65rem]">
@@ -193,6 +214,11 @@ export function SettingsPage() {
<InlineToggle label="Auto-send on Transcribe" enabled={voiceSettings.autoSendOnTranscribe} onChange={() => voiceSettings.updateVoiceSettings({ autoSendOnTranscribe: !voiceSettings.autoSendOnTranscribe })} icon={<Mic size={11} className="text-gray-500" />} />
</Section>
+ {/* ── Memory ─────────────────────────────────── */}
+ <Section title="Memory">
+ <MemorySettings />
+ </Section>
+
{/* ── Personas ───────────────────────────────── */}
<Section title="Personas">
<PersonaPanel />
@@ -247,6 +273,13 @@ export function SettingsPage() {
</Section>
)}
+ {/* ── Agent Workflows ────────────────────────── */}
+ {FEATURE_FLAGS.AGENT_WORKFLOWS && (
+ <Section title="Agent Workflows">
+ <WorkflowSection />
+ </Section>
+ )}
+
{/* ── Search Provider ────────────────────────── */}
{FEATURE_FLAGS.AGENT_MODE && (
<Section title="Search Provider">
@@ -295,13 +328,6 @@ export function SettingsPage() {
</Section>
)}
- {/* ── Memory ─────────────────────────────────── */}
- {FEATURE_FLAGS.AGENT_MODE && (
- <Section title="Agent Memory">
- <MemorySettings />
- </Section>
- )}
-
{/* ── Reset ──────────────────────────────────── */}
<div className="pt-3 pb-6">
<button
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 87585e1f..c00e22e9 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -15,8 +15,38 @@ import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, str
import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
import { useMemoryStore } from '../stores/memoryStore'
import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
+import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-extraction'
+import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
+import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
+import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
+
+// ── Standalone memory extraction (usable outside React hooks) ──
+
+async function extractMemories(userMsg: string, assistantMsg: string, conversationId: string) {
+ const { activeModel } = useModelStore.getState()
+ if (!activeModel) return
+
+ const memState = useMemoryStore.getState()
+ const existingSummary = memState.entries.slice(-20).map(e => `- [${e.type}] ${e.title}`).join('\n')
+ const messages = buildExtractionPrompt(userMsg, assistantMsg, existingSummary)
+
+ const { provider, modelId } = getProviderForModel(activeModel)
+ let fullResponse = ''
+ const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 500 })
+ for await (const chunk of stream) {
+ if (chunk.content) fullResponse += chunk.content
+ if (chunk.done) break
+ }
+
+ const result = parseExtractionResponse(fullResponse)
+ if (result.shouldSave) {
+ for (const memory of result.memories) {
+ memState.addMemory({ ...memory, source: conversationId })
+ }
+ }
+}
// ── Approval promise management ───────────────────────────────
@@ -87,6 +117,56 @@ export function useAgentChat() {
if (!activeModel) return
+ // ── Workflow trigger detection ──────────────────────────
+ const workflowMatch = userContent.match(/^run\s+workflow\s+(.+)$/i)
+ if (workflowMatch) {
+ const workflowName = workflowMatch[1].trim()
+ const wfStore = useAgentWorkflowStore.getState()
+ const workflow = wfStore.workflows.find(
+ w => w.name.toLowerCase() === workflowName.toLowerCase()
+ )
+ if (workflow) {
+ // Delegate to workflow engine
+ let convId = store.activeConversationId
+ if (!convId) {
+ convId = store.createConversation(activeModel, persona?.systemPrompt || '')
+ }
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'user', content: userContent, timestamp: Date.now(),
+ })
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', content: `Running workflow: **${workflow.name}**...`, timestamp: Date.now(),
+ })
+
+ const results: StepResult[] = []
+ const callbacks: WorkflowEngineCallbacks = {
+ onStepStart: () => {},
+ onStepComplete: (_i, r) => { results.push(r) },
+ onStepError: () => {},
+ onWaitingForInput: () => {},
+ onComplete: () => {
+ const lastOutput = results.filter(r => r.output).pop()
+ if (lastOutput && convId) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', content: lastOutput.output, timestamp: Date.now(),
+ })
+ }
+ },
+ onError: (err) => {
+ if (convId) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', content: `Workflow error: ${err}`, timestamp: Date.now(),
+ })
+ }
+ },
+ }
+
+ const engine = new WorkflowEngine(workflow, convId, callbacks)
+ await engine.run()
+ return
+ }
+ }
+
// ── Resolve provider ────────────────────────────────────
const providerId = getProviderIdFromModel(activeModel)
const { provider, modelId } = getProviderForModel(activeModel)
@@ -178,10 +258,15 @@ export function useAgentChat() {
}
}
- // Memory context injection
- const memoryContext = useMemoryStore.getState().getMemoryForPrompt(userContent, 2000)
- if (memoryContext) {
- systemPrompt = (systemPrompt || '') + `\n\n## Remembered Context\n${memoryContext}`
+ // Memory context injection (context-aware)
+ try {
+ const memContextTokens = await getModelMaxTokens(activeModel)
+ const memoryContext = useMemoryStore.getState().getMemoriesForPrompt(userContent, memContextTokens)
+ if (memoryContext) {
+ systemPrompt = (systemPrompt || '') + `\n\n## Remembered Context\n${memoryContext}`
+ }
+ } catch {
+ // Memory injection is non-critical
}
// Build agent system prompt
@@ -383,11 +468,14 @@ export function useAgentChat() {
if (!isError) {
const argsShort = JSON.stringify(tc.function.arguments).substring(0, 100)
const resultShort = result.substring(0, 200)
- useMemoryStore.getState().addEntry(
- 'tool_result',
- `${tc.function.name}(${argsShort}) → ${resultShort}`,
- `agent:${tc.function.name}`
- )
+ useMemoryStore.getState().addMemory({
+ type: 'reference',
+ title: `${tc.function.name} result`,
+ description: `${tc.function.name}(${argsShort.substring(0, 60)}) → ${resultShort.substring(0, 60)}`,
+ content: `${tc.function.name}(${argsShort}) → ${resultShort}`,
+ tags: [`agent:${tc.function.name}`],
+ source: convId || 'agent',
+ })
}
// Append tool call + result to messages for next iteration
@@ -487,6 +575,12 @@ export function useAgentChat() {
} catch { /* TTS errors non-critical */ }
finally { voiceState.setSpeaking(false) }
}
+
+ // Auto-extract memories (fire-and-forget, agent mode always qualifies)
+ const memSettings = useMemoryStore.getState().settings
+ if (memSettings.autoExtractEnabled && contentRef.current.trim() && convId) {
+ extractMemories(userContent, contentRef.current, convId).catch(() => {})
+ }
}
}, [])
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index f34a8753..10ec18b4 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -5,9 +5,12 @@ import { useModelStore } from "../stores/modelStore"
import { useSettingsStore } from "../stores/settingsStore"
import { useRAGStore } from "../stores/ragStore"
import { useVoiceStore } from "../stores/voiceStore"
+import { useMemoryStore } from "../stores/memoryStore"
import { retrieveContext } from "../api/rag"
import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from "../api/voice"
+import { getModelMaxTokens } from "../lib/context-compaction"
import { useAgentChat } from "./useAgentChat"
+import { useMemory } from "./useMemory"
import { useAgentModeStore } from "../stores/agentModeStore"
import { getProviderForModel } from "../api/providers"
import type { ChatStreamChunk } from "../api/providers/types"
@@ -22,6 +25,7 @@ export function useChat() {
// Agent mode composition
const agentChat = useAgentChat()
+ const { extractAndSave } = useMemory()
const sendMessage = useCallback(async (content: string) => {
const { activeModel } = useModelStore.getState()
@@ -95,6 +99,17 @@ export function useChat() {
}
}
+ // Memory context injection (context-aware)
+ try {
+ const contextTokens = await getModelMaxTokens(activeModel)
+ const memoryContext = useMemoryStore.getState().getMemoriesForPrompt(content, contextTokens)
+ if (memoryContext) {
+ systemPrompt = (systemPrompt || '') + `\n\n## Remembered Context\n${memoryContext}`
+ }
+ } catch {
+ // Memory injection is non-critical
+ }
+
const messages = [
...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
...conv.messages
@@ -212,6 +227,12 @@ export function useChat() {
} catch { /* TTS errors are non-critical */ }
finally { voiceState.setSpeaking(false) }
}
+
+ // Auto-extract memories (fire-and-forget)
+ const memSettings = useMemoryStore.getState().settings
+ if (memSettings.autoExtractEnabled && memSettings.autoExtractInAllModes && contentRef.current.trim() && convId) {
+ extractAndSave(content, contentRef.current, convId).catch(() => {})
+ }
}
}, [])
diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.ts
new file mode 100644
index 00000000..6713b660
--- /dev/null
+++ b/src/hooks/useMemory.ts
@@ -0,0 +1,75 @@
+/**
+ * useMemory — Hook for memory operations including LLM-based auto-extraction.
+ *
+ * Fires a separate inference call to analyze conversation exchanges and
+ * extract memorable information. Errors are caught silently — extraction
+ * failures must never disrupt the chat experience.
+ */
+
+import { useCallback } from 'react'
+import { useMemoryStore } from '../stores/memoryStore'
+import { useModelStore } from '../stores/modelStore'
+import { getProviderForModel } from '../api/providers'
+import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-extraction'
+
+export function useMemory() {
+ /**
+ * Fire-and-forget extraction: asks the active LLM to analyze a conversation
+ * exchange and save any extracted memories.
+ */
+ const extractAndSave = useCallback(async (
+ userMessage: string,
+ assistantResponse: string,
+ conversationId: string
+ ) => {
+ try {
+ const { activeModel } = useModelStore.getState()
+ if (!activeModel) return
+
+ const memState = useMemoryStore.getState()
+ if (!memState.settings.autoExtractEnabled) return
+
+ // Build summary of existing memories to prevent duplicates
+ const existingSummary = memState.entries
+ .slice(-20)
+ .map(e => `- [${e.type}] ${e.title}`)
+ .join('\n')
+
+ const messages = buildExtractionPrompt(userMessage, assistantResponse, existingSummary)
+
+ // Use active provider for extraction call
+ const { provider, modelId } = getProviderForModel(activeModel)
+
+ // Collect full response via streaming
+ let fullResponse = ''
+ const stream = provider.chatStream(modelId, messages, {
+ temperature: 0.1,
+ maxTokens: 500,
+ })
+
+ for await (const chunk of stream) {
+ if (chunk.content) fullResponse += chunk.content
+ if (chunk.done) break
+ }
+
+ // Parse and save
+ const result = parseExtractionResponse(fullResponse)
+ if (result.shouldSave) {
+ for (const memory of result.memories) {
+ memState.addMemory({
+ type: memory.type,
+ title: memory.title,
+ description: memory.description,
+ content: memory.content,
+ tags: memory.tags,
+ source: conversationId,
+ })
+ }
+ }
+ } catch {
+ // Extraction failures are non-critical — silently swallowed
+ }
+ }, [])
+
+ return { extractAndSave }
+}
diff --git a/src/hooks/useWorkflow.ts b/src/hooks/useWorkflow.ts
new file mode 100644
index 00000000..69c3253e
--- /dev/null
+++ b/src/hooks/useWorkflow.ts
@@ -0,0 +1,135 @@
+/**
+ * useWorkflow — Hook for running agent workflows.
+ *
+ * Manages workflow lifecycle: start, provide input, cancel.
+ * Delegates execution to WorkflowEngine.
+ */
+
+import { useRef, useState, useCallback } from 'react'
+import { WorkflowEngine } from '../lib/workflow-engine'
+import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
+import { useChatStore } from '../stores/chatStore'
+import { v4 as uuid } from 'uuid'
+import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
+
+export function useWorkflow() {
+ const [isRunning, setIsRunning] = useState(false)
+ const [waitingForInput, setWaitingForInput] = useState<string | null>(null)
+ const [currentStepLabel, setCurrentStepLabel] = useState('')
+ const engineRef = useRef<WorkflowEngine | null>(null)
+
+ const startWorkflow = useCallback(async (
+ workflowId: string,
+ variables?: Record<string, string>
+ ) => {
+ const store = useAgentWorkflowStore.getState()
+ const workflow = store.getWorkflow(workflowId)
+ if (!workflow) return
+
+ const chatStore = useChatStore.getState()
+ const convId = chatStore.activeConversationId || chatStore.createConversation(
+ '', // model will be resolved by engine
+ ''
+ )
+
+ const executionId = store.startExecution(workflowId, convId)
+ if (!executionId) return
+
+ setIsRunning(true)
+ setWaitingForInput(null)
+
+ // Add workflow start message to chat
+ chatStore.addMessage(convId, {
+ id: uuid(),
+ role: 'assistant',
+ content: `Running workflow: **${workflow.name}**...`,
+ timestamp: Date.now(),
+ })
+
+ const callbacks: WorkflowEngineCallbacks = {
+ onStepStart: (stepIndex, step) => {
+ setCurrentStepLabel(step.label)
+ store.updateExecution(executionId, { currentStepIndex: stepIndex })
+ },
+ onStepComplete: (stepIndex, result) => {
+ store.addStepResult(executionId, result)
+ },
+ onStepError: (stepIndex, error) => {
+ store.addStepResult(executionId, {
+ stepId: workflow.steps[stepIndex].id,
+ status: 'failed',
+ output: '',
+ startedAt: Date.now(),
+ error,
+ })
+ },
+ onWaitingForInput: (_stepIndex, prompt) => {
+ setWaitingForInput(prompt)
+ store.updateExecution(executionId, { status: 'waiting_input' })
+ },
+ onComplete: (results: StepResult[]) => {
+ store.updateExecution(executionId, {
+ status: 'completed',
+ completedAt: Date.now(),
+ })
+
+ // Add final result to chat
+ const lastOutput = results.filter(r => r.output).pop()
+ if (lastOutput) {
+ chatStore.addMessage(convId, {
+ id: uuid(),
+ role: 'assistant',
+ content: lastOutput.output,
+ timestamp: Date.now(),
+ })
+ }
+ },
+ onError: (error) => {
+ store.updateExecution(executionId, {
+ status: 'failed',
+ completedAt: Date.now(),
+ error,
+ })
+ chatStore.addMessage(convId, {
+ id: uuid(),
+ role: 'assistant',
+ content: `Workflow failed: ${error}`,
+ timestamp: Date.now(),
+ })
+ },
+ }
+
+ const engine = new WorkflowEngine(workflow, convId, callbacks, variables)
+ engineRef.current = engine
+
+ try {
+ await engine.run()
+ } finally {
+ setIsRunning(false)
+ setWaitingForInput(null)
+ setCurrentStepLabel('')
+ engineRef.current = null
+ }
+ }, [])
+
+ const provideInput = useCallback((input: string) => {
+ engineRef.current?.provideUserInput(input)
+ setWaitingForInput(null)
+ }, [])
+
+ const cancelWorkflow = useCallback(() => {
+ engineRef.current?.cancel()
+ setIsRunning(false)
+ setWaitingForInput(null)
+ setCurrentStepLabel('')
+ }, [])
+
+ return {
+ startWorkflow,
+ provideInput,
+ cancelWorkflow,
+ isRunning,
+ waitingForInput,
+ currentStepLabel,
+ }
+}
diff --git a/src/lib/__tests__/memory-e2e.test.ts b/src/lib/__tests__/memory-e2e.test.ts
new file mode 100644
index 00000000..48c6e23b
--- /dev/null
+++ b/src/lib/__tests__/memory-e2e.test.ts
@@ -0,0 +1,418 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useMemoryStore, getMemoryBudget } from '../../stores/memoryStore'
+import { MEMORY_BUDGET_TIERS } from '../../types/agent-mode'
+import type { MemoryType, MemoryFile } from '../../types/agent-mode'
+
+// ── Helper ────────────────────────────────────────────────────
+
+function resetStore() {
+ useMemoryStore.setState({
+ entries: [],
+ settings: {
+ autoExtractEnabled: true,
+ autoExtractInAllModes: true,
+ maxMemoriesInPrompt: 10,
+ maxMemoryChars: 3000,
+ },
+ lastSynced: 0,
+ })
+}
+
+function addMem(type: MemoryType, title: string, content: string, tags: string[] = []) {
+ return useMemoryStore.getState().addMemory({
+ type, title, description: content.substring(0, 120), content, tags, source: 'test',
+ })
+}
+
+// ── Memory Budget Tiers ────────────────────────────────────────
+
+describe('Memory Budget Tiers', () => {
+ it('returns 0 budget for 2K context', () => {
+ const tier = getMemoryBudget(2048)
+ expect(tier.budgetTokens).toBe(0)
+ expect(tier.maxMemories).toBe(0)
+ })
+
+ it('returns 300 budget for 3K context', () => {
+ const tier = getMemoryBudget(3000)
+ expect(tier.budgetTokens).toBe(300)
+ expect(tier.maxMemories).toBe(3)
+ expect(tier.typesAllowed).toEqual(['user', 'feedback'])
+ })
+
+ it('returns 800 budget for 8K context', () => {
+ const tier = getMemoryBudget(8192)
+ expect(tier.budgetTokens).toBe(800)
+ expect(tier.maxMemories).toBe(8)
+ expect(tier.typesAllowed).toBe('all')
+ })
+
+ it('returns 2000 budget for 32K context', () => {
+ const tier = getMemoryBudget(32000)
+ expect(tier.budgetTokens).toBe(2000)
+ expect(tier.maxMemories).toBe(15)
+ })
+
+ it('returns 4000 budget for 200K context', () => {
+ const tier = getMemoryBudget(200000)
+ expect(tier.budgetTokens).toBe(4000)
+ expect(tier.maxMemories).toBe(25)
+ })
+
+ it('tiers are sorted ascending', () => {
+ for (let i = 1; i < MEMORY_BUDGET_TIERS.length; i++) {
+ expect(MEMORY_BUDGET_TIERS[i].maxContext).toBeGreaterThan(MEMORY_BUDGET_TIERS[i - 1].maxContext)
+ }
+ })
+})
+
+// ── Full CRUD Lifecycle ────────────────────────────────────────
+
+describe('Memory CRUD E2E', () => {
+ beforeEach(resetStore)
+
+ it('full lifecycle: add → update → search → export → delete → clear', () => {
+ // Add
+ const id1 = addMem('user', 'Speaks German', 'User primarily communicates in German')
+ const id2 = addMem('feedback', 'No emojis', 'User wants no emojis in UI')
+ const id3 = addMem('project', 'v2.0 launch', 'Currently working on v2.0 launch')
+ const id4 = addMem('reference', 'GitHub repo', 'Main repo at github.com/test/app')
+
+ expect(useMemoryStore.getState().entries).toHaveLength(4)
+ expect(id1).toBeTruthy()
+ expect(id2).toBeTruthy()
+
+ // Update
+ useMemoryStore.getState().updateMemory(id1, { title: 'German speaker', content: 'User speaks German fluently' })
+ const updated = useMemoryStore.getState().entries.find(e => e.id === id1)!
+ expect(updated.title).toBe('German speaker')
+ expect(updated.content).toBe('User speaks German fluently')
+ expect(updated.updatedAt).toBeGreaterThanOrEqual(updated.createdAt)
+
+ // Search
+ const results = useMemoryStore.getState().searchMemories('German')
+ expect(results.length).toBeGreaterThan(0)
+ expect(results[0].id).toBe(id1)
+
+ // Search by type
+ const feedbackOnly = useMemoryStore.getState().searchMemories('', { type: 'feedback' })
+ expect(feedbackOnly.every(e => e.type === 'feedback')).toBe(true)
+
+ // Export markdown
+ const md = useMemoryStore.getState().exportAsMarkdown()
+ expect(md).toContain('# Memory')
+ expect(md).toContain('## User')
+ expect(md).toContain('German speaker')
+ expect(md).toContain('## Feedback')
+ expect(md).toContain('No emojis')
+
+ // Export JSON
+ const json = useMemoryStore.getState().exportAsJSON()
+ const parsed = JSON.parse(json)
+ expect(parsed.entries).toHaveLength(4)
+ expect(parsed.settings).toBeDefined()
+
+ // Delete one
+ useMemoryStore.getState().removeMemory(id3)
+ expect(useMemoryStore.getState().entries).toHaveLength(3)
+
+ // Clear all
+ useMemoryStore.getState().clearAll()
+ expect(useMemoryStore.getState().entries).toHaveLength(0)
+ })
+})
+
+// ── Deduplication ──────────────────────────────────────────────
+
+describe('Memory Deduplication', () => {
+ beforeEach(resetStore)
+
+ it('rejects exact content + type duplicates', () => {
+ addMem('user', 'A', 'Same content')
+ const dup = addMem('user', 'B', 'Same content')
+ expect(dup).toBe('')
+ expect(useMemoryStore.getState().entries).toHaveLength(1)
+ })
+
+ it('allows same content with different type', () => {
+ addMem('user', 'A', 'Same content')
+ addMem('feedback', 'B', 'Same content')
+ expect(useMemoryStore.getState().entries).toHaveLength(2)
+ })
+
+ it('rejects empty / whitespace-only content', () => {
+ expect(addMem('user', 'Empty', '')).toBe('')
+ expect(addMem('user', 'Whitespace', ' ')).toBe('')
+ expect(useMemoryStore.getState().entries).toHaveLength(0)
+ })
+})
+
+// ── Context-Aware Prompt Injection ─────────────────────────────
+
+describe('Context-Aware Prompt Injection', () => {
+ beforeEach(() => {
+ resetStore()
+ // Seed with diverse memories
+ addMem('user', 'Developer role', 'User is a senior TypeScript developer')
+ addMem('feedback', 'Concise style', 'User prefers short, direct answers')
+ addMem('project', 'Building v2.0', 'Working on multi-provider chat app v2.0')
+ addMem('reference', 'Ollama docs', 'API reference at ollama.com/docs')
+ })
+
+ it('returns empty for 2K context (no injection)', () => {
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('developer', 2048)
+ expect(prompt).toBe('')
+ })
+
+ it('returns only user+feedback for 4K context', () => {
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('developer concise', 4000)
+ expect(prompt).toContain('About the user')
+ expect(prompt).toContain('Developer role')
+ // Project and reference types should NOT appear at 4K
+ expect(prompt).not.toContain('Project context')
+ expect(prompt).not.toContain('References')
+ })
+
+ it('returns all types for 8K+ context', () => {
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('developer v2.0 Ollama', 16000)
+ expect(prompt).toContain('About the user')
+ expect(prompt).toContain('Project context')
+ expect(prompt).toContain('References')
+ })
+
+ it('respects max char budget (does not exceed tokens * 4)', () => {
+ // Add many memories
+ for (let i = 0; i < 30; i++) {
+ addMem('user', `Fact ${i}`, `This is a detailed fact number ${i} about the user's preferences and working style`)
+ }
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('fact user preferences', 4000)
+ // 4K tier = 300 tokens = 1200 chars
+ expect(prompt.length).toBeLessThanOrEqual(1200 + 200) // some tolerance
+ })
+
+ it('structures output with section headers', () => {
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('developer v2.0 Ollama concise', 32000)
+ expect(prompt).toMatch(/### About the user/)
+ expect(prompt).toMatch(/### User feedback/)
+ expect(prompt).toMatch(/### Project context/)
+ expect(prompt).toMatch(/### References/)
+ })
+
+ it('returns empty when no entries match query', () => {
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('xylophone', 32000)
+ expect(prompt).toBe('')
+ })
+})
+
+// ── Search Scoring ─────────────────────────────────────────────
+
+describe('Search Scoring', () => {
+ beforeEach(() => {
+ resetStore()
+ addMem('user', 'TypeScript expert', 'User is expert in TypeScript and React')
+ addMem('project', 'React migration', 'Migrating from Vue to React framework')
+ addMem('reference', 'React docs', 'Official React documentation at react.dev')
+ })
+
+ it('title matches score higher than content matches', () => {
+ const results = useMemoryStore.getState().searchMemories('TypeScript')
+ expect(results[0].title).toBe('TypeScript expert')
+ })
+
+ it('multiple word matches score higher', () => {
+ const results = useMemoryStore.getState().searchMemories('React migration')
+ // "React migration" matches both title words → highest score
+ expect(results[0].title).toBe('React migration')
+ })
+
+ it('respects limit option', () => {
+ const results = useMemoryStore.getState().searchMemories('React', { limit: 1 })
+ expect(results).toHaveLength(1)
+ })
+})
+
+// ── Import / Export Round-Trip ──────────────────────────────────
+
+describe('Import/Export Round-Trip', () => {
+ beforeEach(resetStore)
+
+ it('JSON round-trip preserves all data', () => {
+ addMem('user', 'Pref A', 'Content A', ['tag1'])
+ addMem('feedback', 'Pref B', 'Content B', ['tag2'])
+
+ const json = useMemoryStore.getState().exportAsJSON()
+ resetStore()
+ useMemoryStore.getState().importFromJSON(json)
+
+ expect(useMemoryStore.getState().entries).toHaveLength(2)
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
+ expect(useMemoryStore.getState().entries[1].type).toBe('feedback')
+ })
+
+ it('markdown export contains all entries grouped by type', () => {
+ addMem('user', 'User pref', 'Prefers dark mode')
+ addMem('project', 'Sprint goal', 'Complete feature X by Friday')
+
+ const md = useMemoryStore.getState().exportAsMarkdown()
+ expect(md).toContain('## User')
+ expect(md).toContain('User pref')
+ expect(md).toContain('## Project')
+ expect(md).toContain('Sprint goal')
+ })
+
+ it('markdown import parses legacy "Facts" header as user type', () => {
+ const legacyMd = `## Facts\n\n- Old fact from v1\n`
+ useMemoryStore.getState().importFromMarkdown(legacyMd)
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
+ })
+
+ it('markdown import parses legacy "Tool Results" as reference type', () => {
+ const legacyMd = `## Tool Results\n\n- web_search result\n`
+ useMemoryStore.getState().importFromMarkdown(legacyMd)
+ expect(useMemoryStore.getState().entries[0].type).toBe('reference')
+ })
+
+ it('handles malformed JSON import gracefully', () => {
+ useMemoryStore.getState().importFromJSON('not json')
+ expect(useMemoryStore.getState().entries).toHaveLength(0)
+ })
+
+ it('handles empty markdown import gracefully', () => {
+ useMemoryStore.getState().importFromMarkdown('')
+ expect(useMemoryStore.getState().entries).toHaveLength(0)
+ })
+})
+
+// ── Settings ───────────────────────────────────────────────────
+
+describe('Memory Settings', () => {
+ beforeEach(resetStore)
+
+ it('defaults are correct', () => {
+ const s = useMemoryStore.getState().settings
+ expect(s.autoExtractEnabled).toBe(true)
+ expect(s.autoExtractInAllModes).toBe(true)
+ expect(s.maxMemoriesInPrompt).toBe(10)
+ expect(s.maxMemoryChars).toBe(3000)
+ })
+
+ it('partial updates work', () => {
+ useMemoryStore.getState().updateMemorySettings({ autoExtractEnabled: false })
+ expect(useMemoryStore.getState().settings.autoExtractEnabled).toBe(false)
+ expect(useMemoryStore.getState().settings.autoExtractInAllModes).toBe(true) // unchanged
+ })
+
+ it('multiple updates accumulate', () => {
+ useMemoryStore.getState().updateMemorySettings({ autoExtractEnabled: true })
+ useMemoryStore.getState().updateMemorySettings({ maxMemoriesInPrompt: 20 })
+ const s = useMemoryStore.getState().settings
+ expect(s.autoExtractEnabled).toBe(true)
+ expect(s.maxMemoriesInPrompt).toBe(20)
+ })
+})
+
+// ── Legacy Compat ──────────────────────────────────────────────
+
+describe('Legacy addEntry Compat', () => {
+ beforeEach(resetStore)
+
+ it('fact → user type', () => {
+ useMemoryStore.getState().addEntry('fact', 'The sky is blue')
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
+ })
+
+ it('tool_result → reference type', () => {
+ useMemoryStore.getState().addEntry('tool_result', 'Search found 5 results')
+ expect(useMemoryStore.getState().entries[0].type).toBe('reference')
+ })
+
+ it('decision → project type', () => {
+ useMemoryStore.getState().addEntry('decision', 'Use Zustand')
+ expect(useMemoryStore.getState().entries[0].type).toBe('project')
+ })
+
+ it('context → project type', () => {
+ useMemoryStore.getState().addEntry('context', 'Running on Windows')
+ expect(useMemoryStore.getState().entries[0].type).toBe('project')
+ })
+
+ it('source stored as tag', () => {
+ useMemoryStore.getState().addEntry('fact', 'Test', 'agent:web_search')
+ expect(useMemoryStore.getState().entries[0].tags).toContain('agent:web_search')
+ })
+
+ it('legacy getMemoryForPrompt still works', () => {
+ useMemoryStore.getState().addEntry('fact', 'Rememberable fact about TypeScript')
+ const prompt = useMemoryStore.getState().getMemoryForPrompt('TypeScript')
+ expect(prompt).toContain('TypeScript')
+ })
+})
+
+// ── v1 → v2 Migration ─────────────────────────────────────────
+
+describe('v1 → v2 Migration', () => {
+ it('handles already-migrated state (has type field)', () => {
+ // Simulate setting state with already-migrated entries
+ useMemoryStore.setState({
+ entries: [{
+ id: 'test-1', type: 'user', title: 'Test', description: 'Test',
+ content: 'Already migrated', tags: [], createdAt: 1000, updatedAt: 1000, source: 'test',
+ }],
+ settings: {
+ autoExtractEnabled: false,
+ autoExtractInAllModes: false,
+ maxMemoriesInPrompt: 10,
+ maxMemoryChars: 3000,
+ },
+ lastSynced: 0,
+ })
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
+ })
+})
+
+// ── Stress / Edge Cases ────────────────────────────────────────
+
+describe('Memory Edge Cases', () => {
+ beforeEach(resetStore)
+
+ it('handles 100+ entries without issues', () => {
+ for (let i = 0; i < 100; i++) {
+ addMem('user', `Entry ${i}`, `Content for entry ${i} with some keywords`)
+ }
+ expect(useMemoryStore.getState().entries).toHaveLength(100)
+
+ // Search still works
+ const results = useMemoryStore.getState().searchMemories('Entry keywords')
+ expect(results.length).toBeGreaterThan(0)
+ expect(results.length).toBeLessThanOrEqual(20) // default limit
+
+ // Prompt injection respects budget
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('Entry keywords', 8192)
+ expect(prompt.length).toBeGreaterThan(0)
+ expect(prompt.length).toBeLessThanOrEqual(3200 + 200) // 800 tokens * 4 chars
+ })
+
+ it('handles special characters in content', () => {
+ addMem('user', 'Special chars', 'Content with "quotes", <tags>, and {braces}')
+ const results = useMemoryStore.getState().searchMemories('quotes tags braces')
+ expect(results).toHaveLength(1)
+ })
+
+ it('handles unicode content', () => {
+ addMem('user', 'Deutsch', 'Benutzer spricht Deutsch')
+ const results = useMemoryStore.getState().searchMemories('Deutsch')
+ expect(results).toHaveLength(1)
+ })
+
+ it('handles newlines in content', () => {
+ addMem('project', 'Multi-line', 'Line 1\nLine 2\nLine 3')
+ expect(useMemoryStore.getState().entries[0].content).toContain('\n')
+ // Prompt injection should strip newlines
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('Line', 16000)
+ // Each entry line should not contain raw newlines
+ const lines = prompt.split('\n').filter(l => l.startsWith('- '))
+ for (const line of lines) {
+ expect(line).not.toMatch(/\n.*\n/) // no internal newlines in single entry lines
+ }
+ })
+})
diff --git a/src/lib/__tests__/memory-extraction.test.ts b/src/lib/__tests__/memory-extraction.test.ts
new file mode 100644
index 00000000..f0e9e518
--- /dev/null
+++ b/src/lib/__tests__/memory-extraction.test.ts
@@ -0,0 +1,150 @@
+import { describe, it, expect } from 'vitest'
+import { buildExtractionPrompt, parseExtractionResponse } from '../memory-extraction'
+
+// ── buildExtractionPrompt ──────────────────────────────────────
+
+describe('buildExtractionPrompt', () => {
+ it('returns system + user message array', () => {
+ const messages = buildExtractionPrompt('Hello', 'Hi there', '')
+ expect(messages).toHaveLength(2)
+ expect(messages[0].role).toBe('system')
+ expect(messages[1].role).toBe('user')
+ })
+
+ it('system prompt contains all 4 memory types', () => {
+ const messages = buildExtractionPrompt('test', 'test', '')
+ const sys = messages[0].content
+ expect(sys).toContain('user')
+ expect(sys).toContain('feedback')
+ expect(sys).toContain('project')
+ expect(sys).toContain('reference')
+ })
+
+ it('includes existing memories summary in system prompt', () => {
+ const existing = '- [user] Prefers dark mode\n- [project] Working on v2.0'
+ const messages = buildExtractionPrompt('test', 'test', existing)
+ expect(messages[0].content).toContain('Prefers dark mode')
+ expect(messages[0].content).toContain('Working on v2.0')
+ })
+
+ it('shows "None yet." when no existing memories', () => {
+ const messages = buildExtractionPrompt('test', 'test', '')
+ expect(messages[0].content).toContain('None yet.')
+ })
+
+ it('user prompt contains user message and assistant response', () => {
+ const messages = buildExtractionPrompt('What is React?', 'React is a JavaScript library...', '')
+ const user = messages[1].content
+ expect(user).toContain('What is React?')
+ expect(user).toContain('React is a JavaScript library')
+ })
+
+ it('truncates long messages to 500 chars', () => {
+ const longMsg = 'A'.repeat(1000)
+ const messages = buildExtractionPrompt(longMsg, longMsg, '')
+ const user = messages[1].content
+ // Original was 1000 chars, should be truncated
+ expect(user.length).toBeLessThan(1500)
+ })
+})
+
+// ── parseExtractionResponse ────────────────────────────────────
+
+describe('parseExtractionResponse', () => {
+ it('parses valid JSON with shouldSave: true', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "user", "title": "Dev role", "description": "User is a developer", "content": "The user is a software developer", "tags": ["role"]}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.shouldSave).toBe(true)
+ expect(result.memories).toHaveLength(1)
+ expect(result.memories[0].type).toBe('user')
+ expect(result.memories[0].title).toBe('Dev role')
+ expect(result.memories[0].content).toBe('The user is a software developer')
+ expect(result.memories[0].tags).toEqual(['role'])
+ })
+
+ it('parses shouldSave: false', () => {
+ const result = parseExtractionResponse('{"shouldSave": false, "memories": []}')
+ expect(result.shouldSave).toBe(false)
+ expect(result.memories).toHaveLength(0)
+ })
+
+ it('handles JSON wrapped in markdown code block', () => {
+ const response = 'Here is the analysis:\n```json\n{"shouldSave": true, "memories": [{"type": "feedback", "title": "No emojis", "content": "User does not want emojis", "tags": []}]}\n```'
+ const result = parseExtractionResponse(response)
+ expect(result.shouldSave).toBe(true)
+ expect(result.memories[0].type).toBe('feedback')
+ })
+
+ it('handles JSON with preamble text', () => {
+ const response = 'After analysis, I found:\n{"shouldSave": true, "memories": [{"type": "project", "title": "v2 migration", "content": "Working on v2", "tags": ["migration"]}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.shouldSave).toBe(true)
+ expect(result.memories[0].type).toBe('project')
+ })
+
+ it('returns fallback for garbage input', () => {
+ expect(parseExtractionResponse('this is not json at all')).toEqual({ shouldSave: false, memories: [] })
+ expect(parseExtractionResponse('')).toEqual({ shouldSave: false, memories: [] })
+ expect(parseExtractionResponse('null')).toEqual({ shouldSave: false, memories: [] })
+ })
+
+ it('returns fallback for invalid JSON structure', () => {
+ expect(parseExtractionResponse('{"foo": "bar"}')).toEqual({ shouldSave: false, memories: [] })
+ expect(parseExtractionResponse('{"shouldSave": "yes"}')).toEqual({ shouldSave: false, memories: [] })
+ })
+
+ it('filters out memories with invalid type', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "invalid_type", "title": "Bad", "content": "Bad type"}, {"type": "user", "title": "Good", "content": "Good type", "tags": []}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.memories).toHaveLength(1)
+ expect(result.memories[0].type).toBe('user')
+ })
+
+ it('filters out memories without title or content', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "user", "title": "", "content": "No title"}, {"type": "user", "title": "No content", "content": ""}, {"type": "user", "title": "Valid", "content": "Valid content", "tags": []}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.memories).toHaveLength(1)
+ expect(result.memories[0].title).toBe('Valid')
+ })
+
+ it('truncates long titles to 60 chars', () => {
+ const response = `{"shouldSave": true, "memories": [{"type": "user", "title": "${'A'.repeat(100)}", "content": "Test", "tags": []}]}`
+ const result = parseExtractionResponse(response)
+ expect(result.memories[0].title.length).toBeLessThanOrEqual(60)
+ })
+
+ it('truncates description to 120 chars', () => {
+ const response = `{"shouldSave": true, "memories": [{"type": "user", "title": "Test", "description": "${'B'.repeat(200)}", "content": "Test", "tags": []}]}`
+ const result = parseExtractionResponse(response)
+ expect(result.memories[0].description.length).toBeLessThanOrEqual(120)
+ })
+
+ it('uses content as description fallback', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "user", "title": "Test", "content": "Short content here", "tags": []}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.memories[0].description).toBe('Short content here')
+ })
+
+ it('handles missing tags array gracefully', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "user", "title": "Test", "content": "Content"}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.memories[0].tags).toEqual([])
+ })
+
+ it('filters non-string tags', () => {
+ const response = '{"shouldSave": true, "memories": [{"type": "user", "title": "Test", "content": "Content", "tags": ["valid", 123, null, "also_valid"]}]}'
+ const result = parseExtractionResponse(response)
+ expect(result.memories[0].tags).toEqual(['valid', 'also_valid'])
+ })
+
+ it('handles multiple valid memories', () => {
+ const response = `{"shouldSave": true, "memories": [
+ {"type": "user", "title": "Role", "content": "Developer", "tags": []},
+ {"type": "feedback", "title": "Style", "content": "Prefers concise", "tags": []},
+ {"type": "project", "title": "Goal", "content": "Building v2", "tags": []}
+ ]}`
+ const result = parseExtractionResponse(response)
+ expect(result.memories).toHaveLength(3)
+ expect(result.memories.map(m => m.type)).toEqual(['user', 'feedback', 'project'])
+ })
+})
diff --git a/src/lib/__tests__/workflow-e2e.test.ts b/src/lib/__tests__/workflow-e2e.test.ts
new file mode 100644
index 00000000..954f5b45
--- /dev/null
+++ b/src/lib/__tests__/workflow-e2e.test.ts
@@ -0,0 +1,314 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { BUILT_IN_WORKFLOWS } from '../built-in-workflows'
+import { useMemoryStore } from '../../stores/memoryStore'
+import type { AgentWorkflow, WorkflowStep } from '../../types/agent-workflows'
+
+// ── Helpers ───────────────────────────────────────────────────
+
+function resetStores() {
+ useAgentWorkflowStore.setState({
+ workflows: [...BUILT_IN_WORKFLOWS],
+ executions: [],
+ activeExecutionId: null,
+ })
+ useMemoryStore.setState({
+ entries: [],
+ settings: { autoExtractEnabled: true, autoExtractInAllModes: true, maxMemoriesInPrompt: 10, maxMemoryChars: 3000 },
+ lastSynced: 0,
+ })
+}
+
+// ── Built-in Workflows ─────────────────────────────────────────
+
+describe('Built-in Workflows', () => {
+ it('has exactly 3 built-in workflows', () => {
+ expect(BUILT_IN_WORKFLOWS).toHaveLength(3)
+ })
+
+ it('Research Topic has correct structure', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Research Topic')!
+ expect(wf).toBeDefined()
+ expect(wf.isBuiltIn).toBe(true)
+ expect(wf.icon).toBe('Search')
+ expect(wf.steps.length).toBe(6)
+ expect(wf.steps[0].type).toBe('user_input')
+ expect(wf.steps[1].type).toBe('tool')
+ expect(wf.steps[1].toolName).toBe('web_search')
+ expect(wf.steps[2].type).toBe('prompt')
+ expect(wf.steps[3].type).toBe('tool')
+ expect(wf.steps[3].toolName).toBe('web_fetch')
+ expect(wf.steps[4].type).toBe('prompt')
+ expect(wf.steps[5].type).toBe('memory_save')
+ expect(wf.steps[5].memorySave?.type).toBe('reference')
+ })
+
+ it('Summarize URL has correct structure', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Summarize URL')!
+ expect(wf).toBeDefined()
+ expect(wf.steps.length).toBe(3)
+ expect(wf.steps[0].type).toBe('user_input')
+ expect(wf.steps[1].type).toBe('tool')
+ expect(wf.steps[1].toolName).toBe('web_fetch')
+ expect(wf.steps[2].type).toBe('prompt')
+ })
+
+ it('Code Review has correct structure', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Code Review')!
+ expect(wf).toBeDefined()
+ expect(wf.steps.length).toBe(3)
+ expect(wf.steps[0].type).toBe('user_input')
+ expect(wf.steps[1].type).toBe('tool')
+ expect(wf.steps[1].toolName).toBe('file_read')
+ expect(wf.steps[2].type).toBe('prompt')
+ })
+
+ it('all built-in workflow steps have IDs and labels', () => {
+ for (const wf of BUILT_IN_WORKFLOWS) {
+ for (const step of wf.steps) {
+ expect(step.id).toBeTruthy()
+ expect(step.label).toBeTruthy()
+ expect(step.type).toBeTruthy()
+ }
+ }
+ })
+
+ it('all built-in workflows have unique IDs', () => {
+ const ids = BUILT_IN_WORKFLOWS.map(w => w.id)
+ expect(new Set(ids).size).toBe(ids.length)
+ })
+
+ it('tool steps reference valid tools from registry', () => {
+ const validTools = ['web_search', 'web_fetch', 'file_read', 'file_write', 'code_execute', 'image_generate', 'run_workflow']
+ for (const wf of BUILT_IN_WORKFLOWS) {
+ for (const step of wf.steps) {
+ if (step.type === 'tool' && step.toolName) {
+ expect(validTools).toContain(step.toolName)
+ }
+ }
+ }
+ })
+})
+
+// ── Workflow Store CRUD ────────────────────────────────────────
+
+describe('Workflow Store CRUD', () => {
+ beforeEach(resetStores)
+
+ it('starts with built-in workflows', () => {
+ const { workflows } = useAgentWorkflowStore.getState()
+ expect(workflows.length).toBeGreaterThanOrEqual(3)
+ expect(workflows.filter(w => w.isBuiltIn)).toHaveLength(3)
+ })
+
+ it('addWorkflow creates a custom workflow', () => {
+ const id = useAgentWorkflowStore.getState().addWorkflow({
+ name: 'Custom Flow',
+ description: 'A test workflow',
+ icon: 'Zap',
+ steps: [{ id: 'step-1', type: 'user_input', label: 'Input', userInputPrompt: 'Enter something' }],
+ variables: {},
+ isBuiltIn: false,
+ })
+ expect(id).toBeTruthy()
+ const wf = useAgentWorkflowStore.getState().getWorkflow(id)
+ expect(wf).toBeDefined()
+ expect(wf!.name).toBe('Custom Flow')
+ expect(wf!.isBuiltIn).toBe(false)
+ expect(wf!.createdAt).toBeGreaterThan(0)
+ })
+
+ it('updateWorkflow modifies name and description', () => {
+ const id = useAgentWorkflowStore.getState().addWorkflow({
+ name: 'Original', description: 'Orig desc', icon: 'Zap', steps: [], variables: {}, isBuiltIn: false,
+ })
+ useAgentWorkflowStore.getState().updateWorkflow(id, { name: 'Updated', description: 'New desc' })
+ const wf = useAgentWorkflowStore.getState().getWorkflow(id)!
+ expect(wf.name).toBe('Updated')
+ expect(wf.description).toBe('New desc')
+ expect(wf.updatedAt).toBeGreaterThanOrEqual(wf.createdAt)
+ })
+
+ it('removeWorkflow deletes custom but not built-in', () => {
+ const customId = useAgentWorkflowStore.getState().addWorkflow({
+ name: 'Deletable', description: '', icon: 'Zap', steps: [], variables: {}, isBuiltIn: false,
+ })
+ const builtInId = BUILT_IN_WORKFLOWS[0].id
+
+ // Delete custom
+ useAgentWorkflowStore.getState().removeWorkflow(customId)
+ expect(useAgentWorkflowStore.getState().getWorkflow(customId)).toBeUndefined()
+
+ // Try to delete built-in — should be protected
+ useAgentWorkflowStore.getState().removeWorkflow(builtInId)
+ expect(useAgentWorkflowStore.getState().getWorkflow(builtInId)).toBeDefined()
+ })
+
+ it('duplicateWorkflow creates a copy', () => {
+ const builtInId = BUILT_IN_WORKFLOWS[0].id
+ const copyId = useAgentWorkflowStore.getState().duplicateWorkflow(builtInId)
+ expect(copyId).toBeTruthy()
+
+ const copy = useAgentWorkflowStore.getState().getWorkflow(copyId!)!
+ expect(copy.name).toContain('(copy)')
+ expect(copy.isBuiltIn).toBe(false)
+ expect(copy.id).not.toBe(builtInId)
+ expect(copy.steps.length).toBe(BUILT_IN_WORKFLOWS[0].steps.length)
+ })
+
+ it('duplicateWorkflow returns null for non-existent ID', () => {
+ const result = useAgentWorkflowStore.getState().duplicateWorkflow('non-existent')
+ expect(result).toBeNull()
+ })
+
+ it('getWorkflow returns undefined for non-existent ID', () => {
+ expect(useAgentWorkflowStore.getState().getWorkflow('non-existent')).toBeUndefined()
+ })
+})
+
+// ── Workflow Execution Store ───────────────────────────────────
+
+describe('Workflow Execution Store', () => {
+ beforeEach(resetStores)
+
+ it('startExecution creates execution record', () => {
+ const builtInId = BUILT_IN_WORKFLOWS[0].id
+ const execId = useAgentWorkflowStore.getState().startExecution(builtInId, 'conv-123')
+
+ expect(execId).toBeTruthy()
+ const { executions, activeExecutionId } = useAgentWorkflowStore.getState()
+ expect(executions).toHaveLength(1)
+ expect(executions[0].workflowId).toBe(builtInId)
+ expect(executions[0].status).toBe('running')
+ expect(executions[0].conversationId).toBe('conv-123')
+ expect(activeExecutionId).toBe(execId)
+ })
+
+ it('startExecution returns null for non-existent workflow', () => {
+ const result = useAgentWorkflowStore.getState().startExecution('non-existent')
+ expect(result).toBeNull()
+ })
+
+ it('updateExecution modifies execution fields', () => {
+ const execId = useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[0].id)!
+ useAgentWorkflowStore.getState().updateExecution(execId, { status: 'waiting_input' })
+ expect(useAgentWorkflowStore.getState().executions[0].status).toBe('waiting_input')
+ })
+
+ it('addStepResult appends result and increments step index', () => {
+ const execId = useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[0].id)!
+ useAgentWorkflowStore.getState().addStepResult(execId, {
+ stepId: 'step-1', status: 'completed', output: 'Step 1 done', startedAt: Date.now(), completedAt: Date.now(),
+ })
+
+ const exec = useAgentWorkflowStore.getState().executions[0]
+ expect(exec.stepResults).toHaveLength(1)
+ expect(exec.currentStepIndex).toBe(1)
+ })
+
+ it('cancelExecution sets status and clears active', () => {
+ const execId = useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[0].id)!
+ useAgentWorkflowStore.getState().cancelExecution(execId)
+
+ const exec = useAgentWorkflowStore.getState().executions[0]
+ expect(exec.status).toBe('cancelled')
+ expect(exec.completedAt).toBeGreaterThan(0)
+ expect(useAgentWorkflowStore.getState().activeExecutionId).toBeNull()
+ })
+
+ it('caps execution history at 50', () => {
+ for (let i = 0; i < 55; i++) {
+ useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[0].id, `conv-${i}`)
+ }
+ expect(useAgentWorkflowStore.getState().executions.length).toBeLessThanOrEqual(50)
+ })
+
+ it('clearExecutionHistory removes all', () => {
+ useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[0].id)
+ useAgentWorkflowStore.getState().startExecution(BUILT_IN_WORKFLOWS[1].id)
+ useAgentWorkflowStore.getState().clearExecutionHistory()
+ expect(useAgentWorkflowStore.getState().executions).toHaveLength(0)
+ expect(useAgentWorkflowStore.getState().activeExecutionId).toBeNull()
+ })
+})
+
+// ── Variable Interpolation (indirect via built-in workflow templates) ──
+
+describe('Workflow Template Variables', () => {
+ it('Research Topic uses {{user_input}} in search args', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Research Topic')!
+ const searchStep = wf.steps.find(s => s.toolName === 'web_search')!
+ expect(searchStep.toolArgTemplates?.query).toBe('{{user_input}}')
+ })
+
+ it('Research Topic uses {{last_output}} in fetch args', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Research Topic')!
+ const fetchStep = wf.steps.find(s => s.toolName === 'web_fetch')!
+ expect(fetchStep.toolArgTemplates?.url).toBe('{{last_output}}')
+ })
+
+ it('memory_save step uses {{user_input}} and {{last_output}} in templates', () => {
+ const wf = BUILT_IN_WORKFLOWS.find(w => w.name === 'Research Topic')!
+ const saveStep = wf.steps.find(s => s.type === 'memory_save')!
+ expect(saveStep.memorySave?.titleTemplate).toContain('{{user_input}}')
+ expect(saveStep.memorySave?.contentTemplate).toContain('{{last_output}}')
+ })
+})
+
+// ── Full Workflow Lifecycle E2E ─────────────────────────────────
+
+describe('Workflow Lifecycle E2E', () => {
+ beforeEach(resetStores)
+
+ it('custom workflow: create → edit → duplicate → run → delete', () => {
+ const store = useAgentWorkflowStore.getState()
+
+ // Create
+ const id = store.addWorkflow({
+ name: 'My Workflow',
+ description: 'Test flow',
+ icon: 'Zap',
+ steps: [
+ { id: 's1', type: 'user_input', label: 'Ask', userInputPrompt: 'What?' },
+ { id: 's2', type: 'memory_save', label: 'Save', memorySave: { type: 'project', titleTemplate: 'Result', contentTemplate: '{{last_output}}' } },
+ ],
+ variables: {},
+ isBuiltIn: false,
+ })
+
+ // Edit
+ useAgentWorkflowStore.getState().updateWorkflow(id, {
+ name: 'My Workflow v2',
+ steps: [
+ { id: 's1', type: 'user_input', label: 'Ask updated', userInputPrompt: 'What now?' },
+ ],
+ })
+ expect(useAgentWorkflowStore.getState().getWorkflow(id)!.name).toBe('My Workflow v2')
+ expect(useAgentWorkflowStore.getState().getWorkflow(id)!.steps).toHaveLength(1)
+
+ // Duplicate
+ const copyId = useAgentWorkflowStore.getState().duplicateWorkflow(id)!
+ expect(useAgentWorkflowStore.getState().getWorkflow(copyId)!.name).toBe('My Workflow v2 (copy)')
+
+ // Start execution
+ const execId = useAgentWorkflowStore.getState().startExecution(id)!
+ expect(useAgentWorkflowStore.getState().executions[0].status).toBe('running')
+
+ // Simulate step completion
+ useAgentWorkflowStore.getState().addStepResult(execId, {
+ stepId: 's1', status: 'completed', output: 'user typed something', startedAt: Date.now(),
+ })
+ expect(useAgentWorkflowStore.getState().executions[0].stepResults).toHaveLength(1)
+
+ // Complete execution
+ useAgentWorkflowStore.getState().updateExecution(execId, { status: 'completed', completedAt: Date.now() })
+ expect(useAgentWorkflowStore.getState().executions[0].status).toBe('completed')
+
+ // Delete custom
+ useAgentWorkflowStore.getState().removeWorkflow(id)
+ expect(useAgentWorkflowStore.getState().getWorkflow(id)).toBeUndefined()
+
+ // Copy still exists
+ expect(useAgentWorkflowStore.getState().getWorkflow(copyId)).toBeDefined()
+ })
+})
diff --git a/src/lib/agent-strategy.ts b/src/lib/agent-strategy.ts
new file mode 100644
index 00000000..afdf8ab5
--- /dev/null
+++ b/src/lib/agent-strategy.ts
@@ -0,0 +1,60 @@
+/**
+ * Agent Strategy Resolution — Shared utility for determining tool calling strategy.
+ *
+ * Extracted from useAgentChat.ts so both the agent chat and workflow engine
+ * can reuse the same logic.
+ */
+
+import { getProviderIdFromModel, getProviderForModel } from '../api/providers'
+import { getToolCallingStrategy, type ToolCallingStrategy } from './model-compatibility'
+import { agentVariantExists, createAgentVariant, getAgentModelName, canFixModel } from '../api/model-template-fix'
+
+export interface ResolvedStrategy {
+ strategy: ToolCallingStrategy
+ modelToUse: string
+ providerId: string
+ provider: ReturnType<typeof getProviderForModel>['provider']
+}
+
+/**
+ * Resolve the tool calling strategy for a given model.
+ * Handles cloud providers (always native), Ollama native models,
+ * template_fix (creates agent variant), and hermes_xml fallback.
+ */
+export async function resolveToolCallingStrategy(modelName: string): Promise<ResolvedStrategy> {
+ const providerId = getProviderIdFromModel(modelName)
+ const { provider, modelId } = getProviderForModel(modelName)
+
+ let modelToUse = modelId
+ let strategy: ToolCallingStrategy
+
+ if (providerId === 'openai' || providerId === 'anthropic') {
+ strategy = 'native'
+ } else {
+ strategy = getToolCallingStrategy(modelId)
+
+ if (strategy === 'template_fix') {
+ const agentName = getAgentModelName(modelId)
+ const exists = await agentVariantExists(modelId)
+
+ if (exists) {
+ modelToUse = agentName
+ strategy = 'native'
+ } else {
+ const { fixable } = await canFixModel(modelId)
+ if (fixable) {
+ try {
+ modelToUse = await createAgentVariant(modelId)
+ strategy = 'native'
+ } catch {
+ strategy = 'hermes_xml'
+ }
+ } else {
+ strategy = 'hermes_xml'
+ }
+ }
+ }
+ }
+
+ return { strategy, modelToUse, providerId, provider }
+}
diff --git a/src/lib/built-in-workflows.ts b/src/lib/built-in-workflows.ts
new file mode 100644
index 00000000..95d3de40
--- /dev/null
+++ b/src/lib/built-in-workflows.ts
@@ -0,0 +1,116 @@
+/**
+ * Built-in Agent Workflows — Pre-configured workflow templates.
+ */
+
+import { v4 as uuid } from 'uuid'
+import type { AgentWorkflow, WorkflowStep } from '../types/agent-workflows'
+
+function step(type: WorkflowStep['type'], label: string, overrides: Partial<WorkflowStep> = {}): WorkflowStep {
+ return { id: uuid(), type, label, ...overrides }
+}
+
+// ── Research Topic ────────────────────────────────────────────
+
+const researchTopic: AgentWorkflow = {
+ id: 'builtin-research-topic',
+ name: 'Research Topic',
+ description: 'Search the web, fetch the best result, and summarize it',
+ icon: 'Search',
+ steps: [
+ step('user_input', 'Enter topic', { userInputPrompt: 'What topic should I research?' }),
+ step('tool', 'Search the web', {
+ toolName: 'web_search',
+ toolArgTemplates: { query: '{{user_input}}' },
+ }),
+ step('prompt', 'Pick best URL', {
+ prompt: 'Based on the search results below, pick the single best URL to read for comprehensive information about "{{user_input}}".\n\nSearch results:\n{{last_output}}\n\nRespond with ONLY the URL, nothing else.',
+ allowedTools: [],
+ }),
+ step('tool', 'Fetch page content', {
+ toolName: 'web_fetch',
+ toolArgTemplates: { url: '{{last_output}}' },
+ }),
+ step('prompt', 'Summarize findings', {
+ prompt: 'Summarize the following content about "{{user_input}}" in a clear, structured way. Use bullet points for key facts.\n\nContent:\n{{last_output}}',
+ allowedTools: [],
+ }),
+ step('memory_save', 'Save to memory', {
+ memorySave: {
+ type: 'reference',
+ titleTemplate: 'Research: {{user_input}}',
+ contentTemplate: '{{last_output}}',
+ tags: ['research', 'workflow'],
+ },
+ }),
+ ],
+ variables: {},
+ isBuiltIn: true,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+}
+
+// ── Summarize URL ─────────────────────────────────────────────
+
+const summarizeUrl: AgentWorkflow = {
+ id: 'builtin-summarize-url',
+ name: 'Summarize URL',
+ description: 'Fetch a URL and generate a concise summary',
+ icon: 'FileText',
+ steps: [
+ step('user_input', 'Enter URL', { userInputPrompt: 'Enter the URL to summarize:' }),
+ step('tool', 'Fetch page', {
+ toolName: 'web_fetch',
+ toolArgTemplates: { url: '{{user_input}}' },
+ }),
+ step('prompt', 'Generate summary', {
+ prompt: 'Provide a concise summary of this page content. Include key points as bullet points.\n\nURL: {{user_input}}\n\nContent:\n{{last_output}}',
+ allowedTools: [],
+ }),
+ ],
+ variables: {},
+ isBuiltIn: true,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+}
+
+// ── Code Review ───────────────────────────────────────────────
+
+const codeReview: AgentWorkflow = {
+ id: 'builtin-code-review',
+ name: 'Code Review',
+ description: 'Read a file and provide a code review',
+ icon: 'Code',
+ steps: [
+ step('user_input', 'Enter file path', { userInputPrompt: 'Enter the file path to review:' }),
+ step('tool', 'Read file', {
+ toolName: 'file_read',
+ toolArgTemplates: { path: '{{user_input}}' },
+ }),
+ step('prompt', 'Review code', {
+ prompt: `Review the following code from "{{user_input}}". Check for:
+- Bugs and potential errors
+- Security issues
+- Performance concerns
+- Code style and readability
+- Suggestions for improvement
+
+Code:
+{{last_output}}
+
+Provide a structured review with severity levels (critical/warning/info).`,
+ allowedTools: [],
+ }),
+ ],
+ variables: {},
+ isBuiltIn: true,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+}
+
+// ── Export ─────────────────────────────────────────────────────
+
+export const BUILT_IN_WORKFLOWS: AgentWorkflow[] = [
+ researchTopic,
+ summarizeUrl,
+ codeReview,
+]
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 3ed7c19f..0b39381d 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -3,6 +3,7 @@ import type { Persona, Settings } from '../types/settings'
// Feature flags — flip to true when ready to ship
export const FEATURE_FLAGS = {
AGENT_MODE: true,
+ AGENT_WORKFLOWS: true,
} as const
export const DEFAULT_SETTINGS: Settings = {
diff --git a/src/lib/memory-extraction.ts b/src/lib/memory-extraction.ts
new file mode 100644
index 00000000..f3c423cb
--- /dev/null
+++ b/src/lib/memory-extraction.ts
@@ -0,0 +1,122 @@
+/**
+ * Memory Extraction — LLM-based auto-extraction of memorable information.
+ *
+ * After each conversation turn, optionally asks the LLM to analyze the exchange
+ * and extract information worth remembering across conversations.
+ *
+ * Categories (Claude Code-inspired):
+ * - user: User preferences, role, knowledge level
+ * - feedback: Corrections and confirmations ("don't do X", "yes, keep doing Y")
+ * - project: Ongoing work context, goals, decisions
+ * - reference: Pointers to external resources, tools, URLs
+ */
+
+import type { MemoryType } from '../types/agent-mode'
+
+export interface ExtractedMemory {
+ type: MemoryType
+ title: string
+ description: string
+ content: string
+ tags: string[]
+}
+
+export interface ExtractionResult {
+ shouldSave: boolean
+ memories: ExtractedMemory[]
+}
+
+/**
+ * Build the prompt that instructs the LLM to analyze a conversation exchange
+ * and decide what (if anything) should be remembered.
+ */
+export function buildExtractionPrompt(
+ userMessage: string,
+ assistantResponse: string,
+ existingMemoriesSummary: string
+): Array<{ role: 'system' | 'user'; content: string }> {
+ const systemPrompt = `You are a memory extraction system. Analyze the conversation exchange below and decide if anything should be remembered for future conversations.
+
+## Memory Types
+- **user**: User preferences, role, expertise, knowledge level, how they like to work
+- **feedback**: Corrections ("don't do X") or confirmations ("yes, keep doing Y")
+- **project**: Ongoing work context, goals, decisions, deadlines
+- **reference**: External resources, tools, URLs, documentation pointers
+
+## Rules
+- Only extract genuinely useful cross-conversation information
+- Do NOT save: trivial greetings, one-off questions, code snippets, debugging sessions
+- Do NOT duplicate existing memories (listed below)
+- Keep titles under 60 characters, descriptions under 120 characters
+- Content should be concise but complete (1-3 sentences)
+
+## Existing Memories
+${existingMemoriesSummary || 'None yet.'}
+
+## Response Format
+Respond with ONLY valid JSON (no markdown, no explanation):
+{"shouldSave": true/false, "memories": [{"type": "user|feedback|project|reference", "title": "...", "description": "...", "content": "...", "tags": ["..."]}]}`
+
+ const userPrompt = `## User said:
+${userMessage.substring(0, 500)}
+
+## Assistant replied:
+${assistantResponse.substring(0, 500)}
+
+Analyze this exchange. What (if anything) should be remembered?`
+
+ return [
+ { role: 'system', content: systemPrompt },
+ { role: 'user', content: userPrompt },
+ ]
+}
+
+/**
+ * Parse the LLM's extraction response. Handles models that wrap JSON in
+ * markdown code blocks or add preamble text.
+ */
+export function parseExtractionResponse(response: string): ExtractionResult {
+ const fallback: ExtractionResult = { shouldSave: false, memories: [] }
+
+ try {
+ // Try to extract JSON from the response
+ let jsonStr = response.trim()
+
+ // Strip markdown code blocks
+ const codeBlockMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/)
+ if (codeBlockMatch) {
+ jsonStr = codeBlockMatch[1].trim()
+ }
+
+ // Try to find JSON object in the response
+ const jsonMatch = jsonStr.match(/\{[\s\S]*\}/)
+ if (!jsonMatch) return fallback
+
+ const data = JSON.parse(jsonMatch[0])
+
+ if (typeof data.shouldSave !== 'boolean') return fallback
+ if (!data.shouldSave) return { shouldSave: false, memories: [] }
+ if (!Array.isArray(data.memories)) return fallback
+
+ // Validate each memory
+ const validTypes: MemoryType[] = ['user', 'feedback', 'project', 'reference']
+ const memories: ExtractedMemory[] = data.memories
+ .filter((m: any) =>
+ m &&
+ validTypes.includes(m.type) &&
+ typeof m.title === 'string' && m.title.length > 0 &&
+ typeof m.content === 'string' && m.content.length > 0
+ )
+ .map((m: any) => ({
+ type: m.type as MemoryType,
+ title: m.title.substring(0, 60),
+ description: (m.description || m.content.substring(0, 120)).substring(0, 120),
+ content: m.content,
+ tags: Array.isArray(m.tags) ? m.tags.filter((t: any) => typeof t === 'string') : [],
+ }))
+
+ return { shouldSave: memories.length > 0, memories }
+ } catch {
+ return fallback
+ }
+}
diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.ts
new file mode 100644
index 00000000..46d18835
--- /dev/null
+++ b/src/lib/workflow-engine.ts
@@ -0,0 +1,419 @@
+/**
+ * Workflow Engine — Executes agent workflow steps sequentially.
+ *
+ * Reuses the same tool execution and provider infrastructure as useAgentChat.
+ * Supports: prompt, tool, condition, loop, user_input, memory_save steps.
+ */
+
+import { v4 as uuid } from 'uuid'
+import { useModelStore } from '../stores/modelStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { useMemoryStore } from '../stores/memoryStore'
+import { getOllamaTools, executeAgentTool } from '../api/tool-registry'
+import { chatNonStreaming } from '../api/agents'
+import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
+import { resolveToolCallingStrategy } from './agent-strategy'
+import type { AgentWorkflow, WorkflowStep, StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
+import type { ChatMessage, ToolDefinition } from '../api/providers/types'
+
+// ── Variable Interpolation ────────────────────────────────────
+
+function interpolate(template: string, variables: Record<string, string>): string {
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => variables[key] || '')
+}
+
+// ── Condition Evaluation ──────────────────────────────────────
+
+function evaluateCondition(
+ source: string,
+ operator: string,
+ value: string,
+ variables: Record<string, string>
+): boolean {
+ const sourceValue = source === 'last_output'
+ ? (variables['last_output'] || '')
+ : (variables[source] || '')
+
+ switch (operator) {
+ case 'contains': return sourceValue.includes(value)
+ case 'not_contains': return !sourceValue.includes(value)
+ case 'equals': return sourceValue === value
+ case 'not_equals': return sourceValue !== value
+ case 'truthy': return Boolean(sourceValue && sourceValue !== 'false' && sourceValue !== '0')
+ case 'falsy': return !sourceValue || sourceValue === 'false' || sourceValue === '0'
+ default: return false
+ }
+}
+
+// ── Engine ────────────────────────────────────────────────────
+
+export class WorkflowEngine {
+ private workflow: AgentWorkflow
+ private conversationId: string
+ private callbacks: WorkflowEngineCallbacks
+ private variables: Record<string, string>
+ private abortController: AbortController
+ private inputResolver: ((input: string) => void) | null = null
+
+ constructor(
+ workflow: AgentWorkflow,
+ conversationId: string,
+ callbacks: WorkflowEngineCallbacks,
+ initialVariables?: Record<string, string>
+ ) {
+ this.workflow = workflow
+ this.conversationId = conversationId
+ this.callbacks = callbacks
+ this.variables = { ...workflow.variables, ...(initialVariables || {}) }
+ this.abortController = new AbortController()
+ }
+
+ /**
+ * Run the workflow from start to finish.
+ */
+ async run(): Promise<StepResult[]> {
+ const results: StepResult[] = []
+ let stepIndex = 0
+
+ try {
+ while (stepIndex < this.workflow.steps.length) {
+ if (this.abortController.signal.aborted) break
+
+ const step = this.workflow.steps[stepIndex]
+ this.callbacks.onStepStart(stepIndex, step)
+
+ const result = await this.executeStep(step, stepIndex)
+ results.push(result)
+
+ if (result.status === 'failed') {
+ this.callbacks.onStepError(stepIndex, result.error || 'Unknown error')
+ break
+ }
+
+ this.callbacks.onStepComplete(stepIndex, result)
+
+ // Set last_output for next step
+ if (result.output) {
+ this.variables['last_output'] = result.output
+ }
+
+ // Handle branching (condition step changes stepIndex)
+ if (step.type === 'condition' && step.condition) {
+ const matches = evaluateCondition(
+ step.condition.source,
+ step.condition.operator,
+ interpolate(step.condition.value, this.variables),
+ this.variables
+ )
+ const targetId = matches ? step.condition.thenStepId : step.condition.elseStepId
+ const targetIndex = this.workflow.steps.findIndex(s => s.id === targetId)
+ stepIndex = targetIndex >= 0 ? targetIndex : stepIndex + 1
+ } else {
+ stepIndex++
+ }
+ }
+
+ if (!this.abortController.signal.aborted) {
+ this.callbacks.onComplete(results)
+ }
+ } catch (err) {
+ const errorMsg = (err as Error).message || 'Workflow execution failed'
+ this.callbacks.onError(errorMsg)
+ }
+
+ return results
+ }
+
+ /**
+ * Cancel the running workflow.
+ */
+ cancel() {
+ this.abortController.abort()
+ }
+
+ /**
+ * Provide user input for a waiting user_input step.
+ */
+ provideUserInput(input: string) {
+ if (this.inputResolver) {
+ this.inputResolver(input)
+ this.inputResolver = null
+ }
+ }
+
+ // ── Step Execution ────────────────────────────────────────
+
+ private async executeStep(step: WorkflowStep, stepIndex: number): Promise<StepResult> {
+ const startedAt = Date.now()
+
+ try {
+ switch (step.type) {
+ case 'prompt':
+ return await this.executePromptStep(step, startedAt)
+
+ case 'tool':
+ return await this.executeToolStep(step, startedAt)
+
+ case 'condition':
+ return this.executeConditionStep(step, startedAt)
+
+ case 'loop':
+ return await this.executeLoopStep(step, startedAt)
+
+ case 'user_input':
+ return await this.executeUserInputStep(step, stepIndex, startedAt)
+
+ case 'memory_save':
+ return this.executeMemorySaveStep(step, startedAt)
+
+ default:
+ return { stepId: step.id, status: 'failed', output: '', startedAt, error: `Unknown step type: ${step.type}` }
+ }
+ } catch (err) {
+ return {
+ stepId: step.id,
+ status: 'failed',
+ output: '',
+ startedAt,
+ completedAt: Date.now(),
+ error: (err as Error).message || 'Step execution failed',
+ }
+ }
+ }
+
+ // ── Prompt Step ───────────────────────────────────────────
+
+ private async executePromptStep(step: WorkflowStep, startedAt: number): Promise<StepResult> {
+ const { activeModel } = useModelStore.getState()
+ if (!activeModel) throw new Error('No active model')
+
+ const { strategy, modelToUse, provider } = await resolveToolCallingStrategy(activeModel)
+ const prompt = interpolate(step.prompt || '', this.variables)
+
+ const messages: ChatMessage[] = [
+ { role: 'user', content: prompt },
+ ]
+
+ const { settings } = useSettingsStore.getState()
+ let output = ''
+
+ if (step.allowedTools && step.allowedTools.length === 0) {
+ // No tools — pure prompt
+ if (strategy === 'hermes_xml') {
+ output = await chatNonStreaming(modelToUse, messages.map(m => ({ role: m.role, content: m.content })))
+ } else {
+ const stream = provider.chatStream(modelToUse, messages, {
+ temperature: settings.temperature,
+ signal: this.abortController.signal,
+ })
+ for await (const chunk of stream) {
+ if (chunk.content) output += chunk.content
+ if (chunk.done) break
+ }
+ }
+ } else {
+ // With tools
+ const tools: ToolDefinition[] = getOllamaTools()
+ const allowedTools = step.allowedTools
+ ? tools.filter(t => step.allowedTools!.includes(t.function.name))
+ : tools
+
+ if (strategy === 'native') {
+ const turn = await provider.chatWithTools(modelToUse, messages, allowedTools, {
+ temperature: settings.temperature,
+ signal: this.abortController.signal,
+ })
+ output = turn.content || ''
+
+ // Execute any tool calls
+ for (const tc of turn.toolCalls) {
+ const result = await executeAgentTool(tc.function.name, tc.function.arguments)
+ output += `\n[Tool: ${tc.function.name}] ${result}`
+ }
+ } else {
+ // Hermes XML
+ const hermesSystem = buildHermesToolPrompt(
+ allowedTools.map(t => ({ name: t.function.name, description: t.function.description, parameters: t.function.parameters as any, permission: 'auto' as const }))
+ )
+ const hermesMessages = [{ role: 'system' as const, content: hermesSystem }, ...messages]
+ const rawContent = await chatNonStreaming(modelToUse, hermesMessages.map(m => ({ role: m.role, content: m.content })))
+
+ if (hasToolCallTags(rawContent)) {
+ const toolCalls = parseHermesToolCalls(rawContent)
+ output = stripToolCallTags(rawContent)
+ for (const tc of toolCalls) {
+ const result = await executeAgentTool(tc.name, tc.arguments)
+ output += `\n[Tool: ${tc.name}] ${result}`
+ }
+ } else {
+ output = rawContent
+ }
+ }
+ }
+
+ // Strip think tags
+ output = output.replace(/<think>[\s\S]*?<\/think>/g, '').trim()
+
+ return {
+ stepId: step.id,
+ status: 'completed',
+ output,
+ startedAt,
+ completedAt: Date.now(),
+ }
+ }
+
+ // ── Tool Step ─────────────────────────────────────────────
+
+ private async executeToolStep(step: WorkflowStep, startedAt: number): Promise<StepResult> {
+ if (!step.toolName) throw new Error('Tool step missing toolName')
+
+ // Build args from static + templates
+ const args: Record<string, any> = { ...(step.toolArgs || {}) }
+ if (step.toolArgTemplates) {
+ for (const [key, template] of Object.entries(step.toolArgTemplates)) {
+ args[key] = interpolate(template, this.variables)
+ }
+ }
+
+ const result = await executeAgentTool(step.toolName, args)
+ const isError = result.startsWith('Error:')
+
+ return {
+ stepId: step.id,
+ status: isError ? 'failed' : 'completed',
+ output: result,
+ startedAt,
+ completedAt: Date.now(),
+ error: isError ? result : undefined,
+ toolCalls: [{ name: step.toolName, args, result }],
+ }
+ }
+
+ // ── Condition Step ────────────────────────────────────────
+
+ private executeConditionStep(step: WorkflowStep, startedAt: number): StepResult {
+ if (!step.condition) throw new Error('Condition step missing condition')
+
+ const matches = evaluateCondition(
+ step.condition.source,
+ step.condition.operator,
+ interpolate(step.condition.value, this.variables),
+ this.variables
+ )
+
+ return {
+ stepId: step.id,
+ status: 'completed',
+ output: matches ? 'true' : 'false',
+ startedAt,
+ completedAt: Date.now(),
+ }
+ }
+
+ // ── Loop Step ─────────────────────────────────────────────
+
+ private async executeLoopStep(step: WorkflowStep, startedAt: number): Promise<StepResult> {
+ if (!step.loop) throw new Error('Loop step missing loop config')
+
+ let iterations = 0
+ const outputs: string[] = []
+
+ while (iterations < step.loop.maxIterations) {
+ if (this.abortController.signal.aborted) break
+
+ // Execute body steps
+ for (const bodyStepId of step.loop.bodyStepIds) {
+ const bodyStep = this.workflow.steps.find(s => s.id === bodyStepId)
+ if (!bodyStep) continue
+
+ const bodyResult = await this.executeStep(bodyStep, -1)
+ if (bodyResult.output) {
+ this.variables['last_output'] = bodyResult.output
+ outputs.push(bodyResult.output)
+ }
+ if (bodyResult.status === 'failed') {
+ return { stepId: step.id, status: 'failed', output: outputs.join('\n'), startedAt, completedAt: Date.now(), error: bodyResult.error }
+ }
+ }
+
+ // Check exit condition
+ const shouldContinue = evaluateCondition(
+ step.loop.condition.source,
+ step.loop.condition.operator,
+ interpolate(step.loop.condition.value, this.variables),
+ this.variables
+ )
+ if (!shouldContinue) break
+
+ iterations++
+ }
+
+ return {
+ stepId: step.id,
+ status: 'completed',
+ output: outputs.join('\n'),
+ startedAt,
+ completedAt: Date.now(),
+ }
+ }
+
+ // ── User Input Step ───────────────────────────────────────
+
+ private async executeUserInputStep(step: WorkflowStep, stepIndex: number, startedAt: number): Promise<StepResult> {
+ const prompt = interpolate(step.userInputPrompt || 'Enter input:', this.variables)
+ this.callbacks.onWaitingForInput(stepIndex, prompt)
+
+ const input = await new Promise<string>((resolve) => {
+ this.inputResolver = resolve
+
+ // Also resolve on abort
+ const onAbort = () => {
+ resolve('')
+ this.abortController.signal.removeEventListener('abort', onAbort)
+ }
+ this.abortController.signal.addEventListener('abort', onAbort)
+ })
+
+ if (this.abortController.signal.aborted) {
+ return { stepId: step.id, status: 'failed', output: '', startedAt, error: 'Cancelled' }
+ }
+
+ this.variables['user_input'] = input
+ this.variables['last_output'] = input
+
+ return {
+ stepId: step.id,
+ status: 'completed',
+ output: input,
+ startedAt,
+ completedAt: Date.now(),
+ }
+ }
+
+ // ── Memory Save Step ──────────────────────────────────────
+
+ private executeMemorySaveStep(step: WorkflowStep, startedAt: number): StepResult {
+ if (!step.memorySave) throw new Error('Memory save step missing config')
+
+ const title = interpolate(step.memorySave.titleTemplate, this.variables)
+ const content = interpolate(step.memorySave.contentTemplate, this.variables)
+
+ useMemoryStore.getState().addMemory({
+ type: step.memorySave.type,
+ title: title.substring(0, 60),
+ description: content.substring(0, 120),
+ content,
+ tags: step.memorySave.tags || ['workflow'],
+ source: this.conversationId,
+ })
+
+ return {
+ stepId: step.id,
+ status: 'completed',
+ output: `Saved to memory: ${title}`,
+ startedAt,
+ completedAt: Date.now(),
+ }
+ }
+}
diff --git a/src/stores/__tests__/stores.test.ts b/src/stores/__tests__/stores.test.ts
index 95a25e78..3235060b 100644
--- a/src/stores/__tests__/stores.test.ts
+++ b/src/stores/__tests__/stores.test.ts
@@ -336,24 +336,34 @@ describe('agentModeStore', () => {
describe('memoryStore', () => {
beforeEach(() => {
- useMemoryStore.setState({ entries: [], lastSynced: 0 })
+ useMemoryStore.setState({
+ entries: [],
+ lastSynced: 0,
+ settings: {
+ autoExtractEnabled: true,
+ autoExtractInAllModes: true,
+ maxMemoriesInPrompt: 10,
+ maxMemoryChars: 3000,
+ },
+ })
})
- describe('addEntry', () => {
- it('adds an entry to the store', () => {
+ describe('addEntry (legacy compat)', () => {
+ it('adds an entry to the store via legacy API', () => {
useMemoryStore.getState().addEntry('fact', 'The sky is blue')
expect(useMemoryStore.getState().entries).toHaveLength(1)
expect(useMemoryStore.getState().entries[0].content).toBe('The sky is blue')
- expect(useMemoryStore.getState().entries[0].category).toBe('fact')
+ // Legacy fact → user type
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
})
- it('deduplicates entries with same content and category', () => {
+ it('deduplicates entries with same content and type', () => {
useMemoryStore.getState().addEntry('fact', 'Duplicate')
useMemoryStore.getState().addEntry('fact', 'Duplicate')
expect(useMemoryStore.getState().entries).toHaveLength(1)
})
- it('allows same content in different categories', () => {
+ it('allows same content in different categories (mapped to types)', () => {
useMemoryStore.getState().addEntry('fact', 'Same text')
useMemoryStore.getState().addEntry('decision', 'Same text')
expect(useMemoryStore.getState().entries).toHaveLength(2)
@@ -370,13 +380,44 @@ describe('memoryStore', () => {
expect(useMemoryStore.getState().entries[0].content).toBe('trimmed')
})
- it('stores optional source', () => {
+ it('stores optional source as tag', () => {
useMemoryStore.getState().addEntry('tool_result', 'data', 'agent:web_search')
- expect(useMemoryStore.getState().entries[0].source).toBe('agent:web_search')
+ expect(useMemoryStore.getState().entries[0].tags).toContain('agent:web_search')
+ })
+ })
+
+ describe('addMemory', () => {
+ it('adds a MemoryFile to the store', () => {
+ useMemoryStore.getState().addMemory({
+ type: 'user',
+ title: 'User is a developer',
+ description: 'The user works as a software developer',
+ content: 'The user is a software developer who uses TypeScript',
+ tags: ['role'],
+ source: 'conv-123',
+ })
+ expect(useMemoryStore.getState().entries).toHaveLength(1)
+ expect(useMemoryStore.getState().entries[0].type).toBe('user')
+ expect(useMemoryStore.getState().entries[0].title).toBe('User is a developer')
+ })
+
+ it('deduplicates by content + type', () => {
+ const mem = { type: 'feedback' as const, title: 'No emojis', description: 'User dislikes emojis', content: 'Do not use emojis', tags: [], source: 'manual' }
+ useMemoryStore.getState().addMemory(mem)
+ useMemoryStore.getState().addMemory(mem)
+ expect(useMemoryStore.getState().entries).toHaveLength(1)
+ })
+
+ it('returns the new entry ID', () => {
+ const id = useMemoryStore.getState().addMemory({
+ type: 'project', title: 'Test', description: 'Test', content: 'Test content', tags: [], source: 'manual',
+ })
+ expect(id).toBeTruthy()
+ expect(useMemoryStore.getState().entries[0].id).toBe(id)
})
})
- describe('searchMemory', () => {
+ describe('searchMemories', () => {
beforeEach(() => {
useMemoryStore.getState().addEntry('fact', 'TypeScript is a superset of JavaScript')
useMemoryStore.getState().addEntry('fact', 'React uses virtual DOM')
@@ -385,84 +426,107 @@ describe('memoryStore', () => {
})
it('finds entries matching query words', () => {
- const results = useMemoryStore.getState().searchMemory('TypeScript JavaScript')
+ const results = useMemoryStore.getState().searchMemories('TypeScript JavaScript')
expect(results.length).toBeGreaterThan(0)
expect(results[0].content).toContain('TypeScript')
})
it('filters out words shorter than 3 characters', () => {
- // "is a" are both < 3 chars, "superset" is the only word that qualifies
- const results = useMemoryStore.getState().searchMemory('is a superset')
+ const results = useMemoryStore.getState().searchMemories('is a superset')
expect(results.length).toBeGreaterThan(0)
- // Should match on "superset", not on "is" or "a"
expect(results[0].content).toContain('superset')
})
- it('returns recent entries when all query words are too short', () => {
- const results = useMemoryStore.getState().searchMemory('is a')
- // All words < 3 chars, so it returns last 20 entries
- expect(results).toHaveLength(4)
+ it('returns all entries when query words are too short', () => {
+ const results = useMemoryStore.getState().searchMemories('is a')
+ // All words < 3 chars → all entries have score > 0 (baseline type bonus)
+ expect(results.length).toBeGreaterThan(0)
})
- it('ranks results by number of matching words', () => {
- const results = useMemoryStore.getState().searchMemory('Zustand state')
+ it('ranks results by matching words', () => {
+ const results = useMemoryStore.getState().searchMemories('Zustand state')
expect(results[0].content).toContain('Zustand')
})
it('returns empty for query that matches nothing', () => {
- const results = useMemoryStore.getState().searchMemory('xylophone')
+ const results = useMemoryStore.getState().searchMemories('xylophone')
expect(results).toHaveLength(0)
})
+
+ it('filters by type', () => {
+ const results = useMemoryStore.getState().searchMemories('', { type: 'user' })
+ // fact → user, so the two facts should be user type
+ expect(results.every(e => e.type === 'user')).toBe(true)
+ })
})
- describe('getMemoryForPrompt', () => {
- it('returns formatted string with category labels', () => {
+ describe('getMemoriesForPrompt', () => {
+ it('returns formatted string with section headers', () => {
useMemoryStore.getState().addEntry('fact', 'Earth orbits the Sun')
- const prompt = useMemoryStore.getState().getMemoryForPrompt('Earth Sun')
- expect(prompt).toContain('[Known fact]')
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('Earth Sun', 8192)
+ expect(prompt).toContain('About the user')
expect(prompt).toContain('Earth orbits the Sun')
})
it('returns empty string when no relevant entries', () => {
- const prompt = useMemoryStore.getState().getMemoryForPrompt('xylophone')
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('xylophone', 8192)
expect(prompt).toBe('')
})
- it('respects maxChars limit', () => {
- for (let i = 0; i < 50; i++) {
- useMemoryStore.getState().addEntry('fact', `Fact number ${i} about testing memory store limits`)
- }
- const prompt = useMemoryStore.getState().getMemoryForPrompt('fact testing memory', 100)
- expect(prompt.length).toBeLessThanOrEqual(100 + 100) // some tolerance for the last line
+ it('returns empty for tiny context models', () => {
+ useMemoryStore.getState().addEntry('fact', 'Important fact')
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('fact', 2048)
+ expect(prompt).toBe('')
})
- it('uses correct category labels', () => {
- useMemoryStore.getState().addEntry('decision', 'Use Vitest for testing')
- useMemoryStore.getState().addEntry('tool_result', 'Search returned 5 results')
- useMemoryStore.getState().addEntry('context', 'Running on Windows')
+ it('limits to user+feedback types for small context', () => {
+ useMemoryStore.getState().addEntry('fact', 'User pref') // → user
+ useMemoryStore.getState().addEntry('decision', 'Decision') // → project
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('User pref Decision', 4000)
+ expect(prompt).toContain('User pref')
+ // Project type not allowed at 4000 ctx
+ expect(prompt).not.toContain('Project context')
+ })
+
+ it('includes all types for large context', () => {
+ useMemoryStore.getState().addEntry('fact', 'User info')
+ useMemoryStore.getState().addEntry('decision', 'Project decision about architecture')
+ useMemoryStore.getState().addEntry('tool_result', 'Search result about APIs')
+ const prompt = useMemoryStore.getState().getMemoriesForPrompt('User info Project decision Search result', 16000)
+ expect(prompt).toContain('About the user')
+ expect(prompt).toContain('Project context')
+ expect(prompt).toContain('References')
+ })
+ })
+
+ describe('getMemoryForPrompt (legacy compat)', () => {
+ it('returns formatted string via legacy API', () => {
+ useMemoryStore.getState().addEntry('fact', 'Earth orbits the Sun')
+ const prompt = useMemoryStore.getState().getMemoryForPrompt('Earth Sun')
+ expect(prompt).toContain('Earth orbits the Sun')
+ })
- const prompt = useMemoryStore.getState().getMemoryForPrompt('Vitest search Windows testing results')
- expect(prompt).toContain('[Decision]')
- expect(prompt).toContain('[Previous result]')
- expect(prompt).toContain('[Context]')
+ it('returns empty for no matches', () => {
+ const prompt = useMemoryStore.getState().getMemoryForPrompt('xylophone')
+ expect(prompt).toBe('')
})
})
describe('exportAsMarkdown', () => {
it('returns placeholder when no entries exist', () => {
const md = useMemoryStore.getState().exportAsMarkdown()
- expect(md).toContain('# Agent Memory')
+ expect(md).toContain('# Memory')
expect(md).toContain('No entries yet')
})
- it('groups entries by category with headers', () => {
+ it('groups entries by type with headers', () => {
useMemoryStore.getState().addEntry('fact', 'Fact one')
useMemoryStore.getState().addEntry('decision', 'Decision one')
const md = useMemoryStore.getState().exportAsMarkdown()
- expect(md).toContain('## Facts')
- expect(md).toContain('## Decisions')
- expect(md).toContain('- Fact one')
- expect(md).toContain('- Decision one')
+ expect(md).toContain('## User')
+ expect(md).toContain('## Project')
+ expect(md).toContain('Fact one')
+ expect(md).toContain('Decision one')
})
it('includes source when present', () => {
@@ -473,28 +537,46 @@ describe('memoryStore', () => {
})
describe('importFromMarkdown', () => {
- it('parses categories and list items', () => {
- const md = `# Agent Memory
+ it('parses type headers and list items', () => {
+ const md = `# Memory
-## Facts
+## User
- First fact
- Second fact
-## Decisions
+## Project
- Important decision
`
useMemoryStore.getState().importFromMarkdown(md)
const entries = useMemoryStore.getState().entries
expect(entries).toHaveLength(3)
- expect(entries.filter((e) => e.category === 'fact')).toHaveLength(2)
- expect(entries.filter((e) => e.category === 'decision')).toHaveLength(1)
+ expect(entries.filter((e) => e.type === 'user')).toHaveLength(2)
+ expect(entries.filter((e) => e.type === 'project')).toHaveLength(1)
})
- it('parses source from markdown format', () => {
+ it('supports legacy category headers', () => {
const md = `## Facts
+- Old fact
+
+## Decisions
+
+- Old decision
+`
+ useMemoryStore.getState().importFromMarkdown(md)
+ const entries = useMemoryStore.getState().entries
+ expect(entries).toHaveLength(2)
+ // Legacy 'facts' maps to 'user'
+ expect(entries[0].type).toBe('user')
+ // Legacy 'decisions' maps to 'project'
+ expect(entries[1].type).toBe('project')
+ })
+
+ it('parses source from markdown format', () => {
+ const md = `## User
+
- A fact *(user:manual)* — 4/1/2026
`
useMemoryStore.getState().importFromMarkdown(md)
@@ -504,7 +586,7 @@ describe('memoryStore', () => {
})
it('defaults source to "import" when not present', () => {
- const md = `## Facts
+ const md = `## User
- A plain fact
`
@@ -514,7 +596,7 @@ describe('memoryStore', () => {
it('appends to existing entries', () => {
useMemoryStore.getState().addEntry('fact', 'Existing')
- useMemoryStore.getState().importFromMarkdown('## Decisions\n\n- Imported decision\n')
+ useMemoryStore.getState().importFromMarkdown('## Project\n\n- Imported decision\n')
expect(useMemoryStore.getState().entries).toHaveLength(2)
})
@@ -539,4 +621,23 @@ describe('memoryStore', () => {
expect(useMemoryStore.getState().lastSynced).toBeGreaterThanOrEqual(before)
})
})
+
+ describe('updateMemory', () => {
+ it('updates title and content', () => {
+ useMemoryStore.getState().addMemory({
+ type: 'user', title: 'Old title', description: 'Old', content: 'Old content', tags: [], source: 'manual',
+ })
+ const id = useMemoryStore.getState().entries[0].id
+ useMemoryStore.getState().updateMemory(id, { title: 'New title', content: 'New content' })
+ expect(useMemoryStore.getState().entries[0].title).toBe('New title')
+ expect(useMemoryStore.getState().entries[0].content).toBe('New content')
+ })
+ })
+
+ describe('settings', () => {
+ it('updates memory settings', () => {
+ useMemoryStore.getState().updateMemorySettings({ autoExtractEnabled: true })
+ expect(useMemoryStore.getState().settings.autoExtractEnabled).toBe(true)
+ })
+ })
})
diff --git a/src/stores/agentWorkflowStore.ts b/src/stores/agentWorkflowStore.ts
new file mode 100644
index 00000000..e0b82f67
--- /dev/null
+++ b/src/stores/agentWorkflowStore.ts
@@ -0,0 +1,167 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import { v4 as uuid } from 'uuid'
+import type { AgentWorkflow, WorkflowExecution, StepResult } from '../types/agent-workflows'
+import { BUILT_IN_WORKFLOWS } from '../lib/built-in-workflows'
+
+// ── Max execution history ─────────────────────────────────────
+
+const MAX_EXECUTION_HISTORY = 50
+
+// ── Store Interface ───────────────────────────────────────────
+
+interface AgentWorkflowState {
+ workflows: AgentWorkflow[]
+ executions: WorkflowExecution[]
+ activeExecutionId: string | null
+
+ // Workflow CRUD
+ addWorkflow: (workflow: Omit<AgentWorkflow, 'id' | 'createdAt' | 'updatedAt'>) => string
+ updateWorkflow: (id: string, updates: Partial<Pick<AgentWorkflow, 'name' | 'description' | 'icon' | 'steps' | 'variables'>>) => void
+ removeWorkflow: (id: string) => void
+ duplicateWorkflow: (id: string) => string | null
+ getWorkflow: (id: string) => AgentWorkflow | undefined
+
+ // Execution management
+ startExecution: (workflowId: string, conversationId?: string) => string | null
+ updateExecution: (id: string, updates: Partial<WorkflowExecution>) => void
+ addStepResult: (executionId: string, result: StepResult) => void
+ cancelExecution: (id: string) => void
+ clearExecutionHistory: () => void
+}
+
+// ── Store ─────────────────────────────────────────────────────
+
+export const useAgentWorkflowStore = create<AgentWorkflowState>()(
+ persist(
+ (set, get) => ({
+ workflows: [...BUILT_IN_WORKFLOWS],
+ executions: [],
+ activeExecutionId: null,
+
+ // ── Workflow CRUD ─────────────────────────────────────
+
+ addWorkflow: (workflow) => {
+ const id = uuid()
+ set((state) => ({
+ workflows: [
+ ...state.workflows,
+ { ...workflow, id, createdAt: Date.now(), updatedAt: Date.now() },
+ ],
+ }))
+ return id
+ },
+
+ updateWorkflow: (id, updates) =>
+ set((state) => ({
+ workflows: state.workflows.map((w) =>
+ w.id === id ? { ...w, ...updates, updatedAt: Date.now() } : w
+ ),
+ })),
+
+ removeWorkflow: (id) =>
+ set((state) => ({
+ workflows: state.workflows.filter((w) => w.id !== id || w.isBuiltIn),
+ })),
+
+ duplicateWorkflow: (id) => {
+ const original = get().workflows.find(w => w.id === id)
+ if (!original) return null
+ const newId = uuid()
+ set((state) => ({
+ workflows: [
+ ...state.workflows,
+ {
+ ...original,
+ id: newId,
+ name: `${original.name} (copy)`,
+ isBuiltIn: false,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ],
+ }))
+ return newId
+ },
+
+ getWorkflow: (id) => get().workflows.find(w => w.id === id),
+
+ // ── Execution ─────────────────────────────────────────
+
+ startExecution: (workflowId, conversationId) => {
+ const workflow = get().workflows.find(w => w.id === workflowId)
+ if (!workflow) return null
+
+ const id = uuid()
+ const execution: WorkflowExecution = {
+ id,
+ workflowId,
+ workflowName: workflow.name,
+ status: 'running',
+ currentStepIndex: 0,
+ stepResults: [],
+ variables: { ...workflow.variables },
+ conversationId,
+ startedAt: Date.now(),
+ }
+
+ set((state) => {
+ // Trim history if needed
+ const executions = [execution, ...state.executions].slice(0, MAX_EXECUTION_HISTORY)
+ return { executions, activeExecutionId: id }
+ })
+
+ return id
+ },
+
+ updateExecution: (id, updates) =>
+ set((state) => ({
+ executions: state.executions.map((e) =>
+ e.id === id ? { ...e, ...updates } : e
+ ),
+ })),
+
+ addStepResult: (executionId, result) =>
+ set((state) => ({
+ executions: state.executions.map((e) =>
+ e.id === executionId
+ ? { ...e, stepResults: [...e.stepResults, result], currentStepIndex: e.currentStepIndex + 1 }
+ : e
+ ),
+ })),
+
+ cancelExecution: (id) =>
+ set((state) => ({
+ executions: state.executions.map((e) =>
+ e.id === id ? { ...e, status: 'cancelled', completedAt: Date.now() } : e
+ ),
+ activeExecutionId: state.activeExecutionId === id ? null : state.activeExecutionId,
+ })),
+
+ clearExecutionHistory: () =>
+ set({ executions: [], activeExecutionId: null }),
+ }),
+ {
+ name: 'locally-uncensored-agent-workflows',
+ version: 1,
+ migrate: (persistedState, version) => {
+ const state = persistedState as any
+ if (version < 1 || !state.workflows || state.workflows.length === 0) {
+ return { ...state, workflows: BUILT_IN_WORKFLOWS, executions: [], activeExecutionId: null }
+ }
+ // Ensure built-ins are present (may have been added in updates)
+ const existingIds = new Set(state.workflows.map((w: any) => w.id))
+ const missingBuiltIns = BUILT_IN_WORKFLOWS.filter(w => !existingIds.has(w.id))
+ return {
+ ...state,
+ workflows: [...missingBuiltIns, ...state.workflows],
+ }
+ },
+ partialize: (state) => ({
+ workflows: state.workflows,
+ executions: state.executions.slice(0, MAX_EXECUTION_HISTORY),
+ // Don't persist activeExecutionId
+ }),
+ }
+ )
+)
diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.ts
index 32e4f4a4..c9275976 100644
--- a/src/stores/memoryStore.ts
+++ b/src/stores/memoryStore.ts
@@ -1,52 +1,176 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
-import type { MemoryEntry, MemoryCategory } from '../types/agent-mode'
+import type { MemoryEntry, MemoryCategory, MemoryFile, MemoryType, MemorySettings } from '../types/agent-mode'
+import { MEMORY_MIGRATION_MAP, MEMORY_BUDGET_TIERS } from '../types/agent-mode'
+
+// ── Memory Budget Helper ──────────────────────────────────────
+
+export function getMemoryBudget(contextTokens: number) {
+ for (const tier of MEMORY_BUDGET_TIERS) {
+ if (contextTokens <= tier.maxContext) return tier
+ }
+ return MEMORY_BUDGET_TIERS[MEMORY_BUDGET_TIERS.length - 1]
+}
+
+// ── Search Scoring ────────────────────────────────────────────
+
+function scoreMemory(memory: MemoryFile, queryWords: string[]): number {
+ if (queryWords.length === 0) return 1
+
+ const titleLower = memory.title.toLowerCase()
+ const descLower = memory.description.toLowerCase()
+ const contentLower = memory.content.toLowerCase()
+ const tagsLower = memory.tags.map(t => t.toLowerCase())
+
+ let score = 0
+ for (const w of queryWords) {
+ if (titleLower.includes(w)) score += 4
+ if (descLower.includes(w)) score += 3
+ if (tagsLower.some(t => t.includes(w))) score += 3
+ if (contentLower.includes(w)) score += 1
+ }
+
+ // Bonuses only apply when there's at least one word match
+ if (score > 0) {
+ // Recency bonus
+ const age = Date.now() - memory.updatedAt
+ const oneDay = 86400000
+ if (age < oneDay) score += 2
+ else if (age < 7 * oneDay) score += 1
+
+ // User and feedback types get slight boost (most actionable)
+ if (memory.type === 'user' || memory.type === 'feedback') score += 0.5
+ }
+
+ return score
+}
+
+// ── Type Labels ───────────────────────────────────────────────
+
+const TYPE_SECTION_HEADERS: Record<MemoryType, string> = {
+ user: 'About the user',
+ feedback: 'User feedback / corrections',
+ project: 'Project context',
+ reference: 'References',
+}
+
+// ── Store Interface ───────────────────────────────────────────
interface MemoryState {
- entries: MemoryEntry[]
+ entries: MemoryFile[]
+ settings: MemorySettings
lastSynced: number
- // Actions
- addEntry: (category: MemoryCategory, content: string, source?: string) => void
- removeEntry: (id: string) => void
+ // CRUD
+ addMemory: (memory: Omit<MemoryFile, 'id' | 'createdAt' | 'updatedAt'>) => string
+ updateMemory: (id: string, updates: Partial<Pick<MemoryFile, 'title' | 'description' | 'content' | 'type' | 'tags'>>) => void
+ removeMemory: (id: string) => void
clearAll: () => void
- searchMemory: (query: string) => MemoryEntry[]
- getMemoryForPrompt: (query: string, maxChars?: number) => string
+
+ // Search & Inject
+ searchMemories: (query: string, options?: { type?: MemoryType; limit?: number }) => MemoryFile[]
+ getMemoriesForPrompt: (query: string, contextTokens: number) => string
+
+ // Settings
+ updateMemorySettings: (updates: Partial<MemorySettings>) => void
+
+ // Export / Import
exportAsMarkdown: () => string
importFromMarkdown: (markdown: string) => void
+ exportAsJSON: () => string
+ importFromJSON: (json: string) => void
+
+ // Legacy compat (used by old code paths during transition)
+ addEntry: (category: MemoryCategory, content: string, source?: string) => void
+ getMemoryForPrompt: (query: string, maxChars?: number) => string
}
+// ── Migration from v1 (old MemoryEntry[]) to v2 (MemoryFile[]) ──
+
+function migrateV1toV2(oldState: any): any {
+ if (!oldState || !Array.isArray(oldState.entries)) return oldState
+
+ // Check if already migrated (MemoryFile has 'type' field)
+ if (oldState.entries.length > 0 && 'type' in oldState.entries[0]) {
+ return oldState
+ }
+
+ // Migrate old MemoryEntry[] to MemoryFile[]
+ const migratedEntries: MemoryFile[] = (oldState.entries as MemoryEntry[]).map((e) => ({
+ id: e.id,
+ type: MEMORY_MIGRATION_MAP[e.category] || 'project',
+ title: e.content.substring(0, 60).replace(/\n/g, ' '),
+ description: e.content.substring(0, 120).replace(/\n/g, ' '),
+ content: e.content,
+ tags: e.source ? [e.source] : [],
+ createdAt: e.timestamp,
+ updatedAt: e.timestamp,
+ source: e.source || 'migration',
+ }))
+
+ return {
+ ...oldState,
+ entries: migratedEntries,
+ settings: {
+ autoExtractEnabled: true,
+ autoExtractInAllModes: true,
+ maxMemoriesInPrompt: 10,
+ maxMemoryChars: 3000,
+ },
+ }
+}
+
+// ── Store ─────────────────────────────────────────────────────
+
export const useMemoryStore = create<MemoryState>()(
persist(
(set, get) => ({
entries: [],
+ settings: {
+ autoExtractEnabled: true,
+ autoExtractInAllModes: true,
+ maxMemoriesInPrompt: 10,
+ maxMemoryChars: 3000,
+ },
lastSynced: 0,
- addEntry: (category, content, source) => {
- const trimmed = content.trim()
- if (!trimmed) return
+ // ── CRUD ────────────────────────────────────────────────
- // Deduplicate: don't add if exact same content already exists
+ addMemory: (memory) => {
+ const trimmedContent = memory.content.trim()
+ if (!trimmedContent) return ''
+
+ // Deduplicate: don't add if exact same content + type exists
const existing = get().entries
- if (existing.some(e => e.content === trimmed && e.category === category)) return
+ if (existing.some(e => e.content === trimmedContent && e.type === memory.type)) return ''
+ const id = uuid()
set((state) => ({
entries: [
...state.entries,
{
- id: uuid(),
- category,
- content: trimmed,
- timestamp: Date.now(),
- source,
+ ...memory,
+ id,
+ content: trimmedContent,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
},
],
lastSynced: Date.now(),
}))
+ return id
},
- removeEntry: (id) =>
+ updateMemory: (id, updates) =>
+ set((state) => ({
+ entries: state.entries.map((e) =>
+ e.id === id ? { ...e, ...updates, updatedAt: Date.now() } : e
+ ),
+ lastSynced: Date.now(),
+ })),
+
+ removeMemory: (id) =>
set((state) => ({
entries: state.entries.filter((e) => e.id !== id),
lastSynced: Date.now(),
@@ -54,66 +178,114 @@ export const useMemoryStore = create<MemoryState>()(
clearAll: () => set({ entries: [], lastSynced: Date.now() }),
- searchMemory: (query) => {
+ // ── Search ──────────────────────────────────────────────
+
+ searchMemories: (query, options) => {
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 }
- })
+ let results = get().entries
+
+ // Filter by type
+ if (options?.type) {
+ results = results.filter(e => e.type === options.type)
+ }
+
+ // Score and sort
+ const scored = results
+ .map((entry) => ({ entry, score: scoreMemory(entry, words) }))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
- .map(({ entry }) => entry)
+
+ const limit = options?.limit || 20
+ return scored.slice(0, limit).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',
+ // ── Context-Aware Prompt Injection ──────────────────────
+
+ getMemoriesForPrompt: (query, contextTokens) => {
+ const budget = getMemoryBudget(contextTokens)
+
+ // No budget for tiny models
+ if (budget.budgetTokens === 0 || budget.maxMemories === 0) return ''
+
+ const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2)
+ let candidates = get().entries
+
+ // Filter by allowed types for this tier
+ if (budget.typesAllowed !== 'all') {
+ candidates = candidates.filter(e => (budget.typesAllowed as MemoryType[]).includes(e.type))
}
+ // Score and sort
+ const scored = candidates
+ .map((entry) => ({ entry, score: scoreMemory(entry, words) }))
+ .filter(({ score }) => score > 0)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, budget.maxMemories)
+
+ if (scored.length === 0) return ''
+
+ // Group by type for structured output
+ const grouped: Record<MemoryType, MemoryFile[]> = {
+ user: [], feedback: [], project: [], reference: [],
+ }
+ for (const { entry } of scored) {
+ grouped[entry.type].push(entry)
+ }
+
+ // Build output within char budget (tokens * 4 chars/token)
+ const maxChars = budget.budgetTokens * 4
let result = ''
- for (const entry of relevant) {
- const line = `- [${categoryLabels[entry.category]}] ${entry.content}\n`
- if (result.length + line.length > maxChars) break
- result += line
+ const typeOrder: MemoryType[] = ['user', 'feedback', 'project', 'reference']
+
+ for (const type of typeOrder) {
+ const items = grouped[type]
+ if (items.length === 0) continue
+
+ const header = `### ${TYPE_SECTION_HEADERS[type]}\n`
+ if (result.length + header.length > maxChars) break
+ result += header
+
+ for (const item of items) {
+ const line = `- ${item.title}: ${item.content.substring(0, 200).replace(/\n/g, ' ')}\n`
+ if (result.length + line.length > maxChars) break
+ result += line
+ }
+ result += '\n'
}
- return result
+ return result.trim()
},
+ // ── Settings ────────────────────────────────────────────
+
+ updateMemorySettings: (updates) =>
+ set((state) => ({
+ settings: { ...state.settings, ...updates },
+ })),
+
+ // ── Export / Import ─────────────────────────────────────
+
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',
+ if (entries.length === 0) return '# Memory\n\nNo entries yet.\n'
+
+ const typeOrder: MemoryType[] = ['user', 'feedback', 'project', 'reference']
+ const typeTitles: Record<MemoryType, string> = {
+ user: 'User', feedback: 'Feedback', project: 'Project', reference: 'References',
}
- let md = '# Agent Memory\n\n'
+ let md = '# Memory\n\n'
- for (const cat of categoryOrder) {
- const catEntries = entries.filter(e => e.category === cat)
- if (catEntries.length === 0) continue
+ for (const type of typeOrder) {
+ const typeEntries = entries.filter(e => e.type === type)
+ if (typeEntries.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 += `## ${typeTitles[type]}\n\n`
+ for (const entry of typeEntries) {
+ const date = new Date(entry.updatedAt).toLocaleDateString()
+ md += `- **${entry.title}** — ${entry.content}`
+ if (entry.tags.length > 0) md += ` [${entry.tags.join(', ')}]`
+ md += ` *(${entry.source})* — ${date}\n`
}
md += '\n'
}
@@ -123,38 +295,40 @@ export const useMemoryStore = create<MemoryState>()(
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',
+ const newEntries: MemoryFile[] = []
+ let currentType: MemoryType = 'user'
+
+ const typeMap: Record<string, MemoryType> = {
+ 'user': 'user', 'feedback': 'feedback', 'project': 'project', 'references': 'reference',
+ // Legacy support
+ 'facts': 'user', 'tool results': 'reference', 'decisions': 'project', 'context': 'project',
}
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]
- }
+ if (typeMap[header]) currentType = typeMap[header]
continue
}
- // Parse list items
- const itemMatch = line.match(/^-\s+(.+?)(?:\s+\*\((.+?)\)\*)?(?:\s+—\s+.+)?$/)
+ const itemMatch = line.match(/^-\s+(?:\*\*(.+?)\*\*\s*—\s*)?(.+?)(?:\s+\[(.+?)\])?(?:\s+\*\((.+?)\)\*)?(?:\s+—\s+.+)?$/)
if (itemMatch) {
- const content = itemMatch[1].trim()
- const source = itemMatch[2] || 'import'
+ const title = itemMatch[1] || itemMatch[2].substring(0, 60)
+ const content = itemMatch[2].trim()
+ const tags = itemMatch[3] ? itemMatch[3].split(',').map(t => t.trim()) : []
+ const source = itemMatch[4] || 'import'
+
if (content) {
newEntries.push({
id: uuid(),
- category: currentCategory,
+ type: currentType,
+ title: title.substring(0, 60),
+ description: content.substring(0, 120),
content,
- timestamp: Date.now(),
+ tags,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
source,
})
}
@@ -168,7 +342,59 @@ export const useMemoryStore = create<MemoryState>()(
}))
}
},
+
+ exportAsJSON: () => {
+ const { entries, settings } = get()
+ return JSON.stringify({ entries, settings }, null, 2)
+ },
+
+ importFromJSON: (json) => {
+ try {
+ const data = JSON.parse(json)
+ if (Array.isArray(data.entries)) {
+ set((state) => ({
+ entries: [...state.entries, ...data.entries],
+ lastSynced: Date.now(),
+ }))
+ }
+ } catch {
+ console.error('Failed to parse memory JSON import')
+ }
+ },
+
+ // ── Legacy Compat ───────────────────────────────────────
+
+ addEntry: (category, content, source) => {
+ const type = MEMORY_MIGRATION_MAP[category] || 'project'
+ get().addMemory({
+ type,
+ title: content.substring(0, 60).replace(/\n/g, ' '),
+ description: content.substring(0, 120).replace(/\n/g, ' '),
+ content,
+ tags: source ? [source] : [],
+ source: source || 'agent',
+ })
+ },
+
+ getMemoryForPrompt: (query, maxChars = 2000) => {
+ // Legacy: assume 8K context for backward compat
+ return get().getMemoriesForPrompt(query, 8192)
+ },
}),
- { name: 'locally-uncensored-memory' }
+ {
+ name: 'locally-uncensored-memory',
+ version: 2,
+ migrate: (persistedState, version) => {
+ if (version < 2) {
+ return migrateV1toV2(persistedState)
+ }
+ return persistedState as MemoryState
+ },
+ partialize: (state) => ({
+ entries: state.entries,
+ settings: state.settings,
+ lastSynced: state.lastSynced,
+ }),
+ }
)
)
diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.ts
index de7ebb8c..5f36eef5 100644
--- a/src/types/agent-mode.ts
+++ b/src/types/agent-mode.ts
@@ -91,6 +91,7 @@ export type SandboxLevel = 'restricted' | 'full'
// ── Memory System ─────────────────────────────────────────────
+// Legacy categories (kept for migration)
export type MemoryCategory = 'fact' | 'tool_result' | 'decision' | 'context'
export interface MemoryEntry {
@@ -100,3 +101,50 @@ export interface MemoryEntry {
timestamp: number
source?: string // e.g. "agent:web_search", "user:manual", "auto:extraction"
}
+
+// ── Enhanced Memory System (Claude Code-inspired) ─────────────
+
+export type MemoryType = 'user' | 'feedback' | 'project' | 'reference'
+
+export interface MemoryFile {
+ id: string
+ type: MemoryType
+ title: string // ~60 chars, index-friendly
+ description: string // ~120 chars, one-line hook for relevance matching
+ content: string // full text
+ tags: string[]
+ createdAt: number
+ updatedAt: number
+ source: string // conversationId | 'manual' | 'auto:extraction'
+}
+
+export interface MemorySettings {
+ autoExtractEnabled: boolean // default false — opt-in (costs extra inference)
+ autoExtractInAllModes: boolean // default false — whether to also extract outside agent mode
+ maxMemoriesInPrompt: number // default 10
+ maxMemoryChars: number // default 3000
+}
+
+// Migration map: old category → new type
+export const MEMORY_MIGRATION_MAP: Record<MemoryCategory, MemoryType> = {
+ fact: 'user',
+ tool_result: 'reference',
+ decision: 'project',
+ context: 'project',
+}
+
+// Context-aware memory budget tiers
+export interface MemoryBudgetTier {
+ maxContext: number // upper bound of model context
+ budgetTokens: number // tokens allocated for memory
+ maxMemories: number // max entries to inject
+ typesAllowed: MemoryType[] | 'all'
+}
+
+export const MEMORY_BUDGET_TIERS: MemoryBudgetTier[] = [
+ { maxContext: 2048, budgetTokens: 0, maxMemories: 0, typesAllowed: [] },
+ { maxContext: 4096, budgetTokens: 300, maxMemories: 3, typesAllowed: ['user', 'feedback'] },
+ { maxContext: 8192, budgetTokens: 800, maxMemories: 8, typesAllowed: 'all' },
+ { maxContext: 131072, budgetTokens: 2000, maxMemories: 15, typesAllowed: 'all' },
+ { maxContext: Infinity, budgetTokens: 4000, maxMemories: 25, typesAllowed: 'all' },
+]
diff --git a/src/types/agent-workflows.ts b/src/types/agent-workflows.ts
new file mode 100644
index 00000000..dc7bc9aa
--- /dev/null
+++ b/src/types/agent-workflows.ts
@@ -0,0 +1,117 @@
+/**
+ * Agent Workflows / Chains — Type Definitions
+ *
+ * Multi-step agent sequences that can be saved, shared, and reused.
+ * Steps execute sequentially with branching and looping support.
+ */
+
+import type { MemoryType } from './agent-mode'
+
+// ── Step Types ────────────────────────────────────────────────
+
+export type WorkflowStepType = 'prompt' | 'tool' | 'condition' | 'loop' | 'user_input' | 'memory_save'
+
+export interface WorkflowStep {
+ id: string
+ type: WorkflowStepType
+ label: string
+ description?: string
+
+ // prompt step: send message to LLM
+ prompt?: string
+ allowedTools?: string[] // tool whitelist (empty = no tools, undefined = all tools)
+
+ // tool step: execute specific tool
+ toolName?: string
+ toolArgs?: Record<string, any>
+ toolArgTemplates?: Record<string, string> // supports {{variable}} interpolation
+
+ // condition step: branch based on output
+ condition?: {
+ source: 'last_output' | string // variable name or 'last_output'
+ operator: 'contains' | 'not_contains' | 'equals' | 'not_equals' | 'truthy' | 'falsy'
+ value: string
+ thenStepId: string
+ elseStepId: string
+ }
+
+ // loop step: repeat until condition
+ loop?: {
+ maxIterations: number
+ condition: {
+ source: 'last_output' | string
+ operator: 'contains' | 'not_contains' | 'equals' | 'not_equals' | 'truthy' | 'falsy'
+ value: string
+ }
+ bodyStepIds: string[]
+ }
+
+ // memory_save step: save to memory store
+ memorySave?: {
+ type: MemoryType
+ titleTemplate: string // supports {{variable}}
+ contentTemplate: string // supports {{variable}}
+ tags?: string[]
+ }
+
+ // user_input step: pause for user input
+ userInputPrompt?: string
+}
+
+// ── Workflow Definition ───────────────────────────────────────
+
+export interface AgentWorkflow {
+ id: string
+ name: string
+ description: string
+ icon: string // Lucide icon name
+ steps: WorkflowStep[]
+ variables: Record<string, string> // default variable values
+ isBuiltIn: boolean
+ createdAt: number
+ updatedAt: number
+}
+
+// ── Execution ─────────────────────────────────────────────────
+
+export type StepStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped'
+export type WorkflowStatus = 'idle' | 'running' | 'waiting_input' | 'completed' | 'failed' | 'cancelled'
+
+export interface StepResult {
+ stepId: string
+ status: StepStatus
+ output: string
+ startedAt: number
+ completedAt?: number
+ error?: string
+ toolCalls?: Array<{
+ name: string
+ args: Record<string, any>
+ result: string
+ }>
+}
+
+export interface WorkflowExecution {
+ id: string
+ workflowId: string
+ workflowName: string
+ status: WorkflowStatus
+ currentStepIndex: number
+ stepResults: StepResult[]
+ variables: Record<string, string> // runtime variable state
+ conversationId?: string
+ startedAt: number
+ completedAt?: number
+ error?: string
+}
+
+// ── Engine Callbacks ──────────────────────────────────────────
+
+export interface WorkflowEngineCallbacks {
+ onStepStart: (stepIndex: number, step: WorkflowStep) => void
+ onStepComplete: (stepIndex: number, result: StepResult) => void
+ onStepError: (stepIndex: number, error: string) => void
+ onWaitingForInput: (stepIndex: number, prompt: string) => void
+ onComplete: (results: StepResult[]) => void
+ onError: (error: string) => void
+}