From 6982a4cc31c3ceb46f8a65815829d533c90638e3 Mon Sep 17 00:00:00 2001 From: Finessse Date: Tue, 30 Dec 2025 08:45:56 +0700 Subject: [PATCH] feat(tui): add responsive layout and fix sidebar overflow COMPLETED: - Added ViewWithSize(width, height) pattern to all submodels - login.go: responsive provider rows with adaptive widths - switch.go: responsive agent rows without card borders - mappings.go: responsive table columns with calculateColumnWidths() - usage.go: responsive stat cards (2x2 grid layout) - logs.go: responsive log entries with message truncation - Fixed main View() layout calculation in tui.go - Properly accounts for border (2) + padding (2) = 4 chars per panel - sidebarWidth now represents content width (20/14 for normal/narrow) - contentWidth = m.width - sidebarWidth - 9 (accounts for both panels) - Added new screen files: - integrations.go: setup/integration screen - logs.go: real-time log viewer with filtering - mappings.go: model alias mappings table - usage.go: usage statistics with charts PENDING TEST: - Verify sidebar displays correctly alongside content (was overflowing) - Test all screens at various terminal widths (60, 80, 100+ cols) KNOWN ISSUE BEING FIXED: - Sidebar was showing only "[8] Setup" at top due to width overflow - Content panel was too wide, causing horizontal wrap --- internal/tui/integrations.go | 552 ++++++++++++++++++++ internal/tui/login.go | 311 +++++++++--- internal/tui/logs.go | 534 ++++++++++++++++++++ internal/tui/mappings.go | 354 +++++++++++++ internal/tui/server.go | 444 +++++++++++++---- internal/tui/styles.go | 727 +++++++++++++++------------ internal/tui/switch.go | 459 ++++++++++++++--- internal/tui/tui.go | 942 ++++++++++++++++++++++++----------- internal/tui/usage.go | 808 ++++++++++++++++++++++++++++++ internal/tui/utils.go | 18 +- 10 files changed, 4296 insertions(+), 853 deletions(-) create mode 100644 internal/tui/integrations.go create mode 100644 internal/tui/logs.go create mode 100644 internal/tui/mappings.go create mode 100644 internal/tui/usage.go diff --git a/internal/tui/integrations.go b/internal/tui/integrations.go new file mode 100644 index 00000000..bc85709a --- /dev/null +++ b/internal/tui/integrations.go @@ -0,0 +1,552 @@ +package tui + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// INTEGRATION CARD ICONS - Brand-appropriate terminal icons +// ═══════════════════════════════════════════════════════════════════════════════ + +var integrationIcons = map[string]string{ + "Claude Code": ">>> ", + "Codex CLI": "[*] ", + "Gemini CLI": "<*> ", + "Factory Droid": "{#} ", + "Cursor IDE": "|>| ", + "Continue": "... ", +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// INTEGRATION CARD STYLES - Cyberpunk neon aesthetic +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + // Card container styles + integrationCardStyle = lipgloss.NewStyle(). + Border(SoftBorder). + BorderForeground(BorderDim). + Padding(0, 2). + MarginBottom(0) + + integrationCardSelectedStyle = lipgloss.NewStyle(). + Border(CyberBorder). + BorderForeground(Cyan). + Padding(0, 2). + MarginBottom(0) + + integrationCardExpandedStyle = lipgloss.NewStyle(). + Border(NeonBorder). + BorderForeground(Magenta). + Padding(1, 2). + MarginBottom(0) + + // Setup box styles + setupBoxStyle = lipgloss.NewStyle(). + Border(SoftBorder). + BorderForeground(Violet). + Background(DarkSurface). + Padding(1, 2). + MarginLeft(2). + MarginTop(1) + + // Code block style + codeBlockStyle = lipgloss.NewStyle(). + Background(Surface). + Foreground(NeonGreen). + Padding(0, 1) + + // Config path style + configPathStyle = lipgloss.NewStyle(). + Foreground(TextDim). + Italic(true) + + // Section header inside setup box + setupHeaderStyle = lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true) + + // Step number style + stepNumberStyle = lipgloss.NewStyle(). + Foreground(Magenta). + Bold(true) + + // Instruction text style + instructionStyle = lipgloss.NewStyle(). + Foreground(TextMuted) +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// STATUS BADGE STYLES - Setup status indicators +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + statusProxyBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(NeonGreen). + Bold(true). + Padding(0, 1) + + statusNativeBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(Amber). + Bold(true). + Padding(0, 1) + + statusManualBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(ElecBlue). + Bold(true). + Padding(0, 1) + + statusNotSetBadge = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(Surface). + Padding(0, 1) +) + +// Integration represents a tool integration +type Integration struct { + Name string + Description string + ConfigPath string + Status string + Setup []string +} + +// IntegrationsModel represents the integrations/setup screen +type IntegrationsModel struct { + width int + height int + cursor int + integrations []Integration + expanded int // Which integration is expanded (-1 for none) +} + +// NewIntegrationsModel creates a new integrations model +func NewIntegrationsModel() IntegrationsModel { + integrations := []Integration{ + { + Name: "Claude Code", + Description: "Anthropic's official CLI for Claude", + ConfigPath: "~/.claude/settings.json", + Status: detectAgentMode(expandPath("~/.claude/settings.json")), + Setup: []string{ + `Add to ~/.claude/settings.json:`, + `{`, + ` "env": {`, + ` "ANTHROPIC_BASE_URL": "http://127.0.0.1:8317",`, + ` "ANTHROPIC_AUTH_TOKEN": "your-key"`, + ` }`, + `}`, + }, + }, + { + Name: "Codex CLI", + Description: "OpenAI's coding assistant", + ConfigPath: "~/.codex/config.toml", + Status: detectAgentMode(expandPath("~/.codex/config.toml")), + Setup: []string{ + `Add to ~/.codex/config.toml:`, + ``, + `[openai]`, + `api_base_url = "http://127.0.0.1:8317"`, + }, + }, + { + Name: "Gemini CLI", + Description: "Google's Gemini CLI tool", + ConfigPath: "~/.gemini/settings.json", + Status: detectAgentMode(expandPath("~/.gemini/settings.json")), + Setup: []string{ + `Add to ~/.gemini/settings.json:`, + `{`, + ` "api_base_url": "http://127.0.0.1:8317"`, + `}`, + }, + }, + { + Name: "Factory Droid", + Description: "AI-powered development assistant", + ConfigPath: "~/.factory/config.json", + Status: detectAgentMode(expandPath("~/.factory/config.json")), + Setup: []string{ + `Add to ~/.factory/config.json:`, + `{`, + ` "customModels": [{`, + ` "name": "ProxyPilot",`, + ` "baseUrl": "http://127.0.0.1:8317"`, + ` }]`, + `}`, + }, + }, + { + Name: "Cursor IDE", + Description: "AI-first code editor", + ConfigPath: "Settings > Models > OpenAI API Base URL", + Status: "manual", + Setup: []string{ + `In Cursor Settings:`, + ``, + `1. Open Settings (Cmd/Ctrl + ,)`, + `2. Search for "OpenAI Base URL"`, + `3. Set to: http://127.0.0.1:8317`, + `4. Enable "Override OpenAI Base URL"`, + }, + }, + { + Name: "Continue", + Description: "Open-source AI code assistant", + ConfigPath: "~/.continue/config.json", + Status: detectAgentMode(expandPath("~/.continue/config.json")), + Setup: []string{ + `Add to ~/.continue/config.json:`, + `{`, + ` "models": [{`, + ` "title": "ProxyPilot",`, + ` "provider": "openai",`, + ` "model": "gpt-4",`, + ` "apiBase": "http://127.0.0.1:8317"`, + ` }]`, + `}`, + }, + }, + } + + return IntegrationsModel{ + width: 80, + height: 24, + integrations: integrations, + expanded: -1, + } +} + +// Init initializes the integrations model +func (m IntegrationsModel) Init() tea.Cmd { + return nil +} + +// Update handles messages for the integrations model +func (m IntegrationsModel) Update(msg tea.Msg) (IntegrationsModel, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + return m, nil + + case tea.KeyMsg: + switch msg.String() { + case "up", "k": + if m.cursor > 0 { + m.cursor-- + } + case "down", "j": + if m.cursor < len(m.integrations)-1 { + m.cursor++ + } + case "enter", " ": + if m.expanded == m.cursor { + m.expanded = -1 // Collapse + } else { + m.expanded = m.cursor // Expand + } + } + } + + return m, nil +} + +// View renders the integrations screen +func (m IntegrationsModel) View() string { + var b strings.Builder + + // Cyber header with decorative elements + headerLine := lipgloss.NewStyle().Foreground(Violet).Render("━━━") + + lipgloss.NewStyle().Foreground(Cyan).Bold(true).Render(" INTEGRATIONS ") + + lipgloss.NewStyle().Foreground(Violet).Render("━━━") + b.WriteString(headerLine) + b.WriteString("\n\n") + + // Info text with neon styling + infoIcon := lipgloss.NewStyle().Foreground(ElecBlue).Render(IconInfo) + b.WriteString(infoIcon + " " + lipgloss.NewStyle().Foreground(TextMuted).Render("Configure your AI coding tools to route through ProxyPilot")) + b.WriteString("\n") + hintIcon := lipgloss.NewStyle().Foreground(Violet).Render(IconChevron) + b.WriteString(hintIcon + " " + lipgloss.NewStyle().Foreground(TextDim).Render("Press Enter to expand setup instructions")) + b.WriteString("\n\n") + + // Status legend + b.WriteString(m.renderStatusLegend()) + b.WriteString("\n\n") + + // Integration list + for i, integration := range m.integrations { + isExpanded := m.expanded == i + isSelected := m.cursor == i + + b.WriteString(m.renderIntegrationCard(integration, isSelected, isExpanded)) + + if i < len(m.integrations)-1 { + b.WriteString("\n") + } + } + + // Help footer + b.WriteString("\n") + b.WriteString(m.renderHelp()) + + return b.String() +} + +// renderStatusLegend renders the status indicator legend +func (m IntegrationsModel) renderStatusLegend() string { + proxyIndicator := lipgloss.NewStyle().Foreground(NeonGreen).Render(IconOnline) + " " + + lipgloss.NewStyle().Foreground(TextDim).Render("Proxy Active") + + nativeIndicator := lipgloss.NewStyle().Foreground(Amber).Render(IconPending) + " " + + lipgloss.NewStyle().Foreground(TextDim).Render("Native Mode") + + manualIndicator := lipgloss.NewStyle().Foreground(ElecBlue).Render(IconInfo) + " " + + lipgloss.NewStyle().Foreground(TextDim).Render("Manual Setup") + + notSetIndicator := lipgloss.NewStyle().Foreground(TextDim).Render(IconOffline) + " " + + lipgloss.NewStyle().Foreground(TextDim).Render("Not Configured") + + return lipgloss.JoinHorizontal(lipgloss.Top, + proxyIndicator+" ", + nativeIndicator+" ", + manualIndicator+" ", + notSetIndicator, + ) +} + +// renderIntegrationCard renders a single integration as a styled card +func (m IntegrationsModel) renderIntegrationCard(integration Integration, selected, expanded bool) string { + cardWidth := min(m.width-4, 70) + + // Get the brand icon + icon := integrationIcons[integration.Name] + if icon == "" { + icon = "[?] " + } + + // Status badge + var statusBadge string + var statusIcon string + switch integration.Status { + case "proxy": + statusBadge = statusProxyBadge.Render(" PROXY ") + statusIcon = lipgloss.NewStyle().Foreground(NeonGreen).Render(IconOnline) + case "native": + statusBadge = statusNativeBadge.Render(" NATIVE ") + statusIcon = lipgloss.NewStyle().Foreground(Amber).Render(IconPending) + case "manual": + statusBadge = statusManualBadge.Render(" MANUAL ") + statusIcon = lipgloss.NewStyle().Foreground(ElecBlue).Render(IconInfo) + default: + statusBadge = statusNotSetBadge.Render(" NOT SET ") + statusIcon = lipgloss.NewStyle().Foreground(TextDim).Render(IconOffline) + } + + // Build card content + var content strings.Builder + + // Header line with icon, name, and status + var nameStyle lipgloss.Style + var iconStyle lipgloss.Style + if selected { + nameStyle = lipgloss.NewStyle().Foreground(Cyan).Bold(true) + iconStyle = lipgloss.NewStyle().Foreground(Magenta).Bold(true) + } else { + nameStyle = lipgloss.NewStyle().Foreground(TextBright) + iconStyle = lipgloss.NewStyle().Foreground(Violet) + } + + expandIcon := lipgloss.NewStyle().Foreground(Violet).Render(" ") + if expanded { + expandIcon = lipgloss.NewStyle().Foreground(Magenta).Bold(true).Render(IconArrowDown + " ") + } else if selected { + expandIcon = lipgloss.NewStyle().Foreground(Cyan).Render(IconChevron + " ") + } + + headerLine := fmt.Sprintf("%s%s%s %s %s", + expandIcon, + iconStyle.Render(icon), + nameStyle.Render(integration.Name), + statusIcon, + statusBadge, + ) + content.WriteString(headerLine) + + // Description line + content.WriteString("\n") + descStyle := lipgloss.NewStyle().Foreground(TextMuted) + content.WriteString(" " + descStyle.Render(integration.Description)) + + // Expanded content + if expanded { + content.WriteString("\n\n") + + // Config path with styling + configLabel := lipgloss.NewStyle().Foreground(Violet).Render("Config: ") + configValue := configPathStyle.Render(integration.ConfigPath) + content.WriteString(" " + configLabel + configValue) + + content.WriteString("\n") + + // Setup instructions box + setupContent := m.renderSetupInstructions(integration.Setup) + content.WriteString(setupContent) + } + + // Apply card style based on state + var cardStyle lipgloss.Style + if expanded { + cardStyle = integrationCardExpandedStyle.Width(cardWidth) + } else if selected { + cardStyle = integrationCardSelectedStyle.Width(cardWidth) + } else { + cardStyle = integrationCardStyle.Width(cardWidth) + } + + return cardStyle.Render(content.String()) +} + +// renderSetupInstructions renders the setup instructions with cyber styling +func (m IntegrationsModel) renderSetupInstructions(setup []string) string { + boxWidth := min(m.width-14, 58) + + var content strings.Builder + + // Header with neon styling + headerDecor := lipgloss.NewStyle().Foreground(Cyan).Render("//") + headerText := setupHeaderStyle.Render(" SETUP INSTRUCTIONS ") + content.WriteString(headerDecor + headerText + headerDecor) + content.WriteString("\n") + + // Divider line + divider := lipgloss.NewStyle().Foreground(BorderDim).Render(strings.Repeat("─", boxWidth-4)) + content.WriteString(divider) + content.WriteString("\n\n") + + // Process each line + inCodeBlock := false + for _, line := range setup { + if line == "" { + content.WriteString("\n") + continue + } + + // Check if it's a step instruction (starts with number) + if len(line) > 2 && line[0] >= '1' && line[0] <= '9' && line[1] == '.' { + stepNum := stepNumberStyle.Render(string(line[0:2])) + stepText := instructionStyle.Render(line[2:]) + content.WriteString(stepNum + stepText) + content.WriteString("\n") + continue + } + + // Check if it's the header instruction + if strings.HasPrefix(line, "Add to") || strings.HasPrefix(line, "In ") { + content.WriteString(instructionStyle.Render(line)) + content.WriteString("\n\n") + inCodeBlock = true + continue + } + + // Code-like content (JSON, TOML, etc.) + if inCodeBlock || strings.HasPrefix(line, "{") || strings.HasPrefix(line, "}") || + strings.HasPrefix(line, "[") || strings.HasPrefix(line, "]") || + strings.HasPrefix(line, `"`) || strings.Contains(line, "=") || + strings.HasPrefix(line, " ") { + + // Style the code line + styledLine := m.styleCodeLine(line) + content.WriteString(styledLine) + content.WriteString("\n") + } else { + content.WriteString(instructionStyle.Render(line)) + content.WriteString("\n") + } + } + + return setupBoxStyle.Width(boxWidth).Render(content.String()) +} + +// styleCodeLine applies syntax highlighting to a code line +func (m IntegrationsModel) styleCodeLine(line string) string { + // Bracket and brace styling + if line == "{" || line == "}" || line == "[" || line == "]" || + strings.HasSuffix(line, "{") || strings.HasSuffix(line, "},") || + strings.HasSuffix(line, "}") || strings.HasSuffix(line, "],") || + line == " }]" || line == " }]," { + return lipgloss.NewStyle().Foreground(Violet).Render(line) + } + + // Key-value pairs + if strings.Contains(line, ":") { + parts := strings.SplitN(line, ":", 2) + if len(parts) == 2 { + // Style the key (usually in quotes) + keyStyle := lipgloss.NewStyle().Foreground(Cyan) + valueStyle := lipgloss.NewStyle().Foreground(NeonGreen) + colonStyle := lipgloss.NewStyle().Foreground(TextMuted) + + return keyStyle.Render(parts[0]) + colonStyle.Render(":") + valueStyle.Render(parts[1]) + } + } + + // TOML sections + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + return lipgloss.NewStyle().Foreground(Magenta).Bold(true).Render(line) + } + + // TOML key-value + if strings.Contains(line, " = ") { + parts := strings.SplitN(line, " = ", 2) + if len(parts) == 2 { + keyStyle := lipgloss.NewStyle().Foreground(Cyan) + valueStyle := lipgloss.NewStyle().Foreground(NeonGreen) + eqStyle := lipgloss.NewStyle().Foreground(TextMuted) + + return keyStyle.Render(parts[0]) + eqStyle.Render(" = ") + valueStyle.Render(parts[1]) + } + } + + // Default code styling + return lipgloss.NewStyle().Foreground(NeonGreen).Render(line) +} + +// renderHelp renders the help footer with cyber styling +func (m IntegrationsModel) renderHelp() string { + divider := lipgloss.NewStyle().Foreground(BorderDim).Render(strings.Repeat("─", min(m.width-4, 70))) + + helpItems := []struct { + key string + desc string + }{ + {" / ", "Navigate"}, + {"Enter", "Expand/Collapse"}, + {"Esc", "Back"}, + } + + var helpParts []string + for _, item := range helpItems { + key := lipgloss.NewStyle(). + Foreground(Cyan). + Background(Surface). + Bold(true). + Padding(0, 1). + Render(item.key) + desc := lipgloss.NewStyle().Foreground(TextDim).Render(" " + item.desc) + helpParts = append(helpParts, key+desc) + } + + helpLine := strings.Join(helpParts, " ") + + return "\n" + divider + "\n" + helpLine +} diff --git a/internal/tui/login.go b/internal/tui/login.go index 25216493..9d9bcdf1 100644 --- a/internal/tui/login.go +++ b/internal/tui/login.go @@ -13,6 +13,32 @@ import ( coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" ) +// Provider brand colors are defined in styles.go + +// getProviderColor returns the brand color for a provider +func getProviderColor(providerID string) lipgloss.Color { + switch providerID { + case "claude": + return ClaudeBrand + case "codex": + return CodexBrand + case "gemini": + return GeminiBrand + case "kiro": + return KiroBrand + case "qwen": + return QwenBrand + case "antigravity": + return AntigravityBrand + case "minimax": + return MiniMaxBrand + case "zhipu": + return ZhipuBrand + default: + return Cyan + } +} + // ProviderInfo holds display information for a provider type ProviderInfo struct { ID string @@ -244,83 +270,248 @@ func (m LoginModel) startLogin(providerID string) tea.Cmd { } } -// View renders the login screen +// ═══════════════════════════════════════════════════════════════════════════════ +// VIEW RENDERING - Returns content only (no outer borders) +// The main TUI wraps this in a bordered panel +// ═══════════════════════════════════════════════════════════════════════════════ + +// View renders the login screen content func (m LoginModel) View() string { + return m.ViewWithSize(m.width, m.height) +} + +// ViewWithSize renders with explicit dimensions for responsive layout +func (m LoginModel) ViewWithSize(width, height int) string { var b strings.Builder - // Title - b.WriteString(TitleStyle.Render("Provider Login")) - b.WriteString("\n") - - // Divider - b.WriteString(lipgloss.NewStyle().Foreground(BorderColor).Render(strings.Repeat("\u2500", 40))) - b.WriteString("\n\n") + // Section title (compact) + title := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("Provider Authentication") + subtitle := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(" - Connect via OAuth") + b.WriteString(title + subtitle + "\n\n") + // Loading state if m.loading { - b.WriteString(SpinnerStyle.Render("Loading authentication status...")) - b.WriteString("\n") - } else if m.loggingIn { - b.WriteString(SpinnerStyle.Render(fmt.Sprintf("Logging in to %s...", m.loginProvider))) - b.WriteString("\n") - b.WriteString(Muted("Please complete authentication in your browser.")) - b.WriteString("\n") - } else { - // Provider list - for i, provider := range m.providers { - var line string - cursor := " " - if i == m.cursor { - cursor = "> " - } - - // Provider name - name := provider.Name - - // Status indicator - var status string - if provider.Authenticated { - statusText := "Authenticated" - if provider.Email != "" { - statusText = provider.Email - } - status = Success(fmt.Sprintf("[%s %s]", "\u2713", statusText)) - } else { - status = Error(fmt.Sprintf("[%s Not logged in]", "\u2717")) - } - - // Pad the name for alignment - paddedName := fmt.Sprintf("%-15s", name) - - if i == m.cursor { - line = CursorStyle.Render(cursor) + Primary(paddedName) + " " + status - } else { - line = Dim(cursor) + paddedName + " " + status - } - - b.WriteString(line) - b.WriteString("\n") - } + b.WriteString(lipgloss.NewStyle().Foreground(Accent).Render("◐") + " ") + b.WriteString(lipgloss.NewStyle().Foreground(TextMuted).Render("Scanning authentication status...")) + return b.String() } - // Message area + // Logging in state + if m.loggingIn { + providerColor := getProviderColor(m.loginProvider) + b.WriteString(lipgloss.NewStyle().Foreground(providerColor).Bold(true).Render("◐") + " ") + b.WriteString(lipgloss.NewStyle().Foreground(Text).Render(fmt.Sprintf("Authenticating with %s...", m.loginProvider))) + b.WriteString("\n") + b.WriteString(lipgloss.NewStyle().Foreground(TextMuted).Render("Complete authentication in your browser")) + return b.String() + } + + // Calculate visible rows based on height + maxRows := height - 5 + if maxRows < 4 { + maxRows = 4 + } + if maxRows > len(m.providers) { + maxRows = len(m.providers) + } + + // Provider list - responsive rows + for i := 0; i < maxRows; i++ { + if i >= len(m.providers) { + break + } + provider := m.providers[i] + isSelected := i == m.cursor + row := m.renderProviderRowWithWidth(provider, isSelected, width) + b.WriteString(row + "\n") + } + + // Status message if m.message != "" { b.WriteString("\n") if m.messageIsError { - b.WriteString(Error(m.message)) + b.WriteString(lipgloss.NewStyle().Foreground(Red).Render(IconCross + " " + m.message)) } else { - b.WriteString(Success(m.message)) + b.WriteString(lipgloss.NewStyle().Foreground(Green).Render(IconCheck + " " + m.message)) } - b.WriteString("\n") } - // Help text - b.WriteString("\n") - helpText := "[Enter] Login [r] Refresh [Esc] Back [q] Quit" - b.WriteString(HelpStyle.Render(helpText)) - return b.String() } +// renderProviderRow creates a simple row for the provider list +func (m LoginModel) renderProviderRow(provider ProviderInfo, isSelected bool) string { + return m.renderProviderRowWithWidth(provider, isSelected, m.width) +} + +// renderProviderRowWithWidth creates a row that adapts to available width +func (m LoginModel) renderProviderRowWithWidth(provider ProviderInfo, isSelected bool, width int) string { + providerColor := getProviderColor(provider.ID) + + // Cursor indicator + var cursor string + if isSelected { + cursor = lipgloss.NewStyle().Foreground(Accent).Bold(true).Render(IconChevron + " ") + } else { + cursor = " " + } + + // Calculate responsive widths based on available space + nameWidth := 12 + if width > 60 { + nameWidth = 16 + } + if width > 80 { + nameWidth = 18 + } + + // Provider name + var nameStyle lipgloss.Style + if isSelected { + nameStyle = lipgloss.NewStyle().Foreground(providerColor).Bold(true).Width(nameWidth) + } else { + nameStyle = lipgloss.NewStyle().Foreground(Text).Width(nameWidth) + } + name := nameStyle.Render(provider.Name) + + // Status badge - use shorter text on narrow terminals + var status string + if provider.Authenticated { + if width > 50 { + status = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Green). + Bold(true). + Padding(0, 1). + Render(IconOnline + " CONNECTED") + } else { + status = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Green). + Bold(true). + Padding(0, 1). + Render(IconOnline) + } + } else { + if width > 50 { + status = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Red). + Bold(true). + Padding(0, 1). + Render(IconOffline + " DISCONNECTED") + } else { + status = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Red). + Bold(true). + Padding(0, 1). + Render(IconOffline) + } + } + + // Email info - only show on wider terminals + var emailInfo string + if width > 70 && provider.Authenticated && provider.Email != "" { + // Truncate email if terminal is not wide enough + email := provider.Email + maxEmailLen := width - nameWidth - 30 // Reserve space for cursor, name, status + if maxEmailLen < 10 { + maxEmailLen = 10 + } + if len(email) > maxEmailLen { + email = email[:maxEmailLen-3] + "..." + } + emailInfo = lipgloss.NewStyle().Foreground(TextMuted).Render(" " + email) + } + + // Compose row + row := cursor + name + status + emailInfo + + // Selection highlight + if isSelected { + row = lipgloss.NewStyle().Background(BgSelected).Render(row) + } + + return row +} + +// renderStatusBadge creates a styled status badge for auth state +func (m LoginModel) renderStatusBadge(provider ProviderInfo) string { + if provider.Authenticated { + // Connected badge - NeonGreen with filled circle + return lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(NeonGreen). + Bold(true). + Padding(0, 1). + Render(IconOnline + " CONNECTED") + } + + // Disconnected badge - HotCoral with hollow circle + return lipgloss.NewStyle(). + Foreground(TextBright). + Background(HotCoral). + Bold(true). + Padding(0, 1). + Render(IconOffline + " DISCONNECTED") +} + +// renderKeyInfo displays masked key or email info +func (m LoginModel) renderKeyInfo(provider ProviderInfo) string { + keyStyle := lipgloss.NewStyle().Foreground(TextDim) + valueStyle := lipgloss.NewStyle().Foreground(TextMuted) + + if provider.Email != "" { + // Show email + return keyStyle.Render("Email: ") + valueStyle.Render(provider.Email) + } + + // Show masked key placeholder + maskedKey := "****-****-****-" + lipgloss.NewStyle().Foreground(Cyan).Render("****") + return keyStyle.Render("Token: ") + maskedKey +} + +// renderActionHints creates the keyboard shortcut hints +func (m LoginModel) renderActionHints() string { + keyStyle := lipgloss.NewStyle(). + Foreground(Violet). + Background(Surface). + Bold(true). + Padding(0, 1) + + descStyle := lipgloss.NewStyle(). + Foreground(TextDim) + + separator := lipgloss.NewStyle().Foreground(BorderDim).Render(" ") + + hints := []struct { + key string + desc string + }{ + {"Enter", "Login"}, + {"r", "Refresh"}, + {"Esc", "Back"}, + {"q", "Quit"}, + } + + var parts []string + for _, hint := range hints { + parts = append(parts, keyStyle.Render(hint.key)+descStyle.Render(" "+hint.desc)) + } + + return strings.Join(parts, separator) +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// PUBLIC ACCESSOR METHODS +// ═══════════════════════════════════════════════════════════════════════════════ + // GetSelectedProvider returns the currently selected provider ID func (m LoginModel) GetSelectedProvider() string { if m.cursor >= 0 && m.cursor < len(m.providers) { diff --git a/internal/tui/logs.go b/internal/tui/logs.go new file mode 100644 index 00000000..6ffd176b --- /dev/null +++ b/internal/tui/logs.go @@ -0,0 +1,534 @@ +package tui + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/bubbles/viewport" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// LOGS VIEWER - Cyberpunk Neon Edition +// A visually stunning log viewer with electric neon aesthetics +// ═══════════════════════════════════════════════════════════════════════════════ + +// LogEntry represents a single log entry +type LogEntry struct { + Timestamp time.Time + Level string + Message string + Fields map[string]interface{} +} + +// LogsModel represents the logs viewer screen +type LogsModel struct { + width int + height int + viewport viewport.Model + logs []LogEntry + filter string + levels []string + selected int + + // Auto-scroll state + autoScroll bool + lastRefresh time.Time + + // Animation state for pulsing effect + pulseFrame int +} + +// logsRefreshMsg is sent when logs are refreshed +type logsRefreshMsg struct { + logs []LogEntry +} + +// logsTickMsg triggers periodic refresh +type logsTickMsg time.Time + +// logsPulseMsg triggers pulse animation +type logsPulseMsg time.Time + +// ───────────────────────────────────────────────────────────────────────────── +// Log Level Badge Styles - Vibrant neon indicators +// ───────────────────────────────────────────────────────────────────────────── + +var ( + // Error badge - Hot Coral with glow effect + logErrorBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(HotCoral). + Bold(true). + Padding(0, 1) + + // Warning badge - Warm Amber + logWarnBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(Amber). + Bold(true). + Padding(0, 1) + + // Info badge - Electric Blue + logInfoBadge = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(ElecBlue). + Bold(true). + Padding(0, 1) + + // Debug badge - Soft Violet + logDebugBadge = lipgloss.NewStyle(). + Foreground(TextBright). + Background(Violet). + Bold(true). + Padding(0, 1) + + // Default log badge - Muted + logDefaultBadge = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(Surface). + Padding(0, 1) + + // Timestamp style - Dim for subtle time display + timestampStyle = lipgloss.NewStyle(). + Foreground(TextDim) + + // Log message style + logMessageStyle = lipgloss.NewStyle(). + Foreground(TextBright) + + // Filter tab styles + filterTabActive = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(Cyan). + Bold(true). + Padding(0, 2). + MarginRight(1) + + filterTabInactive = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(Surface). + Padding(0, 2). + MarginRight(1) + + // Status indicator styles + autoScrollOnStyle = lipgloss.NewStyle(). + Foreground(NeonGreen). + Bold(true) + + autoScrollOffStyle = lipgloss.NewStyle(). + Foreground(TextDim) + + // Pulse animation colors for auto-scroll indicator + pulseColors = []lipgloss.Color{ + NeonGreen, + GreenMid, + GreenDark, + GreenMid, + NeonGreen, + GreenMid, + } + + // Log viewer title style + logViewerTitle = lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true) + + // Section separator with neon accent + sectionSeparator = lipgloss.NewStyle(). + Foreground(Violet) + + // Status bar container + statusBarContainer = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(DarkSurface). + Padding(0, 1) + + // Log count style + logCountStyle = lipgloss.NewStyle(). + Foreground(Magenta). + Bold(true) + + // Refresh timestamp style + refreshTimeStyle = lipgloss.NewStyle(). + Foreground(TextDim) + + // Empty state style + emptyStateStyle = lipgloss.NewStyle(). + Foreground(TextMuted). + Italic(true) +) + +// NewLogsModel creates a new logs viewer model +func NewLogsModel() LogsModel { + vp := viewport.New(70, 15) + vp.Style = lipgloss.NewStyle(). + Border(CyberBorder). + BorderForeground(Cyan). + Padding(0, 1) + + return LogsModel{ + width: 80, + height: 24, + viewport: vp, + logs: []LogEntry{}, + levels: []string{"all", "info", "warn", "error", "debug"}, + selected: 0, + autoScroll: true, + lastRefresh: time.Now(), + pulseFrame: 0, + } +} + +// Init initializes the logs model +func (m LogsModel) Init() tea.Cmd { + return tea.Batch( + m.refreshLogs, + m.tickCmd(), + m.pulseCmd(), + ) +} + +// tickCmd returns a command for periodic refresh +func (m LogsModel) tickCmd() tea.Cmd { + return tea.Tick(2*time.Second, func(t time.Time) tea.Msg { + return logsTickMsg(t) + }) +} + +// pulseCmd returns a command for pulse animation +func (m LogsModel) pulseCmd() tea.Cmd { + return tea.Tick(150*time.Millisecond, func(t time.Time) tea.Msg { + return logsPulseMsg(t) + }) +} + +// refreshLogs fetches current logs +func (m LogsModel) refreshLogs() tea.Msg { + // TODO: Implement log ring buffer in logging package + // For now, show sample logs to demonstrate the UI + logs := []LogEntry{ + {Timestamp: time.Now().Add(-10 * time.Minute), Level: "info", Message: "Initializing ProxyPilot server..."}, + {Timestamp: time.Now().Add(-9 * time.Minute), Level: "debug", Message: "Loading configuration from config.yaml"}, + {Timestamp: time.Now().Add(-8 * time.Minute), Level: "info", Message: "Server started on :8317"}, + {Timestamp: time.Now().Add(-7 * time.Minute), Level: "info", Message: "Claude provider initialized successfully"}, + {Timestamp: time.Now().Add(-6 * time.Minute), Level: "warn", Message: "Rate limit threshold approaching for claude-sonnet"}, + {Timestamp: time.Now().Add(-5 * time.Minute), Level: "info", Message: "Gemini provider initialized successfully"}, + {Timestamp: time.Now().Add(-4 * time.Minute), Level: "debug", Message: "Health check endpoint responding normally"}, + {Timestamp: time.Now().Add(-3 * time.Minute), Level: "info", Message: "Management API enabled on /api/v1"}, + {Timestamp: time.Now().Add(-2 * time.Minute), Level: "error", Message: "Connection refused to backup endpoint"}, + {Timestamp: time.Now().Add(-1 * time.Minute), Level: "warn", Message: "Retry attempt 1/3 for backup connection"}, + {Timestamp: time.Now(), Level: "info", Message: "Ready to accept connections"}, + } + + return logsRefreshMsg{logs: logs} +} + +// Update handles messages for the logs model +func (m LogsModel) Update(msg tea.Msg) (LogsModel, tea.Cmd) { + var cmd tea.Cmd + var cmds []tea.Cmd + + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + m.viewport.Width = max(m.width-10, 40) + m.viewport.Height = max(m.height-18, 8) + m.viewport.Style = lipgloss.NewStyle(). + Border(CyberBorder). + BorderForeground(Cyan). + Padding(0, 1). + Width(m.viewport.Width) + return m, nil + + case tea.KeyMsg: + switch msg.String() { + case "tab": + m.selected = (m.selected + 1) % len(m.levels) + m.updateViewport() + case "shift+tab": + m.selected = (m.selected - 1 + len(m.levels)) % len(m.levels) + m.updateViewport() + case "a": + m.autoScroll = !m.autoScroll + case "r": + return m, m.refreshLogs + case "g": + m.viewport.GotoTop() + case "G": + m.viewport.GotoBottom() + } + + case logsPulseMsg: + m.pulseFrame = (m.pulseFrame + 1) % len(pulseColors) + cmds = append(cmds, m.pulseCmd()) + + case logsTickMsg: + cmds = append(cmds, m.tickCmd()) + if m.autoScroll { + cmds = append(cmds, m.refreshLogs) + } + + case logsRefreshMsg: + m.logs = msg.logs + m.lastRefresh = time.Now() + m.updateViewport() + if m.autoScroll { + m.viewport.GotoBottom() + } + } + + // Handle viewport scrolling + m.viewport, cmd = m.viewport.Update(msg) + cmds = append(cmds, cmd) + + return m, tea.Batch(cmds...) +} + +// updateViewport updates the viewport content based on current filter +func (m *LogsModel) updateViewport() { + var content strings.Builder + + filterLevel := m.levels[m.selected] + + for _, log := range m.logs { + // Apply filter + if filterLevel != "all" && log.Level != filterLevel { + continue + } + + // Format log entry + line := m.formatLogEntry(log, m.width) + content.WriteString(line) + content.WriteString("\n") + } + + if content.Len() == 0 { + content.WriteString(emptyStateStyle.Render(" No logs matching current filter")) + } + + m.viewport.SetContent(content.String()) +} + +// formatLogEntry formats a single log entry with cyberpunk styling +func (m LogsModel) formatLogEntry(entry LogEntry, width int) string { + // Timestamp with dim styling + ts := entry.Timestamp.Format("15:04:05.000") + formattedTs := timestampStyle.Render(ts) + + // Level badge with vibrant colors + var levelBadge string + switch entry.Level { + case "error": + levelBadge = logErrorBadge.Render("ERR") + case "warn", "warning": + levelBadge = logWarnBadge.Render("WRN") + case "info": + levelBadge = logInfoBadge.Render("INF") + case "debug": + levelBadge = logDebugBadge.Render("DBG") + default: + levelBadge = logDefaultBadge.Render("LOG") + } + + // Message with appropriate styling based on level + msg := entry.Message + maxLen := width - 30 // Reserve space for timestamp and level badge + if maxLen < 20 { + maxLen = 20 + } + if len(msg) > maxLen { + msg = msg[:maxLen-3] + "..." + } + + // Color message based on level for emphasis + var formattedMsg string + switch entry.Level { + case "error": + formattedMsg = lipgloss.NewStyle().Foreground(HotCoral).Render(msg) + case "warn", "warning": + formattedMsg = lipgloss.NewStyle().Foreground(Amber).Render(msg) + default: + formattedMsg = logMessageStyle.Render(msg) + } + + // Build the line with proper spacing + return fmt.Sprintf(" %s %s %s", formattedTs, levelBadge, formattedMsg) +} + +// View renders the logs viewer screen - Returns content only (no outer borders) +// The main TUI wraps this in a bordered panel +func (m LogsModel) View() string { + return m.ViewWithSize(m.width, m.height) +} + +// ViewWithSize renders the logs viewer screen with specified dimensions +func (m LogsModel) ViewWithSize(width, height int) string { + var b strings.Builder + + // Section title + title := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("Logs") + subtitle := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(" - Real-time stream") + b.WriteString(title + subtitle + "\n\n") + + // Filter tabs + b.WriteString(m.renderFilterTabs()) + b.WriteString("\n\n") + + // Status bar + b.WriteString(m.renderStatusBar()) + b.WriteString("\n\n") + + // Log entries (rendered directly, not in viewport with its own border) + b.WriteString(m.renderLogEntries(width, height)) + + return b.String() +} + +// renderLogEntries renders log entries directly without viewport borders +func (m LogsModel) renderLogEntries(width, height int) string { + var content strings.Builder + + filterLevel := m.levels[m.selected] + count := 0 + maxVisible := height - 8 // Reserve space for header, tabs, status bar, etc. + if maxVisible < 5 { + maxVisible = 5 + } + + // Collect filtered entries + var filtered []LogEntry + for _, log := range m.logs { + if filterLevel != "all" && log.Level != filterLevel { + continue + } + filtered = append(filtered, log) + } + + // Show most recent entries + start := 0 + if len(filtered) > maxVisible { + start = len(filtered) - maxVisible + } + + for i := start; i < len(filtered); i++ { + line := m.formatLogEntry(filtered[i], width) + content.WriteString(line + "\n") + count++ + } + + if count == 0 { + content.WriteString(lipgloss.NewStyle().Foreground(TextMuted).Italic(true).Render("No logs matching current filter")) + } + + return content.String() +} + +// renderFilterTabs renders the log level filter tabs +func (m LogsModel) renderFilterTabs() string { + var tabs []string + + // Level labels + levelLabels := map[string]string{ + "all": "ALL", + "info": "INF", + "warn": "WRN", + "error": "ERR", + "debug": "DBG", + } + + // Level-specific colors + levelColors := map[string]lipgloss.Color{ + "all": Accent, + "info": Blue, + "warn": Yellow, + "error": Red, + "debug": Secondary, + } + + for i, level := range m.levels { + label := levelLabels[level] + + if i == m.selected { + style := lipgloss.NewStyle(). + Foreground(BgDark). + Background(levelColors[level]). + Bold(true). + Padding(0, 1) + tabs = append(tabs, style.Render(label)) + } else { + style := lipgloss.NewStyle(). + Foreground(TextMuted). + Background(BgPanel). + Padding(0, 1) + tabs = append(tabs, style.Render(label)) + } + } + + return lipgloss.JoinHorizontal(lipgloss.Top, tabs...) +} + +// renderStatusBar renders the status bar +func (m LogsModel) renderStatusBar() string { + // Log count + filteredCount := 0 + filterLevel := m.levels[m.selected] + for _, log := range m.logs { + if filterLevel == "all" || log.Level == filterLevel { + filteredCount++ + } + } + + countText := lipgloss.NewStyle().Foreground(TextMuted).Render(fmt.Sprintf("Showing %d entries", filteredCount)) + + // Auto-scroll indicator + var scrollText string + if m.autoScroll { + scrollText = lipgloss.NewStyle().Foreground(Green).Render("● AUTO") + } else { + scrollText = lipgloss.NewStyle().Foreground(TextMuted).Render("○ PAUSED") + } + + // Last refresh + refreshText := lipgloss.NewStyle().Foreground(TextMuted).Render(fmt.Sprintf("Updated: %s", m.lastRefresh.Format("15:04:05"))) + + sep := lipgloss.NewStyle().Foreground(BorderDim).Render(" │ ") + return countText + sep + scrollText + sep + refreshText +} + +// renderHelp renders the help footer with neon key hints +func (m LogsModel) renderHelp() string { + helpItems := []struct { + key string + desc string + }{ + {"Tab", "Filter"}, + {"↑/↓", "Scroll"}, + {"g/G", "Top/Bottom"}, + {"a", "Auto-scroll"}, + {"r", "Refresh"}, + {"Esc", "Back"}, + } + + var parts []string + for _, item := range helpItems { + key := lipgloss.NewStyle(). + Foreground(Violet). + Bold(true). + Render("[" + item.key + "]") + desc := lipgloss.NewStyle(). + Foreground(TextDim). + Render(" " + item.desc) + parts = append(parts, key+desc) + } + + return strings.Join(parts, " ") +} diff --git a/internal/tui/mappings.go b/internal/tui/mappings.go new file mode 100644 index 00000000..ccafa669 --- /dev/null +++ b/internal/tui/mappings.go @@ -0,0 +1,354 @@ +package tui + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// NEON TABLE STYLES - Cyberpunk-inspired data presentation +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + // Table header with electric cyan and violet underline + neonTableHeader = lipgloss.NewStyle(). + Bold(true). + Foreground(Cyan). + BorderStyle(lipgloss.NormalBorder()). + BorderBottom(true). + BorderForeground(Violet). + PaddingBottom(0). + MarginBottom(0) + + // Selected row with glowing cyan highlight + selectedRowStyle = lipgloss.NewStyle(). + Background(BgSelected). + Foreground(Cyan). + Bold(true) + + // Normal row styling + normalRowStyle = lipgloss.NewStyle(). + Foreground(TextBright) + + // Alias column - primary focus element + aliasBaseStyle = lipgloss.NewStyle(). + Width(28) + + // Provider column + providerBaseStyle = lipgloss.NewStyle(). + Width(14) + + // Model column + modelBaseStyle = lipgloss.NewStyle(). + Width(36) + + // Cursor styles + cursorActive = lipgloss.NewStyle(). + Foreground(Magenta). + Bold(true) + + cursorInactive = lipgloss.NewStyle(). + Foreground(TextDim) + + // Scroll indicator style + scrollIndicatorStyle = lipgloss.NewStyle(). + Foreground(Violet). + Background(DarkSurface). + Padding(0, 1) + + // Section divider with neon effect + neonDivider = lipgloss.NewStyle(). + Foreground(Violet) +) + +// ModelMapping represents a single model alias mapping +type ModelMapping struct { + Alias string + Provider string + Model string + Active bool +} + +// MappingsModel represents the model mappings screen +type MappingsModel struct { + width int + height int + cursor int + mappings []ModelMapping + cfg *config.Config +} + +// NewMappingsModel creates a new model mappings model +func NewMappingsModel(cfg *config.Config) MappingsModel { + m := MappingsModel{ + width: 80, + height: 24, + cfg: cfg, + } + m.loadMappings() + return m +} + +// loadMappings loads model mappings from config +func (m *MappingsModel) loadMappings() { + m.mappings = []ModelMapping{} + + // Default mappings that ProxyPilot supports + defaultMappings := []ModelMapping{ + // Claude models + {Alias: "claude-3-opus", Provider: "Claude", Model: "claude-3-opus-20240229", Active: true}, + {Alias: "claude-3-sonnet", Provider: "Claude", Model: "claude-3-sonnet-20240229", Active: true}, + {Alias: "claude-3-haiku", Provider: "Claude", Model: "claude-3-haiku-20240307", Active: true}, + {Alias: "claude-opus-4-5-20251101", Provider: "Claude", Model: "claude-opus-4-5-20251101", Active: true}, + {Alias: "claude-sonnet-4-5-20251101", Provider: "Claude", Model: "claude-sonnet-4-5-20251101", Active: true}, + + // GPT models + {Alias: "gpt-4", Provider: "Codex", Model: "gpt-4", Active: true}, + {Alias: "gpt-4-turbo", Provider: "Codex", Model: "gpt-4-turbo", Active: true}, + {Alias: "gpt-4o", Provider: "Codex", Model: "gpt-4o", Active: true}, + {Alias: "o1", Provider: "Codex", Model: "o1", Active: true}, + {Alias: "o1-mini", Provider: "Codex", Model: "o1-mini", Active: true}, + + // Gemini models + {Alias: "gemini-pro", Provider: "Gemini", Model: "gemini-pro", Active: true}, + {Alias: "gemini-1.5-pro", Provider: "Gemini", Model: "gemini-1.5-pro", Active: true}, + {Alias: "gemini-1.5-flash", Provider: "Gemini", Model: "gemini-1.5-flash", Active: true}, + {Alias: "gemini-2.0-flash", Provider: "Gemini", Model: "gemini-2.0-flash-exp", Active: true}, + } + + m.mappings = defaultMappings + + // Note: Custom mappings can be added via config.yaml + // The ModelMapping field would be added to config if needed +} + +// Init initializes the mappings model +func (m MappingsModel) Init() tea.Cmd { + return nil +} + +// Update handles messages for the mappings model +func (m MappingsModel) Update(msg tea.Msg) (MappingsModel, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + return m, nil + + case tea.KeyMsg: + switch msg.String() { + case "up", "k": + if m.cursor > 0 { + m.cursor-- + } + case "down", "j": + if m.cursor < len(m.mappings)-1 { + m.cursor++ + } + case "g": + m.cursor = 0 + case "G": + m.cursor = len(m.mappings) - 1 + } + } + + return m, nil +} + +// View renders the model mappings screen - Returns content only (no outer borders) +// The main TUI wraps this in a bordered panel +func (m MappingsModel) View() string { + return m.ViewWithSize(m.width, m.height) +} + +// ViewWithSize renders the model mappings screen with specified dimensions +// This allows for responsive layouts based on terminal size +func (m MappingsModel) ViewWithSize(width, height int) string { + var b strings.Builder + + // Calculate responsive column widths based on available width + aliasWidth, providerWidth, modelWidth := m.calculateColumnWidths(width) + + // Section title (compact) + title := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("Model Mappings") + subtitle := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(" - Alias → Provider Model") + b.WriteString(title + subtitle + "\n\n") + + // Table header with responsive widths + headerAlias := lipgloss.NewStyle().Width(aliasWidth).Foreground(Accent).Bold(true).Render(" ALIAS") + headerProvider := lipgloss.NewStyle().Width(providerWidth).Foreground(Accent).Bold(true).Render("PROVIDER") + headerModel := lipgloss.NewStyle().Width(modelWidth).Foreground(Accent).Bold(true).Render("MODEL") + b.WriteString(headerAlias + headerProvider + headerModel + "\n") + + // Divider width matches total table width + dividerWidth := aliasWidth + providerWidth + modelWidth + b.WriteString(lipgloss.NewStyle().Foreground(BorderDim).Render(strings.Repeat("─", dividerWidth)) + "\n") + + // Calculate max visible rows based on height + // Reserve lines for: title (2), header (1), divider (1), scroll indicator (2) + maxRows := height - 6 + if maxRows < 3 { + maxRows = 3 // Minimum visible rows + } + + visibleRows := min(maxRows, len(m.mappings)) + startIdx := 0 + if m.cursor >= visibleRows { + startIdx = m.cursor - visibleRows + 1 + } + + for i := startIdx; i < min(startIdx+visibleRows, len(m.mappings)); i++ { + mapping := m.mappings[i] + isSelected := i == m.cursor + row := m.renderMappingRowWithWidths(mapping, isSelected, aliasWidth, providerWidth, modelWidth) + b.WriteString(row + "\n") + } + + // Scroll indicator + if len(m.mappings) > visibleRows { + endIdx := min(startIdx+visibleRows, len(m.mappings)) + scrollText := fmt.Sprintf("%d-%d of %d", startIdx+1, endIdx, len(m.mappings)) + b.WriteString(lipgloss.NewStyle().Foreground(TextMuted).Render("\n" + scrollText)) + } + + return b.String() +} + +// calculateColumnWidths returns responsive column widths based on terminal width +func (m MappingsModel) calculateColumnWidths(width int) (aliasWidth, providerWidth, modelWidth int) { + // Narrow terminals (< 60) + if width < 60 { + aliasWidth = 16 + providerWidth = 10 + modelWidth = 20 + return + } + + // Medium terminals (60-80) + if width <= 80 { + aliasWidth = 24 + providerWidth = 12 + modelWidth = 30 + return + } + + // Wide terminals (> 80) + aliasWidth = 28 + providerWidth = 14 + modelWidth = 36 + return +} + +// renderMappingRow creates a simple row for the mappings list (uses default widths) +func (m MappingsModel) renderMappingRow(mapping ModelMapping, isSelected bool) string { + return m.renderMappingRowWithWidths(mapping, isSelected, 24, 12, 30) +} + +// renderMappingRowWithWidths creates a row with specified column widths +func (m MappingsModel) renderMappingRowWithWidths(mapping ModelMapping, isSelected bool, aliasWidth, providerWidth, modelWidth int) string { + // Cursor indicator (takes 2 chars from alias width) + var cursor string + if isSelected { + cursor = lipgloss.NewStyle().Foreground(Accent).Bold(true).Render(IconChevron + " ") + } else { + cursor = " " + } + + // Alias (subtract 2 for cursor) + aliasContentWidth := aliasWidth - 2 + var aliasStyle lipgloss.Style + if isSelected { + aliasStyle = lipgloss.NewStyle().Foreground(AccentBright).Bold(true).Width(aliasContentWidth) + } else { + aliasStyle = lipgloss.NewStyle().Foreground(Text).Width(aliasContentWidth) + } + alias := aliasStyle.Render(mapping.Alias) + + // Provider badge + providerBadge := m.renderProviderBadge(mapping.Provider) + providerCell := lipgloss.NewStyle().Width(providerWidth).Render(providerBadge) + + // Model name - truncate based on available width + modelName := mapping.Model + maxModelLen := modelWidth - 2 // Leave some padding + if len(modelName) > maxModelLen { + modelName = modelName[:maxModelLen-3] + "..." + } + modelStyle := lipgloss.NewStyle().Foreground(TextMuted).Width(modelWidth) + model := modelStyle.Render(modelName) + + // Compose row + row := cursor + alias + providerCell + model + + // Selection highlight + if isSelected { + row = lipgloss.NewStyle().Background(BgSelected).Render(row) + } + + return row +} + +// renderProviderBadge creates a styled badge for each provider +func (m MappingsModel) renderProviderBadge(provider string) string { + var badgeStyle lipgloss.Style + var icon string + + switch provider { + case "Claude": + badgeStyle = lipgloss.NewStyle(). + Foreground(ClaudeBrand). + Bold(true) + icon = IconDiamond + " " + case "Codex": + badgeStyle = lipgloss.NewStyle(). + Foreground(CodexBrand). + Bold(true) + icon = IconCircle + " " + case "Gemini": + badgeStyle = lipgloss.NewStyle(). + Foreground(GeminiBrand). + Bold(true) + icon = IconStar + " " + default: + badgeStyle = lipgloss.NewStyle(). + Foreground(TextMuted) + icon = IconSquare + " " + } + + return badgeStyle.Render(icon + provider) +} + +// renderHelp renders the help footer with neon styling +func (m MappingsModel) renderHelp() string { + keyStyle := lipgloss.NewStyle(). + Foreground(Violet). + Bold(true) + + descStyle := lipgloss.NewStyle(). + Foreground(TextDim) + + sepStyle := lipgloss.NewStyle(). + Foreground(TextDim). + Render(" ") + + dividerStyle := lipgloss.NewStyle(). + Foreground(BorderDim) + + // Build help text + help := dividerStyle.Render(strings.Repeat("─", 50)) + "\n" + help += keyStyle.Render("["+IconArrowUp+"/"+IconArrowDown+"]") + " " + descStyle.Render("Navigate") + sepStyle + help += keyStyle.Render("[j/k]") + " " + descStyle.Render("Navigate") + sepStyle + help += keyStyle.Render("[g/G]") + " " + descStyle.Render("Top/Bottom") + sepStyle + help += keyStyle.Render("[Esc]") + " " + descStyle.Render("Back") + + return lipgloss.NewStyle().MarginTop(0).Render(help) +} diff --git a/internal/tui/server.go b/internal/tui/server.go index 0e928d07..ad91fa86 100644 --- a/internal/tui/server.go +++ b/internal/tui/server.go @@ -13,6 +13,10 @@ import ( "github.com/router-for-me/CLIProxyAPI/v6/internal/embedded" ) +// ═══════════════════════════════════════════════════════════════════════════════ +// SERVER CONTROL PANEL - Cyberpunk Neon Edition +// ═══════════════════════════════════════════════════════════════════════════════ + // ServerMenuOption represents an option in the server control menu type ServerMenuOption int @@ -44,6 +48,133 @@ type serverActionResultMsg struct { // serverTickMsg is sent on each tick for polling server status type serverTickMsg time.Time +// ═══════════════════════════════════════════════════════════════════════════════ +// CYBERPUNK STYLES - Neon-infused visual components +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + // Panel title with electric glow + serverTitleStyle = lipgloss.NewStyle(). + Bold(true). + Foreground(Cyan). + Background(DarkSurface). + Padding(0, 2). + MarginBottom(1) + + // Main control panel container + controlPanelStyle = lipgloss.NewStyle(). + Border(CyberBorder). + BorderForeground(Cyan). + Background(DeepBlack). + Padding(1, 3). + MarginBottom(1) + + // Status panel with neon border + statusPanelStyle = lipgloss.NewStyle(). + Border(SoftBorder). + BorderForeground(Violet). + Background(DarkSurface). + Padding(1, 2). + MarginBottom(1) + + // Glowing status indicator - RUNNING + runningBadgeStyle = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(NeonGreen). + Bold(true). + Padding(0, 2) + + // Glowing status indicator - STOPPED + stoppedBadgeStyle = lipgloss.NewStyle(). + Foreground(TextBright). + Background(HotCoral). + Bold(true). + Padding(0, 2) + + // Action buttons - Normal state + actionButtonStyle = lipgloss.NewStyle(). + Foreground(TextMuted). + Padding(0, 1) + + // Action buttons - Selected/Focused + actionButtonSelectedStyle = lipgloss.NewStyle(). + Foreground(DeepBlack). + Background(Cyan). + Bold(true). + Padding(0, 2) + + // Action buttons - Disabled + actionButtonDisabledStyle = lipgloss.NewStyle(). + Foreground(TextDim). + Background(Surface). + Padding(0, 1) + + // Cursor arrow with magenta glow + cursorActiveStyle = lipgloss.NewStyle(). + Foreground(Magenta). + Bold(true) + + // Data labels + labelStyle = lipgloss.NewStyle(). + Foreground(TextMuted). + Width(14) + + // Data values with cyan highlight + valueStyle = lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true) + + // Success message style + successMsgStyle = lipgloss.NewStyle(). + Foreground(NeonGreen). + Bold(true) + + // Error message style + errorMsgStyle = lipgloss.NewStyle(). + Foreground(HotCoral). + Bold(true) + + // Warning message style + warningMsgStyle = lipgloss.NewStyle(). + Foreground(Amber). + Bold(true) + + // Info/uptime style + infoValueStyle = lipgloss.NewStyle(). + Foreground(ElecBlue) + + // Muted path/config style + pathStyle = lipgloss.NewStyle(). + Foreground(TextDim). + Italic(true) + + // Section header + sectionHeaderStyle = lipgloss.NewStyle(). + Foreground(Violet). + Bold(true). + MarginTop(1). + MarginBottom(1) + + // Help key highlight + helpKeyNeonStyle = lipgloss.NewStyle(). + Foreground(Cyan). + Background(Surface). + Bold(true). + Padding(0, 1) + + // Help description + helpDescNeonStyle = lipgloss.NewStyle(). + Foreground(TextDim) + + // Spinner with cyan glow + neonSpinnerStyle = lipgloss.NewStyle(). + Foreground(Cyan) + + // Decorative divider + dividerStyle = lipgloss.NewStyle(). + Foreground(BorderDim) +) + // ServerModel represents the server control screen state type ServerModel struct { status ServerControlStatus @@ -98,8 +229,8 @@ func DefaultServerKeyMap() ServerKeyMap { // NewServerModel creates a new server control model func NewServerModel(configPath, password string) ServerModel { s := spinner.New() - s.Spinner = spinner.Dot - s.Style = SpinnerStyle + s.Spinner = spinner.Points + s.Style = neonSpinnerStyle return ServerModel{ status: ServerControlStatus{ @@ -191,15 +322,15 @@ func (m ServerModel) Update(msg tea.Msg) (ServerModel, tea.Cmd) { case serverActionResultMsg: m.loading = false if msg.success { - m.message = fmt.Sprintf("Server %s successfully", msg.action) - m.msgStyle = lipgloss.NewStyle().Foreground(SuccessColor) + m.message = fmt.Sprintf("%s Server %s successfully", IconCheck, msg.action) + m.msgStyle = successMsgStyle } else { errMsg := "unknown error" if msg.err != nil { errMsg = msg.err.Error() } - m.message = fmt.Sprintf("Failed to %s server: %s", msg.action, errMsg) - m.msgStyle = lipgloss.NewStyle().Foreground(ErrorColor) + m.message = fmt.Sprintf("%s Failed to %s server: %s", IconCross, msg.action, errMsg) + m.msgStyle = errorMsgStyle } // Refresh status after action cmds = append(cmds, m.pollServerStatus()) @@ -239,8 +370,8 @@ func (m ServerModel) handleSelection() (ServerModel, tea.Cmd) { m.message = "" return m, tea.Batch(m.spinner.Tick, m.startServer()) } else { - m.message = "Server is already running" - m.msgStyle = lipgloss.NewStyle().Foreground(WarningColor) + m.message = fmt.Sprintf("%s Server is already running", IconWarning) + m.msgStyle = warningMsgStyle } case ServerMenuOptionStop: @@ -249,8 +380,8 @@ func (m ServerModel) handleSelection() (ServerModel, tea.Cmd) { m.message = "" return m, tea.Batch(m.spinner.Tick, m.stopServer()) } else { - m.message = "Server is not running" - m.msgStyle = lipgloss.NewStyle().Foreground(WarningColor) + m.message = fmt.Sprintf("%s Server is not running", IconWarning) + m.msgStyle = warningMsgStyle } case ServerMenuOptionBack: @@ -301,140 +432,254 @@ func (m ServerModel) IsBackSelected() bool { func (m ServerModel) View() string { var b strings.Builder - // Title - title := TitleStyle.Render("Server Control") + // ═══════════════════════════════════════════════════════════════════════ + // HEADER - Cyberpunk title with neon glow + // ═══════════════════════════════════════════════════════════════════════ + title := m.renderHeader() b.WriteString(title) - b.WriteString("\n") - - // Divider - dividerWidth := lipgloss.Width(title) - if dividerWidth < 20 { - dividerWidth = 20 - } - b.WriteString(Dim(strings.Repeat("-", dividerWidth))) b.WriteString("\n\n") - // Status panel + // ═══════════════════════════════════════════════════════════════════════ + // STATUS PANEL - Server status with glowing indicators + // ═══════════════════════════════════════════════════════════════════════ statusPanel := m.renderStatusPanel() b.WriteString(statusPanel) b.WriteString("\n\n") - // Options menu - b.WriteString(Bold("Options")) - b.WriteString("\n") - b.WriteString(Dim(strings.Repeat("-", 10))) - b.WriteString("\n") + // ═══════════════════════════════════════════════════════════════════════ + // ACTION BUTTONS - Neon-styled control options + // ═══════════════════════════════════════════════════════════════════════ + actionsPanel := m.renderActionsPanel() + b.WriteString(actionsPanel) - for i, opt := range m.options { - cursor := " " - style := MenuItemStyle - - if i == m.cursor { - cursor = Primary("> ") - style = SelectedItemStyle - } - - // Disable start option if running, disable stop if not running - optText := opt - if i == int(ServerMenuOptionStart) && m.status.Running { - style = DisabledItemStyle - optText = opt + " (running)" - } else if i == int(ServerMenuOptionStop) && !m.status.Running { - style = DisabledItemStyle - optText = opt + " (stopped)" - } - - b.WriteString(cursor) - b.WriteString(style.Render(optText)) - b.WriteString("\n") - } - - // Loading indicator + // ═══════════════════════════════════════════════════════════════════════ + // FEEDBACK - Loading/Status messages + // ═══════════════════════════════════════════════════════════════════════ if m.loading { - b.WriteString("\n") - b.WriteString(m.spinner.View()) - b.WriteString(" Processing...") + b.WriteString("\n\n") + loadingText := fmt.Sprintf(" %s %s", m.spinner.View(), lipgloss.NewStyle().Foreground(Cyan).Render("Processing...")) + b.WriteString(loadingText) } - // Status message if m.message != "" && !m.loading { - b.WriteString("\n") - b.WriteString(m.msgStyle.Render(m.message)) + b.WriteString("\n\n") + b.WriteString(" " + m.msgStyle.Render(m.message)) } - // Help text + // ═══════════════════════════════════════════════════════════════════════ + // HELP BAR - Keyboard shortcuts + // ═══════════════════════════════════════════════════════════════════════ b.WriteString("\n\n") - help := m.renderHelp() - b.WriteString(HelpStyle.Render(help)) + help := m.renderHelpBar() + b.WriteString(help) - return BoxStyle.Render(b.String()) + return controlPanelStyle.Render(b.String()) } -// renderStatusPanel renders the server status information panel +// renderHeader renders the cyberpunk header with decorative elements +func (m ServerModel) renderHeader() string { + // Create decorative line + decorLine := lipgloss.NewStyle().Foreground(Violet).Render("━━━") + + // Main title with glow effect + titleText := lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true). + Render(" SERVER CONTROL ") + + // Accent decorations + leftDecor := lipgloss.NewStyle().Foreground(Magenta).Bold(true).Render("[ ") + rightDecor := lipgloss.NewStyle().Foreground(Magenta).Bold(true).Render(" ]") + + header := decorLine + leftDecor + titleText + rightDecor + decorLine + + // Subtitle + subtitle := lipgloss.NewStyle(). + Foreground(TextDim). + Render("ProxyPilot Control Panel") + + return header + "\n" + lipgloss.NewStyle().MarginLeft(4).Render(subtitle) +} + +// renderStatusPanel renders the server status information panel with neon styling func (m ServerModel) renderStatusPanel() string { var b strings.Builder - // Status header - b.WriteString(Bold("Server Status")) + // Section header with icon + sectionIcon := lipgloss.NewStyle().Foreground(ElecBlue).Render(IconServer) + sectionTitle := lipgloss.NewStyle().Foreground(Violet).Bold(true).Render(" STATUS MONITOR") + b.WriteString(sectionIcon + sectionTitle) b.WriteString("\n") - b.WriteString(Dim(strings.Repeat("-", 15))) + b.WriteString(dividerStyle.Render(strings.Repeat("─", 40))) b.WriteString("\n\n") - // Running status with badge - b.WriteString(" Status: ") + // Status indicator with glowing badge + b.WriteString(labelStyle.Render(" Status")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) if m.status.Running { - b.WriteString(SuccessBadge.Render(" RUNNING ")) + statusIcon := lipgloss.NewStyle().Foreground(NeonGreen).Render(IconOnline + " ") + b.WriteString(statusIcon) + b.WriteString(runningBadgeStyle.Render(" RUNNING ")) } else { - b.WriteString(ErrorBadge.Render(" STOPPED ")) + statusIcon := lipgloss.NewStyle().Foreground(HotCoral).Render(IconOffline + " ") + b.WriteString(statusIcon) + b.WriteString(stoppedBadgeStyle.Render(" STOPPED ")) } - b.WriteString("\n") + b.WriteString("\n\n") - // Port number - b.WriteString(" Port: ") - b.WriteString(Primary(fmt.Sprintf("%d", m.status.Port))) - b.WriteString("\n") + // Port number with cyan highlight + b.WriteString(labelStyle.Render(" Port")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) + portValue := fmt.Sprintf(":%d", m.status.Port) + b.WriteString(valueStyle.Render(portValue)) + b.WriteString("\n\n") + + // Endpoint display + b.WriteString(labelStyle.Render(" Endpoint")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) + endpoint := fmt.Sprintf("http://localhost%s", portValue) + endpointStyle := lipgloss.NewStyle().Foreground(Cyan).Underline(true) + b.WriteString(endpointStyle.Render(endpoint)) + b.WriteString("\n\n") // Connected clients - b.WriteString(" Clients: ") - clientsStr := fmt.Sprintf("%d connected", m.status.ConnectedCount) + b.WriteString(labelStyle.Render(" Clients")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) if m.status.ConnectedCount > 0 { - b.WriteString(Success(clientsStr)) + clientStr := fmt.Sprintf("%d connected", m.status.ConnectedCount) + b.WriteString(lipgloss.NewStyle().Foreground(NeonGreen).Bold(true).Render(clientStr)) } else { - b.WriteString(Muted(clientsStr)) + b.WriteString(lipgloss.NewStyle().Foreground(TextMuted).Render("0 connected")) } b.WriteString("\n") // Uptime (if running) if m.status.Running && !m.status.StartedAt.IsZero() { uptime := time.Since(m.status.StartedAt) - b.WriteString(" Uptime: ") - b.WriteString(Info(formatServerUptime(uptime))) b.WriteString("\n") + b.WriteString(labelStyle.Render(" Uptime")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) + b.WriteString(infoValueStyle.Render(formatServerUptime(uptime))) } // Config path if m.status.ConfigPath != "" { - b.WriteString(" Config: ") + b.WriteString("\n\n") + b.WriteString(labelStyle.Render(" Config")) + b.WriteString(lipgloss.NewStyle().Foreground(TextDim).Render(": ")) configDisplay := m.status.ConfigPath - if len(configDisplay) > 40 { - configDisplay = "..." + configDisplay[len(configDisplay)-37:] + if len(configDisplay) > 35 { + configDisplay = "..." + configDisplay[len(configDisplay)-32:] } - b.WriteString(Muted(configDisplay)) + b.WriteString(pathStyle.Render(configDisplay)) + } + + return statusPanelStyle.Render(b.String()) +} + +// renderActionsPanel renders the action buttons with neon styling +func (m ServerModel) renderActionsPanel() string { + var b strings.Builder + + // Section header + sectionIcon := lipgloss.NewStyle().Foreground(Magenta).Render(IconTerminal) + sectionTitle := lipgloss.NewStyle().Foreground(Violet).Bold(true).Render(" ACTIONS") + b.WriteString(sectionIcon + sectionTitle) + b.WriteString("\n") + b.WriteString(dividerStyle.Render(strings.Repeat("─", 40))) + b.WriteString("\n\n") + + // Button icons + buttonIcons := []string{IconBolt, IconSquare, IconArrowLeft} + + for i, opt := range m.options { + isSelected := i == m.cursor + isDisabled := false + displayText := opt + + // Determine if option is disabled + if i == int(ServerMenuOptionStart) && m.status.Running { + isDisabled = true + displayText = opt + " (running)" + } else if i == int(ServerMenuOptionStop) && !m.status.Running { + isDisabled = true + displayText = opt + " (stopped)" + } + + // Render cursor + if isSelected { + cursor := cursorActiveStyle.Render(IconChevron + " ") + b.WriteString(" " + cursor) + } else { + b.WriteString(" ") + } + + // Render button icon + icon := buttonIcons[i] + if isSelected && !isDisabled { + iconStyle := lipgloss.NewStyle().Foreground(Cyan).Bold(true) + b.WriteString(iconStyle.Render(icon) + " ") + } else if isDisabled { + iconStyle := lipgloss.NewStyle().Foreground(TextDim) + b.WriteString(iconStyle.Render(icon) + " ") + } else { + iconStyle := lipgloss.NewStyle().Foreground(TextMuted) + b.WriteString(iconStyle.Render(icon) + " ") + } + + // Render button text + var buttonStyle lipgloss.Style + if isDisabled { + buttonStyle = actionButtonDisabledStyle + } else if isSelected { + buttonStyle = actionButtonSelectedStyle + } else { + buttonStyle = actionButtonStyle + } + + b.WriteString(buttonStyle.Render(displayText)) b.WriteString("\n") } - return RoundedBorder.Render(b.String()) + return b.String() } -// renderHelp renders the help text -func (m ServerModel) renderHelp() string { - parts := []string{ - HelpKeyStyle.Render("^/v") + HelpDescStyle.Render(": navigate"), - HelpKeyStyle.Render("enter") + HelpDescStyle.Render(": select"), - HelpKeyStyle.Render("esc/b") + HelpDescStyle.Render(": back"), - HelpKeyStyle.Render("q") + HelpDescStyle.Render(": quit"), - } - return strings.Join(parts, " ") +// renderHelpBar renders the help text with neon styling +func (m ServerModel) renderHelpBar() string { + var parts []string + + // Navigation keys + navKey := helpKeyNeonStyle.Render("^/v") + navDesc := helpDescNeonStyle.Render(" navigate") + parts = append(parts, navKey+navDesc) + + // Select key + selKey := helpKeyNeonStyle.Render("Enter") + selDesc := helpDescNeonStyle.Render(" select") + parts = append(parts, selKey+selDesc) + + // Back key + backKey := helpKeyNeonStyle.Render("Esc") + backDesc := helpDescNeonStyle.Render(" back") + parts = append(parts, backKey+backDesc) + + // Quit key + quitKey := helpKeyNeonStyle.Render("q") + quitDesc := helpDescNeonStyle.Render(" quit") + parts = append(parts, quitKey+quitDesc) + + // Join with separator + separator := lipgloss.NewStyle().Foreground(BorderDim).Render(" | ") + helpLine := strings.Join(parts, separator) + + // Wrap in subtle container + return lipgloss.NewStyle(). + Foreground(TextDim). + BorderStyle(lipgloss.NormalBorder()). + BorderTop(true). + BorderForeground(BorderDim). + PaddingTop(1). + Render(helpLine) } // formatServerUptime formats a duration in a human-readable way @@ -455,6 +700,10 @@ func formatServerUptime(d time.Duration) string { return fmt.Sprintf("%dd %dh %dm", days, hours, minutes) } +// ═══════════════════════════════════════════════════════════════════════════════ +// SERVER SCREEN - Standalone wrapper for the server control panel +// ═══════════════════════════════════════════════════════════════════════════════ + // ServerScreen wraps ServerModel to implement tea.Model for standalone use type ServerScreen struct { model ServerModel @@ -503,7 +752,12 @@ func (s ServerScreen) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // View renders the server screen func (s ServerScreen) View() string { if s.quitting { - return "Goodbye!\n" + // Styled goodbye message + goodbye := lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true). + Render("Goodbye!") + return goodbye + "\n" } return s.model.View() } diff --git a/internal/tui/styles.go b/internal/tui/styles.go index 12bd3461..1699f569 100644 --- a/internal/tui/styles.go +++ b/internal/tui/styles.go @@ -1,399 +1,464 @@ package tui -import "github.com/charmbracelet/lipgloss" +import ( + "fmt" + + "github.com/charmbracelet/lipgloss" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// PROXYPILOT THEME - Catppuccin Mocha +// Premium dark theme with HIGH CONTRAST visibility +// ═══════════════════════════════════════════════════════════════════════════════ -// Color palette - Clean and professional color scheme var ( - // Primary colors - PrimaryColor = lipgloss.Color("#00D4FF") // Cyan - SecondaryColor = lipgloss.Color("#6C757D") // Gray - AccentColor = lipgloss.Color("#7C3AED") // Purple accent + // ───────────────────────────────────────────────────────────────────────── + // CATPPUCCIN MOCHA - Premium dark theme with HIGH CONTRAST + // ───────────────────────────────────────────────────────────────────────── + + // Backgrounds - 30+ hex levels apart for VISIBLE contrast + BgDark = lipgloss.Color("#1E1E2E") // Base - Catppuccin base + BgPanel = lipgloss.Color("#181825") // Mantle - darker panels + BgSurface = lipgloss.Color("#11111B") // Crust - darkest + BgSelected = lipgloss.Color("#313244") // Surface0 - selection + BgHighlight = lipgloss.Color("#45475A") // Surface1 - hover + + // Borders - MUST BE VISIBLE (bright enough to see!) + Border = lipgloss.Color("#585B70") // Surface2 - VISIBLE! + BorderDim = lipgloss.Color("#45475A") // Surface1 + BorderBright = lipgloss.Color("#6C7086") // Overlay0 + BorderAccent = lipgloss.Color("#89B4FA") // Blue - focus accent + + // Text - clear hierarchy + Text = lipgloss.Color("#CDD6F4") // Text + TextDim = lipgloss.Color("#A6ADC8") // Subtext1 + TextMuted = lipgloss.Color("#6C7086") // Overlay0 + + // Accents - VIBRANT + Accent = lipgloss.Color("#89B4FA") // Blue - primary + AccentBright = lipgloss.Color("#B4BEFE") // Lavender - bright + AccentDim = lipgloss.Color("#74C7EC") // Sapphire - dim + + Secondary = lipgloss.Color("#CBA6F7") // Mauve - secondary + SecondaryDim = lipgloss.Color("#F5C2E7") // Pink + + Tertiary = lipgloss.Color("#94E2D5") // Teal // Status colors - SuccessColor = lipgloss.Color("#10B981") // Green - ErrorColor = lipgloss.Color("#EF4444") // Red - WarningColor = lipgloss.Color("#F59E0B") // Yellow/Amber - InfoColor = lipgloss.Color("#3B82F6") // Blue + Green = lipgloss.Color("#A6E3A1") // Green + Red = lipgloss.Color("#F38BA8") // Red + Yellow = lipgloss.Color("#F9E2AF") // Yellow + Blue = lipgloss.Color("#89B4FA") // Blue - // Neutral colors - TextColor = lipgloss.Color("#E5E7EB") // Light gray text - MutedColor = lipgloss.Color("#9CA3AF") // Muted text - DimColor = lipgloss.Color("#6B7280") // Dim text - BgColor = lipgloss.Color("#1F2937") // Dark background - SurfaceColor = lipgloss.Color("#374151") // Surface/card background - BorderColor = lipgloss.Color("#4B5563") // Border gray - HighlightBg = lipgloss.Color("#2D3748") // Highlight background + // Neon compatibility aliases + Cyan = lipgloss.Color("#89DCEB") // Sky + Magenta = lipgloss.Color("#CBA6F7") // Mauve + Violet = lipgloss.Color("#B4BEFE") // Lavender + NeonGreen = lipgloss.Color("#A6E3A1") // Green + HotCoral = lipgloss.Color("#F38BA8") // Red + Amber = lipgloss.Color("#FAB387") // Peach + ElecBlue = lipgloss.Color("#89B4FA") // Blue + NeonPink = lipgloss.Color("#F5C2E7") // Pink + + // Legacy mappings + DeepBlack = BgSurface + DarkSurface = BgPanel + Surface = BgPanel + BorderMid = Border + TextBright = Text + + // Provider brand colors + ClaudeBrand = lipgloss.Color("#D4A27F") // Warm terracotta + CodexBrand = lipgloss.Color("#74AA9C") // OpenAI teal + GeminiBrand = lipgloss.Color("#8AB4F8") // Google blue + KiroBrand = lipgloss.Color("#FF6B6B") // Coral red + QwenBrand = lipgloss.Color("#7C3AED") // Purple + AntigravityBrand = lipgloss.Color("#F59E0B") // Amber + MiniMaxBrand = lipgloss.Color("#EC4899") // Pink + ZhipuBrand = lipgloss.Color("#06B6D4") // Teal + + // Legacy color mappings + PrimaryColor = Accent + SecondaryColor = Secondary + AccentColor = Tertiary + SuccessColor = Green + ErrorColor = Red + WarningColor = Yellow + InfoColor = Blue + TextColor = Text + MutedColor = TextMuted + DimColor = TextDim + BgColor = BgDark + SurfaceColor = BgPanel + BorderColor = Border + HighlightBg = BgSelected + + // Gradient shades for animations and progress bars + GreenMid = lipgloss.Color("#8BD48B") // Mid green for gradients + GreenDark = lipgloss.Color("#76C776") // Dark green for gradients ) -// Title styles +// ═══════════════════════════════════════════════════════════════════════════════ +// BORDERS - Clean, minimal styles +// ═══════════════════════════════════════════════════════════════════════════════ + var ( - // TitleStyle is the main application title style + // Standard rounded border + RoundedBorder = lipgloss.RoundedBorder() + + // Simple line border + SimpleBorder = lipgloss.NormalBorder() + + // Thick border for emphasis + ThickBorder = lipgloss.ThickBorder() + + // Compatibility + SoftBorder = RoundedBorder + NeonBorder = lipgloss.DoubleBorder() + CyberBorder = ThickBorder +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// BASE STYLES - Reusable building blocks +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + // Title styles TitleStyle = lipgloss.NewStyle(). - Bold(true). - Foreground(PrimaryColor). - MarginBottom(1) + Bold(true). + Foreground(Text) - // SubtitleStyle for secondary headings SubtitleStyle = lipgloss.NewStyle(). - Foreground(MutedColor). - MarginBottom(1) + Foreground(TextDim) - // HeaderStyle for section headers - HeaderStyle = lipgloss.NewStyle(). - Bold(true). - Foreground(TextColor). - BorderStyle(lipgloss.NormalBorder()). - BorderBottom(true). - BorderForeground(BorderColor). - PaddingBottom(1). - MarginBottom(1) -) + // Panel/container styles + PanelStyle = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Border). // #585B70 - VISIBLE! + Padding(0, 1) -// Menu and list item styles -var ( - // MenuItemStyle for normal menu items - MenuItemStyle = lipgloss.NewStyle(). - Foreground(TextColor). - PaddingLeft(2) + // Selected/active styles + SelectedStyle = lipgloss.NewStyle(). + Background(BgSelected). + Foreground(AccentBright). + Bold(true) - // SelectedItemStyle for currently selected/focused items - SelectedItemStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor). - Bold(true). - PaddingLeft(2). - Background(HighlightBg) - - // ActiveItemStyle for active/enabled items - ActiveItemStyle = lipgloss.NewStyle(). - Foreground(SuccessColor). - PaddingLeft(2) - - // DisabledItemStyle for disabled/inactive items - DisabledItemStyle = lipgloss.NewStyle(). - Foreground(DimColor). - PaddingLeft(2) - - // CursorStyle for the selection cursor - CursorStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor). - Bold(true) -) - -// Status badge styles -var ( - // SuccessBadge for success status indicators + // Status badges SuccessBadge = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#000000")). - Background(SuccessColor). - Bold(true). - Padding(0, 1) + Foreground(Green). + Bold(true) - // ErrorBadge for error status indicators ErrorBadge = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#FFFFFF")). - Background(ErrorColor). - Bold(true). - Padding(0, 1) + Foreground(Red). + Bold(true) - // WarningBadge for warning status indicators WarningBadge = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#000000")). - Background(WarningColor). - Bold(true). - Padding(0, 1) + Foreground(Yellow). + Bold(true) - // InfoBadge for informational status indicators InfoBadge = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#FFFFFF")). - Background(InfoColor). - Bold(true). - Padding(0, 1) + Foreground(Blue). + Bold(true) - // PrimaryBadge for primary action indicators - PrimaryBadge = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#000000")). - Background(PrimaryColor). - Bold(true). - Padding(0, 1) - - // MutedBadge for neutral/inactive indicators - MutedBadge = lipgloss.NewStyle(). - Foreground(TextColor). - Background(SurfaceColor). - Padding(0, 1) -) - -// Border styles -var ( - // RoundedBorder is a standard rounded border style - RoundedBorder = lipgloss.NewStyle(). - Border(lipgloss.RoundedBorder()). - BorderForeground(BorderColor). - Padding(1, 2) - - // ThickBorder is a thicker border for emphasis - ThickBorder = lipgloss.NewStyle(). - Border(lipgloss.ThickBorder()). - BorderForeground(PrimaryColor). - Padding(1, 2) - - // DoubleBorder for important sections - DoubleBorder = lipgloss.NewStyle(). - Border(lipgloss.DoubleBorder()). - BorderForeground(PrimaryColor). - Padding(1, 2) - - // NormalBorder for standard sections - NormalBorder = lipgloss.NewStyle(). - Border(lipgloss.NormalBorder()). - BorderForeground(BorderColor). - Padding(1, 2) - - // HiddenBorder maintains spacing without visible border - HiddenBorder = lipgloss.NewStyle(). - Border(lipgloss.HiddenBorder()). - Padding(1, 2) -) - -// Box and container styles -var ( - // BoxStyle is a general purpose container - BoxStyle = lipgloss.NewStyle(). - Border(lipgloss.RoundedBorder()). - BorderForeground(BorderColor). - Padding(1, 2). - MarginBottom(1) - - // FocusedBoxStyle for focused/active containers - FocusedBoxStyle = lipgloss.NewStyle(). - Border(lipgloss.RoundedBorder()). - BorderForeground(PrimaryColor). - Padding(1, 2). - MarginBottom(1) - - // CardStyle for card-like containers - CardStyle = lipgloss.NewStyle(). - Border(lipgloss.RoundedBorder()). - BorderForeground(BorderColor). - Background(SurfaceColor). - Padding(1, 2). - MarginBottom(1) -) - -// Input styles -var ( - // InputStyle for text input fields - InputStyle = lipgloss.NewStyle(). - Border(lipgloss.NormalBorder()). - BorderForeground(BorderColor). - Padding(0, 1) - - // FocusedInputStyle for focused text input fields - FocusedInputStyle = lipgloss.NewStyle(). - Border(lipgloss.NormalBorder()). - BorderForeground(PrimaryColor). - Padding(0, 1) - - // InputLabelStyle for input labels - InputLabelStyle = lipgloss.NewStyle(). - Foreground(MutedColor). - MarginBottom(1) - - // PlaceholderStyle for placeholder text - PlaceholderStyle = lipgloss.NewStyle(). - Foreground(DimColor) -) - -// Button styles -var ( - // ButtonStyle for standard buttons - ButtonStyle = lipgloss.NewStyle(). - Foreground(TextColor). - Background(SurfaceColor). - Padding(0, 2). - MarginRight(1) - - // PrimaryButtonStyle for primary action buttons - PrimaryButtonStyle = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#000000")). - Background(PrimaryColor). - Bold(true). - Padding(0, 2). - MarginRight(1) - - // DangerButtonStyle for destructive action buttons - DangerButtonStyle = lipgloss.NewStyle(). - Foreground(lipgloss.Color("#FFFFFF")). - Background(ErrorColor). - Bold(true). - Padding(0, 2). - MarginRight(1) - - // DisabledButtonStyle for disabled buttons - DisabledButtonStyle = lipgloss.NewStyle(). - Foreground(DimColor). - Background(SurfaceColor). - Padding(0, 2). - MarginRight(1) -) - -// Help and hint styles -var ( - // HelpStyle for help text + // Help bar styles HelpStyle = lipgloss.NewStyle(). - Foreground(DimColor). - MarginTop(1) + Foreground(TextMuted) - // HelpKeyStyle for keyboard shortcut keys HelpKeyStyle = lipgloss.NewStyle(). - Foreground(MutedColor). - Bold(true) + Foreground(Accent). + Bold(true) - // HelpDescStyle for help descriptions HelpDescStyle = lipgloss.NewStyle(). - Foreground(DimColor) + Foreground(TextMuted) - // HintStyle for inline hints - HintStyle = lipgloss.NewStyle(). - Foreground(MutedColor). - Italic(true) -) + // Input styles + InputStyle = lipgloss.NewStyle(). + Border(SimpleBorder). + BorderForeground(Border). + Padding(0, 1) -// Status line and footer styles -var ( - // StatusBarStyle for the bottom status bar + FocusedInputStyle = lipgloss.NewStyle(). + Border(SimpleBorder). + BorderForeground(Accent). + Padding(0, 1) + + // Button styles + ButtonStyle = lipgloss.NewStyle(). + Foreground(Text). + Background(BgPanel). + Padding(0, 2) + + PrimaryButtonStyle = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Accent). + Bold(true). + Padding(0, 2) + + // Status bar StatusBarStyle = lipgloss.NewStyle(). - Foreground(TextColor). - Background(SurfaceColor). - Padding(0, 1) + Background(BgPanel). + Foreground(Text). + Padding(0, 1) - // StatusTextStyle for status bar text - StatusTextStyle = lipgloss.NewStyle(). - Foreground(MutedColor) - - // FooterStyle for footer content - FooterStyle = lipgloss.NewStyle(). - Foreground(DimColor). - BorderStyle(lipgloss.NormalBorder()). - BorderTop(true). - BorderForeground(BorderColor). - PaddingTop(1). - MarginTop(1) -) - -// Spinner and progress styles -var ( - // SpinnerStyle for loading spinners + // Spinner SpinnerStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor) + Foreground(Accent) - // ProgressBarStyle for progress indicators - ProgressBarStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor) - - // ProgressTrackStyle for progress bar track - ProgressTrackStyle = lipgloss.NewStyle(). - Foreground(SurfaceColor) -) - -// Table styles -var ( - // TableHeaderStyle for table headers + // Table styles TableHeaderStyle = lipgloss.NewStyle(). - Bold(true). - Foreground(TextColor). - BorderStyle(lipgloss.NormalBorder()). - BorderBottom(true). - BorderForeground(BorderColor). - PaddingRight(2) + Bold(true). + Foreground(Accent). + BorderStyle(SimpleBorder). + BorderBottom(true). + BorderForeground(Border) - // TableCellStyle for table cells TableCellStyle = lipgloss.NewStyle(). - Foreground(TextColor). - PaddingRight(2) + Foreground(Text) - // TableSelectedRowStyle for selected table rows TableSelectedRowStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor). - Background(HighlightBg). - Bold(true) + Background(BgSelected). + Foreground(AccentBright). + Bold(true) ) -// Logo and branding +// ═══════════════════════════════════════════════════════════════════════════════ +// MENU STYLES - Navigation elements +// ═══════════════════════════════════════════════════════════════════════════════ + var ( - // LogoStyle for the application logo/brand - LogoStyle = lipgloss.NewStyle(). - Foreground(PrimaryColor). - Bold(true) + MenuItemStyle = lipgloss.NewStyle(). + Foreground(TextDim). + PaddingLeft(2) - // VersionStyle for version information - VersionStyle = lipgloss.NewStyle(). - Foreground(DimColor) + SelectedItemStyle = lipgloss.NewStyle(). + Background(BgSelected). + Foreground(AccentBright). + Bold(true). + PaddingLeft(2) + + ActiveItemStyle = lipgloss.NewStyle(). + Foreground(Green). + PaddingLeft(2) + + DisabledItemStyle = lipgloss.NewStyle(). + Foreground(TextMuted). + PaddingLeft(2) + + CursorStyle = lipgloss.NewStyle(). + Foreground(Accent). + Bold(true) + + NavIndicator = lipgloss.NewStyle(). + Foreground(Accent). + Bold(true) ) -// Helper functions for dynamic styling +// ═══════════════════════════════════════════════════════════════════════════════ +// ADDITIONAL STYLES - Compatibility +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + HeaderStyle = TitleStyle + SectionTitle = TitleStyle + + BoxStyle = PanelStyle + FocusedBoxStyle = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Accent). // #89B4FA - BRIGHT BLUE! + Padding(0, 1) + + CardStyle = PanelStyle + + GlowBox = FocusedBoxStyle + GlowBoxMagenta = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Secondary). + Padding(0, 1) + GlowBoxSuccess = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Green). + Padding(0, 1) + GlowBoxError = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Red). + Padding(0, 1) + + TitleGlow = TitleStyle + + MagentaBadge = lipgloss.NewStyle(). + Foreground(Secondary). + Bold(true) + + PrimaryBadge = lipgloss.NewStyle(). + Foreground(Accent). + Bold(true) + + MutedBadge = lipgloss.NewStyle(). + Foreground(TextMuted) + + OnlineBadge = SuccessBadge + OfflineBadge = ErrorBadge + + InputLabelStyle = SubtitleStyle + PlaceholderStyle = lipgloss.NewStyle().Foreground(TextMuted) + + DangerButtonStyle = lipgloss.NewStyle(). + Foreground(Text). + Background(Red). + Bold(true). + Padding(0, 2) + + DisabledButtonStyle = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(BgPanel). + Padding(0, 2) + + StatusTextStyle = SubtitleStyle + FooterStyle = HelpStyle + + ProgressBarStyle = lipgloss.NewStyle().Foreground(Green) + ProgressTrackStyle = lipgloss.NewStyle().Foreground(BorderDim) + + HintStyle = SubtitleStyle + KeyHint = HelpKeyStyle + + LogoStyle = TitleStyle + LogoAccent = lipgloss.NewStyle().Foreground(Accent).Bold(true) + VersionStyle = SubtitleStyle +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// ICONS - Simple, clean icons +// ═══════════════════════════════════════════════════════════════════════════════ + +const ( + IconOnline = "●" + IconOffline = "○" + IconPending = "◐" + + IconArrowRight = "→" + IconArrowLeft = "←" + IconArrowUp = "↑" + IconArrowDown = "↓" + IconChevron = "›" + + IconCheck = "✓" + IconCross = "✗" + IconWarning = "!" + IconInfo = "i" + IconStar = "*" + IconDiamond = "◆" + IconSquare = "■" + IconCircle = "●" + IconTriangle = "▲" + + IconBolt = "⚡" + IconFire = "~" + IconRocket = ">" + IconGear = "*" + IconLock = "#" + IconUnlock = "#" + IconKey = "*" + IconCloud = "~" + IconServer = "■" + IconTerminal = ">" + IconCode = "<>" + IconPulse = "~" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// HELPER FUNCTIONS +// ═══════════════════════════════════════════════════════════════════════════════ + +func Bold(text string) string { + return lipgloss.NewStyle().Bold(true).Foreground(Text).Render(text) +} + +func Dim(text string) string { + return lipgloss.NewStyle().Foreground(TextMuted).Render(text) +} + +func Success(text string) string { + return lipgloss.NewStyle().Foreground(Green).Render(text) +} + +func Error(text string) string { + return lipgloss.NewStyle().Foreground(Red).Render(text) +} + +func Warning(text string) string { + return lipgloss.NewStyle().Foreground(Yellow).Render(text) +} + +func Info(text string) string { + return lipgloss.NewStyle().Foreground(Blue).Render(text) +} + +func Primary(text string) string { + return lipgloss.NewStyle().Foreground(Accent).Render(text) +} + +func Accent2(text string) string { + return lipgloss.NewStyle().Foreground(Secondary).Render(text) +} + +func Muted(text string) string { + return lipgloss.NewStyle().Foreground(TextMuted).Render(text) +} -// Colorize returns text with the specified color func Colorize(text string, color lipgloss.Color) string { return lipgloss.NewStyle().Foreground(color).Render(text) } -// Bold returns bold text -func Bold(text string) string { - return lipgloss.NewStyle().Bold(true).Render(text) +func Glow(text string, color lipgloss.Color) string { + return lipgloss.NewStyle().Bold(true).Foreground(color).Render(text) } -// Dim returns dimmed text -func Dim(text string) string { - return lipgloss.NewStyle().Foreground(DimColor).Render(text) -} - -// Success returns success-colored text -func Success(text string) string { - return lipgloss.NewStyle().Foreground(SuccessColor).Render(text) -} - -// Error returns error-colored text -func Error(text string) string { - return lipgloss.NewStyle().Foreground(ErrorColor).Render(text) -} - -// Warning returns warning-colored text -func Warning(text string) string { - return lipgloss.NewStyle().Foreground(WarningColor).Render(text) -} - -// Info returns info-colored text -func Info(text string) string { - return lipgloss.NewStyle().Foreground(InfoColor).Render(text) -} - -// Primary returns primary-colored text -func Primary(text string) string { - return lipgloss.NewStyle().Foreground(PrimaryColor).Render(text) -} - -// Muted returns muted text -func Muted(text string) string { - return lipgloss.NewStyle().Foreground(MutedColor).Render(text) -} - -// WithWidth returns a style with the specified width func WithWidth(style lipgloss.Style, width int) lipgloss.Style { return style.Width(width) } -// WithHeight returns a style with the specified height func WithHeight(style lipgloss.Style, height int) lipgloss.Style { return style.Height(height) } -// Centered returns centered text within the given width func Centered(text string, width int) string { return lipgloss.NewStyle().Width(width).Align(lipgloss.Center).Render(text) } -// RightAligned returns right-aligned text within the given width func RightAligned(text string, width int) string { return lipgloss.NewStyle().Width(width).Align(lipgloss.Right).Render(text) } + +// Gradient functions (simplified - no actual gradient, just color) +func GradientText(text string, colors []lipgloss.Color) string { + if len(colors) == 0 { + return text + } + return lipgloss.NewStyle().Foreground(colors[0]).Render(text) +} + +func CyanGradient(text string) string { + return lipgloss.NewStyle().Foreground(Accent).Render(text) +} + +func MagentaGradient(text string) string { + return lipgloss.NewStyle().Foreground(Secondary).Render(text) +} + +// FormatCount formats numbers with K/M suffix +func FormatCount(count int64) string { + if count >= 1000000 { + return lipgloss.NewStyle().Foreground(Accent).Bold(true).Render( + fmt.Sprintf("%.1fM", float64(count)/1000000), + ) + } + if count >= 1000 { + return lipgloss.NewStyle().Foreground(Accent).Bold(true).Render( + fmt.Sprintf("%.1fK", float64(count)/1000), + ) + } + return lipgloss.NewStyle().Foreground(Accent).Bold(true).Render( + fmt.Sprintf("%d", count), + ) +} diff --git a/internal/tui/switch.go b/internal/tui/switch.go index 5b41b5d8..6cf4313d 100644 --- a/internal/tui/switch.go +++ b/internal/tui/switch.go @@ -11,6 +11,10 @@ import ( "github.com/router-for-me/CLIProxyAPI/v6/internal/config" ) +// ═══════════════════════════════════════════════════════════════════════════════ +// SWITCH SCREEN - Cyberpunk Neon Agent Configuration Panel +// ═══════════════════════════════════════════════════════════════════════════════ + // AgentItem represents a single agent in the switch list type AgentItem struct { ID string @@ -39,6 +43,139 @@ type SwitchKeyMap struct { Quit key.Binding } +// ═══════════════════════════════════════════════════════════════════════════════ +// AGENT TYPE ICONS - Violet accented symbols +// ═══════════════════════════════════════════════════════════════════════════════ + +var agentIcons = map[string]string{ + "claude": "C", + "gemini": "G", + "codex": "X", + "opencode": "O", + "droid": "D", + "cursor": "R", + "kilo": "K", + "roocode": "P", +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// SWITCH SCREEN STYLES - Using colors from styles.go +// ═══════════════════════════════════════════════════════════════════════════════ + +var ( + // Header with electric glow + switchHeaderStyle = lipgloss.NewStyle(). + Bold(true). + Foreground(Accent). + Background(BgDark). + Padding(0, 1). + MarginBottom(1) + + // Agent card - unselected + agentCardStyle = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(BorderDim). + Padding(0, 2). + Width(52). + MarginBottom(0) + + // Agent card - selected with glowing accent border + agentCardSelectedStyle = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(Accent). + Padding(0, 2). + Width(52). + MarginBottom(0) + + // Agent name - normal + agentNameStyle = lipgloss.NewStyle(). + Foreground(Text). + Bold(true) + + // Agent name - selected (glowing accent) + agentNameSelectedStyle = lipgloss.NewStyle(). + Foreground(AccentBright). + Bold(true) + + // Agent icon container with tertiary accent + agentIconStyle = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Tertiary). + Bold(true). + Padding(0, 1) + + // Mode badge - PROXY (Green) + modeBadgeProxy = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Green). + Bold(true). + Padding(0, 1) + + // Mode badge - DIRECT (Yellow/Amber) + modeBadgeDirect = lipgloss.NewStyle(). + Foreground(BgDark). + Background(Yellow). + Bold(true). + Padding(0, 1) + + // Mode badge - unavailable + modeBadgeUnavailable = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(BgPanel). + Padding(0, 1) + + // Availability status - online + statusOnlineStyle = lipgloss.NewStyle(). + Foreground(Green). + Bold(true) + + // Availability status - offline + statusOfflineStyle = lipgloss.NewStyle(). + Foreground(Red). + Bold(true) + + // Toggle indicator + toggleIndicatorStyle = lipgloss.NewStyle(). + Foreground(Secondary). + Bold(true) + + // Success message + successMessageStyle = lipgloss.NewStyle(). + Foreground(Green). + Bold(true). + Padding(0, 1) + + // Error message + errorMessageStyle = lipgloss.NewStyle(). + Foreground(Red). + Bold(true). + Padding(0, 1) + + // Separator line + separatorStyle = lipgloss.NewStyle(). + Foreground(Tertiary) + + // Help section container + helpContainerStyle = lipgloss.NewStyle(). + Border(RoundedBorder). + BorderForeground(BorderDim). + BorderTop(true). + BorderBottom(false). + BorderLeft(false). + BorderRight(false). + Padding(1, 0). + MarginTop(1) + + // Cursor arrow + cursorArrowStyle = lipgloss.NewStyle(). + Foreground(Secondary). + Bold(true) +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// KEY BINDINGS +// ═══════════════════════════════════════════════════════════════════════════════ + // DefaultSwitchKeyMap returns the default key bindings func DefaultSwitchKeyMap() SwitchKeyMap { return SwitchKeyMap{ @@ -61,6 +198,10 @@ func DefaultSwitchKeyMap() SwitchKeyMap { } } +// ═══════════════════════════════════════════════════════════════════════════════ +// MODEL INITIALIZATION +// ═══════════════════════════════════════════════════════════════════════════════ + // NewSwitchModel creates a new switch model func NewSwitchModel(cfg *config.Config) SwitchModel { m := SwitchModel{ @@ -90,6 +231,10 @@ func (m *SwitchModel) refreshAgents() { } } +// ═══════════════════════════════════════════════════════════════════════════════ +// TEA MODEL IMPLEMENTATION +// ═══════════════════════════════════════════════════════════════════════════════ + // Init implements tea.Model func (m SwitchModel) Init() tea.Cmd { return nil @@ -171,79 +316,244 @@ func (m *SwitchModel) toggleCurrent() { m.refreshAgents() } -// View implements tea.Model +// ═══════════════════════════════════════════════════════════════════════════════ +// VIEW RENDERING - Premium Cyberpunk Interface +// ═══════════════════════════════════════════════════════════════════════════════ + +// View implements tea.Model - Returns content only (no outer borders) func (m SwitchModel) View() string { + return m.ViewWithSize(m.width, m.height) +} + +// ViewWithSize renders with explicit dimensions for responsive layout +func (m SwitchModel) ViewWithSize(width, height int) string { if m.quitting { return "" } var b strings.Builder - // Title - title := TitleStyle.Render("Switch Agent Configuration") - b.WriteString(title) - b.WriteString("\n") + // Section title (compact) + title := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("Agent Configuration") + subtitle := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(" - Toggle routing modes") + b.WriteString(title + subtitle + "\n\n") - // Separator line - separator := lipgloss.NewStyle(). - Foreground(BorderColor). - Render(strings.Repeat("─", min(26, m.width-2))) - b.WriteString(separator) - b.WriteString("\n\n") - - // Agent list - for i, agent := range m.agents { - cursor := " " - if i == m.cursor { - cursor = "> " - } - - // Format the mode badge - modeBadge := m.formatModeBadge(agent) - - // Build the line - var line string - nameStyle := MenuItemStyle - if i == m.cursor { - nameStyle = SelectedItemStyle.Copy().PaddingLeft(0) - } - - // Pad the name to align badges - paddedName := fmt.Sprintf("%-15s", agent.DisplayName) - - if i == m.cursor { - cursorStr := CursorStyle.Render(cursor) - nameStr := nameStyle.Render(paddedName) - line = cursorStr + nameStr + " " + modeBadge - } else { - line = cursor + nameStyle.Render(paddedName) + " " + modeBadge - } - - b.WriteString(line) - b.WriteString("\n") + // Calculate visible rows based on height + maxRows := height - 5 + if maxRows < 4 { + maxRows = 4 + } + if maxRows > len(m.agents) { + maxRows = len(m.agents) } - // Status message (if any) + // Agent list - responsive rows + for i := 0; i < maxRows; i++ { + if i >= len(m.agents) { + break + } + agent := m.agents[i] + isSelected := i == m.cursor + row := m.renderAgentRowWithWidth(agent, isSelected, width) + b.WriteString(row + "\n") + } + + // Status message if m.message != "" { b.WriteString("\n") - msgStyle := lipgloss.NewStyle().Foreground(InfoColor) if strings.HasPrefix(m.message, "Error:") { - msgStyle = lipgloss.NewStyle().Foreground(ErrorColor) + b.WriteString(lipgloss.NewStyle().Foreground(Red).Render(IconCross + " " + m.message)) + } else { + b.WriteString(lipgloss.NewStyle().Foreground(Green).Render(IconCheck + " " + m.message)) } - b.WriteString(msgStyle.Render(m.message)) - b.WriteString("\n") } - // Help footer - b.WriteString("\n") - helpText := m.renderHelp() - b.WriteString(helpText) - return b.String() } -// formatModeBadge returns a styled mode badge for an agent -func (m SwitchModel) formatModeBadge(agent AgentItem) string { +// renderAgentRowWithWidth creates a row that adapts to available width +func (m SwitchModel) renderAgentRowWithWidth(agent AgentItem, isSelected bool, width int) string { + // Cursor indicator + var cursor string + if isSelected { + cursor = lipgloss.NewStyle().Foreground(Accent).Bold(true).Render(IconChevron + " ") + } else { + cursor = " " + } + + // Agent icon + icon := agentIcons[agent.ID] + if icon == "" { + icon = "?" + } + iconRendered := lipgloss.NewStyle(). + Foreground(BgDark). + Background(Tertiary). + Bold(true). + Padding(0, 1). + Render(icon) + + // Calculate responsive widths + nameWidth := 14 + if width > 60 { + nameWidth = 18 + } + + // Agent name + var nameStyle lipgloss.Style + if isSelected { + nameStyle = lipgloss.NewStyle().Foreground(AccentBright).Bold(true).Width(nameWidth) + } else { + nameStyle = lipgloss.NewStyle().Foreground(Text).Width(nameWidth) + } + name := nameStyle.Render(agent.DisplayName) + + // Status badge (only show on wider terminals) + var status string + if width > 50 { + if agent.Available { + status = lipgloss.NewStyle().Foreground(Green).Render(IconOnline + " READY") + } else { + status = lipgloss.NewStyle().Foreground(Red).Render(IconOffline + " N/A ") + } + status = lipgloss.NewStyle().Width(10).Render(status) + } + + // Mode badge + modeBadge := m.renderModeBadge(agent) + + // Compose row + row := cursor + iconRendered + " " + name + if status != "" { + row += " " + status + } + row += " " + modeBadge + + // Selection highlight + if isSelected { + row = lipgloss.NewStyle().Background(BgSelected).Render(row) + } + + return row +} + +// renderAgentRow creates a simple row for the agent list (no card borders) +func (m SwitchModel) renderAgentRow(agent AgentItem, isSelected bool) string { + // Cursor indicator + var cursor string + if isSelected { + cursor = lipgloss.NewStyle().Foreground(Accent).Bold(true).Render(IconChevron + " ") + } else { + cursor = " " + } + + // Agent icon + icon := agentIcons[agent.ID] + if icon == "" { + icon = "?" + } + iconRendered := lipgloss.NewStyle(). + Foreground(BgDark). + Background(Tertiary). + Bold(true). + Padding(0, 1). + Render(icon) + + // Agent name + var nameStyle lipgloss.Style + if isSelected { + nameStyle = lipgloss.NewStyle().Foreground(AccentBright).Bold(true).Width(16) + } else { + nameStyle = lipgloss.NewStyle().Foreground(Text).Width(16) + } + name := nameStyle.Render(agent.DisplayName) + + // Status badge + var status string + if agent.Available { + status = lipgloss.NewStyle().Foreground(Green).Render(IconOnline + " READY") + } else { + status = lipgloss.NewStyle().Foreground(Red).Render(IconOffline + " N/A ") + } + statusPadded := lipgloss.NewStyle().Width(10).Render(status) + + // Mode badge + modeBadge := m.renderModeBadge(agent) + + // Compose row + row := fmt.Sprintf("%s%s %s %s %s", cursor, iconRendered, name, statusPadded, modeBadge) + + // Selection highlight + if isSelected { + row = lipgloss.NewStyle().Background(BgSelected).Render(row) + } + + return row +} + +// renderAgentCard creates a premium styled agent card (legacy, kept for standalone mode) +func (m SwitchModel) renderAgentCard(agent AgentItem, isSelected bool) string { + // Get the icon for this agent type + icon := agentIcons[agent.ID] + if icon == "" { + icon = "?" + } + + // Render icon with tertiary accent + iconRendered := agentIconStyle.Render(icon) + + // Render agent name + var nameRendered string + if isSelected { + nameRendered = agentNameSelectedStyle.Render(agent.DisplayName) + } else { + nameRendered = agentNameStyle.Render(agent.DisplayName) + } + + // Pad name for alignment + namePadded := lipgloss.NewStyle().Width(18).Render(nameRendered) + + // Render availability badge + var availBadge string + if agent.Available { + availBadge = statusOnlineStyle.Render(IconOnline + " READY") + } else { + availBadge = statusOfflineStyle.Render(IconOffline + " N/A") + } + availPadded := lipgloss.NewStyle().Width(12).Render(availBadge) + + // Render mode badge + modeBadge := m.renderModeBadge(agent) + + // Build the card content + cardContent := fmt.Sprintf("%s %s %s %s", iconRendered, namePadded, availPadded, modeBadge) + + // Wrap in card container + var cardStyle lipgloss.Style + if isSelected { + cardStyle = agentCardSelectedStyle + } else { + cardStyle = agentCardStyle + } + + // Add cursor indicator + var cursor string + if isSelected { + cursor = cursorArrowStyle.Render(IconChevron + " ") + } else { + cursor = " " + } + + return cursor + cardStyle.Render(cardContent) +} + +// renderModeBadge returns a styled mode badge for an agent +func (m SwitchModel) renderModeBadge(agent AgentItem) string { if !agent.Available { // Agent not found or has special status msg := agent.Message @@ -251,35 +561,46 @@ func (m SwitchModel) formatModeBadge(agent AgentItem) string { msg = "NOT FOUND" } // Truncate long messages - if len(msg) > 20 { - msg = msg[:17] + "..." + if len(msg) > 15 { + msg = msg[:12] + "..." } - return MutedBadge.Render(strings.ToUpper(msg)) + return modeBadgeUnavailable.Render(strings.ToUpper(msg)) } switch agent.Mode { case cmd.ModeProxy: - return SuccessBadge.Render("PROXY") + // Proxy mode - Green with electric styling + return modeBadgeProxy.Render(IconBolt + " PROXY") case cmd.ModeNative: - return WarningBadge.Render("NATIVE") + // Direct/Native mode - Yellow with clean styling + return modeBadgeDirect.Render(IconArrowRight + " DIRECT") default: - return MutedBadge.Render("UNKNOWN") + return modeBadgeUnavailable.Render("UNKNOWN") } } -// renderHelp renders the help footer -func (m SwitchModel) renderHelp() string { - keyStyle := HelpKeyStyle - descStyle := HelpDescStyle - - help := []string{ - keyStyle.Render("[Enter]") + " " + descStyle.Render("Toggle Mode"), - keyStyle.Render("[Esc]") + " " + descStyle.Render("Back"), +// renderNeonHelp renders the help footer with cyberpunk neon styling +func (m SwitchModel) renderNeonHelp() string { + // Build help items using styles from styles.go + items := []string{ + HelpKeyStyle.Copy().Background(BgPanel).Padding(0, 1).Render("Enter") + " " + HelpDescStyle.Render("Toggle Mode"), + HelpKeyStyle.Copy().Background(BgPanel).Padding(0, 1).Render("j/k") + " " + HelpDescStyle.Render("Navigate"), + HelpKeyStyle.Copy().Background(BgPanel).Padding(0, 1).Render("Esc") + " " + HelpDescStyle.Render("Back"), } - return HelpStyle.Render(strings.Join(help, " ")) + // Separator + sepLine := separatorStyle.Render(strings.Repeat("─", 54)) + + // Join items with spacing + helpLine := strings.Join(items, " ") + + return sepLine + "\n" + " " + helpLine } +// ═══════════════════════════════════════════════════════════════════════════════ +// ENTRY POINT +// ═══════════════════════════════════════════════════════════════════════════════ + // RunSwitchScreen runs the switch screen as a standalone TUI program func RunSwitchScreen(cfg *config.Config) error { model := NewSwitchModel(cfg) diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 5fd76e83..1adad817 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -2,366 +2,746 @@ package tui import ( "fmt" + "math/rand" "strings" + "time" + "github.com/charmbracelet/bubbles/spinner" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" ) -// Screen represents the different screens/views in the TUI +// ═══════════════════════════════════════════════════════════════════════════════ +// PREMIUM TUI - Proper lipgloss borders, high contrast, btop-style +// ═══════════════════════════════════════════════════════════════════════════════ + type Screen int const ( - ScreenMainMenu Screen = iota + ScreenDashboard Screen = iota ScreenServer - ScreenSwitch - ScreenLogin - ScreenStatus + ScreenProviders + ScreenAgents + ScreenUsage + ScreenLogs + ScreenMappings + ScreenIntegrations ) -// MenuItem represents a menu item in the main menu type MenuItem struct { + Key string Title string + Icon string Screen Screen } -// Model is the main TUI application state type Model struct { - currentScreen Screen + screen Screen cursor int - menuItems []MenuItem + menu []MenuItem width int height int quitting bool - message string // For displaying status messages + ready bool + serverOn bool + cfg *config.Config + host string + port int + spinner spinner.Model + loginModel LoginModel + switchModel SwitchModel + mappingsModel MappingsModel + usageModel UsageModel + logsModel LogsModel + tick int + spark []int } -// Styles defines the lipgloss styles for the TUI -type Styles struct { - Title lipgloss.Style - Divider lipgloss.Style - MenuItem lipgloss.Style - SelectedItem lipgloss.Style - Help lipgloss.Style - StatusMessage lipgloss.Style - Container lipgloss.Style +type TickMsg time.Time + +func doTick() tea.Cmd { + return tea.Tick(200*time.Millisecond, func(t time.Time) tea.Msg { + return TickMsg(t) + }) } -// DefaultStyles returns the default styling for the TUI -func DefaultStyles() Styles { - return Styles{ - Title: lipgloss.NewStyle(). - Bold(true). - Foreground(lipgloss.Color("99")). - MarginBottom(0), - Divider: lipgloss.NewStyle(). - Foreground(lipgloss.Color("240")), - MenuItem: lipgloss.NewStyle(). - Foreground(lipgloss.Color("252")). - PaddingLeft(2), - SelectedItem: lipgloss.NewStyle(). - Foreground(lipgloss.Color("212")). - Bold(true). - PaddingLeft(0), - Help: lipgloss.NewStyle(). - Foreground(lipgloss.Color("241")). - MarginTop(1), - StatusMessage: lipgloss.NewStyle(). - Foreground(lipgloss.Color("82")). - MarginTop(1), - Container: lipgloss.NewStyle(). - Padding(1, 2), +func NewModel(cfg *config.Config, host string, port int) Model { + s := spinner.New() + s.Spinner = spinner.Dot + s.Style = lipgloss.NewStyle().Foreground(Accent) + + spark := make([]int, 40) + for i := range spark { + spark[i] = rand.Intn(8) } -} -var styles = DefaultStyles() - -// NewModel creates a new TUI model with default values -func NewModel() Model { - return Model{ - currentScreen: ScreenMainMenu, - cursor: 0, - menuItems: []MenuItem{ - {Title: "Start Server", Screen: ScreenServer}, - {Title: "Switch Agent Config", Screen: ScreenSwitch}, - {Title: "Login to Provider", Screen: ScreenLogin}, - {Title: "Show Status", Screen: ScreenStatus}, + m := Model{ + screen: ScreenDashboard, + cursor: 0, + menu: []MenuItem{ + {Key: "1", Title: "Dashboard", Screen: ScreenDashboard}, + {Key: "2", Title: "Server", Screen: ScreenServer}, + {Key: "3", Title: "Providers", Screen: ScreenProviders}, + {Key: "4", Title: "Agents", Screen: ScreenAgents}, + {Key: "5", Title: "Usage", Screen: ScreenUsage}, + {Key: "6", Title: "Logs", Screen: ScreenLogs}, + {Key: "7", Title: "Mappings", Screen: ScreenMappings}, + {Key: "8", Title: "Setup", Screen: ScreenIntegrations}, }, - width: 80, - height: 24, - quitting: false, - message: "", + width: 120, + height: 40, + cfg: cfg, + host: host, + port: port, + spinner: s, + loginModel: NewLoginModel(cfg), + switchModel: NewSwitchModel(cfg), + mappingsModel: NewMappingsModel(cfg), + usageModel: NewUsageModel(cfg), + logsModel: NewLogsModel(), + spark: spark, } + + status := CheckServerRunning(host, port) + m.serverOn = status.Running + + return m } -// Init implements tea.Model func (m Model) Init() tea.Cmd { - return nil + return tea.Batch(m.spinner.Tick, doTick()) } -// Update implements tea.Model func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + var cmds []tea.Cmd + switch msg := msg.(type) { - case tea.KeyMsg: - return m.handleKeyPress(msg) + case TickMsg: + m.tick++ + if m.tick%2 == 0 { + m.spark = append(m.spark[1:], rand.Intn(8)) + } + return m, doTick() + case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height + m.ready = true return m, nil - } - return m, nil -} -// handleKeyPress handles keyboard input -func (m Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch m.currentScreen { - case ScreenMainMenu: - return m.handleMainMenuKeys(msg) - case ScreenServer: - return m.handleServerKeys(msg) - case ScreenSwitch: - return m.handleSwitchKeys(msg) - case ScreenLogin: - return m.handleLoginKeys(msg) - case ScreenStatus: - return m.handleStatusKeys(msg) - } - return m, nil -} - -// handleMainMenuKeys handles key presses on the main menu -func (m Model) handleMainMenuKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - m.quitting = true - return m, tea.Quit - case "up", "k": - if m.cursor > 0 { - m.cursor-- - } - case "down", "j": - if m.cursor < len(m.menuItems) { // Allow cursor to reach Exit option - m.cursor++ - } - case "enter", " ": - // Handle menu selection - if m.cursor == len(m.menuItems) { - // Exit option selected + case tea.KeyMsg: + switch msg.String() { + case "q", "ctrl+c": m.quitting = true return m, tea.Quit - } - if m.cursor >= 0 && m.cursor < len(m.menuItems) { - selectedItem := m.menuItems[m.cursor] - m.currentScreen = selectedItem.Screen - m.message = "" + case "1", "2", "3", "4", "5", "6", "7", "8": + idx := int(msg.String()[0] - '1') + if idx >= 0 && idx < len(m.menu) { + m.cursor = idx + m.screen = m.menu[idx].Screen + } + case "up", "k": + if m.cursor > 0 { + m.cursor-- + m.screen = m.menu[m.cursor].Screen + } + case "down", "j": + if m.cursor < len(m.menu)-1 { + m.cursor++ + m.screen = m.menu[m.cursor].Screen + } + case "esc": + m.screen = ScreenDashboard + m.cursor = 0 + case "r": + status := CheckServerRunning(m.host, m.port) + m.serverOn = status.Running } } - return m, nil -} -// handleServerKeys handles key presses on the server screen -func (m Model) handleServerKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - m.quitting = true - return m, tea.Quit - case "esc", "b": - m.currentScreen = ScreenMainMenu - m.message = "" + // Forward to submodels + switch m.screen { + case ScreenProviders: + updated, cmd := m.loginModel.Update(msg) + if lm, ok := updated.(LoginModel); ok { + m.loginModel = lm + } + cmds = append(cmds, cmd) + case ScreenAgents: + updated, cmd := m.switchModel.Update(msg) + if sm, ok := updated.(SwitchModel); ok { + m.switchModel = sm + } + cmds = append(cmds, cmd) + case ScreenMappings: + m.mappingsModel, _ = m.mappingsModel.Update(msg) + case ScreenUsage: + m.usageModel, _ = m.usageModel.Update(msg) + case ScreenLogs: + m.logsModel, _ = m.logsModel.Update(msg) } - return m, nil + + var cmd tea.Cmd + m.spinner, cmd = m.spinner.Update(msg) + cmds = append(cmds, cmd) + + return m, tea.Batch(cmds...) } -// handleSwitchKeys handles key presses on the switch screen -func (m Model) handleSwitchKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - m.quitting = true - return m, tea.Quit - case "esc", "b": - m.currentScreen = ScreenMainMenu - m.message = "" - } - return m, nil -} +// ═══════════════════════════════════════════════════════════════════════════════ +// VIEW - Main layout with REAL lipgloss borders +// ═══════════════════════════════════════════════════════════════════════════════ -// handleLoginKeys handles key presses on the login screen -func (m Model) handleLoginKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - m.quitting = true - return m, tea.Quit - case "esc", "b": - m.currentScreen = ScreenMainMenu - m.message = "" - } - return m, nil -} - -// handleStatusKeys handles key presses on the status screen -func (m Model) handleStatusKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "q", "ctrl+c": - m.quitting = true - return m, tea.Quit - case "esc", "b": - m.currentScreen = ScreenMainMenu - m.message = "" - } - return m, nil -} - -// View implements tea.Model func (m Model) View() string { if m.quitting { - return "Goodbye!\n" + return "" + } + if !m.ready { + return "\n Loading..." } - var content string - switch m.currentScreen { - case ScreenMainMenu: - content = m.viewMainMenu() - case ScreenServer: - content = m.viewServer() - case ScreenSwitch: - content = m.viewSwitch() - case ScreenLogin: - content = m.viewLogin() - case ScreenStatus: - content = m.viewStatus() + // Border (2) + Padding (2) = 4 chars overhead per bordered panel + const panelOverhead = 4 + + // Calculate dimensions - responsive sidebar + // sidebarWidth is the CONTENT width (lipgloss adds border+padding on top) + sidebarWidth := 20 // Renders as 20 + 4 = 24 total + if m.width < 80 { + sidebarWidth = 14 // Renders as 14 + 4 = 18 total } - return styles.Container.Render(content) + // contentWidth = total width - sidebar rendered - 1 space - content panel overhead + // sidebar rendered = sidebarWidth + panelOverhead + // We need: (sidebarWidth + panelOverhead) + 1 + (contentWidth + panelOverhead) <= m.width + // So: contentWidth = m.width - sidebarWidth - panelOverhead - 1 - panelOverhead + // = m.width - sidebarWidth - 9 + contentWidth := m.width - sidebarWidth - 9 + if contentWidth < 30 { + contentWidth = 30 + } + mainHeight := m.height - 4 + + // Render components + header := m.renderHeader() + sidebar := m.renderSidebar(sidebarWidth, mainHeight-2) + content := m.renderContentView(contentWidth, mainHeight-2) + footer := m.renderFooter() + + // Join sidebar and content + main := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, " ", content) + + return lipgloss.JoinVertical(lipgloss.Left, header, main, footer) } -// viewMainMenu renders the main menu -func (m Model) viewMainMenu() string { - var b strings.Builder +// ═══════════════════════════════════════════════════════════════════════════════ +// HEADER - Status bar with logo, sparkline, and server status +// ═══════════════════════════════════════════════════════════════════════════════ - // Title - b.WriteString(styles.Title.Render("ProxyPilot CLI")) - b.WriteString("\n") +func (m Model) renderHeader() string { + // Logo + logo := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("◆ PROXYPILOT") - // Divider - b.WriteString(styles.Divider.Render(strings.Repeat("─", 17))) - b.WriteString("\n") + version := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(" v0.2") - // Menu items - for i, item := range m.menuItems { - if i == m.cursor { - b.WriteString(styles.SelectedItem.Render(fmt.Sprintf("> %s", item.Title))) - } else { - b.WriteString(styles.MenuItem.Render(item.Title)) - } - b.WriteString("\n") - } - - // Exit option (special handling) - if m.cursor == len(m.menuItems) { - b.WriteString(styles.SelectedItem.Render("> Exit")) + // Status indicator + var status string + if m.serverOn { + pulse := []string{"●", "◉", "●", "○"}[m.tick%4] + status = lipgloss.NewStyle().Foreground(Green).Bold(true).Render(pulse + " ONLINE") } else { - b.WriteString(styles.MenuItem.Render("Exit")) + status = lipgloss.NewStyle().Foreground(Red).Bold(true).Render("○ OFFLINE") } - b.WriteString("\n") - // Help text - b.WriteString(styles.Help.Render("↑/↓: navigate • enter: select • q: quit")) + // Sparkline with block characters + sparkChars := []string{"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"} + var spark strings.Builder + for _, v := range m.spark { + var color lipgloss.Color + switch { + case v < 2: + color = Blue + case v < 4: + color = Accent + case v < 6: + color = Green + default: + color = Yellow + } + spark.WriteString(lipgloss.NewStyle().Foreground(color).Render(sparkChars[v])) + } - // Status message if any - if m.message != "" { + // Compose header + leftSide := logo + version + rightSide := spark.String() + " " + status + + gap := m.width - lipgloss.Width(leftSide) - lipgloss.Width(rightSide) - 4 + if gap < 0 { + gap = 0 + } + + content := " " + leftSide + strings.Repeat(" ", gap) + rightSide + " " + + // Header bar with background and bottom border + return lipgloss.NewStyle(). + Background(BgSurface). + Foreground(Text). + Width(m.width). + Render(content) + "\n" +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// SIDEBAR - Navigation with REAL rounded border +// ═══════════════════════════════════════════════════════════════════════════════ + +func (m Model) renderSidebar(width, height int) string { + var items []string + + for i, item := range m.menu { + isSelected := i == m.cursor + + key := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(fmt.Sprintf("[%s]", item.Key)) + + var row string + if isSelected { + // Selected: cyan cursor bar + highlighted background + cursor := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("▌") + title := lipgloss.NewStyle(). + Background(BgSelected). + Foreground(Accent). + Bold(true). + Width(width - 7). + Render(item.Title) + row = cursor + " " + key + " " + title + } else { + title := lipgloss.NewStyle(). + Foreground(TextDim). + Width(width - 7). + Render(item.Title) + row = " " + key + " " + title + } + items = append(items, row) + } + + // Pad to fill height + for len(items) < height-2 { + items = append(items, "") + } + + content := strings.Join(items, "\n") + + // REAL lipgloss border - rounded, visible color + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(Border). + Width(width). + Height(height). + Padding(0, 1). + Render(content) +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// CONTENT - Main area with ACCENT border +// ═══════════════════════════════════════════════════════════════════════════════ + +func (m Model) renderContentView(width, height int) string { + var content string + + innerWidth := width - 4 + innerHeight := height - 2 + + switch m.screen { + case ScreenDashboard: + content = m.renderDashboard(innerWidth, innerHeight) + case ScreenServer: + content = m.renderServerView(innerWidth, innerHeight) + case ScreenProviders: + content = m.loginModel.ViewWithSize(innerWidth, innerHeight) + case ScreenAgents: + content = m.switchModel.ViewWithSize(innerWidth, innerHeight) + case ScreenMappings: + content = m.mappingsModel.ViewWithSize(innerWidth, innerHeight) + case ScreenUsage: + content = m.usageModel.ViewWithSize(innerWidth, innerHeight) + case ScreenLogs: + content = m.logsModel.ViewWithSize(innerWidth, innerHeight) + case ScreenIntegrations: + content = m.renderSetupView(innerWidth, innerHeight) + default: + content = "Select an option from the menu" + } + + // Content panel with ACCENT colored border + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(Accent). + Width(width). + Height(height). + Padding(0, 1). + Render(content) +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// DASHBOARD - Multi-card layout with bordered sections +// ═══════════════════════════════════════════════════════════════════════════════ + +func (m Model) renderDashboard(width, height int) string { + var b strings.Builder + + // Card style with dim border + cardBorder := lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(BorderDim). + Padding(0, 1) + + titleStyle := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true) + + labelStyle := lipgloss.NewStyle().Foreground(TextMuted) + valueStyle := lipgloss.NewStyle().Foreground(Accent).Bold(true) + + // Determine layout mode based on width + narrowMode := width < 50 + var cardWidth int + if narrowMode { + // Single column: cards use full width + cardWidth = width - 2 + } else { + // Two column: cards share width + cardWidth = (width - 3) / 2 + } + + // ─── SERVER STATUS ─── + var statusIcon, statusText string + if m.serverOn { + statusIcon = lipgloss.NewStyle().Foreground(Green).Render("●") + statusText = lipgloss.NewStyle().Foreground(Green).Bold(true).Render("Running") + } else { + statusIcon = lipgloss.NewStyle().Foreground(Red).Render("○") + statusText = lipgloss.NewStyle().Foreground(Red).Bold(true).Render("Stopped") + } + + serverContent := titleStyle.Render("Server") + "\n\n" + + fmt.Sprintf(" %s %s\n", statusIcon, statusText) + + fmt.Sprintf(" %s %s", labelStyle.Render("Endpoint:"), valueStyle.Render(fmt.Sprintf("%s:%d", m.host, m.port))) + serverCard := cardBorder.Width(cardWidth).Render(serverContent) + + // ─── STATISTICS ─── + agentCount := 0 + for _, a := range m.switchModel.agents { + if a.Available { + agentCount++ + } + } + providerCount := 0 + if m.cfg != nil { + if len(m.cfg.ClaudeKey) > 0 { + providerCount++ + } + if len(m.cfg.GeminiKey) > 0 { + providerCount++ + } + if len(m.cfg.CodexKey) > 0 { + providerCount++ + } + } + + statsContent := titleStyle.Render("Statistics") + "\n\n" + + fmt.Sprintf(" %s %s\n", labelStyle.Render("Agents:"), valueStyle.Render(fmt.Sprintf("%d", agentCount))) + + fmt.Sprintf(" %s %s", labelStyle.Render("Providers:"), valueStyle.Render(fmt.Sprintf("%d", providerCount))) + statsCard := cardBorder.Width(cardWidth).Render(statsContent) + + // Top row: layout depends on terminal width + if narrowMode { + // Narrow: stack cards vertically + b.WriteString(serverCard) + b.WriteString("\n") + b.WriteString(statsCard) + } else { + // Normal: two cards side by side + topRow := lipgloss.JoinHorizontal(lipgloss.Top, serverCard, " ", statsCard) + b.WriteString(topRow) + } + b.WriteString("\n\n") + + // ─── ACTIVITY GRAPH ─── + graphTitle := titleStyle.Render("Activity") + "\n" + var graphLines []string + graphWidth := width - 4 // Responsive graph width + for row := 7; row >= 0; row-- { + var line strings.Builder + line.WriteString(" ") + sparkLen := min(graphWidth, len(m.spark)) + for i := 0; i < sparkLen; i++ { + v := m.spark[i] + if v >= row { + line.WriteString(lipgloss.NewStyle().Foreground(Green).Render("█")) + } else { + line.WriteString(lipgloss.NewStyle().Foreground(BorderDim).Render("░")) + } + } + graphLines = append(graphLines, line.String()) + } + graphContent := graphTitle + strings.Join(graphLines, "\n") + activityCard := cardBorder.Width(width - 2).Render(graphContent) + b.WriteString(activityCard) + b.WriteString("\n\n") + + // ─── PROVIDERS ─── + providers := []struct { + name string + active bool + color lipgloss.Color + }{ + {"Claude", m.cfg != nil && len(m.cfg.ClaudeKey) > 0, ClaudeBrand}, + {"Gemini", m.cfg != nil && len(m.cfg.GeminiKey) > 0, GeminiBrand}, + {"OpenAI", m.cfg != nil && len(m.cfg.CodexKey) > 0, CodexBrand}, + } + + providerLines := titleStyle.Render("Providers") + "\n" + for _, p := range providers { + icon := lipgloss.NewStyle().Foreground(p.color).Render("●") + name := lipgloss.NewStyle().Foreground(TextDim).Width(10).Render(p.name) + var status string + if p.active { + status = lipgloss.NewStyle().Foreground(Green).Render("Ready") + } else { + status = lipgloss.NewStyle().Foreground(TextMuted).Render("--") + } + providerLines += fmt.Sprintf("\n %s %s %s", icon, name, status) + } + providersCard := cardBorder.Width(width - 2).Render(providerLines) + b.WriteString(providersCard) + + return b.String() +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// SERVER VIEW +// ═══════════════════════════════════════════════════════════════════════════════ + +func (m Model) renderServerView(width, height int) string { + var b strings.Builder + + // Responsive card style + cardBorder := lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(BorderDim). + Padding(0, 1) + + titleStyle := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true) + + labelStyle := lipgloss.NewStyle().Foreground(TextMuted) + valueStyle := lipgloss.NewStyle().Foreground(Accent).Bold(true) + + // Calculate responsive widths + cardWidth := width - 2 + if cardWidth < 20 { + cardWidth = 20 + } + + // For narrow terminals, use single column layout + // For wider terminals, use two-column layout + useWideLayout := width >= 60 + + // ─── STATUS CARD ─── + var statusIcon, statusText string + if m.serverOn { + pulse := []string{"●", "◉", "●", "○"}[m.tick%4] + statusIcon = lipgloss.NewStyle().Foreground(Green).Render(pulse) + statusText = lipgloss.NewStyle().Foreground(Green).Bold(true).Render("Running") + } else { + statusIcon = lipgloss.NewStyle().Foreground(Red).Render("○") + statusText = lipgloss.NewStyle().Foreground(Red).Bold(true).Render("Stopped") + } + + statusContent := titleStyle.Render("Status") + "\n\n" + + fmt.Sprintf(" %s %s", statusIcon, statusText) + + // ─── ENDPOINT CARD ─── + endpoint := fmt.Sprintf("http://%s:%d", m.host, m.port) + // Truncate endpoint for narrow terminals + maxEndpointLen := cardWidth - 14 + if maxEndpointLen < 10 { + maxEndpointLen = 10 + } + if len(endpoint) > maxEndpointLen && !useWideLayout { + endpoint = endpoint[:maxEndpointLen-3] + "..." + } + + endpointContent := titleStyle.Render("Endpoint") + "\n\n" + + fmt.Sprintf(" %s", valueStyle.Render(endpoint)) + + if useWideLayout { + // Two-column layout for wider terminals + halfWidth := (width - 3) / 2 + if halfWidth < 20 { + halfWidth = 20 + } + statusCard := cardBorder.Width(halfWidth).Render(statusContent) + endpointCard := cardBorder.Width(halfWidth).Render(endpointContent) + topRow := lipgloss.JoinHorizontal(lipgloss.Top, statusCard, " ", endpointCard) + b.WriteString(topRow) + } else { + // Single column layout for narrow terminals + statusCard := cardBorder.Width(cardWidth).Render(statusContent) + endpointCard := cardBorder.Width(cardWidth).Render(endpointContent) + b.WriteString(statusCard) + b.WriteString("\n") + b.WriteString(endpointCard) + } + b.WriteString("\n\n") + + // ─── SERVER DETAILS CARD ─── + detailsContent := titleStyle.Render("Details") + "\n" + + // Calculate label width for alignment - adapts to available space + labelWidth := 10 + if width < 50 { + labelWidth = 8 + } + + labels := []string{"Protocol:", "Version:", "Host:", "Port:"} + values := []string{ + "HTTP/1.1, SSE", + "v0.2.0", + m.host, + fmt.Sprintf("%d", m.port), + } + + for i, label := range labels { + labelText := labelStyle.Width(labelWidth).Render(label) + valueText := valueStyle.Render(values[i]) + detailsContent += fmt.Sprintf("\n %s %s", labelText, valueText) + } + + detailsCard := cardBorder.Width(cardWidth).Render(detailsContent) + b.WriteString(detailsCard) + b.WriteString("\n\n") + + // ─── HELP HINT ─── + hintStyle := lipgloss.NewStyle().Foreground(TextMuted) + keyStyle := lipgloss.NewStyle().Foreground(Accent).Bold(true) + + hint := fmt.Sprintf(" %s %s", keyStyle.Render("r"), hintStyle.Render("refresh status")) + b.WriteString(hint) + + return b.String() +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// SETUP VIEW +// ═══════════════════════════════════════════════════════════════════════════════ + +func (m Model) renderSetupView(width, height int) string { + var b strings.Builder + + title := lipgloss.NewStyle().Foreground(Tertiary).Bold(true).Render("Setup") + b.WriteString(title + "\n\n") + + items := []struct { + key string + name string + desc string + }{ + {"1", "Quick Setup", "Guided configuration wizard"}, + {"2", "Provider Login", "Authenticate with AI providers"}, + {"3", "Agent Config", "Configure agent routing modes"}, + {"4", "Edit Config", "Open config.yaml in editor"}, + } + + // Card style that adapts to available width + cardBorder := lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(BorderDim). + Padding(0, 1) + + // Calculate card width based on available space + cardWidth := width - 2 + if cardWidth < 20 { + cardWidth = 20 + } + + for _, item := range items { + key := lipgloss.NewStyle().Foreground(Accent).Bold(true).Render(fmt.Sprintf("[%s]", item.key)) + name := lipgloss.NewStyle().Foreground(Text).Bold(true).Render(item.name) + desc := lipgloss.NewStyle().Foreground(TextMuted).Render(item.desc) + + // Build card content + cardContent := fmt.Sprintf("%s %s\n%s", key, name, desc) + card := cardBorder.Width(cardWidth).Render(cardContent) + b.WriteString(card) b.WriteString("\n") - b.WriteString(styles.StatusMessage.Render(m.message)) } return b.String() } -// viewServer renders the server screen -func (m Model) viewServer() string { - var b strings.Builder +// ═══════════════════════════════════════════════════════════════════════════════ +// FOOTER - Keybindings +// ═══════════════════════════════════════════════════════════════════════════════ - b.WriteString(styles.Title.Render("Server")) - b.WriteString("\n") - b.WriteString(styles.Divider.Render(strings.Repeat("─", 17))) - b.WriteString("\n\n") +func (m Model) renderFooter() string { + keyStyle := lipgloss.NewStyle().Foreground(Accent).Bold(true) + descStyle := lipgloss.NewStyle().Foreground(TextMuted) + sep := lipgloss.NewStyle().Foreground(Border).Render(" │ ") - b.WriteString("Server management screen.\n") - b.WriteString("Press 's' to start/stop the server.\n") + help := keyStyle.Render("↑↓") + descStyle.Render(" nav") + sep + + keyStyle.Render("1-8") + descStyle.Render(" jump") + sep + + keyStyle.Render("⏎") + descStyle.Render(" select") + sep + + keyStyle.Render("r") + descStyle.Render(" refresh") + sep + + keyStyle.Render("q") + descStyle.Render(" quit") - b.WriteString("\n") - b.WriteString(styles.Help.Render("esc/b: back • q: quit")) + timeStr := lipgloss.NewStyle().Foreground(TextMuted).Render(time.Now().Format("15:04:05")) - return b.String() + gap := m.width - lipgloss.Width(help) - lipgloss.Width(timeStr) - 4 + if gap < 0 { + gap = 0 + } + + content := " " + help + strings.Repeat(" ", gap) + timeStr + " " + + return "\n" + lipgloss.NewStyle(). + Background(BgSurface). + Width(m.width). + Render(content) } -// viewSwitch renders the switch agent config screen -func (m Model) viewSwitch() string { - var b strings.Builder +// ═══════════════════════════════════════════════════════════════════════════════ +// RUN - Entry point +// ═══════════════════════════════════════════════════════════════════════════════ - b.WriteString(styles.Title.Render("Switch Agent Config")) - b.WriteString("\n") - b.WriteString(styles.Divider.Render(strings.Repeat("─", 19))) - b.WriteString("\n\n") - - b.WriteString("Switch between different agent configurations.\n") - b.WriteString("Select an agent config to switch to.\n") - - b.WriteString("\n") - b.WriteString(styles.Help.Render("esc/b: back • q: quit")) - - return b.String() -} - -// viewLogin renders the login screen -func (m Model) viewLogin() string { - var b strings.Builder - - b.WriteString(styles.Title.Render("Login to Provider")) - b.WriteString("\n") - b.WriteString(styles.Divider.Render(strings.Repeat("─", 17))) - b.WriteString("\n\n") - - b.WriteString("Login to different AI providers.\n") - b.WriteString("Select a provider to authenticate.\n") - - b.WriteString("\n") - b.WriteString(styles.Help.Render("esc/b: back • q: quit")) - - return b.String() -} - -// viewStatus renders the status screen -func (m Model) viewStatus() string { - var b strings.Builder - - b.WriteString(styles.Title.Render("Status")) - b.WriteString("\n") - b.WriteString(styles.Divider.Render(strings.Repeat("─", 17))) - b.WriteString("\n\n") - - b.WriteString("Current system status.\n") - b.WriteString("Server: Not running\n") - b.WriteString("Active Config: None\n") - - b.WriteString("\n") - b.WriteString(styles.Help.Render("esc/b: back • q: quit")) - - return b.String() -} - -// Run starts the TUI application func Run() error { - p := tea.NewProgram(NewModel(), tea.WithAltScreen()) - _, err := p.Run() + cfg, err := config.LoadConfigOptional("config.yaml", true) + if err != nil || cfg == nil { + cfg = &config.Config{} + } + + host := "127.0.0.1" + port := 8317 + + if cfg.Host != "" { + host = cfg.Host + } + if cfg.Port != 0 { + port = cfg.Port + } + + m := NewModel(cfg, host, port) + p := tea.NewProgram(m, tea.WithAltScreen()) + _, err = p.Run() return err } - -// GetCurrentScreen returns the current screen -func (m Model) GetCurrentScreen() Screen { - return m.currentScreen -} - -// SetMessage sets a status message to display -func (m *Model) SetMessage(msg string) { - m.message = msg -} diff --git a/internal/tui/usage.go b/internal/tui/usage.go new file mode 100644 index 00000000..d001afac --- /dev/null +++ b/internal/tui/usage.go @@ -0,0 +1,808 @@ +package tui + +import ( + "fmt" + "sort" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" + "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" +) + +// ═══════════════════════════════════════════════════════════════════════════════ +// USAGE MODEL - Cyberpunk Statistics Dashboard +// ═══════════════════════════════════════════════════════════════════════════════ + +// UsageModel represents the usage statistics screen +type UsageModel struct { + width int + height int + + // Stats data + totalRequests int64 + successCount int64 + failureCount int64 + requestsToday int64 + requestsByDay map[string]int64 + tokensByModel map[string]int64 + requestsByModel map[string]int64 + + // UI state + selectedTab int + tabs []string + lastRefresh time.Time + cfg *config.Config +} + +// usageRefreshMsg is sent when stats are refreshed +type usageRefreshMsg struct { + totalRequests int64 + successCount int64 + failureCount int64 + requestsToday int64 + requestsByDay map[string]int64 + tokensByModel map[string]int64 + requestsByModel map[string]int64 +} + +// usageTickMsg triggers periodic refresh +type usageTickMsg time.Time + +// NewUsageModel creates a new usage statistics model +func NewUsageModel(cfg *config.Config) UsageModel { + return UsageModel{ + width: 80, + height: 24, + cfg: cfg, + tabs: []string{"OVERVIEW", "MODELS", "HISTORY"}, + selectedTab: 0, + lastRefresh: time.Now(), + requestsByDay: make(map[string]int64), + tokensByModel: make(map[string]int64), + requestsByModel: make(map[string]int64), + } +} + +// Init initializes the usage model +func (m UsageModel) Init() tea.Cmd { + return tea.Batch( + m.refreshStats, + m.tickCmd(), + ) +} + +// tickCmd returns a command for periodic refresh +func (m UsageModel) tickCmd() tea.Cmd { + return tea.Tick(10*time.Second, func(t time.Time) tea.Msg { + return usageTickMsg(t) + }) +} + +// refreshStats fetches current statistics +func (m UsageModel) refreshStats() tea.Msg { + stats := usage.GetRequestStatistics() + if stats == nil { + return usageRefreshMsg{} + } + + snapshot := stats.Snapshot() + today := time.Now().Format("2006-01-02") + requestsToday := int64(0) + if count, ok := snapshot.RequestsByDay[today]; ok { + requestsToday = count + } + + // Extract per-model stats from APIs + tokensByModel := make(map[string]int64) + requestsByModel := make(map[string]int64) + + for _, api := range snapshot.APIs { + for modelName, modelStats := range api.Models { + tokensByModel[modelName] += modelStats.TotalTokens + requestsByModel[modelName] += modelStats.TotalRequests + } + } + + return usageRefreshMsg{ + totalRequests: snapshot.TotalRequests, + successCount: snapshot.SuccessCount, + failureCount: snapshot.FailureCount, + requestsToday: requestsToday, + requestsByDay: snapshot.RequestsByDay, + tokensByModel: tokensByModel, + requestsByModel: requestsByModel, + } +} + +// Update handles messages for the usage model +func (m UsageModel) Update(msg tea.Msg) (UsageModel, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + return m, nil + + case tea.KeyMsg: + switch msg.String() { + case "tab", "l", "right": + m.selectedTab = (m.selectedTab + 1) % len(m.tabs) + case "shift+tab", "h", "left": + m.selectedTab = (m.selectedTab - 1 + len(m.tabs)) % len(m.tabs) + case "r": + return m, m.refreshStats + } + + case usageTickMsg: + return m, tea.Batch(m.refreshStats, m.tickCmd()) + + case usageRefreshMsg: + m.totalRequests = msg.totalRequests + m.successCount = msg.successCount + m.failureCount = msg.failureCount + m.requestsToday = msg.requestsToday + m.requestsByDay = msg.requestsByDay + m.tokensByModel = msg.tokensByModel + m.requestsByModel = msg.requestsByModel + m.lastRefresh = time.Now() + } + + return m, nil +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// VIEW RENDERING - Returns content only (no outer borders) +// The main TUI wraps this in a bordered panel +// ═══════════════════════════════════════════════════════════════════════════════ + +// View renders the usage statistics screen content +func (m UsageModel) View() string { + return m.ViewWithSize(m.width, m.height) +} + +// ViewWithSize renders the usage statistics screen content with specified dimensions +func (m UsageModel) ViewWithSize(width, height int) string { + var b strings.Builder + + // Section title with tabs + title := lipgloss.NewStyle(). + Foreground(Accent). + Bold(true). + Render("Usage Statistics") + refreshTime := m.lastRefresh.Format("15:04:05") + subtitle := lipgloss.NewStyle(). + Foreground(TextMuted). + Render(fmt.Sprintf(" - Last sync: %s", refreshTime)) + b.WriteString(title + subtitle + "\n\n") + + // Tabs + b.WriteString(m.renderTabs()) + b.WriteString("\n\n") + + // Content based on selected tab + switch m.selectedTab { + case 0: + b.WriteString(m.renderOverview(width, height)) + case 1: + b.WriteString(m.renderByModel(width, height)) + case 2: + b.WriteString(m.renderHistory(width, height)) + } + + return b.String() +} + +// renderTabs renders the tab bar +func (m UsageModel) renderTabs() string { + var tabs []string + + for i, tab := range m.tabs { + var style lipgloss.Style + + if i == m.selectedTab { + // Active tab + style = lipgloss.NewStyle(). + Bold(true). + Foreground(BgDark). + Background(Accent). + Padding(0, 1) + } else { + // Inactive tab + style = lipgloss.NewStyle(). + Foreground(TextMuted). + Background(BgPanel). + Padding(0, 1) + } + + tabs = append(tabs, style.Render(tab)) + } + + return lipgloss.JoinHorizontal(lipgloss.Top, tabs...) +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// OVERVIEW TAB - Neon Stat Cards +// ═══════════════════════════════════════════════════════════════════════════════ + +// renderOverview renders the overview statistics with neon cards +func (m UsageModel) renderOverview(width, height int) string { + var b strings.Builder + + // Calculate success rate + successRate := float64(0) + if m.totalRequests > 0 { + successRate = float64(m.successCount) / float64(m.totalRequests) * 100 + } + + // Threshold for single column layout (narrow terminals) + const narrowThreshold = 55 + + // Determine layout based on width + useNarrowLayout := width < narrowThreshold + + var cardWidth int + if useNarrowLayout { + // Single column layout - use full width minus padding + cardWidth = width - 6 + if cardWidth < 20 { + cardWidth = 20 // Minimum card width + } + if cardWidth > 40 { + cardWidth = 40 // Maximum card width for single column + } + } else { + // Two column layout - account for 2 cards per row with spacing + availableWidth := width - 4 + cardWidth = availableWidth / 2 + if cardWidth < 20 { + cardWidth = 20 // Minimum card width + } + if cardWidth > 30 { + cardWidth = 30 // Maximum card width + } + } + + // Create neon stat cards + cards := []string{ + m.renderStatCard("TOTAL REQUESTS", formatLargeNumber(m.totalRequests), Cyan, "pulse", cardWidth), + m.renderStatCard("TODAY", formatLargeNumber(m.requestsToday), ElecBlue, "bolt", cardWidth), + m.renderStatCard("SUCCESS RATE", fmt.Sprintf("%.1f%%", successRate), NeonGreen, "check", cardWidth), + m.renderStatCard("FAILED", formatLargeNumber(m.failureCount), func() lipgloss.Color { + if m.failureCount > 0 { + return HotCoral + } + return TextDim + }(), "warn", cardWidth), + } + + // Arrange cards based on layout + if useNarrowLayout { + // Single column layout - stack all cards vertically + // Limit visible cards based on height (each card ~6 lines) + maxCards := 4 + if height > 0 { + // Reserve lines for header, tabs, breakdown section + availableLines := height - 12 + if availableLines > 0 { + possibleCards := availableLines / 6 + if possibleCards < maxCards && possibleCards > 0 { + maxCards = possibleCards + } + } + } + for i := 0; i < len(cards) && i < maxCards; i++ { + b.WriteString(cards[i]) + if i < len(cards)-1 && i < maxCards-1 { + b.WriteString("\n") + } + } + } else { + // Two column layout - arrange cards in 2x2 grid + row1 := lipgloss.JoinHorizontal(lipgloss.Top, cards[0], " ", cards[1]) + row2 := lipgloss.JoinHorizontal(lipgloss.Top, cards[2], " ", cards[3]) + + b.WriteString(row1) + b.WriteString("\n") + b.WriteString(row2) + } + + // Visual breakdown section + // Calculate breakdown width based on available space + breakdownWidth := width - 8 // Account for padding + if breakdownWidth < 40 { + breakdownWidth = 40 // Minimum width + } + if breakdownWidth > 60 { + breakdownWidth = 60 // Maximum width + } + b.WriteString("\n\n") + b.WriteString(m.renderBreakdown(breakdownWidth)) + + return b.String() +} + +// renderStatCard creates a neon-styled stat card +func (m UsageModel) renderStatCard(label, value string, color lipgloss.Color, icon string, cardWidth int) string { + // Card dimensions + width := cardWidth + + // Icon based on type + var iconChar string + switch icon { + case "pulse": + iconChar = IconPulse + case "bolt": + iconChar = IconBolt + case "check": + iconChar = IconCheck + case "warn": + iconChar = IconWarning + default: + iconChar = IconDiamond + } + + // Build card content + iconStyle := lipgloss.NewStyle(). + Foreground(color). + Bold(true) + + labelStyle := lipgloss.NewStyle(). + Foreground(TextMuted). + Width(width - 4) + + valueStyle := lipgloss.NewStyle(). + Foreground(color). + Bold(true). + Width(width - 4) + + content := fmt.Sprintf("%s %s\n\n%s", + iconStyle.Render(iconChar), + labelStyle.Render(label), + valueStyle.Render(value), + ) + + // Card with neon border + cardStyle := lipgloss.NewStyle(). + Border(SoftBorder). + BorderForeground(color). + Padding(1, 2). + Width(width) + + return cardStyle.Render(content) +} + +// renderBreakdown shows success/failure breakdown with neon progress bar +func (m UsageModel) renderBreakdown(width int) string { + var b strings.Builder + + // Section header + sectionHeader := lipgloss.NewStyle(). + Bold(true). + Foreground(Violet). + Render("REQUEST BREAKDOWN") + + divider := lipgloss.NewStyle(). + Foreground(BorderDim). + Render(strings.Repeat("─", width-20)) + + b.WriteString(sectionHeader) + b.WriteString("\n") + b.WriteString(divider) + b.WriteString("\n\n") + + if m.totalRequests > 0 { + // Calculate proportions + barWidth := width - 10 // Account for margins and borders + successPct := float64(m.successCount) / float64(m.totalRequests) + successBars := int(successPct * float64(barWidth)) + failBars := barWidth - successBars + + // Create gradient progress bar + successBar := m.createGradientBar(successBars, []lipgloss.Color{NeonGreen, GreenMid, GreenDark}) + failBar := "" + if failBars > 0 { + failBar = lipgloss.NewStyle().Foreground(HotCoral).Render(strings.Repeat("█", failBars)) + } + + // Progress bar with glow effect + barContainer := lipgloss.NewStyle(). + Foreground(BorderDim). + Render("│") + + b.WriteString(fmt.Sprintf(" %s%s%s%s\n", barContainer, successBar, failBar, barContainer)) + + // Legend with neon indicators + successIndicator := lipgloss.NewStyle().Foreground(NeonGreen).Bold(true).Render("●") + failIndicator := lipgloss.NewStyle().Foreground(HotCoral).Bold(true).Render("●") + successLabel := lipgloss.NewStyle().Foreground(TextBright).Render(fmt.Sprintf("Success: %s", formatLargeNumber(m.successCount))) + failLabel := lipgloss.NewStyle().Foreground(TextBright).Render(fmt.Sprintf("Failed: %s", formatLargeNumber(m.failureCount))) + separator := lipgloss.NewStyle().Foreground(BorderDim).Render(" │ ") + + b.WriteString(fmt.Sprintf("\n %s %s%s%s %s\n", + successIndicator, successLabel, + separator, + failIndicator, failLabel, + )) + } else { + // Empty state with style + emptyMsg := lipgloss.NewStyle(). + Foreground(TextDim). + Italic(true). + Render(" Awaiting incoming requests...") + + b.WriteString(emptyMsg) + } + + return b.String() +} + +// createGradientBar creates a gradient-colored progress bar +func (m UsageModel) createGradientBar(length int, colors []lipgloss.Color) string { + if length <= 0 { + return "" + } + + var result strings.Builder + for i := 0; i < length; i++ { + colorIdx := i * len(colors) / length + if colorIdx >= len(colors) { + colorIdx = len(colors) - 1 + } + result.WriteString(lipgloss.NewStyle().Foreground(colors[colorIdx]).Render("█")) + } + return result.String() +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// MODELS TAB - Neon Data Table +// ═══════════════════════════════════════════════════════════════════════════════ + +// renderByModel renders statistics grouped by model with neon table +func (m UsageModel) renderByModel(width, height int) string { + var b strings.Builder + + if len(m.requestsByModel) == 0 { + return m.renderEmptyState("MODEL STATISTICS", "Statistics will appear as requests are processed.") + } + + // Calculate responsive column widths based on available width + // Reserve space for: bar indicator (variable), padding/separators (4) + availableWidth := width - 4 + if availableWidth < 40 { + availableWidth = 40 // Minimum usable width + } + + // Calculate bar width based on terminal width + barWidth := 8 + if width >= 100 { + barWidth = 12 + } else if width < 60 { + barWidth = 4 + } + + // Remaining width after bar for columns + tableWidth := availableWidth - barWidth - 2 + + // Allocate columns: model name gets ~50%, requests and tokens get ~25% each + modelColWidth := tableWidth * 50 / 100 + countColWidth := tableWidth * 25 / 100 + tokensColWidth := tableWidth - modelColWidth - countColWidth + + // Ensure minimum column widths + if modelColWidth < 15 { + modelColWidth = 15 + } + if countColWidth < 8 { + countColWidth = 8 + } + if tokensColWidth < 8 { + tokensColWidth = 8 + } + + // Table header with neon accents + headerStyle := lipgloss.NewStyle(). + Bold(true). + Foreground(Cyan). + Width(modelColWidth) + + countHeaderStyle := lipgloss.NewStyle(). + Bold(true). + Foreground(Magenta). + Width(countColWidth). + Align(lipgloss.Right) + + tokensHeaderStyle := lipgloss.NewStyle(). + Bold(true). + Foreground(Violet). + Width(tokensColWidth). + Align(lipgloss.Right) + + // Header row + b.WriteString(headerStyle.Render("MODEL")) + b.WriteString(countHeaderStyle.Render("REQUESTS")) + b.WriteString(tokensHeaderStyle.Render("TOKENS")) + b.WriteString("\n") + + // Neon divider - adapt to total width + dividerWidth := modelColWidth + countColWidth + tokensColWidth + barWidth + 2 + divider := lipgloss.NewStyle(). + Foreground(Violet). + Render(strings.Repeat("━", dividerWidth)) + b.WriteString(divider) + b.WriteString("\n") + + // Sort models by request count for consistent display + type modelStat struct { + name string + requests int64 + tokens int64 + } + var models []modelStat + for model, count := range m.requestsByModel { + models = append(models, modelStat{ + name: model, + requests: count, + tokens: m.tokensByModel[model], + }) + } + sort.Slice(models, func(i, j int) bool { + return models[i].requests > models[j].requests + }) + + // Model rows with alternating subtle highlights + for i, model := range models { + modelName := model.name + // Truncate model name based on column width + maxNameLen := modelColWidth - 3 + if maxNameLen < 5 { + maxNameLen = 5 + } + if len(modelName) > maxNameLen { + modelName = modelName[:maxNameLen-3] + "..." + } + + // Subtle row highlight for alternating rows + rowBg := DeepBlack + if i%2 == 1 { + rowBg = DarkSurface + } + + modelStyle := lipgloss.NewStyle(). + Foreground(TextBright). + Background(rowBg). + Width(modelColWidth) + + countStyle := lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true). + Background(rowBg). + Width(countColWidth). + Align(lipgloss.Right) + + tokensStyle := lipgloss.NewStyle(). + Foreground(ElecBlue). + Background(rowBg). + Width(tokensColWidth). + Align(lipgloss.Right) + + // Request count bar indicator + maxRequests := models[0].requests + barLen := 0 + if maxRequests > 0 { + barLen = int(float64(model.requests) / float64(maxRequests) * float64(barWidth)) + } + bar := lipgloss.NewStyle().Foreground(Cyan).Render(strings.Repeat("▪", barLen)) + emptyBar := lipgloss.NewStyle().Foreground(BorderDim).Render(strings.Repeat("▪", barWidth-barLen)) + + b.WriteString(modelStyle.Render(modelName)) + b.WriteString(countStyle.Render(formatLargeNumber(model.requests))) + b.WriteString(tokensStyle.Render(formatLargeNumber(model.tokens))) + b.WriteString(" ") + b.WriteString(bar) + b.WriteString(emptyBar) + b.WriteString("\n") + } + + return b.String() +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// HISTORY TAB - Neon Timeline +// ═══════════════════════════════════════════════════════════════════════════════ + +// renderHistory renders request history by day with neon visualization +func (m UsageModel) renderHistory(width, height int) string { + var b strings.Builder + + if len(m.requestsByDay) == 0 { + return m.renderEmptyState("REQUEST HISTORY", "History will appear as requests are processed.") + } + + // Calculate responsive bar width + // Reserve 25 chars for: indent(2) + date(12) + connector(3) + count(10) + spacing + barWidth := width - 25 + if barWidth < 10 { + barWidth = 10 // Minimum bar width + } + if barWidth > 50 { + barWidth = 50 // Maximum bar width + } + + // Section header + sectionHeader := lipgloss.NewStyle(). + Bold(true). + Foreground(Magenta). + Render("ACTIVITY TIMELINE") + + subtitle := lipgloss.NewStyle(). + Foreground(TextDim). + Render(" // Last 7 days") + + // Divider adapts to width + dividerWidth := width - 4 + if dividerWidth < 30 { + dividerWidth = 30 + } + divider := lipgloss.NewStyle(). + Foreground(Violet). + Render(strings.Repeat("━", dividerWidth)) + + b.WriteString(sectionHeader) + b.WriteString(subtitle) + b.WriteString("\n") + b.WriteString(divider) + b.WriteString("\n\n") + + // Find max for scaling + maxDaily := int64(0) + for _, c := range m.requestsByDay { + if c > maxDaily { + maxDaily = c + } + } + + // Date and bar styling + dateStyle := lipgloss.NewStyle(). + Foreground(TextMuted). + Width(12) + + todayStyle := lipgloss.NewStyle(). + Foreground(Cyan). + Bold(true). + Width(12) + + // Get last 7 days + today := time.Now() + + // Gradient colors for the bars + barColors := []lipgloss.Color{Cyan, ElecBlue, Violet, Magenta} + + for i := 0; i < 7; i++ { + date := today.AddDate(0, 0, -i) + dateStr := date.Format("2006-01-02") + count := m.requestsByDay[dateStr] + + // Format date display + displayDate := date.Format("Jan 02") + var formattedDate string + if i == 0 { + formattedDate = todayStyle.Render("Today") + } else if i == 1 { + formattedDate = dateStyle.Render("Yesterday") + } else { + formattedDate = dateStyle.Render(displayDate) + } + + // Calculate bar length + barLen := 0 + if count > 0 && maxDaily > 0 { + barLen = int(float64(count) / float64(maxDaily) * float64(barWidth)) + if barLen < 1 && count > 0 { + barLen = 1 + } + } + + // Create gradient bar + bar := m.createGradientBar(barLen, barColors) + emptyBar := lipgloss.NewStyle().Foreground(BorderDim).Render(strings.Repeat("░", barWidth-barLen)) + + // Count display + countDisplay := lipgloss.NewStyle(). + Foreground(func() lipgloss.Color { + if count > 0 { + return TextBright + } + return TextDim + }()). + Width(10). + Align(lipgloss.Right). + Render(formatLargeNumber(count)) + + // Timeline connector + connector := lipgloss.NewStyle().Foreground(Violet).Render("│") + + b.WriteString(fmt.Sprintf(" %s %s %s%s %s\n", + formattedDate, + connector, + bar, + emptyBar, + countDisplay, + )) + } + + return b.String() +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// HELPER COMPONENTS +// ═══════════════════════════════════════════════════════════════════════════════ + +// renderEmptyState creates a styled empty state message +func (m UsageModel) renderEmptyState(title, message string) string { + var b strings.Builder + + // Empty state container + iconStyle := lipgloss.NewStyle(). + Foreground(TextDim). + Render(IconPending) + + titleStyle := lipgloss.NewStyle(). + Foreground(TextMuted). + Bold(true). + Render(title) + + msgStyle := lipgloss.NewStyle(). + Foreground(TextDim). + Italic(true). + Render(message) + + b.WriteString(fmt.Sprintf("\n %s %s\n\n", iconStyle, titleStyle)) + b.WriteString(fmt.Sprintf(" %s\n", msgStyle)) + + return b.String() +} + +// renderHelp renders the help footer with cyber styling +func (m UsageModel) renderHelp() string { + // Help bar with neon key hints + divider := lipgloss.NewStyle(). + Foreground(BorderDim). + Render(strings.Repeat("─", 56)) + + keyStyle := lipgloss.NewStyle(). + Foreground(Violet). + Bold(true) + + descStyle := lipgloss.NewStyle(). + Foreground(TextDim) + + separator := lipgloss.NewStyle(). + Foreground(BorderDim). + Render(" │ ") + + help := fmt.Sprintf("%s %s%s%s %s%s%s %s", + keyStyle.Render("[Tab/Arrow]"), + descStyle.Render("Navigate"), + separator, + keyStyle.Render("[R]"), + descStyle.Render("Refresh"), + separator, + keyStyle.Render("[Esc]"), + descStyle.Render("Back"), + ) + + return fmt.Sprintf("\n%s\n%s", divider, help) +} + +// formatLargeNumber formats numbers with K/M suffixes +func formatLargeNumber(n int64) string { + if n >= 1000000 { + return fmt.Sprintf("%.1fM", float64(n)/1000000) + } + if n >= 1000 { + return fmt.Sprintf("%.1fK", float64(n)/1000) + } + return fmt.Sprintf("%d", n) +} diff --git a/internal/tui/utils.go b/internal/tui/utils.go index 0234f40b..befac8bc 100644 --- a/internal/tui/utils.go +++ b/internal/tui/utils.go @@ -368,23 +368,7 @@ func FormatDuration(d time.Duration) string { return fmt.Sprintf("%ds", seconds) } -// FormatCount formats a count with appropriate suffix (K, M, B). -// Examples: "1,234", "12.3K", "1.5M" -func FormatCount(n int64) string { - if n < 1000 { - return fmt.Sprintf("%d", n) - } - - if n < 1000000 { - return fmt.Sprintf("%.1fK", float64(n)/1000) - } - - if n < 1000000000 { - return fmt.Sprintf("%.1fM", float64(n)/1000000) - } - - return fmt.Sprintf("%.1fB", float64(n)/1000000000) -} +// FormatCount is defined in styles.go - removed duplicate // FormatCountWithCommas formats a count with comma separators. // Examples: "1,234", "1,234,567"