Amitkasar's picture
Add multi-LLM support, settings & migrations
1e24842
Raw History Blame Contribute Delete
18.3 kB
import React, { useEffect, useState } from 'react';
import { Bot, Check, ChevronDown, Clock, Cpu, Eye, EyeOff, Shield, X } from 'lucide-react';
import { LLMSettingsService } from '../services/api';
const SETTINGS_KEY = '_app_settings';
const DEFAULTS = {
httpTimeout: 120,
tokenBudget: 100000,
theme: 'dark',
};
function loadSettings() {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
return raw ? { ...DEFAULTS, ...JSON.parse(raw) } : { ...DEFAULTS };
} catch {
return { ...DEFAULTS };
}
}
function saveSettings(s) {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
}
export function useAppSettings() {
const [settings, setSettings] = useState(loadSettings);
useEffect(() => { saveSettings(settings); }, [settings]);
const update = (key, value) => setSettings(prev => ({ ...prev, [key]: value }));
return { settings, update };
}
// ── Shared styles ─────────────────────────────────────────────────────────────
const sectionStyle = {
background: 'var(--bg-2)',
border: '1px solid var(--line-2)',
borderRadius: 10,
padding: '16px 20px',
};
const labelStyle = {
fontSize: 10,
textTransform: 'uppercase',
letterSpacing: '0.1em',
color: 'var(--fg-3)',
fontWeight: 700,
display: 'block',
marginBottom: 6,
};
const sectionHeadStyle = {
display: 'flex',
alignItems: 'center',
gap: 8,
marginBottom: 16,
};
// ── AI Models section ─────────────────────────────────────────────────────────
function ProviderCard({ provider, onSave, onClear }) {
const [key, setKey] = useState('');
const [show, setShow] = useState(false);
const [saving, setSaving] = useState(false);
const [flash, setFlash] = useState(null); // 'ok' | 'err'
const handleSave = async () => {
if (!key.trim()) return;
setSaving(true);
try {
await onSave(provider.provider_id, key.trim());
setKey('');
setFlash('ok');
} catch {
setFlash('err');
} finally {
setSaving(false);
setTimeout(() => setFlash(null), 2000);
}
};
const handleClear = async () => {
await onClear(provider.provider_id);
};
return (
<div style={{
border: '1px solid var(--line-2)',
borderRadius: 8,
padding: '12px 14px',
background: 'var(--bg-1)',
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>{provider.display_name}</span>
<span style={{
fontSize: 10,
fontWeight: 700,
padding: '2px 8px',
borderRadius: 10,
background: provider.is_active ? 'var(--ok-muted, rgba(52,199,89,0.12))' : 'var(--bg-3)',
color: provider.is_active ? 'var(--ok)' : 'var(--fg-3)',
}}>
{provider.is_active ? 'Configured' : 'Not set'}
</span>
</div>
{provider.key_preview && (
<div style={{ fontSize: 11, color: 'var(--fg-3)', marginBottom: 8, fontFamily: 'monospace' }}>
Current key: {provider.key_preview}
</div>
)}
<div style={{ display: 'flex', gap: 6 }}>
<div style={{ flex: 1, position: 'relative' }}>
<input
type={show ? 'text' : 'password'}
placeholder="Paste new API key…"
value={key}
onChange={e => setKey(e.target.value)}
className="input"
style={{ width: '100%', paddingRight: 32, fontSize: 12 }}
/>
<button
onClick={() => setShow(v => !v)}
style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-3)', padding: 0 }}
>
{show ? <EyeOff size={13} /> : <Eye size={13} />}
</button>
</div>
<button
onClick={handleSave}
disabled={saving || !key.trim()}
className="btn btn-primary"
style={{ fontSize: 12, padding: '0 12px', minWidth: 60 }}
>
{flash === 'ok' ? <Check size={12} /> : flash === 'err' ? <X size={12} /> : saving ? '…' : 'Save'}
</button>
{provider.is_active && (
<button onClick={handleClear} className="btn" style={{ fontSize: 12, padding: '0 10px', color: 'var(--danger, #ff453a)' }}>
Clear
</button>
)}
</div>
</div>
);
}
function TaskRow({ task, providers, registry, onSave }) {
const [provId, setProvId] = useState(task.provider_id || '');
const [model, setModel] = useState(task.model_name || '');
const [temp, setTemp] = useState(task.temperature ?? 0.0);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const activeProviders = providers.filter(p => p.is_active);
const models = provId && registry[provId] ? registry[provId].models : [];
useEffect(() => {
if (!models.includes(model)) setModel(models[0] || '');
}, [provId]);
const handleSave = async () => {
setSaving(true);
try {
await onSave(task.task_name, { provider_id: provId || null, model_name: model || null, temperature: temp });
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} finally {
setSaving(false);
}
};
const noKey = provId && !providers.find(p => p.provider_id === provId)?.is_active;
return (
<div style={{
display: 'grid',
gridTemplateColumns: '160px 1fr 1fr 80px 80px',
gap: 8,
alignItems: 'center',
padding: '10px 0',
borderBottom: '1px solid var(--line-2)',
}}>
<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-0)' }}>{task.label}</span>
{/* Provider dropdown */}
<div style={{ position: 'relative' }}>
<select
value={provId}
onChange={e => { setProvId(e.target.value); setModel(''); }}
className="input"
style={{ width: '100%', fontSize: 12, appearance: 'none', paddingRight: 24 }}
>
<option value="" disabled>Select a provider…</option>
{activeProviders.map(p => (
<option key={p.provider_id} value={p.provider_id}>{p.display_name}</option>
))}
</select>
<ChevronDown size={12} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--fg-3)' }} />
</div>
{/* Model dropdown */}
<div style={{ position: 'relative' }}>
<select
value={model}
onChange={e => setModel(e.target.value)}
disabled={!provId}
className="input"
style={{ width: '100%', fontSize: 12, appearance: 'none', paddingRight: 24, opacity: provId ? 1 : 0.5 }}
>
{models.length === 0 && <option value="">β€”</option>}
{models.map(m => <option key={m} value={m}>{m}</option>)}
</select>
<ChevronDown size={12} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--fg-3)' }} />
</div>
{/* Temperature */}
<input
type="number"
min={0}
max={1}
step={0.1}
value={temp}
onChange={e => setTemp(parseFloat(e.target.value) || 0)}
className="input"
style={{ fontSize: 12, textAlign: 'center' }}
/>
{/* Save button */}
<button
onClick={handleSave}
disabled={saving || noKey}
className={`btn${saved ? '' : ' btn-primary'}`}
style={{ fontSize: 11, padding: '0 8px' }}
title={noKey ? 'Save an API key for this provider first' : ''}
>
{saved ? <Check size={12} /> : saving ? '…' : 'Apply'}
</button>
</div>
);
}
function AIModelsSection() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const load = async () => {
setLoading(true);
setError(null);
try {
const d = await LLMSettingsService.get();
setData(d);
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => { load(); }, []);
const handleSaveKey = async (providerId, apiKey) => {
await LLMSettingsService.saveProviderKey(providerId, apiKey);
// Auto-configure any task that has no provider set yet
const current = await LLMSettingsService.get();
const registry = current.registry[providerId];
const defaultModel = registry?.models?.[0] || '';
await Promise.all(
current.tasks
.filter(t => !t.provider_id)
.map(t => LLMSettingsService.saveTaskConfig(t.task_name, {
provider_id: providerId,
model_name: defaultModel,
temperature: t.temperature ?? 0.0,
}))
);
await load();
};
const handleClearKey = async (providerId) => {
await LLMSettingsService.deleteProviderKey(providerId);
await load();
};
const handleSaveTask = async (taskName, config) => {
await LLMSettingsService.saveTaskConfig(taskName, config);
};
const handleApplyAll = async (providerId) => {
const registry = data.registry[providerId];
const defaultModel = registry?.models?.[0] || '';
await Promise.all(
data.tasks.map(t => LLMSettingsService.saveTaskConfig(t.task_name, {
provider_id: providerId,
model_name: defaultModel,
temperature: t.temperature ?? 0.0,
}))
);
await load();
};
return (
<section style={sectionStyle}>
<div style={sectionHeadStyle}>
<Bot size={15} style={{ color: 'var(--accent)' }} />
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>AI Models</span>
</div>
{loading && <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Loading…</div>}
{error && <div style={{ fontSize: 12, color: 'var(--danger, #ff453a)' }}>{error}</div>}
{data && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
{/* Provider API keys */}
<div>
<label style={labelStyle}>API Keys</label>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{data.providers.map(p => (
<ProviderCard
key={p.provider_id}
provider={p}
onSave={handleSaveKey}
onClear={handleClearKey}
/>
))}
</div>
</div>
{/* Task routing */}
<div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
<label style={{ ...labelStyle, marginBottom: 0 }}>Task Routing</label>
{data.providers.filter(p => p.is_active).length > 0 && (
<div style={{ display: 'flex', gap: 6 }}>
{data.providers.filter(p => p.is_active).map(p => (
<button
key={p.provider_id}
onClick={() => handleApplyAll(p.provider_id)}
className="btn"
style={{ fontSize: 11, padding: '2px 10px' }}
>
Apply {p.display_name} to all
</button>
))}
</div>
)}
</div>
{data.tasks.some(t => !t.provider_id) && (
<div style={{ fontSize: 11, color: 'var(--warning, #ff9f0a)', background: 'rgba(255,159,10,0.08)', border: '1px solid rgba(255,159,10,0.2)', borderRadius: 6, padding: '6px 10px', marginBottom: 8 }}>
Some tasks have no provider set β€” plan generation and execution will fail until all tasks are configured. Use the button above to apply in one click.
</div>
)}
{/* Header row */}
<div style={{
display: 'grid',
gridTemplateColumns: '160px 1fr 1fr 80px 80px',
gap: 8,
paddingBottom: 6,
borderBottom: '1px solid var(--line-2)',
}}>
{['Task', 'Provider', 'Model', 'Temp', ''].map((h, i) => (
<span key={i} style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-3)' }}>{h}</span>
))}
</div>
{data.tasks.map(t => (
<TaskRow
key={t.task_name}
task={t}
providers={data.providers}
registry={data.registry}
onSave={handleSaveTask}
/>
))}
</div>
</div>
)}
</section>
);
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function SettingsPage() {
const [settings, setSettings] = useState(loadSettings);
const [saved, setSaved] = useState(false);
const update = (key, value) => setSettings(prev => ({ ...prev, [key]: value }));
const handleSave = () => {
saveSettings(settings);
setSaved(true);
setTimeout(() => setSaved(false), 2000);
};
return (
<div className="page">
<div className="page-inner" style={{ maxWidth: 720 }}>
<div style={{ marginBottom: 24 }}>
<div className="h-eyebrow">Configuration</div>
<h1 style={{ fontSize: 18, fontWeight: 600, color: 'var(--fg-0)', letterSpacing: '-0.01em', margin: '4px 0 0', display: 'flex', alignItems: 'center', gap: 8 }}>
<Cpu size={18} style={{ color: 'var(--accent)' }} />
Settings
</h1>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* AI Models β€” live backend config */}
<AIModelsSection />
{/* HTTP */}
<section style={sectionStyle}>
<div style={sectionHeadStyle}>
<Clock size={15} style={{ color: 'var(--accent)' }} />
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>HTTP Execution</span>
</div>
<div>
<label style={labelStyle}>Request Timeout</label>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<input
type="number"
min={5}
max={600}
step={5}
value={settings.httpTimeout}
onChange={e => update('httpTimeout', parseInt(e.target.value, 10) || DEFAULTS.httpTimeout)}
className="input"
style={{ width: 100 }}
/>
<span style={{ fontSize: 11, color: 'var(--fg-3)' }}>seconds</span>
</div>
<p style={{ fontSize: 11, color: 'var(--fg-3)', margin: '6px 0 0' }}>
Note: the backend timeout is set in <code>execution.py</code>. This setting is for reference.
</p>
</div>
</section>
{/* Token budget */}
<section style={sectionStyle}>
<div style={sectionHeadStyle}>
<Cpu size={15} style={{ color: 'var(--accent)' }} />
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>Usage Limits</span>
</div>
<div>
<label style={labelStyle}>Token Budget (max tokens per session)</label>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<input
type="number"
min={1000}
max={2000000}
step={1000}
value={settings.tokenBudget}
onChange={e => update('tokenBudget', parseInt(e.target.value, 10) || DEFAULTS.tokenBudget)}
className="input"
style={{ width: 140 }}
/>
<span style={{ fontSize: 11, color: 'var(--fg-3)' }}>tokens</span>
</div>
<p style={{ fontSize: 11, color: 'var(--fg-3)', margin: '6px 0 0' }}>
Sessions exceeding this limit will be blocked. Set high to disable the guard.
</p>
</div>
</section>
{/* Security info */}
<section style={sectionStyle}>
<div style={sectionHeadStyle}>
<Shield size={15} style={{ color: 'var(--accent)' }} />
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>Security</span>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{[
'Credentials and API keys are encrypted at rest with Fernet symmetric encryption.',
'SSRF protection is enabled β€” private/loopback IPs are blocked.',
'Rate limiting is active (10 plan/min, 30 execute/min, 20 chat/min).',
'JWTs expire after the configured JWT_EXPIRE_HOURS from .env.',
].map((text, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.5 }}>
<Check size={12} style={{ color: 'var(--ok)', flexShrink: 0, marginTop: 2 }} />
{text}
</div>
))}
</div>
</section>
{/* Save (for localStorage settings) */}
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<button
onClick={handleSave}
className={`btn${saved ? '' : ' btn-primary'}`}
style={{ gap: 8, minWidth: 120 }}
>
{saved ? <><Check size={13} /> Saved!</> : 'Save settings'}
</button>
</div>
</div>
</div>
</div>
);
}