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.

refactor(agent): remove dead legacy ReAct chain + unwired modules

purple8158bedeae0e
diff --git a/src/api/__tests__/agents-parsing.test.ts b/src/api/__tests__/agents-parsing.test.ts
deleted file mode 100644
index 9aa0147c..00000000
--- a/src/api/__tests__/agents-parsing.test.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import {
- AGENT_TOOLS,
- buildReActPrompt,
- buildJsonRetryPrompt,
- parseAgentResponse,
-} from '../agents'
-import type { AgentLogEntry } from '../../types/agents'
-
-describe('agents — pure functions', () => {
- // ─── AGENT_TOOLS ───
-
- describe('AGENT_TOOLS', () => {
- it('has exactly 7 tools (web_search, web_fetch, get_current_time, file_read, file_write, code_execute, image_generate)', () => {
- expect(AGENT_TOOLS).toHaveLength(7)
- })
-
- it('contains all 7 tool names', () => {
- const names = AGENT_TOOLS.map((t) => t.name)
- expect(names).toContain('web_search')
- expect(names).toContain('web_fetch')
- expect(names).toContain('get_current_time')
- expect(names).toContain('file_read')
- expect(names).toContain('file_write')
- expect(names).toContain('code_execute')
- expect(names).toContain('image_generate')
- })
-
- it('every tool has name, description, and parameters array', () => {
- for (const tool of AGENT_TOOLS) {
- expect(typeof tool.name).toBe('string')
- expect(tool.name.length).toBeGreaterThan(0)
- expect(typeof tool.description).toBe('string')
- expect(tool.description.length).toBeGreaterThan(0)
- expect(Array.isArray(tool.parameters)).toBe(true)
- // get_current_time takes zero args — everything else has at least one.
- if (tool.name !== 'get_current_time') {
- expect(tool.parameters.length).toBeGreaterThan(0)
- } else {
- expect(tool.parameters.length).toBe(0)
- }
- }
- })
-
- it('every parameter has name, type, description, required', () => {
- for (const tool of AGENT_TOOLS) {
- for (const param of tool.parameters) {
- expect(typeof param.name).toBe('string')
- expect(typeof param.type).toBe('string')
- expect(typeof param.description).toBe('string')
- expect(typeof param.required).toBe('boolean')
- }
- }
- })
-
- it('file_write and code_execute require approval', () => {
- const fileWrite = AGENT_TOOLS.find((t) => t.name === 'file_write')
- const codeExec = AGENT_TOOLS.find((t) => t.name === 'code_execute')
- expect(fileWrite?.requiresApproval).toBe(true)
- expect(codeExec?.requiresApproval).toBe(true)
- })
-
- it('web_search, web_fetch, file_read, image_generate do not require approval', () => {
- const noApproval = ['web_search', 'web_fetch', 'file_read', 'image_generate']
- for (const name of noApproval) {
- const tool = AGENT_TOOLS.find((t) => t.name === name)
- expect(tool?.requiresApproval).toBe(false)
- }
- })
- })
-
- // ─── buildReActPrompt ───
-
- describe('buildReActPrompt', () => {
- it('output contains the goal text', () => {
- const prompt = buildReActPrompt('Find weather data', AGENT_TOOLS, [])
- expect(prompt).toContain('Find weather data')
- })
-
- it('output contains tool names and descriptions', () => {
- const prompt = buildReActPrompt('test', AGENT_TOOLS, [])
- expect(prompt).toContain('web_search')
- expect(prompt).toContain('file_read')
- expect(prompt).toContain('file_write')
- expect(prompt).toContain('code_execute')
- expect(prompt).toContain('image_generate')
- })
-
- it('output contains parameter details for tools', () => {
- const prompt = buildReActPrompt('test', AGENT_TOOLS, [])
- expect(prompt).toContain('query')
- expect(prompt).toContain('path')
- expect(prompt).toContain('content')
- expect(prompt).toContain('code')
- expect(prompt).toContain('prompt')
- })
-
- it('output contains JSON format instructions', () => {
- const prompt = buildReActPrompt('test', AGENT_TOOLS, [])
- expect(prompt).toContain('"thought"')
- expect(prompt).toContain('"action"')
- expect(prompt).toContain('"finish"')
- })
-
- it('includes history entries when present', () => {
- const history: AgentLogEntry[] = [
- { type: 'thought', content: 'I should search the web', timestamp: Date.now() },
- { type: 'action', content: 'web_search({"query":"test"})', timestamp: Date.now() },
- { type: 'observation', content: 'Found 3 results', timestamp: Date.now() },
- ]
- const prompt = buildReActPrompt('test', AGENT_TOOLS, history)
- expect(prompt).toContain('Thought: I should search the web')
- expect(prompt).toContain('Action: web_search')
- expect(prompt).toContain('Observation: Found 3 results')
- expect(prompt).toContain('Continue from where you left off')
- })
-
- it('says "Begin working" when history is empty', () => {
- const prompt = buildReActPrompt('test', AGENT_TOOLS, [])
- expect(prompt).toContain('Begin working on the goal now')
- })
-
- it('includes error entries from history', () => {
- const history: AgentLogEntry[] = [
- { type: 'error', content: 'Tool failed: network error', timestamp: Date.now() },
- ]
- const prompt = buildReActPrompt('test', AGENT_TOOLS, history)
- expect(prompt).toContain('Error: Tool failed: network error')
- })
-
- it('includes user_input entries from history', () => {
- const history: AgentLogEntry[] = [
- { type: 'user_input', content: 'Please try again', timestamp: Date.now() },
- ]
- const prompt = buildReActPrompt('test', AGENT_TOOLS, history)
- expect(prompt).toContain('User: Please try again')
- })
- })
-
- // ─── buildJsonRetryPrompt ───
-
- describe('buildJsonRetryPrompt', () => {
- it('mentions the original response was unparsable', () => {
- const prompt = buildJsonRetryPrompt('some garbage text')
- expect(prompt).toContain('could not be parsed as valid JSON')
- })
-
- it('includes the original response text', () => {
- const prompt = buildJsonRetryPrompt('I think we should search for cats')
- expect(prompt).toContain('I think we should search for cats')
- })
-
- it('truncates original response at 500 characters', () => {
- const longText = 'A'.repeat(1000)
- const prompt = buildJsonRetryPrompt(longText)
- // The original response is sliced to 500 chars
- const aCount = (prompt.match(/A/g) || []).length
- expect(aCount).toBe(500)
- })
-
- it('contains JSON format instructions', () => {
- const prompt = buildJsonRetryPrompt('oops')
- expect(prompt).toContain('"thought"')
- expect(prompt).toContain('"action"')
- expect(prompt).toContain('"finish"')
- })
- })
-
- // ─── parseAgentResponse ───
-
- describe('parseAgentResponse', () => {
- it('parses valid JSON response with action', () => {
- const json = JSON.stringify({
- thought: 'I need to search',
- action: 'web_search',
- args: { query: 'cats' },
- })
- const result = parseAgentResponse(json)
- expect(result.thought).toBe('I need to search')
- expect(result.action).toBe('web_search')
- expect(result.args).toEqual({ query: 'cats' })
- })
-
- it('parses JSON inside a code block', () => {
- const response = '```json\n{"thought": "testing", "action": "file_read", "args": {"path": "test.txt"}}\n```'
- const result = parseAgentResponse(response)
- expect(result.thought).toBe('testing')
- expect(result.action).toBe('file_read')
- expect(result.args).toEqual({ path: 'test.txt' })
- })
-
- it('parses JSON inside a bare code block (no json tag)', () => {
- const response = '```\n{"thought": "bare", "action": "finish", "answer": "done"}\n```'
- const result = parseAgentResponse(response)
- expect(result.thought).toBe('bare')
- expect(result.action).toBe('finish')
- expect(result.answer).toBe('done')
- })
-
- it('handles plain thought response (no JSON)', () => {
- const response = 'I am just thinking about the problem and have no action to take.'
- const result = parseAgentResponse(response)
- expect(result.thought).toBe(response)
- expect(result.action).toBe('continue')
- expect(result.args).toEqual({})
- })
-
- it('handles response with final answer', () => {
- const json = JSON.stringify({
- thought: 'Task complete',
- action: 'finish',
- answer: 'The weather is sunny',
- })
- const result = parseAgentResponse(json)
- expect(result.action).toBe('finish')
- expect(result.answer).toBe('The weather is sunny')
- })
-
- it('handles response with only thought (no action key)', () => {
- const json = JSON.stringify({ thought: 'Just thinking' })
- const result = parseAgentResponse(json)
- expect(result.thought).toBe('Just thinking')
- expect(result.action).toBe('continue')
- })
-
- it('handles empty response', () => {
- const result = parseAgentResponse('')
- expect(result.action).toBe('continue')
- expect(result.thought).toBe('')
- })
-
- it('normalizes action name to lowercase', () => {
- const json = JSON.stringify({
- thought: 'test',
- action: 'Web_Search',
- args: { query: 'test' },
- })
- const result = parseAgentResponse(json)
- expect(result.action).toBe('web_search')
- })
-
- it('handles alternative field names: thinking, tool, arguments', () => {
- const json = JSON.stringify({
- thinking: 'alternative thinking',
- tool: 'code_execute',
- arguments: { code: 'print(1)' },
- })
- const result = parseAgentResponse(json)
- expect(result.thought).toBe('alternative thinking')
- expect(result.action).toBe('code_execute')
- expect(result.args).toEqual({ code: 'print(1)' })
- })
-
- it('handles alternative field: reasoning', () => {
- const json = JSON.stringify({
- reasoning: 'my reasoning',
- action: 'finish',
- final_answer: 'all done',
- })
- const result = parseAgentResponse(json)
- expect(result.thought).toBe('my reasoning')
- expect(result.answer).toBe('all done')
- })
-
- it('handles alternative field: parameters (as args)', () => {
- const json = JSON.stringify({
- thought: 'test',
- action: 'file_write',
- parameters: { path: 'a.txt', content: 'hello' },
- })
- const result = parseAgentResponse(json)
- expect(result.args).toEqual({ path: 'a.txt', content: 'hello' })
- })
-
- it('handles alternative field: input (as args)', () => {
- const json = JSON.stringify({
- thought: 'test',
- action: 'web_search',
- input: { query: 'dogs' },
- })
- const result = parseAgentResponse(json)
- expect(result.args).toEqual({ query: 'dogs' })
- })
-
- it('recovers from malformed JSON with regex fallback', () => {
- const response = 'Here is my plan:\n"thought": "search for info"\n"action": "web_search"\n"answer": "found it"'
- const result = parseAgentResponse(response)
- expect(result.thought).toBe('search for info')
- expect(result.action).toBe('web_search')
- expect(result.answer).toBe('found it')
- })
-
- it('truncates long plain-text thought at 500 chars', () => {
- const longText = 'B'.repeat(1000)
- const result = parseAgentResponse(longText)
- expect(result.thought).toHaveLength(500)
- expect(result.action).toBe('continue')
- })
-
- it('handles JSON with extra text before and after', () => {
- const response = 'Sure, here is my response:\n{"thought": "mixed", "action": "finish", "answer": "ok"}\nThat was my answer.'
- const result = parseAgentResponse(response)
- expect(result.thought).toBe('mixed')
- expect(result.action).toBe('finish')
- expect(result.answer).toBe('ok')
- })
- })
-})
diff --git a/src/api/agents.ts b/src/api/agents.ts
index 0ded4d31..4658eca9 100644
--- a/src/api/agents.ts
+++ b/src/api/agents.ts
@@ -1,413 +1,17 @@
-import type { Tool, ToolName, AgentLogEntry } from "../types/agents";
-import { backendCall, ollamaUrl, localFetch } from "./backend";
-
-export const AGENT_TOOLS: Tool[] = [
- {
- name: "web_search",
- description:
- "Search the web. Returns a LIST of candidate results (title + URL + short snippet). The snippet alone is almost never enough — when the user needs an answer grounded in a specific page, follow up with `web_fetch(url)` on the best match to read the actual content.",
- parameters: [
- {
- name: "query",
- type: "string",
- description: "The search query string",
- required: true,
- },
- {
- name: "maxResults",
- type: "number",
- description: "Maximum number of results to return (default: 5)",
- required: false,
- },
- ],
- requiresApproval: false,
- },
- {
- name: "web_fetch",
- description:
- "Fetch a web page and return its readable text content (up to ~24 000 characters). Use this AFTER web_search when you need the actual article / documentation / page body, not just the snippet. HTML is stripped, <script>/<style>/<nav>/<footer> are removed, paragraphs preserved. Refuses private / loopback addresses.",
- parameters: [
- {
- name: "url",
- type: "string",
- description: "Full URL to fetch (must start with http:// or https://)",
- required: true,
- },
- ],
- requiresApproval: false,
- },
- {
- name: "get_current_time",
- description:
- "Return the user's current local date, time and timezone. Use this FIRST for any 'what day / time / date is it' question — do NOT web_search for it. Zero arguments.",
- parameters: [],
- requiresApproval: false,
- },
- {
- name: "file_read",
- description:
- "Read the contents of a file from the local filesystem within the agent workspace.",
- parameters: [
- {
- name: "path",
- type: "string",
- description: "Relative path to the file within the workspace",
- required: true,
- },
- ],
- requiresApproval: false,
- },
- {
- name: "file_write",
- description:
- "Write content to a file in the agent workspace. Creates the file if it does not exist, overwrites if it does.",
- parameters: [
- {
- name: "path",
- type: "string",
- description: "Relative path to the file within the workspace",
- required: true,
- },
- {
- name: "content",
- type: "string",
- description: "The content to write to the file",
- required: true,
- },
- ],
- requiresApproval: true,
- },
- {
- name: "code_execute",
- description:
- "Execute code in a sandboxed environment. Supports Python and shell commands. Returns stdout, stderr, and exit code.",
- parameters: [
- {
- name: "code",
- type: "string",
- description: "The code to execute",
- required: true,
- },
- {
- name: "language",
- type: "string",
- description: 'Programming language: "python" or "shell" (default: "python")',
- required: false,
- },
- ],
- requiresApproval: true,
- },
- {
- name: "image_generate",
- description:
- "Generate an image from a text description. Delegates to the Create tab for image generation.",
- parameters: [
- {
- name: "prompt",
- type: "string",
- description: "Text description of the image to generate",
- required: true,
- },
- {
- name: "negativePrompt",
- type: "string",
- description: "Things to avoid in the generated image",
- required: false,
- },
- ],
- requiresApproval: false,
- },
-];
-
-export function buildReActPrompt(
- goal: string,
- tools: Tool[],
- history: AgentLogEntry[]
-): string {
- const toolDescriptions = tools
- .map((t) => {
- const params = t.parameters
- .map(
- (p) =>
- ` - ${p.name} (${p.type}${p.required ? ", required" : ", optional"}): ${p.description}`
- )
- .join("\n");
- return ` ${t.name}: ${t.description}\n Parameters:\n${params}`;
- })
- .join("\n\n");
-
- const historyText = history
- .map((entry) => {
- switch (entry.type) {
- case "thought":
- return `Thought: ${entry.content}`;
- case "action":
- return `Action: ${entry.content}`;
- case "observation":
- return `Observation: ${entry.content}`;
- case "error":
- return `Error: ${entry.content}`;
- case "user_input":
- return `User: ${entry.content}`;
- default:
- return entry.content;
- }
- })
- .join("\n");
-
- const codeBlockOpen = "``" + "`json";
- const codeBlockClose = "``" + "`";
-
- return `You are an autonomous AI agent. Your goal is: ${goal}
-
-You have access to the following tools:
-
-${toolDescriptions}
-
-You must respond with a JSON object in one of these two formats:
-
-To use a tool:
-${codeBlockOpen}
-{"thought": "your reasoning about what to do next", "action": "tool_name", "args": {"param1": "value1"}}
-${codeBlockClose}
-
-To finish the task:
-${codeBlockOpen}
-{"thought": "your final reasoning", "action": "finish", "answer": "your final answer or summary of what was accomplished"}
-${codeBlockClose}
-
-Rules:
-- Always include a "thought" explaining your reasoning
-- Use exactly one action per response
-- Only use tools from the list above
-- If a tool returns an error, try a different approach
-- When the goal is accomplished, use the "finish" action
-- Be concise and efficient
-
-${historyText ? `\nPrevious steps:\n${historyText}\n\nContinue from where you left off.` : "Begin working on the goal now."}`;
-}
-
-/**
- * Build a simplified retry prompt when the LLM failed to produce valid JSON.
- */
-export function buildJsonRetryPrompt(originalResponse: string): string {
- return `Your previous response could not be parsed as valid JSON. Please respond with ONLY a valid JSON object, no other text.
-
-Your previous (unparsable) response was:
-${originalResponse.slice(0, 500)}
-
-Respond with ONLY a JSON object in this exact format:
-{"thought": "your reasoning", "action": "tool_name", "args": {"param": "value"}}
-
-Or to finish:
-{"thought": "your reasoning", "action": "finish", "answer": "your answer"}`;
-}
+import { ollamaUrl, localFetch } from "./backend";
/**
- * Robustly parse an LLM agent response into structured thought/action/args.
+ * Minimal non-streaming chat helper — one request, one response, no tools.
*
- * Handles:
- * 1. JSON in code blocks
- * 2. Multiple JSON objects (takes the first)
- * 3. Partial/broken JSON via regex fallback
- * 4. No JSON at all (treats as thought with action "continue")
- * 5. Action name casing normalization
- * 6. Alternative field names (thinking, reasoning, tool, arguments, parameters, etc.)
+ * The legacy ReAct agent that used to fill this file (AGENT_TOOLS,
+ * buildReActPrompt, buildJsonRetryPrompt, parseAgentResponse, executeTool, and
+ * the AgentView/useAgent/agentStore chain that consumed them) was removed in
+ * 2.5.9: it had been dead since the Codex + Agent-workflow stacks replaced it,
+ * with zero reachable references. Only this helper survives — still used by
+ * useCodex, useAgentChat and the workflow engine for one-shot "give me the
+ * whole answer at once" calls (plan synthesis, JSON repair) where streaming
+ * and the tool loop are not wanted.
*/
-export function parseAgentResponse(response: string): {
- thought: string;
- action: string;
- args?: Record<string, any>;
- answer?: string;
-} {
- // 1. Try to find JSON in code blocks first
- const codeBlockMatch = response.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
- const jsonCandidate = codeBlockMatch ? codeBlockMatch[1] : response;
-
- // 2. Try to find a JSON object
- const jsonMatch = jsonCandidate.match(/\{[\s\S]*\}/);
- if (jsonMatch) {
- try {
- const parsed = JSON.parse(jsonMatch[0]);
- return {
- thought: parsed.thought || parsed.thinking || parsed.reasoning || "",
- action: (parsed.action || parsed.tool || "continue").toLowerCase().trim(),
- args: parsed.args || parsed.arguments || parsed.parameters || parsed.input || {},
- answer: parsed.answer || parsed.final_answer || parsed.response || undefined,
- };
- } catch {
- // JSON parse failed - if there is a nested object, try the first one
- const firstObjMatch = jsonCandidate.match(/\{[^{}]*\}/);
- if (firstObjMatch && firstObjMatch[0] !== jsonMatch[0]) {
- try {
- const parsed = JSON.parse(firstObjMatch[0]);
- return {
- thought: parsed.thought || parsed.thinking || parsed.reasoning || "",
- action: (parsed.action || parsed.tool || "continue").toLowerCase().trim(),
- args: parsed.args || parsed.arguments || parsed.parameters || parsed.input || {},
- answer: parsed.answer || parsed.final_answer || parsed.response || undefined,
- };
- } catch {
- // Fall through to regex
- }
- }
- }
- }
-
- // 3. Regex fallback for individual fields
- const thoughtMatch = response.match(/["']?(?:thought|thinking|reasoning)["']?\s*[:=]\s*["']([^"']+)["']/i);
- const actionMatch = response.match(/["']?(?:action|tool)["']?\s*[:=]\s*["']([^"']+)["']/i);
- const answerMatch = response.match(/["']?(?:answer|final_answer|response)["']?\s*[:=]\s*["']([^"']+)["']/i);
-
- if (actionMatch) {
- return {
- thought: thoughtMatch?.[1] || "",
- action: actionMatch[1].toLowerCase().trim(),
- args: {},
- answer: answerMatch?.[1],
- };
- }
-
- // 4. Total fallback: treat entire response as a thought
- return {
- thought: response.slice(0, 500),
- action: "continue",
- args: {},
- };
-}
-
-export async function executeTool(
- tool: ToolName,
- args: Record<string, any>
-): Promise<string> {
- // Thread the active agent loop's chat id through to Rust so relative paths
- // land in the per-chat workspace (~/agent-workspace/<chatId>/) instead of
- // the shared `default/` fallback.
- const { getActiveChatId } = await import("./agent-context");
- const chatId = getActiveChatId() || undefined;
-
- switch (tool) {
- case "code_execute": {
- const data = await backendCall("execute_code", {
- code: args.code,
- timeout: 30000,
- chatId,
- });
- const output = data.stdout || "";
- const err = data.stderr || "";
- if (data.exitCode && data.exitCode !== 0) return `Error (${data.exitCode}):\n${err || output}`;
- return output || (err ? `stderr: ${err}` : "Done.");
- }
-
- case "file_read": {
- const data = await backendCall("file_read", { path: args.path, chatId });
- return data.content || "";
- }
-
- case "file_write": {
- // Rust returns {status: 'saved', path: <absolute>}. Return the real
- // resolved path so the model knows where the file actually landed.
- // The old "File written successfully" fallback was a silent lie when
- // Rust failed — surfaced as ✓ in the UI with no file on disk.
- const data = await backendCall("file_write", { path: args.path, content: args.content, chatId });
- if (data.status === "saved" && data.path) return `File saved: ${data.path}`;
- return data.message || JSON.stringify(data);
- }
-
- case "web_search": {
- // Pass search provider config from settings
- const { useSettingsStore } = await import('../stores/settingsStore')
- const searchSettings = useSettingsStore.getState().settings
- const data = await backendCall("web_search", {
- query: args.query,
- count: args.maxResults || 5,
- provider: searchSettings.searchProvider || 'auto',
- braveApiKey: searchSettings.braveApiKey || '',
- tavilyApiKey: searchSettings.tavilyApiKey || '',
- });
- if (Array.isArray(data.results)) {
- return data.results
- .map(
- (r: any, i: number) =>
- `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`
- )
- .join("\n\n");
- }
- return JSON.stringify(data);
- }
-
- case "web_fetch": {
- const url = typeof args.url === 'string' ? args.url.trim() : ''
- if (!url) return "Error: web_fetch requires a `url` argument."
- try {
- const data = await backendCall<{ url: string; status: number; contentType: string; title: string; text: string; truncated: boolean }>(
- "web_fetch",
- { url }
- )
- const parts: string[] = []
- if (data.title) parts.push(`Title: ${data.title}`)
- parts.push(`URL: ${data.url}`)
- parts.push(`Status: ${data.status}${data.contentType ? ` (${data.contentType.split(';')[0]})` : ''}`)
- parts.push('')
- parts.push(data.text || '(empty body)')
- if (data.truncated) parts.push('\n…(truncated to 24 000 chars)')
- return parts.join('\n')
- } catch (e) {
- return `Error: web_fetch failed — ${e instanceof Error ? e.message : String(e)}`
- }
- }
-
- case "get_current_time": {
- try {
- const data = await backendCall<{ unix: number; iso_local: string; iso_utc: string; timezone: string; timezone_offset: number }>(
- "get_current_time",
- {}
- )
- return `Local: ${data.iso_local} ${data.timezone}\nUTC: ${data.iso_utc}\nUnix: ${data.unix}`
- } catch (e) {
- return `Error: get_current_time failed — ${e instanceof Error ? e.message : String(e)}`
- }
- }
-
- case "image_generate": {
- const prompt = args.prompt || args.description || ''
- if (!prompt) return "Error: No prompt provided for image generation."
- try {
- const { buildDynamicWorkflow } = await import('./dynamic-workflow')
- const { submitWorkflow, getHistory, classifyModel, getImageModels } = await import('./comfyui')
- const models = await getImageModels()
- if (models.length === 0) return "Error: No image models available in ComfyUI."
- const model = models[0]
- const workflow = await buildDynamicWorkflow({
- prompt, negativePrompt: '', model: model.name,
- sampler: 'euler', scheduler: 'normal', steps: 20, cfgScale: 7,
- width: 1024, height: 1024, seed: -1, batchSize: 1,
- }, classifyModel(model.name))
- const promptId = await submitWorkflow(workflow)
- for (let i = 0; i < 300; i++) {
- await new Promise(r => setTimeout(r, 1000))
- const history = await getHistory(promptId)
- if (history?.status?.completed) {
- const outputs = history.outputs ?? {}
- for (const nodeId of Object.keys(outputs)) {
- const files = [...(outputs[nodeId].images ?? []), ...(outputs[nodeId].gifs ?? [])]
- if (files.length > 0) return `Image generated: ${files[0].filename} (prompt: "${prompt}")`
- }
- return "Generation completed but no output produced."
- }
- if (history?.status?.status_str === 'error') return `Generation failed: ${history.status.messages?.[0]?.[1]?.message || 'Unknown error'}`
- }
- return "Generation timed out after 5 minutes."
- } catch (err) {
- return `Generation failed: ${err instanceof Error ? err.message : String(err)}`
- }
- }
-
- default:
- throw new Error(`Unknown tool: ${tool}`);
- }
-}
-
export async function chatNonStreaming(
model: string,
messages: { role: string; content: string }[],
diff --git a/src/api/agents/__tests__/format-capability.test.ts b/src/api/agents/__tests__/format-capability.test.ts
deleted file mode 100644
index a79f2fe1..00000000
--- a/src/api/agents/__tests__/format-capability.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest'
-import {
- getFormatCapability,
- markFormatSupported,
- markFormatUnsupported,
- clearFormatCapability,
- resetFormatCapabilityCache,
- probeFormatSupport,
-} from '../format-capability'
-
-// Minimal localStorage polyfill — tests run under vitest node env where
-// localStorage is absent. The module itself gracefully no-ops without it,
-// but we want to validate cache behaviour, so we install a stub.
-const installLocalStorageStub = () => {
- const store: Record<string, string> = {}
- ;(globalThis as any).localStorage = {
- getItem: (k: string) => (k in store ? store[k] : null),
- setItem: (k: string, v: string) => {
- store[k] = v
- },
- removeItem: (k: string) => {
- delete store[k]
- },
- clear: () => {
- for (const k of Object.keys(store)) delete store[k]
- },
- }
-}
-
-describe('format-capability — cache', () => {
- beforeEach(() => {
- installLocalStorageStub()
- resetFormatCapabilityCache()
- })
-
- it('returns "unknown" for a model never probed', () => {
- expect(getFormatCapability('qwen3:8b')).toBe('unknown')
- })
-
- it('records supported and returns "supported"', () => {
- markFormatSupported('qwen3:8b')
- expect(getFormatCapability('qwen3:8b')).toBe('supported')
- })
-
- it('records unsupported and returns "unsupported" within TTL', () => {
- markFormatUnsupported('oldmodel:latest')
- expect(getFormatCapability('oldmodel:latest')).toBe('unsupported')
- })
-
- it('treats unsupported entries older than TTL as "unknown" (re-probe)', () => {
- const past = Date.now() - 25 * 60 * 60 * 1000 // 25h ago, past 24h TTL
- ;(globalThis as any).localStorage.setItem(
- 'lu-format-capability-v1',
- JSON.stringify({ 'oldmodel:latest': { capability: 'unsupported', checkedAt: past } })
- )
- expect(getFormatCapability('oldmodel:latest')).toBe('unknown')
- })
-
- it('clearFormatCapability removes a single entry', () => {
- markFormatSupported('a')
- markFormatSupported('b')
- clearFormatCapability('a')
- expect(getFormatCapability('a')).toBe('unknown')
- expect(getFormatCapability('b')).toBe('supported')
- })
-
- it('isolates models by name', () => {
- markFormatSupported('a')
- markFormatUnsupported('b')
- expect(getFormatCapability('a')).toBe('supported')
- expect(getFormatCapability('b')).toBe('unsupported')
- })
-
- it('survives corrupted cache gracefully', () => {
- ;(globalThis as any).localStorage.setItem('lu-format-capability-v1', '{not-json')
- expect(getFormatCapability('a')).toBe('unknown')
- // And subsequent writes overwrite cleanly.
- markFormatSupported('a')
- expect(getFormatCapability('a')).toBe('supported')
- })
-})
-
-describe('format-capability — probeFormatSupport', () => {
- beforeEach(() => {
- installLocalStorageStub()
- resetFormatCapabilityCache()
- })
-
- it('marks supported on HTTP 200 with parseable JSON response', async () => {
- const fetchStub = vi.fn(async () =>
- new Response(JSON.stringify({ response: '{"ok":true}' }), { status: 200 })
- ) as any
- const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
- expect(result).toBe('supported')
- expect(getFormatCapability('m')).toBe('supported')
- })
-
- it('marks unsupported on HTTP 200 but non-JSON response text', async () => {
- const fetchStub = vi.fn(async () =>
- new Response(JSON.stringify({ response: 'hello, not JSON' }), { status: 200 })
- ) as any
- const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
- expect(result).toBe('unsupported')
- expect(getFormatCapability('m')).toBe('unsupported')
- })
-
- it('marks unsupported on HTTP error status', async () => {
- const fetchStub = vi.fn(async () =>
- new Response('{"error":"bad"}', { status: 500 })
- ) as any
- const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
- expect(result).toBe('unsupported')
- })
-
- it('marks unsupported on abort (timeout)', async () => {
- const fetchStub = vi.fn((_url, opts: any) => {
- return new Promise((_resolve, reject) => {
- opts?.signal?.addEventListener('abort', () => {
- const err: any = new Error('aborted')
- err.name = 'AbortError'
- reject(err)
- })
- })
- }) as any
- const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
- expect(result).toBe('unsupported')
- expect(getFormatCapability('m')).toBe('unsupported')
- }, 10000)
-
- it('re-throws on non-abort network errors (does not corrupt cache)', async () => {
- const fetchStub = vi.fn(async () => {
- throw new Error('ECONNREFUSED')
- }) as any
- await expect(
- probeFormatSupport('m', 'http://localhost:11434', fetchStub)
- ).rejects.toThrow('ECONNREFUSED')
- expect(getFormatCapability('m')).toBe('unknown')
- })
-
- it('strips trailing slash from base URL', async () => {
- const fetchStub = vi.fn(async (url: string) => {
- expect(url).toBe('http://localhost:11434/api/generate')
- return new Response(JSON.stringify({ response: '{"ok":1}' }), { status: 200 })
- }) as any
- await probeFormatSupport('m', 'http://localhost:11434/', fetchStub)
- expect(fetchStub).toHaveBeenCalled()
- })
-})
diff --git a/src/api/agents/__tests__/partial-args-accumulator.test.ts b/src/api/agents/__tests__/partial-args-accumulator.test.ts
deleted file mode 100644
index 256c3a2b..00000000
--- a/src/api/agents/__tests__/partial-args-accumulator.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { describe, it, expect } from 'vitest'
-import {
- parsePartialJson,
- PartialArgsAccumulator,
- __internal,
-} from '../partial-args-accumulator'
-
-describe('partial-args-accumulator — parsePartialJson', () => {
- it('empty buffer → complete=false, partial={}', () => {
- const r = parsePartialJson('')
- expect(r.complete).toBe(false)
- expect(r.partial).toEqual({})
- })
-
- it('whitespace-only buffer → partial={}', () => {
- expect(parsePartialJson(' \n').partial).toEqual({})
- })
-
- it('complete valid JSON → complete=true + parsed object', () => {
- const r = parsePartialJson('{"a":1,"b":"x"}')
- expect(r.complete).toBe(true)
- expect(r.partial).toEqual({ a: 1, b: 'x' })
- })
-
- it('missing closing brace → partial object', () => {
- const r = parsePartialJson('{"a":1,"b":"x"')
- expect(r.complete).toBe(false)
- expect(r.partial).toEqual({ a: 1, b: 'x' })
- })
-
- it('missing closing bracket in value array → partial with array closed', () => {
- const r = parsePartialJson('{"items":[1,2,3')
- expect(r.complete).toBe(false)
- expect(r.partial).toEqual({ items: [1, 2, 3] })
- })
-
- it('open string literal mid-value → close the string + partial', () => {
- const r = parsePartialJson('{"q":"hello wor')
- expect(r.complete).toBe(false)
- expect(r.partial.q).toMatch(/^hello wor/)
- })
-
- it('trailing comma after last value → stripped, partial still returned', () => {
- const r = parsePartialJson('{"a":1,')
- expect(r.complete).toBe(false)
- expect(r.partial).toEqual({ a: 1 })
- })
-
- it('nested objects partially streamed', () => {
- const r = parsePartialJson('{"outer":{"inner":42')
- expect(r.partial).toEqual({ outer: { inner: 42 } })
- })
-
- it('broken input that cannot be closed → partial={}', () => {
- const r = parsePartialJson('{"a":@#@invalid')
- expect(r.partial).toEqual({})
- })
-
- it('array at top level → treated as non-object (returns {})', () => {
- const r = parsePartialJson('[1,2,3]')
- expect(r.partial).toEqual({})
- expect(r.complete).toBe(false)
- })
-
- it('escaped quotes inside string survive closure', () => {
- // Raw stream: `{"msg":"she said \"hi\"` — the two \" pairs are both
- // escaped, so the string value ends up as `she said "hi"`. Closure
- // appends a `"` + `}` to finalize the JSON.
- const r = parsePartialJson('{"msg":"she said \\"hi\\"')
- expect(r.partial.msg).toBe('she said "hi"')
- })
-})
-
-describe('partial-args-accumulator — PartialArgsAccumulator', () => {
- it('appends chunks and reflects them in snapshot', () => {
- const acc = new PartialArgsAccumulator()
- expect(acc.length()).toBe(0)
- acc.push('{"q":"')
- acc.push('hel')
- acc.push('lo"}')
- expect(acc.length()).toBeGreaterThan(0)
- const snap = acc.snapshot()
- expect(snap.complete).toBe(true)
- expect(snap.partial).toEqual({ q: 'hello' })
- })
-
- it('set() overwrites the buffer', () => {
- const acc = new PartialArgsAccumulator()
- acc.push('{"a":1}')
- acc.set('{"b":2}')
- const snap = acc.snapshot()
- expect(snap.partial).toEqual({ b: 2 })
- })
-
- it('reset() clears buffer', () => {
- const acc = new PartialArgsAccumulator()
- acc.push('{"a":1}')
- acc.reset()
- expect(acc.length()).toBe(0)
- expect(acc.snapshot().partial).toEqual({})
- })
-
- it('empty chunk push is a no-op', () => {
- const acc = new PartialArgsAccumulator()
- acc.push('')
- acc.push('{"a":1}')
- expect(acc.length()).toBe(7)
- })
-})
-
-describe('partial-args-accumulator — closeOpenStructures (internal)', () => {
- it('closes open strings', () => {
- expect(__internal.closeOpenStructures('{"q":"abc')).toBe('{"q":"abc"}')
- })
- it('closes nested objects + strings', () => {
- expect(__internal.closeOpenStructures('{"a":{"b":"c')).toBe('{"a":{"b":"c"}}')
- })
- it('closes arrays', () => {
- expect(__internal.closeOpenStructures('{"xs":[1,2')).toBe('{"xs":[1,2]}')
- })
- it('strips trailing comma before closing', () => {
- expect(__internal.closeOpenStructures('{"a":1,')).toBe('{"a":1}')
- })
- it('handles escaped backslash before quote correctly', () => {
- expect(__internal.closeOpenStructures('{"p":"C:\\\\x')).toBe('{"p":"C:\\\\x"}')
- })
-})
diff --git a/src/api/agents/format-capability.ts b/src/api/agents/format-capability.ts
deleted file mode 100644
index 6deea141..00000000
--- a/src/api/agents/format-capability.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Phase 4 (v2.4.0) — Ollama `format` capability probe.
- *
- * Ollama supports a `format` request parameter for constrained JSON output
- * (`format: "json"` or, as of 0.5+, `format: <JSON-Schema>` for strict
- * structured output). Support varies by MODEL, not by server version:
- * - Most modern models (Qwen 3, Llama 3.1+, Gemma 3/4) handle it cleanly.
- * - Some older quants crash, refuse, or hang the daemon when given it.
- *
- * To stay safe we probe per-model the first time we would use `format`,
- * cache the result in localStorage, and silently fall back to unconstrained
- * generation on failure.
- *
- * This module is deliberately pure + side-effect-light — it exposes a probe
- * entry point and two cache helpers. Actual probing is done by the caller
- * (ollama-provider) with a tiny request under a short timeout.
- */
-
-const STORAGE_KEY = 'lu-format-capability-v1'
-/** How long a cached negative-probe result is considered valid. */
-const NEGATIVE_TTL_MS = 24 * 60 * 60 * 1000
-
-export type FormatCapability = 'supported' | 'unsupported' | 'unknown'
-
-type CacheEntry = {
- capability: 'supported' | 'unsupported'
- checkedAt: number
-}
-
-type CacheShape = Record<string, CacheEntry>
-
-function loadCache(): CacheShape {
- try {
- if (typeof localStorage === 'undefined') return {}
- const raw = localStorage.getItem(STORAGE_KEY)
- if (!raw) return {}
- const parsed = JSON.parse(raw)
- return parsed && typeof parsed === 'object' ? parsed : {}
- } catch {
- return {}
- }
-}
-
-function saveCache(cache: CacheShape): void {
- try {
- if (typeof localStorage === 'undefined') return
- localStorage.setItem(STORAGE_KEY, JSON.stringify(cache))
- } catch {
- // Quota errors etc. — swallowed; capability will re-probe next session.
- }
-}
-
-/**
- * Returns the cached capability for a model. 'unknown' means the caller
- * should probe before sending `format`. Negative results older than
- * NEGATIVE_TTL_MS are treated as 'unknown' so models that once failed can
- * be re-tried (Ollama upgrades, model re-quantisation, etc.).
- */
-export function getFormatCapability(model: string): FormatCapability {
- const cache = loadCache()
- const entry = cache[model]
- if (!entry) return 'unknown'
- if (entry.capability === 'supported') return 'supported'
- if (Date.now() - entry.checkedAt > NEGATIVE_TTL_MS) return 'unknown'
- return 'unsupported'
-}
-
-/** Mark a model as supporting `format`. Sticky — retained indefinitely. */
-export function markFormatSupported(model: string): void {
- const cache = loadCache()
- cache[model] = { capability: 'supported', checkedAt: Date.now() }
- saveCache(cache)
-}
-
-/**
- * Mark a model as NOT supporting `format`. Expires after NEGATIVE_TTL_MS
- * so infra upgrades can be picked up without manual cache clears.
- */
-export function markFormatUnsupported(model: string): void {
- const cache = loadCache()
- cache[model] = { capability: 'unsupported', checkedAt: Date.now() }
- saveCache(cache)
-}
-
-/** Drop the cache entry for a model (forces re-probe next use). */
-export function clearFormatCapability(model: string): void {
- const cache = loadCache()
- delete cache[model]
- saveCache(cache)
-}
-
-/** Debug / test helper — wipe the entire capability cache. */
-export function resetFormatCapabilityCache(): void {
- saveCache({})
-}
-
-/**
- * Probe a model for `format` support. The probe sends a minimal
- * /api/generate request with `format: "json"`, a 3-second abort timeout,
- * and a trivial prompt that must return valid JSON.
- *
- * The probe is deliberately tolerant: a non-JSON response is treated as
- * unsupported, a timeout as unsupported, a network error re-throws so the
- * caller can distinguish transport issues from model issues.
- */
-export async function probeFormatSupport(
- model: string,
- ollamaBaseUrl: string,
- fetchImpl: typeof fetch = fetch
-): Promise<'supported' | 'unsupported'> {
- const url = `${ollamaBaseUrl.replace(/\/$/, '')}/api/generate`
- const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), 3000)
- try {
- const res = await fetchImpl(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- signal: controller.signal,
- body: JSON.stringify({
- model,
- prompt: 'Return the JSON object {"ok":true} and nothing else.',
- stream: false,
- format: 'json',
- options: { temperature: 0, num_predict: 32 },
- }),
- })
- clearTimeout(timer)
- if (!res.ok) {
- markFormatUnsupported(model)
- return 'unsupported'
- }
- const data = await res.json().catch(() => null)
- const text: string = data?.response ?? ''
- try {
- const parsed = JSON.parse(text)
- if (parsed && typeof parsed === 'object') {
- markFormatSupported(model)
- return 'supported'
- }
- } catch {
- // Not JSON — model ignored the format param.
- }
- markFormatUnsupported(model)
- return 'unsupported'
- } catch (err) {
- clearTimeout(timer)
- if ((err as DOMException)?.name === 'AbortError') {
- markFormatUnsupported(model)
- return 'unsupported'
- }
- // Network / transport — leave cache alone and surface the error.
- throw err
- }
-}
diff --git a/src/api/agents/partial-args-accumulator.ts b/src/api/agents/partial-args-accumulator.ts
deleted file mode 100644
index c2029180..00000000
--- a/src/api/agents/partial-args-accumulator.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * Phase 11 (v2.4.0) — Partial tool-call args accumulator.
- *
- * Providers that stream tool-call arguments (OpenAI via
- * choice.delta.tool_calls[].function.arguments, Anthropic via
- * input_json_delta) emit JSON in fragments. To render "args as they
- * stream" in the UI — the same experience leading coding agents ship — we
- * need a cheap best-effort parser that takes the accumulated string so far and
- * returns a partial object.
- *
- * Strategy:
- * 1. Try JSON.parse on the raw buffer (works once the object is complete).
- * 2. On failure, attempt to close open braces/brackets and finish open
- * strings, then re-parse. Yields a partial object with the keys that
- * have already streamed.
- * 3. If even that fails, return { __partial: raw } — the UI renders the
- * raw stream so the user at least sees progress.
- *
- * This is deliberately NOT a full streaming JSON parser (jsonStream etc.)
- * because tool args are small enough that the heuristic above handles
- * 100 % of real-world cases in <1 ms. Full streaming becomes necessary
- * only for megabyte-scale payloads, which never happens here.
- */
-
-export interface PartialParse {
- /** True when the buffer successfully parsed as complete JSON. */
- complete: boolean
- /** Partial object view, or {} if nothing parseable yet. */
- partial: Record<string, any>
- /** Raw buffer — available for streaming log display fallbacks. */
- raw: string
-}
-
-/**
- * Parse a possibly-incomplete JSON object buffer. See module doc.
- */
-export function parsePartialJson(raw: string): PartialParse {
- const trimmed = raw.trim()
- if (!trimmed) return { complete: false, partial: {}, raw }
-
- // Fast path: complete and valid.
- try {
- const obj = JSON.parse(trimmed)
- if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
- return { complete: true, partial: obj, raw }
- }
- } catch {
- // fall through
- }
-
- // Heuristic closure of unfinished string / braces / brackets.
- const closed = closeOpenStructures(trimmed)
- try {
- const obj = JSON.parse(closed)
- if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
- return { complete: false, partial: obj, raw }
- }
- } catch {
- // fall through
- }
-
- return { complete: false, partial: {}, raw }
-}
-
-/**
- * Stateful accumulator — append chunks as they arrive, ask for the
- * current parse whenever the UI tick wants to render.
- */
-export class PartialArgsAccumulator {
- private buffer = ''
-
- /** Append a streamed chunk. No parsing happens here. */
- push(chunk: string): void {
- if (chunk) this.buffer += chunk
- }
-
- /** Replace the buffer (e.g. when a provider sends a full replacement). */
- set(full: string): void {
- this.buffer = full
- }
-
- /** Current buffer length — useful for animation pacing. */
- length(): number {
- return this.buffer.length
- }
-
- /** Parse current buffer into a best-effort partial object. */
- snapshot(): PartialParse {
- return parsePartialJson(this.buffer)
- }
-
- /** Reset for the next tool call. */
- reset(): void {
- this.buffer = ''
- }
-}
-
-// ─── Internals ───
-
-/**
- * Given a JSON prefix, try to make it syntactically complete by:
- * 1. Closing an unterminated string literal
- * 2. Adding matching } / ] for each unmatched { / [
- * 3. Stripping a trailing comma just before the closing brace
- *
- * This is a heuristic — it can be wrong for deeply adversarial input,
- * but real LLM stream output is well-formed once normalized.
- */
-function closeOpenStructures(s: string): string {
- let out = s
- // If odd number of unescaped quotes, we are mid-string.
- let inString = false
- let escape = false
- const stack: string[] = []
- for (let i = 0; i < out.length; i++) {
- const ch = out[i]
- if (inString) {
- if (escape) { escape = false; continue }
- if (ch === '\\') { escape = true; continue }
- if (ch === '"') inString = false
- continue
- }
- if (ch === '"') { inString = true; continue }
- if (ch === '{') stack.push('}')
- else if (ch === '[') stack.push(']')
- else if (ch === '}' || ch === ']') stack.pop()
- }
-
- if (inString) out += '"'
-
- // Drop a trailing comma that would otherwise become invalid.
- out = out.replace(/,\s*$/, '')
-
- while (stack.length > 0) out += stack.pop()
- return out
-}
-
-export const __internal = { closeOpenStructures }
diff --git a/src/api/tool-capability.ts b/src/api/tool-capability.ts
index d2803d36..b0df61bb 100644
--- a/src/api/tool-capability.ts
+++ b/src/api/tool-capability.ts
@@ -10,10 +10,10 @@
* - the chat model dropdown can flag it with a small marker, and
* - a later Agent / Code run can warn before wasting another request.
*
- * Mirrors `agents/format-capability.ts`: localStorage-backed, negative results
- * expire after a day so a re-quantised model or an upgraded server deployment
- * recovers on its own without a manual cache clear. No active probe — tool
- * support is learned from real request outcomes, never a synthetic call.
+ * localStorage-backed; negative results expire after a day so a re-quantised
+ * model or an upgraded server deployment recovers on its own without a manual
+ * cache clear. No active probe — tool support is learned from real request
+ * outcomes, never a synthetic call.
*/
const STORAGE_KEY = 'lu-tool-capability-v1'
diff --git a/src/components/agents/AgentView.tsx b/src/components/agents/AgentView.tsx
deleted file mode 100644
index 53763b86..00000000
--- a/src/components/agents/AgentView.tsx
+++ /dev/null
@@ -1,306 +0,0 @@
-import { useState, useEffect } from 'react'
-import { backendCall } from '../../api/backend'
-import { motion, AnimatePresence } from 'framer-motion'
-import { Bot, Play, Square, Trash2, Clock, Download, Loader2, CircleCheck, CircleAlert } from 'lucide-react'
-import { GlowButton } from '../ui/GlowButton'
-import { GlassCard } from '../ui/GlassCard'
-import { TaskBreakdown } from './TaskBreakdown'
-import { AgentLog } from './AgentLog'
-import { useAgent } from '../../hooks/useAgent'
-import { useAgentStore } from '../../stores/agentStore'
-import { useModelStore } from '../../stores/modelStore'
-import type { AgentRun } from '../../types/agents'
-
-function formatTime(ts: number): string {
- const d = new Date(ts)
- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
-}
-
-function statusColor(status: AgentRun['status']): string {
- switch (status) {
- case 'completed': return 'text-green-400'
- case 'failed': return 'text-red-400'
- case 'executing': case 'planning': return 'text-blue-400'
- case 'paused': return 'text-amber-400'
- default: return 'text-gray-400'
- }
-}
-
-function statusLabel(status: AgentRun['status']): string {
- switch (status) {
- case 'completed': return 'Done'
- case 'failed': return 'Failed'
- case 'executing': return 'Running'
- case 'planning': return 'Planning'
- case 'paused': return 'Paused'
- default: return 'Idle'
- }
-}
-
-export function AgentView() {
- const [goal, setGoal] = useState('')
- const [selectedModel, setSelectedModel] = useState<string | null>(null)
- const [searxngStatus, setSearxngStatus] = useState<{ installed: boolean; running: boolean; dockerAvailable: boolean } | null>(null)
- const [searxngInstalling, setSearxngInstalling] = useState(false)
- const [searxngMsg, setSearxngMsg] = useState('')
-
- const checkSearxngStatus = async () => {
- try {
- const data = await backendCall('searxng_status')
- setSearxngStatus({ installed: data.installed, running: data.running, dockerAvailable: data.dockerAvailable })
- } catch {
- setSearxngStatus({ installed: false, running: false, dockerAvailable: false })
- }
- }
-
- const installOrStartSearxng = async () => {
- setSearxngInstalling(true)
- setSearxngMsg('Starting...')
- try {
- const data = await backendCall('install_searxng')
- if (data.error) {
- setSearxngMsg(data.error)
- setSearxngInstalling(false)
- return
- }
- if (data.status === 'ok') {
- setSearxngMsg(data.message)
- setSearxngInstalling(false)
- setTimeout(checkSearxngStatus, 3000)
- return
- }
- const poll = setInterval(async () => {
- try {
- const statusData = await backendCall('searxng_status')
- const lastLog = statusData.logs?.length ? statusData.logs[statusData.logs.length - 1] : ''
- setSearxngMsg(lastLog || statusData.status)
- if (statusData.status === 'complete') {
- clearInterval(poll)
- setSearxngInstalling(false)
- setSearxngMsg('')
- checkSearxngStatus()
- } else if (statusData.status === 'error') {
- clearInterval(poll)
- setSearxngInstalling(false)
- setSearxngMsg(statusData.error || 'Install failed')
- }
- } catch { /* ignore poll errors */ }
- }, 2000)
- } catch {
- setSearxngMsg('Failed to start install')
- setSearxngInstalling(false)
- }
- }
-
- useEffect(() => {
- checkSearxngStatus()
- }, [])
- const { activeRun, isRunning, startAgent, stopAgent, approveToolCall, rejectToolCall } = useAgent()
- const { runs, setActiveRun, deleteRun } = useAgentStore()
- const { models, activeModel } = useModelStore()
-
- const currentModel = selectedModel || activeModel || ''
-
- const handleRun = () => {
- if (!goal.trim() || !currentModel) return
- startAgent(goal.trim(), currentModel)
- setGoal('')
- }
-
- const handleKeyDown = (e: React.KeyboardEvent) => {
- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
- e.preventDefault()
- handleRun()
- }
- }
-
- return (
- <div className="flex flex-col h-full gap-3 p-4">
- {/* Goal Input Area */}
- <GlassCard className="flex-shrink-0">
- <div className="flex flex-col gap-3">
- <div className="flex items-center gap-2 text-[0.8rem] text-gray-400">
- <Bot size={16} />
- <span>Agent Goal</span>
- </div>
- <div className="flex gap-3 items-end">
- <textarea
- value={goal}
- onChange={(e) => setGoal(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="Describe what you want the agent to accomplish..."
- className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-[0.85rem] text-white placeholder-gray-500 resize-none focus:outline-none focus:border-white/20 transition-colors min-h-[60px] max-h-[120px]"
- rows={2}
- />
- <div className="flex flex-col gap-2">
- <select
- value={currentModel}
- onChange={(e) => setSelectedModel(e.target.value)}
- className="bg-white/5 border border-white/10 rounded-lg px-2 py-1.5 text-[0.75rem] text-gray-300 focus:outline-none focus:border-white/20 min-w-[140px]"
- >
- {models.map((m) => (
- <option key={m.name} value={m.name} className="bg-[#262626]">
- {m.name}
- </option>
- ))}
- </select>
- {isRunning ? (
- <GlowButton variant="danger" onClick={stopAgent} className="text-[0.75rem] py-1.5">
- <Square size={14} className="inline mr-1" />
- Stop
- </GlowButton>
- ) : (
- <GlowButton
- onClick={handleRun}
- disabled={!goal.trim() || !currentModel}
- className="text-[0.75rem] py-1.5"
- >
- <Play size={14} className="inline mr-1" />
- Run Agent
- </GlowButton>
- )}
- </div>
- </div>
- </div>
- </GlassCard>
-
- {searxngStatus && (
- <div className="text-[0.7rem] px-1 -mt-1.5 flex items-center gap-2">
- {searxngStatus.running ? (
- <>
- <CircleCheck size={12} className="text-green-400 flex-shrink-0" />
- <span className="text-green-400/80">Search Enhanced</span>
- </>
- ) : searxngInstalling ? (
- <>
- <Loader2 size={12} className="text-blue-400 animate-spin flex-shrink-0" />
- <span className="text-blue-400/80 truncate max-w-[400px]" title={searxngMsg}>
- {searxngMsg || 'Installing SearXNG...'}
- </span>
- </>
- ) : searxngStatus.installed ? (
- <>
- <CircleAlert size={12} className="text-amber-400 flex-shrink-0" />
- <span className="text-gray-500">SearXNG: Stopped</span>
- <button
- onClick={installOrStartSearxng}
- className="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 hover:bg-amber-500/30 transition-colors text-[0.65rem] font-medium border border-amber-500/30"
- >
- Start SearXNG
- </button>
- </>
- ) : (
- <>
- <span className="text-gray-500">SearXNG: Not installed</span>
- {searxngStatus.dockerAvailable ? (
- <button
- onClick={installOrStartSearxng}
- className="px-2 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors text-[0.65rem] font-medium border border-blue-500/30"
- >
- <Download size={10} className="inline mr-1 -mt-0.5" />
- Install SearXNG
- </button>
- ) : (
- <span className="text-gray-600 text-[0.65rem]">Docker required</span>
- )}
- {searxngMsg && (
- <span className="text-red-400/70 text-[0.65rem] truncate max-w-[300px]" title={searxngMsg}>
- {searxngMsg}
- </span>
- )}
- </>
- )}
- </div>
- )}
-
- {/* Main Content */}
- <div className="flex-1 flex gap-3 min-h-0 overflow-hidden">
- {/* Run History Sidebar */}
- <GlassCard className="w-[250px] flex-shrink-0 flex flex-col overflow-hidden">
- <div className="text-[0.75rem] text-gray-400 mb-2 font-medium flex items-center gap-1.5">
- <Clock size={13} />
- Run History
- </div>
- <div className="flex-1 overflow-y-auto space-y-1.5 min-h-0 scrollbar-thin">
- <AnimatePresence>
- {runs.length === 0 && (
- <motion.div
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- className="text-[0.75rem] text-gray-500 text-center py-6"
- >
- No runs yet
- </motion.div>
- )}
- {[...runs].reverse().map((run) => (
- <motion.div
- key={run.id}
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -10 }}
- onClick={() => setActiveRun(run.id)}
- className={`group flex items-start gap-2 p-2 rounded-lg cursor-pointer transition-colors text-[0.75rem] ${
- activeRun?.id === run.id
- ? 'bg-white/10 border border-white/15'
- : 'hover:bg-white/5 border border-transparent'
- }`}
- >
- <div className="flex-1 min-w-0">
- <div className="text-white truncate leading-tight">
- {run.goal.length > 50 ? run.goal.slice(0, 50) + '...' : run.goal}
- </div>
- <div className="flex items-center gap-2 mt-1">
- <span className={`${statusColor(run.status)} text-[0.65rem]`}>
- {statusLabel(run.status)}
- </span>
- <span className="text-gray-500 text-[0.65rem]">
- {formatTime(run.createdAt)}
- </span>
- </div>
- </div>
- <button
- onClick={(e) => { e.stopPropagation(); deleteRun(run.id) }}
- className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-red-400 transition-all p-0.5"
- >
- <Trash2 size={12} />
- </button>
- </motion.div>
- ))}
- </AnimatePresence>
- </div>
- </GlassCard>
-
- {/* Active Run Details */}
- <div className="flex-1 flex flex-col gap-3 min-h-0 overflow-hidden">
- {activeRun ? (
- <>
- {/* Task Breakdown */}
- <GlassCard className="flex-shrink-0 max-h-[40%] overflow-y-auto">
- <TaskBreakdown tasks={activeRun.tasks} />
- </GlassCard>
-
- {/* Agent Log */}
- <GlassCard className="flex-1 min-h-0 overflow-hidden flex flex-col">
- <AgentLog
- entries={activeRun.log}
- onApprove={activeRun.status === 'paused' ? (toolCallId) => approveToolCall(activeRun.id, toolCallId) : undefined}
- onReject={activeRun.status === 'paused' ? (toolCallId) => rejectToolCall(activeRun.id, toolCallId) : undefined}
- />
- </GlassCard>
- </>
- ) : (
- <GlassCard className="flex-1 flex items-center justify-center">
- <div className="text-center text-gray-500">
- <Bot size={48} className="mx-auto mb-3 opacity-30" />
- <div className="text-[0.85rem]">No active run</div>
- <div className="text-[0.7rem] mt-1">
- Enter a goal above and click Run Agent to start
- </div>
- </div>
- </GlassCard>
- )}
- </div>
- </div>
- </div>
- )
-}
diff --git a/src/hooks/useAgent.ts b/src/hooks/useAgent.ts
deleted file mode 100644
index 9e32edef..00000000
--- a/src/hooks/useAgent.ts
+++ /dev/null
@@ -1,433 +0,0 @@
-import { useCallback, useRef } from "react";
-import { useAgentStore } from "../stores/agentStore";
-import {
- AGENT_TOOLS,
- buildReActPrompt,
- buildJsonRetryPrompt,
- parseAgentResponse,
- executeTool,
- chatNonStreaming,
-} from "../api/agents";
-import type {
- AgentRun,
- ToolCall,
- ToolName,
-} from "../types/agents";
-import { log } from "../lib/logger";
-
-function generateId(): string {
- return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
-}
-
-const MAX_CONSECUTIVE_ERRORS = 3;
-
-export function useAgent() {
- const store = useAgentStore();
- const abortRef = useRef<AbortController | null>(null);
- const loopRef = useRef<boolean>(false);
-
- const activeRun = store.getActiveRun();
- const isRunning =
- activeRun?.status === "planning" || activeRun?.status === "executing";
-
- const runReActLoop = useCallback(
- async (runId: string, model: string) => {
- const maxIter = store.maxIterations;
- let consecutiveErrors = 0;
-
- while (loopRef.current) {
- const currentRun = store.runs.find((r) => r.id === runId);
- if (!currentRun || currentRun.currentIteration >= maxIter) {
- store.updateRun(runId, {
- status: currentRun?.currentIteration! >= maxIter ? "failed" : "completed",
- });
- if (currentRun?.currentIteration! >= maxIter) {
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `Max iterations (${maxIter}) reached`,
- timestamp: Date.now(),
- });
- }
- break;
- }
-
- // Check abort
- if (abortRef.current?.signal.aborted) {
- store.updateRun(runId, { status: "failed" });
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: "Agent run cancelled by user",
- timestamp: Date.now(),
- });
- break;
- }
-
- // Check consecutive errors - pause and ask user
- if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
- store.updateRun(runId, { status: "paused" });
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `${MAX_CONSECUTIVE_ERRORS} consecutive tool errors occurred. Agent paused. Please review the errors and resume or stop the agent.`,
- timestamp: Date.now(),
- });
- break;
- }
-
- const iteration = currentRun.currentIteration + 1;
- store.updateRun(runId, {
- currentIteration: iteration,
- status: "executing",
- });
-
- try {
- // Build prompt with full history
- const freshRun = store.runs.find((r) => r.id === runId)!;
- const systemPrompt = buildReActPrompt(
- freshRun.goal,
- AGENT_TOOLS,
- freshRun.log
- );
-
- // Call LLM
- let response = await chatNonStreaming(model, [
- { role: "system", content: systemPrompt },
- { role: "user", content: freshRun.goal },
- ]);
-
- // Parse response
- let parsed = parseAgentResponse(response);
-
- // If parse totally failed (action === 'continue'), retry once with simpler prompt
- if (parsed.action === "continue" && !parsed.answer) {
- store.addLogEntry(runId, {
- id: generateId(),
- type: "thought",
- content: "[JSON parse failed, retrying with simplified prompt]",
- timestamp: Date.now(),
- });
-
- const retryPrompt = buildJsonRetryPrompt(response);
- const retryResponse = await chatNonStreaming(model, [
- { role: "system", content: systemPrompt },
- { role: "user", content: retryPrompt },
- ]);
-
- const retryParsed = parseAgentResponse(retryResponse);
- // Only use retry result if it actually produced a real action
- if (retryParsed.action !== "continue") {
- parsed = retryParsed;
- }
- }
-
- // Log the thought
- store.addLogEntry(runId, {
- id: generateId(),
- type: "thought",
- content: parsed.thought,
- timestamp: Date.now(),
- });
-
- // Check if finished
- if (parsed.action === "finish") {
- store.addLogEntry(runId, {
- id: generateId(),
- type: "observation",
- content: parsed.answer || "Task completed",
- timestamp: Date.now(),
- });
- store.updateRun(runId, { status: "completed" });
- consecutiveErrors = 0;
- break;
- }
-
- // If still 'continue' after retry, log and loop again
- if (parsed.action === "continue") {
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: "LLM failed to produce valid JSON after retry. Continuing to next iteration.",
- timestamp: Date.now(),
- });
- consecutiveErrors++;
- continue;
- }
-
- // Validate tool
- const toolDef = AGENT_TOOLS.find((t) => t.name === parsed.action);
- if (!toolDef) {
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `Unknown tool: ${parsed.action}`,
- timestamp: Date.now(),
- });
- consecutiveErrors++;
- continue;
- }
-
- const toolCall: ToolCall = {
- id: generateId(),
- tool: parsed.action as ToolName,
- args: parsed.args || {},
- status: "pending",
- timestamp: Date.now(),
- };
-
- // Log the action
- store.addLogEntry(runId, {
- id: generateId(),
- type: "action",
- content: `${parsed.action}(${JSON.stringify(parsed.args || {})})`,
- timestamp: Date.now(),
- toolCall,
- });
-
- // Check if tool requires approval
- if (toolDef.requiresApproval) {
- // Create a task for tracking and pause
- const taskId = generateId();
- const task = {
- id: taskId,
- description: `${parsed.action}: ${JSON.stringify(parsed.args || {})}`,
- status: "pending" as const,
- toolCalls: [toolCall],
- reasoning: parsed.thought,
- order: iteration,
- };
-
- store.updateRun(runId, {
- status: "paused",
- tasks: [...(store.runs.find((r) => r.id === runId)?.tasks || []), task],
- });
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "observation",
- content: `Tool "${parsed.action}" requires approval. Agent paused.`,
- timestamp: Date.now(),
- });
-
- // Break loop - will be resumed via approveToolCall
- break;
- }
-
- // Execute tool directly
- const startTime = Date.now();
- try {
- const result = await executeTool(
- parsed.action as ToolName,
- parsed.args || {}
- );
- const duration = Date.now() - startTime;
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "observation",
- content: result,
- timestamp: Date.now(),
- toolCall: { ...toolCall, status: "completed", result, duration },
- });
-
- // Tool succeeded, reset consecutive error counter
- consecutiveErrors = 0;
- } catch (err: any) {
- const duration = Date.now() - startTime;
- const errorMsg = err?.message || String(err);
-
- consecutiveErrors++;
-
- // Include the error in the log so the LLM sees it in the next iteration
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `Tool "${parsed.action}" failed (attempt ${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}): ${errorMsg}`,
- timestamp: Date.now(),
- toolCall: {
- ...toolCall,
- status: "failed",
- error: errorMsg,
- duration,
- },
- });
- }
- } catch (err: any) {
- const errorMsg = err?.message || String(err);
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `LLM error: ${errorMsg}`,
- timestamp: Date.now(),
- });
- store.updateRun(runId, { status: "failed" });
- break;
- }
- }
-
- loopRef.current = false;
- },
- [store]
- );
-
- const startAgent = useCallback(
- async (goal: string, model: string) => {
- const runId = generateId();
- const run: AgentRun = {
- id: runId,
- goal,
- model,
- status: "planning",
- tasks: [],
- log: [],
- createdAt: Date.now(),
- updatedAt: Date.now(),
- maxIterations: store.maxIterations,
- currentIteration: 0,
- };
-
- store.createRun(run);
-
- abortRef.current = new AbortController();
- loopRef.current = true;
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "user_input",
- content: goal,
- timestamp: Date.now(),
- });
-
- // Run the loop (not awaited to avoid blocking)
- runReActLoop(runId, model).catch((err) => {
- log.error("Agent loop crashed", { err });
- store.updateRun(runId, { status: "failed" });
- });
- },
- [store, runReActLoop]
- );
-
- const stopAgent = useCallback(() => {
- loopRef.current = false;
- if (abortRef.current) {
- abortRef.current.abort();
- abortRef.current = null;
- }
- if (activeRun && isRunning) {
- store.updateRun(activeRun.id, { status: "failed" });
- store.addLogEntry(activeRun.id, {
- id: generateId(),
- type: "error",
- content: "Agent stopped by user",
- timestamp: Date.now(),
- });
- }
- }, [activeRun, isRunning, store]);
-
- const approveToolCall = useCallback(
- async (runId: string, toolCallId: string) => {
- const run = store.runs.find((r) => r.id === runId);
- if (!run) return;
-
- // Find the pending tool call
- let pendingToolCall: ToolCall | undefined;
- for (const task of run.tasks) {
- const tc = task.toolCalls.find((tc) => tc.id === toolCallId);
- if (tc) {
- pendingToolCall = tc;
- break;
- }
- }
-
- if (!pendingToolCall) return;
-
- store.updateToolCallStatus(runId, toolCallId, "approved");
-
- // Execute the tool
- const startTime = Date.now();
- try {
- const result = await executeTool(pendingToolCall.tool, pendingToolCall.args);
- const duration = Date.now() - startTime;
-
- store.updateToolCallStatus(
- runId,
- toolCallId,
- "completed",
- result,
- undefined,
- duration
- );
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "observation",
- content: result,
- timestamp: Date.now(),
- });
- } catch (err: any) {
- const duration = Date.now() - startTime;
- const errorMsg = err?.message || String(err);
-
- store.updateToolCallStatus(
- runId,
- toolCallId,
- "failed",
- undefined,
- errorMsg,
- duration
- );
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "error",
- content: `Tool error: ${errorMsg}`,
- timestamp: Date.now(),
- });
- }
-
- // Resume the ReAct loop
- abortRef.current = new AbortController();
- loopRef.current = true;
- runReActLoop(runId, run.model).catch((err) => {
- log.error("Agent loop crashed after approval", { err });
- store.updateRun(runId, { status: "failed" });
- });
- },
- [store, runReActLoop]
- );
-
- const rejectToolCall = useCallback(
- async (runId: string, toolCallId: string) => {
- const run = store.runs.find((r) => r.id === runId);
- if (!run) return;
-
- store.updateToolCallStatus(runId, toolCallId, "rejected");
-
- store.addLogEntry(runId, {
- id: generateId(),
- type: "observation",
- content: "Tool call rejected by user. Continuing to next iteration.",
- timestamp: Date.now(),
- });
-
- // Resume the ReAct loop
- abortRef.current = new AbortController();
- loopRef.current = true;
- runReActLoop(runId, run.model).catch((err) => {
- log.error("Agent loop crashed after rejection", { err });
- store.updateRun(runId, { status: "failed" });
- });
- },
- [store, runReActLoop]
- );
-
- return {
- activeRun,
- isRunning,
- startAgent,
- stopAgent,
- approveToolCall,
- rejectToolCall,
- };
-}
diff --git a/src/stores/__tests__/agentStore.test.ts b/src/stores/__tests__/agentStore.test.ts
deleted file mode 100644
index a5fd0ffc..00000000
--- a/src/stores/__tests__/agentStore.test.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import { describe, it, expect, beforeEach } from 'vitest'
-import { useAgentStore } from '../agentStore'
-import type { AgentRun, AgentLogEntry, ToolCall, AgentTask } from '../../types/agents'
-
-function makeTask(id: string, toolCalls: ToolCall[] = []): AgentTask {
- return { id, description: `Task ${id}`, status: 'pending', toolCalls, reasoning: '', order: 0 }
-}
-
-function makeToolCall(id: string): ToolCall {
- return { id, tool: 'web_search', args: {}, status: 'pending', timestamp: Date.now() }
-}
-
-function makeRun(id: string, tasks: AgentTask[] = []): AgentRun {
- return {
- id,
- goal: `Goal for ${id}`,
- model: 'test-model',
- status: 'idle',
- tasks,
- log: [],
- createdAt: Date.now(),
- updatedAt: Date.now(),
- maxIterations: 20,
- currentIteration: 0,
- }
-}
-
-describe('agentStore', () => {
- beforeEach(() => {
- useAgentStore.setState({
- runs: [],
- activeRunId: null,
- maxIterations: 20,
- workspacePath: '~/agent-workspace',
- })
- })
-
- // ── createRun ──────────────────────────────────────────────
-
- describe('createRun', () => {
- it('adds the run to runs array', () => {
- const run = makeRun('run-1')
- useAgentStore.getState().createRun(run)
- expect(useAgentStore.getState().runs).toHaveLength(1)
- expect(useAgentStore.getState().runs[0].id).toBe('run-1')
- })
-
- it('sets activeRunId to the new run', () => {
- const run = makeRun('run-1')
- useAgentStore.getState().createRun(run)
- expect(useAgentStore.getState().activeRunId).toBe('run-1')
- })
-
- it('adds multiple runs', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().createRun(makeRun('run-2'))
- expect(useAgentStore.getState().runs).toHaveLength(2)
- expect(useAgentStore.getState().activeRunId).toBe('run-2')
- })
- })
-
- // ── updateRun ──────────────────────────────────────────────
-
- describe('updateRun', () => {
- it('merges partial updates into the run', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().updateRun('run-1', { status: 'executing' })
- expect(useAgentStore.getState().runs[0].status).toBe('executing')
- })
-
- it('auto-sets updatedAt', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- const before = Date.now()
- useAgentStore.getState().updateRun('run-1', { currentIteration: 5 })
- expect(useAgentStore.getState().runs[0].updatedAt).toBeGreaterThanOrEqual(before)
- })
-
- it('does not modify other runs', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().createRun(makeRun('run-2'))
- useAgentStore.getState().updateRun('run-1', { status: 'completed' })
- expect(useAgentStore.getState().runs[1].status).toBe('idle')
- })
-
- it('is a no-op for non-existent runId', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().updateRun('nonexistent', { status: 'failed' })
- expect(useAgentStore.getState().runs[0].status).toBe('idle')
- })
- })
-
- // ── addLogEntry ────────────────────────────────────────────
-
- describe('addLogEntry', () => {
- it('appends a log entry to the correct run', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- const entry: AgentLogEntry = {
- id: 'log-1',
- type: 'thought',
- content: 'Thinking...',
- timestamp: Date.now(),
- }
- useAgentStore.getState().addLogEntry('run-1', entry)
- expect(useAgentStore.getState().runs[0].log).toHaveLength(1)
- expect(useAgentStore.getState().runs[0].log[0].id).toBe('log-1')
- })
-
- it('sets updatedAt on the run', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- const before = Date.now()
- useAgentStore.getState().addLogEntry('run-1', {
- id: 'log-1',
- type: 'action',
- content: 'Doing something',
- timestamp: Date.now(),
- })
- expect(useAgentStore.getState().runs[0].updatedAt).toBeGreaterThanOrEqual(before)
- })
-
- it('appends multiple entries in order', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().addLogEntry('run-1', { id: 'a', type: 'thought', content: '1', timestamp: 1 })
- useAgentStore.getState().addLogEntry('run-1', { id: 'b', type: 'action', content: '2', timestamp: 2 })
- const log = useAgentStore.getState().runs[0].log
- expect(log).toHaveLength(2)
- expect(log[0].id).toBe('a')
- expect(log[1].id).toBe('b')
- })
- })
-
- // ── addToolCall ────────────────────────────────────────────
-
- describe('addToolCall', () => {
- it('appends a toolCall to the correct task', () => {
- const task = makeTask('task-1')
- useAgentStore.getState().createRun(makeRun('run-1', [task]))
- const tc = makeToolCall('tc-1')
- useAgentStore.getState().addToolCall('run-1', 'task-1', tc)
- const tasks = useAgentStore.getState().runs[0].tasks
- expect(tasks[0].toolCalls).toHaveLength(1)
- expect(tasks[0].toolCalls[0].id).toBe('tc-1')
- })
-
- it('does not affect other tasks in the same run', () => {
- const task1 = makeTask('task-1')
- const task2 = makeTask('task-2')
- useAgentStore.getState().createRun(makeRun('run-1', [task1, task2]))
- useAgentStore.getState().addToolCall('run-1', 'task-1', makeToolCall('tc-1'))
- expect(useAgentStore.getState().runs[0].tasks[1].toolCalls).toHaveLength(0)
- })
-
- it('updates updatedAt on the run', () => {
- useAgentStore.getState().createRun(makeRun('run-1', [makeTask('task-1')]))
- const before = Date.now()
- useAgentStore.getState().addToolCall('run-1', 'task-1', makeToolCall('tc-1'))
- expect(useAgentStore.getState().runs[0].updatedAt).toBeGreaterThanOrEqual(before)
- })
- })
-
- // ── updateToolCallStatus ───────────────────────────────────
-
- describe('updateToolCallStatus', () => {
- it('updates status on the correct nested toolCall', () => {
- const tc = makeToolCall('tc-1')
- useAgentStore.getState().createRun(makeRun('run-1', [makeTask('task-1', [tc])]))
- useAgentStore.getState().updateToolCallStatus('run-1', 'tc-1', 'completed', 'result data')
- const updated = useAgentStore.getState().runs[0].tasks[0].toolCalls[0]
- expect(updated.status).toBe('completed')
- expect(updated.result).toBe('result data')
- })
-
- it('sets error and duration when provided', () => {
- const tc = makeToolCall('tc-1')
- useAgentStore.getState().createRun(makeRun('run-1', [makeTask('task-1', [tc])]))
- useAgentStore.getState().updateToolCallStatus('run-1', 'tc-1', 'failed', undefined, 'timeout', 1500)
- const updated = useAgentStore.getState().runs[0].tasks[0].toolCalls[0]
- expect(updated.status).toBe('failed')
- expect(updated.error).toBe('timeout')
- expect(updated.duration).toBe(1500)
- })
-
- it('finds toolCall across multiple tasks', () => {
- const tc1 = makeToolCall('tc-1')
- const tc2 = makeToolCall('tc-2')
- useAgentStore.getState().createRun(makeRun('run-1', [
- makeTask('task-1', [tc1]),
- makeTask('task-2', [tc2]),
- ]))
- useAgentStore.getState().updateToolCallStatus('run-1', 'tc-2', 'completed', 'ok')
- expect(useAgentStore.getState().runs[0].tasks[1].toolCalls[0].status).toBe('completed')
- // tc-1 unchanged
- expect(useAgentStore.getState().runs[0].tasks[0].toolCalls[0].status).toBe('pending')
- })
-
- it('does not overwrite result when result is undefined', () => {
- const tc = makeToolCall('tc-1')
- tc.result = 'existing'
- useAgentStore.getState().createRun(makeRun('run-1', [makeTask('task-1', [tc])]))
- useAgentStore.getState().updateToolCallStatus('run-1', 'tc-1', 'completed')
- // result should NOT be overwritten since undefined was passed
- expect(useAgentStore.getState().runs[0].tasks[0].toolCalls[0].result).toBe('existing')
- })
- })
-
- // ── deleteRun ──────────────────────────────────────────────
-
- describe('deleteRun', () => {
- it('removes the run from the array', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().deleteRun('run-1')
- expect(useAgentStore.getState().runs).toHaveLength(0)
- })
-
- it('clears activeRunId if deleted run was active', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- expect(useAgentStore.getState().activeRunId).toBe('run-1')
- useAgentStore.getState().deleteRun('run-1')
- expect(useAgentStore.getState().activeRunId).toBeNull()
- })
-
- it('does not clear activeRunId if a different run is deleted', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().createRun(makeRun('run-2'))
- // run-2 is active
- useAgentStore.getState().deleteRun('run-1')
- expect(useAgentStore.getState().activeRunId).toBe('run-2')
- expect(useAgentStore.getState().runs).toHaveLength(1)
- })
- })
-
- // ── getActiveRun ───────────────────────────────────────────
-
- describe('getActiveRun', () => {
- it('returns the active run', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- const active = useAgentStore.getState().getActiveRun()
- expect(active).toBeDefined()
- expect(active!.id).toBe('run-1')
- })
-
- it('returns undefined when no run is active', () => {
- expect(useAgentStore.getState().getActiveRun()).toBeUndefined()
- })
-
- it('returns undefined after active run is deleted', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().deleteRun('run-1')
- expect(useAgentStore.getState().getActiveRun()).toBeUndefined()
- })
-
- it('returns the most recently set active run', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().createRun(makeRun('run-2'))
- useAgentStore.getState().setActiveRun('run-1')
- expect(useAgentStore.getState().getActiveRun()!.id).toBe('run-1')
- })
- })
-
- // ── setActiveRun ───────────────────────────────────────────
-
- describe('setActiveRun', () => {
- it('sets activeRunId', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().setActiveRun('run-1')
- expect(useAgentStore.getState().activeRunId).toBe('run-1')
- })
-
- it('can set to null', () => {
- useAgentStore.getState().createRun(makeRun('run-1'))
- useAgentStore.getState().setActiveRun(null)
- expect(useAgentStore.getState().activeRunId).toBeNull()
- })
- })
-})
diff --git a/src/stores/agentStore.ts b/src/stores/agentStore.ts
deleted file mode 100644
index cd4aa87e..00000000
--- a/src/stores/agentStore.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { create } from "zustand";
-import { persist } from "zustand/middleware";
-import type {
- AgentRun,
- AgentLogEntry,
- ToolCall,
-} from "../types/agents";
-
-interface AgentState {
- runs: AgentRun[];
- activeRunId: string | null;
- maxIterations: number;
- workspacePath: string;
-
- // Actions
- createRun: (run: AgentRun) => void;
- updateRun: (
- runId: string,
- updates: Partial<
- Pick<
- AgentRun,
- "status" | "tasks" | "currentIteration" | "updatedAt" | "log"
- >
- >
- ) => void;
- addLogEntry: (runId: string, entry: AgentLogEntry) => void;
- addToolCall: (runId: string, taskId: string, toolCall: ToolCall) => void;
- updateToolCallStatus: (
- runId: string,
- toolCallId: string,
- status: ToolCall["status"],
- result?: string,
- error?: string,
- duration?: number
- ) => void;
- setActiveRun: (runId: string | null) => void;
- deleteRun: (runId: string) => void;
- getActiveRun: () => AgentRun | undefined;
-}
-
-export const useAgentStore = create<AgentState>()(
- persist(
- (set, get) => ({
- runs: [],
- activeRunId: null,
- maxIterations: 20,
- workspacePath: "~/agent-workspace",
-
- createRun: (run) =>
- set((state) => ({
- runs: [...state.runs, run],
- activeRunId: run.id,
- })),
-
- updateRun: (runId, updates) =>
- set((state) => ({
- runs: state.runs.map((r) =>
- r.id === runId
- ? { ...r, ...updates, updatedAt: Date.now() }
- : r
- ),
- })),
-
- addLogEntry: (runId, entry) =>
- set((state) => ({
- runs: state.runs.map((r) =>
- r.id === runId
- ? {
- ...r,
- log: [...r.log, entry],
- updatedAt: Date.now(),
- }
- : r
- ),
- })),
-
- addToolCall: (runId, taskId, toolCall) =>
- set((state) => ({
- runs: state.runs.map((r) =>
- r.id === runId
- ? {
- ...r,
- tasks: r.tasks.map((t) =>
- t.id === taskId
- ? { ...t, toolCalls: [...t.toolCalls, toolCall] }
- : t
- ),
- updatedAt: Date.now(),
- }
- : r
- ),
- })),
-
- updateToolCallStatus: (runId, toolCallId, status, result, error, duration) =>
- set((state) => ({
- runs: state.runs.map((r) =>
- r.id === runId
- ? {
- ...r,
- tasks: r.tasks.map((t) => ({
- ...t,
- toolCalls: t.toolCalls.map((tc) =>
- tc.id === toolCallId
- ? {
- ...tc,
- status,
- ...(result !== undefined && { result }),
- ...(error !== undefined && { error }),
- ...(duration !== undefined && { duration }),
- }
- : tc
- ),
- })),
- updatedAt: Date.now(),
- }
- : r
- ),
- })),
-
- setActiveRun: (runId) => set({ activeRunId: runId }),
-
- deleteRun: (runId) =>
- set((state) => ({
- runs: state.runs.filter((r) => r.id !== runId),
- activeRunId:
- state.activeRunId === runId ? null : state.activeRunId,
- })),
-
- getActiveRun: () => {
- const state = get();
- return state.runs.find((r) => r.id === state.activeRunId);
- },
- }),
- {
- name: "locally-uncensored-agent",
- partialize: (state) => ({
- runs: state.runs,
- activeRunId: state.activeRunId,
- maxIterations: state.maxIterations,
- workspacePath: state.workspacePath,
- }),
- }
- )
-);