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
 
7457a6f
1e24842
 
 
 
 
 
 
 
 
 
 
 
7457a6f
 
 
1e24842
 
 
 
 
 
 
 
 
7457a6f
 
 
 
 
1e24842
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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>
  );
}