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

@@ -1 +1 @@
0.25.3
0.25.4

View File

@@ -472,19 +472,21 @@ func (h *FileHandler) UploadToProject(c *gin.Context) {
userID := getUserID(c)
projectID := c.Param("id")
// Verify project access (user owns or is team member)
var exists bool
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
SELECT EXISTS(
SELECT 1 FROM projects
WHERE id = $1 AND (owner_id = $2 OR team_id IN (
SELECT team_id FROM team_members WHERE user_id = $2 AND is_active = true
))
)
`), projectID, userID).Scan(&exists)
if err != nil || !exists {
c.JSON(http.StatusForbidden, gin.H{"error": "project not found or access denied"})
return
// Verify project access (user owns or is team member; admins bypass)
if c.GetString("role") != "admin" {
var exists bool
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
SELECT EXISTS(
SELECT 1 FROM projects
WHERE id = $1 AND (owner_id = $2 OR team_id IN (
SELECT team_id FROM team_members WHERE user_id = $2 AND is_active = true
))
)
`), projectID, userID).Scan(&exists)
if err != nil || !exists {
c.JSON(http.StatusForbidden, gin.H{"error": "project not found or access denied"})
return
}
}
file, header, err := c.Request.FormFile("file")
@@ -551,19 +553,21 @@ func (h *FileHandler) ListByProject(c *gin.Context) {
userID := getUserID(c)
projectID := c.Param("id")
// Verify project access
var exists bool
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
SELECT EXISTS(
SELECT 1 FROM projects
WHERE id = $1 AND (owner_id = $2 OR team_id IN (
SELECT team_id FROM team_members WHERE user_id = $2 AND is_active = true
))
)
`), projectID, userID).Scan(&exists)
if err != nil || !exists {
c.JSON(http.StatusForbidden, gin.H{"error": "project not found or access denied"})
return
// Admins bypass project ownership/membership checks
if c.GetString("role") != "admin" {
var exists bool
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
SELECT EXISTS(
SELECT 1 FROM projects
WHERE id = $1 AND (owner_id = $2 OR team_id IN (
SELECT team_id FROM team_members WHERE user_id = $2 AND is_active = true
))
)
`), projectID, userID).Scan(&exists)
if err != nil || !exists {
c.JSON(http.StatusForbidden, gin.H{"error": "project not found or access denied"})
return
}
}
files, err := h.stores.Files.GetByProject(c.Request.Context(), projectID)

View File

