Changeset 0.4.3 (#32)

This commit is contained in:
2026-02-18 17:47:21 +00:00
parent 2fc4f6980c
commit c98eb80950
14 changed files with 1134 additions and 17 deletions

View File

@@ -40,6 +40,21 @@ function initAdminListeners() {
document.getElementById('adminResetCancelBtn').addEventListener('click', closeResetDialog);
document.getElementById('adminResetConfirmBtn').addEventListener('click', handleResetPassword);
// Admin providers
document.getElementById('adminProviderShowAddBtn').addEventListener('click', () => {
document.getElementById('adminProviderAddForm').style.display = '';
document.getElementById('adminProviderShowAddBtn').style.display = 'none';
});
document.getElementById('adminProviderCancelBtn').addEventListener('click', () => {
document.getElementById('adminProviderAddForm').style.display = 'none';
document.getElementById('adminProviderShowAddBtn').style.display = '';
clearAdminProviderForm();
});
document.getElementById('adminProviderCreateBtn').addEventListener('click', handleCreateAdminProvider);
// Admin models
document.getElementById('adminFetchModelsBtn').addEventListener('click', handleAdminFetchModels);
document.getElementById('adminResetNewPw').addEventListener('keydown', function(e) {
if (e.key === 'Enter') handleResetPassword();
});
@@ -50,10 +65,14 @@ function switchAdminTab(tab) {
t.classList.toggle('active', t.dataset.tab === tab);
});
document.getElementById('adminUsersTab').style.display = tab === 'users' ? '' : 'none';
document.getElementById('adminModelsTab').style.display = tab === 'models' ? '' : 'none';
document.getElementById('adminProvidersTab').style.display = tab === 'providers' ? '' : 'none';
document.getElementById('adminSettingsTab').style.display = tab === 'settings' ? '' : 'none';
document.getElementById('adminStatsTab').style.display = tab === 'stats' ? '' : 'none';
document.getElementById('adminResetDialog').style.display = 'none';
if (tab === 'models') loadAdminModels();
if (tab === 'providers') loadAdminProviders();
if (tab === 'settings') loadAdminSettings();
if (tab === 'stats') loadAdminStats();
}
@@ -271,3 +290,198 @@ function escapeHtml(str) {
div.textContent = str;
return div.innerHTML;
}
// ── Admin Models ────────────────────────────
const CAPS = ['tool', 'thinking', 'vision', 'code'];
async function loadAdminModels() {
const container = document.getElementById('adminModelList');
container.innerHTML = '<div class="admin-loading">Loading models...</div>';
try {
const data = await Backend.adminListModels();
const models = data.models || [];
if (models.length === 0) {
container.innerHTML = '<div class="admin-empty">No models configured. Add a provider first, then click "Fetch Models".</div>';
return;
}
// Group by provider
const grouped = {};
for (const m of models) {
const key = m.provider_name || 'Unknown';
if (!grouped[key]) grouped[key] = [];
grouped[key].push(m);
}
let html = '';
for (const [provider, provModels] of Object.entries(grouped)) {
html += '<div class="admin-model-group">';
html += '<div class="admin-model-group-header">' + escapeHtml(provider) + '</div>';
for (const m of provModels) {
const caps = m.capabilities || {};
const name = m.display_name || m.model_id;
html += '<div class="admin-model-row">';
html += ' <div class="admin-model-toggle">';
html += ' <label class="toggle-label-compact">';
html += ' <input type="checkbox" ' + (m.is_enabled ? 'checked' : '') +
' onchange="toggleModelEnabled(\'' + m.id + '\', this.checked)">';
html += ' </label>';
html += ' </div>';
html += ' <div class="admin-model-info">';
html += ' <span class="admin-model-name">' + escapeHtml(name) + '</span>';
html += ' <span class="admin-model-id">' + escapeHtml(m.model_id) + '</span>';
html += ' </div>';
html += ' <div class="admin-model-caps">';
for (const cap of CAPS) {
const active = caps[cap] === true;
html += ' <button class="cap-badge ' + (active ? 'cap-active' : 'cap-inactive') + '"' +
' onclick="toggleModelCap(\'' + m.id + '\', \'' + cap + '\', ' + !active + ', \'' + escapeHtml(JSON.stringify(caps)) + '\')"' +
' title="' + cap + '">' + cap + '</button>';
}
html += ' </div>';
html += ' <div class="admin-model-actions">';
html += ' <button class="btn btn-small btn-danger" onclick="deleteAdminModel(\'' + m.id + '\', \'' + escapeHtml(m.model_id) + '\')">✕</button>';
html += ' </div>';
html += '</div>';
}
html += '</div>';
}
container.innerHTML = html;
} catch (e) {
container.innerHTML = '<div class="admin-error">Failed to load models: ' + e.message + '</div>';
}
}
async function handleAdminFetchModels() {
const btn = document.getElementById('adminFetchModelsBtn');
btn.disabled = true;
btn.textContent = '⏳ Fetching...';
try {
const data = await Backend.adminFetchModels();
const added = data.total_added || 0;
const results = data.results || [];
const errors = results.filter(r => r.error);
if (errors.length > 0) {
showToast('⚠️ Fetched with ' + errors.length + ' error(s). ' + added + ' new models.', 'warning');
} else {
showToast('✅ Fetched ' + added + ' new models', 'success');
}
loadAdminModels();
} catch (e) {
showToast('❌ ' + e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = '🔄 Fetch Models';
}
}
async function toggleModelEnabled(modelId, enabled) {
try {
await Backend.adminUpdateModel(modelId, { is_enabled: enabled });
} catch (e) {
showToast('❌ ' + e.message, 'error');
loadAdminModels();
}
}
async function toggleModelCap(modelId, cap, value, capsJson) {
try {
const caps = JSON.parse(capsJson);
caps[cap] = value;
await Backend.adminUpdateModel(modelId, { capabilities: caps });
loadAdminModels();
} catch (e) {
showToast('❌ ' + e.message, 'error');
loadAdminModels();
}
}
async function deleteAdminModel(modelId, modelName) {
if (!confirm('Remove model "' + modelName + '"? It can be re-fetched later.')) return;
try {
await Backend.adminDeleteModel(modelId);
showToast('✅ Model removed', 'success');
loadAdminModels();
} catch (e) {
showToast('❌ ' + e.message, 'error');
}
}
async function loadAdminProviders() {
const container = document.getElementById('adminProviderList');
container.innerHTML = '<div class="admin-loading">Loading...</div>';
try {
const data = await Backend.adminListGlobalConfigs();
const configs = data.configs || [];
if (configs.length === 0) {
container.innerHTML = '<div class="provider-empty">No global providers. Users must add their own.</div>';
return;
}
container.innerHTML = configs.map(c => `
<div class="provider-row">
<div class="provider-info">
<span class="provider-name">${escapeHtml(c.name)}</span>
<span class="provider-meta">${c.provider} · ${c.model_default || 'no default'}</span>
</div>
<div class="provider-actions">
<span class="admin-badge admin-badge-active">${c.has_key ? '🔑' : '⚠️'}</span>
<button class="btn btn-small btn-danger" onclick="deleteAdminProvider('${c.id}', '${escapeHtml(c.name)}')">Remove</button>
</div>
</div>
`).join('');
} catch (e) {
container.innerHTML = '<div class="admin-error">Failed to load providers: ' + e.message + '</div>';
}
}
function clearAdminProviderForm() {
document.getElementById('adminProviderName').value = '';
document.getElementById('adminProviderType').value = 'openai';
document.getElementById('adminProviderEndpoint').value = '';
document.getElementById('adminProviderApiKey').value = '';
document.getElementById('adminProviderDefaultModel').value = '';
}
async function handleCreateAdminProvider() {
const name = document.getElementById('adminProviderName').value.trim();
const provider = document.getElementById('adminProviderType').value;
const endpoint = document.getElementById('adminProviderEndpoint').value.trim();
const apiKey = document.getElementById('adminProviderApiKey').value.trim();
const modelDefault = document.getElementById('adminProviderDefaultModel').value.trim();
if (!name || !endpoint || !apiKey) {
showToast('⚠️ Name, endpoint, and API key are required', 'warning');
return;
}
try {
await Backend.adminCreateGlobalConfig(name, provider, endpoint, apiKey, modelDefault || null);
showToast('✅ Global provider added', 'success');
clearAdminProviderForm();
document.getElementById('adminProviderAddForm').style.display = 'none';
document.getElementById('adminProviderShowAddBtn').style.display = '';
loadAdminProviders();
} catch (e) {
showToast('❌ ' + e.message, 'error');
}
}
async function deleteAdminProvider(configId, name) {
if (!confirm('Remove global provider "' + name + '"?')) return;
try {
await Backend.adminDeleteGlobalConfig(configId);
showToast('✅ Global provider removed', 'success');
loadAdminProviders();
} catch (e) {
showToast('❌ ' + e.message, 'error');
}
}

View File

@@ -16,13 +16,22 @@ async function fetchModels(showInModal = true) {
let models = [];
if (Backend.isManaged) {
// Managed mode: fetch from backend aggregated models endpoint
const data = await Backend.listAllModels();
// Managed mode: fetch admin-curated enabled models
const data = await Backend.listEnabledModels();
models = (data.models || []).map(m => ({
id: m.id || m.name,
owned_by: m.owned_by || m.provider || null,
id: m.model_id || m.id,
owned_by: m.provider_name || m.provider || null,
config_id: m.config_id || null
}));
// Fallback: if no curated models, try raw aggregation
if (models.length === 0) {
const raw = await Backend.listAllModels();
models = (raw.models || []).map(m => ({
id: m.id || m.name,
owned_by: m.owned_by || m.provider || null,
config_id: m.config_id || null
}));
}
} else {
// Unmanaged mode: direct provider call
const endpoint = showInModal

View File

@@ -39,12 +39,19 @@ async function init() {
// Already authed or no backend → go straight to app
hideSplashGate();
await loadSettingsFromBackend();
await initApp();
}
async function initApp() {
await loadChats();
initializeEventListeners();
// In managed mode, fetch models from backend (ignore localStorage cache)
if (Backend.isManaged) {
fetchModels(false); // async, non-blocking
}
updateQuickModelSelector();
renderChatHistory();
updateConnectionStatus();
@@ -80,8 +87,9 @@ function hideSplashGate() {
async function authSuccess() {
hideSplashGate();
await loadSettingsFromBackend();
await initApp();
showToast(`✅ Welcome, ${Backend.user?.username || 'user'}!`, 'success');
showToast(`✅ Welcome, ${Backend.user?.display_name || Backend.user?.username || 'user'}!`, 'success');
}
function initializeEventListeners() {
@@ -99,6 +107,12 @@ function initializeEventListeners() {
});
document.getElementById('profileSavePwBtn').addEventListener('click', handleChangePassword);
// Providers (managed mode)
document.getElementById('providerShowAddBtn').addEventListener('click', showProviderForm);
document.getElementById('providerCancelBtn').addEventListener('click', hideProviderForm);
document.getElementById('providerCreateBtn').addEventListener('click', handleCreateProvider);
document.getElementById('providerType').addEventListener('change', updateProviderEndpointHint);
// Chat controls
document.getElementById('newChatBtn').addEventListener('click', newChat);
document.getElementById('sendBtn').addEventListener('click', sendMessage);

View File

@@ -294,6 +294,57 @@ const Backend = {
return this._authedFetch('/api/v1/admin/stats');
},
// Admin Global Configs
async adminListGlobalConfigs() {
return this._authedFetch('/api/v1/admin/configs');
},
async adminCreateGlobalConfig(name, provider, endpoint, apiKey, modelDefault) {
return this._authedFetch('/api/v1/admin/configs', {
method: 'POST',
body: JSON.stringify({
name, provider, endpoint,
api_key: apiKey,
model_default: modelDefault
})
});
},
async adminDeleteGlobalConfig(configId) {
return this._authedFetch(`/api/v1/admin/configs/${configId}`, {
method: 'DELETE'
});
},
// Admin Model Configs
async adminListModels() {
return this._authedFetch('/api/v1/admin/models');
},
async adminFetchModels() {
return this._authedFetch('/api/v1/admin/models/fetch', {
method: 'POST'
});
},
async adminUpdateModel(modelId, updates) {
return this._authedFetch(`/api/v1/admin/models/${modelId}`, {
method: 'PUT',
body: JSON.stringify(updates)
});
},
async adminDeleteModel(modelId) {
return this._authedFetch(`/api/v1/admin/models/${modelId}`, {
method: 'DELETE'
});
},
// Enabled models (for quick selector in managed mode)
async listEnabledModels() {
return this._authedFetch('/api/v1/models/enabled');
},
// ── Models ──────────────────────────────
async listAllModels() {

View File

@@ -26,7 +26,7 @@ const State = {
abortController: null
};
// ── Settings (always localStorage) ──────────
// ── Settings (localStorage + backend sync) ──
function loadSettings() {
const saved = Storage.get('chatSwitchboard_settings');
@@ -37,6 +37,47 @@ function loadSettings() {
function saveSettings() {
Storage.set('chatSwitchboard_settings', State.settings);
// Fire-and-forget sync to backend
syncSettingsToBackend();
}
async function syncSettingsToBackend() {
if (!Backend.isManaged) return;
try {
// Only sync preferences, not apiEndpoint/apiKey (those live in api_configs)
const prefs = {
model: State.settings.model,
stream: State.settings.stream,
saveHistory: State.settings.saveHistory,
showThinking: State.settings.showThinking,
systemPrompt: State.settings.systemPrompt,
maxTokens: State.settings.maxTokens,
temperature: State.settings.temperature,
topP: State.settings.topP,
presencePenalty: State.settings.presencePenalty
};
await Backend.updateSettings(prefs);
} catch (e) {
console.warn('Failed to sync settings to backend:', e);
}
}
async function loadSettingsFromBackend() {
if (!Backend.isManaged) return;
try {
const remote = await Backend.getSettings();
if (remote && Object.keys(remote).length > 0) {
// Merge remote prefs over local, but keep apiEndpoint/apiKey local
const localEndpoint = State.settings.apiEndpoint;
const localKey = State.settings.apiKey;
State.settings = { ...State.settings, ...remote };
State.settings.apiEndpoint = localEndpoint;
State.settings.apiKey = localKey;
Storage.set('chatSwitchboard_settings', State.settings);
}
} catch (e) {
console.warn('Failed to load settings from backend:', e);
}
}
// ── Models (always localStorage) ────────────

View File

@@ -89,22 +89,27 @@ function updateQuickModelSelector() {
function openSettings() {
updateSettingsUI();
updateProfileSection();
updateProviderSection();
document.getElementById('settingsModal').classList.add('active');
}
function updateProfileSection() {
const profileSection = document.getElementById('profileSection');
const unmanagedSettings = document.getElementById('unmanagedSettings');
const modeBadge = document.getElementById('settingsModeBadge');
if (Backend.isManaged) {
profileSection.style.display = '';
unmanagedSettings.style.display = 'none';
modeBadge.textContent = '🔗 Managed Mode — API keys are configured by your admin or in Providers below';
modeBadge.className = 'settings-mode-badge mode-managed';
loadProfileIntoSettings();
} else {
profileSection.style.display = 'none';
unmanagedSettings.style.display = '';
modeBadge.textContent = '📱 Offline Mode — Configure your own API endpoint and key';
modeBadge.className = 'settings-mode-badge mode-unmanaged';
}
// Always reset password form
document.getElementById('profileChangePwForm').style.display = 'none';
}
@@ -170,6 +175,121 @@ async function handleChangePassword() {
}
}
// ── API Providers (managed mode) ────────────
function updateProviderSection() {
const managed = document.getElementById('managedProviders');
if (Backend.isManaged) {
managed.style.display = '';
loadProviderList();
} else {
managed.style.display = 'none';
}
}
async function loadProviderList() {
const container = document.getElementById('providerList');
container.innerHTML = '<div class="admin-loading">Loading...</div>';
try {
const data = await Backend.listConfigs();
const configs = data.configs || data.data || data || [];
const list = Array.isArray(configs) ? configs : [];
if (list.length === 0) {
container.innerHTML = '<div class="provider-empty">No providers configured. Add one to start chatting.</div>';
return;
}
container.innerHTML = list.map(c => `
<div class="provider-row">
<div class="provider-info">
<span class="provider-name">${escapeHtmlUI(c.name)}</span>
<span class="provider-meta">${c.provider} · ${c.model_default || 'no default'}</span>
</div>
<div class="provider-actions">
<span class="admin-badge admin-badge-active">${c.has_key ? '🔑' : '⚠️'}</span>
${c.user_id ? `<button class="btn btn-small btn-danger" onclick="deleteProvider('${c.id}', '${escapeHtmlUI(c.name)}')">Remove</button>` : '<span class="admin-badge admin-badge-moderator">global</span>'}
</div>
</div>
`).join('');
} catch (e) {
container.innerHTML = '<div class="admin-error">Failed to load providers: ' + e.message + '</div>';
}
}
function showProviderForm() {
document.getElementById('providerAddForm').style.display = '';
document.getElementById('providerShowAddBtn').style.display = 'none';
// Set default endpoint based on provider type
updateProviderEndpointHint();
}
function hideProviderForm() {
document.getElementById('providerAddForm').style.display = 'none';
document.getElementById('providerShowAddBtn').style.display = '';
clearProviderForm();
}
function clearProviderForm() {
document.getElementById('providerName').value = '';
document.getElementById('providerType').value = 'openai';
document.getElementById('providerEndpoint').value = '';
document.getElementById('providerApiKey').value = '';
document.getElementById('providerDefaultModel').value = '';
}
function updateProviderEndpointHint() {
const type = document.getElementById('providerType').value;
const endpoint = document.getElementById('providerEndpoint');
if (!endpoint.value) {
endpoint.placeholder = type === 'anthropic'
? 'https://api.anthropic.com'
: 'https://api.openai.com/v1';
}
}
async function handleCreateProvider() {
const name = document.getElementById('providerName').value.trim();
const provider = document.getElementById('providerType').value;
const endpoint = document.getElementById('providerEndpoint').value.trim();
const apiKey = document.getElementById('providerApiKey').value.trim();
const modelDefault = document.getElementById('providerDefaultModel').value.trim();
if (!name || !endpoint || !apiKey) {
showToast('⚠️ Name, endpoint, and API key are required', 'warning');
return;
}
try {
await Backend.createConfig(name, provider, endpoint, apiKey, modelDefault || null);
showToast('✅ Provider added', 'success');
hideProviderForm();
loadProviderList();
fetchModels(false); // Refresh model list
} catch (e) {
showToast('❌ ' + e.message, 'error');
}
}
async function deleteProvider(configId, name) {
if (!confirm('Remove provider "' + name + '"?')) return;
try {
await Backend.deleteConfig(configId);
showToast('✅ Provider removed', 'success');
loadProviderList();
fetchModels(false);
} catch (e) {
showToast('❌ ' + e.message, 'error');
}
}
function escapeHtmlUI(str) {
const div = document.createElement('div');
div.textContent = str || '';
return div.innerHTML;
}
function closeSettings() {
document.getElementById('settingsModal').classList.remove('active');
}