Changeset 0.22.7 (#149)

This commit is contained in:
2026-03-04 10:44:42 +00:00
parent d8e0664fa3
commit 389e47b0f9
62 changed files with 6820 additions and 1476 deletions

View File

@@ -15,8 +15,8 @@ import (
//
// Tier | enabled | team | disabled
// ----------+----------------+----------------------+---------
// Global | All users | Team admin → presets | Hidden
// Team | Team members | Team admin → presets | Hidden
// Global | All users | Team admin → personas | Hidden
// Team | Team members | Team admin → personas | Hidden
// Personal | Owner direct | N/A | Hidden
//
// Sources aggregated:
@@ -175,7 +175,7 @@ func ModelsForUser(ctx context.Context, stores store.Stores, userID string) ([]m
}
}
// Fallback: look up any provider's catalog entry for this model
// (covers auto-resolve presets where provider_config_id is NULL)
// (covers auto-resolve personas where provider_config_id is NULL)
if catalogCaps == nil {
if entry, err := stores.Catalog.GetByModelIDAny(ctx, p.BaseModelID); err == nil {
catalogCaps = &entry.Capabilities
@@ -209,12 +209,11 @@ func ModelsForUser(ctx context.Context, stores store.Stores, userID string) ([]m
ProviderName: provName,
ProviderType: provType,
Capabilities: caps,
IsPreset: true,
PresetID: p.ID,
PresetScope: p.Scope,
PresetAvatar: p.Avatar,
PresetTeamName: teamName(p, stores, ctx),
IsPersona: true,
PersonaID: p.ID,
PersonaScope: p.Scope,
PersonaAvatar: p.Avatar,
PersonaTeamName: teamName(p, stores, ctx),
Description: p.Description,
Icon: p.Icon,
Avatar: p.Avatar,
@@ -245,7 +244,7 @@ func ResolveForPersona(ctx context.Context, stores store.Stores, persona *models
catalogCaps = &entry.Capabilities
}
}
// Fallback: any provider's catalog entry (auto-resolve presets)
// Fallback: any provider's catalog entry (auto-resolve personas)
if catalogCaps == nil {
if entry, err := stores.Catalog.GetByModelIDAny(ctx, persona.BaseModelID); err == nil {
catalogCaps = &entry.Capabilities

View File

@@ -164,10 +164,10 @@ func bilinearMix(c00, c10, c01, c11 color.Color, xf, yf float64) color.Color {
}
}
// ── Preset Avatar Upload ────────────────────
// POST /api/v1/presets/:id/avatar (user) or /api/v1/admin/presets/:id/avatar (admin)
func UploadPresetAvatar(c *gin.Context) {
presetID := c.Param("id")
// ── Persona Avatar Upload ────────────────────
// POST /api/v1/personas/:id/avatar (user) or /api/v1/admin/personas/:id/avatar (admin)
func UploadPersonaAvatar(c *gin.Context) {
personaID := c.Param("id")
var req uploadAvatarRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -208,7 +208,7 @@ func UploadPresetAvatar(c *gin.Context) {
result, err := database.DB.Exec(
database.Q(`UPDATE personas SET avatar = $1, updated_at = NOW() WHERE id = $2`),
dataURI, presetID,
dataURI, personaID,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save avatar"})
@@ -216,20 +216,20 @@ func UploadPresetAvatar(c *gin.Context) {
}
rows, _ := result.RowsAffected()
if rows == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "preset not found"})
c.JSON(http.StatusNotFound, gin.H{"error": "persona not found"})
return
}
c.JSON(http.StatusOK, gin.H{"avatar": dataURI})
}
// DeletePresetAvatar clears a preset's avatar.
func DeletePresetAvatar(c *gin.Context) {
presetID := c.Param("id")
// DeletePersonaAvatar clears a persona's avatar.
func DeletePersonaAvatar(c *gin.Context) {
personaID := c.Param("id")
result, err := database.DB.Exec(
database.Q(`UPDATE personas SET avatar = '', updated_at = NOW() WHERE id = $1`),
presetID,
personaID,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to remove avatar"})
@@ -237,7 +237,7 @@ func DeletePresetAvatar(c *gin.Context) {
}
rows, _ := result.RowsAffected()
if rows == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "preset not found"})
c.JSON(http.StatusNotFound, gin.H{"error": "persona not found"})
return
}

View File

@@ -23,7 +23,7 @@ type createChannelRequest struct {
Description string `json:"description,omitempty"`
Model string `json:"model,omitempty"`
SystemPrompt string `json:"system_prompt,omitempty"`
APIConfigID *string `json:"provider_config_id,omitempty"`
ProviderConfigID *string `json:"provider_config_id,omitempty"`
Folder string `json:"folder,omitempty"`
Tags []string `json:"tags,omitempty"`
}
@@ -33,7 +33,7 @@ type updateChannelRequest struct {
Description *string `json:"description,omitempty"`
Model *string `json:"model,omitempty"`
SystemPrompt *string `json:"system_prompt,omitempty"`
APIConfigID *string `json:"provider_config_id,omitempty"`
ProviderConfigID *string `json:"provider_config_id,omitempty"`
IsArchived *bool `json:"is_archived,omitempty"`
IsPinned *bool `json:"is_pinned,omitempty"`
Folder *string `json:"folder,omitempty"`
@@ -49,7 +49,7 @@ type channelResponse struct {
Type string `json:"type"`
Description *string `json:"description"`
Model *string `json:"model"`
APIConfigID *string `json:"provider_config_id"`
ProviderConfigID *string `json:"provider_config_id"`
SystemPrompt *string `json:"system_prompt"`
IsArchived bool `json:"is_archived"`
IsPinned bool `json:"is_pinned"`
@@ -231,7 +231,7 @@ func (h *ChannelHandler) ListChannels(c *gin.Context) {
var ch channelResponse
var tags []string
err := rows.Scan(
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.APIConfigID,
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.ProviderConfigID,
&ch.SystemPrompt, &ch.IsArchived, &ch.IsPinned, &ch.Folder, &ch.ProjectID, &ch.WorkspaceID,
scanTags(&tags), scanJSON(&ch.Settings),
&ch.MessageCount, &ch.CreatedAt, &ch.UpdatedAt,
@@ -288,7 +288,7 @@ func (h *ChannelHandler) CreateChannel(c *gin.Context) {
system_prompt, provider_config_id, folder, tags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
id, userID, req.Title, channelType, req.Description, req.Model,
req.SystemPrompt, req.APIConfigID, req.Folder, writeTagsArg(req.Tags),
req.SystemPrompt, req.ProviderConfigID, req.Folder, writeTagsArg(req.Tags),
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create channel"})
@@ -301,7 +301,7 @@ func (h *ChannelHandler) CreateChannel(c *gin.Context) {
tags, settings,
created_at, updated_at
FROM channels WHERE id = ?`, id).Scan(
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.APIConfigID,
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.ProviderConfigID,
&ch.SystemPrompt, &ch.IsArchived, &ch.IsPinned, &ch.Folder, &ch.ProjectID, &ch.WorkspaceID,
scanTags(&tags), scanJSON(&ch.Settings), &ch.CreatedAt, &ch.UpdatedAt,
)
@@ -315,10 +315,10 @@ func (h *ChannelHandler) CreateChannel(c *gin.Context) {
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, user_id, title, type, description, model, provider_config_id, system_prompt,
is_archived, is_pinned, folder, project_id, workspace_id, tags, settings, created_at, updated_at
`, userID, req.Title, channelType, req.Description, req.Model, req.SystemPrompt, req.APIConfigID,
`, userID, req.Title, channelType, req.Description, req.Model, req.SystemPrompt, req.ProviderConfigID,
req.Folder, pq.Array(req.Tags),
).Scan(
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.APIConfigID,
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.ProviderConfigID,
&ch.SystemPrompt, &ch.IsArchived, &ch.IsPinned, &ch.Folder, &ch.ProjectID, &ch.WorkspaceID,
pq.Array(&tags), scanJSON(&ch.Settings), &ch.CreatedAt, &ch.UpdatedAt,
)
@@ -356,13 +356,13 @@ func (h *ChannelHandler) CreateChannel(c *gin.Context) {
INSERT INTO channel_models (id, channel_id, model_id, provider_config_id, is_default)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT DO NOTHING
`, store.NewID(), ch.ID, req.Model, req.APIConfigID)
`, store.NewID(), ch.ID, req.Model, req.ProviderConfigID)
} else {
_, _ = database.DB.Exec(`
INSERT INTO channel_models (channel_id, model_id, provider_config_id, is_default)
VALUES ($1, $2, $3, true)
ON CONFLICT DO NOTHING
`, ch.ID, req.Model, req.APIConfigID)
`, ch.ID, req.Model, req.ProviderConfigID)
}
}
@@ -389,7 +389,7 @@ func (h *ChannelHandler) GetChannel(c *gin.Context) {
) mc ON mc.channel_id = c.id
WHERE c.id = $1 AND c.user_id = $2
`), channelID, userID).Scan(
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.APIConfigID,
&ch.ID, &ch.UserID, &ch.Title, &ch.Type, &ch.Description, &ch.Model, &ch.ProviderConfigID,
&ch.SystemPrompt, &ch.IsArchived, &ch.IsPinned, &ch.Folder, &ch.ProjectID, &ch.WorkspaceID,
scanTags(&tags), scanJSON(&ch.Settings),
&ch.MessageCount, &ch.CreatedAt, &ch.UpdatedAt,
@@ -462,8 +462,8 @@ func (h *ChannelHandler) UpdateChannel(c *gin.Context) {
if req.SystemPrompt != nil {
addClause("system_prompt", *req.SystemPrompt)
}
if req.APIConfigID != nil {
addClause("provider_config_id", *req.APIConfigID)
if req.ProviderConfigID != nil {
addClause("provider_config_id", *req.ProviderConfigID)
}
if req.IsArchived != nil {
addClause("is_archived", *req.IsArchived)

View File

@@ -32,12 +32,11 @@ import (
// ── Request Types ───────────────────────────
type completionRequest struct {
ChannelID string `json:"channel_id"` // preferred; validated manually below
ChatID string `json:"chat_id"` // deprecated alias — maps to channel_id
Content string `json:"content" binding:"required"`
Model string `json:"model,omitempty"`
PresetID string `json:"preset_id,omitempty"` // if set, unwraps preset → base model + config
APIConfigID string `json:"provider_config_id,omitempty"`
ChannelID string `json:"channel_id"`
Content string `json:"content" binding:"required"`
Model string `json:"model,omitempty"`
PersonaID string `json:"persona_id,omitempty"`
ProviderConfigID string `json:"provider_config_id,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
@@ -194,11 +193,7 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
return
}
// Support chat_id as alias during frontend transition
channelID := req.ChannelID
if channelID == "" {
channelID = req.ChatID
}
if channelID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "channel_id is required"})
return
@@ -211,60 +206,60 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
return
}
// ── Preset unwrap: preset overrides defaults, explicit request fields win ──
var presetSystemPrompt string
// ── Persona unwrap: persona overrides defaults, explicit request fields win ──
var personaSystemPrompt string
var personaID string // tracks active persona for KB scoping
var presetThinkingBudget *int // persona-level thinking budget for hook injection (v0.22.1)
if req.PresetID != "" {
preset := ResolvePreset(h.stores, req.PresetID, userID)
if preset == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "preset not found or not accessible"})
var personaThinkingBudget *int // persona-level thinking budget for hook injection (v0.22.1)
if req.PersonaID != "" {
persona := ResolvePersona(h.stores, req.PersonaID, userID)
if persona == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "persona not found or not accessible"})
return
}
personaID = preset.ID
// Preset provides defaults; explicit request fields take priority
personaID = persona.ID
// Persona provides defaults; explicit request fields take priority
if req.Model == "" {
req.Model = preset.BaseModelID
req.Model = persona.BaseModelID
}
if req.APIConfigID == "" && preset.ProviderConfigID != nil {
req.APIConfigID = *preset.ProviderConfigID
if req.ProviderConfigID == "" && persona.ProviderConfigID != nil {
req.ProviderConfigID = *persona.ProviderConfigID
}
if req.Temperature == nil && preset.Temperature != nil {
req.Temperature = preset.Temperature
if req.Temperature == nil && persona.Temperature != nil {
req.Temperature = persona.Temperature
}
if req.MaxTokens == 0 && preset.MaxTokens != nil {
req.MaxTokens = *preset.MaxTokens
if req.MaxTokens == 0 && persona.MaxTokens != nil {
req.MaxTokens = *persona.MaxTokens
}
if preset.SystemPrompt != "" {
presetSystemPrompt = preset.SystemPrompt
if persona.SystemPrompt != "" {
personaSystemPrompt = persona.SystemPrompt
}
presetThinkingBudget = preset.ThinkingBudget
personaThinkingBudget = persona.ThinkingBudget
}
// ── Project persona fallback (v0.19.2): if no explicit preset, check project ──
if req.PresetID == "" && h.stores.Projects != nil {
// ── Project persona fallback (v0.19.2): if no explicit persona, check project ──
if req.PersonaID == "" && h.stores.Projects != nil {
projID, _ := h.stores.Projects.GetProjectIDForChannel(context.Background(), channelID)
if projID != "" {
if proj, err := h.stores.Projects.GetByID(context.Background(), projID); err == nil {
if pid, ok := proj.Settings["persona_id"].(string); ok && pid != "" {
if preset := ResolvePreset(h.stores, pid, userID); preset != nil {
personaID = preset.ID
if persona := ResolvePersona(h.stores, pid, userID); persona != nil {
personaID = persona.ID
if req.Model == "" {
req.Model = preset.BaseModelID
req.Model = persona.BaseModelID
}
if req.APIConfigID == "" && preset.ProviderConfigID != nil {
req.APIConfigID = *preset.ProviderConfigID
if req.ProviderConfigID == "" && persona.ProviderConfigID != nil {
req.ProviderConfigID = *persona.ProviderConfigID
}
if req.Temperature == nil && preset.Temperature != nil {
req.Temperature = preset.Temperature
if req.Temperature == nil && persona.Temperature != nil {
req.Temperature = persona.Temperature
}
if req.MaxTokens == 0 && preset.MaxTokens != nil {
req.MaxTokens = *preset.MaxTokens
if req.MaxTokens == 0 && persona.MaxTokens != nil {
req.MaxTokens = *persona.MaxTokens
}
if preset.SystemPrompt != "" {
presetSystemPrompt = preset.SystemPrompt
if persona.SystemPrompt != "" {
personaSystemPrompt = persona.SystemPrompt
}
presetThinkingBudget = preset.ThinkingBudget
personaThinkingBudget = persona.ThinkingBudget
}
}
}
@@ -287,7 +282,7 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
routingDecision = dec
if winConfigID != configID {
// Routing selected a different provider — reload its credentials
req.APIConfigID = winConfigID
req.ProviderConfigID = winConfigID
providerCfg2, providerID2, model2, configID2, providerScope2, err := h.resolveConfig(userID, channelID, req)
if err == nil {
providerCfg = providerCfg2
@@ -307,12 +302,12 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
// ── Inject persona-level thinking budget into provider settings (v0.22.1) ──
// When a persona specifies a thinking budget, promote it into provider
// settings so hooks can activate extended thinking automatically.
if presetThinkingBudget != nil && *presetThinkingBudget > 0 {
if personaThinkingBudget != nil && *personaThinkingBudget > 0 {
if providerCfg.Settings == nil {
providerCfg.Settings = make(map[string]interface{})
}
providerCfg.Settings["extended_thinking"] = true
providerCfg.Settings["thinking_budget"] = *presetThinkingBudget
providerCfg.Settings["thinking_budget"] = *personaThinkingBudget
}
// ── Team policy: require_private_providers ──
@@ -337,7 +332,7 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
}
// Load conversation history
messages, err := h.loadConversation(channelID, userID, presetSystemPrompt, personaID)
messages, err := h.loadConversation(channelID, userID, personaSystemPrompt, personaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load conversation"})
return
@@ -396,7 +391,7 @@ func (h *CompletionHandler) Complete(c *gin.Context) {
parsed := mentions.Parse(req.Content, roster)
targets := mentions.ResolvedModels(parsed)
if len(targets) > 1 {
h.multiModelStream(c, targets, messages, channelID, userID, personaID, presetSystemPrompt, workspaceID, req)
h.multiModelStream(c, targets, messages, channelID, userID, personaID, personaSystemPrompt, workspaceID, req)
return
}
}
@@ -449,7 +444,7 @@ func (h *CompletionHandler) multiModelStream(
c *gin.Context,
targets []models.ChannelModel,
messages []providers.Message,
channelID, userID, personaID, presetSystemPrompt, workspaceID string,
channelID, userID, personaID, personaSystemPrompt, workspaceID string,
req completionRequest,
) {
// Set SSE headers once for the entire multi-model stream
@@ -485,7 +480,7 @@ func (h *CompletionHandler) multiModelStream(
targetReq := req
targetReq.Model = target.ModelID
if target.ProviderConfigID != "" {
targetReq.APIConfigID = target.ProviderConfigID
targetReq.ProviderConfigID = target.ProviderConfigID
}
providerCfg, providerID, model, configID, providerScope, err := h.resolveConfig(userID, channelID, targetReq)
@@ -998,8 +993,8 @@ func (h *CompletionHandler) resolveConfig(userID string, channelID string, req c
var configID string
// 1. Explicit config from request
if req.APIConfigID != "" {
configID = req.APIConfigID
if req.ProviderConfigID != "" {
configID = req.ProviderConfigID
}
// 2. Config from channel
@@ -1115,7 +1110,7 @@ func (h *CompletionHandler) resolveConfig(userID string, channelID string, req c
//
// Summary-aware: if the path contains a summary node (metadata.type = "summary"),
// messages before it are replaced by the summary content as a system message.
func (h *CompletionHandler) loadConversation(channelID, userID, presetSystemPrompt, personaID string) ([]providers.Message, error) {
func (h *CompletionHandler) loadConversation(channelID, userID, personaSystemPrompt, personaID string) ([]providers.Message, error) {
messages := make([]providers.Message, 0)
// ── Admin system prompt (always injected first, no opt out) ──
@@ -1129,17 +1124,17 @@ func (h *CompletionHandler) loadConversation(channelID, userID, presetSystemProm
}
}
// ── User/preset system prompt (appended after admin prompt) ──
// ── User/persona system prompt (appended after admin prompt) ──
var systemPrompt *string
_ = database.DB.QueryRow(
database.Q(`SELECT system_prompt FROM channels WHERE id = $1`), channelID,
).Scan(&systemPrompt)
// Preset system prompt takes priority; channel system prompt is fallback
if presetSystemPrompt != "" {
// Persona system prompt takes priority; channel system prompt is fallback
if personaSystemPrompt != "" {
messages = append(messages, providers.Message{
Role: "system",
Content: presetSystemPrompt,
Content: personaSystemPrompt,
})
} else if systemPrompt != nil && *systemPrompt != "" {
messages = append(messages, providers.Message{

View File

@@ -200,12 +200,12 @@ func setupHarness(t *testing.T) *testHarness {
settings := NewSettingsHandler(nil)
protected.GET("/profile", settings.GetProfile)
// Presets
presets := NewPersonaHandler(stores)
protected.GET("/presets", presets.ListUserPersonas)
protected.POST("/presets", presets.CreateUserPersona)
protected.GET("/presets/:id/knowledge-bases", presets.GetPersonaKBs) // v0.17.0
protected.PUT("/presets/:id/knowledge-bases", presets.SetPersonaKBs) // v0.17.0
// Personas
personas := NewPersonaHandler(stores)
protected.GET("/personas", personas.ListUserPersonas)
protected.POST("/personas", personas.CreateUserPersona)
protected.GET("/personas/:id/knowledge-bases", personas.GetPersonaKBs) // v0.17.0
protected.PUT("/personas/:id/knowledge-bases", personas.SetPersonaKBs) // v0.17.0
// Notes
notes := NewNoteHandler(stores)
@@ -283,10 +283,10 @@ func setupHarness(t *testing.T) *testHarness {
admin.GET("/teams/:id", teams.GetTeam)
admin.GET("/teams/:id/members", teams.ListMembers)
admin.POST("/teams/:id/members", teams.AddMember)
admin.GET("/presets", presets.ListAdminPersonas)
admin.POST("/presets", presets.CreateAdminPersona)
admin.GET("/presets/:id/knowledge-bases", presets.GetPersonaKBs) // v0.17.0
admin.PUT("/presets/:id/knowledge-bases", presets.SetPersonaKBs) // v0.17.0
admin.GET("/personas", personas.ListAdminPersonas)
admin.POST("/personas", personas.CreateAdminPersona)
admin.GET("/personas/:id/knowledge-bases", personas.GetPersonaKBs) // v0.17.0
admin.PUT("/personas/:id/knowledge-bases", personas.SetPersonaKBs) // v0.17.0
// Admin groups (v0.16.0)
groupAdm := NewGroupHandler(stores)
@@ -802,14 +802,14 @@ func TestIntegration_TeamMemberManagement(t *testing.T) {
}
}
// ── 7. Presets (Policy Gated) ───────────────
// ── 7. Personas (Policy Gated) ───────────────
func TestIntegration_PresetCreation_PolicyGated(t *testing.T) {
func TestIntegration_PersonaCreation_PolicyGated(t *testing.T) {
h := setupHarness(t)
adminID, adminToken := h.createAdminUser("admin", "admin@test.com")
_ = adminID
// Create a provider config (presets need a valid model reference)
// Create a provider config (personas need a valid model reference)
w := h.request("POST", "/api/v1/admin/configs", adminToken, map[string]interface{}{
"name": "TestProvider", "provider": "openai",
"endpoint": "https://api.openai.com/v1", "api_key": "sk-test",
@@ -821,13 +821,13 @@ func TestIntegration_PresetCreation_PolicyGated(t *testing.T) {
// Ensure allow_user_personas = false
database.TestDB.Exec("INSERT INTO platform_policies (key, value) VALUES ('allow_user_personas', 'false') ON CONFLICT (key) DO UPDATE SET value = 'false'")
// Try to create a preset as admin (role=admin but policy says no)
w = h.request("POST", "/api/v1/presets", adminToken, map[string]interface{}{
"name": "My Preset", "base_model_id": "gpt-4o",
// Try to create a persona as admin (role=admin but policy says no)
w = h.request("POST", "/api/v1/personas", adminToken, map[string]interface{}{
"name": "My Persona", "base_model_id": "gpt-4o",
"provider_config_id": configID, "system_prompt": "You are helpful",
})
if w.Code != http.StatusForbidden {
t.Fatalf("preset create with policy=false: want 403, got %d: %s", w.Code, w.Body.String())
t.Fatalf("persona create with policy=false: want 403, got %d: %s", w.Code, w.Body.String())
}
// Enable the policy
@@ -835,18 +835,18 @@ func TestIntegration_PresetCreation_PolicyGated(t *testing.T) {
map[string]interface{}{"value": "true"})
// Now creation should succeed
w = h.request("POST", "/api/v1/presets", adminToken, map[string]interface{}{
"name": "My Preset", "base_model_id": "gpt-4o",
w = h.request("POST", "/api/v1/personas", adminToken, map[string]interface{}{
"name": "My Persona", "base_model_id": "gpt-4o",
"provider_config_id": configID, "system_prompt": "You are helpful",
})
if w.Code != http.StatusCreated {
t.Fatalf("preset create with policy=true: want 201, got %d: %s", w.Code, w.Body.String())
t.Fatalf("persona create with policy=true: want 201, got %d: %s", w.Code, w.Body.String())
}
// List presets
w = h.request("GET", "/api/v1/presets", adminToken, nil)
// List personas
w = h.request("GET", "/api/v1/personas", adminToken, nil)
if w.Code != http.StatusOK {
t.Fatalf("list presets: want 200, got %d: %s", w.Code, w.Body.String())
t.Fatalf("list personas: want 200, got %d: %s", w.Code, w.Body.String())
}
}
@@ -1105,7 +1105,7 @@ func TestIntegration_AdminModelFetchEnableUserSees(t *testing.T) {
t.Error("MISSING: model_id — required for composite ID")
}
// source required for preset detection
// source required for persona detection
if m["source"] == nil || m["source"] == "" {
t.Error("MISSING: source — frontend uses this to distinguish catalog vs persona")
}
@@ -2748,7 +2748,7 @@ func TestResourceGrants(t *testing.T) {
decode(w, &group)
// Create a persona (admin)
w = h.request("POST", "/api/v1/admin/presets", adminToken, map[string]interface{}{
w = h.request("POST", "/api/v1/admin/personas", adminToken, map[string]interface{}{
"name": "Test Bot",
"base_model_id": "test-model",
"scope": "global",
@@ -2840,11 +2840,11 @@ func TestGroupBasedPersonaAccess(t *testing.T) {
}
// ── User should NOT see team persona ──
w = h.request("GET", "/api/v1/presets", userToken, nil)
var presetsResp map[string]interface{}
decode(w, &presetsResp)
presets, _ := presetsResp["presets"].([]interface{})
for _, p := range presets {
w = h.request("GET", "/api/v1/personas", userToken, nil)
var personasResp map[string]interface{}
decode(w, &personasResp)
personas, _ := personasResp["personas"].([]interface{})
for _, p := range personas {
pm := p.(map[string]interface{})
if pm["id"] == personaID {
t.Fatalf("user should NOT see team persona without group access")
@@ -2872,14 +2872,14 @@ func TestGroupBasedPersonaAccess(t *testing.T) {
}
// ── User should NOW see team persona via group grant ──
w = h.request("GET", "/api/v1/presets", userToken, nil)
w = h.request("GET", "/api/v1/personas", userToken, nil)
if w.Code != http.StatusOK {
t.Fatalf("list presets: want 200, got %d: %s", w.Code, w.Body.String())
t.Fatalf("list personas: want 200, got %d: %s", w.Code, w.Body.String())
}
decode(w, &presetsResp)
presets, _ = presetsResp["presets"].([]interface{})
decode(w, &personasResp)
personas, _ = personasResp["personas"].([]interface{})
found := false
for _, p := range presets {
for _, p := range personas {
pm := p.(map[string]interface{})
if pm["id"] == personaID {
found = true
@@ -2887,16 +2887,16 @@ func TestGroupBasedPersonaAccess(t *testing.T) {
}
}
if !found {
t.Fatalf("user should see team persona after group grant, but didn't find it in %d presets (response: %s)", len(presets), w.Body.String())
t.Fatalf("user should see team persona after group grant, but didn't find it in %d personas (response: %s)", len(personas), w.Body.String())
}
// ── Remove user from group → should lose access ──
w = h.request("DELETE", fmt.Sprintf("/api/v1/admin/groups/%s/members/%s", group.ID, userID), adminToken, nil)
w = h.request("GET", "/api/v1/presets", userToken, nil)
decode(w, &presetsResp)
presets, _ = presetsResp["presets"].([]interface{})
for _, p := range presets {
w = h.request("GET", "/api/v1/personas", userToken, nil)
decode(w, &personasResp)
personas, _ = personasResp["personas"].([]interface{})
for _, p := range personas {
pm := p.(map[string]interface{})
if pm["id"] == personaID {
t.Fatalf("user should NOT see persona after group removal")
@@ -2915,7 +2915,7 @@ func TestIntegration_PersonaKB_Binding(t *testing.T) {
_, adminToken := h.createAdminUser("admin", "admin@test.com")
// 1. Create a global persona via admin API
w := h.request("POST", "/api/v1/admin/presets", adminToken, map[string]interface{}{
w := h.request("POST", "/api/v1/admin/personas", adminToken, map[string]interface{}{
"name": "KB Persona",
"base_model_id": "test-model",
"system_prompt": "You are a test persona.",
@@ -2941,7 +2941,7 @@ func TestIntegration_PersonaKB_Binding(t *testing.T) {
// 3. Bind KB to persona
w = h.request("PUT",
fmt.Sprintf("/api/v1/admin/presets/%s/knowledge-bases", personaID),
fmt.Sprintf("/api/v1/admin/personas/%s/knowledge-bases", personaID),
adminToken, map[string]interface{}{
"kb_ids": []string{kbID},
"auto_search": map[string]bool{kbID: true},
@@ -2952,7 +2952,7 @@ func TestIntegration_PersonaKB_Binding(t *testing.T) {
// 4. Read back bindings
w = h.request("GET",
fmt.Sprintf("/api/v1/admin/presets/%s/knowledge-bases", personaID),
fmt.Sprintf("/api/v1/admin/personas/%s/knowledge-bases", personaID),
adminToken, nil)
if w.Code != http.StatusOK {
t.Fatalf("get persona KBs: want 200, got %d: %s", w.Code, w.Body.String())
@@ -2973,7 +2973,7 @@ func TestIntegration_PersonaKB_Binding(t *testing.T) {
// 5. Unbind — send empty list
w = h.request("PUT",
fmt.Sprintf("/api/v1/admin/presets/%s/knowledge-bases", personaID),
fmt.Sprintf("/api/v1/admin/personas/%s/knowledge-bases", personaID),
adminToken, map[string]interface{}{
"kb_ids": []string{},
})
@@ -2983,7 +2983,7 @@ func TestIntegration_PersonaKB_Binding(t *testing.T) {
// 6. Verify empty
w = h.request("GET",
fmt.Sprintf("/api/v1/admin/presets/%s/knowledge-bases", personaID),
fmt.Sprintf("/api/v1/admin/personas/%s/knowledge-bases", personaID),
adminToken, nil)
if w.Code != http.StatusOK {
t.Fatalf("get empty persona KBs: want 200, got %d: %s", w.Code, w.Body.String())

View File

@@ -47,8 +47,8 @@ type editRequest struct {
type regenerateRequest struct {
Model string `json:"model,omitempty"`
PresetID string `json:"preset_id,omitempty"`
APIConfigID string `json:"provider_config_id,omitempty"`
PersonaID string `json:"persona_id,omitempty"`
ProviderConfigID string `json:"provider_config_id,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
DisabledTools []string `json:"disabled_tools,omitempty"`
@@ -417,34 +417,34 @@ func (h *MessageHandler) Regenerate(c *gin.Context) {
comp := NewCompletionHandler(h.vault, h.stores, h.hub, h.objStore, nil)
var presetSystemPrompt string
var personaSystemPrompt string
var personaID string
model := req.Model
apiConfigID := req.APIConfigID
providerConfigID := req.ProviderConfigID
temperature := req.Temperature
maxTokens := req.MaxTokens
if req.PresetID != "" {
preset := ResolvePreset(h.stores, req.PresetID, userID)
if preset == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "preset not found"})
if req.PersonaID != "" {
persona := ResolvePersona(h.stores, req.PersonaID, userID)
if persona == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "persona not found"})
return
}
personaID = preset.ID
personaID = persona.ID
if model == "" {
model = preset.BaseModelID
model = persona.BaseModelID
}
if apiConfigID == "" && preset.ProviderConfigID != nil {
apiConfigID = *preset.ProviderConfigID
if providerConfigID == "" && persona.ProviderConfigID != nil {
providerConfigID = *persona.ProviderConfigID
}
if temperature == nil && preset.Temperature != nil {
temperature = preset.Temperature
if temperature == nil && persona.Temperature != nil {
temperature = persona.Temperature
}
if maxTokens == 0 && preset.MaxTokens != nil {
maxTokens = *preset.MaxTokens
if maxTokens == 0 && persona.MaxTokens != nil {
maxTokens = *persona.MaxTokens
}
if preset.SystemPrompt != "" {
presetSystemPrompt = preset.SystemPrompt
if persona.SystemPrompt != "" {
personaSystemPrompt = persona.SystemPrompt
}
}
@@ -459,7 +459,7 @@ func (h *MessageHandler) Regenerate(c *gin.Context) {
providerCfg, providerID, model, configID, providerScope, err := comp.resolveConfig(userID, channelID, completionRequest{
Model: model,
APIConfigID: apiConfigID,
ProviderConfigID: providerConfigID,
})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
@@ -475,8 +475,8 @@ func (h *MessageHandler) Regenerate(c *gin.Context) {
// Build LLM message array
llmMessages := make([]providers.Message, 0, len(contextPath)+1)
if presetSystemPrompt != "" {
llmMessages = append(llmMessages, providers.Message{Role: "system", Content: presetSystemPrompt})
if personaSystemPrompt != "" {
llmMessages = append(llmMessages, providers.Message{Role: "system", Content: personaSystemPrompt})
} else {
var systemPrompt *string
_ = database.DB.QueryRow(database.Q(`SELECT system_prompt FROM channels WHERE id = $1`), channelID).Scan(&systemPrompt)

View File

@@ -30,7 +30,7 @@ func (h *PersonaHandler) ListUserPersonas(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{"personas": personas, "presets": personas})
c.JSON(http.StatusOK, gin.H{"personas": personas})
}
func (h *PersonaHandler) CreateUserPersona(c *gin.Context) {
@@ -121,7 +121,7 @@ func (h *PersonaHandler) ListTeamPersonas(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{"personas": personas, "presets": personas})
c.JSON(http.StatusOK, gin.H{"personas": personas})
}
func (h *PersonaHandler) CreateTeamPersona(c *gin.Context) {
@@ -167,7 +167,7 @@ func (h *PersonaHandler) ListAdminPersonas(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{"personas": personas, "presets": personas})
c.JSON(http.StatusOK, gin.H{"personas": personas})
}
func (h *PersonaHandler) CreateAdminPersona(c *gin.Context) {
@@ -253,18 +253,17 @@ func (r *personaRequest) toPersona() *models.Persona {
return p
}
// ResolvePreset loads a persona by ID and returns it if the user has access.
// ResolvePersona loads a persona by ID and returns it if the user has access.
// Returns nil if not found, inactive, or not accessible.
// Used by completion.go and messages.go for preset unwrapping.
func ResolvePreset(stores store.Stores, presetID, userID string) *models.Persona {
func ResolvePersona(stores store.Stores, personaID, userID string) *models.Persona {
ctx := context.Background()
p, err := stores.Personas.GetByID(ctx, presetID)
p, err := stores.Personas.GetByID(ctx, personaID)
if err != nil || !p.IsActive {
return nil
}
ok, err := stores.Personas.UserCanAccess(ctx, userID, presetID)
ok, err := stores.Personas.UserCanAccess(ctx, userID, personaID)
if err != nil || !ok {
return nil
}

View File

@@ -470,10 +470,10 @@ func (h *TeamHandler) MyTeams(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": teams})
}
// ── Team Models: Available for Presets ──────
// ── Team Models: Available for Personas ──────
// ListAvailableModels returns models with visibility 'enabled' or 'team'
// for team admins building presets. Requires RequireTeamAdmin middleware.
// for team admins building personas. Requires RequireTeamAdmin middleware.
// GET /api/v1/teams/:teamId/models
func (h *TeamHandler) ListAvailableModels(c *gin.Context) {
teamID := getTeamID(c)

View File

@@ -427,7 +427,6 @@ func main() {
modelH.SetHealthStore(healthStore)
}
protected.GET("/models/enabled", modelH.ListEnabledModels)
protected.GET("/models", modelH.ListEnabledModels) // alias
// Model Preferences
modelPrefs := handlers.NewModelPrefsHandler(stores)
@@ -449,16 +448,16 @@ func main() {
usage := handlers.NewUsageHandler(stores)
protected.GET("/usage", usage.PersonalUsage)
// Personas (replaces /presets)
// Personas
personas := handlers.NewPersonaHandler(stores)
protected.GET("/presets", personas.ListUserPersonas) // backward compat
protected.POST("/presets", personas.CreateUserPersona)
protected.PUT("/presets/:id", personas.UpdateUserPersona)
protected.DELETE("/presets/:id", personas.DeleteUserPersona)
protected.POST("/presets/:id/avatar", handlers.UploadPresetAvatar)
protected.DELETE("/presets/:id/avatar", handlers.DeletePresetAvatar)
protected.GET("/presets/:id/knowledge-bases", personas.GetPersonaKBs) // v0.17.0
protected.PUT("/presets/:id/knowledge-bases", personas.SetPersonaKBs) // v0.17.0
protected.GET("/personas", personas.ListUserPersonas)
protected.POST("/personas", personas.CreateUserPersona)
protected.PUT("/personas/:id", personas.UpdateUserPersona)
protected.DELETE("/personas/:id", personas.DeleteUserPersona)
protected.POST("/personas/:id/avatar", handlers.UploadPersonaAvatar)
protected.DELETE("/personas/:id/avatar", handlers.DeletePersonaAvatar)
protected.GET("/personas/:id/knowledge-bases", personas.GetPersonaKBs) // v0.17.0
protected.PUT("/personas/:id/knowledge-bases", personas.SetPersonaKBs) // v0.17.0
// Notes
notes := handlers.NewNoteHandler(stores)
@@ -634,11 +633,11 @@ func main() {
// Team personas
teamPersonas := handlers.NewPersonaHandler(stores)
teamScoped.GET("/presets", teamPersonas.ListTeamPersonas)
teamScoped.POST("/presets", teamPersonas.CreateTeamPersona)
teamScoped.DELETE("/presets/:id", teamPersonas.DeleteTeamPersona)
teamScoped.GET("/presets/:id/knowledge-bases", teamPersonas.GetPersonaKBs) // v0.17.0
teamScoped.PUT("/presets/:id/knowledge-bases", teamPersonas.SetPersonaKBs) // v0.17.0
teamScoped.GET("/personas", teamPersonas.ListTeamPersonas)
teamScoped.POST("/personas", teamPersonas.CreateTeamPersona)
teamScoped.DELETE("/personas/:id", teamPersonas.DeleteTeamPersona)
teamScoped.GET("/personas/:id/knowledge-bases", teamPersonas.GetPersonaKBs) // v0.17.0
teamScoped.PUT("/personas/:id/knowledge-bases", teamPersonas.SetPersonaKBs) // v0.17.0
// Team role overrides
teamRoles := handlers.NewRolesHandler(stores, roleResolver)
@@ -697,14 +696,14 @@ func main() {
// Personas (admin global)
personaAdm := handlers.NewPersonaHandler(stores)
admin.GET("/presets", personaAdm.ListAdminPersonas)
admin.POST("/presets", personaAdm.CreateAdminPersona)
admin.PUT("/presets/:id", personaAdm.UpdateAdminPersona)
admin.DELETE("/presets/:id", personaAdm.DeleteAdminPersona)
admin.POST("/presets/:id/avatar", handlers.UploadPresetAvatar)
admin.DELETE("/presets/:id/avatar", handlers.DeletePresetAvatar)
admin.GET("/presets/:id/knowledge-bases", personaAdm.GetPersonaKBs) // v0.17.0
admin.PUT("/presets/:id/knowledge-bases", personaAdm.SetPersonaKBs) // v0.17.0
admin.GET("/personas", personaAdm.ListAdminPersonas)
admin.POST("/personas", personaAdm.CreateAdminPersona)
admin.PUT("/personas/:id", personaAdm.UpdateAdminPersona)
admin.DELETE("/personas/:id", personaAdm.DeleteAdminPersona)
admin.POST("/personas/:id/avatar", handlers.UploadPersonaAvatar)
admin.DELETE("/personas/:id/avatar", handlers.DeletePersonaAvatar)
admin.GET("/personas/:id/knowledge-bases", personaAdm.GetPersonaKBs) // v0.17.0
admin.PUT("/personas/:id/knowledge-bases", personaAdm.SetPersonaKBs) // v0.17.0
// Admin memory review (v0.18.0)
adminMemH := handlers.NewMemoryHandler(stores)

View File

@@ -609,14 +609,13 @@ type UserModel struct {
Capabilities ModelCapabilities `json:"capabilities"`
// Preset fields — always emitted so frontend can branch on is_preset.
IsPreset bool `json:"is_preset"`
PresetID string `json:"preset_id,omitempty"`
PresetScope string `json:"preset_scope,omitempty"`
PresetAvatar string `json:"preset_avatar,omitempty"`
PresetTeamName string `json:"preset_team_name,omitempty"`
// Persona fields — always emitted so frontend can branch on is_persona.
IsPersona bool `json:"is_persona"`
PersonaID string `json:"persona_id,omitempty"`
PersonaScope string `json:"persona_scope,omitempty"`
PersonaAvatar string `json:"persona_avatar,omitempty"`
PersonaTeamName string `json:"persona_team_name,omitempty"`
PersonaID string `json:"persona_id,omitempty"`
Description string `json:"description,omitempty"`
Icon string `json:"icon,omitempty"`
Avatar string `json:"avatar,omitempty"`

View File

@@ -112,6 +112,11 @@ type NotesPageData struct {
// SettingsPageData is what the settings surface templates receive.
type SettingsPageData struct {
Section string `json:"section"`
// v0.22.7: Feature gates from admin config.
// These control which nav links/tabs are visible in the settings surface.
BYOKEnabled bool `json:"BYOKEnabled"`
UserPersonasEnabled bool `json:"UserPersonasEnabled"`
}
// ── Loader registration ──────────────────────
@@ -290,7 +295,7 @@ func sectionCategory(section string) string {
switch section {
case "users", "teams", "groups":
return "people"
case "providers", "models", "presets", "roles", "knowledgeBases", "memory":
case "providers", "models", "personas", "roles", "knowledgeBases", "memory":
return "ai"
case "health", "routing", "capabilities":
return "routing"
@@ -373,7 +378,6 @@ func (e *Engine) loadUsers(ctx context.Context, s store.Stores) []UserRow {
return out
}
// ── Editor loader ────────────────────────────
// Resolves workspace from URL param. The heavy lifting (file tree, CodeMirror)
// is done client-side by editor-mode.js.
@@ -400,13 +404,35 @@ func (e *Engine) notesLoader(c *gin.Context, s store.Stores) (any, error) {
}
// ── Settings loader ──────────────────────────
// Most settings sections are populated client-side by existing JS.
// Server just passes the section name for navigation highlighting.
// v0.22.7: Reads feature gates from GlobalConfig to control
// which nav links/tabs are visible (BYOK, User Personas).
func (e *Engine) settingsLoader(c *gin.Context, s store.Stores) (any, error) {
section := c.Param("section")
if section == "" {
section = "general"
}
return &SettingsPageData{Section: section}, nil
data := &SettingsPageData{Section: section}
// Read feature gates from admin config
if s.GlobalConfig != 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
}
}
}
return data, nil
}

View File

@@ -4,7 +4,7 @@
//
// templates/base.html — outer shell (banner + surface block + scripts)
// templates/login.html — standalone login page
// templates/components/*.html — reusable partials (model-select, team-select, etc.)
// templates/components/*.html — reusable partials (model-select, team-select, chat-pane, etc.)
// templates/surfaces/*.html — one per surface (chat, editor, notes, admin, etc.)
// templates/admin/*.html — admin sub-pages (roles, routing, providers, etc.)
package pages
@@ -52,15 +52,25 @@ type BannerConfig struct {
// PageData is passed to every template render.
type PageData struct {
Banner BannerConfig
Surface string // active surface ID
Section string // sub-section (for admin pages)
CSPNonce string
Banner BannerConfig
Surface string // active surface ID
Section string // sub-section (for admin pages)
CSPNonce string
BasePath string
Version string
Environment string
User *UserContext
Data any // surface-specific data from loader
User *UserContext
Data any // surface-specific data from loader
// v0.22.7: Theme + settings injection
Theme string // "dark", "light", or "" (= use default)
SurfaceSettings any // JSON-serialized to window.__SETTINGS__
// v0.22.7: Login/splash page fields
InstanceName string // branding: instance display name
LogoURL string // branding: custom logo URL
Tagline string // branding: tagline under instance name
RegistrationOpen bool // whether self-registration is enabled
}
// UserContext is the authenticated user's info available to templates.
@@ -138,6 +148,11 @@ func (e *Engine) Render(c *gin.Context, name string, data PageData) {
data.CSPNonce = generateNonce()
data.Banner = e.loadBanner()
// v0.22.7: Default theme if not set
if data.Theme == "" {
data.Theme = "dark"
}
e.mu.RLock()
tmpl := e.templates
e.mu.RUnlock()
@@ -186,8 +201,16 @@ func (e *Engine) RenderSurface(surfaceID string) gin.HandlerFunc {
// RenderLogin serves the standalone login page.
func (e *Engine) RenderLogin() gin.HandlerFunc {
return func(c *gin.Context) {
// v0.22.7: Populate splash/login fields from global config
instanceName, logoURL, tagline := e.loadBranding()
regOpen := e.isRegistrationOpen()
e.Render(c, "login.html", PageData{
Surface: "login",
Surface: "login",
InstanceName: instanceName,
LogoURL: logoURL,
Tagline: tagline,
RegistrationOpen: regOpen,
})
}
}
@@ -229,6 +252,43 @@ func (e *Engine) loadBanner() BannerConfig {
return b
}
// loadBranding reads instance branding from global settings.
func (e *Engine) loadBranding() (name, logoURL, tagline string) {
name = "Chat Switchboard" // default
if e.stores.GlobalConfig == nil {
return
}
raw, err := e.stores.GlobalConfig.Get(context.Background(), "branding")
if err != nil || raw == nil {
return
}
if v, ok := raw["instance_name"].(string); ok && v != "" {
name = v
}
if v, ok := raw["logo_url"].(string); ok {
logoURL = v
}
if v, ok := raw["tagline"].(string); ok {
tagline = v
}
return
}
// isRegistrationOpen checks if self-registration is enabled.
func (e *Engine) isRegistrationOpen() bool {
if e.stores.GlobalConfig == nil {
return false
}
raw, err := e.stores.GlobalConfig.Get(context.Background(), "registration")
if err != nil || raw == nil {
return false
}
if v, ok := raw["enabled"].(bool); ok {
return v
}
return false
}
// Version is injected at build time via ldflags.
var Version = "dev"

View File

@@ -3,7 +3,7 @@
{{define "admin-teams"}}
<div class="admin-page">
<h2>Teams</h2>
<p class="section-hint">Organize users into teams for scoped access to providers, presets, and policies.</p>
<p class="section-hint">Organize users into teams for scoped access to providers, personas, and policies.</p>
<div class="admin-toolbar">
<button class="btn-small btn-primary" onclick="Pages.showTeamForm()">+ Create Team</button>

View File

@@ -9,10 +9,7 @@
<link rel="icon" type="image/x-icon" href="{{.BasePath}}/favicon.ico?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/styles.css?v={{.Version}}">
{{if eq .Surface "chat"}}{{template "css-chat" .}}{{end}}
{{if eq .Surface "admin"}}{{template "css-admin" .}}{{end}}
{{if eq .Surface "editor"}}{{template "css-editor" .}}{{end}}
{{if eq .Surface "notes"}}{{template "css-notes" .}}{{end}}
{{if eq .Surface "settings"}}{{template "css-settings" .}}{{end}}
<style>
:root {
--banner-h: 28px;
@@ -20,13 +17,13 @@
--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-primary, #0e0e10); color: var(--text-primary, #e0e0e0); }
body { margin: 0; background: var(--bg); color: var(--text); }
.surface { height: var(--surface-h); overflow: hidden; }
.banner { flex-shrink: 0; }
</style>
<meta name="theme-color" content="#0e0e10">
</head>
<body data-surface="{{.Surface}}" data-base-path="{{.BasePath}}">
<body data-surface="{{.Surface}}" data-base-path="{{.BasePath}}" data-theme="{{or .Theme "dark"}}">
{{if .Banner.Visible}}
<div class="banner banner-top" style="background:{{.Banner.Background}};color:{{.Banner.Color}};height:var(--banner-h);line-height:var(--banner-h);text-align:center;font-size:12px;font-weight:600;overflow:hidden;">
{{.Banner.Text}}
@@ -59,9 +56,16 @@
window.__USER__ = {{.User | toJSON}};
</script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/app-state.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/api.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}">
// Hydrate auth tokens for all surfaces (chat surface also calls this in init)
API.loadTokens();
</script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/events.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-primitives.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-primitives-additions.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-core.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/pages.js?v={{.Version}}"></script>
{{if eq .Surface "chat"}}{{template "scripts-chat" .}}{{end}}

View File

@@ -0,0 +1,23 @@
{{/*
Chat Pane Component - reusable chat scaffold.
Usage: {{template "chat-pane" dict "ID" "main"}}
Creates mount points: {ID}ChatMessages, {ID}ChatInput, {ID}SendBtn, {ID}ModelSel
ChatPane.create() in chat-pane.js binds to these IDs.
*/}}
{{define "chat-pane"}}
<div class="chat-pane" id="{{.ID}}ChatPane">
<div class="chat-pane-messages" id="{{.ID}}ChatMessages"></div>
<div class="chat-pane-input-bar">
<div class="chat-pane-model-sel" id="{{.ID}}ModelSel"></div>
<div class="chat-pane-input-wrap">
<div class="chat-pane-input" id="{{.ID}}ChatInput"></div>
<button class="chat-pane-send" id="{{.ID}}SendBtn" title="Send">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
</svg>
</button>
</div>
<div class="chat-pane-toolbar" id="{{.ID}}Toolbar"></div>
</div>
</div>
{{end}}

View File

@@ -4,68 +4,342 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login — Chat Switchboard</title>
<title>Chat Switchboard</title>
<link rel="icon" type="image/svg+xml" href="{{.BasePath}}/favicon.svg?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/styles.css?v={{.Version}}">
<link rel="icon" type="image/x-icon" href="{{.BasePath}}/favicon.ico?v={{.Version}}">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600;9..40,700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0e0e10; --bg-surface: #18181b; --bg-raised: #222227;
--border: #2e2e35; --border-light: #3a3a42;
--text: #e8e8ed; --text-2: #9898a8; --text-3: #6b6b7b;
--accent: #6c9fff; --accent-hover: #84b0ff; --accent-dim: rgba(108,159,255,0.12);
--purple: #a78bfa; --purple-dim: rgba(167,139,250,0.10);
--danger: #ef4444; --success: #22c55e;
--input-bg: #1a1a1f;
--grid-line: rgba(108,159,255,0.04);
--glow1: rgba(108,159,255,0.06); --glow2: rgba(167,139,250,0.05);
--orb: rgba(167,139,250,0.08);
--font: 'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--mono: 'JetBrains Mono', monospace;
--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}};
}
body { margin: 0; background: var(--bg-primary, #0e0e10); color: var(--text-primary, #e0e0e0); }
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: var(--font); background: var(--bg); color: var(--text); overflow: hidden; }
.login-shell { display: flex; flex-direction: column; height: 100vh; }
.login-main { display: flex; flex: 1; min-height: 0; }
/* ── Hero Panel (left) ─────────────────── */
.hero {
flex: 1; display: flex; flex-direction: column; justify-content: center;
padding: 4rem 3.5rem; position: relative; overflow: hidden;
background:
radial-gradient(ellipse 80% 60% at 30% 40%, var(--glow1), transparent),
radial-gradient(ellipse 60% 50% at 70% 70%, var(--glow2), transparent),
var(--bg);
}
.hero-grid {
position: absolute; inset: -50%;
background-image:
linear-gradient(var(--grid-line) 1px, transparent 1px),
linear-gradient(90deg, var(--grid-line) 1px, transparent 1px);
background-size: 48px 48px;
animation: gridDrift 30s linear infinite;
pointer-events: none;
}
.hero-orb {
position: absolute; width: 320px; height: 320px; bottom: -80px; right: -60px;
background: radial-gradient(circle, var(--orb), transparent 70%);
border-radius: 50%; pointer-events: none;
}
.hero-content { position: relative; z-index: 1; max-width: 520px; }
.hero-brand { display: flex; align-items: center; gap: 14px; margin-bottom: 1.5rem; }
.hero-brand-icon { font-size: 40px; line-height: 1; }
.hero-brand-text { font-size: 1.6rem; font-weight: 700; letter-spacing: -0.03em; line-height: 1.1; }
.hero-brand-text .hl { color: var(--accent); }
.hero h1 {
font-size: 2.4rem; font-weight: 700; line-height: 1.15;
letter-spacing: -0.03em; margin-bottom: 1rem;
background: linear-gradient(135deg, var(--text) 0%, var(--text-2) 100%);
-webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
}
.hero-sub {
font-size: 1.05rem; color: var(--text-2); line-height: 1.6;
margin-bottom: 2.5rem; max-width: 440px;
}
.hero-pills { display: flex; flex-wrap: wrap; gap: 10px; }
.hero-pill {
display: inline-flex; align-items: center; gap: 7px;
padding: 7px 14px; background: var(--bg-surface);
border-radius: 100px; font-size: 0.8rem; font-weight: 500;
transition: all 0.15s;
}
.hero-pill.ac { border: 1px solid rgba(108,159,255,0.2); color: var(--accent); }
.hero-pill.pu { border: 1px solid rgba(167,139,250,0.2); color: var(--purple); }
.hero-pill-icon { font-size: 0.95rem; line-height: 1; }
.hero-version {
margin-top: 3rem; font-size: 0.72rem; font-family: var(--mono);
color: var(--text-3); letter-spacing: 0.04em;
}
/* ── Auth Panel (right) ────────────────── */
.auth-panel {
width: 440px; flex-shrink: 0; display: flex; align-items: center;
justify-content: center; padding: 2rem; background: var(--bg-surface);
border-left: 1px solid var(--border); overflow-y: auto;
}
.auth-inner { width: 100%; max-width: 340px; }
.auth-heading { margin-bottom: 2rem; }
.auth-heading h2 { font-size: 1.25rem; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 4px; }
.auth-heading p { font-size: 0.85rem; color: var(--text-3); }
.auth-tabs { display: flex; margin-bottom: 1.5rem; border-bottom: 1px solid var(--border); }
.auth-tab {
flex: 1; background: none; border: none; border-bottom: 2px solid transparent;
color: var(--text-3); padding: 10px 0; cursor: pointer; font-family: var(--font);
font-size: 0.85rem; font-weight: 500; transition: color 0.15s;
}
.auth-tab.active { color: var(--accent); border-bottom-color: var(--accent); }
.auth-tab:hover { color: var(--text-2); }
.form-field { margin-bottom: 16px; }
.form-field label { display: block; font-size: 13px; font-weight: 500; color: var(--text-2); margin-bottom: 6px; }
.form-field input {
width: 100%; box-sizing: border-box; background: var(--input-bg);
border: 1px solid var(--border); color: var(--text);
padding: 10px 14px; border-radius: 10px; font-size: 14px; font-family: var(--font);
outline: none; transition: border-color 0.15s, box-shadow 0.15s;
}
.form-field input:focus {
border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-dim);
}
.auth-error { color: var(--danger); font-size: 0.78rem; margin: 0 0 0.5rem; }
.btn-login {
width: 100%; background: var(--accent); color: #fff; border: none;
padding: 10px 18px; font-size: 14px; border-radius: 10px; cursor: pointer;
font-family: var(--font); font-weight: 600; letter-spacing: -0.01em;
transition: all 0.18s; margin-top: 1.5rem;
}
.btn-login:hover { background: var(--accent-hover); }
.btn-login:disabled { opacity: 0.55; cursor: not-allowed; }
.auth-footer {
margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--border);
text-align: center;
}
.auth-footer p { font-size: 0.75rem; color: var(--text-3); line-height: 1.6; }
/* ── Banner ─────────────────────────────── */
.login-banner {
text-align: center; font-size: 11px; font-weight: 700;
letter-spacing: 1.2px; padding: 3px 0; text-transform: uppercase; flex-shrink: 0;
}
/* ── Animations ─────────────────────────── */
@keyframes gridDrift { to { transform: translate(48px, 48px); } }
@keyframes fadeUp { to { opacity: 1; transform: translateY(0); } }
.anim { opacity: 0; transform: translateY(12px); animation: fadeUp 0.5s ease forwards; }
.anim-1 { animation-delay: .05s; } .anim-2 { animation-delay: .12s; }
.anim-3 { animation-delay: .19s; } .anim-4 { animation-delay: .26s; }
.anim-5 { animation-delay: .33s; }
.anim-a1 { animation-delay: .15s; } .anim-a2 { animation-delay: .22s; }
.anim-a3 { animation-delay: .29s; }
/* ── Responsive ─────────────────────────── */
@media (max-width: 900px) {
.hero { display: none; }
.auth-panel { width: 100%; border-left: none; }
}
::-webkit-scrollbar { width: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { border-radius: 3px; background: var(--border); }
</style>
</head>
<body>
{{if .Banner.Visible}}
<div class="banner banner-top" style="background:{{.Banner.Background}};color:{{.Banner.Color}};height:var(--banner-h);line-height:var(--banner-h);text-align:center;font-size:12px;font-weight:600;">
{{.Banner.Text}}
</div>
{{end}}
<div class="login-shell">
<div style="display:flex;align-items:center;justify-content:center;height:calc(100vh - var(--banner-top-h) - var(--banner-bot-h));">
<div style="width:360px;padding:32px;">
<div style="text-align:center;margin-bottom:24px;">
<img src="{{.BasePath}}/favicon-32.png" alt="" style="width:48px;height:48px;margin-bottom:12px;">
<h1 style="font-size:20px;margin:0;">Chat Switchboard</h1>
</div>
<div id="loginError" class="form-error" style="display:none;margin-bottom:12px;color:#ef4444;font-size:13px;"></div>
<div style="margin-bottom:12px;">
<label for="loginUsername" style="display:block;font-size:12px;color:var(--text-secondary,#888);margin-bottom:4px;">Username</label>
<input type="text" id="loginUsername" autocomplete="username" autofocus
style="width:100%;padding:8px;border-radius:6px;border:1px solid var(--border,#2a2a2a);background:var(--bg-secondary,#1a1a1e);color:var(--text-primary,#e0e0e0);font-size:14px;box-sizing:border-box;">
</div>
<div style="margin-bottom:16px;">
<label for="loginPassword" style="display:block;font-size:12px;color:var(--text-secondary,#888);margin-bottom:4px;">Password</label>
<input type="password" id="loginPassword" autocomplete="current-password"
style="width:100%;padding:8px;border-radius:6px;border:1px solid var(--border,#2a2a2a);background:var(--bg-secondary,#1a1a1e);color:var(--text-primary,#e0e0e0);font-size:14px;box-sizing:border-box;">
</div>
<button id="loginBtn" onclick="Pages.doLogin()"
style="width:100%;padding:10px;border:none;border-radius:6px;background:var(--accent,#5865f2);color:white;font-size:14px;cursor:pointer;">
Log In
</button>
{{if .Banner.Visible}}
<div class="login-banner" style="background:{{.Banner.Background}};color:{{.Banner.Color}};">
{{.Banner.Text}}
</div>
</div>
{{end}}
<div class="login-main">
<!-- ═══ HERO (left) ═══ -->
<div class="hero">
<div class="hero-grid"></div>
<div class="hero-orb"></div>
<div class="hero-content">
<div class="hero-brand anim anim-1">
<span class="hero-brand-icon">&#x1F500;</span>
<span class="hero-brand-text">Chat <span class="hl">Switchboard</span></span>
</div>
<h1 class="anim anim-2">Your AI conversations,<br>your infrastructure</h1>
<p class="hero-sub anim anim-3">
Self-hosted multi-provider chat with team collaboration, BYOK privacy, and an extensible plugin system.
</p>
<div class="hero-pills anim anim-4">
<span class="hero-pill ac"><span class="hero-pill-icon">&#x1F916;</span> Multi-Provider AI</span>
<span class="hero-pill pu"><span class="hero-pill-icon">&#x1F511;</span> Bring Your Own Key</span>
<span class="hero-pill ac"><span class="hero-pill-icon">&#x1F465;</span> Teams &amp; Projects</span>
<span class="hero-pill pu"><span class="hero-pill-icon">&#x1F9E9;</span> Extensions</span>
<span class="hero-pill ac"><span class="hero-pill-icon">&#x1F50D;</span> Web Search Tools</span>
<span class="hero-pill pu"><span class="hero-pill-icon">&#x1F4DD;</span> Notes &amp; Memory</span>
</div>
<p class="hero-version anim anim-5">v{{.Version}} &middot; gobha.ai</p>
</div>
</div>
<!-- ═══ AUTH (right) ═══ -->
<div class="auth-panel">
<div class="auth-inner">
<div class="auth-heading anim anim-a1">
<h2 id="authTitle">Welcome back</h2>
<p id="authSubtitle">Sign in to your Switchboard instance</p>
</div>
<div class="auth-tabs anim anim-a2">
<button class="auth-tab active" id="tabLogin" onclick="_switchTab('login')">Log In</button>
<button class="auth-tab" id="tabRegister" onclick="_switchTab('register')">Register</button>
</div>
<!-- LOGIN FORM -->
<div id="loginForm" class="anim anim-a3">
<div class="form-field">
<label for="loginUsername">Username</label>
<input type="text" id="loginUsername" placeholder="Enter username" autocomplete="username" autofocus>
</div>
<div class="form-field">
<label for="loginPassword">Password</label>
<input type="password" id="loginPassword" placeholder="Enter password" autocomplete="current-password">
</div>
<p class="auth-error" id="loginError" style="display:none;"></p>
<button class="btn-login" id="loginBtn" onclick="Pages.doLogin()">Log In</button>
</div>
<!-- REGISTER FORM -->
<div id="registerForm" style="display:none;">
<div class="form-field">
<label for="regUsername">Username</label>
<input type="text" id="regUsername" placeholder="Choose a username" autocomplete="username">
</div>
<div class="form-field">
<label for="regEmail">Email</label>
<input type="email" id="regEmail" placeholder="you@example.com" autocomplete="email">
</div>
<div class="form-field">
<label for="regPassword">Password</label>
<input type="password" id="regPassword" placeholder="Min 8 characters" autocomplete="new-password">
</div>
<div class="form-field">
<label for="regConfirm">Confirm Password</label>
<input type="password" id="regConfirm" placeholder="Re-enter password" autocomplete="new-password">
</div>
<p class="auth-error" id="regError" style="display:none;"></p>
<button class="btn-login" id="regBtn" onclick="_doRegister()">Create Account</button>
</div>
<div class="auth-footer">
<p>Self-hosted instance &middot; Your data stays on your infrastructure</p>
</div>
</div>
</div>
</div>
{{if .Banner.Visible}}
<div class="login-banner" style="background:{{.Banner.Background}};color:{{.Banner.Color}};">
{{.Banner.Text}}
</div>
{{end}}
{{if .Banner.Visible}}
<div class="banner banner-bottom" style="background:{{.Banner.Background}};color:{{.Banner.Color}};height:var(--banner-h);line-height:var(--banner-h);text-align:center;font-size:12px;font-weight:600;">
{{.Banner.Text}}
</div>
{{end}}
<script>
window.__BASE__ = '{{.BasePath}}';
</script>
<script src="{{.BasePath}}/js/pages.js?v={{.Version}}"></script>
<script>
document.getElementById('loginPassword').addEventListener('keydown', (e) => {
function _switchTab(tab) {
document.getElementById('loginForm').style.display = tab === 'login' ? '' : 'none';
document.getElementById('registerForm').style.display = tab === 'register' ? '' : 'none';
document.getElementById('tabLogin').classList.toggle('active', tab === 'login');
document.getElementById('tabRegister').classList.toggle('active', tab === 'register');
document.getElementById('authTitle').textContent = tab === 'login' ? 'Welcome back' : 'Create account';
document.getElementById('authSubtitle').textContent = tab === 'login'
? 'Sign in to your Switchboard instance'
: 'Join your team on Switchboard';
document.getElementById('loginError').textContent = '';
document.getElementById('regError').textContent = '';
}
async function _doRegister() {
const username = document.getElementById('regUsername').value.trim();
const email = document.getElementById('regEmail').value.trim();
const password = document.getElementById('regPassword').value;
const confirm = document.getElementById('regConfirm').value;
const errEl = document.getElementById('regError');
const btn = document.getElementById('regBtn');
if (!username || !password) { errEl.textContent = 'Username and password are required'; return; }
if (password.length < 8) { errEl.textContent = 'Password must be at least 8 characters'; return; }
if (password !== confirm) { errEl.textContent = 'Passwords do not match'; return; }
errEl.textContent = '';
btn.disabled = true; btn.textContent = 'Creating account\u2026';
const base = window.__BASE__ || '';
try {
const resp = await fetch(base + '/api/v1/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, email, password }),
});
if (!resp.ok) {
const err = await resp.json().catch(() => ({}));
throw new Error(err.error || 'Registration failed');
}
const data = await resp.json();
if (data.pending) {
errEl.textContent = 'Account created — pending admin approval.';
errEl.style.color = 'var(--success)';
setTimeout(() => { errEl.style.color = ''; _switchTab('login'); }, 3000);
} else {
// Auto-login
const storageKey = base ? 'sb_auth_' + base.replace(/\//g, '') : 'sb_auth';
localStorage.setItem(storageKey, JSON.stringify({
accessToken: data.access_token, refreshToken: data.refresh_token, user: data.user,
}));
document.cookie = 'sb_token=' + data.access_token + '; path=/; max-age=900; SameSite=Strict';
window.location.href = base + '/';
}
} catch (e) {
errEl.textContent = e.message;
} finally {
btn.disabled = false; btn.textContent = 'Create Account';
}
}
// Enter key handlers
document.getElementById('loginPassword').addEventListener('keydown', e => {
if (e.key === 'Enter') Pages.doLogin();
});
document.getElementById('loginUsername').addEventListener('keydown', (e) => {
document.getElementById('loginUsername').addEventListener('keydown', e => {
if (e.key === 'Enter') document.getElementById('loginPassword').focus();
});
document.getElementById('regConfirm').addEventListener('keydown', e => {
if (e.key === 'Enter') _doRegister();
});
</script>
</body>
</html>

View File

@@ -1,193 +1,117 @@
{{/* Admin surface — full admin panel with category/section navigation.
Categories and sections mirror the SPA's ADMIN_SECTIONS structure.
Server-rendered sections: roles, routing, providers, models, teams, users, settings.
Hybrid sections: container div + JS loader fills content. */}}
{{/*
Admin surface — matches switchboard-prototype-admin.jsx.
Full-page layout: topbar (with category tabs) + left nav + content area.
JS (admin-handlers.js, ui-admin.js) populates dynamic sections.
*/}}
{{define "surface-admin"}}
<div class="admin-surface">
{{/* ── Category bar (top) ───────────────── */}}
<div class="admin-cat-bar">
{{$cat := .Data.Category}}
<button class="admin-cat{{if eq $cat "people"}} active{{end}}" onclick="window.location='{{.BasePath}}/admin/users'">People</button>
<button class="admin-cat{{if eq $cat "ai"}} active{{end}}" onclick="window.location='{{.BasePath}}/admin/providers'">AI</button>
<button class="admin-cat{{if eq $cat "routing"}} active{{end}}" onclick="window.location='{{.BasePath}}/admin/health'">Routing</button>
<button class="admin-cat{{if eq $cat "system"}} active{{end}}" onclick="window.location='{{.BasePath}}/admin/settings'">System</button>
<button class="admin-cat{{if eq $cat "monitoring"}} active{{end}}" onclick="window.location='{{.BasePath}}/admin/usage'">Monitoring</button>
<div class="admin-cat-spacer"></div>
<a href="{{.BasePath}}/" class="admin-back-link">← Chat</a>
<div class="surface-admin">
{{/* Top Bar */}}
<div class="admin-topbar">
<a href="{{.BasePath}}/" class="admin-topbar-back">
<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 to Chat
</a>
<div class="admin-topbar-sep"></div>
<span class="admin-topbar-title">&#x1F500; Administration</span>
{{/* Category tabs */}}
<div class="admin-category-tabs" id="adminCategoryTabs">
{{$section := .Section}}
{{$base := .BasePath}}
<a href="{{$base}}/admin/users" class="admin-cat-btn{{if eq $section "users"}} active{{else if eq $section "teams"}} active{{else if eq $section "groups"}} active{{end}}" data-cat="people">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
People
</a>
<a href="{{$base}}/admin/providers" class="admin-cat-btn{{if eq $section "providers"}} active{{else if eq $section "models"}} active{{else if eq $section "personas"}} active{{else if eq $section "roles"}} active{{else if eq $section "knowledgeBases"}} active{{else if eq $section "memory"}} active{{end}}" data-cat="ai">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="4" width="16" height="16" rx="2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/></svg>
AI
</a>
<a href="{{$base}}/admin/health" class="admin-cat-btn{{if eq $section "health"}} active{{else if eq $section "routing"}} active{{else if eq $section "capabilities"}} active{{end}}" data-cat="routing">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
Routing
</a>
<a href="{{$base}}/admin/settings" class="admin-cat-btn{{if eq $section "settings"}} active{{else if eq $section "storage"}} active{{else if eq $section "extensions"}} active{{end}}" data-cat="system">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09"/></svg>
System
</a>
<a href="{{$base}}/admin/usage" class="admin-cat-btn{{if eq $section "usage"}} active{{else if eq $section "audit"}} active{{else if eq $section "stats"}} active{{end}}" data-cat="monitoring">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
Monitoring
</a>
</div>
</div>
<div class="admin-body">
{{/* ── Section sidebar ──────────────── */}}
<nav class="admin-sidebar">
{{$section := .Section}}
{{$bp := .BasePath}}
{{if eq $cat "people"}}
<a href="{{$bp}}/admin/users" class="admin-nav-link{{if eq $section "users"}} active{{end}}">Users</a>
<a href="{{$bp}}/admin/teams" class="admin-nav-link{{if eq $section "teams"}} active{{end}}">Teams</a>
<a href="{{$bp}}/admin/groups" class="admin-nav-link{{if eq $section "groups"}} active{{end}}">Groups</a>
{{else if eq $cat "ai"}}
<a href="{{$bp}}/admin/providers" class="admin-nav-link{{if eq $section "providers"}} active{{end}}">Providers</a>
<a href="{{$bp}}/admin/models" class="admin-nav-link{{if eq $section "models"}} active{{end}}">Models</a>
<a href="{{$bp}}/admin/presets" class="admin-nav-link{{if eq $section "presets"}} active{{end}}">Personas</a>
<a href="{{$bp}}/admin/roles" class="admin-nav-link{{if eq $section "roles"}} active{{end}}">Roles</a>
<a href="{{$bp}}/admin/knowledgeBases" class="admin-nav-link{{if eq $section "knowledgeBases"}} active{{end}}">Knowledge</a>
<a href="{{$bp}}/admin/memory" class="admin-nav-link{{if eq $section "memory"}} active{{end}}">Memory</a>
{{else if eq $cat "routing"}}
<a href="{{$bp}}/admin/health" class="admin-nav-link{{if eq $section "health"}} active{{end}}">Health</a>
<a href="{{$bp}}/admin/routing" class="admin-nav-link{{if eq $section "routing"}} active{{end}}">Routing</a>
<a href="{{$bp}}/admin/capabilities" class="admin-nav-link{{if eq $section "capabilities"}} active{{end}}">Capabilities</a>
{{else if eq $cat "system"}}
<a href="{{$bp}}/admin/settings" class="admin-nav-link{{if eq $section "settings"}} active{{end}}">Settings</a>
<a href="{{$bp}}/admin/storage" class="admin-nav-link{{if eq $section "storage"}} active{{end}}">Storage</a>
<a href="{{$bp}}/admin/extensions" class="admin-nav-link{{if eq $section "extensions"}} active{{end}}">Extensions</a>
{{else if eq $cat "monitoring"}}
<a href="{{$bp}}/admin/usage" class="admin-nav-link{{if eq $section "usage"}} active{{end}}">Usage</a>
<a href="{{$bp}}/admin/audit" class="admin-nav-link{{if eq $section "audit"}} active{{end}}">Audit</a>
<a href="{{$bp}}/admin/stats" class="admin-nav-link{{if eq $section "stats"}} active{{end}}">Stats</a>
{{end}}
</nav>
{{/* 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>
{{/* ── Content area ─────────────────── */}}
{{/* Content Area */}}
<div class="admin-content">
{{if eq .Section "roles"}}{{template "admin-roles" .}}
{{else if eq .Section "routing"}}{{template "admin-routing" .}}
{{else if eq .Section "providers"}}{{template "admin-providers" .}}
{{else if eq .Section "models"}}{{template "admin-models" .}}
{{else if eq .Section "teams"}}{{template "admin-teams" .}}
{{else if eq .Section "users"}}{{template "admin-users" .}}
{{else if eq .Section "settings"}}{{template "admin-settings" .}}
{{else}}
{{/* Hybrid: container for JS-loaded sections */}}
<div class="admin-page" id="adminHybridContainer" data-section="{{.Section}}">
<div class="admin-loading">Loading {{.Section}}…</div>
<div class="admin-content-header">
<h2 id="adminSectionTitle">{{$section}}</h2>
<div style="flex:1;"></div>
<div class="admin-search">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color:var(--text-3);flex-shrink:0;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
<input id="adminSearch" placeholder="Search…" autocomplete="off">
</div>
{{end}}
<button id="adminAddBtn" class="btn-md btn-primary" style="display:none;">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
Add
</button>
</div>
<div class="admin-content-body" id="adminContentBody" data-section="{{$section}}">
{{/* Populated by admin-handlers.js */}}
<div class="settings-placeholder" id="adminDynamic">Loading…</div>
</div>
</div>
</div>
</div>
<div id="toastContainer" class="toast-container"></div>
{{/* Confirm dialog */}}
<div id="confirmModal" class="modal-overlay">
<div class="modal" style="max-width:380px;">
<div class="modal-header">
<h2 id="confirmTitle">Confirm</h2>
<button class="modal-close" onclick="closeModal('confirmModal')">&#10005;</button>
</div>
<div class="modal-body">
<p id="confirmMessage" style="color:var(--text-2);font-size:14px;line-height:1.65;"></p>
</div>
<div class="modal-footer">
<button class="btn-md btn-ghost" onclick="closeModal('confirmModal')">Cancel</button>
<button id="confirmOkBtn" class="btn-md btn-danger">Confirm</button>
</div>
</div>
</div>
{{end}}
{{define "css-admin"}}
<style>
/* ── Admin surface layout ───────────────── */
.admin-surface { display: flex; flex-direction: column; height: 100%; font-family: inherit; }
.admin-cat-bar {
display: flex; align-items: center; gap: 2px;
padding: 6px 12px; border-bottom: 1px solid var(--border, #2a2a2a);
flex-shrink: 0; background: var(--bg-secondary, #1a1a1e);
}
.admin-cat {
background: none; border: none; color: var(--text-secondary, #888);
padding: 5px 12px; border-radius: 6px; cursor: pointer; font-size: 13px;
}
.admin-cat:hover { background: var(--hover, #252528); color: var(--text-primary, #e0e0e0); }
.admin-cat.active { background: var(--bg-tertiary, #252528); color: var(--text-primary, #e0e0e0); font-weight: 600; }
.admin-cat-spacer { flex: 1; }
.admin-back-link { color: var(--text-secondary, #888); text-decoration: none; font-size: 13px; padding: 5px 8px; }
.admin-back-link:hover { color: var(--text-primary, #e0e0e0); }
.admin-body { display: flex; flex: 1; min-height: 0; overflow: hidden; }
.admin-sidebar {
width: 160px; border-right: 1px solid var(--border, #2a2a2a);
padding: 8px; overflow-y: auto; flex-shrink: 0;
}
.admin-nav-link {
display: block; padding: 6px 10px; border-radius: 6px;
color: var(--text-primary, #e0e0e0); text-decoration: none;
font-size: 13px; margin-bottom: 2px;
}
.admin-nav-link.active { background: var(--bg-tertiary, #252528); }
.admin-nav-link:hover { background: var(--bg-secondary, #1a1a1e); }
.admin-content { flex: 1; overflow-y: auto; padding: 20px; }
/* ── Shared admin styles ────────────────── */
.admin-page h2 { font-size: 18px; margin: 0 0 8px; }
.section-hint { font-size: 13px; color: var(--text-secondary, #888); margin: 0 0 16px; }
.settings-section { padding: 16px; background: var(--bg-secondary, #1a1a1e); border-radius: 8px; border: 1px solid var(--border, #2a2a2a); margin-bottom: 16px; }
.form-row { display: flex; flex-wrap: wrap; gap: 12px; }
.form-group { margin-bottom: 8px; }
.form-group label { display: block; font-size: 12px; color: var(--text-secondary, #888); margin-bottom: 4px; }
.form-group select, .form-group input, .form-group textarea {
padding: 6px 8px; border-radius: 6px; border: 1px solid var(--border, #2a2a2a);
background: var(--bg-primary, #0e0e10); color: var(--text-primary, #e0e0e0); font-size: 13px; width: 100%;
}
.btn-small { padding: 6px 14px; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; }
.btn-primary { background: var(--accent, #5865f2); color: white; }
.btn-primary:hover { opacity: 0.9; }
.btn-danger { background: var(--error, #ef4444); color: white; }
.btn-danger:hover { opacity: 0.9; }
.checkbox-label { display: flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
.admin-inline-form { padding: 16px; background: var(--bg-secondary, #1a1a1e); border-radius: 8px; border: 1px solid var(--border, #2a2a2a); margin-bottom: 16px; }
.empty-hint { font-size: 13px; color: var(--text-secondary, #888); padding: 12px 0; }
.admin-loading { font-size: 13px; color: var(--text-tertiary, #666); padding: 20px; text-align: center; }
/* ── Tables ──────────────────────────────── */
.admin-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.admin-table th {
text-align: left; padding: 8px; font-size: 11px; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.5px;
color: var(--text-tertiary, #666); border-bottom: 1px solid var(--border, #2a2a2a);
}
.admin-table td { padding: 8px; border-bottom: 1px solid var(--border, #2a2a2a); vertical-align: top; }
.admin-table tr:hover td { background: var(--hover, rgba(255,255,255,0.02)); }
.admin-badge {
display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;
}
.admin-badge-admin { background: rgba(239,68,68,0.15); color: #ef4444; }
.admin-badge-user { background: rgba(59,130,246,0.15); color: #3b82f6; }
.admin-badge-active { background: rgba(34,197,94,0.15); color: #22c55e; }
.admin-badge-inactive { background: rgba(239,68,68,0.15); color: #ef4444; }
.admin-badge-global { background: rgba(168,85,247,0.15); color: #a855f7; }
.admin-badge-team { background: rgba(59,130,246,0.15); color: #3b82f6; }
.admin-badge-personal { background: rgba(234,179,8,0.15); color: #eab308; }
/* ── Toolbar ─────────────────────────────── */
.admin-toolbar { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
.admin-search {
padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border, #2a2a2a);
background: var(--bg-primary, #0e0e10); color: var(--text-primary, #e0e0e0);
font-size: 13px; min-width: 200px;
}
</style>
{{end}}
{{/* CSS: consolidated into styles.css */}}
{{define "css-admin"}}{{end}}
{{/* Scripts */}}
{{define "scripts-admin"}}
<script nonce="{{.CSPNonce}}">
// Hybrid section loader — for admin sections not yet server-rendered.
// Detects the data-section on the hybrid container and calls the
// appropriate legacy loader if ui-admin.js is loaded.
(function() {
const container = document.getElementById('adminHybridContainer');
if (!container) return;
const section = container.dataset.section;
if (!section) return;
// Wait for UI and admin loaders to be available
function tryLoad() {
if (typeof UI === 'undefined' || typeof UI.loadAdminUsers === 'undefined') {
setTimeout(tryLoad, 100);
return;
}
container.innerHTML = '';
const LOADERS = {
groups: () => UI.loadAdminGroups(),
presets: () => UI.loadAdminPresets(),
knowledgeBases: () => typeof KnowledgeUI !== 'undefined' ? KnowledgeUI.openAdminPanel() : null,
memory: () => typeof MemoryUI !== 'undefined' ? MemoryUI.openAdminPanel() : null,
storage: () => typeof loadAdminStorage === 'function' ? loadAdminStorage() : null,
extensions: () => UI.loadAdminExtensions(),
health: () => UI.loadAdminHealth(),
capabilities: () => UI.loadAdminCapabilities(),
usage: () => UI.loadAdminUsage(),
audit: () => UI.loadAuditLog(),
stats: () => UI.loadAdminStats(),
};
const loader = LOADERS[section];
if (loader) loader();
else container.innerHTML = '<div class="empty-hint">Section not found</div>';
}
tryLoad();
})();
</script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/marked.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/purify.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-format.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-settings.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-admin.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/admin-handlers.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/settings-handlers.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/knowledge-ui.js?v={{.Version}}"></script>
<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/admin-scaffold.js?v={{.Version}}"></script>
{{end}}

View File

@@ -55,12 +55,12 @@
{{/* ── Sidebar ─────────────────────── */}}
<div id="sidebar" class="sidebar">
<div class="sidebar-top">
{{/* Brand */}}
<div class="sb-brand">
{{/* Brand — click toggles sidebar */}}
<div class="sb-brand" onclick="UI.toggleSidebar()" role="button" tabindex="0">
<div id="brandSidebarLogo" class="sb-logo">
<img src="{{.BasePath}}/favicon.svg" alt="" style="width:28px;height:28px;">
<img src="{{.BasePath}}/favicon-32.png" alt="" class="brand-logo-img">
</div>
<span id="brandSidebarText" class="brand-text">Chat Switchboard</span>
<span id="brandSidebarText" class="brand-text">Switchboard</span>
<span id="brandWordmark" class="brand-text" style="display:none;"></span>
</div>
@@ -73,24 +73,41 @@
<button id="newChatDropBtn" class="split-btn-drop" title="More options">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</button>
<div id="newChatDropdown" class="split-btn-dropdown">
{{/* Populated by projects-ui.js */}}
<div id="newChatDropdown" class="split-dropdown">
<button class="split-dropdown-item" onclick="document.getElementById('newChatDropdown').classList.remove('open'); newChat();">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
<span>New Chat</span>
</button>
<button class="split-dropdown-item" onclick="document.getElementById('newChatDropdown').classList.remove('open'); if(typeof createProject==='function') createProject();">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
<span>New Project</span>
</button>
<button class="split-dropdown-item disabled" title="Coming soon">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
<span>Group Chat</span>
<span class="dd-hint">soon</span>
</button>
<button class="split-dropdown-item disabled" title="Coming soon">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
<span>New Channel</span>
<span class="dd-hint">soon</span>
</button>
</div>
</div>
{{/* Search */}}
<div id="sidebarSearch" class="sidebar-search">
<svg class="search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
<input type="text" id="chatSearchInput" placeholder="Search chats…" autocomplete="off">
<button id="chatSearchClear" class="search-clear" title="Clear search"></button>
</div>
{{/* Sidebar toggle (hamburger) */}}
<button id="sidebarToggle" class="sb-btn sidebar-toggle" title="Toggle sidebar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
</div>
{{/* Search (outside sidebar-top, below brand section) */}}
<div id="sidebarSearch" class="sidebar-search">
<svg class="search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
<input type="text" id="chatSearchInput" placeholder="Search chats…" autocomplete="off">
<button id="chatSearchClear" class="sidebar-search-clear" title="Clear search"></button>
</div>
{{/* Sidebar toggle (hidden on desktop, used by JS for mobile) */}}
<button id="sidebarToggle" class="sb-btn sidebar-toggle" title="Toggle sidebar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
{{/* Sidebar Tabs (Chats / Files) */}}
<div id="sidebarTabs" class="sidebar-tabs" style="display:none;">
<button class="sidebar-tab active" data-tab="chats">Chats</button>
@@ -107,6 +124,12 @@
{{/* User / bottom */}}
<div class="sidebar-bottom">
{{/* Notes shortcut */}}
<button id="notesBtn" class="sb-btn sidebar-notes-btn">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
<span class="sb-label">Notes</span>
</button>
<div class="sidebar-bottom-divider"></div>
<button id="userMenuBtn" class="user-btn">
<div id="userAvatar" class="user-avatar">
<span id="avatarLetter">?</span>
@@ -151,7 +174,7 @@
<div class="workspace">
<div class="workspace-primary workspace-pane">
{{/* Chat header: model selector + token count */}}
{{/* Chat header: model selector + caps + tokens + panel + notif */}}
<div class="chat-header">
<div id="modelDropdown" class="model-dropdown">
<button id="modelDropdownBtn" class="model-dropdown-btn">
@@ -169,6 +192,21 @@
<button id="summarizeBtn" class="action-btn" style="display:none;" title="Summarize older messages">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
</button>
{{/* Panel toggle */}}
<button id="panelToggleBtn" class="action-btn" title="Toggle side panel" onclick="if(typeof PanelRegistry!=='undefined')PanelRegistry.toggle('preview')">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="15" y1="3" x2="15" y2="21"/></svg>
</button>
{{/* Notification bell (inline, not fixed) */}}
<div id="notifWrap" class="notif-wrap">
<button class="notif-bell" onclick="Notifications.toggleDropdown()">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
<span id="notifBadge" class="notif-badge" style="display:none;">0</span>
</button>
<div id="notifDropdown" class="notif-dropdown" style="display:none;">
<div id="notifPanelList"></div>
<div id="notifPanelMore" style="text-align:center;padding:8px;"></div>
</div>
</div>
</div>
</div>
@@ -188,28 +226,49 @@
{{/* Streaming tools display */}}
<div id="streamTools" class="stream-tools" style="display:none;"></div>
{{/* Input toolbar (attach, tools toggle, KB) */}}
<div class="input-toolbar">
<button id="attachBtn" class="action-btn attach-btn" title="Attach file">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
</button>
{{/* tools-toggle.js adds toggle buttons here */}}
</div>
{{/* Input wrap: CM6 editor + send/stop */}}
<div class="input-wrap">
<div id="messageInputWrap">
{{/* CM6 mounts here (chat.js). Fallback textarea below. */}}
<textarea id="messageInput" placeholder="Type a message…" rows="1"></textarea>
{{/* Input area (centered, padded bottom) */}}
<div class="chat-input-area">
{{/* Input toolbar (attach, tools toggle, KB) */}}
<div class="input-toolbar">
<button id="attachBtn" class="action-btn attach-btn" title="Attach file">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
</button>
{{/* Tools toggle */}}
<div class="tools-toggle-wrap" style="display:none;">
<button id="toolsToggleBtn" class="action-btn tools-toggle-btn" title="Tools">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
</button>
<div id="toolsPopup" class="popup tools-popup"></div>
</div>
{{/* Knowledge Bases toggle */}}
<div class="kb-toggle-wrap">
<button id="kbToggleBtn" class="action-btn kb-toggle-btn" title="Knowledge Bases">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
</button>
<div id="kbPopup" class="popup kb-popup"></div>
</div>
{{/* tools-toggle.js + knowledge-ui.js show/populate these at init */}}
</div>
<div class="input-actions">
<span id="inputTokenCount" class="input-token-count"></span>
<button id="sendBtn" class="action-btn send-btn" title="Send message">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
</button>
<button id="stopBtn" class="action-btn stop-btn" title="Stop generating">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/></svg>
</button>
{{/* Input wrap: CM6 editor + send/stop */}}
<div class="input-wrap">
<div id="messageInputWrap">
{{/* CM6 mounts here (chat.js). Fallback textarea below. */}}
<textarea id="messageInput" placeholder="Type a message…" rows="1"></textarea>
</div>
<div class="input-actions">
<span id="inputTokenCount" class="input-token-count"></span>
<button id="sendBtn" class="action-btn send-btn" title="Send message">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
</button>
<button id="stopBtn" class="action-btn stop-btn" title="Stop generating">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/></svg>
</button>
</div>
</div>
<div class="chat-footer">
<span class="chat-version">Switchboard v{{.Version}}</span>
</div>
</div>
</div>
@@ -239,7 +298,7 @@
<p>Open a code block preview or extension output here.</p>
</div>
</div>
{{/* Notes and project panels are registered dynamically */}}
{{/* Notes and project panels are registered dynamically by their JS modules */}}
</div>
</div>
</div>
@@ -273,13 +332,13 @@
<div class="modal-content modal-lg">
<div class="modal-header">
<h2>Settings</h2>
<button class="modal-close" onclick="closeModal('settingsModal')"></button>
<button id="settingsCloseBtn" class="modal-close" onclick="closeModal('settingsModal')"></button>
</div>
<div class="modal-tabs">
<button class="settings-tab active" data-stab="general" onclick="UI.switchSettingsTab('general')">General</button>
<button class="settings-tab" data-stab="appearance" onclick="UI.switchSettingsTab('appearance')">Appearance</button>
<button id="settingsProvidersTabBtn" class="settings-tab" data-stab="providers" onclick="UI.switchSettingsTab('providers')">My Providers</button>
<button id="settingsPersonasTabBtn" class="settings-tab" data-stab="personas" onclick="UI.switchSettingsTab('personas')">My Presets</button>
<button id="settingsPersonasTabBtn" class="settings-tab" data-stab="personas" onclick="UI.switchSettingsTab('personas')">My Personas</button>
<button id="settingsUsageTabBtn" class="settings-tab" data-stab="usage" onclick="UI.switchSettingsTab('usage')">Usage</button>
<button class="settings-tab" data-stab="profile" onclick="UI.switchSettingsTab('profile')">Profile</button>
<button id="settingsRolesTabBtn" class="settings-tab" data-stab="roles" onclick="UI.switchSettingsTab('roles')" style="display:none;">Roles</button>
@@ -333,11 +392,11 @@
<div id="providerAddForm" style="display:none;"></div>
<div id="providerList"></div>
</div>
{{/* Presets tab */}}
{{/* Personas tab */}}
<div id="settingsPersonasTab" class="settings-tab-content" style="display:none;">
<button id="userAddPresetBtn" class="btn-small" style="display:none;">+ New Preset</button>
<div id="userAddPresetForm" style="display:none;"></div>
<div id="userPresetList"></div>
<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;">
@@ -345,6 +404,19 @@
</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">
@@ -354,12 +426,12 @@
<input type="email" id="profileEmail" disabled>
</div>
<div class="form-group">
<button class="btn-small" onclick="document.getElementById('profileChangePwForm').style.display=''">Change Password</button>
<button id="profileChangePwBtn" class="btn-small">Change Password</button>
<div id="profileChangePwForm" style="display:none;margin-top:8px;">
<input type="password" id="settingsCurrentPw" placeholder="Current password" autocomplete="current-password" style="margin-bottom:6px;">
<input type="password" id="settingsNewPw" placeholder="New password" autocomplete="new-password" style="margin-bottom:6px;">
<input type="password" id="settingsConfirmPw" placeholder="Confirm new password" autocomplete="new-password" style="margin-bottom:6px;">
<button class="btn-small" onclick="Pages.changePassword()">Update Password</button>
<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>
@@ -377,8 +449,8 @@
<div id="settingsTeamsTab" class="settings-tab-content" style="display:none;">
<div id="settingsTeamsList"></div>
<div id="settingsTeamMembers" style="display:none;"></div>
<div id="settingsTeamPresets" style="display:none;">
<div id="adminPresetList"></div>
<div id="settingsTeamPersonas" style="display:none;">
<div id="adminPersonaList"></div>
</div>
<div id="settingsTeamProviders" style="display:none;">
<button id="settingsTeamAddProviderBtn" class="btn-small" style="display:none;">+ Add Provider</button>
@@ -394,7 +466,7 @@
</div>
</div>
<div class="modal-footer">
<button class="btn-primary" onclick="UI.saveSettingsAndClose()">Save</button>
<button id="settingsSaveBtn" class="btn-primary" onclick="UI.saveSettingsAndClose()">Save</button>
<button class="btn-secondary" onclick="closeModal('settingsModal')">Cancel</button>
</div>
</div>
@@ -457,7 +529,7 @@
<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="adminUserPresetsToggle"> Allow User Presets</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>
@@ -544,8 +616,8 @@
<button id="teamAuditNextBtn" class="btn-small"></button>
</div>
</div>
{{/* Team preset model select */}}
<div style="display:none;"><select id="teamPreset_model"></select></div>
{{/* Team persona model select */}}
<div style="display:none;"><select id="teamPersona_model"></select></div>
</div>
</div>
</div>
@@ -590,17 +662,7 @@
</div>
</div>
{{/* ── Notification Bell ───────────────────── */}}
<div id="notifWrap" class="notif-wrap" style="position:fixed;top:8px;right:12px;z-index:100;">
<button class="notif-btn" onclick="Notifications.toggleDropdown()">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
<span id="notifBadge" class="notif-badge" style="display:none;">0</span>
</button>
<div id="notifDropdown" class="notif-dropdown" style="display:none;">
<div id="notifPanelList"></div>
<div id="notifPanelMore" style="text-align:center;padding:8px;"></div>
</div>
</div>
{{/* ── Notification bell is now inside .chat-header ── */}}
{{/* ── Routing Policy Form (shared) ────────── */}}
<div id="routingPolicyForm" style="display:none;">
@@ -649,7 +711,6 @@
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/extensions.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/panels.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/ui-format.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/ui-core.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/ui-settings.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/ui-admin.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/tokens.js?v={{$.Version}}"></script>
@@ -667,6 +728,7 @@
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/chat.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/settings-handlers.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/admin-handlers.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/surface-nav.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/editor-mode.js?v={{$.Version}}"></script>
<script nonce="{{$.CSPNonce}}" src="{{$.BasePath}}/js/app.js?v={{$.Version}}"></script>
{{end}}

View File

@@ -1,91 +1,127 @@
{{/*
Editor surface (Phase 2b).
Server renders the layout shell with proper CSS sizing.
editor-mode.js mounts CodeMirror, file tree, etc. into these containers.
Fixes bugs #4 and #5: layout collapse when switching surfaces.
Editor surface — matches switchboard-prototype-editor.jsx.
IDE-like layout: topbar + file tree + tabs + code + chat pane.
editor-mode.js builds CodeMirror, file tree, etc.
*/}}
{{define "surface-editor"}}
<div class="surface-editor" id="surfaceEditor" data-ws-id="{{.Data.WorkspaceID}}" data-ws-name="{{.Data.WorkspaceName}}">
{{/* Header — editor-mode.js populates this */}}
<div class="surface-editor-header" id="editorHeaderMount"></div>
<div class="surface-editor">
<div class="surface-editor-body">
{{/* Editor main area — left pane (tabs + code) + split handle + right pane (chat) */}}
<div class="surface-editor-main" id="editorMainMount"></div>
{{/* Top Bar */}}
<div class="editor-topbar">
<a href="{{.BasePath}}/" class="editor-topbar-back">
<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>
<div style="width:1px;height:18px;background:var(--border);"></div>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--accent);"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
<span style="font-size:13px;font-weight:600;" id="editorWorkspaceName">
{{if .Data}}{{.Data.WorkspaceName}}{{else}}Editor{{end}}
</span>
<div style="display:flex;align-items:center;gap:4px;background:var(--purple-dim);padding:2px 8px;border-radius:4px;">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--purple)" stroke-width="2"><circle cx="12" cy="18" r="3"/><circle cx="12" cy="6" r="3"/><line x1="12" y1="9" x2="12" y2="15"/></svg>
<span style="font-size:11px;font-weight:600;color:var(--purple);font-family:var(--mono);">main</span>
</div>
<div style="flex:1;"></div>
<button class="icon-btn" id="editorNewFileBtn" title="New File">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
</button>
<button class="icon-btn" id="editorRefreshBtn" title="Refresh">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
</button>
<button class="icon-btn" id="editorSearchBtn" title="Search">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
</button>
<div style="width:1px;height:18px;background:var(--border);"></div>
<button class="icon-btn" id="editorToggleTree" title="Toggle file tree">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
</button>
<button class="icon-btn" id="editorToggleChat" title="Toggle chat">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="15" y1="3" x2="15" y2="21"/></svg>
</button>
</div>
{{/* Body: tree + editor + chat */}}
<div class="editor-body" id="editorBody">
{{/* File Tree */}}
<div class="editor-tree" id="editorFileTree">
<div class="editor-tree-header">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
<span style="font-size:11px;font-weight:600;color:var(--text-2);text-transform:uppercase;letter-spacing:0.4px;flex:1;">Files</span>
<button class="icon-btn" id="treeNewFileBtn" title="New file">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
</button>
</div>
<div class="editor-tree-files" id="editorTreeFiles">
{{/* Populated by editor-mode.js */}}
</div>
</div>
{{/* Main Editor Area */}}
<div class="editor-main" id="editorMain">
{{/* Tabs */}}
<div class="editor-tabs" id="editorTabs">
{{/* Populated by editor-mode.js */}}
</div>
{{/* Code Content */}}
<div class="editor-content" id="editorContent">
<div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--text-3);">
<div style="text-align:center;">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="opacity:0.12;display:inline-block;margin-bottom:10px;"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>
<p style="margin:0;font-size:14px;">Open a file to start editing</p>
<p style="margin:6px 0 0;font-size:12px;">Select from the file tree or Ctrl+P</p>
</div>
</div>
</div>
{{/* Status Bar */}}
<div class="editor-statusbar" id="editorStatusbar">
<span>Ready</span>
</div>
</div>
{{/* Chat Pane (resizable) */}}
<div id="editorSplitHandle" style="width:5px;background:var(--border);cursor:col-resize;flex-shrink:0;display:none;"></div>
<div class="editor-chat" id="editorChatPane" style="display:none;">
<div class="editor-chat-header">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
<span style="font-size:12px;font-weight:600;flex:1;">AI Chat</span>
<span class="badge badge-accent" id="editorChatModel">claude-sonnet-4-5</span>
</div>
<div class="editor-chat-messages" id="editorChatMessages">
{{/* Populated by editor-mode.js */}}
</div>
<div class="editor-chat-input">
<div style="display:flex;gap:8px;align-items:flex-end;">
<textarea id="editorChatInput" placeholder="Ask about this code…" rows="2"
style="flex:1;background:var(--input-bg,var(--bg));border:1px solid var(--border);color:var(--text);padding:8px 10px;border-radius:8px;font-size:12px;font-family:inherit;outline:none;resize:none;"></textarea>
<button id="editorChatSendBtn" style="background:var(--accent);color:#fff;border:none;border-radius:8px;padding:8px 14px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;">Send</button>
</div>
<div style="display:flex;gap:6px;margin-top:6px;font-size:10px;color:var(--text-3);">
<span id="editorChatContext">Context: none</span>
<span>&middot;</span>
<span>Cmd+L to focus</span>
</div>
</div>
</div>
</div>
</div>
<div id="toastContainer" class="toast-container"></div>
{{end}}
{{/* CSS: consolidated into styles.css */}}
{{define "css-editor"}}
<link rel="stylesheet" href="{{.BasePath}}/css/editor-mode.css?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/persona-kb.css?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/memory.css?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/notifications.css?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/css/channel-models.css?v={{.Version}}">
<link rel="stylesheet" href="{{.BasePath}}/branding/custom.css" onerror="this.remove()">
<style>
/*
* Editor surface layout — owns the full viewport below banners.
* This is the bug #5 fix: height is set by the server, not fought over
* with other surfaces' CSS.
*/
.surface-editor {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.surface-editor-header {
flex-shrink: 0;
}
.surface-editor-body {
flex: 1;
display: flex;
min-height: 0;
overflow: hidden;
}
.surface-editor-main {
flex: 1;
display: flex;
min-height: 0;
overflow: hidden;
}
</style>
{{end}}
{{/* Scripts */}}
{{define "scripts-editor"}}
{{/* Chat rendering for the assist pane */}}
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/marked.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/purify.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-core.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/codemirror/codemirror.bundle.js?v={{.Version}}" onerror="console.warn('[CM6] Bundle not available')"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-format.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/chat.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/attachments.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/channel-models.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/tokens.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/extensions.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/notes.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/knowledge-ui.js?v={{.Version}}"></script>
<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/panels.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/debug.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/editor-mode.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/projects-ui.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/tools-toggle.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/repl.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/app.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}">
// Editor surface boot: initialize and mount into template containers
document.addEventListener('DOMContentLoaded', () => {
if (typeof EditorMode !== 'undefined' && window.__SURFACE__ === 'editor') {
const data = window.__PAGE_DATA__ || {};
if (data.WorkspaceID) {
EditorMode.mountServerRendered(data.WorkspaceID, data.WorkspaceName || 'Workspace');
}
}
});
</script>
{{end}}

View File

@@ -58,7 +58,6 @@
{{define "scripts-notes"}}
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/marked.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/purify.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-core.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-format.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/chat.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/attachments.js?v={{.Version}}"></script>

View File

@@ -1,236 +1,162 @@
{{/*
Settings surface (Phase 2b).
Server renders a full-page settings layout (replaces the modal).
Reuses existing settings-handlers.js + ui-settings.js for interactions.
Settings surface — matches switchboard-prototype-settings.jsx.
Full-page layout: topbar + left nav + content area.
JS (settings-handlers.js, ui-settings.js) populates dynamic sections.
*/}}
{{define "surface-settings"}}
<div class="surface-settings">
<div class="settings-nav">
<div class="settings-nav-title">Settings</div>
{{$section := .Section}}
<a href="{{.BasePath}}/settings/general" class="settings-nav-link{{if eq $section "general"}} active{{end}}">General</a>
<a href="{{.BasePath}}/settings/appearance" class="settings-nav-link{{if eq $section "appearance"}} active{{end}}">Appearance</a>
<a href="{{.BasePath}}/settings/providers" class="settings-nav-link{{if eq $section "providers"}} active{{end}}">My Providers</a>
<a href="{{.BasePath}}/settings/models" class="settings-nav-link{{if eq $section "models"}} active{{end}}">My Models</a>
<a href="{{.BasePath}}/settings/personas" class="settings-nav-link{{if eq $section "personas"}} active{{end}}">My Presets</a>
<a href="{{.BasePath}}/settings/roles" class="settings-nav-link{{if eq $section "roles"}} active{{end}}">Model Roles</a>
<a href="{{.BasePath}}/settings/knowledge" class="settings-nav-link{{if eq $section "knowledge"}} active{{end}}">Knowledge Bases</a>
<a href="{{.BasePath}}/settings/memory" class="settings-nav-link{{if eq $section "memory"}} active{{end}}">Memory</a>
<a href="{{.BasePath}}/settings/notifications" class="settings-nav-link{{if eq $section "notifications"}} active{{end}}">Notifications</a>
<a href="{{.BasePath}}/settings/usage" class="settings-nav-link{{if eq $section "usage"}} active{{end}}">Usage</a>
<div class="settings-nav-sep"></div>
<a href="{{.BasePath}}/" class="settings-nav-link settings-nav-back">← Back to Chat</a>
<div class="surface-settings" style="flex-direction:column;">
{{/* Top Bar */}}
<div class="settings-topbar">
<a href="{{.BasePath}}/" class="settings-topbar-back">
<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 to Chat
</a>
<div class="settings-topbar-sep"></div>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--text-2)"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
<span class="settings-topbar-title">Settings</span>
</div>
<div class="settings-content" id="settingsContentMount">
{{/* Content rendered by section-specific JS or server template */}}
<div class="settings-content-inner" id="settingsSection" data-section="{{.Section}}">
{{if eq .Section "general"}}{{template "settings-general" .}}
{{else if eq .Section "appearance"}}{{template "settings-appearance" .}}
{{else if eq .Section "providers"}}{{template "settings-providers" .}}
{{else if eq .Section "personas"}}{{template "settings-personas" .}}
{{else}}<div class="settings-placeholder" id="settingsDynamic">Loading…</div>
{{end}}
<div style="display:flex;flex:1;min-height:0;">
{{/* Left Nav */}}
<div class="settings-nav">
{{$section := .Section}}
{{$base := .BasePath}}
<a href="{{$base}}/settings/general" class="settings-nav-link{{if eq $section "general"}} active{{end}}">General</a>
<a href="{{$base}}/settings/appearance" class="settings-nav-link{{if eq $section "appearance"}} active{{end}}">Appearance</a>
<a href="{{$base}}/settings/models" class="settings-nav-link{{if eq $section "models"}} active{{end}}">Models</a>
<a href="{{$base}}/settings/personas" class="settings-nav-link{{if eq $section "personas"}} active{{end}}">Personas</a>
<a href="{{$base}}/settings/profile" class="settings-nav-link{{if eq $section "profile"}} active{{end}}">Profile</a>
<a href="{{$base}}/settings/teams" class="settings-nav-link{{if eq $section "teams"}} active{{end}}">Teams</a>
{{/* BYOK-gated nav items */}}
<div id="settingsByokNav" style="display:none;">
<div class="settings-nav-sep"></div>
<a href="{{$base}}/settings/providers" class="settings-nav-link{{if eq $section "providers"}} active{{end}}">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
My Providers
</a>
<a href="{{$base}}/settings/roles" class="settings-nav-link{{if eq $section "roles"}} active{{end}}">Model Roles</a>
<a href="{{$base}}/settings/usage" class="settings-nav-link{{if eq $section "usage"}} active{{end}}">My Usage</a>
</div>
{{/* BYOK indicator */}}
<div id="settingsByokIndicator" class="settings-nav-footer" style="display:none;">
<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
<span style="font-size:11px;font-weight:600;color:var(--success);">BYOK Enabled</span>
</div>
<p style="font-size:10px;color:var(--text-3);margin:0;line-height:1.5;">Admin has enabled Bring Your Own Key</p>
</div>
</div>
{{/* Content */}}
<div class="settings-content" id="settingsContentMount">
<div id="settingsSection" data-section="{{.Section}}">
<h2 id="settingsSectionTitle">{{if eq .Section "general"}}General{{else if eq .Section "appearance"}}Appearance{{else if eq .Section "models"}}Models{{else if eq .Section "personas"}}Personas{{else if eq .Section "profile"}}Profile{{else if eq .Section "teams"}}Teams{{else if eq .Section "providers"}}My Providers{{else if eq .Section "roles"}}Model Roles{{else if eq .Section "usage"}}My Usage{{else if eq .Section "knowledge"}}Knowledge Bases{{else if eq .Section "memory"}}Memory{{else if eq .Section "notifications"}}Notifications{{else}}Settings{{end}}</h2>
{{if eq .Section "general"}}
<div class="settings-section">
<h3>Chat Defaults</h3>
<div class="form-group">
<label>Default Model</label>
<select id="settingsModel"></select>
</div>
<div class="form-group">
<label>System Prompt</label>
<textarea id="settingsSystemPrompt" rows="3" placeholder="Optional system prompt…" style="max-width:100%;"></textarea>
</div>
<div style="display:flex;gap:16px;">
<div class="form-group" style="flex:1;">
<label>Max Tokens <span id="settingsMaxHint" style="font-weight:400;color:var(--text-3);"></span></label>
<input type="number" id="settingsMaxTokens" placeholder="default">
</div>
<div class="form-group" style="flex:1;">
<label>Temperature</label>
<div style="display:flex;align-items:center;gap:8px;">
<input type="range" id="settingsTemp" min="0" max="2" step="0.1" value="0.7" style="flex:1;">
<span id="settingsTempValue" style="font-size:12px;color:var(--text-2);font-family:var(--mono);">0.7</span>
</div>
</div>
</div>
<label style="display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text-2);cursor:pointer;margin-top:4px;">
<input type="checkbox" id="settingsThinking"> Show thinking blocks
</label>
</div>
{{else if eq .Section "appearance"}}
<div class="settings-section">
<h3>Theme</h3>
<div id="themeToggle" class="toggle-group">
<button class="toggle-btn" data-theme="light">&#9728; Light</button>
<button class="toggle-btn" data-theme="dark">&#9790; Dark</button>
<button class="toggle-btn" data-theme="system">&#8862; System</button>
</div>
</div>
<div class="settings-section">
<h3>UI Scale</h3>
<div class="form-group">
<div style="display:flex;align-items:center;gap:8px;">
<input type="range" id="settingsScale" min="80" max="120" step="5" value="100" style="flex:1;">
<span id="scaleValue" style="font-size:12px;color:var(--text-2);font-family:var(--mono);min-width:32px;">100%</span>
</div>
</div>
<h3 style="margin-top:16px;">Message Font Size</h3>
<div class="form-group">
<div style="display:flex;align-items:center;gap:8px;">
<input type="range" id="settingsMsgFont" min="12" max="20" step="1" value="14" style="flex:1;">
<span id="msgFontValue" style="font-size:12px;color:var(--text-2);font-family:var(--mono);min-width:32px;">14px</span>
</div>
</div>
</div>
<button class="btn-md btn-primary" onclick="if(typeof UI!=='undefined')UI.saveAppearance?.()">Save</button>
{{else if eq .Section "profile"}}
<div class="settings-section">
<h3>Profile</h3>
<div class="form-group"><label>Display Name</label><input type="text" id="profileDisplayName" placeholder="Your display name"></div>
<div class="form-group"><label>Email</label><input type="email" id="profileEmail" disabled></div>
<button class="btn-md btn-primary" onclick="if(typeof Pages!=='undefined')Pages.saveProfile?.()">Save Profile</button>
</div>
<div class="settings-section" style="margin-top:20px;">
<h3>Change Password</h3>
<div class="form-group"><label>Current Password</label><input type="password" id="settingsCurrentPw" autocomplete="current-password"></div>
<div class="form-group"><label>New Password</label><input type="password" id="settingsNewPw" autocomplete="new-password"></div>
<div class="form-group"><label>Confirm New Password</label><input type="password" id="settingsConfirmPw" autocomplete="new-password"></div>
<button class="btn-md btn-primary" onclick="if(typeof Pages!=='undefined')Pages.changePassword?.()">Update Password</button>
</div>
{{else if eq .Section "providers"}}
<div id="userProvidersDisabled" style="display:none;">
<div class="settings-section"><p style="color:var(--text-2);font-size:13px;">Your admin has disabled user-managed API keys (BYOK).</p></div>
</div>
<div style="margin-bottom:12px;">
<button class="btn-md btn-primary" id="providerShowAddBtn" style="display:none;">+ Add Provider</button>
</div>
<div id="providerAddForm" style="display:none;"></div>
<div id="providerList"><div class="settings-placeholder">Loading providers…</div></div>
{{else if eq .Section "personas"}}
<div style="margin-bottom:12px;">
<button class="btn-md btn-primary" id="userAddPersonaBtn" style="display:none;">+ New Persona</button>
</div>
<div id="userAddPersonaForm" style="display:none;"></div>
<div id="userPersonaList"><div class="settings-placeholder">Loading personas…</div></div>
{{else}}<div class="settings-placeholder" id="settingsDynamic">Loading…</div>
{{end}}
</div>
</div>
</div>
</div>
<div id="toastContainer" class="toast-container"></div>
{{end}}
{{define "settings-general"}}
<div class="settings-section">
<h2>Profile</h2>
<div class="form-group">
<label>Display Name</label>
<input type="text" id="settingsDisplayName" value="{{if .User}}{{.User.display_name}}{{end}}" placeholder="Your name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="settingsEmail" value="{{if .User}}{{.User.email}}{{end}}" disabled>
</div>
<button class="btn-small btn-primary" onclick="Pages.saveProfile()">Save</button>
</div>
<div class="settings-section" style="margin-top:16px">
<h2>Password</h2>
<div class="form-group">
<label>Current Password</label>
<input type="password" id="settingsCurrentPw">
</div>
<div class="form-group">
<label>New Password</label>
<input type="password" id="settingsNewPw">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" id="settingsConfirmPw">
</div>
<button class="btn-small btn-primary" onclick="Pages.changePassword()">Change Password</button>
</div>
{{end}}
{{define "settings-appearance"}}
<div class="settings-section">
<h2>Theme</h2>
<div id="themeToggle" class="settings-toggle-group">
<button class="theme-btn" data-theme="dark">Dark</button>
<button class="theme-btn" data-theme="light">Light</button>
</div>
</div>
<div class="settings-section" style="margin-top:16px">
<h2>Editor Keymap</h2>
<div id="keymapToggle" class="settings-toggle-group">
<button class="theme-btn" data-keymap="standard">Standard</button>
<button class="theme-btn" data-keymap="vim">Vim</button>
<button class="theme-btn" data-keymap="emacs">Emacs</button>
</div>
</div>
<div class="settings-section" style="margin-top:16px">
<h2>UI Scale</h2>
<div class="form-group">
<input type="range" id="settingsScale" min="80" max="120" step="5" value="100">
<span id="scaleValue">100%</span>
</div>
<h2>Message Font Size</h2>
<div class="form-group">
<input type="range" id="settingsMsgFont" min="12" max="20" step="1" value="14">
<span id="msgFontValue">14px</span>
</div>
</div>
{{end}}
{{define "settings-providers"}}
<div id="userProvidersDisabled" class="settings-section" style="display:none;">
<p style="color:var(--text-secondary);font-size:13px;">Your admin has disabled user-managed API keys (BYOK). Models are available through team presets.</p>
</div>
<div style="margin-bottom:12px;">
<button class="btn-small btn-primary" id="providerShowAddBtn">+ Add Provider</button>
</div>
<div id="providerAddForm" style="display:none;"></div>
<div id="providerList"><div class="settings-placeholder">Loading providers…</div></div>
{{end}}
{{define "settings-personas"}}
<div style="margin-bottom:12px;">
<button class="btn-small btn-primary" id="userAddPresetBtn">+ New Preset</button>
</div>
<div id="userAddPresetForm" style="display:none;"></div>
<div id="userPresetList"><div class="settings-placeholder">Loading presets…</div></div>
{{end}}
{{define "css-settings"}}
<style>
.surface-settings {
display: flex;
height: 100%;
overflow: hidden;
}
.settings-nav {
width: 200px;
border-right: 1px solid var(--border, #2a2a2a);
padding: 12px;
overflow-y: auto;
flex-shrink: 0;
}
.settings-nav-title {
font-size: 13px;
font-weight: 600;
color: var(--text-secondary, #888);
margin-bottom: 12px;
}
.settings-nav-link {
display: block;
padding: 6px 10px;
border-radius: 6px;
color: var(--text-primary, #e0e0e0);
text-decoration: none;
font-size: 13px;
margin-bottom: 2px;
}
.settings-nav-link.active { background: var(--bg-tertiary, #252528); }
.settings-nav-link:hover { background: var(--bg-secondary, #1a1a1e); }
.settings-nav-sep {
margin: 12px 0;
border-top: 1px solid var(--border, #2a2a2a);
}
.settings-nav-back { color: var(--text-secondary, #888); }
.settings-content {
flex: 1;
overflow-y: auto;
padding: 20px;
}
.settings-section {
padding: 16px;
background: var(--bg-secondary, #1a1a1e);
border-radius: 8px;
border: 1px solid var(--border, #2a2a2a);
max-width: 600px;
}
.settings-section h2 {
font-size: 15px;
margin: 0 0 12px;
}
.settings-toggle-group {
display: flex;
gap: 6px;
}
.settings-toggle-group .theme-btn {
padding: 6px 14px;
border: 1px solid var(--border, #2a2a2a);
border-radius: 6px;
background: var(--bg-primary, #0e0e10);
color: var(--text-primary, #e0e0e0);
cursor: pointer;
font-size: 13px;
}
.settings-toggle-group .theme-btn.active {
background: var(--accent, #5865f2);
border-color: var(--accent, #5865f2);
color: white;
}
.settings-placeholder {
padding: 20px;
color: var(--text-secondary, #888);
}
.form-group { margin-bottom: 8px; }
.form-group label {
display: block;
font-size: 12px;
color: var(--text-secondary, #888);
margin-bottom: 4px;
}
.form-group input, .form-group select, .form-group textarea {
padding: 6px 8px;
border-radius: 6px;
border: 1px solid var(--border, #2a2a2a);
background: var(--bg-primary, #0e0e10);
color: var(--text-primary, #e0e0e0);
font-size: 13px;
width: 100%;
max-width: 300px;
}
.btn-small {
padding: 6px 14px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
}
.btn-primary {
background: var(--accent, #5865f2);
color: white;
}
.btn-primary:hover { opacity: 0.9; }
@media (max-width: 768px) {
.settings-nav { width: 160px; font-size: 12px; }
}
</style>
{{end}}
{{/* CSS: consolidated into styles.css */}}
{{define "css-settings"}}{{end}}
{{/* Scripts */}}
{{define "scripts-settings"}}
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/marked.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/vendor/purify.min.js"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-core.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-format.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/ui-settings.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/settings-handlers.js?v={{.Version}}"></script>
@@ -239,32 +165,50 @@
<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/notification-prefs.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}" src="{{.BasePath}}/js/channel-models.js?v={{.Version}}"></script>
<script nonce="{{.CSPNonce}}">
// Settings surface boot
document.addEventListener('DOMContentLoaded', () => {
const section = document.getElementById('settingsSection')?.dataset.section;
if (!section) return;
// Appearance: wire up theme/keymap buttons and sliders
if (section === 'appearance' && typeof UI !== 'undefined') {
UI.loadAppearanceSettings();
UI.initAppearance();
// Show BYOK nav if enabled
const pageData = window.__PAGE_DATA__;
if (pageData && pageData.BYOKEnabled) {
const byokNav = document.getElementById('settingsByokNav');
const byokInd = document.getElementById('settingsByokIndicator');
if (byokNav) byokNav.style.display = '';
if (byokInd) byokInd.style.display = '';
}
// Dynamic sections: let existing JS populate the container
const dynamicSections = {
providers: () => typeof UI !== 'undefined' && UI.loadProviderList(),
models: () => typeof UI !== 'undefined' && UI.loadUserModels(),
personas: () => typeof UI !== 'undefined' && UI.loadUserPresets(),
usage: () => typeof UI !== 'undefined' && UI.loadMyUsage(),
roles: () => typeof UI !== 'undefined' && UI.loadUserRoles(),
knowledge: () => typeof KnowledgeUI !== 'undefined' && KnowledgeUI.openManagePanel(),
memory: () => typeof MemoryUI !== 'undefined' && MemoryUI.openSettingsPanel(),
notifications: () => typeof NotifPrefs !== 'undefined' && NotifPrefs.load(),
};
if (dynamicSections[section]) {
dynamicSections[section]();
if (section === 'appearance' && typeof UI !== 'undefined') {
UI.loadAppearanceSettings?.();
UI.initAppearance?.();
}
if (section === 'general' && typeof UI !== 'undefined') {
UI.loadGeneralSettings?.();
}
if (section === 'profile') {
const user = window.__USER__;
if (user) {
const dn = document.getElementById('profileDisplayName');
const em = document.getElementById('profileEmail');
if (dn) dn.value = user.display_name || user.username || '';
if (em) em.value = user.email || '';
}
}
const dynamicSections = {
providers: () => typeof UI !== 'undefined' && UI.loadProviderList?.(),
models: () => typeof UI !== 'undefined' && UI.loadUserModels?.(),
personas: () => typeof UI !== 'undefined' && UI.loadUserPersonas?.(),
usage: () => typeof UI !== 'undefined' && UI.loadMyUsage?.(),
roles: () => typeof UI !== 'undefined' && UI.loadUserRoles?.(),
knowledge: () => typeof KnowledgeUI !== 'undefined' && KnowledgeUI.openManagePanel?.(),
memory: () => typeof MemoryUI !== 'undefined' && MemoryUI.openSettingsPanel?.(),
notifications: () => typeof NotifPrefs !== 'undefined' && NotifPrefs.load?.(),
teams: () => typeof UI !== 'undefined' && UI.loadTeamsSettings?.(),
};
if (dynamicSections[section]) dynamicSections[section]();
});
</script>
{{end}}

View File

@@ -265,13 +265,13 @@ func (h *OpenRouterHooks) PostStreamEvent(_ ProviderConfig, _ *StreamEvent) {
// No post-processing needed. OpenRouter returns standard OAI format.
}
// ── Preset Override Merge ───────────────────
// ── Persona Override Merge ───────────────────
// MergePresetSettings merges persona-level setting overrides onto
// provider-level settings. Preset values take priority except for
// MergePersonaSettings merges persona-level setting overrides onto
// provider-level settings. Persona values take priority except for
// fields marked ProviderOnly in the schema.
func MergePresetSettings(providerType string, providerSettings, presetOverrides map[string]interface{}) map[string]interface{} {
if len(presetOverrides) == 0 {
func MergePersonaSettings(providerType string, providerSettings, personaOverrides map[string]interface{}) map[string]interface{} {
if len(personaOverrides) == 0 {
return providerSettings
}
@@ -283,11 +283,11 @@ func MergePresetSettings(providerType string, providerSettings, presetOverrides
}
}
merged := make(map[string]interface{}, len(providerSettings)+len(presetOverrides))
merged := make(map[string]interface{}, len(providerSettings)+len(personaOverrides))
for k, v := range providerSettings {
merged[k] = v
}
for k, v := range presetOverrides {
for k, v := range personaOverrides {
if !providerOnly[k] {
merged[k] = v
}

View File

@@ -270,45 +270,45 @@ func TestGetHooks_Unknown(t *testing.T) {
}
}
// ── MergePresetSettings Tests ──────────────
// ── MergePersonaSettings Tests ──────────────
func TestMergePresetSettings_Basic(t *testing.T) {
func TestMergePersonaSettings_Basic(t *testing.T) {
provider := map[string]interface{}{
"system_prompt_prefix": "Provider prompt",
"frequency_penalty": 0.3,
}
preset := map[string]interface{}{
"system_prompt_prefix": "Preset prompt",
persona := map[string]interface{}{
"system_prompt_prefix": "Persona prompt",
}
merged := MergePresetSettings("openai", provider, preset)
merged := MergePersonaSettings("openai", provider, persona)
if merged["system_prompt_prefix"] != "Preset prompt" {
t.Errorf("preset should override provider, got %v", merged["system_prompt_prefix"])
if merged["system_prompt_prefix"] != "Persona prompt" {
t.Errorf("persona should override provider, got %v", merged["system_prompt_prefix"])
}
if merged["frequency_penalty"] != 0.3 {
t.Errorf("provider value should be preserved, got %v", merged["frequency_penalty"])
}
}
func TestMergePresetSettings_ProviderOnlyBlocked(t *testing.T) {
func TestMergePersonaSettings_ProviderOnlyBlocked(t *testing.T) {
provider := map[string]interface{}{
"route": "auto",
}
preset := map[string]interface{}{
persona := map[string]interface{}{
"route": "fallback", // route is ProviderOnly for openrouter
}
merged := MergePresetSettings("openrouter", provider, preset)
merged := MergePersonaSettings("openrouter", provider, persona)
if merged["route"] != "auto" {
t.Errorf("ProviderOnly field should not be overridden by preset, got %v", merged["route"])
t.Errorf("ProviderOnly field should not be overridden by persona, got %v", merged["route"])
}
}
func TestMergePresetSettings_EmptyOverrides(t *testing.T) {
func TestMergePersonaSettings_EmptyOverrides(t *testing.T) {
provider := map[string]interface{}{"key": "value"}
merged := MergePresetSettings("openai", provider, nil)
merged := MergePersonaSettings("openai", provider, nil)
if merged["key"] != "value" {
t.Error("empty overrides should return provider settings unchanged")
}

View File

@@ -18,7 +18,7 @@ type ProfileField struct {
Min *int `json:"min,omitempty"` // min for int/float
Max *int `json:"max,omitempty"` // max for int/float
DependsOn string `json:"depends_on,omitempty"` // only show when this key is truthy
ProviderOnly bool `json:"provider_only,omitempty"` // not overridable at preset level
ProviderOnly bool `json:"provider_only,omitempty"` // not overridable at persona level
}
// ── Built-in Profile Schemas ────────────────

View File

@@ -86,7 +86,7 @@ func (s *CatalogStore) GetByModelID(ctx context.Context, providerConfigID, model
}
// GetByModelIDAny returns the most recently synced catalog entry for a model_id
// across any provider. Used to resolve capabilities for presets with auto-resolve
// across any provider. Used to resolve capabilities for personas with auto-resolve
// (no specific provider_config_id).
func (s *CatalogStore) GetByModelIDAny(ctx context.Context, modelID string) (*models.CatalogEntry, error) {
row := DB.QueryRowContext(ctx,

View File

@@ -20,7 +20,7 @@ func SetDB(db *sql.DB) {
// ── Dynamic SQL Builder ─────────────────────
// Replaces the copy-pasted addClause/addField pattern
// found in admin.go, presets.go, team_providers.go, apiconfigs.go.
// found in admin.go, personas.go, team_providers.go, apiconfigs.go.
// UpdateBuilder constructs a dynamic UPDATE statement.
type UpdateBuilder struct {

View File

@@ -86,7 +86,7 @@ func (s *CatalogStore) GetByModelID(ctx context.Context, providerConfigID, model
}
// GetByModelIDAny returns the most recently synced catalog entry for a model_id
// across any provider. Used to resolve capabilities for presets with auto-resolve
// across any provider. Used to resolve capabilities for personas with auto-resolve
// (no specific provider_config_id).
func (s *CatalogStore) GetByModelIDAny(ctx context.Context, modelID string) (*models.CatalogEntry, error) {
row := DB.QueryRowContext(ctx,