@@ -4,7 +4,9 @@ import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
@@ -37,12 +39,22 @@ type liveProviderConfig struct {
// defaultEndpoints maps provider names to their default API endpoints.
var defaultEndpoints = map[string]string{
"venice": "https://api.venice.ai/api/v1",
"openai": "https://api.openai.com/v1",
"anthropic": "https://api.anthropic.com/v1",
"venice": "https://api.venice.ai/api/v1",
"openai": "https://api.openai.com/v1",
"anthropic": "https://api.anthropic.com/v1",
"openrouter": "https://openrouter.ai/api/v1",
}
// requireLiveProvider resolves provider config from env vars and skips if not configured.
// providerKeyEnvs maps provider names to their API key env var names.
var providerKeyEnvs = map[string]string{
"venice": "VENICE_API_KEY",
"openai": "OPENAI_API_KEY",
"anthropic": "ANTHROPIC_API_KEY",
"openrouter": "OPENROUTER_API_KEY",
}
// requireLiveProvider resolves the primary provider config from env vars.
// Kept for backward compat — tests that only need one provider use this.
func requireLiveProvider(t *testing.T) liveProviderConfig {
t.Helper()
@@ -73,6 +85,191 @@ func requireLiveProvider(t *testing.T) liveProviderConfig {
return liveProviderConfig{Provider: provider, Key: key, Endpoint: endpoint}
}
// requireLiveProviders resolves all configured providers for failover tests.
// Reads LIVE_PROVIDERS (comma-separated, e.g. "venice,openai") and resolves
// API keys from {PROVIDER}_API_KEY env vars. Falls back to requireLiveProvider
// if LIVE_PROVIDERS is not set.
func requireLiveProviders(t *testing.T) []liveProviderConfig {
t.Helper()
list := os.Getenv("LIVE_PROVIDERS")
if list == "" {
// Fallback: just the primary provider
return []liveProviderConfig{requireLiveProvider(t)}
}
var configs []liveProviderConfig
for _, name := range splitTrim(list, ",") {
keyEnv := providerKeyEnvs[name]
if keyEnv == "" {
keyEnv = strings.ToUpper(name) + "_API_KEY"
}
key := os.Getenv(keyEnv)
if key == "" {
t.Logf(" Skipping provider %s: %s not set", name, keyEnv)
continue
}
endpoint := os.Getenv(strings.ToUpper(name) + "_API_URL")
if endpoint == "" {
endpoint = defaultEndpoints[name]
}
if endpoint == "" {
t.Logf(" Skipping provider %s: no endpoint", name)
continue
}
configs = append(configs, liveProviderConfig{Provider: name, Key: key, Endpoint: endpoint})
}
if len(configs) == 0 {
t.Skip("no live providers configured — set LIVE_PROVIDERS + API keys")
}
t.Logf(" Live providers: %d configured", len(configs))
return configs
}
// splitTrim splits s by sep and trims whitespace from each element.
func splitTrim(s, sep string) []string {
parts := strings.Split(s, sep)
var out []string
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}
// providerModel holds a resolved (configID, modelID) pair from a provider.
type providerModel struct {
ConfigID string
ModelID string
Provider string
}
// setupAllProviders creates configs and enables a model for each provider.
// Tolerant: if a provider fails setup, it's skipped. Fails only if zero succeed.
func setupAllProviders(t *testing.T, h *testHarness, adminToken string, providerList []liveProviderConfig) []providerModel {
t.Helper()
var models []providerModel
for _, pc := range providerList {
configID, modelID, err := trySetupProvider(h, adminToken, pc)
if err != nil {
t.Logf(" ⚠ %s setup failed: %v — skipping", pc.Provider, err)
continue
}
t.Logf(" Provider %s ready, model %s enabled", pc.Provider, modelID)
models = append(models, providerModel{ConfigID: configID, ModelID: modelID, Provider: pc.Provider})
}
if len(models) == 0 {
t.Fatal("no providers available after setup — all failed")
}
return models
}
// trySetupProvider is like setupProviderWithModel but returns error instead of t.Fatal.
func trySetupProvider(h *testHarness, adminToken string, pc liveProviderConfig) (string, string, error) {
// Create provider
w := h.request("POST", "/api/v1/admin/configs", adminToken, map[string]interface{}{
"name": pc.Provider + " Test", "provider": pc.Provider,
"endpoint": pc.Endpoint, "api_key": pc.Key,
})
if w.Code != http.StatusCreated {
return "", "", fmt.Errorf("create config: %d: %s", w.Code, w.Body.String())
}
var cfg map[string]interface{}
decode(w, &cfg)
configID := cfg["id"].(string)
// Fetch models
w = h.request("POST", "/api/v1/admin/models/fetch", adminToken,
map[string]interface{}{"provider_config_id": configID})
if w.Code != http.StatusOK {
return "", "", fmt.Errorf("fetch models: %d: %s", w.Code, w.Body.String())
}
// Find and enable a non-reasoning model
w = h.request("GET", "/api/v1/admin/models", adminToken, nil)
var modelsResp map[string]interface{}
decode(w, &modelsResp)
var catalogID, modelID string
var fallbackCatalogID, fallbackModelID string
for _, raw := range modelsResp["models"].([]interface{}) {
m := raw.(map[string]interface{})
if m["visibility"].(string) != "disabled" {
continue
}
// Only pick models from this provider
if m["provider_config_id"] != nil && m["provider_config_id"].(string) != configID {
continue
}
mid := m["model_id"].(string)
cid := m["id"].(string)
if fallbackCatalogID == "" {
fallbackCatalogID = cid
fallbackModelID = mid
}
isReasoning := false
if caps, ok := m["capabilities"].(map[string]interface{}); ok {
if r, exists := caps["reasoning"]; exists && r == true {
isReasoning = true
}
}
if !isReasoning {
catalogID = cid
modelID = mid
break
}
}
if catalogID == "" {
catalogID = fallbackCatalogID
modelID = fallbackModelID
}
if catalogID == "" {
return "", "", fmt.Errorf("no disabled model found")
}
w = h.request("PUT", "/api/v1/admin/models/"+catalogID, adminToken,
map[string]interface{}{"visibility": "enabled"})
if w.Code != http.StatusOK {
return "", "", fmt.Errorf("enable model: %d: %s", w.Code, w.Body.String())
}
return configID, modelID, nil
}
// tryCompletion attempts a completion against each provider/model in order.
// Returns the first successful response and the provider that worked.
// Fails only if ALL providers fail.
func tryCompletion(t *testing.T, h *testHarness, token, channelID string, models []providerModel, stream bool) (*httptest.ResponseRecorder, providerModel) {
t.Helper()
var lastW *httptest.ResponseRecorder
for _, pm := range models {
w := h.request("POST", "/api/v1/chat/completions", token, map[string]interface{}{
"channel_id": channelID,
"content": "Say ok",
"model": pm.ModelID,
"provider_config_id": pm.ConfigID,
"stream": &stream,
"max_tokens": 1200,
})
if w.Code == http.StatusOK {
t.Logf(" ✓ Completion via %s/%s (status %d)", pm.Provider, pm.ModelID, w.Code)
return w, pm
}
t.Logf(" ✗ %s/%s returned %d — trying next", pm.Provider, pm.ModelID, w.Code)
lastW = w
}
// All failed
body := ""
if lastW != nil {
body = lastW.Body.String()
}
t.Fatalf("all %d providers failed; last: %s", len(models), body)
return nil, providerModel{} // unreachable
}
// setupProviderWithModel creates a provider config, fetches models, and enables
// the first available model. Returns (configID, enabledModelID).
func setupProviderWithModel(t *testing.T, h *testHarness, adminToken string, pc liveProviderConfig) (string, string) {
@@ -334,10 +531,10 @@ func TestLive_FetchModelsCapabilities(t *testing.T) {
// TestLive_ChatCompletion sends an actual non-streaming chat completion.
func TestLive_ChatCompletion(t *testing.T) {
h := setupHarness(t)
pc := requireLiveProvider(t)
liveProvs := requireLiveProviders(t)
_, adminToken := h.createAdminUser("admin", "admin@test.com")
configID, modelID := setupProviderWithModel(t, h, adminToken, pc)
models := setupAllProviders(t, h, adminToken, liveProvs)
w := h.request("POST", "/api/v1/channels", adminToken, map[string]interface{}{
"title": "Chat Test", "type": "direct",
@@ -349,18 +546,7 @@ func TestLive_ChatCompletion(t *testing.T) {
decode(w, &ch)
channelID := ch["id"].(string)
stream := false
w = h.request("POST", "/api/v1/chat/completions", adminToken, map[string]interface{}{
"channel_id": channelID,
"content": "Say ok",
"model": modelID,
"provider_config_id": configID,
"stream": &stream,
"max_tokens": 1200,
})
if w.Code != http.StatusOK {
t.Fatalf("completion: want 200, got %d: %s", w.Code, w.Body.String())
}
w, _ = tryCompletion(t, h, adminToken, channelID, models, false)
t.Logf(" ✓ Completion succeeded: %s", w.Body.String()[:min(200, w.Body.Len())])
}
@@ -368,10 +554,10 @@ func TestLive_ChatCompletion(t *testing.T) {
// creates a usage_log row with token counts.
func TestLive_UsageLogging(t *testing.T) {
h := setupHarness(t)
pc := requireLiveProvider(t)
liveProvs := requireLiveProviders(t)
_, adminToken := h.createAdminUser("admin", "admin@test.com")
configID, modelID := setupProviderWithModel(t, h, adminToken, pc)
models := setupAllProviders(t, h, adminToken, liveProvs)
w := h.request("POST", "/api/v1/channels", adminToken, map[string]interface{}{
"title": "Usage Test", "type": "direct",
@@ -382,23 +568,12 @@ func TestLive_UsageLogging(t *testing.T) {
var ch map[string]interface{}
decode(w, &ch)
stream := false
w = h.request("POST", "/api/v1/chat/completions", adminToken, map[string]interface{}{
"channel_id": ch["id"].(string),
"content": "Say ok",
"model": modelID,
"provider_config_id": configID,
"stream": &stream,
"max_tokens": 1200,
})
if w.Code != http.StatusOK {
t.Fatalf("completion: %d: %s", w.Code, w.Body.String())
}
_, used := tryCompletion(t, h, adminToken, ch["id"].(string), models, false)
var rowCount, promptTokens, completionTokens int
err := database.TestDB.QueryRow(
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens), 0), COALESCE(SUM(completion_tokens), 0) FROM usage_log WHERE provider_config_id = "+database.PH(1),
configID).Scan(&rowCount, &promptTokens, &completionTokens)
used.ConfigID).Scan(&rowCount, &promptTokens, &completionTokens)
if err != nil {
t.Fatalf("query usage_log: %v", err)
}
@@ -408,16 +583,16 @@ func TestLive_UsageLogging(t *testing.T) {
if promptTokens == 0 {
t.Fatal("completion should report prompt tokens")
}
t.Logf(" ✓ Usage: %d row(s), prompt=%d completion=%d", rowCount, promptTokens, completionTokens)
t.Logf(" ✓ Usage: %d row(s), prompt=%d completion=%d (via %s)", rowCount, promptTokens, completionTokens, used.Provider)
}
// TestLive_StreamingUsageLogging verifies streaming completions log usage.
func TestLive_StreamingUsageLogging(t *testing.T) {
h := setupHarness(t)
pc := requireLiveProvider(t)
liveProvs := requireLiveProviders(t)
_, adminToken := h.createAdminUser("admin", "admin@test.com")
configID, modelID := setupProviderWithModel(t, h, adminToken, pc)
models := setupAllProviders(t, h, adminToken, liveProvs)
w := h.request("POST", "/api/v1/channels", adminToken, map[string]interface{}{
"title": "Stream Usage Test", "type": "direct",
@@ -428,23 +603,12 @@ func TestLive_StreamingUsageLogging(t *testing.T) {
var ch map[string]interface{}
decode(w, &ch)
stream := true
w = h.request("POST", "/api/v1/chat/completions", adminToken, map[string]interface{}{
"channel_id": ch["id"].(string),
"content": "Say ok",
"model": modelID,
"provider_config_id": configID,
"stream": &stream,
"max_tokens": 1200,
})
if w.Code != http.StatusOK {
t.Fatalf("streaming completion: %d: %s", w.Code, w.Body.String())
}
_, used := tryCompletion(t, h, adminToken, ch["id"].(string), models, true)
var rowCount, promptTokens, completionTokens int
err := database.TestDB.QueryRow(
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens), 0), COALESCE(SUM(completion_tokens), 0) FROM usage_log WHERE provider_config_id = "+database.PH(1),
configID).Scan(&rowCount, &promptTokens, &completionTokens)
used.ConfigID).Scan(&rowCount, &promptTokens, &completionTokens)
if err != nil {
t.Fatalf("query usage_log: %v", err)
}
@@ -454,7 +618,7 @@ func TestLive_StreamingUsageLogging(t *testing.T) {
if promptTokens == 0 {
t.Fatal("streaming completion should report prompt tokens")
}
t.Logf(" ✓ Streaming usage: %d row(s), prompt=%d completion=%d", rowCount, promptTokens, completionTokens)
t.Logf(" ✓ Streaming usage: %d row(s), prompt=%d completion=%d (via %s)", rowCount, promptTokens, completionTokens, used.Provider)
}
// TestLive_PricingFromCatalog verifies model sync populates pricing.

View File

@@ -449,16 +449,20 @@ func (h *ProjectHandler) loadAndAuthorize(c *gin.Context) (*models.Project, bool
}
userID := getUserID(c)
teamIDs, _ := h.stores.Teams.GetUserTeamIDs(c.Request.Context(), userID)
ok, err := h.stores.Projects.UserCanAccess(c.Request.Context(), userID, projectID, teamIDs)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "access check failed"})
return nil, false
}
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "project not found"})
return nil, false
// Admins can access all projects
if c.GetString("role") != "admin" {
teamIDs, _ := h.stores.Teams.GetUserTeamIDs(c.Request.Context(), userID)
ok, err := h.stores.Projects.UserCanAccess(c.Request.Context(), userID, projectID, teamIDs)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "access check failed"})
return nil, false
}
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "project not found"})
return nil, false
}
}
project, err := h.stores.Projects.GetByID(c.Request.Context(), projectID)

