ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(settings): add connected AI model policies and usage views
Juan Denis7d5623bccbb8
diff --git a/frontend/src/components/ai/ConnectionSelector.jsx b/frontend/src/components/ai/ConnectionSelector.jsxindex d4004eb3..821454e2 100644--- a/frontend/src/components/ai/ConnectionSelector.jsx+++ b/frontend/src/components/ai/ConnectionSelector.jsx@@ -1,22 +1,37 @@import { FormField } from '../FormField';import { useServerkitAI } from '../../contexts/useServerkitAI';import { useTranslation } from 'react-i18next';+import ModelBinding from './ModelBinding';export default function ConnectionSelector() {const { t } = useTranslation();- const { connections, selectedConnection, selectedModel, selectConnection, selectModel, activeId, isStreaming } = useServerkitAI();+ const { connections, selectedConnection, selectedModel, selectConnection, selectModel,+ profile, workflow, selectProfile, selectWorkflow, activeId, isStreaming } = useServerkitAI();if (activeId || !connections.length) return null;return (- <div className="sk-ai-connection-selector">- <FormField htmlFor="ai-chat-connection" label={<>{t('ai.connections.connection', 'Connection')}</>}>- <select id="ai-chat-connection" value={selectedConnection} disabled={isStreaming} onChange={(event) => selectConnection(event.target.value)}>- <option value="">{t('ai.connections.panelDefault', 'Panel default')}</option>- {connections.map((connection) => <option key={connection.id} value={connection.id}>{connection.name}</option>)}+ <div className="sk-ai-task-selector">+ <div className="sk-ai-connection-selector">+ <FormField htmlFor="ai-chat-workflow" label={t('ai.tasks.task', 'Task')}>+ <select id="ai-chat-workflow" value={workflow} disabled={isStreaming} onChange={(e) => selectWorkflow(e.target.value)}>+ <option value="chat">{t('ai.tasks.chat', 'Chat')}</option>+ <option value="summarize">{t('ai.tasks.summarize', 'Summarize')}</option>+ <option value="extract">{t('ai.tasks.extract', 'Extract structured facts')}</option>+ <option value="diagnose">{t('ai.tasks.diagnose', 'Read-only diagnosis')}</option></select></FormField>- <FormField htmlFor="ai-chat-model" label={<>{t('ai.connections.model', 'Model')}</>}>- <input id="ai-chat-model" value={selectedModel} disabled={isStreaming} maxLength={256} onChange={(event) => selectModel(event.target.value)} placeholder={t('ai.connections.connectionDefault', 'Connection default')} />+ <FormField htmlFor="ai-chat-profile" label={t('ai.tasks.role', 'Model role')}>+ <select id="ai-chat-profile" value={profile} disabled={isStreaming} onChange={(e) => selectProfile(e.target.value)}>+ <option value="">{t('ai.tasks.automatic', 'Task default / automatic routing')}</option>+ <option value="utility">{t('ai.management.utility', 'Utility')}</option>+ <option value="standard">{t('ai.management.standard', 'Standard')}</option>+ <option value="advanced">{t('ai.management.advanced', 'Advanced')}</option>+ </select></FormField>+ </div>+ <details><summary>{t('ai.tasks.override', 'Override connection and model')}</summary>+ <ModelBinding id="ai-chat" value={selectedConnection ? { connection_id: selectedConnection, model: selectedModel } : null}+ connections={connections} disabled={isStreaming} allowInherit inheritLabel={t('ai.tasks.useTaskModel', 'Use selected task model')} onChange={(next) => { selectConnection(next?.connection_id || ''); selectModel(next?.model || ''); }} />+ </details></div>);}diff --git a/frontend/src/components/ai/Message.jsx b/frontend/src/components/ai/Message.jsxindex da50d026..aa35f8ff 100644--- a/frontend/src/components/ai/Message.jsx+++ b/frontend/src/components/ai/Message.jsx@@ -1,8 +1,14 @@import Markdown from './Markdown';import ToolCallCard from './ToolCallCard';import AttachmentChip from './AttachmentChip';+import { useTranslation } from 'react-i18next';+import useFormat from '../../hooks/useFormat';const Message = ({ message }) => {+ const { t } = useTranslation();+ const { formatNumber } = useFormat();+ const money = (amount) => t('ai.usage.usd', '{{amount}} USD', { amount: formatNumber(amount, { maximumFractionDigits: 4 }) });+ const usage = message.usage;if (message.role === 'user') {return (<div className="sk-ai-message sk-ai-message--user">@@ -30,6 +36,15 @@ const Message = ({ message }) => {{message.status === 'error' ? (<div className="sk-ai-message__error">{message.error || 'Something went wrong.'}</div>) : null}+ {usage?.run_id && <details className="sk-ai-message__usage">+ <summary>{usage.model} · {formatNumber(usage.total_tokens || 0)} {t('ai.usage.tokens', 'Tokens')} · {usage.cost_source === 'unknown' ? t('ai.usage.unknown', 'Unknown') : money(usage.cost || 0)}</summary>+ <p>{usage.reason}</p>+ <p>{t('ai.usage.runSummary', '{{profile}} · {{calls}} provider calls · {{errors}} errors · {{seconds}} seconds', { profile: usage.profile, calls: usage.call_count, errors: usage.errors, seconds: formatNumber((usage.duration_ms || 0) / 1000, { maximumFractionDigits: 1 }) })}</p>+ <p>{t('ai.usage.source', 'Cost source: {{source}}', { source: usage.cost_source })}</p>+ {usage.budget?.cost_remaining != null && <p>{t('ai.usage.costRemaining', 'Conversation cost allowance remaining: {{amount}}', { amount: money(usage.budget.cost_remaining) })}</p>}+ {usage.budget?.tokens_remaining != null && <p>{t('ai.usage.tokensRemaining', 'Conversation tokens remaining: {{count}}', { count: usage.budget.tokens_remaining })}</p>}+ {usage.budget?.exceeded && <p role="status">{t('ai.usage.budgetWarning', 'The conversation allowance has been reached. Further calls follow the configured budget policy.')}</p>}+ </details>}</div>);};diff --git a/frontend/src/components/ai/ModelBinding.jsx b/frontend/src/components/ai/ModelBinding.jsxnew file mode 100644index 00000000..dd07b22d--- /dev/null+++ b/frontend/src/components/ai/ModelBinding.jsx@@ -0,0 +1,43 @@+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import api from '../../services/api';+import { FormField } from '../FormField';+import { Button } from '../ui/button';+import ModelPicker from './ModelPicker';++export default function ModelBinding({ id, value, onChange, connections, disabled, allowInherit = false, inheritLabel, discover = false }) {+ const { t } = useTranslation();+ const [models, setModels] = useState(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const connection = connections.find((item) => item.id === value?.connection_id);+ const catalog = models || connection?.model_catalog || [];+ const refresh = async () => {+ setBusy(true); setError('');+ try {+ const result = await api.aiProbeConnection({ ...connection, test: false });+ setModels(result.model_details || result.models || []);+ } catch (e) { setError(e.message); }+ finally { setBusy(false); }+ };+ return <div className="sk-ai-binding">+ <FormField htmlFor={`${id}-connection`} label={t('ai.connections.connection', 'Connection')}>+ <select id={`${id}-connection`} disabled={disabled || busy} value={value?.connection_id || ''} onChange={(event) => {+ const next = connections.find((item) => item.id === event.target.value);+ setModels(null); setError('');+ onChange(next ? { connection_id: next.id, model: next.model } : null);+ }}>+ <option value="">{allowInherit ? (inheritLabel || t('ai.management.inherit', 'Use Standard / panel default')) : t('ai.management.chooseConnection', 'Choose a connection')}</option>+ {connections.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}+ </select>+ </FormField>+ {value && <FormField htmlFor={`${id}-model`} label={t('ai.connections.model', 'Model')}>+ <ModelPicker id={`${id}-model`} value={value.model} models={catalog} disabled={disabled || busy}+ onChange={(model) => onChange({ ...value, model })} />+ </FormField>}+ {discover && connection && <Button variant="outline" type="button" disabled={disabled || busy} onClick={refresh}>+ {busy ? t('ai.connections.discovering', 'Discovering…') : t('ai.connections.discover', 'Discover models')}+ </Button>}+ {error && <p className="error-message" role="alert">{error}</p>}+ </div>;+}diff --git a/frontend/src/components/ai/ModelPicker.jsx b/frontend/src/components/ai/ModelPicker.jsxindex 36eec903..66e3e92b 100644--- a/frontend/src/components/ai/ModelPicker.jsx+++ b/frontend/src/components/ai/ModelPicker.jsx@@ -10,6 +10,11 @@ import { Command, CommandInput, CommandList, CommandEmpty, CommandItem } from '.export default function ModelPicker({ id, value, models, onChange, disabled }) {const { t } = useTranslation();const [open, setOpen] = useState(false);+ const [filter, setFilter] = useState('all');+ const choices = [...new Map(models.map((model) => {+ const item = typeof model === 'string' ? { id: model } : model;+ return [item.id, item];+ })).values()].filter((model) => filter === 'all' || model[filter] === true);return (<div className="sk-model-picker"><Input id={id} value={value} maxLength={256} disabled={disabled}@@ -27,12 +32,31 @@ export default function ModelPicker({ id, value, models, onChange, disabled }) {aria-label={t('ai.connections.chooseModel', 'Choose a model')}><Command><CommandInput placeholder={t('ai.connections.searchModels', 'Search models…')} />+ <div className="sk-model-picker__filters">+ <label htmlFor={`${id}-filter`}>{t('ai.models.capability', 'Capability')}</label>+ <select id={`${id}-filter`} value={filter} onChange={(event) => setFilter(event.target.value)}>+ <option value="all">{t('ai.models.all', 'All models')}</option>+ <option value="tools">{t('ai.models.tools', 'Tool calling')}</option>+ <option value="vision">{t('ai.models.vision', 'Vision')}</option>+ <option value="reasoning">{t('ai.models.reasoning', 'Reasoning')}</option>+ <option value="structured">{t('ai.models.structured', 'Structured output')}</option>+ </select>+ </div><CommandList><CommandEmpty>{t('ai.connections.noModels', 'No matching models. Enter a model ID manually.')}</CommandEmpty>- {[...new Set(models)].map((model) => (- <CommandItem key={model} value={model} onSelect={() => { onChange(model); setOpen(false); }}>- <span className="sk-model-picker__name">{model}</span>- {value === model && <Check size={16} />}+ {choices.map((model) => (+ <CommandItem key={model.id} value={model.id} onSelect={() => { onChange(model.id); setOpen(false); }}>+ <span className="sk-model-picker__name">{model.id}+ <small>{model.context_window ? t('ai.models.context', '{{count}} token context', { count: model.context_window }) : t('ai.models.unknownContext', 'Context unknown')}+ {' · '}{model.pricing ? t('ai.models.prices', '{{input}} USD input / {{output}} USD output per 1M tokens', { input: model.pricing.input, output: model.pricing.output }) : t('ai.models.unknownPrice', 'Pricing unknown')}+ </small>+ <small>{[+ model.tools && t('ai.models.tools', 'Tool calling'), model.vision && t('ai.models.vision', 'Vision'),+ model.structured && t('ai.models.structured', 'Structured output'), model.reasoning && t('ai.models.reasoning', 'Reasoning'),+ model.max_output_tokens && t('ai.models.outputLimit', '{{count}} maximum output tokens', { count: model.max_output_tokens }),+ ].filter(Boolean).join(' · ')}</small>+ </span>+ {value === model.id && <Check size={16} />}</CommandItem>))}</CommandList>diff --git a/frontend/src/components/settings/AIConnectionsSettings.jsx b/frontend/src/components/settings/AIConnectionsSettings.jsxindex 64e13e72..e808377f 100644--- a/frontend/src/components/settings/AIConnectionsSettings.jsx+++ b/frontend/src/components/settings/AIConnectionsSettings.jsx@@ -85,7 +85,7 @@ export default function AIConnectionsSettings({ connections, providers, defaultIconst result = await api.aiProbeConnection({ ...draft, test: operation === 'test' });if (current !== revision.current) return;if (operation === 'models') {- setModels(result.models || []);+ setModels(result.model_details || result.models || []);setMessage({ type: 'success', text: t('ai.connections.modelsFound', '{{count}} models found. You can also enter a model ID manually.', { count: result.models?.length || 0 }) });} else setMessage({ type: 'success', text: result.message || t('ai.connections.verified', 'Connection verified.') });}diff --git a/frontend/src/components/settings/AIManagementSettings.jsx b/frontend/src/components/settings/AIManagementSettings.jsxnew file mode 100644index 00000000..5639b5f7--- /dev/null+++ b/frontend/src/components/settings/AIManagementSettings.jsx@@ -0,0 +1,142 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import api from '../../services/api';+import { FormField } from '../FormField';+import { Input } from '../ui/input';+import { Button } from '../ui/button';+import { Switch } from '../ui/switch';+import ModelBinding from '../ai/ModelBinding';+import EmptyState from '../EmptyState';++export default function AIManagementSettings({ connections, defaultId }) {+ const { t } = useTranslation();+ const [config, setConfig] = useState(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [saved, setSaved] = useState(false);+ const [sample, setSample] = useState('');+ const [preview, setPreview] = useState(null);+ const defaultConnection = connections.find((item) => item.id === defaultId);+ const inherited = config?.profiles.standard || (defaultConnection && { connection_id: defaultId, model: defaultConnection.model });+ const load = () => api.aiGetManagement().then(setConfig).catch((e) => setError(e.message));+ useEffect(() => { let active = true; api.aiGetManagement().then((data) => { if (active) setConfig(data); }).catch((e) => { if (active) setError(e.message); }); return () => { active = false; }; }, []);+ const change = (key, value) => { setConfig((current) => ({ ...current, [key]: value })); setSaved(false); setPreview(null); };+ const submit = async () => {+ setBusy(true); setError('');+ try {+ setConfig(await api.aiSaveManagement(config)); setSaved(true);+ window.dispatchEvent(new Event('serverkit:ai-config-changed'));+ } catch (e) { setError(e.message); }+ finally { setBusy(false); }+ };+ const previewRoute = async () => {+ setBusy(true); setError('');+ try { setPreview(await api.aiPreviewRouting({ message: sample, config })); }+ catch (e) { setError(e.message); }+ finally { setBusy(false); }+ };+ if (!config) return <div className="settings-card">{error ? <><p role="alert">{error}</p><Button onClick={load}>{t('common.retry', 'Retry')}</Button></> : <EmptyState loading title={t('common.loading', 'Loading…')} />}</div>;+ const profiles = [+ ['utility', t('ai.management.utility', 'Utility'), t('ai.management.utilityHint', 'Economical model for summaries and structured extraction.')],+ ['standard', t('ai.management.standard', 'Standard'), t('ai.management.standardHint', 'Everyday questions and tool-assisted troubleshooting.')],+ ['advanced', t('ai.management.advanced', 'Advanced'), t('ai.management.advancedHint', 'Complex analysis and read-only diagnostic tasks.')],+ ];+ const numberField = (key, label, min, max, hint, step = '1') => <FormField key={key} htmlFor={`ai-${key}`} label={label} hint={hint}>+ <Input id={`ai-${key}`} type="number" min={min} max={max} step={step} value={config[key]} disabled={busy} onChange={(e) => change(key, e.target.value)} />+ </FormField>;+ const toggle = (key, label) => <div className="settings-row"><label htmlFor={`ai-${key}`}>{label}</label>+ <Switch id={`ai-${key}`} checked={config[key]} disabled={busy} onCheckedChange={(value) => change(key, value)} /></div>;+ const candidates = (key) => <div className="sk-ai-candidates">+ {config[key].map((candidate, index) => <div className="sk-ai-candidates__row" key={`${key}-${index}`}>+ <ModelBinding id={`ai-${key}-${index}`} value={candidate} connections={connections} disabled={busy} discover onChange={(next) => change(key, config[key].map((item, i) => i === index ? { ...next, ...(key === 'pool' ? { tier: candidate.tier } : {}) } : item))} />+ {key === 'pool' && <FormField htmlFor={`ai-tier-${index}`} label={t('ai.management.tier', 'Capability tier')}>+ <select id={`ai-tier-${index}`} value={candidate.tier} disabled={busy} onChange={(e) => change(key, config[key].map((item, i) => i === index ? { ...item, tier: e.target.value } : item))}>+ <option value="budget">{t('ai.management.utility', 'Utility')}</option><option value="standard">{t('ai.management.standard', 'Standard')}</option><option value="premium">{t('ai.management.advanced', 'Advanced')}</option>+ </select>+ </FormField>}+ <div className="settings-actions">+ {key === 'fallbacks' && <Button type="button" variant="outline" disabled={busy || index === 0} onClick={() => { const next = [...config[key]]; [next[index - 1], next[index]] = [next[index], next[index - 1]]; change(key, next); }}>{t('ai.management.moveUp', 'Move up')}</Button>}+ <Button type="button" variant="ghost" disabled={busy} onClick={() => change(key, config[key].filter((_, i) => i !== index))}>{t('common.actions.remove', 'Remove')}</Button>+ </div>+ </div>)}+ <Button type="button" variant="outline" disabled={busy || !connections.length || config[key].length >= 12} onClick={() => change(key, [...config[key], { connection_id: connections[0].id, model: connections[0].model, ...(key === 'pool' ? { tier: 'standard' } : {}) }])}>+ {t('ai.management.addCandidate', 'Add model candidate')}+ </Button>+ </div>;+ return <div className="sk-ai-management">+ <section className="settings-card">+ <h3>{t('ai.management.taskModels', 'Task models')}</h3>+ <p>{t('ai.management.taskModelsHint', 'Choose models by task. New chats resolve these roles; existing chats keep their selected connection.')}</p>+ {profiles.map(([key, label, hint]) => <div className="sk-ai-profile" key={key}>+ <h4>{label}</h4><p className="settings-hint">{hint}</p>+ <ModelBinding id={`ai-profile-${key}`} value={config.profiles[key]} connections={connections} allowInherit discover disabled={busy}+ inheritLabel={key === 'standard' ? t('ai.management.panelDefault', 'Use panel default') : undefined}+ onChange={(value) => change('profiles', { ...config.profiles, [key]: value })} />+ {!config.profiles[key] && inherited && <p className="settings-hint">{t('ai.management.inheritedModel', 'Inherited model: {{connection}} · {{model}}', {+ connection: connections.find((item) => item.id === inherited.connection_id)?.name, model: inherited.model,+ })}</p>}+ </div>)}+ </section>+ <section className="settings-card">+ <h3>{t('ai.management.routing', 'Routing and fallback')}</h3>+ <p>{t('ai.management.routingHint', 'Automatic routing uses only the approved pool below. An explicit model choice takes priority. Capability tiers guide selection; speed is not a measured guarantee.')}</p>+ {toggle('routing_enabled', t('ai.management.enableRouting', 'Enable automatic routing'))}+ <FormField htmlFor="ai-routing-strategy" label={t('ai.management.strategy', 'Strategy')}>+ <select id="ai-routing-strategy" value={config.strategy} disabled={busy} onChange={(e) => change('strategy', e.target.value)}>+ <option value="cost_optimized">{t('ai.management.economical', 'Cost optimized')}</option><option value="balanced">{t('ai.management.balanced', 'Balanced')}</option>+ <option value="quality_first">{t('ai.management.quality', 'Quality first')}</option><option value="fast">{t('ai.management.fast', 'Fast')}</option>+ </select>+ </FormField>+ {candidates('pool')}+ <FormField htmlFor="ai-routing-sample" label={t('ai.management.previewTask', 'Preview a task')} hint={t('ai.management.previewHint', 'Uses the current draft. Preview does not send your task to a provider or spend tokens.')}>+ <Input id="ai-routing-sample" value={sample} onChange={(e) => setSample(e.target.value)} maxLength={16000} />+ </FormField>+ <Button type="button" variant="outline" onClick={previewRoute} disabled={busy || !sample.trim()}>{t('ai.management.preview', 'Preview routing')}</Button>+ {preview && <div className="sk-ai-routing-result" role="status"><strong>{connections.find((item) => item.id === preview.connection_id)?.name} · {preview.model}</strong><p>{preview.reason}</p></div>}+ {toggle('fallback_enabled', t('ai.management.enableFallback', 'Enable fallback before output starts'))}+ <p className="settings-hint">{t('ai.management.fallbackHint', 'Candidates are tried in order using their own saved credentials. Delivered output and tool actions are never replayed. Degradation chooses a lower-priced candidate before a turn at 80% of the conversation allowance; unknown prices cannot be compared.')}</p>+ {candidates('fallbacks')}+ </section>+ <section className="settings-card">+ <h3>{t('ai.management.behavior', 'Generation and spending')}</h3>+ <FormField htmlFor="ai-budget-policy" label={t('ai.management.budgetPolicy', 'Conversation budget behavior')}>+ <select id="ai-budget-policy" value={config.budget_policy} disabled={busy} onChange={(e) => change('budget_policy', e.target.value)}>+ <option value="hard_stop">{t('ai.management.stop', 'Stop at the limit')}</option>+ <option value="warn_and_continue">{t('ai.management.warn', 'Warn and continue')}</option>+ <option value="degrade">{t('ai.management.degrade', 'Use a cheaper model near the limit, then stop')}</option>+ </select>+ </FormField>+ <div className="ai-connections__fields">+ {numberField('max_output_tokens', t('ai.management.outputTokens', 'Maximum output tokens per response'), 64, 65536)}+ {numberField('max_tokens', t('ai.management.totalTokens', 'Conversation token allowance'), 0, 10000000, t('ai.management.zeroUnlimited', 'Set 0 for no limit.'))}+ </div>+ <details className="sk-ai-advanced"><summary>{t('ai.management.advancedControls', 'Advanced generation controls')}</summary>+ <div className="ai-connections__fields">+ {numberField('max_tool_rounds', t('ai.management.toolRounds', 'Maximum tool rounds'), 1, 20)}+ {numberField('max_tool_result_length', t('ai.management.toolLength', 'Maximum tool result characters'), 256, 32000)}+ {numberField('max_history_messages', t('ai.management.history', 'Messages kept in model context'), 4, 200)}+ <FormField htmlFor="ai-temperature" label={t('ai.management.temperature', 'Temperature')} hint={t('ai.management.supportedOnly', 'Applied only when the model catalog confirms support. Blank uses the provider default.')}>+ <Input id="ai-temperature" type="number" min="0" max="2" step="0.1" disabled={busy} value={config.temperature ?? ''} onChange={(e) => change('temperature', e.target.value === '' ? null : e.target.value)} />+ </FormField>+ <FormField htmlFor="ai-reasoning" label={t('ai.management.reasoning', 'Reasoning effort')} hint={t('ai.management.reasoningHint', 'Applied to supported OpenAI reasoning models. Other models retain provider defaults.')}>+ <select id="ai-reasoning" disabled={busy} value={config.reasoning_effort || ''} onChange={(e) => change('reasoning_effort', e.target.value || null)}>+ <option value="">{t('ai.management.providerDefault', 'Provider default')}</option><option value="low">{t('ai.management.low', 'Low')}</option><option value="medium">{t('ai.management.medium', 'Medium')}</option><option value="high">{t('ai.management.high', 'High')}</option>+ </select>+ </FormField>+ </div>+ </details>+ <details className="sk-ai-advanced"><summary>{t('ai.management.monthly', 'Monthly spending allowances')}</summary>+ <p>{t('ai.management.allowanceHint', 'Allowances include active run reservations. Unknown-cost attempts consume the reservation conservatively. Limits use reported or estimated costs; a final call can overshoot. Use provider limits for authoritative billing caps.')}</p>+ <div className="ai-connections__fields">+ {numberField('monthly_limit_usd', t('ai.management.panelLimit', 'Panel allowance (USD / month)'), 0, 1000000, null, '0.01')}+ {numberField('user_monthly_limit_usd', t('ai.management.userLimit', 'Allowance per user (USD / month)'), 0, 1000000, null, '0.01')}+ {numberField('workspace_monthly_limit_usd', t('ai.management.workspaceLimit', 'Allowance per workspace (USD / month)'), 0, 1000000, t('ai.management.workspaceHint', 'Applies to chats started in an active workspace. User and panel limits also apply.'), '0.01')}+ {numberField('reservation_usd', t('ai.management.reserve', 'Reserve per run (USD)'), 0.01, 1000, t('ai.management.reserveHint', 'When monthly limits apply, each run reserves this amount and stops further calls when it is spent.'), '0.01')}+ </div>+ </details>+ {error && <p role="alert" className="error-message">{error}</p>}+ {saved && <p role="status">{t('ai.management.saved', 'AI management settings saved.')}</p>}+ <div className="settings-actions settings-actions--footer"><Button onClick={submit} disabled={busy}>{busy ? t('common.saving', 'Saving…') : t('ai.management.save', 'Save AI management settings')}</Button></div>+ </section>+ </div>;+}diff --git a/frontend/src/components/settings/AISettingsTab.jsx b/frontend/src/components/settings/AISettingsTab.jsxindex 1568218d..faa4e7f2 100644--- a/frontend/src/components/settings/AISettingsTab.jsx+++ b/frontend/src/components/settings/AISettingsTab.jsx@@ -8,6 +8,9 @@ import { Input } from '../ui/input';import EmptyState from '../EmptyState';import { Button } from '@/components/ui/button';import AIConnectionsSettings from './AIConnectionsSettings';+import AIManagementSettings from './AIManagementSettings';+import AIUsageSettings from './AIUsageSettings';+import { SegControl } from '../ds/SegControl';import { useTranslation } from 'react-i18next';const AI_CONFIG_CHANGED_EVENT = 'serverkit:ai-config-changed';@@ -27,6 +30,7 @@ const AISettingsTab = () => {const [toggling, setToggling] = useState(false);const [loadError, setLoadError] = useState(false);const [message, setMessage] = useState(null);+ const [section, setSection] = useState('connections');useEffect(() => {if (!isAdmin) { setLoading(false); return; }@@ -109,6 +113,12 @@ const AISettingsTab = () => {<p>{t('ai.settings.intro', 'Connect a provider, choose a model, and set the assistant’s limits.')}</p></div>{message && <div className={`alert alert-${message.type === 'error' ? 'danger' : 'success'}`} role={message.type === 'error' ? 'alert' : 'status'}>{message.text}</div>}+ <SegControl className="sk-ai-settings-tabs" value={section} onChange={setSection} aria-label={t('ai.management.sections', 'AI settings sections')} options={[+ { value: 'connections', label: t('ai.management.connectionsSafety', 'Connections and protections') },+ { value: 'models', label: t('ai.management.modelsBehavior', 'Task models and behavior') },+ { value: 'usage', label: t('ai.usage.title', 'AI usage') },+ ]} />+ <div hidden={section !== 'connections'}><div {...register('ai-enable', 'settings-card')}><div className="settings-row"><div className="settings-label">@@ -141,7 +151,7 @@ const AISettingsTab = () => {value={settings.max_cost_usd}onChange={(e) => setSettings((s) => ({ ...s, max_cost_usd: e.target.value }))}/>- <p id="ai-max-cost-hint" className="settings-hint">{t('ai.settings.costHint', 'Stops further model calls when reported spending reaches this amount. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.')}</p>+ <p id="ai-max-cost-hint" className="settings-hint">{t('ai.settings.costHint', 'Used by the budget behavior in Task models and behavior. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.')}</p></div><div {...register('ai-pii-redaction', 'form-group')}>@@ -169,6 +179,9 @@ const AISettingsTab = () => {</Button></div></div>+ </div>+ <div hidden={section !== 'models'}><AIManagementSettings connections={settings.connections || []} defaultId={settings.default_connection_id} /></div>+ <div hidden={section !== 'usage'}><AIUsageSettings connections={settings.connections || []} /></div></div>);};diff --git a/frontend/src/components/settings/AIUsageSettings.jsx b/frontend/src/components/settings/AIUsageSettings.jsxnew file mode 100644index 00000000..e5f87fb8--- /dev/null+++ b/frontend/src/components/settings/AIUsageSettings.jsx@@ -0,0 +1,98 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import api from '../../services/api';+import useFormat from '../../hooks/useFormat';+import { FormField } from '../FormField';+import { Input } from '../ui/input';+import { Button } from '../ui/button';+import { DataTable } from '../ds/DataTable';+import { DataTableFooter } from '../ds/DataTableFooter';+import EmptyState from '../EmptyState';+import { CardHeader } from '../ui/card';+import { Drawer } from '../ds/Drawer';++export default function AIUsageSettings({ connections }) {+ const { t } = useTranslation();+ const { formatNumber, formatDateTime } = useFormat();+ const [filters, setFilters] = useState({ days: '30', profile: '', connection_id: '', user_id: '', workspace_id: '' });+ const [applied, setApplied] = useState(filters);+ const [data, setData] = useState(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [group, setGroup] = useState('model');+ const [offset, setOffset] = useState(0);+ const [revision, setRevision] = useState(0);+ const [selected, setSelected] = useState(null);+ useEffect(() => {+ let active = true; setBusy(true); setError('');+ api.aiGetUsage({ ...applied, offset }).then((result) => { if (active) setData(result); }).catch((e) => { if (active) setError(e.message); }).finally(() => { if (active) setBusy(false); });+ return () => { active = false; };+ }, [applied, offset, revision]);+ const money = (amount) => t('ai.usage.usd', '{{amount}} USD', { amount: formatNumber(amount, { maximumFractionDigits: 4 }) });+ const connectionName = (id) => connections.find((item) => item.id === id)?.name || id;+ const groups = {+ model: t('ai.usage.byModel', 'Model'), profile: t('ai.usage.byRole', 'Task role'),+ daily: t('ai.usage.byDay', 'Day'), connection_id: t('ai.usage.byConnection', 'Connection'),+ user_id: t('ai.usage.byUser', 'User'), workspace_id: t('ai.usage.byWorkspace', 'Workspace'),+ };+ return <section className="settings-card sk-ai-usage">+ <CardHeader variant="legacy"><div><h3>{t('ai.usage.title', 'AI usage')}</h3><p>{t('ai.usage.hint', 'Per-run accounting across chats, task roles, and provider attempts. Totals include the entire filtered period.')}</p></div>+ <Button variant="outline" disabled={busy} onClick={() => setRevision((value) => value + 1)}>{t('common.actions.refresh', 'Refresh')}</Button>+ </CardHeader>+ <div className="ai-connections__fields">+ <FormField htmlFor="ai-usage-days" label={t('ai.usage.period', 'Period')}><select id="ai-usage-days" value={filters.days} onChange={(e) => setFilters({ ...filters, days: e.target.value })}>+ <option value="1">{t('ai.usage.day', 'Last 24 hours')}</option><option value="7">{t('ai.usage.week', 'Last 7 days')}</option><option value="30">{t('ai.usage.month', 'Last 30 days')}</option><option value="90">{t('ai.usage.quarter', 'Last 90 days')}</option>+ </select></FormField>+ <FormField htmlFor="ai-usage-role" label={groups.profile}><select id="ai-usage-role" value={filters.profile} onChange={(e) => setFilters({ ...filters, profile: e.target.value })}>+ <option value="">{t('ai.usage.allRoles', 'All task roles')}</option><option value="utility">{t('ai.management.utility', 'Utility')}</option><option value="standard">{t('ai.management.standard', 'Standard')}</option><option value="advanced">{t('ai.management.advanced', 'Advanced')}</option>+ </select></FormField>+ <FormField htmlFor="ai-usage-connection" label={groups.connection_id}><select id="ai-usage-connection" value={filters.connection_id} onChange={(e) => setFilters({ ...filters, connection_id: e.target.value })}>+ <option value="">{t('ai.usage.allConnections', 'All connections')}</option>{connections.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}+ </select></FormField>+ {['user_id', 'workspace_id'].map((key) => <FormField key={key} htmlFor={`ai-usage-${key}`} label={groups[key]} hint={t('ai.usage.idFilter', 'Optional numeric ID')}><Input id={`ai-usage-${key}`} type="number" min="1" value={filters[key]} onChange={(e) => setFilters({ ...filters, [key]: e.target.value })} /></FormField>)}+ </div>+ <div className="settings-actions settings-actions--footer"><Button variant="outline" disabled={busy} onClick={() => { setOffset(0); setApplied({ ...filters }); }}>{t('ai.usage.apply', 'Apply filters')}</Button></div>+ {error && <p className="error-message" role="alert">{error}</p>}+ {busy && <EmptyState loading title={t('common.loading', 'Loading…')} />}+ {!busy && data?.totals && <>+ <div className="stat-strip">+ <div className="stat-strip__item"><span>{t('ai.usage.cost', 'Known cost')}</span><strong>{money(data.totals.cost)}</strong></div>+ <div className="stat-strip__item"><span>{t('ai.usage.tokens', 'Tokens')}</span><strong>{formatNumber(data.totals.tokens)}</strong></div>+ <div className="stat-strip__item"><span>{t('ai.usage.runs', 'Runs')}</span><strong>{formatNumber(data.totals.runs)}</strong></div>+ <div className="stat-strip__item"><span>{t('ai.usage.errors', 'Stopped / failed')}</span><strong>{formatNumber(data.totals.errors)}</strong></div>+ </div>+ <p className="settings-hint">{t('ai.usage.unknowns', '{{count}} runs have unknown or partial pricing. Known cost is not a complete billing total.', { count: data.totals.unknown_cost_runs })}</p>+ <p className="settings-hint">{t('ai.usage.latency', 'Average run duration: {{seconds}} seconds', { seconds: formatNumber(data.totals.average_duration_ms / 1000, { maximumFractionDigits: 1 }) })}</p>+ {(data.allowances || []).map((item) => <p key={item.scope}>{t('ai.usage.allowance', '{{scope}} monthly allowance: {{remaining}} remaining of {{limit}}', { scope: item.scope, remaining: money(item.remaining), limit: money(item.limit) })}</p>)}+ <FormField htmlFor="ai-usage-group" label={t('ai.usage.breakdown', 'Cost breakdown')}><select id="ai-usage-group" value={group} onChange={(e) => setGroup(e.target.value)}>{Object.entries(groups).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></FormField>+ <DataTable data={data.groups[group] || []} keyField="label" columns={[+ { key: 'label', header: groups[group], render: (item) => group === 'connection_id' ? connectionName(item.label) : item.label },+ { key: 'runs', header: t('ai.usage.runs', 'Runs') },+ { key: 'tokens', header: t('ai.usage.tokens', 'Tokens'), render: (item) => formatNumber(item.tokens) },+ { key: 'cost', header: t('ai.usage.cost', 'Known cost'), render: (item) => money(item.cost) },+ ]} emptyTitle={t('ai.usage.empty', 'No AI runs in this period')} />+ <h4>{t('ai.usage.recent', 'Run details')}</h4>+ <DataTable data={data.runs} columns={[+ { key: 'created_at', header: t('ai.usage.when', 'Started'), render: (run) => formatDateTime(run.created_at) },+ { key: 'model', header: groups.model }, { key: 'profile', header: groups.profile },+ { key: 'status', header: t('ai.usage.outcome', 'Outcome') },+ { key: 'cost', header: t('ai.usage.cost', 'Known cost'), render: (run) => run.usage.cost_source === 'unknown' ? t('ai.usage.unknown', 'Unknown') : money(run.cost) },+ { key: 'details', header: '', sortable: false, render: (run) => <Button variant="ghost" onClick={() => setSelected(run)}>{t('ai.usage.details', 'Details')}</Button> },+ ]} emptyTitle={t('ai.usage.empty', 'No AI runs in this period')} />+ <DataTableFooter shown={data.runs.length} total={data.totals.runs} page={Math.floor(offset / 50) + 1}+ totalPages={Math.max(1, Math.ceil(data.totals.runs / 50))} onPageChange={(page) => setOffset((page - 1) * 50)} />+ <Drawer open={!!selected} onOpenChange={(open) => { if (!open) setSelected(null); }} width={640} title={t('ai.usage.details', 'Details')}>+ {selected && <>+ <strong>{selected.model}</strong><p>{selected.reason}</p>+ <p>{t('ai.usage.source', 'Cost source: {{source}}', { source: selected.usage.cost_source })}</p>+ <DataTable data={(selected.usage.attempts || []).map((item, index) => ({ ...item, id: index }))} columns={[+ { key: 'connection_id', header: groups.connection_id, render: (item) => connectionName(item.connection_id) },+ { key: 'model', header: groups.model }, { key: 'status', header: t('ai.usage.outcome', 'Outcome') },+ { key: 'total_tokens', header: t('ai.usage.tokens', 'Tokens') },+ ]} emptyTitle={t('ai.usage.noAttempts', 'No provider attempts were recorded')} />+ <Button variant="ghost" onClick={() => setSelected(null)}>{t('common.actions.close', 'Close')}</Button>+ </>}+ </Drawer>+ </>}+ </section>;+}diff --git a/frontend/src/contexts/AIContext.jsx b/frontend/src/contexts/AIContext.jsxindex 566a5a06..90d7d591 100644--- a/frontend/src/contexts/AIContext.jsx+++ b/frontend/src/contexts/AIContext.jsx@@ -23,6 +23,8 @@ const initialState = {includeContext: true,providerConfigured: false,enabled: false,+ profile: '',+ workflow: 'chat',statusLoaded: false,conversations: [],connections: [],@@ -73,11 +75,16 @@ function reducer(state, action) {case 'SET_STATUS':return { ...state, enabled: action.enabled, providerConfigured: action.configured, statusLoaded: true };case 'SET_CONNECTIONS': {- const selected = action.connections.find((connection) => connection.id === state.selectedConnection)- || action.connections.find((connection) => connection.id === action.defaultId);+ const selected = action.connections.find((connection) => connection.id === state.selectedConnection);return { ...state, connections: action.connections, selectedConnection: selected?.id || '',- selectedModel: state.selectedConnection === selected?.id ? state.selectedModel : selected?.model || '' };+ selectedModel: selected ? state.selectedModel : '' };}+ case 'SELECT_PROFILE':+ return { ...state, profile: action.profile, selectedConnection: '', selectedModel: '' };+ case 'SELECT_WORKFLOW':+ return { ...state, workflow: action.workflow, profile: '', selectedConnection: '', selectedModel: '' };+ case 'RUN_START':+ return { ...state, messages: patchLastAssistant(state.messages, (message) => ({ ...message, selection: action.selection })) };case 'SELECT_CONNECTION': {const connection = state.connections.find((item) => item.id === action.id);return { ...state, selectedConnection: action.id, selectedModel: connection?.model || '' };@@ -190,6 +197,7 @@ function reducer(state, action) {(message) => ({...message,status: message.status === 'streaming' ? 'done' : message.status,+ usage: action.usage || message.usage,}),),};@@ -251,6 +259,7 @@ export function AIProvider({ children }) {id: `srv_${m.id}`,role: m.role === 'assistant' ? 'assistant' : 'user',content: m.content || '',+ usage: m.usage,attachments: (m.attachments || []).map(normalizeAttachment).filter(Boolean),toolCalls: (m.tool_calls || []).map((tc) => ({id: tc.id, name: tc.name, input: tc.input, output: tc.output,@@ -300,7 +309,8 @@ export function AIProvider({ children }) {case 'pending_action': dispatch({ type: 'SET_PENDING_CONFIRM', payload: data }); break;case 'attachment_warning': dispatch({ type: 'ATTACHMENT_WARNING', warning: data }); break;case 'error': dispatch({ type: 'SET_ERROR', message: data.message || 'The assistant hit an error.' }); break;- case 'done': dispatch({ type: 'TURN_DONE', conversationId: data.conversation_id }); break;+ case 'run_start': dispatch({ type: 'RUN_START', selection: data }); break;+ case 'done': dispatch({ type: 'TURN_DONE', conversationId: data.conversation_id, usage: data.usage }); break;default: break;}}, []);@@ -320,6 +330,8 @@ export function AIProvider({ children }) {mode,connection_id: activeIdRef.current ? undefined : state.selectedConnection || undefined,model: activeIdRef.current ? undefined : state.selectedModel || undefined,+ profile: activeIdRef.current ? undefined : opts.profile || state.profile || undefined,+ workflow: activeIdRef.current ? undefined : opts.workflow || state.workflow,};if (requestedAttachments.length) {payload.attachments = requestedAttachments.map(toAttachmentPayload).filter(Boolean);@@ -356,6 +368,7 @@ export function AIProvider({ children }) {}, [state.isStreaming, state.providerConfigured, state.mode, state.includeContext, state.attachments,state.selectedConnection, state.selectedModel,+ state.profile, state.workflow,buildPageContext, handleEvent, loadConversations,]);@@ -429,6 +442,8 @@ export function AIProvider({ children }) {isOpen: state.open,selectConnection: (id) => dispatch({ type: 'SELECT_CONNECTION', id }),selectModel: (model) => dispatch({ type: 'SELECT_MODEL', model }),+ selectProfile: (profile) => dispatch({ type: 'SELECT_PROFILE', profile }),+ selectWorkflow: (workflow) => dispatch({ type: 'SELECT_WORKFLOW', workflow }),pageContext,// controlsopen, close, toggle, ask, send, stop, confirmAction, setMode, setIncludeContext,diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 98d57e99..a0ba90ee 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -7,7 +7,6 @@"choosePreset": "Custom URL, or choose a preset…","clearSecret": "Clear saved credential","connection": "Connection",- "connectionDefault": "Connection default","defaultModel": "Default model ID","defaultSuffix": " (default)","delete": "Delete",@@ -27,7 +26,6 @@"namePlaceholder": "e.g. Team Anthropic or Local OmniRoute","noModels": "No matching models. Enter a model ID manually.","optional": " (optional)",- "panelDefault": "Panel default","preset": "Endpoint preset","provider": "Provider","required": " (required)",@@ -43,8 +41,84 @@"verified": "Connection verified.","working": "Working…"},+ "management": {+ "addCandidate": "Add model candidate",+ "advanced": "Advanced",+ "advancedControls": "Advanced generation controls",+ "advancedHint": "Complex analysis and read-only diagnostic tasks.",+ "allowanceHint": "Allowances include active run reservations. Unknown-cost attempts consume the reservation conservatively. Limits use reported or estimated costs; a final call can overshoot. Use provider limits for authoritative billing caps.",+ "balanced": "Balanced",+ "behavior": "Generation and spending",+ "budgetPolicy": "Conversation budget behavior",+ "chooseConnection": "Choose a connection",+ "connectionsSafety": "Connections and protections",+ "degrade": "Use a cheaper model near the limit, then stop",+ "economical": "Cost optimized",+ "enableFallback": "Enable fallback before output starts",+ "enableRouting": "Enable automatic routing",+ "fallbackHint": "Candidates are tried in order using their own saved credentials. Delivered output and tool actions are never replayed. Degradation chooses a lower-priced candidate before a turn at 80% of the conversation allowance; unknown prices cannot be compared.",+ "fast": "Fast",+ "high": "High",+ "history": "Messages kept in model context",+ "inherit": "Use Standard / panel default",+ "inheritedModel": "Inherited model: {{connection}} · {{model}}",+ "low": "Low",+ "medium": "Medium",+ "modelsBehavior": "Task models and behavior",+ "monthly": "Monthly spending allowances",+ "moveUp": "Move up",+ "outputTokens": "Maximum output tokens per response",+ "panelDefault": "Use panel default",+ "panelLimit": "Panel allowance (USD / month)",+ "preview": "Preview routing",+ "previewHint": "Uses the current draft. Preview does not send your task to a provider or spend tokens.",+ "previewTask": "Preview a task",+ "providerDefault": "Provider default",+ "quality": "Quality first",+ "reasoning": "Reasoning effort",+ "reasoningHint": "Applied to supported OpenAI reasoning models. Other models retain provider defaults.",+ "reserve": "Reserve per run (USD)",+ "reserveHint": "When monthly limits apply, each run reserves this amount and stops further calls when it is spent.",+ "routing": "Routing and fallback",+ "routingHint": "Automatic routing uses only the approved pool below. An explicit model choice takes priority. Capability tiers guide selection; speed is not a measured guarantee.",+ "save": "Save AI management settings",+ "saved": "AI management settings saved.",+ "sections": "AI settings sections",+ "standard": "Standard",+ "standardHint": "Everyday questions and tool-assisted troubleshooting.",+ "stop": "Stop at the limit",+ "strategy": "Strategy",+ "supportedOnly": "Applied only when the model catalog confirms support. Blank uses the provider default.",+ "taskModels": "Task models",+ "taskModelsHint": "Choose models by task. New chats resolve these roles; existing chats keep their selected connection.",+ "temperature": "Temperature",+ "tier": "Capability tier",+ "toolLength": "Maximum tool result characters",+ "toolRounds": "Maximum tool rounds",+ "totalTokens": "Conversation token allowance",+ "userLimit": "Allowance per user (USD / month)",+ "utility": "Utility",+ "utilityHint": "Economical model for summaries and structured extraction.",+ "warn": "Warn and continue",+ "workspaceHint": "Applies to chats started in an active workspace. User and panel limits also apply.",+ "workspaceLimit": "Allowance per workspace (USD / month)",+ "zeroUnlimited": "Set 0 for no limit."+ },+ "models": {+ "all": "All models",+ "capability": "Capability",+ "context": "{{count}} token context",+ "outputLimit": "{{count}} maximum output tokens",+ "prices": "{{input}} USD input / {{output}} USD output per 1M tokens",+ "reasoning": "Reasoning",+ "structured": "Structured output",+ "tools": "Tool calling",+ "unknownContext": "Context unknown",+ "unknownPrice": "Pricing unknown",+ "vision": "Vision"+ },"settings": {- "costHint": "Stops further model calls when reported spending reaches this amount. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.",+ "costHint": "Used by the budget behavior in Task models and behavior. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.","disabled": "Assistant disabled","disabledHelp": "The assistant is disabled. An admin can enable it in","disabledMessage": "Assistant disabled. New messages are blocked; chat history is kept.",@@ -55,6 +129,57 @@"limits": "Limits and protections","limitsHint": "These settings apply to assistant conversations. Save changes to apply them.","setupHint": "Save a provider connection below before enabling the assistant."+ },+ "tasks": {+ "automatic": "Task default / automatic routing",+ "chat": "Chat",+ "diagnose": "Read-only diagnosis",+ "extract": "Extract structured facts",+ "override": "Override connection and model",+ "role": "Model role",+ "summarize": "Summarize",+ "task": "Task",+ "useTaskModel": "Use selected task model"+ },+ "usage": {+ "allConnections": "All connections",+ "allRoles": "All task roles",+ "allowance": "{{scope}} monthly allowance: {{remaining}} remaining of {{limit}}",+ "apply": "Apply filters",+ "breakdown": "Cost breakdown",+ "budgetWarning": "The conversation allowance has been reached. Further calls follow the configured budget policy.",+ "byConnection": "Connection",+ "byDay": "Day",+ "byModel": "Model",+ "byRole": "Task role",+ "byUser": "User",+ "byWorkspace": "Workspace",+ "cost": "Known cost",+ "costRemaining": "Conversation cost allowance remaining: {{amount}}",+ "day": "Last 24 hours",+ "details": "Details",+ "empty": "No AI runs in this period",+ "errors": "Stopped / failed",+ "hint": "Per-run accounting across chats, task roles, and provider attempts. Totals include the entire filtered period.",+ "idFilter": "Optional numeric ID",+ "latency": "Average run duration: {{seconds}} seconds",+ "month": "Last 30 days",+ "noAttempts": "No provider attempts were recorded",+ "outcome": "Outcome",+ "period": "Period",+ "quarter": "Last 90 days",+ "recent": "Run details",+ "runSummary": "{{profile}} · {{calls}} provider calls · {{errors}} errors · {{seconds}} seconds",+ "runs": "Runs",+ "source": "Cost source: {{source}}",+ "title": "AI usage",+ "tokens": "Tokens",+ "tokensRemaining": "Conversation tokens remaining: {{count}}",+ "unknown": "Unknown",+ "unknowns": "{{count}} runs have unknown or partial pricing. Known cost is not a complete billing total.",+ "usd": "{{amount}} USD",+ "week": "Last 7 days",+ "when": "Started"}},"app": {diff --git a/frontend/src/services/api/ai.js b/frontend/src/services/api/ai.jsindex 87885061..6021570a 100644--- a/frontend/src/services/api/ai.js+++ b/frontend/src/services/api/ai.js@@ -17,6 +17,13 @@ export async function aiGetSettings() {return this.request('/ai/settings');}+export async function aiGetManagement() { return this.request('/ai/management'); }+export async function aiSaveManagement(body) { return this.request('/ai/management', { method: 'PUT', body }); }+export async function aiPreviewRouting(body) { return this.request('/ai/management/preview', { method: 'POST', body }); }+export async function aiGetUsage(filters = {}) {+ return this.request(`/ai/usage?${new URLSearchParams(Object.entries(filters).filter(([, value]) => value !== ''))}`);+}+export async function aiUpdateSettings(body) {return this.request('/ai/settings', { method: 'PUT', body });}@@ -82,6 +89,7 @@ export async function aiCancel(conversationId) {// Resolves when the stream ends; throws on a non-OK pre-flight response.export async function aiStreamChat(payload, { signal, onEvent } = {}) {const token = this.getToken();+ const { activeWorkspaceId } = this.workspace.getSnapshot();const res = await fetch(`${this.baseUrl}/ai/chat/stream`, {method: 'POST',signal,@@ -89,6 +97,7 @@ export async function aiStreamChat(payload, { signal, onEvent } = {}) {'Content-Type': 'application/json',Accept: 'text/event-stream',...(token && { Authorization: `Bearer ${token}` }),+ ...(activeWorkspaceId !== 'all' && { 'X-Workspace-Id': activeWorkspaceId }),},body: JSON.stringify(payload),});diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scssindex 7bc55481..7257f81f 100644--- a/frontend/src/styles/pages/_settings.scss+++ b/frontend/src/styles/pages/_settings.scss@@ -2591,9 +2591,49 @@padding: 0;}&__name { flex: 1; overflow-wrap: anywhere; font-family: $font-mono; }+ &__name small { display: block; margin-top: $space-1; color: $text-secondary; font-size: $font-size-xs; }+ &__filters { padding: $space-3; display: flex; align-items: center; gap: $space-3;+ select { @include input-base; min-width: 0; }+ }@media (max-width: $breakpoint-sm) {flex-direction: column;align-items: stretch;> .ui-input { flex: auto; }}}++.sk-ai-management, .sk-ai-binding { display: grid; gap: $space-4; min-width: 0; }+.sk-ai-settings-tabs { margin-bottom: $space-5; flex-wrap: wrap; }+.sk-ai-profile { margin-top: $space-4; padding-top: $space-4; border-top: 1px solid $border-subtle; }+.sk-ai-binding {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ align-items: start;+ > .form-field { margin-bottom: 0; }+ > button, > .error-message { grid-column: 1 / -1; justify-self: start; }+ @media (max-width: $breakpoint-md) { grid-template-columns: 1fr; }+}+.sk-ai-candidates { display: grid; gap: $space-3; margin-block: $space-4;+ > button { justify-self: start; }+ &__row { padding: $space-4; background: $bg-elevated; border: 1px solid $border-default; border-radius: $radius-md; min-width: 0;+ > .form-field { margin-block: $space-4; }+ .settings-actions { justify-content: flex-end; }+ }+}+.sk-ai-advanced { border-top: 1px solid $border-subtle; padding-block: $space-4;+ summary { cursor: pointer; font-weight: $font-weight-medium; margin-bottom: $space-3; }+}+.sk-ai-routing-result { background: $bg-body; border: 1px solid $border-default; border-radius: $radius-md; padding: $space-4; margin-block: $space-4; overflow-wrap: anywhere; }+.sk-ai-usage { min-width: 0;+ .stat-strip { margin-block: $space-4; }+ .stat-strip__item { background: $bg-body; }+ .stat-strip__item > strong { font-family: $font-mono; font-size: $font-size-lg; }+ .card-header { flex-wrap: wrap; gap: $space-3; }+ h4 { margin-top: $space-5; }+}+.sk-ai-task-selector { padding: $space-3; min-width: 0;+ summary { cursor: pointer; color: $text-secondary; font-size: $font-size-xs; }+ .sk-ai-binding { margin-top: $space-3; }+}+.sk-ai-message__usage { font-size: $font-size-xs; color: $text-secondary; border-top: 1px solid $border-subtle; margin-top: $space-3; padding-top: $space-2; overflow-wrap: anywhere;+ summary { cursor: pointer; }+}