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
This commit is contained in:
Finessse
2025-12-30 08:45:56 +07:00
parent bd7575ca2b
commit 6982a4cc31
10 changed files with 4296 additions and 853 deletions
+552
View File
@@ -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
}
+251 -60
View File
@@ -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) {
+534
View File
@@ -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, " ")
}
+354
View File
@@ -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)
}
+349 -95
View File
@@ -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()
}
+396 -331
View File
@@ -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),
)
}
+390 -69
View File
@@ -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)
+661 -281
View File
File diff suppressed because it is too large Load Diff
+808
View File
@@ -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)
}
+1 -17
View File
@@ -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"