dashboard.go
332 lines1
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"congo.gg/dev/internal"
"congo.gg/dev/models"
"congo.gg/pkg/application"
)
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, then cache infra configs
go func() {
internal.SyncFromFilesystem()
internal.InitInfraCache()
}()
// Dashboard (root path)
app.Handle("GET /{$}", app.Serve("dashboard.html", RequireAuth()))
app.Handle("GET /getting-started", app.Serve("getting-started.html", RequireAuth()))
app.Handle("GET /stats", app.Method(c, "Stats", RequireAuth()))
app.Handle("GET /api/stats", app.Method(c, "APIStats", RequireAuth()))
app.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()))
app.Handle("GET /coder/{path...}", coderPathProxy)
app.Handle("POST /coder/{path...}", coderPathProxy)
app.Handle("PUT /coder/{path...}", coderPathProxy)
app.Handle("DELETE /coder/{path...}", coderPathProxy)
// Code-server management
app.Handle("POST /coder/restart", app.Method(c, "RestartCoder", RequireAuth()))
// Domain management
app.Handle("POST /dashboard/setup-domain", app.Method(c, "SetupDomain", RequireAuth()))
// Cron management
app.Handle("GET /cron", app.Method(c, "CronList", RequireAuth()))
app.Handle("POST /cron/create", app.Method(c, "CronCreate", RequireAuth()))
app.Handle("POST /cron/delete", app.Method(c, "CronDelete", RequireAuth()))
// Redirects from old pages to dashboard
for _, path := range []string{"/services", "/repos", "/routes", "/agent"} {
app.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
})
}
}
// ─── Template methods ───────────────────────────────────────────────────────
func (c *DashboardController) SystemStats() *internal.SystemStats {
return internal.GetSystemStats()
}
// RunningContainers returns all running Docker containers for dashboard display.
func (c *DashboardController) RunningContainers() []internal.RunningContainer {
return internal.AllRunningContainers()
}
// 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()
}
// ClaudeProcess represents a running Claude Code instance.
type ClaudeProcess struct {
PID string
Command string
Running bool
}
// ClaudeProcesses checks for running Claude instances in the code-server container.
func (c *DashboardController) ClaudeProcesses() []ClaudeProcess {
output, err := internal.CoderExec("ps aux | grep '[c]laude' | head -5")
if err != nil || strings.TrimSpace(output) == "" {
return nil
}
var procs []ClaudeProcess
for _, line := range strings.Split(strings.TrimSpace(output), "\n") {
fields := strings.Fields(line)
if len(fields) < 11 {
continue
}
procs = append(procs, ClaudeProcess{
PID: fields[1],
Command: strings.Join(fields[10:], " "),
Running: true,
})
}
return procs
}
// ActivityGroup is a set of consecutive log entries with the same type.
type ActivityGroup struct {
Action string
Items []*models.LogEntry
}
// First returns the most recent entry in the group (for timestamps).
func (g ActivityGroup) First() *models.LogEntry { return g.Items[0] }
// Count returns the number of items in the group.
func (g ActivityGroup) Count() int { return len(g.Items) }
// Single returns true if the group has exactly one item.
func (g ActivityGroup) Single() bool { return len(g.Items) == 1 }
// RecentActivity returns log entries grouped by consecutive type.
func (c *DashboardController) RecentActivity() []ActivityGroup {
entries, _ := models.LogEntries.Search("ORDER BY CreatedAt DESC LIMIT 30")
if len(entries) == 0 {
return nil
}
var groups []ActivityGroup
current := ActivityGroup{Action: entries[0].Type, Items: []*models.LogEntry{entries[0]}}
for _, entry := range entries[1:] {
if entry.Type == current.Action {
current.Items = append(current.Items, entry)
} else {
groups = append(groups, current)
current = ActivityGroup{Action: entry.Type, Items: []*models.LogEntry{entry}}
}
}
groups = append(groups, current)
// Cap to 15 groups
if len(groups) > 15 {
groups = groups[:15]
}
return groups
}
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 {
return len(internal.AllRunningContainers())
}
// ServicesByRepo returns a map of repo ID → service count from infra.json.
func (c *DashboardController) ServicesByRepo() map[string]int {
result := make(map[string]int)
for _, svc := range internal.AllLocalServices() {
if svc.RepoID != "" {
result[svc.RepoID]++
}
}
return result
}
// ActiveTasks returns user-created task checklist items.
func (c *DashboardController) ActiveTasks() []*models.Task {
tasks, _ := models.Tasks.Search("ORDER BY CreatedAt DESC LIMIT 15")
return tasks
}
// CronJobs returns cron entries from code-server.
func (c *DashboardController) CronJobs() []internal.CronJob {
return internal.ListCronJobs()
}
// ─── 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) {
containers := internal.AllRunningContainers()
type status struct {
Name string `json:"name"`
Repo string `json:"repo"`
Status string `json:"status"`
Ports string `json:"ports"`
Domain string `json:"domain"`
}
var result []status
for _, ct := range containers {
result = append(result, status{
Name: ct.Name,
Repo: ct.RepoName,
Status: "running",
Ports: ct.ShortPorts(),
Domain: ct.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.LogEntries.Insert(&models.LogEntry{
Type: "coder_restart",
Summary: "Restarted VS Code server",
Author: "system",
})
}()
c.Refresh(w, r)
}
func (c *DashboardController) CronList(w http.ResponseWriter, r *http.Request) {
c.Render(w, r, "cron-list.html", internal.ListCronJobs())
}
func (c *DashboardController) CronCreate(w http.ResponseWriter, r *http.Request) {
schedule := r.FormValue("schedule")
command := r.FormValue("command")
comment := r.FormValue("comment")
if schedule == "" || command == "" {
c.RenderError(w, r, fmt.Errorf("schedule and command are required"))
return
}
// Basic validation: schedule must have 5 fields
if len(strings.Fields(schedule)) != 5 {
c.RenderError(w, r, fmt.Errorf("schedule must have 5 fields (e.g. */5 * * * *)"))
return
}
comment = strings.ReplaceAll(comment, "\n", " ")
comment = strings.ReplaceAll(comment, "\r", " ")
if err := internal.AddCronJob(schedule, command, comment); err != nil {
c.RenderError(w, r, err)
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "cron_create",
Summary: fmt.Sprintf("Created cron: %s %s", schedule, command),
Author: "system",
})
c.Render(w, r, "cron-list.html", internal.ListCronJobs())
}
func (c *DashboardController) CronDelete(w http.ResponseWriter, r *http.Request) {
schedule := r.FormValue("schedule")
command := r.FormValue("command")
if err := internal.RemoveCronJob(schedule, command); err != nil {
c.RenderError(w, r, err)
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "cron_delete",
Summary: "Removed cron job",
Author: "system",
})
c.Render(w, r, "cron-list.html", internal.ListCronJobs())
}
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.LogEntries.Insert(&models.LogEntry{
Type: "domain_setup",
Summary: fmt.Sprintf("Refreshed domain %s", domain),
Author: "system",
})
c.Refresh(w, r)
}