View File

@@ -171,8 +171,11 @@ func (h *SettingsHandler) GetSettings(c *gin.Context) {
userID := getUserID(c)
var settingsRaw string
// Handle three states: SQL NULL, JSON null, or valid JSON object.
// NULLIF(settings, 'null') converts JSON null to SQL NULL,
// then COALESCE handles both SQL NULL cases.
err := database.DB.QueryRow(
database.Q(`SELECT settings::text FROM users WHERE id = $1`), userID,
database.Q(`SELECT COALESCE(NULLIF(settings::text, 'null'), '{}') FROM users WHERE id = $1`), userID,
).Scan(&settingsRaw)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load settings"})
@@ -202,12 +205,25 @@ func (h *SettingsHandler) UpdateSettings(c *gin.Context) {
return
}
// JSONB merge — existing keys preserved, incoming keys overwrite
// JSONB merge — existing keys preserved, incoming keys overwrite.
// Must handle three column states:
// 1. SQL NULL (never saved)
// 2. JSON literal null (corrupted by earlier bug)
// 3. JSON array (corrupted by repeated appends to null)
// 4. Valid JSON object (normal)
// NULLIF converts JSON null → SQL NULL, then COALESCE → '{}',
// and we enforce jsonb_typeof = 'object' to catch array corruption.
var mergeQuery string
if database.IsSQLite() {
mergeQuery = `UPDATE users SET settings = json_patch(settings, ?), updated_at = datetime('now') WHERE id = ?`
mergeQuery = `UPDATE users SET settings = json_patch(
CASE WHEN settings IS NULL OR settings = 'null' OR json_type(settings) != 'object'
THEN '{}' ELSE settings END,
?), updated_at = datetime('now') WHERE id = ?`
} else {
mergeQuery = `UPDATE users SET settings = settings || $1::jsonb, updated_at = NOW() WHERE id = $2`
mergeQuery = `UPDATE users SET settings = (
CASE WHEN settings IS NULL OR settings = 'null'::jsonb OR jsonb_typeof(settings) != 'object'
THEN '{}'::jsonb ELSE settings END
) || $1::jsonb, updated_at = NOW() WHERE id = $2`
}
_, err = database.DB.Exec(mergeQuery, string(patch), userID)
if err != nil {

View File

@@ -430,22 +430,14 @@ func (e *Engine) settingsLoader(c *gin.Context, s store.Stores) (any, error) {
data := &SettingsPageData{Section: section}
// Read feature gates from admin config
if s.GlobalConfig != nil {
// Read feature gates from policies (where admin settings saves them).
// Keys: allow_user_byok, allow_user_personas
if s.Policies != nil {
ctx := context.Background()
// BYOK: check if user providers are enabled
if raw, err := s.GlobalConfig.Get(ctx, "user_providers"); err == nil && raw != nil {
if v, ok := raw["enabled"].(bool); ok {
data.BYOKEnabled = v
}
}
// User Personas: check if user-created personas are enabled
if raw, err := s.GlobalConfig.Get(ctx, "user_personas"); err == nil && raw != nil {
if v, ok := raw["enabled"].(bool); ok {
data.UserPersonasEnabled = v
}
policies, err := s.Policies.GetAll(ctx)
if err == nil {
data.BYOKEnabled = policies["allow_user_byok"] == "true"
data.UserPersonasEnabled = policies["allow_user_personas"] == "true"
}
}

View File

@@ -26,12 +26,10 @@
<style>
:root {
--banner-h: 28px;
--banner-top-h: {{if .Banner.Visible}}var(--banner-h){{else}}0px{{end}};
--banner-bot-h: {{if .Banner.Visible}}var(--banner-h){{else}}0px{{end}};
--surface-h: calc(100vh - var(--banner-top-h) - var(--banner-bot-h));
}
body { margin: 0; background: var(--bg); color: var(--text); }
.surface { height: var(--surface-h); overflow: hidden; }
body { margin: 0; background: var(--bg); color: var(--text); display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
.surface { flex: 1; min-height: 0; overflow: hidden; }
.surface-inner { width: 100%; height: 100%; transform-origin: top left; }
.banner { flex-shrink: 0; }
</style>
<meta name="theme-color" content="#0e0e10" id="metaThemeColor">
@@ -58,6 +56,7 @@
{{end}}
<div class="surface" id="surface">
<div class="surface-inner" id="surfaceInner">
{{if eq .Surface "chat"}}{{template "surface-chat" .}}
{{else if eq .Surface "admin"}}{{template "surface-admin" .}}
{{else if eq .Surface "editor"}}{{template "surface-editor" .}}
@@ -65,6 +64,7 @@
{{else if eq .Surface "settings"}}{{template "surface-settings" .}}
{{else}}<div style="padding:20px">Unknown surface: {{.Surface}}</div>
{{end}}
</div>
</div>
{{if .Banner.Visible}}

View File

@@ -9,7 +9,7 @@
{{/* Top Bar */}}
<div class="admin-topbar">
<a href="{{.BasePath}}/" class="admin-topbar-back" id="adminBackBtn">>
<a href="{{.BasePath}}/" class="admin-topbar-back" id="adminBackBtn">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
Back
</a>
@@ -44,16 +44,8 @@
</div>
<div class="admin-body">
{{/* Left Nav */}}
<div class="admin-nav" id="adminNav">
{{/* People sections */}}
{{if eq $section "users"}}<a href="{{$base}}/admin/users" class="admin-nav-link active">Users</a>
{{else}}<a href="{{$base}}/admin/users" class="admin-nav-link">Users</a>{{end}}
{{if eq $section "teams"}}<a href="{{$base}}/admin/teams" class="admin-nav-link active">Teams</a>
{{else}}<a href="{{$base}}/admin/teams" class="admin-nav-link">Teams</a>{{end}}
{{if eq $section "groups"}}<a href="{{$base}}/admin/groups" class="admin-nav-link active">Groups</a>
{{else}}<a href="{{$base}}/admin/groups" class="admin-nav-link">Groups</a>{{end}}
</div>
{{/* Left Nav — populated by admin-scaffold.js from ADMIN_SECTIONS */}}
<div class="admin-nav" id="adminNav"></div>
{{/* Content Area */}}
<div class="admin-content">
@@ -218,6 +210,7 @@
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/persona-kb.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/memory-ui.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/notifications.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/files.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/admin-scaffold.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/admin-surfaces.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}">

View File

@@ -350,234 +350,9 @@ window.addEventListener('unhandledrejection', function(e) {
{{/* ── Hidden File Input ─────── */}}
<input type="file" id="fileInput" multiple style="display:none;">
{{/* ── Team Admin Modal ────────────────────── */}}
</div>
<div class="modal-body">
{{/* General tab */}}
<div id="settingsGeneralTab" class="settings-tab-content" style="display:block;">
<div class="form-group">
<label>Model</label>
<select id="settingsModel"></select>
</div>
<div class="form-group">
<label>System Prompt</label>
<textarea id="settingsSystemPrompt" rows="4"></textarea>
</div>
<div class="form-group">
<label>Max Tokens <span id="settingsMaxHint" class="form-hint"></span></label>
<input type="number" id="settingsMaxTokens" placeholder="default">
</div>
<div class="form-group">
<label>Temperature</label>
<input type="range" id="settingsTemp" min="0" max="2" step="0.1" value="0.7">
</div>
<div class="form-group">
<label><input type="checkbox" id="settingsThinking"> Show thinking blocks</label>
</div>
</div>
{{/* Appearance tab */}}
<div id="settingsAppearanceTab" class="settings-tab-content" style="display:none;">
<div class="form-group">
<label>Message Font Size</label>
<div style="display:flex;align-items:center;gap:8px;">
<input type="range" id="settingsMsgFont" min="12" max="20" step="1" value="14">
<span id="msgFontValue">14px</span>
</div>
</div>
<div class="form-group">
<label>UI Scale</label>
<div style="display:flex;align-items:center;gap:8px;">
<input type="range" id="settingsScale" min="0.8" max="1.2" step="0.05" value="1.0">
<span id="scaleValue">100%</span>
</div>
</div>
</div>
{{/* Providers tab */}}
<div id="settingsProvidersTab" class="settings-tab-content" style="display:none;">
<div id="userProvidersDisabled" class="notice" style="display:none;">Personal API keys are not enabled by your administrator.</div>
<button id="providerShowAddBtn" class="btn-small" style="display:none;">+ Add Provider</button>
<div id="providerAddForm" style="display:none;"></div>
<div id="providerList"></div>
</div>
{{/* Personas tab */}}
<div id="settingsPersonasTab" class="settings-tab-content" style="display:none;">
<button id="userAddPersonaBtn" class="btn-small" style="display:none;">+ New Persona</button>
<div id="userAddPersonaForm" style="display:none;"></div>
<div id="userPersonaList"></div>
</div>
{{/* Usage tab */}}
<div id="settingsUsageTab" class="settings-tab-content" style="display:none;">
<div id="myUsageTotals"></div>
</div>
{{/* Profile tab */}}
<div id="settingsProfileTab" class="settings-tab-content" style="display:none;">
<div class="form-group">
<label>Avatar</label>
<div style="display:flex;align-items:center;gap:12px;margin-bottom:4px;">
<div id="avatarPreview" class="user-avatar" style="width:48px;height:48px;font-size:20px;">
<span id="avatarPreviewLetter">?</span>
</div>
<div style="display:flex;gap:6px;">
<button id="avatarUploadBtn" class="btn-small">Upload</button>
<button id="avatarRemoveBtn" class="btn-small btn-danger" style="display:none;">Remove</button>
</div>
<input type="file" id="avatarFileInput" accept="image/*" style="display:none;">
</div>
</div>
<div class="form-group">
<label>Display Name</label>
<input type="text" id="profileDisplayName">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="profileEmail" disabled>
</div>
<div class="form-group">
<button id="profileChangePwBtn" class="btn-small">Change Password</button>
<div id="profileChangePwForm" style="display:none;margin-top:8px;">
<input type="password" id="profileCurrentPw" placeholder="Current password" autocomplete="current-password" style="margin-bottom:6px;">
<input type="password" id="profileNewPw" placeholder="New password" autocomplete="new-password" style="margin-bottom:6px;">
<input type="password" id="profileConfirmPw" placeholder="Confirm new password" autocomplete="new-password" style="margin-bottom:6px;">
<button id="profileSavePwBtn" class="btn-small">Update Password</button>
</div>
</div>
</div>
{{/* Roles tab (admin) */}}
<div id="settingsRolesTab" class="settings-tab-content" style="display:none;">
<div id="userRolesDisabled" class="notice" style="display:none;"></div>
<div id="userRolesConfig"></div>
<div id="userModelList"></div>
</div>
{{/* KB tab */}}
<div id="settingsKBTab" class="settings-tab-content" style="display:none;">
<div id="kbManagePanel"></div>
</div>
{{/* Teams tab */}}
<div id="settingsTeamsTab" class="settings-tab-content" style="display:none;">
<div id="settingsTeamsList"></div>
<div id="settingsTeamMembers" style="display:none;"></div>
<div id="settingsTeamPersonas" style="display:none;">
<div id="teamPersonaList"></div>
</div>
<div id="settingsTeamProviders" style="display:none;">
<button id="settingsTeamAddProviderBtn" class="btn-small" style="display:none;">+ Add Provider</button>
<div id="settingsTeamProviderForm" style="display:none;"></div>
</div>
<div id="settingsTeamGroups" style="display:none;"></div>
<div id="settingsTeamAudit" style="display:none;"></div>
<div id="settingsTeamUsageTotals" style="display:none;"></div>
</div>
{{/* Memory tab */}}
<div id="settingsMemoryTab" class="settings-tab-content" style="display:none;">
<div id="settingsMemoryContent"></div>
</div>
</div>
<div class="modal-footer">
<button id="settingsSaveBtn" class="btn-primary" onclick="UI.saveSettingsAndClose()">Save</button>
<button class="btn-secondary" onclick="closeModal('settingsModal')">Cancel</button>
</div>
</div>
</div>
{{/* ── Admin Panel (SPA modal — fallback, admin surface is preferred) */}}
<div id="adminPanel" class="modal-overlay">
<div class="modal-content modal-xl">
<div class="modal-header">
<h2>Admin</h2>
<button class="modal-close" onclick="closeModal('adminPanel')"></button>
</div>
<div class="modal-body" style="display:flex;min-height:400px;">
<div id="adminSidebar" class="admin-sidebar"></div>
<div class="admin-content" style="flex:1;overflow-y:auto;padding:16px;">
{{/* Admin sections — dynamically shown/hidden by ui-admin.js */}}
<div id="adminStats" class="admin-section"></div>
<div id="adminModelList" class="admin-section" style="display:none;"></div>
<div id="adminProviderList" class="admin-section" style="display:none;"></div>
<div id="adminUserList" class="admin-section" style="display:none;"></div>
<div id="adminTeamList" class="admin-section" style="display:none;"></div>
<div id="adminHealthContent" class="admin-section" style="display:none;">
<button id="adminHealthRefreshBtn" class="btn-small">Refresh</button>
</div>
<div id="adminRolesContent" class="admin-section" style="display:none;"></div>
<div id="adminCapabilityList" class="admin-section" style="display:none;"></div>
<div id="adminExtensionsList" class="admin-section" style="display:none;"></div>
<div id="adminPricingTable" class="admin-section" style="display:none;"></div>
<div id="adminAuditList" class="admin-section" style="display:none;">
<div style="display:flex;gap:8px;margin-bottom:8px;">
<select id="auditFilterAction"><option value="">All actions</option></select>
<select id="auditFilterResource"><option value="">All resources</option></select>
</div>
<div id="auditPagination" style="display:flex;gap:8px;align-items:center;">
<button id="auditPrevBtn" class="btn-small" disabled>← Prev</button>
<span id="auditPageInfo"></span>
<button id="auditNextBtn" class="btn-small">Next →</button>
</div>
</div>
<div id="adminStorageContent" class="admin-section" style="display:none;"></div>
<div id="adminRoutingPolicyList" class="admin-section" style="display:none;">
<button id="adminAddRoutingPolicyBtn" class="btn-small">+ Add Policy</button>
<div id="adminRoutingForm" style="display:none;"></div>
<div style="margin-top:16px;border-top:1px solid var(--border);padding-top:16px;">
<h4>Test Routing</h4>
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
<input type="text" id="routingTestModel" placeholder="Model ID">
<input type="text" id="routingTestUser" placeholder="User ID (optional)">
<button id="routingTestBtn" class="btn-small">Test</button>
</div>
<pre id="routingTestResult" style="margin-top:8px;font-size:12px;"></pre>
</div>
</div>
<div id="adminUsageResults" class="admin-section" style="display:none;">
<div id="adminUsageTotals"></div>
<div id="_adminUsageContainer"></div>
</div>
{{/* Settings admin section */}}
<div class="admin-section" style="display:none;">
<div class="form-group"><label><input type="checkbox" id="adminRegToggle"> Registration Enabled</label></div>
<div class="form-group"><label>Default User State</label><select id="adminRegDefaultState"><option value="active">Active</option><option value="pending">Pending Approval</option></select></div>
<div class="form-group"><label><input type="checkbox" id="adminUserProvidersToggle"> Allow User BYOK</label></div>
<div class="form-group"><label><input type="checkbox" id="adminUserPersonasToggle"> Allow User Personas</label></div>
<div class="form-group"><label><input type="checkbox" id="adminKBDirectAccessToggle"> KB Direct Access</label></div>
<div class="form-group"><label>Default Model</label><select id="adminDefaultModel"></select></div>
<div class="form-group"><label>System Prompt</label><textarea id="adminSystemPrompt" rows="4"></textarea></div>
<div class="form-group"><label><input type="checkbox" id="adminBannerEnabled"> Banner</label></div>
<div id="bannerConfigFields" style="display:none;">
<input type="text" id="adminBannerText" placeholder="Banner text">
<div style="display:flex;gap:8px;margin-top:6px;">
<input type="color" id="adminBannerBg" value="#007a33"><input type="text" id="adminBannerBgHex" value="#007a33" style="width:80px;">
<input type="color" id="adminBannerFg" value="#ffffff"><input type="text" id="adminBannerFgHex" value="#ffffff" style="width:80px;">
</div>
<div id="bannerPreview" class="banner-preview" style="margin-top:8px;"></div>
</div>
<div class="form-group"><label><input type="checkbox" id="adminMemoryExtractionEnabled"> Memory Extraction</label></div>
<div id="memoryExtractionConfigFields" style="display:none;">
<label><input type="checkbox" id="adminMemoryAutoApprove"> Auto-approve</label>
</div>
<div class="form-group"><label><input type="checkbox" id="adminCompactionEnabled"> Auto-Compaction</label></div>
<div id="compactionConfigFields" style="display:none;">
<label>Threshold <input type="number" id="adminCompactionThreshold" value="100000"></label>
<label>Cooldown <input type="number" id="adminCompactionCooldown" value="3600"></label>
</div>
<div class="form-group">
<label>Web Search</label>
<select id="adminSearchProvider"><option value="">Disabled</option><option value="searxng">SearXNG</option></select>
<div id="searxngConfigFields" style="display:none;">
<input type="text" id="adminSearchEndpoint" placeholder="SearXNG URL">
<input type="text" id="adminSearchApiKey" placeholder="API key (optional)">
<input type="number" id="adminSearchMaxResults" placeholder="Max results" value="5">
</div>
</div>
<button id="adminRunCleanup" class="btn-small btn-danger" style="margin-top:12px;">Run Cleanup</button>
<div id="adminVaultStatus" style="margin-top:12px;"></div>
</div>
</div>
</div>
</div>
</div>
{{/* ── Team Admin Modal ────────────────────── */}}
<div id="teamAdminModal" class="modal-overlay">
<div class="modal-content modal-lg" style="max-width:900px;height:80vh;display:flex;flex-direction:column;">
<div class="modal" style="max-width:900px;height:80vh;display:flex;flex-direction:column;">
<div class="modal-header" style="flex-shrink:0;">
<h2 id="teamAdminTitle">Team Admin</h2>
<button id="teamAdminCloseBtn" class="modal-close"></button>
@@ -589,7 +364,7 @@ window.addEventListener('unhandledrejection', function(e) {
</div>
{{/* Tabbed team management */}}
<div id="teamAdminContent" style="display:none;flex:1;display:flex;flex-direction:column;min-width:0;">
<div id="teamAdminContent" class="team-admin-content" style="display:none;">
{{/* Tab bar */}}
<div id="teamAdminTabs" style="display:flex;gap:2px;padding:8px 16px;border-bottom:1px solid var(--border);flex-shrink:0;overflow-x:auto;">
<button class="admin-tab active" data-ttab="members" onclick="UI.switchTeamTab('members')">Members</button>
@@ -628,8 +403,10 @@ window.addEventListener('unhandledrejection', function(e) {
{{/* Personas */}}
<div id="teamTabPersonas" class="team-tab-content" style="display:none;">
<div id="teamPersonaList"></div>
<div id="settingsTeamAddPersona" style="display:none;margin-top:12px;"></div>
<div id="settingsTeamPersonas" style="display:none;"></div>
<div style="display:none;"><select id="teamPersona_model"></select></div>
<button class="btn-small" id="settingsTeamAddPersonaBtn" style="margin-top:8px">+ New Persona</button>
</div>
{{/* Knowledge */}}

View File

@@ -142,6 +142,13 @@
<div id="userPersonaList"><div class="settings-placeholder">Loading personas…</div></div>
{{else if eq .Section "models"}}
<div id="userModelList"><div class="settings-placeholder">Loading models…</div></div>
{{else if eq .Section "roles"}}
<div id="userRolesDisabled" class="settings-section" style="display:none;">
<p style="color:var(--text-2);font-size:13px;">Add a personal provider first to configure model role overrides.</p>
</div>
<div id="userRolesConfig"></div>
{{else if eq .Section "usage"}}
<div id="myUsageTotals"></div>
{{else if eq .Section "teams"}}
<div id="settingsDynamic"><div class="settings-placeholder">Loading teams…</div></div>
{{else}}<div class="settings-placeholder" id="settingsDynamic">Loading…</div>
@@ -166,7 +173,7 @@
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/notification-prefs.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/channel-models.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}">
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', async () => {
const section = document.getElementById('settingsSection')?.dataset.section;
if (!section) return;
@@ -241,6 +248,22 @@
notifications: () => typeof NotifPrefs !== 'undefined' && NotifPrefs.load?.(),
teams: () => typeof UI !== 'undefined' && UI.loadTeamsSettings?.(),
};
// Populate App.policies and App.models from API.
// On chat surface, app.js does this. On settings surface, we must do it here.
try {
const pubData = await API.getPublicSettings();
App.policies = pubData.policies || {};
} catch (_) { App.policies = App.policies || {}; }
if (typeof fetchModels === 'function') await fetchModels();
// Wire up interactive handlers (BYOK provider form, model visibility, etc.)
if (typeof _initSettingsListeners === 'function') _initSettingsListeners();
// Show/hide BYOK and persona features based on policies
if (typeof UI !== 'undefined') {
UI.checkUserProvidersAllowed?.();
UI.checkUserPersonasAllowed?.();
}
if (dynamicSections[section]) dynamicSections[section]();
});
</script>

View File

@@ -46,7 +46,6 @@ func (b *UpdateBuilder) Set(col string, val interface{}) *UpdateBuilder {
// SetNull adds a col = NULL pair to the UPDATE.
func (b *UpdateBuilder) SetNull(col string) *UpdateBuilder {
b.argIdx++
b.sets = append(b.sets, fmt.Sprintf("%s = NULL", col))
return b
}

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>`; }
},