Personal AI, On Personal Devices
Python
feat: operatives tab improvements — 9 UX/functionality fixes (#63)
Jon Saad-Falcon51a2b4ccebb3
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 6bca66e4..0bc2cfe4 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -433,12 +433,18 @@ export async function fetchTemplates(): Promise<AgentTemplate[]> {export async function runManagedAgent(agentId: string): Promise<void> {const res = await fetch(`${getBase()}/v1/managed-agents/${agentId}/run`, { method: 'POST' });- if (!res.ok) throw new Error(`Failed: ${res.status}`);+ if (!res.ok) {+ const body = await res.json().catch(() => ({ detail: res.statusText }));+ throw new Error(body.detail || `Failed: ${res.status}`);+ }}-export async function recoverManagedAgent(agentId: string): Promise<unknown> {+export async function recoverManagedAgent(agentId: string): Promise<{ recovered: boolean; checkpoint: unknown }> {const res = await fetch(`${getBase()}/v1/managed-agents/${agentId}/recover`, { method: 'POST' });- if (!res.ok) throw new Error(`Failed: ${res.status}`);+ if (!res.ok) {+ const body = await res.json().catch(() => ({ detail: res.statusText }));+ throw new Error(body.detail || `Failed: ${res.status}`);+ }return res.json();}@@ -498,6 +504,36 @@ export interface AgentTrace {started_at: number;steps: number;error_message?: string;+ metadata?: Record<string, unknown>;+}++export interface ToolInfo {+ name: string;+ description: string;+ category: string;+ source: 'tool' | 'channel';+ requires_credentials: boolean;+ credential_keys: string[];+ configured: boolean;+}++export async function fetchAvailableTools(): Promise<ToolInfo[]> {+ const res = await fetch(`${getBase()}/v1/tools`);+ if (!res.ok) throw new Error(`Failed: ${res.status}`);+ const data = await res.json();+ return data.tools || [];+}++export async function saveToolCredentials(+ toolName: string,+ credentials: Record<string, string>,+): Promise<void> {+ const res = await fetch(`${getBase()}/v1/tools/${toolName}/credentials`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(credentials),+ });+ if (!res.ok) throw new Error(`Failed: ${res.status}`);}export interface AgentTraceDetail {diff --git a/frontend/src/pages/AgentsPage.tsx b/frontend/src/pages/AgentsPage.tsxindex 10927885..702dee16 100644--- a/frontend/src/pages/AgentsPage.tsx+++ b/frontend/src/pages/AgentsPage.tsx@@ -18,8 +18,10 @@ import {triggerLearning,fetchAgentTraces,fetchManagedAgent,+ fetchAvailableTools,+ saveToolCredentials,} from '../lib/api';-import type { AgentTask, ChannelBinding, AgentTemplate, AgentMessage, ManagedAgent, LearningLogEntry, AgentTrace } from '../lib/api';+import type { AgentTask, ChannelBinding, AgentTemplate, AgentMessage, ManagedAgent, LearningLogEntry, AgentTrace, ToolInfo } from '../lib/api';import {Plus,Bot,@@ -41,7 +43,6 @@ import {ChevronRight,Send,RefreshCw,- Info,} from 'lucide-react';// ---------------------------------------------------------------------------@@ -116,23 +117,92 @@ function formatRelativeTime(ts?: number | null): string {function formatSchedule(type?: string, value?: string): string {if (!type || type === 'manual') return 'Manual';if (type === 'cron') return value ? `Cron: ${value}` : 'Cron';- if (type === 'interval') return value ? `Every ${value}` : 'Interval';- return type;+ if (type === 'interval' && value) {+ const total = parseInt(value);+ if (!isNaN(total) && total > 0) {+ const h = Math.floor(total / 3600);+ const m = Math.floor((total % 3600) / 60);+ const s = total % 60;+ const parts: string[] = [];+ if (h > 0) parts.push(`${h}h`);+ if (m > 0) parts.push(`${m}m`);+ if (s > 0) parts.push(`${s}s`);+ return `Every ${parts.join(' ') || '0s'}`;+ }+ return `Every ${value}`;+ }+ return type || 'Manual';}// ---------------------------------------------------------------------------// Launch Wizard// ----------------------------------------------------------------------------const AVAILABLE_TOOLS = [- { id: 'web_search', label: 'Web Search' },- { id: 'code_interpreter', label: 'Code Interpreter' },- { id: 'file_read', label: 'File Read' },- { id: 'shell_exec', label: 'Shell Exec' },- { id: 'browser', label: 'Browser' },- { id: 'calculator', label: 'Calculator' },+const CATEGORY_MAP: Record<string, string> = {+ communication: 'Communication',+ channel: 'Communication',+ search: 'Search & Browse',+ browser: 'Search & Browse',+ code: 'Code & Dev',+ system: 'Code & Dev',+ filesystem: 'Files & Data',+ memory: 'Memory & Knowledge',+ knowledge_graph: 'Memory & Knowledge',+ reasoning: 'Reasoning & AI',+ math: 'Reasoning & AI',+ inference: 'Reasoning & AI',+ agents: 'Reasoning & AI',+ media: 'Media',+};++const TOOL_NAME_FALLBACK: Record<string, string> = {+ file_read: 'Files & Data',+ file_write: 'Files & Data',+ pdf_extract: 'Files & Data',+ db_query: 'Files & Data',+ http_request: 'Files & Data',+ apply_patch: 'Code & Dev',+ git_status: 'Code & Dev',+ git_diff: 'Code & Dev',+ git_log: 'Code & Dev',+ git_commit: 'Code & Dev',+ channel_send: 'Communication',+ channel_list: 'Communication',+ channel_status: 'Communication',+};++const CATEGORY_ORDER = [+ 'Communication', 'Search & Browse', 'Code & Dev', 'Files & Data',+ 'Memory & Knowledge', 'Reasoning & AI', 'Media',+];++const POPULAR_TOOLS = new Set([+ 'slack', 'email', 'telegram', 'whatsapp',+ 'web_search', 'browser',+ 'code_interpreter', 'shell_exec', 'git_status', 'git_diff',+ 'file_read', 'file_write', 'pdf_extract',+ 'retrieval', 'memory_store',+ 'think', 'llm', 'calculator',+ 'image_generate',+]);++const BROWSER_SUB_TOOLS = [+ 'browser_navigate', 'browser_click', 'browser_type',+ 'browser_screenshot', 'browser_extract', 'browser_axtree',];+function parseIntervalParts(val: string): { hours: number; minutes: number; seconds: number } {+ const total = parseInt(val) || 0;+ const hours = Math.floor(total / 3600);+ const minutes = Math.floor((total % 3600) / 60);+ const seconds = total % 60;+ return { hours, minutes, seconds };+}++function serializeInterval(hours: number, minutes: number, seconds: number): string {+ return String(hours * 3600 + minutes * 60 + seconds);+}+interface WizardState {step: number;templateId: string;@@ -143,11 +213,11 @@ interface WizardState {scheduleValue: string;selectedTools: string[];budget: string;- learningEnabled: boolean;- intervalH: number;- intervalM: number;- intervalS: number;+ routerPolicy: string;memoryExtraction: string;+ observationCompression: string;+ retrievalStrategy: string;+ taskDecomposition: string;}function LaunchWizard({@@ -169,13 +239,66 @@ function LaunchWizard({scheduleValue: '',selectedTools: [],budget: '',- learningEnabled: false,- intervalH: 0,- intervalM: 30,- intervalS: 0,+ routerPolicy: '',memoryExtraction: 'causality_graph',+ observationCompression: 'summarize',+ retrievalStrategy: 'hybrid_with_self_eval',+ taskDecomposition: 'phased',});const [launching, setLaunching] = useState(false);+ const models = useAppStore((s) => s.models);+ const [availableTools, setAvailableTools] = useState<ToolInfo[]>([]);+ const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());+ const [credentialInputs, setCredentialInputs] = useState<Record<string, Record<string, string>>>({});+ const [savingCredentials, setSavingCredentials] = useState<string | null>(null);++ useEffect(() => {+ fetchAvailableTools().then(setAvailableTools).catch(() => {});+ }, []);++ function getToolCategory(tool: ToolInfo): string {+ if (tool.category && CATEGORY_MAP[tool.category]) return CATEGORY_MAP[tool.category];+ if (TOOL_NAME_FALLBACK[tool.name]) return TOOL_NAME_FALLBACK[tool.name];+ return 'Reasoning & AI';+ }++ function toggleCategory(cat: string) {+ setExpandedCategories((prev) => {+ const next = new Set(prev);+ if (next.has(cat)) next.delete(cat);+ else next.add(cat);+ return next;+ });+ }++ function handleToggleTool(name: string) {+ if (name === 'browser') {+ const has = BROWSER_SUB_TOOLS.every((t) => wizard.selectedTools.includes(t));+ if (has) {+ update({ selectedTools: wizard.selectedTools.filter((t) => !BROWSER_SUB_TOOLS.includes(t)) });+ } else {+ update({ selectedTools: [...new Set([...wizard.selectedTools, ...BROWSER_SUB_TOOLS])] });+ }+ } else {+ toggleTool(name);+ }+ }++ async function handleSaveCredentials(toolName: string) {+ const inputs = credentialInputs[toolName];+ if (!inputs) return;+ setSavingCredentials(toolName);+ try {+ await saveToolCredentials(toolName, inputs);+ toast.success(`Credentials saved for ${toolName}`);+ const updated = await fetchAvailableTools();+ setAvailableTools(updated);+ } catch (err: any) {+ toast.error(err.message || 'Failed to save credentials');+ } finally {+ setSavingCredentials(null);+ }+ }function update(partial: Partial<WizardState>) {setWizard((prev) => ({ ...prev, ...partial }));@@ -209,18 +332,18 @@ function LaunchWizard({try {const config: Record<string, unknown> = {schedule_type: wizard.scheduleType,- schedule_value: wizard.scheduleType === 'interval'- ? String(wizard.intervalH * 3600 + wizard.intervalM * 60 + wizard.intervalS)- : wizard.scheduleValue || undefined,+ schedule_value: wizard.scheduleValue || undefined,tools: wizard.selectedTools,- learning_enabled: wizard.learningEnabled,+ learning_enabled: !!wizard.routerPolicy,};if (wizard.budget) config.budget = parseFloat(wizard.budget);- if (wizard.learningEnabled && wizard.memoryExtraction) {- config.memory_extraction = wizard.memoryExtraction;- }if (wizard.instruction.trim()) config.instruction = wizard.instruction.trim();if (wizard.model) config.model = wizard.model;+ if (wizard.routerPolicy) config.router_policy = wizard.routerPolicy;+ config.memory_extraction = wizard.memoryExtraction;+ config.observation_compression = wizard.observationCompression;+ config.retrieval_strategy = wizard.retrievalStrategy;+ config.task_decomposition = wizard.taskDecomposition;const created = await createManagedAgent({name: wizard.name,template_id: wizard.templateId || undefined,@@ -383,7 +506,7 @@ function LaunchWizard({{/* Model */}<div>- <div className="text-xs mb-1" style={{ color: 'var(--color-text-secondary)' }}>Model</div>+ <div className="text-xs mb-1" style={{ color: 'var(--color-text-secondary)' }}>Intelligence (Model)</div><selectvalue={wizard.model}onChange={(e) => update({ model: e.target.value })}@@ -395,110 +518,268 @@ function LaunchWizard({}}><option value="">Server default</option>- {useAppStore.getState().models.map((m) => (- <option key={m.id} value={m.id}>{m.id}</option>- ))}+ {(() => {+ const local = models.filter((m) => !m.id.includes('/') && !m.id.startsWith('gpt') && !m.id.startsWith('claude') && !m.id.startsWith('gemini'));+ const cloud = models.filter((m) => m.id.includes('/') || m.id.startsWith('gpt') || m.id.startsWith('claude') || m.id.startsWith('gemini'));+ const formatModel = (m: { id: string; context_length?: number; params?: string }) => {+ const parts = [m.id];+ if ((m as any).params) parts.push(`(${(m as any).params})`);+ if ((m as any).context_length) parts.push(`${Math.round((m as any).context_length / 1024)}K ctx`);+ return parts.join(' ');+ };+ return (+ <>+ {local.length > 0 && (+ <optgroup label="Local (Running)">+ {local.map((m) => (+ <option key={m.id} value={m.id}>{formatModel(m)}</option>+ ))}+ </optgroup>+ )}+ {cloud.length > 0 && (+ <optgroup label="Cloud">+ {cloud.map((m) => (+ <option key={m.id} value={m.id}>{formatModel(m)}</option>+ ))}+ </optgroup>+ )}+ {local.length === 0 && cloud.length === 0 && (+ <option disabled>No models available — start an engine or add API keys</option>+ )}+ </>+ );+ })()}</select></div>- <div className="grid grid-cols-2 gap-3">- <div>- <label className="flex items-center gap-1 text-xs font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>- Schedule Type- <span title="Manual: runs only when you click Run Now. Cron: standard cron schedule (e.g. 0 */6 * * * = every 6h). Interval: runs repeatedly with a fixed delay.">- <Info size={12} style={{ color: 'var(--color-text-tertiary)', cursor: 'help' }} />- </span>+ {/* Schedule */}+ <div>+ <div className="flex items-center gap-1.5 mb-1">+ <label className="block text-xs font-medium" style={{ color: 'var(--color-text-secondary)' }}>+ Schedule</label>- <select- value={wizard.scheduleType}- onChange={(e) => update({ scheduleType: e.target.value })}- className="w-full px-3 py-2 rounded-lg text-sm"- style={{- background: 'var(--color-bg)',- border: '1px solid var(--color-border)',- color: 'var(--color-text)',- }}- >- <option value="manual">Manual</option>- <option value="cron">Cron</option>- <option value="interval">Interval</option>- </select>+ <div className="relative group">+ <span+ className="inline-flex items-center justify-center w-3.5 h-3.5 rounded-full text-[9px] font-bold cursor-help"+ style={{ background: 'var(--color-border)', color: 'var(--color-text-tertiary)' }}+ >+ i+ </span>+ <div+ className="absolute left-0 bottom-full mb-1 w-64 p-2 rounded-lg text-xs hidden group-hover:block z-50"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}+ >+ <div className="space-y-1.5">+ <div><strong>Manual</strong> — Run only when you click "Run Now"</div>+ <div><strong>Cron</strong> — UNIX cron schedule (e.g. <code>0 9 * * *</code> = daily at 9 AM)</div>+ <div><strong>Interval</strong> — Fixed delay between runs for continuous monitoring</div>+ </div>+ </div>+ </div></div>+ <select+ value={wizard.scheduleType}+ onChange={(e) => update({ scheduleType: e.target.value, scheduleValue: '' })}+ className="w-full px-3 py-2 rounded-lg text-sm"+ style={{+ background: 'var(--color-bg)',+ border: '1px solid var(--color-border)',+ color: 'var(--color-text)',+ }}+ >+ <option value="manual">Manual — Run on demand only</option>+ <option value="cron">Cron — Recurring fixed-time schedule</option>+ <option value="interval">Interval — Fixed delay between runs</option>+ </select>+ </div>++ {/* Interval spinners */}+ {wizard.scheduleType === 'interval' && (<div><label className="block text-xs font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>- {wizard.scheduleType === 'interval' ? 'Interval' : 'Schedule Value'}+ Run Every</label>- {wizard.scheduleType === 'interval' ? (- <div className="flex items-center gap-1">- <input type="number" min={0} max={999} value={wizard.intervalH}- onChange={(e) => update({ intervalH: parseInt(e.target.value) || 0 })}- className="w-14 px-2 py-2 rounded-lg text-sm text-center bg-transparent outline-none"- style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}- />- <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>h</span>- <input type="number" min={0} max={59} value={wizard.intervalM}- onChange={(e) => update({ intervalM: parseInt(e.target.value) || 0 })}- className="w-14 px-2 py-2 rounded-lg text-sm text-center bg-transparent outline-none"- style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}- />- <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>m</span>- <input type="number" min={0} max={59} value={wizard.intervalS}- onChange={(e) => update({ intervalS: parseInt(e.target.value) || 0 })}- className="w-14 px-2 py-2 rounded-lg text-sm text-center bg-transparent outline-none"- style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}- />- <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>s</span>+ <div className="grid grid-cols-3 gap-2">+ {(['hours', 'minutes', 'seconds'] as const).map((unit) => {+ const max = unit === 'hours' ? 999 : 59;+ const vals = parseIntervalParts(wizard.scheduleValue);+ return (+ <div key={unit} className="flex flex-col">+ <input+ type="number"+ min={0}+ max={max}+ value={vals[unit]}+ onChange={(e) => {+ const v = { ...vals, [unit]: Math.max(0, Math.min(max, parseInt(e.target.value) || 0)) };+ update({ scheduleValue: serializeInterval(v.hours, v.minutes, v.seconds) });+ }}+ className="w-full px-2 py-2 rounded-lg text-sm text-center bg-transparent outline-none"+ style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}+ />+ <span className="text-[10px] text-center mt-0.5" style={{ color: 'var(--color-text-tertiary)' }}>{unit}</span>+ </div>+ );+ })}+ </div>+ {wizard.scheduleValue && parseInt(wizard.scheduleValue) > 0 && parseInt(wizard.scheduleValue) < 10 && (+ <div className="text-[10px] mt-1" style={{ color: 'var(--color-error)' }}>+ Minimum interval is 10 seconds</div>- ) : (- <input- type="text"- placeholder={wizard.scheduleType === 'cron' ? '0 * * * *' : '—'}- value={wizard.scheduleValue}- onChange={(e) => update({ scheduleValue: e.target.value })}- disabled={wizard.scheduleType === 'manual'}- className="w-full px-3 py-2 rounded-lg text-sm bg-transparent outline-none"- style={{- border: '1px solid var(--color-border)',- color: 'var(--color-text)',- opacity: wizard.scheduleType === 'manual' ? 0.4 : 1,- }}- />)}</div>- </div>+ )}++ {/* Cron input */}+ {wizard.scheduleType === 'cron' && (+ <div>+ <div className="flex items-center gap-1.5 mb-1">+ <label className="block text-xs font-medium" style={{ color: 'var(--color-text-secondary)' }}>+ Cron Expression+ </label>+ <div className="relative group">+ <span+ className="inline-flex items-center justify-center w-3.5 h-3.5 rounded-full text-[9px] font-bold cursor-help"+ style={{ background: 'var(--color-border)', color: 'var(--color-text-tertiary)' }}+ >+ i+ </span>+ <div+ className="absolute left-0 bottom-full mb-1 w-52 p-2 rounded-lg text-xs hidden group-hover:block z-50"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}+ >+ <div className="space-y-1">+ <div><code>0 * * * *</code> — Every hour</div>+ <div><code>0 9 * * *</code> — Daily at 9 AM</div>+ <div><code>0 9 * * 1</code> — Mondays at 9 AM</div>+ </div>+ </div>+ </div>+ </div>+ <input+ type="text"+ placeholder="0 * * * *"+ value={wizard.scheduleValue}+ onChange={(e) => update({ scheduleValue: e.target.value })}+ className="w-full px-3 py-2 rounded-lg text-sm bg-transparent outline-none"+ style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}+ />+ </div>+ )}<div><label className="block text-xs font-medium mb-2" style={{ color: 'var(--color-text-secondary)' }}>- Tools+ Tools & Channels</label>- <div className="grid grid-cols-2 gap-2">- {AVAILABLE_TOOLS.map((tool) => (- <label- key={tool.id}- className="flex items-center gap-2 p-2 rounded-lg cursor-pointer"- style={{- background: wizard.selectedTools.includes(tool.id) ? 'var(--color-accent)' + '10' : 'var(--color-bg-secondary)',- border: `1px solid ${wizard.selectedTools.includes(tool.id) ? 'var(--color-accent)' + '50' : 'var(--color-border)'}`,- }}- >- <input- type="checkbox"- checked={wizard.selectedTools.includes(tool.id)}- onChange={() => toggleTool(tool.id)}- className="accent-current"- />- <span className="text-xs" style={{ color: 'var(--color-text)' }}>- {tool.label}- </span>- </label>- ))}+ {(() => {+ const unconfiguredSelected = wizard.selectedTools.filter((t) => {+ const tool = availableTools.find((at) => at.name === t);+ return tool && tool.requires_credentials && !tool.configured;+ });+ return unconfiguredSelected.length > 0 ? (+ <div className="text-[10px] mb-2 px-2 py-1 rounded" style={{ background: '#f59e0b20', color: '#f59e0b' }}>+ {unconfiguredSelected.length} tool{unconfiguredSelected.length > 1 ? 's' : ''} need setup — credentials required before they will work+ </div>+ ) : null;+ })()}+ <div className="space-y-3 max-h-64 overflow-y-auto">+ {CATEGORY_ORDER.map((cat) => {+ const catTools = availableTools.filter((t) => getToolCategory(t) === cat);+ if (catTools.length === 0) return null;+ const popular = catTools.filter((t) => POPULAR_TOOLS.has(t.name));+ const rest = catTools.filter((t) => !POPULAR_TOOLS.has(t.name));+ const isExpanded = expandedCategories.has(cat);+ const shown = isExpanded ? catTools : popular;++ return (+ <div key={cat}>+ <div+ className="flex items-center justify-between cursor-pointer mb-1"+ onClick={() => rest.length > 0 && toggleCategory(cat)}+ >+ <span className="text-[10px] font-semibold uppercase tracking-wide" style={{ color: 'var(--color-text-tertiary)' }}>+ {cat} ({catTools.length})+ </span>+ {rest.length > 0 && (+ <span className="text-[10px]" style={{ color: 'var(--color-accent)' }}>+ {isExpanded ? 'Show less' : `Show all (${catTools.length})`}+ </span>+ )}+ </div>+ <div className="grid grid-cols-2 gap-1.5">+ {shown.map((tool) => {+ const isSelected = tool.name === 'browser'+ ? BROWSER_SUB_TOOLS.every((t) => wizard.selectedTools.includes(t))+ : wizard.selectedTools.includes(tool.name);+ const needsSetup = tool.requires_credentials && !tool.configured;+ return (+ <div key={tool.name}>+ <button+ type="button"+ onClick={() => handleToggleTool(tool.name)}+ className="w-full text-left p-2 rounded-lg text-xs transition-colors cursor-pointer"+ style={{+ background: isSelected ? 'var(--color-accent)' + '10' : 'var(--color-bg-secondary)',+ border: `1px solid ${isSelected ? 'var(--color-accent)' + '50' : 'var(--color-border)'}`,+ color: 'var(--color-text)',+ }}+ >+ <div className="flex items-center gap-1.5">+ {isSelected && <span style={{ color: 'var(--color-accent)' }}>✓</span>}+ <span className="font-medium">{tool.name.replace(/_/g, ' ')}</span>+ {needsSetup && <span className="w-1.5 h-1.5 rounded-full inline-block" style={{ background: '#f59e0b' }} />}+ </div>+ {tool.description && (+ <div className="text-[10px] mt-0.5 truncate" style={{ color: 'var(--color-text-tertiary)' }}>+ {tool.description.slice(0, 60)}+ </div>+ )}+ </button>+ {isSelected && needsSetup && (+ <div className="mt-1 p-2 rounded-lg text-xs space-y-1.5" style={{ background: 'var(--color-bg)', border: '1px solid #f59e0b40' }}>+ {tool.credential_keys.map((key) => (+ <div key={key}>+ <label className="block text-[10px] mb-0.5" style={{ color: 'var(--color-text-tertiary)' }}>+ {key.replace(/_/g, ' ')}+ </label>+ <input+ type="password"+ value={credentialInputs[tool.name]?.[key] || ''}+ onChange={(e) => setCredentialInputs((prev) => ({+ ...prev,+ [tool.name]: { ...prev[tool.name], [key]: e.target.value },+ }))}+ className="w-full px-2 py-1 rounded text-xs bg-transparent outline-none"+ style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}+ placeholder={`Enter ${key}`}+ />+ </div>+ ))}+ <button+ type="button"+ onClick={() => handleSaveCredentials(tool.name)}+ disabled={savingCredentials === tool.name}+ className="px-2 py-1 rounded text-[10px] font-medium cursor-pointer"+ style={{ background: 'var(--color-accent)', color: 'white' }}+ >+ {savingCredentials === tool.name ? 'Saving...' : 'Save'}+ </button>+ </div>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+ })}</div></div><div className="grid grid-cols-2 gap-3"><div><label className="block text-xs font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>- Budget ($, optional)+ Budget (optional)</label><inputtype="number"@@ -510,45 +791,88 @@ function LaunchWizard({className="w-full px-3 py-2 rounded-lg text-sm bg-transparent outline-none"style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}/>- <p className="text-[10px] mt-1" style={{ color: 'var(--color-text-tertiary)' }}>- Maximum cloud API spend. Does not apply to local models.- </p>+ <div className="text-[10px] mt-0.5" style={{ color: 'var(--color-text-tertiary)' }}>+ Cloud API models only (OpenAI, Anthropic, Google). Local models have no cost.+ </div></div>- <div className="flex flex-col justify-end">- <label className="flex items-center gap-2 cursor-pointer p-2 rounded-lg" style={{ background: 'var(--color-bg-secondary)' }}>- <input- type="checkbox"- checked={wizard.learningEnabled}- onChange={(e) => update({ learningEnabled: e.target.checked })}- />- <span className="text-xs" style={{ color: 'var(--color-text)' }}>- Enable Learning- </span>- </label>- {wizard.learningEnabled && (- <div className="mt-2">- <label className="block text-xs font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>- Learning Technique- </label>- <select- value={wizard.memoryExtraction}- onChange={(e) => update({ memoryExtraction: e.target.value })}- className="w-full px-3 py-2 rounded-lg text-sm"- style={{- background: 'var(--color-bg)',- border: '1px solid var(--color-border)',- color: 'var(--color-text)',- }}+ <div>+ <div className="flex items-center gap-1.5 mb-1">+ <label className="block text-xs font-medium" style={{ color: 'var(--color-text-secondary)' }}>+ Learning+ </label>+ <div className="relative group">+ <span+ className="inline-flex items-center justify-center w-3.5 h-3.5 rounded-full text-[9px] font-bold cursor-help"+ style={{ background: 'var(--color-border)', color: 'var(--color-text-tertiary)' }}+ >+ i+ </span>+ <div+ className="absolute right-0 bottom-full mb-1 w-56 p-2 rounded-lg text-xs hidden group-hover:block z-50"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}>- <option value="causality_graph">Causality Graph</option>- <option value="scratchpad">Scratchpad</option>- <option value="structured_json">Structured JSON</option>- <option value="none">None</option>- </select>+ Router policies let the agent learn which model works best for different query types over time.+ </div></div>- )}+ </div>+ <select+ value={wizard.routerPolicy}+ onChange={(e) => update({ routerPolicy: e.target.value })}+ className="w-full px-3 py-2 rounded-lg text-sm"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}+ >+ <option value="">None — Always use selected model</option>+ <option value="heuristic">Heuristic — Rule-based model selection</option>+ <option value="learned">Trace-Driven — Learns from past runs</option>+ </select></div></div>+ {/* Agent Strategies — shown for monitor_operative (default when no template selected) */}+ {(!wizard.templateId || templates.find((t) => t.id === wizard.templateId)?.agent_type === 'monitor_operative') && (+ <div>+ <div className="flex items-center gap-1.5 mb-1">+ <label className="block text-xs font-medium" style={{ color: 'var(--color-text-secondary)' }}>+ Agent Strategies+ </label>+ </div>+ <div className="grid grid-cols-2 gap-2">+ {([+ { label: 'Memory Extraction', key: 'memoryExtraction' as const, tooltip: 'How the agent stores findings between runs',+ options: [['causality_graph', 'Causality Graph'], ['scratchpad', 'Scratchpad'], ['structured_json', 'Structured JSON'], ['none', 'None']] },+ { label: 'Observation Compression', key: 'observationCompression' as const, tooltip: 'How long tool outputs are compressed',+ options: [['summarize', 'Summarize'], ['truncate', 'Truncate'], ['none', 'None']] },+ { label: 'Retrieval Strategy', key: 'retrievalStrategy' as const, tooltip: 'How the agent retrieves past context',+ options: [['hybrid_with_self_eval', 'Hybrid + Self-Eval'], ['keyword', 'Keyword'], ['semantic', 'Semantic'], ['none', 'None']] },+ { label: 'Task Decomposition', key: 'taskDecomposition' as const, tooltip: 'How complex instructions are broken down',+ options: [['phased', 'Phased'], ['monolithic', 'Monolithic'], ['hierarchical', 'Hierarchical']] },+ ] as const).map((s) => (+ <div key={s.key}>+ <div className="flex items-center gap-1 mb-0.5">+ <span className="text-[10px]" style={{ color: 'var(--color-text-tertiary)' }}>{s.label}</span>+ <div className="relative group">+ <span className="inline-flex items-center justify-center w-3 h-3 rounded-full text-[8px] font-bold cursor-help"+ style={{ background: 'var(--color-border)', color: 'var(--color-text-tertiary)' }}>i</span>+ <div className="absolute left-0 bottom-full mb-1 w-48 p-1.5 rounded text-[10px] hidden group-hover:block z-50"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}>+ {s.tooltip}+ </div>+ </div>+ </div>+ <select+ value={wizard[s.key]}+ onChange={(e) => update({ [s.key]: e.target.value } as Partial<WizardState>)}+ className="w-full px-2 py-1.5 rounded text-xs"+ style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}+ >+ {s.options.map(([val, label]) => (+ <option key={val} value={val}>{label}</option>+ ))}+ </select>+ </div>+ ))}+ </div>+ </div>+ )}</div>)}@@ -586,12 +910,22 @@ function LaunchWizard({</div><div className="flex justify-between"><span style={{ color: 'var(--color-text-tertiary)' }}>Budget</span>- <span style={{ color: 'var(--color-text)' }}>{wizard.budget ? `$${wizard.budget}` : 'Unlimited'}</span>+ <span style={{ color: 'var(--color-text)' }}>{wizard.budget ? `$${wizard.budget}` : 'Unlimited (local models free)'}</span></div><div className="flex justify-between"><span style={{ color: 'var(--color-text-tertiary)' }}>Learning</span>- <span style={{ color: 'var(--color-text)' }}>{wizard.learningEnabled ? 'Enabled' : 'Disabled'}</span>+ <span style={{ color: 'var(--color-text)' }}>+ {wizard.routerPolicy ? (wizard.routerPolicy === 'heuristic' ? 'Heuristic Router' : 'Trace-Driven Router') : 'Disabled'}+ </span></div>+ {wizard.routerPolicy && (+ <div className="flex justify-between">+ <span style={{ color: 'var(--color-text-tertiary)' }}>Strategies</span>+ <span className="text-xs text-right" style={{ color: 'var(--color-text)' }}>+ {wizard.memoryExtraction}, {wizard.observationCompression}, {wizard.retrievalStrategy}, {wizard.taskDecomposition}+ </span>+ </div>+ )}</div></div>)}@@ -1043,6 +1377,7 @@ function LearningTab({ agentId, learningEnabled }: { agentId: string; learningEnfunction LogsTab({ agentId }: { agentId: string }) {const [traces, setTraces] = useState<AgentTrace[]>([]);+ const [expandedTrace, setExpandedTrace] = useState<string | null>(null);useEffect(() => {fetchAgentTraces(agentId).then(setTraces).catch(() => {});@@ -1064,38 +1399,64 @@ function LogsTab({ agentId }: { agentId: string }) {</div>) : (<div className="space-y-2">- {traces.map((t) => (- <div- key={t.id}- className="rounded-lg p-3 text-sm"- style={{ background: 'var(--color-bg-secondary)', border: '1px solid var(--color-border)' }}- >- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <span- className="w-2 h-2 rounded-full inline-block"- style={{ background: t.outcome === 'success' ? '#22c55e' : '#ef4444' }}- />- <span style={{ color: 'var(--color-text)' }}>{t.outcome}</span>+ {traces.map((t) => {+ const errorDetail = t.metadata?.error_detail as+ | { error_type: string; error_message: string; suggested_action: string }+ | undefined;+ const isError = t.outcome !== 'success';+ const isExpanded = expandedTrace === t.id;++ return (+ <div+ key={t.id}+ className="rounded-lg p-3 text-sm cursor-pointer"+ style={{ background: 'var(--color-bg-secondary)', border: '1px solid var(--color-border)' }}+ onClick={() => isError && errorDetail && setExpandedTrace(isExpanded ? null : t.id)}+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <span+ className="w-2 h-2 rounded-full inline-block"+ style={{ background: t.outcome === 'success' ? '#22c55e' : '#ef4444' }}+ />+ <span style={{ color: 'var(--color-text)' }}>{t.outcome}</span>+ {errorDetail && (+ <span+ className="text-[10px] px-1.5 py-0.5 rounded font-medium"+ style={{+ background: errorDetail.error_type === 'fatal' ? '#ef444420' :+ errorDetail.error_type === 'escalate' ? '#f59e0b20' : '#3b82f620',+ color: errorDetail.error_type === 'fatal' ? '#ef4444' :+ errorDetail.error_type === 'escalate' ? '#f59e0b' : '#3b82f6',+ }}+ >+ {errorDetail.error_type}+ </span>+ )}+ </div>+ <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>+ {formatRelativeTime(t.started_at)}+ </span></div>- <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>- {formatRelativeTime(t.started_at)}- </span>- </div>- <div className="flex items-center gap-3 mt-1 text-xs" style={{ color: 'var(--color-text-tertiary)' }}>- <span>{t.duration.toFixed(1)}s</span>- <span>{t.steps} step{t.steps !== 1 ? 's' : ''}</span>- </div>- {t.outcome !== 'success' && t.error_message && (- <div- className="mt-1 text-xs px-2 py-1 rounded"- style={{ color: '#ef4444', background: 'rgba(239, 68, 68, 0.1)' }}- >- {t.error_message}+ <div className="flex items-center gap-3 mt-1 text-xs" style={{ color: 'var(--color-text-tertiary)' }}>+ <span>{t.duration.toFixed(1)}s</span>+ <span>{t.steps} step{t.steps !== 1 ? 's' : ''}</span></div>- )}- </div>- ))}+ {isExpanded && errorDetail && (+ <div className="mt-2 pt-2 space-y-1.5 text-xs" style={{ borderTop: '1px solid var(--color-border)' }}>+ <div>+ <span className="font-medium" style={{ color: 'var(--color-text-secondary)' }}>Error: </span>+ <span style={{ color: 'var(--color-text)' }}>{errorDetail.error_message}</span>+ </div>+ <div>+ <span className="font-medium" style={{ color: 'var(--color-text-secondary)' }}>Action: </span>+ <span style={{ color: 'var(--color-text)' }}>{errorDetail.suggested_action}</span>+ </div>+ </div>+ )}+ </div>+ );+ })}</div>)}</div>@@ -1168,16 +1529,13 @@ export function AgentsPage() {try {await runManagedAgent(id);} catch (err: any) {- const msg = err?.message || 'Unknown error';- toast.error('Failed to start agent', { description: msg });- useAppStore.getState().addLogEntry({- timestamp: Date.now(), level: 'error', category: 'model',- message: `Agent run failed: ${msg}`,+ toast.error('Failed to start agent', {+ description: err.message || 'Unknown error',});+ await refresh();return;}await refresh();- // Delayed check for agent-level errors (e.g. crash during tick)setTimeout(async () => {try {const agent = await fetchManagedAgent(id);@@ -1197,10 +1555,17 @@ export function AgentsPage() {const handleRecover = async (id: string) => {try {- await recoverManagedAgent(id);- toast.success('Agent recovered — status reset to idle');- } catch {- toast.error('Recovery failed — no checkpoint available');+ const result = await recoverManagedAgent(id);+ if (result.checkpoint) {+ toast.success('Agent recovered from checkpoint');+ } else {+ toast.success('Agent reset to idle (no checkpoint available)');+ }+ setDetailTab('overview');+ } catch (err: any) {+ toast.error('Recovery failed', {+ description: err.message || 'Unknown error',+ });}await refresh();};diff --git a/frontend/tsconfig.tsbuildinfo b/frontend/tsconfig.tsbuildinfoindex 2049c77e..475306ac 100644--- a/frontend/tsconfig.tsbuildinfo+++ b/frontend/tsconfig.tsbuildinfo@@ -1 +1 @@-{"root":["./src/App.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/components/CommandPalette.tsx","./src/components/ErrorBoundary.tsx","./src/components/Layout.tsx","./src/components/OptInModal.tsx","./src/components/SetupScreen.tsx","./src/components/Chat/ChatArea.tsx","./src/components/Chat/InputArea.tsx","./src/components/Chat/MessageBubble.tsx","./src/components/Chat/MicButton.tsx","./src/components/Chat/StreamingDots.tsx","./src/components/Chat/SystemPanel.tsx","./src/components/Chat/ToolCallCard.tsx","./src/components/Dashboard/CostComparison.tsx","./src/components/Dashboard/EnergyDashboard.tsx","./src/components/Dashboard/TraceDebugger.tsx","./src/components/Sidebar/ConversationList.tsx","./src/components/Sidebar/Sidebar.tsx","./src/hooks/useSpeech.ts","./src/lib/api.ts","./src/lib/profanity.ts","./src/lib/sse.ts","./src/lib/store.ts","./src/pages/AgentsPage.tsx","./src/pages/ChatPage.tsx","./src/pages/DashboardPage.tsx","./src/pages/GetStartedPage.tsx","./src/pages/SettingsPage.tsx","./src/types/index.ts"],"version":"5.7.3"}\ No newline at end of file+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/components/commandpalette.tsx","./src/components/errorboundary.tsx","./src/components/layout.tsx","./src/components/optinmodal.tsx","./src/components/setupscreen.tsx","./src/components/systempulse.tsx","./src/components/chat/chatarea.tsx","./src/components/chat/inputarea.tsx","./src/components/chat/messagebubble.tsx","./src/components/chat/micbutton.tsx","./src/components/chat/streamingdots.tsx","./src/components/chat/systempanel.tsx","./src/components/chat/toolcallcard.tsx","./src/components/chat/xrayfooter.tsx","./src/components/dashboard/costcomparison.tsx","./src/components/dashboard/energydashboard.tsx","./src/components/dashboard/tracedebugger.tsx","./src/components/sidebar/conversationlist.tsx","./src/components/sidebar/sidebar.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/components/ui/input.tsx","./src/components/ui/select.tsx","./src/components/ui/sonner.tsx","./src/components/ui/tooltip.tsx","./src/hooks/usespeech.ts","./src/lib/api.ts","./src/lib/profanity.ts","./src/lib/sse.ts","./src/lib/store.ts","./src/lib/utils.ts","./src/pages/agentspage.tsx","./src/pages/chatpage.tsx","./src/pages/dashboardpage.tsx","./src/pages/getstartedpage.tsx","./src/pages/logspage.tsx","./src/pages/settingspage.tsx","./src/types/index.ts"],"version":"5.7.3"}\ No newline at end of filediff --git a/src/openjarvis/agents/errors.py b/src/openjarvis/agents/errors.pyindex 91559a17..d130d859 100644--- a/src/openjarvis/agents/errors.py+++ b/src/openjarvis/agents/errors.py@@ -85,3 +85,17 @@ def classify_error(exc: Exception) -> AgentTickError:def retry_delay(attempt: int) -> int:"""Exponential backoff delay in seconds: min(10 * 2^attempt, 300)."""return min(10 * (2**attempt), 300)+++def suggest_action(error: AgentTickError) -> str:+ """Return a human-readable suggested action for the given error."""+ msg = str(error).lower()+ if any(p in msg for p in ("rate limit", "rate_limit", "429", "too many requests")):+ return "Rate limited \u2014 agent will auto-retry on next tick"+ if any(p in msg for p in ("timeout", "timed out", "connection", "unavailable")):+ return "Engine not reachable \u2014 check that your inference engine is running"+ if any(p in msg for p in ("401", "403", "permission", "unauthorized", "api key")):+ return "Check API key configuration in Settings"+ if "not found" in msg or "404" in msg:+ return "Model or endpoint not found \u2014 verify model name and engine URL"+ return "Unexpected error \u2014 check the full trace for details"diff --git a/src/openjarvis/agents/executor.py b/src/openjarvis/agents/executor.pyindex 160a6b94..1b78e9cc 100644--- a/src/openjarvis/agents/executor.py+++ b/src/openjarvis/agents/executor.py@@ -185,6 +185,27 @@ class AgentExecutor:if not model:raise FatalError("No model configured for agent")+ # Optionally override model via router policy+ router_policy_key = config.get("router_policy")+ if router_policy_key and self._system:+ try:+ from openjarvis.core.registry import RouterPolicyRegistry+ from openjarvis.learning.routing.types import (+ build_routing_context,+ )++ policy = RouterPolicyRegistry.create(+ router_policy_key,+ available_models=[model],+ )+ instruction = config.get("instruction", "")+ ctx = build_routing_context(instruction)+ selected = policy.select_model(ctx)+ if selected:+ model = selected+ except Exception:+ pass # Fall back to configured model+# Construct agent instance (BaseAgent requires engine, model as positional args)agent_instance = agent_cls(engine,@@ -211,6 +232,32 @@ class AgentExecutor:return agent_instance.run(context)+ def _build_error_detail(self, error: AgentTickError) -> dict[str, Any]:+ """Build structured error detail for trace metadata."""+ import traceback++ from openjarvis.agents.errors import (+ EscalateError,+ FatalError,+ suggest_action,+ )++ if isinstance(error, EscalateError):+ error_type = "escalate"+ elif isinstance(error, FatalError):+ error_type = "fatal"+ else:+ error_type = "retryable"++ return {+ "error_type": error_type,+ "error_message": str(error)[:2000],+ "suggested_action": suggest_action(error),+ "stack_trace_summary": "".join(+ traceback.format_exception(type(error), error, error.__traceback__)[-3:]+ )[:1000] if error.__traceback__ else "",+ }+def _finalize_tick(self,agent_id: str,@@ -316,6 +363,10 @@ class AgentExecutor:timestamp=s.get("start_time", tick_start),))+ metadata: dict[str, Any] = {}+ if error is not None:+ metadata["error_detail"] = self._build_error_detail(error)+outcome = "success" if error is None else "error"trace = Trace(agent=agent_id,@@ -327,6 +378,7 @@ class AgentExecutor:started_at=tick_start,ended_at=tick_start + tick_duration,total_latency_seconds=tick_duration,+ metadata=metadata,)try:self._trace_store.save(trace)diff --git a/src/openjarvis/agents/manager.py b/src/openjarvis/agents/manager.pyindex 8dcf06c6..d197183d 100644--- a/src/openjarvis/agents/manager.py+++ b/src/openjarvis/agents/manager.py@@ -283,8 +283,8 @@ class AgentManager:def recover_agent(self, agent_id: str) -> Optional[Dict[str, Any]]:checkpoint = self.get_latest_checkpoint(agent_id)- if checkpoint is not None:- self.update_agent(agent_id, status="idle")+ # Always reset to idle — clearing the error state is the primary purpose+ self.update_agent(agent_id, status="idle")return checkpoint@staticmethoddiff --git a/src/openjarvis/core/credentials.py b/src/openjarvis/core/credentials.pynew file mode 100644index 00000000..cee6a019--- /dev/null+++ b/src/openjarvis/core/credentials.py@@ -0,0 +1,107 @@+"""Credential persistence for tools and channels.++Stores credentials in ~/.openjarvis/credentials.toml with 0o600 permissions.+Thread-safe writes via lock. Sets os.environ on save for immediate effect.+"""+from __future__ import annotations++import os+import threading+from pathlib import Path++try:+ import tomllib+except ModuleNotFoundError:+ import tomli as tomllib # type: ignore[no-redef]++_LOCK = threading.Lock()+_DEFAULT_PATH = Path.home() / ".openjarvis" / "credentials.toml"++TOOL_CREDENTIALS: dict[str, list[str]] = {+ "web_search": ["TAVILY_API_KEY"],+ "image_generate": ["OPENAI_API_KEY"],+ "slack": ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],+ "telegram": ["TELEGRAM_BOT_TOKEN"],+ "discord": ["DISCORD_BOT_TOKEN"],+ "email": ["EMAIL_USERNAME", "EMAIL_PASSWORD"],+ "whatsapp": ["WHATSAPP_ACCESS_TOKEN", "WHATSAPP_PHONE_NUMBER_ID"],+ "signal": ["SIGNAL_CLI_PATH"],+ "google_chat": ["GOOGLE_CHAT_WEBHOOK_URL"],+ "teams": ["TEAMS_WEBHOOK_URL"],+ "bluebubbles": ["BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"],+ "line": ["LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET"],+ "viber": ["VIBER_AUTH_TOKEN"],+ "messenger": ["MESSENGER_PAGE_ACCESS_TOKEN", "MESSENGER_VERIFY_TOKEN"],+ "reddit": [+ "REDDIT_CLIENT_ID", "REDDIT_CLIENT_SECRET",+ "REDDIT_USERNAME", "REDDIT_PASSWORD",+ ],+ "mastodon": ["MASTODON_ACCESS_TOKEN", "MASTODON_API_BASE_URL"],+ "twitch": ["TWITCH_TOKEN", "TWITCH_CHANNEL"],+ "matrix": ["MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"],+ "mattermost": ["MATTERMOST_URL", "MATTERMOST_TOKEN"],+ "zulip": ["ZULIP_EMAIL", "ZULIP_API_KEY", "ZULIP_SITE"],+ "rocketchat": ["ROCKETCHAT_URL", "ROCKETCHAT_USER_ID", "ROCKETCHAT_AUTH_TOKEN"],+ "xmpp": ["XMPP_JID", "XMPP_PASSWORD"],+ "feishu": ["FEISHU_APP_ID", "FEISHU_APP_SECRET"],+ "nostr": ["NOSTR_PRIVATE_KEY"],+}+++def load_credentials(path: Path | None = None) -> dict[str, dict[str, str]]:+ """Load credentials from TOML file."""+ p = Path(path) if path else _DEFAULT_PATH+ if not p.exists():+ return {}+ with open(p, "rb") as f:+ return tomllib.load(f)+++def save_credential(+ tool_name: str,+ key: str,+ value: str,+ *,+ path: Path | None = None,+) -> None:+ """Save a single credential key, validate, write file, and set os.environ."""+ allowed = TOOL_CREDENTIALS.get(tool_name, [])+ if key not in allowed:+ raise ValueError(f"Unknown credential key '{key}' for tool '{tool_name}'")+ stripped = value.strip()+ if not stripped:+ raise ValueError("Credential value must not be empty")++ p = Path(path) if path else _DEFAULT_PATH+ with _LOCK:+ creds = load_credentials(path=p)+ if tool_name not in creds:+ creds[tool_name] = {}+ creds[tool_name][key] = stripped++ p.parent.mkdir(parents=True, exist_ok=True)+ lines: list[str] = []+ for section, kvs in creds.items():+ lines.append(f"[{section}]")+ for k, v in kvs.items():+ lines.append(f'{k} = "{v}"')+ lines.append("")+ p.write_text("\n".join(lines))+ os.chmod(p, 0o600)++ os.environ[key] = stripped+++def get_credential_status(tool_name: str) -> dict[str, bool]:+ """Return {KEY: bool} for each required key indicating if set in env."""+ keys = TOOL_CREDENTIALS.get(tool_name, [])+ return {k: bool(os.environ.get(k)) for k in keys}+++def inject_credentials(path: Path | None = None) -> None:+ """Load credentials.toml and inject into os.environ. Call at server startup."""+ creds = load_credentials(path=path)+ for _tool, kvs in creds.items():+ for k, v in kvs.items():+ if k not in os.environ:+ os.environ[k] = vdiff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.pyindex 26483bac..45a93f1a 100644--- a/src/openjarvis/server/agent_manager_routes.py+++ b/src/openjarvis/server/agent_manager_routes.py@@ -53,12 +53,161 @@ class FeedbackRequest(BaseModel):reason: Optional[str] = None+_BROWSER_SUB_TOOLS = {+ "browser_navigate", "browser_click", "browser_type",+ "browser_screenshot", "browser_extract", "browser_axtree",+}+++def _ensure_registries_populated() -> None:+ """Ensure ToolRegistry and ChannelRegistry are populated.++ If the registries are empty (e.g. cleared by test fixtures) but the+ modules are already cached in sys.modules, reload the individual+ submodules to re-execute their @register decorators.+ """+ import importlib+ import sys++ from openjarvis.core.registry import ChannelRegistry, ToolRegistry++ # First, try a normal import (works if modules haven't been imported yet)+ try:+ import openjarvis.channels # noqa: F401+ except Exception:+ pass++ try:+ import openjarvis.tools # noqa: F401+ except Exception:+ pass++ # Also try to import browser tools (not included in openjarvis.tools.__init__)+ for _browser_mod in ("openjarvis.tools.browser", "openjarvis.tools.browser_axtree"):+ try:+ importlib.import_module(_browser_mod)+ except Exception:+ pass++ # If registries are still empty, reload individual submodules from sys.modules+ if not ChannelRegistry.keys():+ for mod_name in list(sys.modules):+ if (+ mod_name.startswith("openjarvis.channels.")+ and not mod_name.endswith("_stubs")+ ):+ try:+ importlib.reload(sys.modules[mod_name])+ except Exception:+ pass++ if not ToolRegistry.keys():+ for mod_name in list(sys.modules):+ if (+ mod_name.startswith("openjarvis.tools.")+ and not mod_name.endswith("_stubs")+ and not mod_name.endswith("agent_tools")+ ):+ try:+ importlib.reload(sys.modules[mod_name])+ except Exception:+ pass++ # After reloading tools, also try browser tools if still not registered+ if not any(ToolRegistry.contains(n) for n in _BROWSER_SUB_TOOLS):+ for _browser_mod in (+ "openjarvis.tools.browser",+ "openjarvis.tools.browser_axtree",+ ):+ mod = sys.modules.get(_browser_mod)+ if mod is not None:+ try:+ importlib.reload(mod)+ except Exception:+ pass+++def build_tools_list() -> List[Dict[str, Any]]:+ """Build unified tools list from ToolRegistry + ChannelRegistry."""+ import os++ from openjarvis.core.credentials import TOOL_CREDENTIALS+ from openjarvis.core.registry import ChannelRegistry, ToolRegistry++ _ensure_registries_populated()++ items: List[Dict[str, Any]] = []++ try:+ for name, tool_cls in ToolRegistry.items():+ if name in _BROWSER_SUB_TOOLS:+ continue+ spec = getattr(tool_cls, "spec", None)+ if callable(spec):+ try:+ spec = spec(tool_cls)+ except Exception:+ spec = None+ cred_keys = TOOL_CREDENTIALS.get(name, [])+ items.append({+ "name": name,+ "description": spec.description if spec else "",+ "category": spec.category if spec else "",+ "source": "tool",+ "requires_credentials": len(cred_keys) > 0,+ "credential_keys": cred_keys,+ "configured": (+ all(bool(os.environ.get(k)) for k in cred_keys)+ if cred_keys else True+ ),+ })+ except Exception:+ pass++ try:+ if any(ToolRegistry.contains(n) for n in _BROWSER_SUB_TOOLS):+ items.append({+ "name": "browser",+ "description": (+ "Web browser automation"+ " (navigate, click, type, screenshot, extract)"+ ),+ "category": "browser",+ "source": "tool",+ "requires_credentials": False,+ "credential_keys": [],+ "configured": True,+ })+ except Exception:+ pass++ try:+ for name, _cls in ChannelRegistry.items():+ cred_keys = TOOL_CREDENTIALS.get(name, [])+ items.append({+ "name": name,+ "description": f"{name.replace('_', ' ').title()} messaging channel",+ "category": "communication",+ "source": "channel",+ "requires_credentials": len(cred_keys) > 0,+ "credential_keys": cred_keys,+ "configured": (+ all(bool(os.environ.get(k)) for k in cred_keys)+ if cred_keys else True+ ),+ })+ except Exception:+ pass++ return items++def create_agent_manager_router(manager: AgentManager,-) -> Tuple[APIRouter, APIRouter, APIRouter]:+) -> Tuple[APIRouter, APIRouter, APIRouter, APIRouter]:"""Create FastAPI routers with agent management endpoints.- Returns a 3-tuple: (agents_router, templates_router, global_router).+ Returns a 4-tuple: (agents_router, templates_router, global_router, tools_router)."""agents_router = APIRouter(prefix="/v1/managed-agents", tags=["managed-agents"])templates_router = APIRouter(prefix="/v1/templates", tags=["templates"])@@ -153,15 +302,24 @@ def create_agent_manager_router(try:system = SystemBuilder().build()executor.set_system(system)- except Exception:- pass+ except Exception as build_err:+ manager.update_agent(agent_id, status="error")+ manager.update_summary_memory(+ agent_id,+ f"ERROR: Failed to build system: {build_err}",+ )+ returnexecutor.execute_tick(agent_id)- except Exception:+ except Exception as exc:try:manager.end_tick(agent_id)- manager.update_agent(agent_id, status="error")except Exception:pass+ manager.update_agent(agent_id, status="error")+ manager.update_summary_memory(+ agent_id,+ f"ERROR: {exc}",+ )threading.Thread(target=_run_tick, daemon=True).start()return {"status": "running", "agent_id": agent_id}@@ -170,10 +328,10 @@ def create_agent_manager_router(@agents_router.post("/{agent_id}/recover")def recover_agent(agent_id: str):+ if not manager.get_agent(agent_id):+ raise HTTPException(status_code=404, detail="Agent not found")checkpoint = manager.recover_agent(agent_id)- if checkpoint is None:- raise HTTPException(status_code=404, detail="No checkpoint found")- return checkpoint+ return {"recovered": True, "checkpoint": checkpoint}# ── Tasks ────────────────────────────────────────────────@@ -299,6 +457,7 @@ def create_agent_manager_router("duration": t.total_latency_seconds,"started_at": t.started_at,"steps": len(t.steps),+ "metadata": t.metadata,}for t in traces]@@ -376,4 +535,28 @@ def create_agent_manager_router("by_status": dict(counts),}- return agents_router, templates_router, global_router+ # ── Tools & credentials ──────────────────────────────────++ tools_router = APIRouter(prefix="/v1/tools", tags=["tools"])++ @tools_router.get("")+ def list_tools():+ return {"tools": build_tools_list()}++ @tools_router.post("/{tool_name}/credentials")+ async def save_tool_credentials(tool_name: str, request: Request):+ from openjarvis.core.credentials import save_credential++ body = await request.json()+ saved = []+ for key, value in body.items():+ save_credential(tool_name, key, value)+ saved.append(key)+ return {"saved": saved}++ @tools_router.get("/{tool_name}/credentials/status")+ def credential_status(tool_name: str):+ from openjarvis.core.credentials import get_credential_status+ return get_credential_status(tool_name)++ return agents_router, templates_router, global_router, tools_routerdiff --git a/src/openjarvis/server/api_routes.py b/src/openjarvis/server/api_routes.pyindex 6362dfc1..24b5a7fe 100644--- a/src/openjarvis/server/api_routes.py+++ b/src/openjarvis/server/api_routes.py@@ -759,12 +759,13 @@ def include_all_routes(app) -> None:from openjarvis.server.agent_manager_routes import ( # noqa: PLC0415create_agent_manager_router,)- agents_r, templates_r, global_r = create_agent_manager_router(+ agents_r, templates_r, global_r, tools_r = create_agent_manager_router(app.state.agent_manager)app.include_router(agents_r)app.include_router(templates_r)app.include_router(global_r)+ app.include_router(tools_r)except ImportError:passdiff --git a/tests/agents/test_executor_error_detail.py b/tests/agents/test_executor_error_detail.pynew file mode 100644index 00000000..aa4fbd81--- /dev/null+++ b/tests/agents/test_executor_error_detail.py@@ -0,0 +1,34 @@+"""Tests for structured error_detail in executor traces."""+from openjarvis.agents.errors import EscalateError, FatalError, RetryableError+from openjarvis.agents.executor import AgentExecutor+from openjarvis.core.events import EventBus+++def test_build_error_detail_fatal(tmp_path):+ from openjarvis.agents.manager import AgentManager+ mgr = AgentManager(db_path=str(tmp_path / "agents.db"))+ exe = AgentExecutor(manager=mgr, event_bus=EventBus())+ error = FatalError("401 unauthorized")+ detail = exe._build_error_detail(error)+ assert detail["error_type"] == "fatal"+ assert "401 unauthorized" in detail["error_message"]+ assert "API key" in detail["suggested_action"]+++def test_build_error_detail_retryable(tmp_path):+ from openjarvis.agents.manager import AgentManager+ mgr = AgentManager(db_path=str(tmp_path / "agents.db"))+ exe = AgentExecutor(manager=mgr, event_bus=EventBus())+ error = RetryableError("connection timed out")+ detail = exe._build_error_detail(error)+ assert detail["error_type"] == "retryable"+ assert "engine" in detail["suggested_action"].lower()+++def test_build_error_detail_escalate(tmp_path):+ from openjarvis.agents.manager import AgentManager+ mgr = AgentManager(db_path=str(tmp_path / "agents.db"))+ exe = AgentExecutor(manager=mgr, event_bus=EventBus())+ error = EscalateError("agent needs help")+ detail = exe._build_error_detail(error)+ assert detail["error_type"] == "escalate"diff --git a/tests/agents/test_manager_recover.py b/tests/agents/test_manager_recover.pynew file mode 100644index 00000000..81a3defd--- /dev/null+++ b/tests/agents/test_manager_recover.py@@ -0,0 +1,36 @@+"""Tests for AgentManager.recover_agent() always resetting status."""+import pytest++from openjarvis.agents.manager import AgentManager+++def manager(tmp_path):+ db = str(tmp_path / "agents.db")+ return AgentManager(db_path=db)+++def test_recover_resets_to_idle_without_checkpoint(manager):+ """recover_agent must reset status to idle even when no checkpoint exists."""+ agent = manager.create_agent(name="test", agent_type="monitor_operative")+ manager.update_agent(agent["id"], status="error")++ result = manager.recover_agent(agent["id"])++ assert result is None+ refreshed = manager.get_agent(agent["id"])+ assert refreshed["status"] == "idle"+++def test_recover_resets_to_idle_with_checkpoint(manager):+ """recover_agent returns checkpoint and resets status when checkpoint exists."""+ agent = manager.create_agent(name="test", agent_type="monitor_operative")+ manager.update_agent(agent["id"], status="error")+ manager.save_checkpoint(agent["id"], "tick-1", {"history": []}, {"tools": {}})++ result = manager.recover_agent(agent["id"])++ assert result is not None+ assert result["tick_id"] == "tick-1"+ refreshed = manager.get_agent(agent["id"])+ assert refreshed["status"] == "idle"diff --git a/tests/agents/test_suggest_action.py b/tests/agents/test_suggest_action.pynew file mode 100644index 00000000..004ed738--- /dev/null+++ b/tests/agents/test_suggest_action.py@@ -0,0 +1,28 @@+"""Tests for suggest_action helper."""+from openjarvis.agents.errors import FatalError, RetryableError, suggest_action+++def test_suggest_action_rate_limit():+ err = RetryableError("rate limit exceeded")+ assert "auto-retry" in suggest_action(err).lower()+++def test_suggest_action_timeout():+ err = RetryableError("connection timed out")+ assert "engine" in suggest_action(err).lower()+++def test_suggest_action_auth():+ err = FatalError("401 unauthorized")+ assert "API key" in suggest_action(err)+++def test_suggest_action_not_found():+ err = FatalError("model not found (404)")+ action = suggest_action(err).lower()+ assert "model name" in action or "endpoint" in action+++def test_suggest_action_unknown():+ err = RetryableError("something weird happened")+ assert "trace" in suggest_action(err).lower()diff --git a/tests/core/test_credentials.py b/tests/core/test_credentials.pynew file mode 100644index 00000000..e5679d47--- /dev/null+++ b/tests/core/test_credentials.py@@ -0,0 +1,55 @@+"""Tests for credential persistence module."""+import os++import pytest++from openjarvis.core.credentials import (+ get_credential_status,+ load_credentials,+ save_credential,+)+++def cred_path(tmp_path):+ return tmp_path / "credentials.toml"+++def test_save_and_load(cred_path):+ save_credential("web_search", "TAVILY_API_KEY", "tvly-123", path=cred_path)+ creds = load_credentials(path=cred_path)+ assert creds["web_search"]["TAVILY_API_KEY"] == "tvly-123"+++def test_save_sets_env(cred_path, monkeypatch):+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)+ save_credential("web_search", "TAVILY_API_KEY", "tvly-abc", path=cred_path)+ assert os.environ["TAVILY_API_KEY"] == "tvly-abc"+++def test_save_rejects_unknown_key(cred_path):+ with pytest.raises(ValueError, match="Unknown credential key"):+ save_credential("web_search", "BOGUS_KEY", "val", path=cred_path)+++def test_save_rejects_empty_value(cred_path):+ with pytest.raises(ValueError, match="empty"):+ save_credential("web_search", "TAVILY_API_KEY", " ", path=cred_path)+++def test_get_status(cred_path, monkeypatch):+ monkeypatch.setenv("TAVILY_API_KEY", "tvly-x")+ status = get_credential_status("web_search")+ assert status["TAVILY_API_KEY"] is True+++def test_get_status_missing(monkeypatch):+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)+ status = get_credential_status("web_search")+ assert status["TAVILY_API_KEY"] is False+++def test_file_permissions(cred_path):+ save_credential("web_search", "TAVILY_API_KEY", "tvly-x", path=cred_path)+ mode = oct(cred_path.stat().st_mode & 0o777)+ assert mode == "0o600"diff --git a/tests/server/test_agent_manager_routes.py b/tests/server/test_agent_manager_routes.pyindex 5f7e08ba..b694edd5 100644--- a/tests/server/test_agent_manager_routes.py+++ b/tests/server/test_agent_manager_routes.py@@ -35,12 +35,12 @@ class TestAgentManagerRoutes:from openjarvis.server.agent_manager_routes import create_agent_manager_routerapp = FastAPI()- agents_router, templates_router, global_router = create_agent_manager_router(- manager- )+ routers = create_agent_manager_router(manager)+ agents_router, templates_router, global_router, tools_router = routersapp.include_router(agents_router)app.include_router(templates_router)app.include_router(global_router)+ app.include_router(tools_router)return TestClient(app)def test_list_agents_empty(self, client):@@ -141,12 +141,21 @@ class TestAgentManagerRoutes:res = client.post(f"/v1/managed-agents/{agent['id']}/recover")assert res.status_code == 200- assert res.json()["tick_id"] == "tick-1"+ body = res.json()+ assert body["recovered"] is True+ assert body["checkpoint"]["tick_id"] == "tick-1"def test_recover_agent_no_checkpoint(self, manager, client):agent = manager.create_agent(name="err", agent_type="simple")+ manager.update_agent(agent["id"], status="error")res = client.post(f"/v1/managed-agents/{agent['id']}/recover")- assert res.status_code == 404+ assert res.status_code == 200+ body = res.json()+ assert body["recovered"] is True+ assert body["checkpoint"] is None+ # Status should be reset to idle+ refreshed = manager.get_agent(agent["id"])+ assert refreshed["status"] == "idle"def test_list_error_agents(self, manager, client):manager.create_agent(name="ok", agent_type="simple")diff --git a/tests/server/test_tools_endpoint.py b/tests/server/test_tools_endpoint.pynew file mode 100644index 00000000..414b194d--- /dev/null+++ b/tests/server/test_tools_endpoint.py@@ -0,0 +1,43 @@+"""Tests for GET /v1/tools endpoint."""+import pytest++try:+ from openjarvis.server.agent_manager_routes import build_tools_list+except ImportError:+ build_tools_list = None++pytestmark = pytest.mark.skipif(+ build_tools_list is None,+ reason="fastapi not installed (requires server extra)",+)+++def test_tools_endpoint_returns_list():+ from openjarvis.server.agent_manager_routes import build_tools_list+ tools = build_tools_list()+ assert isinstance(tools, list)+ assert len(tools) > 0+ for t in tools:+ assert "name" in t+ assert "description" in t+ assert "category" in t+ assert "source" in t+ assert "requires_credentials" in t+ assert "credential_keys" in t+ assert "configured" in t+++def test_tools_includes_channels():+ from openjarvis.server.agent_manager_routes import build_tools_list+ tools = build_tools_list()+ names = {t["name"] for t in tools}+ channel_names = {"slack", "telegram", "discord", "email"}+ assert channel_names & names+++def test_browser_meta_group():+ from openjarvis.server.agent_manager_routes import build_tools_list+ tools = build_tools_list()+ names = {t["name"] for t in tools}+ assert "browser" in names+ assert "browser_navigate" not in names