dashboard.go

245 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"congo.gg/pkg/application"
	"congo.gg/dev/internal"
	"congo.gg/dev/models"
)

func Dashboard() (string, *DashboardController) {
	return "dashboard", &DashboardController{}
}

type DashboardController struct {
	application.BaseController
}

func (c *DashboardController) Setup(app *application.App) {
	c.BaseController.Setup(app)

	// Start code-server
	if err := internal.EnsureCoder(); err != nil {
		fmt.Printf("congo-dev: failed to start code-server: %v\n", err)
	}

	// Sync filesystem repos with DB
	go internal.SyncFromFilesystem()

	// Dashboard (root path)
	http.Handle("GET /{$}", app.Serve("dashboard.html", RequireAuth()))
	http.Handle("GET /stats", app.Method(c, "Stats", RequireAuth()))
	http.Handle("GET /api/stats", app.Method(c, "APIStats", RequireAuth()))
	http.Handle("GET /api/services/status", app.Method(c, "APIServicesStatus", RequireAuth()))

	// Code-server proxy — auth-wrapped
	// Path-based access at /coder/ and host-based access at code.* subdomain
	coderPathProxy := AuthMiddleware(http.StripPrefix("/coder", internal.CoderProxy()))
	http.Handle("GET /coder/{path...}", coderPathProxy)
	http.Handle("POST /coder/{path...}", coderPathProxy)
	http.Handle("PUT /coder/{path...}", coderPathProxy)
	http.Handle("DELETE /coder/{path...}", coderPathProxy)

	// Code-server management
	http.Handle("POST /coder/restart", app.Method(c, "RestartCoder", RequireAuth()))

	// Domain management
	http.Handle("POST /dashboard/setup-domain", app.Method(c, "SetupDomain", RequireAuth()))

	// Redirects from old pages to dashboard
	for _, path := range []string{"/services", "/repos", "/routes", "/agent"} {
		http.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
			http.Redirect(w, r, "/", http.StatusSeeOther)
		})
	}
}

func (c DashboardController) Handle(r *http.Request) application.Controller {
	c.Request = r
	return &c
}

// ─── Template methods ───────────────────────────────────────────────────────

func (c *DashboardController) SystemStats() *internal.SystemStats {
	return internal.GetSystemStats()
}

func (c *DashboardController) Services() []*models.Service {
	services, _ := models.Services.Search("ORDER BY CreatedAt DESC")
	return services
}

// AllServices returns services with live status from Docker.
func (c *DashboardController) AllServices() []*models.Service {
	services, _ := models.Services.Search("ORDER BY CreatedAt DESC")
	for _, s := range services {
		if internal.IsContainerRunning("svc-" + s.Slug) {
			s.Status = "running"
		} else if s.Status == "running" {
			s.Status = "stopped"
		}
	}
	return services
}

// Repositories returns all repos ordered by update time.
func (c *DashboardController) Repositories() []*models.Repository {
	repos, _ := models.Repositories.Search("ORDER BY UpdatedAt DESC")
	return repos
}

// AvailableRepos returns repos available for deployment.
func (c *DashboardController) AvailableRepos() []*models.Repository {
	repos, _ := models.Repositories.Search("WHERE Status != 'missing' ORDER BY Name")
	return repos
}

// Routes returns all domain records.
func (c *DashboardController) Routes() []*models.Domain {
	domains, _ := models.Domains.Search("ORDER BY System DESC, Host ASC")
	return domains
}

// Conversations returns recent agent conversations.
func (c *DashboardController) Conversations() []*models.Conversation {
	convs, _ := models.Conversations.Search("ORDER BY UpdatedAt DESC LIMIT 20")
	return convs
}

// HasAgent checks if the Claude Code CLI is authenticated.
func (c *DashboardController) HasAgent() bool {
	return internal.IsAgentAvailable()
}

func (c *DashboardController) RecentActivity() []*models.Activity {
	acts, _ := models.Activities.Search("ORDER BY CreatedAt DESC LIMIT 20")
	return acts
}

func (c *DashboardController) IsCoderRunning() bool {
	return internal.IsCoderRunning()
}

func (c *DashboardController) Domain() string {
	return internal.SystemDomain()
}

func (c *DashboardController) HasDomain() bool {
	return internal.SystemDomain() != ""
}

func (c *DashboardController) RepoCount() int {
	count, _ := models.Repositories.Count("")
	return count
}

func (c *DashboardController) RunningServiceCount() int {
	services, _ := models.Services.Search("WHERE Status = ?", "running")
	return len(services)
}

// ActiveTasks returns running and recently completed tasks.
func (c *DashboardController) ActiveTasks() []*models.Task {
	tasks, _ := models.Tasks.Search("WHERE Status IN ('running', 'completed', 'failed') ORDER BY CreatedAt DESC LIMIT 10")
	return tasks
}

// InfraContainers returns non-service infrastructure containers (caddy, dev, coder, website).
func (c *DashboardController) InfraContainers() []map[string]string {
	containers, err := internal.ListContainers()
	if err != nil {
		return nil
	}
	// Filter to only infra containers (not svc-* user services)
	var infra []map[string]string
	for _, ct := range containers {
		name := strings.TrimPrefix(ct.Name, "/")
		if strings.HasPrefix(name, "svc-") {
			continue
		}
		status := "stopped"
		if ct.State == "running" {
			status = "running"
		}
		infra = append(infra, map[string]string{
			"Name":   name,
			"Status": status,
			"Image":  ct.Image,
		})
	}
	return infra
}

// ─── Handlers ───────────────────────────────────────────────────────────────

func (c *DashboardController) Stats(w http.ResponseWriter, r *http.Request) {
	c.Render(w, r, "system-bar.html", internal.GetSystemStats())
}

func (c *DashboardController) APIStats(w http.ResponseWriter, r *http.Request) {
	stats := internal.GetSystemStats()
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(stats)
}

func (c *DashboardController) APIServicesStatus(w http.ResponseWriter, r *http.Request) {
	services, _ := models.Services.All()
	type status struct {
		ID     string `json:"id"`
		Name   string `json:"name"`
		Slug   string `json:"slug"`
		Status string `json:"status"`
		Port   int    `json:"port"`
		Domain string `json:"domain"`
	}
	var result []status
	for _, s := range services {
		st := "stopped"
		if internal.IsContainerRunning("svc-" + s.Slug) {
			st = "running"
		}
		result = append(result, status{
			ID:     s.ID,
			Name:   s.Name,
			Slug:   s.Slug,
			Status: st,
			Port:   s.Port,
			Domain: s.Domain,
		})
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}

func (c *DashboardController) RestartCoder(w http.ResponseWriter, r *http.Request) {
	go func() {
		internal.CoderRestart()
		models.Activities.Insert(&models.Activity{
			Action: "coder_restart",
			Detail: "Restarted VS Code server",
		})
	}()
	c.Refresh(w, r)
}

func (c *DashboardController) SetupDomain(w http.ResponseWriter, r *http.Request) {
	domain := internal.SystemDomain()
	if domain == "" {
		c.RenderError(w, r, fmt.Errorf("no domain configured"))
		return
	}
	if err := internal.SetupDomain(domain); err != nil {
		c.RenderError(w, r, fmt.Errorf("domain setup failed: %v", err))
		return
	}
	models.Activities.Insert(&models.Activity{
		Action: "domain_setup",
		Detail: fmt.Sprintf("Refreshed domain %s", domain),
	})
	c.Refresh(w, r)
}