Changeset 0.25.4 (#164)

This commit is contained in:
2026-03-09 20:17:46 +00:00
parent 2f7a0fb027
commit dbc1a97343
22 changed files with 660 additions and 491 deletions

View File

@@ -293,6 +293,7 @@
transition: opacity var(--transition);
}
.team-admin-back:hover { opacity: 1; }
.team-admin-content { flex: 1; flex-direction: column; min-width: 0; }
.team-tab-content { padding: 0; }
/* Health + Routing admin (v0.22.3) */

View File

@@ -469,11 +469,9 @@ async function saveGrant(resourceType, resourceId) {
// ── Admin Listeners (extracted from initListeners) ──
function _initAdminListeners() {
// Admin panel navigation (elements may not exist for non-admin users)
document.getElementById('adminBackBtn')?.addEventListener('click', UI.closeAdmin);
document.querySelectorAll('.admin-cat').forEach(btn => {
btn.addEventListener('click', () => UI.switchAdminCategory(btn.dataset.cat));
});
// Back button and category tab navigation are handled by the inline
// script in admin.html (sessionStorage return URL + location.replace).
// Only wire up section-specific action handlers here.
document.getElementById('adminSaveSettings')?.addEventListener('click', handleSaveAdminSettings);
// Admin — users

View File

@@ -181,7 +181,13 @@
'<div id="adminVaultStatus"><span class="text-muted">Loading...</span></div>' +
'</div>' +
'<div id="roleFallbackBanner"></div>' +
'<button class="btn-md btn-primary" id="adminSaveSettings" style="margin-top:16px">Save Settings</button>' +
'<div style="display:flex;gap:8px;align-items:center;margin-top:16px">' +
'<button class="btn-md btn-primary" id="adminSaveSettings">Save Settings</button>' +
'<div style="flex:1"></div>' +
'<button class="btn-small" id="adminExportSettings" title="Export admin settings as JSON">Export</button>' +
'<button class="btn-small" id="adminImportSettings" title="Import admin settings from JSON">Import</button>' +
'<input type="file" id="adminImportFile" accept=".json,application/json" style="display:none">' +
'</div>' +
'</div>';
SCAFFOLDING.storage = '<div id="adminStorageContent"></div>';

View File

@@ -334,6 +334,7 @@ const API = {
listWorkspaces() { return this._get('/api/v1/workspaces'); },
createWorkspace(data) { return this._post('/api/v1/workspaces', data); },
updateWorkspace(id, patch) { return this._patch(`/api/v1/workspaces/${id}`, patch); },
deleteWorkspace(id) { return this._delete(`/api/v1/workspaces/${id}`); },
listGitCredentials() { return this._get('/api/v1/git-credentials'); },
// ── Messages ─────────────────────────────

View File

@@ -634,7 +634,7 @@ function _showSaveToNoteModal(opts) {
modal.id = 'saveToNoteModal';
modal.className = 'modal-overlay active';
modal.innerHTML = `
<div class="modal-content save-to-note-modal">
<div class="modal save-to-note-modal">
<h3>Save to Note</h3>
<div class="save-note-mode-toggle">
<label><input type="radio" name="saveNoteMode" value="create" checked> Create new note</label>

View File

@@ -318,11 +318,11 @@ function _initWorkspaceResize() {
// the open-transition is still animating.
secondary.style.transition = 'none';
void secondary.offsetWidth;
// #surface has transform:scale(z) from applyAppearance.
// getBoundingClientRect returns post-transform visual px.
// Divide by scale to recover CSS px for style.width.
const surface = document.getElementById('surface');
const m = surface?.style.transform?.match(/scale\(([^)]+)\)/);
// #surfaceInner has transform:scale(z) from applyAppearance.
// getBoundingClientRect on descendants returns post-transform
// visual px. Divide by scale to recover CSS px for style.width.
const inner = document.getElementById('surfaceInner');
const m = inner?.style.transform?.match(/scale\(([^)]+)\)/);
const scale = m ? parseFloat(m[1]) : 1;
const startW = secondary.getBoundingClientRect().width / scale;
secondary.style.width = startW + 'px';

View File

@@ -1035,9 +1035,13 @@ async function showWorkspacePicker(chatId) {
for (const opt of options) {
const row = document.createElement('div');
row.className = 'editor-qo-row' + (opt.value === currentWsId ? ' active' : '');
row.style.fontWeight = opt.value === currentWsId ? '600' : '';
row.textContent = opt.label;
row.addEventListener('click', async () => {
row.style.cssText = 'display:flex;align-items:center;gap:8px;' + (opt.value === currentWsId ? 'font-weight:600;' : '');
const label = document.createElement('span');
label.style.flex = '1';
label.style.cursor = 'pointer';
label.textContent = opt.label;
label.addEventListener('click', async () => {
overlay.remove();
if (opt.value === '__new__') {
const name = prompt('Workspace name:');
@@ -1064,6 +1068,46 @@ async function showWorkspacePicker(chatId) {
}
}
});
row.appendChild(label);
// Action buttons for real workspaces (not "None" or "Create new")
if (opt.value && opt.value !== '__new__') {
const renameBtn = document.createElement('button');
renameBtn.className = 'icon-btn';
renameBtn.title = 'Rename';
renameBtn.textContent = '✏';
renameBtn.style.cssText = 'font-size:12px;padding:2px 4px;flex-shrink:0;';
renameBtn.addEventListener('click', async (e) => {
e.stopPropagation();
const newName = prompt('Rename workspace:', opt.label);
if (!newName || !newName.trim() || newName.trim() === opt.label) return;
try {
await API.updateWorkspace(opt.value, { name: newName.trim() });
UI.toast('Workspace renamed');
overlay.remove();
showWorkspacePicker(chatId); // reopen with updated names
} catch (err) { UI.toast('Rename failed: ' + err.message, 'error'); }
});
row.appendChild(renameBtn);
const delBtn = document.createElement('button');
delBtn.className = 'icon-btn icon-btn-danger';
delBtn.title = 'Delete workspace';
delBtn.textContent = '🗑';
delBtn.style.cssText = 'font-size:12px;padding:2px 4px;flex-shrink:0;';
delBtn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!await showConfirm(`Delete workspace "${opt.label}"?\n\nAll files in this workspace will be permanently deleted.`)) return;
try {
await API.deleteWorkspace(opt.value);
UI.toast('Workspace deleted');
overlay.remove();
showWorkspacePicker(chatId);
} catch (err) { UI.toast('Delete failed: ' + err.message, 'error'); }
});
row.appendChild(delBtn);
}
list.appendChild(row);
}

View File

@@ -141,7 +141,7 @@ function _initUserProviderPrimitives() {
formEl.style.display = 'none';
_userProvForm.setCreateMode();
_userProvList.refresh();
fetchModels();
if (typeof fetchModels === 'function') fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
},
onCancel: () => {
@@ -167,7 +167,7 @@ function _initUserProviderPrimitives() {
await API.deleteConfig(prov.id);
UI.toast('Provider removed', 'success');
_userProvList.refresh();
fetchModels();
if (typeof fetchModels === 'function') fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
},
onRefresh: async (prov) => {
@@ -176,7 +176,7 @@ function _initUserProviderPrimitives() {
const result = await API.fetchProviderModels(prov.id);
const total = result.total || 0;
UI.toast(`${prov.name}: ${total} model${total !== 1 ? 's' : ''} synced`, 'success');
fetchModels();
if (typeof fetchModels === 'function') fetchModels();
} catch (e) { UI.toast(`Failed to fetch models: ${e.message}`, 'error'); }
},
});
@@ -291,24 +291,23 @@ function _initUserRolePrimitive() {
},
fetchModels: async () => {
// Refresh App.models to ensure personal provider models are current.
// Without this, newly added providers may not appear in the dropdown.
await fetchModels();
return App.models || [];
if (typeof fetchModels === 'function') await fetchModels();
return (typeof App !== 'undefined' && App.models) || [];
},
fetchRoles: async () => {
const settings = await API.getSettings();
const settings = await API.getSettings() || {};
return settings.model_roles || {};
},
onSave: async (roleId, config) => {
if (!config.primary) throw new Error('Select both a provider and model');
const settings = await API.getSettings();
const settings = await API.getSettings() || {};
const roles = settings.model_roles || {};
roles[roleId] = config;
await API.updateSettings({ model_roles: roles });
UI.toast(`${roleId} role override saved`, 'success');
},
onClear: async (roleId) => {
const settings = await API.getSettings();
const settings = await API.getSettings() || {};
const roles = settings.model_roles || {};
delete roles[roleId];
await API.updateSettings({ model_roles: Object.keys(roles).length > 0 ? roles : null });
@@ -463,77 +462,46 @@ function _renderCmdResults(query) {
}
// ── Settings Listeners (extracted from initListeners) ──
// Settings surface elements (settingsModel, providerShowAddBtn, etc.) only
// exist on the /settings/ surface. Team admin elements (settingsTeamAddMemberBtn,
// etc.) exist on the chat surface. Both are wired here — settings-surface
// features under a guard, team admin features unconditionally via ?.
function _initSettingsListeners() {
// Settings modal elements only exist on the settings surface.
// On chat surface, openSettings() navigates to /settings/ instead.
const settingsModel = document.getElementById('settingsModel');
if (!settingsModel) return;
document.getElementById('settingsCloseBtn')?.addEventListener('click', UI.closeSettings);
document.getElementById('settingsSaveBtn')?.addEventListener('click', handleSaveSettings);
document.querySelectorAll('.settings-tab').forEach(tab => {
tab.addEventListener('click', () => UI.switchSettingsTab(tab.dataset.stab));
});
settingsModel.addEventListener('change', function() {
const model = App.findModel(this.value);
const caps = model?.capabilities || {};
const hint = document.getElementById('settingsMaxHint');
if (hint) {
hint.textContent = caps.max_output_tokens > 0
? `(model max: ${(caps.max_output_tokens / 1000).toFixed(0)}K)`
: '';
}
});
document.getElementById('profileChangePwBtn').addEventListener('click', () => {
document.getElementById('profileChangePwForm').style.display = '';
});
document.getElementById('profileSavePwBtn').addEventListener('click', handleChangePassword);
// Avatar upload
document.getElementById('avatarUploadBtn').addEventListener('click', () => {
document.getElementById('avatarFileInput').click();
});
document.getElementById('avatarFileInput').addEventListener('change', async function() {
const file = this.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
try {
const data = await API.uploadAvatar(reader.result);
if (data.avatar) {
API.user.avatar = data.avatar;
API.saveTokens();
updateAvatarPreview(data.avatar);
UI.updateUser();
UI.toast('Avatar updated');
// ── Settings surface features (only exist on /settings/) ──
// Use data-surface to detect we're on the settings surface (not chat).
// Individual features guard on their own elements since each section
// only renders its own DOM.
const isSettingsSurface = document.body.dataset.surface === 'settings';
if (isSettingsSurface) {
// General section: model change hint
const settingsModel = document.getElementById('settingsModel');
if (settingsModel) {
settingsModel.addEventListener('change', function() {
const model = App.findModel(this.value);
const caps = model?.capabilities || {};
const hint = document.getElementById('settingsMaxHint');
if (hint) {
hint.textContent = caps.max_output_tokens > 0
? `(model max: ${(caps.max_output_tokens / 1000).toFixed(0)}K)`
: '';
}
} catch (e) { UI.toast(e.message || 'Upload failed', 'error'); }
};
reader.readAsDataURL(file);
this.value = '';
});
document.getElementById('avatarRemoveBtn').addEventListener('click', async () => {
try {
await API.deleteAvatar();
API.user.avatar = null;
API.saveTokens();
updateAvatarPreview(null);
UI.updateUser();
UI.toast('Avatar removed');
} catch (e) { UI.toast(e.message || 'Remove failed', 'error'); }
});
});
}
// User BYOK provider primitives
_initUserProviderPrimitives();
_initUserRolePrimitive();
document.getElementById('providerShowAddBtn').addEventListener('click', () => {
const formEl = document.getElementById('providerAddForm');
if (_userProvForm) _userProvForm.setCreateMode();
formEl.style.display = '';
});
// Providers section: BYOK form + list primitives
_initUserProviderPrimitives();
document.getElementById('providerShowAddBtn')?.addEventListener('click', () => {
const formEl = document.getElementById('providerAddForm');
if (_userProvForm) _userProvForm.setCreateMode();
if (formEl) formEl.style.display = '';
});
// Settings — Team management (team admin self-service)
// Models section: role primitives
_initUserRolePrimitive();
}
// ── Team management (team admin self-service, on chat surface) ──
document.getElementById('settingsTeamAddMemberBtn')?.addEventListener('click', async () => {
document.getElementById('settingsTeamAddMember').style.display = '';
const sel = document.getElementById('settingsTeamMemberUser');
@@ -578,7 +546,7 @@ function _initSettingsListeners() {
_teamPersonaForm.clearForm();
UI.toast('Team persona created');
await UI.loadTeamManagePersonas(teamId);
await fetchModels();
if (typeof fetchModels === 'function') await fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
},
onCancel: () => { container.style.display = 'none'; _teamPersonaForm.clearForm(); }
@@ -627,7 +595,7 @@ function _initSettingsListeners() {
_userPersonaForm.clearForm();
UI.toast('Persona created');
await UI.loadUserPersonas();
await fetchModels();
if (typeof fetchModels === 'function') await fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
},
onCancel: () => { container.style.display = 'none'; _userPersonaForm.clearForm(); }
@@ -644,28 +612,6 @@ function _initSettingsListeners() {
});
}
});
// Admin — banner controls
document.getElementById('adminBannerEnabled')?.addEventListener('change', (e) => {
document.getElementById('bannerConfigFields').style.display = e.target.checked ? '' : 'none';
});
['adminBannerText', 'adminBannerBg', 'adminBannerFg'].forEach(id => {
document.getElementById(id)?.addEventListener('input', UI.updateBannerPreview);
});
document.getElementById('adminBannerBg')?.addEventListener('input', (e) => { document.getElementById('adminBannerBgHex').value = e.target.value; });
document.getElementById('adminBannerFg')?.addEventListener('input', (e) => { document.getElementById('adminBannerFgHex').value = e.target.value; });
document.getElementById('adminBannerBgHex')?.addEventListener('input', (e) => { if (/^#[0-9a-f]{6}$/i.test(e.target.value)) { document.getElementById('adminBannerBg').value = e.target.value; UI.updateBannerPreview(); }});
document.getElementById('adminBannerFgHex')?.addEventListener('input', (e) => { if (/^#[0-9a-f]{6}$/i.test(e.target.value)) { document.getElementById('adminBannerFg').value = e.target.value; UI.updateBannerPreview(); }});
// Admin — auto-compaction controls
document.getElementById('adminCompactionEnabled')?.addEventListener('change', (e) => {
document.getElementById('compactionConfigFields').style.display = e.target.checked ? '' : 'none';
});
// Admin — search provider controls
document.getElementById('adminSearchProvider')?.addEventListener('change', (e) => {
document.getElementById('searxngConfigFields').style.display = e.target.value === 'searxng' ? '' : 'none';
});
}
// Admin settings toggle wiring — safe to call from admin surface scaffold
@@ -704,4 +650,187 @@ function _initAdminSettingsToggles() {
document.getElementById('usageRefreshBtn')?.addEventListener('click', () => UI.loadAdminUsage());
document.getElementById('usagePeriod')?.addEventListener('change', () => UI.loadAdminUsage());
document.getElementById('usageGroupBy')?.addEventListener('change', () => UI.loadAdminUsage());
// Admin — settings export/import
document.getElementById('adminExportSettings')?.addEventListener('click', _exportAdminSettings);
const importBtn = document.getElementById('adminImportSettings');
const importFile = document.getElementById('adminImportFile');
if (importBtn && importFile) {
importBtn.addEventListener('click', () => importFile.click());
importFile.addEventListener('change', () => {
if (importFile.files[0]) _importAdminSettings(importFile.files[0]);
importFile.value = ''; // reset so same file can be re-selected
});
}
}
// ── Admin Settings Export ────────────────────
async function _exportAdminSettings() {
try {
const data = await API.adminGetSettings();
const envelope = {
_type: 'switchboard_admin_settings',
_version: 1,
_exported_at: new Date().toISOString(),
_switchboard_version: window.__VERSION__ || 'unknown',
settings: data.settings || {},
policies: data.policies || {},
};
const blob = new Blob([JSON.stringify(envelope, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
a.download = `switchboard-admin-${ts}.json`;
a.click();
URL.revokeObjectURL(url);
// Count sensitive keys so admin is aware
const sensitiveKeys = ['search_config', 'notifications'];
const hasSensitive = sensitiveKeys.some(k => data.settings?.[k]);
UI.toast(
'Settings exported' + (hasSensitive ? ' (includes API keys/credentials)' : ''),
hasSensitive ? 'warning' : 'success'
);
} catch (e) {
UI.toast('Export failed: ' + e.message, 'error');
}
}
// ── Admin Settings Import ────────────────────
async function _importAdminSettings(file) {
try {
const text = await file.text();
let envelope;
try {
envelope = JSON.parse(text);
} catch (_) {
UI.toast('Invalid JSON file', 'error');
return;
}
if (envelope._type !== 'switchboard_admin_settings') {
UI.toast('Not a Switchboard settings export', 'error');
return;
}
const settingsCount = Object.keys(envelope.settings || {}).length;
const policiesCount = Object.keys(envelope.policies || {}).length;
const totalKeys = settingsCount + policiesCount;
if (totalKeys === 0) {
UI.toast('Settings file is empty', 'warning');
return;
}
const meta = envelope._exported_at
? `Exported ${new Date(envelope._exported_at).toLocaleString()}`
: 'Unknown export date';
const ver = envelope._switchboard_version
? ` from v${envelope._switchboard_version}`
: '';
const confirmed = await showConfirm(
`Import ${totalKeys} settings?\n\n` +
`${settingsCount} config keys, ${policiesCount} policies\n` +
`${meta}${ver}\n\n` +
`This will overwrite current admin settings.`
);
if (!confirmed) return;
let applied = 0;
let errors = 0;
// Apply policies (string values)
for (const [key, val] of Object.entries(envelope.policies || {})) {
try {
await API.adminUpdateSetting(key, { value: val });
applied++;
} catch (e) {
console.warn(`[import] policy "${key}" failed:`, e.message);
errors++;
}
}
// Apply settings (JSON values)
for (const [key, val] of Object.entries(envelope.settings || {})) {
try {
await API.adminUpdateSetting(key, { value: val });
applied++;
} catch (e) {
console.warn(`[import] setting "${key}" failed:`, e.message);
errors++;
}
}
if (errors === 0) {
UI.toast(`Imported ${applied} settings`, 'success');
} else {
UI.toast(`Imported ${applied} settings, ${errors} failed (check console)`, 'warning');
}
// Reload the settings form to reflect imported values
if (typeof UI !== 'undefined' && UI.loadAdminSettings) {
await UI.loadAdminSettings();
}
} catch (e) {
UI.toast('Import failed: ' + e.message, 'error');
}
}
// ── User-Facing Model/Persona Functions ──────
// These are called from onclick handlers rendered by loadUserModels() and
// loadUserPersonas(). Defined here so they're available on the settings
// surface (admin-handlers.js which also defines them is only loaded on
// chat and admin surfaces).
if (typeof toggleUserModelVisibility === 'undefined') {
window.toggleUserModelVisibility = async function(modelId, providerConfigId, currentlyHidden) {
const compositeKey = (providerConfigId || '') + ':' + modelId;
try {
await API.setModelPreference(modelId, providerConfigId || null, !currentlyHidden);
if (currentlyHidden) App.hiddenModels.delete(compositeKey);
else App.hiddenModels.add(compositeKey);
await UI.loadUserModels();
if (typeof fetchModels === 'function') await fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
};
}
if (typeof bulkSetUserModelVisibility === 'undefined') {
window.bulkSetUserModelVisibility = async function(show) {
const models = (App.models || []).filter(m => !m.isPersona);
if (!models.length) return;
const shouldHide = !show;
const toUpdate = models
.filter(m => {
const compositeKey = (m.configId || '') + ':' + (m.baseModelId || m.id);
return App.hiddenModels.has(compositeKey) !== shouldHide;
})
.map(m => ({ model_id: m.baseModelId || m.id, provider_config_id: m.configId || '' }));
if (!toUpdate.length) { UI.toast(show ? 'All already visible' : 'All already hidden'); return; }
try {
await API.bulkSetModelPreferences(toUpdate, shouldHide);
toUpdate.forEach(e => {
const key = (e.provider_config_id || '') + ':' + e.model_id;
shouldHide ? App.hiddenModels.add(key) : App.hiddenModels.delete(key);
});
await UI.loadUserModels();
if (typeof fetchModels === 'function') await fetchModels();
UI.toast(`${toUpdate.length} model${toUpdate.length !== 1 ? 's' : ''} ${show ? 'shown' : 'hidden'}`);
} catch (e) { UI.toast(e.message, 'error'); }
};
}
if (typeof deleteUserPersona === 'undefined') {
window.deleteUserPersona = async function(id, name) {
if (!await showConfirm(`Delete persona "${name}"?`)) return;
try {
await API.deleteUserPersona(id);
UI.toast('Persona deleted');
await UI.loadUserPersonas();
if (typeof fetchModels === 'function') await fetchModels();
} catch (e) { UI.toast(e.message, 'error'); }
};
}

View File

@@ -72,13 +72,15 @@ Object.assign(UI, {
closeAdmin() {
const base = window.__BASE__ || '';
window.location.href = base + '/';
const returnURL = sessionStorage.getItem('sb_admin_return');
sessionStorage.removeItem('sb_admin_return');
window.location.href = returnURL || (base + '/');
},
// ── Navigate to specific section ──────────
openAdminSection(section) {
const base = window.__BASE__ || '';
window.location.href = base + '/admin/' + (section || 'users');
location.replace(base + '/admin/' + (section || 'users'));
},
// ── Category switch ───────────────────────

View File

@@ -1481,30 +1481,24 @@ const UI = {
// which only loaded on chat/settings — editor surface was skipped.
applyAppearance(scale, msgFont) {
// Use transform:scale() on #surface — the prototype's proven approach.
// Transform operates on the visual layer without affecting layout flow
// of siblings (banners stay unscaled). Inverse dimensions provide the
// right layout space so the scaled visual output fills the viewport:
// At 80%: width=125%, height=125% of surface → scale(0.8) → visual 100%
// At 150%: width=66.7%, height=66.7% of surface → scale(1.5) → visual 100%
const surface = document.getElementById('surface');
if (surface) {
// Scale #surfaceInner — the generic wrapper injected by base.html
// around every surface template. No surface-specific selectors.
// #surface stays as flex child, banners are siblings — untouched.
const inner = document.getElementById('surfaceInner');
if (inner) {
if (scale === 100) {
surface.style.transform = '';
surface.style.transformOrigin = '';
surface.style.width = '';
surface.style.height = '';
inner.style.transform = '';
inner.style.width = '';
inner.style.height = '';
} else {
const z = scale / 100;
surface.style.transform = `scale(${z})`;
surface.style.transformOrigin = 'top left';
surface.style.width = (10000 / scale) + '%';
surface.style.height = `calc(var(--surface-h) * ${10000 / scale} / 100)`;
inner.style.transform = `scale(${z})`;
inner.style.width = (100 / z) + '%';
inner.style.height = (100 / z) + '%';
}
}
document.documentElement.style.setProperty('--msg-font', msgFont + 'px');
localStorage.setItem('cs-appearance', JSON.stringify({ scale, msgFont }));
// Recheck tab overflow after layout settles
requestAnimationFrame(() => {
document.querySelectorAll('.modal-overlay.active .modal-tabs').forEach(t => {
if (typeof checkTabsOverflow === 'function') checkTabsOverflow(t);
@@ -1513,7 +1507,7 @@ const UI = {
},
restoreAppearance() {
// Clear any stale zoom from previous scaling approaches
// Clear stale zoom/transform from any previous scaling approaches
document.body.style.zoom = '';
document.documentElement.style.zoom = '';
try {
@@ -1523,7 +1517,6 @@ const UI = {
if (scale !== 100 || msgFont !== 14) {
UI.applyAppearance(scale, msgFont);
} else {
// Still set the CSS variable for default
document.documentElement.style.setProperty('--msg-font', msgFont + 'px');
}
} catch (_) { /* corrupt localStorage — ignore */ }

View File

@@ -362,7 +362,7 @@ Object.assign(UI, {
titleEl.textContent = teamName;
}
document.getElementById('teamAdminPicker').style.display = 'none';
document.getElementById('teamAdminContent').style.display = '';
document.getElementById('teamAdminContent').style.display = 'flex';
// Reset forms (null-safe — not all form containers may exist)
['settingsTeamAddMember', 'settingsTeamAddPersona', 'settingsTeamProviderForm'].forEach(id => {
@@ -607,13 +607,18 @@ Object.assign(UI, {
async loadUserRoles() {
const el = document.getElementById('userRolesConfig');
const notice = document.getElementById('userRolesDisabled');
const tabBtn = document.getElementById('settingsRolesTabBtn');
if (!el) return;
// Only show if BYOK is enabled
const byokAllowed = App.policies?.allow_user_byok === 'true';
if (tabBtn) tabBtn.style.display = byokAllowed ? '' : 'none';
if (!byokAllowed) return;
if (!byokAllowed) {
el.style.display = 'none';
if (notice) {
notice.innerHTML = '<p style="color:var(--text-2);font-size:13px;">BYOK (Bring Your Own Key) must be enabled by your admin before you can configure model role overrides.</p>';
notice.style.display = '';
}
return;
}
// Check if user has personal providers
try {
@@ -623,7 +628,10 @@ Object.assign(UI, {
if (personalProviders.length === 0) {
el.style.display = 'none';
if (notice) notice.style.display = '';
if (notice) {
notice.innerHTML = '<p style="color:var(--text-2);font-size:13px;">Add a personal provider in <strong>My Providers</strong> first to configure model role overrides.</p>';
notice.style.display = '';
}
return;
}
el.style.display = '';
@@ -789,7 +797,21 @@ Object.assign(UI, {
el.innerHTML = '<div class="empty-hint">No models available</div>';
return;
}
el.innerHTML = models.map(m => {
const hiddenCount = models.filter(m => {
const cfgId = m.config_id || m.provider_config_id || '';
return App.hiddenModels.has((cfgId || '') + ':' + (m.model_id || m.id));
}).length;
const visibleCount = models.length - hiddenCount;
let html = `<div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
<span class="text-muted" style="font-size:12px">${visibleCount} visible, ${hiddenCount} hidden of ${models.length} total</span>
<div style="flex:1"></div>
<button class="btn-small" onclick="bulkSetUserModelVisibility(true)">Show All</button>
<button class="btn-small" onclick="bulkSetUserModelVisibility(false)">Hide All</button>
</div>`;
html += models.map(m => {
const mid = m.model_id || m.id;
const cfgId = m.config_id || m.provider_config_id || '';
const compositeKey = (cfgId || '') + ':' + mid;
@@ -808,6 +830,7 @@ Object.assign(UI, {
<button class="admin-model-toggle ${toggleCls}" onclick="toggleUserModelVisibility('${esc(mid)}', '${esc(cfgId)}', ${hidden})" title="${hidden ? 'Show in selector' : 'Hide from selector'}">${toggleLabel}</button>
</div>`;
}).join('');
el.innerHTML = html;
} catch (e) { el.innerHTML = `<div class="error-hint">${esc(e.message)}</div>`; }
},