-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
4226 lines (3974 loc) · 123 KB
/
Copy pathmain.go
File metadata and controls
4226 lines (3974 loc) · 123 KB
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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"database/sql"
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
osexec "os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
_ "modernc.org/sqlite"
"github.com/yuin/goldmark"
)
//go:embed templates/* static/* docs/*
var embeddedFiles embed.FS
const (
StatusBacklog = "backlog"
StatusQueued = "queued"
StatusInProgress = "in_progress"
StatusInReview = "in_review"
StatusDone = "done"
StatusClosed = "closed"
AutonomyAutonomous = "autonomous"
AutonomySupervised = "supervised"
QueueItemAwaitingHuman = "awaiting_human"
QueueItemCompleted = "completed"
QueueItemFailed = "failed"
QueueItemRunning = "running"
QueueItemStopped = "stopped"
QueueItemSkipped = "skipped"
)
var validStatuses = map[string]bool{
StatusBacklog: true,
StatusQueued: true,
StatusInProgress: true,
StatusInReview: true,
StatusDone: true,
StatusClosed: true,
}
var uiWritableStatuses = map[string]bool{
StatusBacklog: true,
StatusQueued: true,
StatusInProgress: true,
StatusInReview: true,
StatusDone: true,
}
var botWritableStatuses = map[string]bool{
StatusBacklog: true,
StatusInProgress: true,
StatusDone: true,
}
type App struct {
db *sql.DB
templates *template.Template
agentMu sync.Mutex
agentStatus AgentStatus
agentCancel context.CancelFunc
streamMu sync.Mutex
streams map[chan string]bool
}
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"`
WorkingDirectory string `json:"workingDirectory"`
AutonomyMode string `json:"autonomyMode"`
DefaultBranchOverride string `json:"defaultBranchOverride"`
PRBaseBranch string `json:"prBaseBranch"`
QualityGateMode string `json:"qualityGateMode"`
DeleteBranchOnMerge bool `json:"deleteBranchOnMerge"`
BranchNameTemplate string `json:"branchNameTemplate"`
NextStoryNumber int `json:"nextStoryNumber"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
const (
QualityGateStrict = "strict"
QualityGateWarn = "warn"
DefaultBranchNameTemplate = "ripple/{id}-{slug}"
eventQualityGateWarned = "quality_gate_warned"
)
type Epic struct {
ID string `json:"id"`
ProjectID string `json:"projectId"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type Story struct {
ID string `json:"id"`
ProjectID string `json:"projectId"`
ProjectName string `json:"projectName,omitempty"`
ProjectPrefix string `json:"projectPrefix,omitempty"`
EpicID *string `json:"epicId"`
EpicName *string `json:"epicName,omitempty"`
Title string `json:"title"`
Description string `json:"description"`
Status string `json:"status"`
CloseComment string `json:"closeComment,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ClosedAt *time.Time `json:"closedAt"`
QueuePosition *int `json:"-"`
}
type QueueRunItem struct {
ID int64
QueueRunID int64
Story Story
Position int
Status string
}
type StoryEvent struct {
ID int64 `json:"id"`
StoryID string `json:"storyId"`
Type string `json:"type"`
Message string `json:"message"`
CreatedAt time.Time `json:"createdAt"`
}
type BoardData struct {
Projects []Project
Epics []Epic
StoriesByCol map[string][]Story
SelectedProject string
SelectedEpic string
ShowClosed bool
StatusColumns []string
HasDetailStory bool
Detail StoryPanelData
Dashboard DashboardData
Agent AgentPanelData
}
type StoryPanelData struct {
Story Story
Events []StoryEvent
Pipeline *StoryPipeline
}
type DashboardData struct {
Scope string
ProjectCount int
EpicCount int
Counts StatusCounts
Projects []ProjectDashboard
Project Project
Epic Epic
Heatmap []HeatmapDay
HeatmapTotal int
}
type AgentStatus struct {
Running bool
QueueRunID int64
CurrentStoryID string
Message string
LastError string
StartedAt time.Time
FinishedAt time.Time
Completed int
Total int
}
type AgentPanelData struct {
Status AgentStatus
QueuedCount int
MissingPathProjects []Project
Activity AgentActivityData
ActionError string
ActionErrorAgentsLink bool
}
type FolderPickerData struct {
Project Project
Path string
Parent string
Home string
Directories []FolderEntry
Error string
SuggestedGitRoot string
GitRootDiffers bool
}
type FolderEntry struct {
Name string
Path string
}
type AgentActivityData struct {
LatestRun QueueRunSummary
StoryRuns []AgentRunSummary
}
type QueueRunSummary struct {
ID int64
Status string
ProjectID string
EpicID string
Total int
Completed int
Message string
Error string
StartedAt time.Time
FinishedAt *time.Time
}
type AgentRunSummary struct {
ID int64
QueueRunID int64
StoryID string
StoryTitle string
RunKind string
Status string
WorkingDirectory string
Branch string
PRNumber int
PRURL string
Stdout string
Stderr string
FinalMessage string
ExitError string
StartedAt time.Time
FinishedAt *time.Time
LogItems []AgentLogItem
}
type AgentLogItem struct {
Kind string
Text string
}
type PageData struct {
Page string
Projects []Project
Project Project
Dashboard DashboardData
Backlog BacklogPageData
Run RunPageData
HasDetailStory bool
Detail StoryPanelData
CurrentAgent AgentStatus
ActiveRun QueueRunSummary
SettingsAgents SettingsAgentsData
GitHubIdentity GitHubIdentityView
}
type BacklogPageData struct {
Project Project
Epics []Epic
Stories []Story
Queued []Story
SelectedEpic string
SelectedStatus string
Counts StatusCounts
}
type RunPageData struct {
Project Project
Run QueueRunSummary
Runs []QueueRunSummary
Items []QueueRunItem
LiveQueue []Story
Activity AgentActivityData
Agent AgentStatus
MissingPath bool
Legacy bool
Summary RunCompletionSummary
// ActionError is a user-facing message from a failed UI action (query ?error=).
ActionError string
// ActionErrorAgentsLink shows a Settings → Agents shortcut for tooling/config errors.
ActionErrorAgentsLink bool
}
type RunCompletionSummary struct {
Elapsed string
AgentSteps int
PullRequests []RunPullRequest
MergedPRs []RunPullRequest
AwaitingHumanPRs []RunPullRequest
OpenPRs []RunPullRequest
MergedCount int
AwaitingHumanCount int
}
type RunPullRequest struct {
StoryID string
StoryTitle string
Number int
URL string
Branch string
// Outcome is "merged", "awaiting_human", or "open" for run completion UI.
Outcome string
// HasMergeConflict disables merge and surfaces a warning for awaiting-human PRs.
HasMergeConflict bool
ConflictDetail string
}
type ProjectDashboard struct {
Project Project
EpicCount int
Counts StatusCounts
}
type StatusCounts struct {
Backlog int
Queued int
InProgress int
InReview int
Done int
Closed int
Total int
}
type HeatmapDay struct {
Date string
Count int
Level int
}
func main() {
var (
addr = flag.String("addr", defaultEnv("RIPPLE_ADDR", defaultEnv("TASKMANAGER_ADDR", ":8080")), "HTTP listen address")
dbPath = flag.String("db", defaultRippleDBPath(), "SQLite database path")
)
flag.Parse()
if err := os.MkdirAll(filepath.Dir(dbFilePath(*dbPath)), 0755); err != nil {
log.Fatal(err)
}
db, err := sql.Open("sqlite", *dbPath)
if err != nil {
log.Fatal(err)
}
defer db.Close()
app, err := NewApp(db)
if err != nil {
log.Fatal(err)
}
if err := app.migrate(context.Background()); err != nil {
log.Fatal(err)
}
log.Printf("Ripple listening on http://localhost%s", strings.TrimPrefix(*addr, "0.0.0.0"))
log.Fatal(http.ListenAndServe(*addr, app.routes()))
}
func NewApp(db *sql.DB) (*App, error) {
db.SetMaxOpenConns(1)
funcs := template.FuncMap{
"statusTitle": statusTitle,
"runKindTitle": runKindTitle,
"runKindSource": runKindSource,
"eventTitle": eventTitle,
"queueItemStatusTitle": queueItemStatusTitle,
"truncateText": truncate,
"markdown": func(s string) template.HTML {
var buf bytes.Buffer
if err := goldmark.Convert([]byte(s), &buf); err != nil {
return template.HTML(template.HTMLEscapeString(s))
}
return template.HTML(buf.String())
},
"coalesce": func(v *string, fallback string) string {
if v == nil || *v == "" {
return fallback
}
return *v
},
"urlquery": url.QueryEscape,
}
tpl, err := template.New("").Funcs(funcs).ParseFS(embeddedFiles, "templates/*.html")
if err != nil {
return nil, err
}
return &App{db: db, templates: tpl, streams: make(map[chan string]bool)}, nil
}
func (a *App) routes() http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /static/", http.FileServerFS(embeddedFiles))
mux.HandleFunc("GET /", a.handleDashboard)
mux.HandleFunc("GET /about", a.handleAbout)
mux.HandleFunc("GET /settings", a.handleSettings)
mux.HandleFunc("POST /settings/agents", a.handleUIAgentSettings)
mux.HandleFunc("POST /settings/github-identity", a.handleUIGitHubIdentity)
mux.HandleFunc("POST /settings/agents/api-providers", a.handleUICreateAPIProvider)
mux.HandleFunc("POST /settings/agents/api-providers/{id}", a.handleUIUpdateAPIProvider)
mux.HandleFunc("POST /settings/agents/api-providers/{id}/delete", a.handleUIDeleteAPIProvider)
mux.HandleFunc("POST /settings/agents/api-providers/{id}/test", a.handleUITestAPIProvider)
mux.HandleFunc("GET /board", a.handleBoardPartial)
mux.HandleFunc("GET /projects/{id}/backlog", a.handleProjectBacklog)
mux.HandleFunc("GET /projects/{id}/run", a.handleProjectRun)
mux.HandleFunc("GET /projects/{id}/run/content", a.handleProjectRunContent)
mux.HandleFunc("GET /projects/{id}/runs/{runID}", a.handleProjectRun)
mux.HandleFunc("POST /projects/{id}/queue/reorder", a.handleUIQueueReorder)
mux.HandleFunc("GET /stories/{id}/panel", a.handleStoryPanel)
mux.HandleFunc("POST /stories/{id}/status", a.handleUIStatus)
mux.HandleFunc("POST /stories/{id}/description", a.handleUIDescription)
mux.HandleFunc("POST /stories/{id}/address-feedback", a.handleUIAddressFeedback)
mux.HandleFunc("POST /stories/{id}/resolve-conflicts", a.handleUIResolveConflicts)
mux.HandleFunc("POST /stories/{id}/merge", a.handleUIMergeStory)
mux.HandleFunc("POST /stories/{id}/sync-pr", a.handleUISyncPR)
mux.HandleFunc("POST /stories/{id}/close", a.handleUIClose)
mux.HandleFunc("POST /stories/close-done", a.handleUICloseDone)
mux.HandleFunc("POST /stories/queue-backlog", a.handleUIQueueBacklog)
mux.HandleFunc("POST /projects/{id}/working-directory", a.handleUIProjectWorkingDirectory)
mux.HandleFunc("POST /projects/{id}/settings", a.handleUIProjectSettings)
mux.HandleFunc("GET /projects/{id}/setup-status", a.handleProjectSetupStatus)
mux.HandleFunc("POST /projects/{id}/use-git-root", a.handleUIUseGitRoot)
mux.HandleFunc("POST /projects/{id}/clone", a.handleUICloneRepo)
mux.HandleFunc("POST /projects", a.handleUICreateProject)
mux.HandleFunc("GET /folder-picker", a.handleUIFolderPicker)
mux.HandleFunc("POST /agent/run-queue", a.handleUIRunQueue)
mux.HandleFunc("POST /agent/stop", a.handleUIStopAgent)
mux.HandleFunc("GET /agent/status", a.handleUIAgentStatus)
mux.HandleFunc("GET /agent/activity", a.handleUIAgentActivity)
mux.HandleFunc("GET /agent/events", a.handleUIAgentEvents)
mux.HandleFunc("GET /api", a.handleAPIRoot)
mux.HandleFunc("GET /api/docs", a.handleBotDocs)
mux.HandleFunc("GET /api/openapi.yaml", a.handleOpenAPI)
mux.HandleFunc("GET /api/projects", a.handleAPIProjects)
mux.HandleFunc("POST /api/projects", a.handleAPIProjects)
mux.HandleFunc("GET /api/epics", a.handleAPIEpics)
mux.HandleFunc("POST /api/epics", a.handleAPIEpics)
mux.HandleFunc("GET /api/stories", a.handleAPIStories)
mux.HandleFunc("POST /api/stories", a.handleAPIStories)
mux.HandleFunc("GET /api/stories/{id}", a.handleAPIStory)
mux.HandleFunc("PATCH /api/stories/{id}", a.handleAPIStory)
mux.HandleFunc("PATCH /api/stories/{id}/status", a.handleAPIStoryStatus)
mux.HandleFunc("GET /api/stories/{id}/events", a.handleAPIStoryEvents)
return logging(mux)
}
func (a *App) handleAbout(w http.ResponseWriter, r *http.Request) {
projects, err := a.listProjects(r.Context())
if err != nil {
httpError(w, err)
return
}
a.render(w, "layout.html", PageData{Page: "about", Projects: projects, CurrentAgent: a.currentAgentStatus()})
}
func (a *App) handleSettings(w http.ResponseWriter, r *http.Request) {
projects, err := a.listProjects(r.Context())
if err != nil {
httpError(w, err)
return
}
flash := strings.TrimSpace(r.URL.Query().Get("flash"))
agents, err := a.settingsAgentsData(r.Context(), flash)
if err != nil {
httpError(w, err)
return
}
ghIdentity, err := a.githubIdentityView(r.Context(), flash)
if err != nil {
httpError(w, err)
return
}
a.render(w, "layout.html", PageData{
Page: "settings",
Projects: projects,
CurrentAgent: a.currentAgentStatus(),
SettingsAgents: agents,
GitHubIdentity: ghIdentity,
})
}
func (a *App) handleUIAgentSettings(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httpError(w, err)
return
}
err := a.saveAgentSettingsFromForm(r.Context(),
r.FormValue("implementerProviderId"),
r.FormValue("reviewerProviderId"),
r.FormValue("codexBinaryPath"),
r.FormValue("grokBinaryPath"),
)
if err != nil {
httpError(w, err)
return
}
http.Redirect(w, r, "/settings?flash=saved#agents", http.StatusSeeOther)
}
func (a *App) handleUIGitHubIdentity(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httpError(w, err)
return
}
form := map[string]string{
"prAuthorMode": r.FormValue("prAuthorMode"),
"commitMode": r.FormValue("commitMode"),
"commentMode": r.FormValue("commentMode"),
"commitName": r.FormValue("commitName"),
"commitEmail": r.FormValue("commitEmail"),
"humanName": r.FormValue("humanName"),
"humanEmail": r.FormValue("humanEmail"),
"botToken": r.FormValue("botToken"),
"clearBotToken": r.FormValue("clearBotToken"),
}
if err := a.saveGitHubIdentityFromForm(r.Context(), form); err != nil {
httpError(w, err)
return
}
http.Redirect(w, r, "/settings?flash=github_saved#github-identity", http.StatusSeeOther)
}
func (a *App) handleUICreateAPIProvider(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httpError(w, err)
return
}
_, err := a.createAPIProvider(r.Context(),
r.FormValue("name"),
r.FormValue("baseUrl"),
r.FormValue("apiKey"),
r.FormValue("model"),
)
if err != nil {
httpError(w, err)
return
}
http.Redirect(w, r, "/settings?flash=api_saved#api-providers", http.StatusSeeOther)
}
func (a *App) handleUIUpdateAPIProvider(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httpError(w, err)
return
}
err := a.updateAPIProvider(r.Context(), r.PathValue("id"),
r.FormValue("name"),
r.FormValue("baseUrl"),
r.FormValue("apiKey"),
r.FormValue("model"),
)
if err != nil {
httpError(w, err)
return
}
http.Redirect(w, r, "/settings?flash=api_saved#api-providers", http.StatusSeeOther)
}
func (a *App) handleUIDeleteAPIProvider(w http.ResponseWriter, r *http.Request) {
if err := a.deleteAPIProvider(r.Context(), r.PathValue("id")); err != nil {
httpError(w, err)
return
}
http.Redirect(w, r, "/settings?flash=api_deleted#api-providers", http.StatusSeeOther)
}
func (a *App) handleUITestAPIProvider(w http.ResponseWriter, r *http.Request) {
if err := a.testAPIProviderConnection(r.Context(), r.PathValue("id")); err != nil {
// Surface a soft redirect with failure flash rather than raw JSON for form posts.
http.Redirect(w, r, "/settings?flash=api_test_failed#api-providers", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/settings?flash=api_tested#api-providers", http.StatusSeeOther)
}
func (a *App) handleDashboard(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
projects, err := a.listProjects(r.Context())
if err != nil {
httpError(w, err)
return
}
dashboard, err := a.dashboardData(r.Context(), projects, "", "")
if err != nil {
httpError(w, err)
return
}
current := a.currentAgentStatus()
var activeRun QueueRunSummary
if current.Running && current.QueueRunID != 0 {
activeRun, _ = a.getQueueRun(r.Context(), current.QueueRunID)
}
a.render(w, "layout.html", PageData{Page: "dashboard", Projects: projects, Dashboard: dashboard, CurrentAgent: current, ActiveRun: activeRun})
}
func (a *App) handleProjectBacklog(w http.ResponseWriter, r *http.Request) {
data, err := a.projectBacklogPageData(r)
if err != nil {
httpError(w, err)
return
}
a.render(w, "layout.html", data)
}
func (a *App) projectBacklogPageData(r *http.Request) (PageData, error) {
project, err := a.getProject(r.Context(), r.PathValue("id"))
if err != nil {
return PageData{}, err
}
projects, err := a.listProjects(r.Context())
if err != nil {
return PageData{}, err
}
epics, err := a.listEpics(r.Context(), project.ID)
if err != nil {
return PageData{}, err
}
epicID := strings.TrimSpace(r.URL.Query().Get("epicId"))
status := strings.TrimSpace(r.URL.Query().Get("status"))
if status == "" {
status = StatusBacklog
}
if !validStatuses[status] {
return PageData{}, badRequest("invalid status filter")
}
projectStories, err := a.listStories(r.Context(), storyFilters{ProjectID: project.ID, ShowClosed: true})
if err != nil {
return PageData{}, err
}
all := projectStories
if epicID != "" {
all = []Story{}
for _, story := range projectStories {
if story.EpicID != nil && *story.EpicID == epicID {
all = append(all, story)
}
}
}
stories := []Story{}
queued := []Story{}
for _, story := range projectStories {
if story.Status == StatusQueued {
queued = append(queued, story)
}
}
for _, story := range all {
if story.Status == status {
stories = append(stories, story)
}
}
data := PageData{Page: "backlog", Projects: projects, Project: project, Backlog: BacklogPageData{
Project: project, Epics: epics, Stories: stories, Queued: queued, SelectedEpic: epicID, SelectedStatus: status, Counts: countStatuses(projectStories),
}, CurrentAgent: a.currentAgentStatus()}
if storyID := strings.TrimSpace(r.URL.Query().Get("storyId")); storyID != "" {
story, err := a.getStory(r.Context(), storyID)
if err == nil && story.ProjectID == project.ID {
panel, panelErr := a.storyPanelData(r.Context(), story.ID)
if panelErr != nil {
return PageData{}, panelErr
}
data.HasDetailStory = true
data.Detail = panel
} else if err != nil && !errors.Is(err, sql.ErrNoRows) {
return PageData{}, err
}
}
return data, nil
}
func (a *App) handleProjectRun(w http.ResponseWriter, r *http.Request) {
data, err := a.projectRunPageData(r)
if err != nil {
httpError(w, err)
return
}
a.render(w, "layout.html", data)
}
func (a *App) handleProjectRunContent(w http.ResponseWriter, r *http.Request) {
data, err := a.projectRunPageData(r)
if err != nil {
httpError(w, err)
return
}
a.render(w, "run_content.html", data)
}
func (a *App) projectRunPageData(r *http.Request) (PageData, error) {
project, err := a.getProject(r.Context(), r.PathValue("id"))
if err != nil {
return PageData{}, err
}
projects, err := a.listProjects(r.Context())
if err != nil {
return PageData{}, err
}
runs, err := a.listQueueRuns(r.Context(), project.ID)
if err != nil {
return PageData{}, err
}
var selected QueueRunSummary
rawRunID := strings.TrimSpace(r.PathValue("runID"))
if rawRunID == "" {
rawRunID = strings.TrimSpace(r.URL.Query().Get("runId"))
}
if raw := rawRunID; raw != "" {
var runID int64
if _, err := fmt.Sscanf(raw, "%d", &runID); err != nil {
return PageData{}, badRequest("invalid run id")
}
selected, err = a.getQueueRun(r.Context(), runID)
if err != nil {
return PageData{}, err
}
if selected.ProjectID != project.ID {
return PageData{}, sql.ErrNoRows
}
} else if r.URL.Query().Get("new") != "1" && len(runs) > 0 {
selected = runs[0]
}
queued, err := a.listStories(r.Context(), storyFilters{ProjectID: project.ID, Status: StatusQueued, ShowClosed: true})
if err != nil {
return PageData{}, err
}
actionError := strings.TrimSpace(r.URL.Query().Get("error"))
runData := RunPageData{
Project: project, Run: selected, Runs: runs, LiveQueue: queued,
Agent: a.currentAgentStatus(), MissingPath: strings.TrimSpace(project.WorkingDirectory) == "",
ActionError: actionError, ActionErrorAgentsLink: actionErrorNeedsAgentsSettings(actionError),
}
if selected.ID != 0 {
runData.Items, err = a.listQueueRunItems(r.Context(), selected.ID)
if err != nil {
return PageData{}, err
}
runData.Activity = AgentActivityData{LatestRun: selected}
runData.Activity.StoryRuns, err = a.listAgentStoryRuns(r.Context(), selected.ID)
if err != nil {
return PageData{}, err
}
if len(runData.Items) == 0 && len(runData.Activity.StoryRuns) > 0 {
runData.Legacy = true
seen := map[string]bool{}
for _, storyRun := range runData.Activity.StoryRuns {
if seen[storyRun.StoryID] {
continue
}
seen[storyRun.StoryID] = true
story, getErr := a.getStory(r.Context(), storyRun.StoryID)
if getErr == nil {
runData.Items = append(runData.Items, QueueRunItem{QueueRunID: selected.ID, Story: story, Position: len(runData.Items) + 1, Status: storyRun.Status})
}
}
}
runData.Summary = buildRunCompletionSummary(selected, runData.Activity.StoryRuns, runData.Items)
a.enrichAwaitingPRConflicts(r.Context(), selected.ID, &runData.Summary)
}
return PageData{Page: "run", Projects: projects, Project: project, Run: runData, CurrentAgent: a.currentAgentStatus()}, nil
}
func (a *App) enrichAwaitingPRConflicts(ctx context.Context, queueRunID int64, summary *RunCompletionSummary) {
if summary == nil || queueRunID == 0 {
return
}
items, err := a.listQueueRunItems(ctx, queueRunID)
if err != nil {
return
}
seen := map[string]bool{}
for _, pr := range summary.AwaitingHumanPRs {
seen[pr.StoryID] = true
}
for _, item := range items {
if item.Status != QueueItemAwaitingHuman {
continue
}
pipeline, err := a.getStoryPipeline(ctx, queueRunID, item.Story.ID)
if err != nil || pipeline.PRNumber <= 0 {
continue
}
if !seen[item.Story.ID] {
summary.AwaitingHumanPRs = append(summary.AwaitingHumanPRs, RunPullRequest{
StoryID: item.Story.ID, StoryTitle: item.Story.Title,
Number: pipeline.PRNumber, URL: pipeline.PRURL, Branch: pipeline.Branch,
Outcome: "awaiting_human",
})
seen[item.Story.ID] = true
if summary.AwaitingHumanCount == 0 {
// Count is derived separately from items; leave as-is.
}
}
}
for i := range summary.AwaitingHumanPRs {
pr := &summary.AwaitingHumanPRs[i]
pipeline, err := a.getStoryPipeline(ctx, queueRunID, pr.StoryID)
if err != nil {
continue
}
if pipeline.MergeConflict {
pr.HasMergeConflict = true
pr.ConflictDetail = strings.TrimSpace(pipeline.Error)
if pr.ConflictDetail == "" {
pr.ConflictDetail = "Pull request has merge conflicts with the base branch"
}
}
}
}
func buildRunCompletionSummary(run QueueRunSummary, storyRuns []AgentRunSummary, items []QueueRunItem) RunCompletionSummary {
summary := RunCompletionSummary{AgentSteps: len(storyRuns)}
if run.FinishedAt != nil {
summary.Elapsed = formatElapsed(run.FinishedAt.Sub(run.StartedAt))
}
itemStatus := map[string]string{}
for _, item := range items {
itemStatus[item.Story.ID] = item.Status
}
seen := map[string]bool{}
for _, storyRun := range storyRuns {
if storyRun.PRNumber == 0 || strings.TrimSpace(storyRun.PRURL) == "" {
continue
}
key := storyRun.PRURL
if seen[key] {
continue
}
seen[key] = true
outcome := prOutcomeForRunItem(itemStatus[storyRun.StoryID])
pr := RunPullRequest{
StoryID: storyRun.StoryID, StoryTitle: storyRun.StoryTitle, Number: storyRun.PRNumber, URL: storyRun.PRURL, Branch: storyRun.Branch, Outcome: outcome,
}
summary.PullRequests = append(summary.PullRequests, pr)
switch outcome {
case "merged":
summary.MergedPRs = append(summary.MergedPRs, pr)
summary.MergedCount++
case "awaiting_human":
summary.AwaitingHumanPRs = append(summary.AwaitingHumanPRs, pr)
default:
summary.OpenPRs = append(summary.OpenPRs, pr)
}
}
// Prefer queue-item outcomes for "waiting on you" so the count matches the sidebar.
for _, item := range items {
if item.Status == QueueItemAwaitingHuman {
summary.AwaitingHumanCount++
}
}
return summary
}
func prOutcomeForRunItem(itemStatus string) string {
switch itemStatus {
case QueueItemAwaitingHuman:
return "awaiting_human"
case QueueItemCompleted:
return "merged"
default:
return "open"
}
}
func formatElapsed(duration time.Duration) string {
if duration < 0 {
duration = 0
}
seconds := int(duration.Round(time.Second).Seconds())
hours, seconds := seconds/3600, seconds%3600
minutes, seconds := seconds/60, seconds%60
if hours > 0 {
return fmt.Sprintf("%dh %dm %ds", hours, minutes, seconds)
}
if minutes > 0 {
return fmt.Sprintf("%dm %ds", minutes, seconds)
}
return fmt.Sprintf("%ds", seconds)
}
func (a *App) migrate(ctx context.Context) error {
stmts := []string{
`PRAGMA foreign_keys = ON`,
`PRAGMA busy_timeout = 5000`,
`CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
prefix TEXT NOT NULL UNIQUE,
working_directory TEXT NOT NULL DEFAULT '',
autonomy_mode TEXT NOT NULL DEFAULT 'autonomous',
next_story_number INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS epics (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL REFERENCES projects(id),
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(project_id, name)
)`,
`CREATE TABLE IF NOT EXISTS stories (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL REFERENCES projects(id),
epic_id TEXT REFERENCES epics(id),
title TEXT NOT NULL,
description TEXT NOT NULL,
status TEXT NOT NULL,
close_comment TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
closed_at TEXT
)`,
`CREATE TABLE IF NOT EXISTS story_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
story_id TEXT NOT NULL REFERENCES stories(id),
type TEXT NOT NULL,
message TEXT NOT NULL,
created_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS queue_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
status TEXT NOT NULL,
project_id TEXT NOT NULL DEFAULT '',
epic_id TEXT NOT NULL DEFAULT '',
total INTEGER NOT NULL DEFAULT 0,
completed INTEGER NOT NULL DEFAULT 0,
message TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
finished_at TEXT
)`,
`CREATE TABLE IF NOT EXISTS agent_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue_run_id INTEGER NOT NULL REFERENCES queue_runs(id),
story_id TEXT NOT NULL REFERENCES stories(id),
project_id TEXT NOT NULL REFERENCES projects(id),
working_directory TEXT NOT NULL,
status TEXT NOT NULL,
run_kind TEXT NOT NULL DEFAULT 'codex_implement',
branch TEXT NOT NULL DEFAULT '',
pr_number INTEGER NOT NULL DEFAULT 0,
pr_url TEXT NOT NULL DEFAULT '',
prompt TEXT NOT NULL DEFAULT '',
stdout TEXT NOT NULL DEFAULT '',
stderr TEXT NOT NULL DEFAULT '',
final_message TEXT NOT NULL DEFAULT '',
exit_error TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
finished_at TEXT
)`,
`CREATE TABLE IF NOT EXISTS story_pipelines (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue_run_id INTEGER NOT NULL REFERENCES queue_runs(id),
story_id TEXT NOT NULL REFERENCES stories(id),
phase TEXT NOT NULL DEFAULT '',
branch TEXT NOT NULL DEFAULT '',
default_branch TEXT NOT NULL DEFAULT '',
pr_number INTEGER NOT NULL DEFAULT 0,
pr_url TEXT NOT NULL DEFAULT '',
review_json TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL,
UNIQUE(queue_run_id, story_id)
)`,
`CREATE TABLE IF NOT EXISTS queue_run_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue_run_id INTEGER NOT NULL REFERENCES queue_runs(id),
story_id TEXT NOT NULL REFERENCES stories(id),
position INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
UNIQUE(queue_run_id, story_id),
UNIQUE(queue_run_id, position)
)`,