-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathreview_runtime.go
More file actions
2767 lines (2479 loc) · 83.9 KB
/
review_runtime.go
File metadata and controls
2767 lines (2479 loc) · 83.9 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 appcore
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/HexmosTech/git-lrc/attestation"
"github.com/HexmosTech/git-lrc/configpath"
"github.com/HexmosTech/git-lrc/interactive/input"
"github.com/HexmosTech/git-lrc/internal/appcore/decisionruntime"
"github.com/HexmosTech/git-lrc/internal/decisionflow"
"github.com/HexmosTech/git-lrc/internal/reviewapi"
"github.com/HexmosTech/git-lrc/internal/reviewdb"
"github.com/HexmosTech/git-lrc/internal/reviewhtml"
"github.com/HexmosTech/git-lrc/internal/reviewmodel"
"github.com/HexmosTech/git-lrc/internal/reviewopts"
"github.com/HexmosTech/git-lrc/internal/selfupdate"
"github.com/HexmosTech/git-lrc/internal/staticserve"
"github.com/HexmosTech/git-lrc/network"
"github.com/HexmosTech/git-lrc/storage"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
"github.com/urfave/cli/v2"
"golang.org/x/term"
)
func newRuntimeHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) == 0 {
return nil
}
if req.URL.Host != via[0].URL.Host {
return http.ErrUseLastResponse
}
return nil
},
}
}
func liveReviewAuthFailureError(apiURL, technicalDetails string) error {
technical := strings.TrimSpace(technicalDetails)
if technical == "" {
technical = "(empty response body)"
}
return fmt.Errorf("LiveReview authentication failed for review submission.\n\nNext steps:\n 1. Run: lrc ui\n 2. Login or re-authenticate\n 3. Retry: git lrc\n\nThis is LiveReview review-submission authentication, not your AI connector provider key.\n\nTechnical details:\nAPI URL: %s\n%s", apiURL, technical)
}
func formatLiveReviewTechnicalDetails(rawBody string) string {
trimmed := strings.TrimSpace(rawBody)
if trimmed == "" {
return "(empty response body)"
}
var payload reviewmodel.APIErrorPayload
if err := json.Unmarshal([]byte(trimmed), &payload); err != nil {
return trimmed
}
var lines []string
if strings.TrimSpace(payload.ErrorCode) != "" {
lines = append(lines, fmt.Sprintf("error_code: %s", payload.ErrorCode))
}
if strings.TrimSpace(payload.Error) != "" {
lines = append(lines, fmt.Sprintf("error: %s", payload.Error))
}
if payload.Envelope != nil {
for _, line := range formatEnvelopeUsageLines(payload.Envelope) {
lines = append(lines, line)
}
}
if len(lines) == 0 {
return trimmed
}
lines = append(lines, fmt.Sprintf("raw_response: %s", trimmed))
return strings.Join(lines, "\n")
}
func runReviewWithOptions(opts reviewopts.Options) error {
verbose := opts.Verbose
defer func() {
if err := selfupdate.ApplyPendingUpdateIfAny(verbose); err != nil && verbose {
log.Printf("pending self-update apply failed: %v", err)
}
}()
var tempHTMLPath string
var commitMsgPath string
attestationAction := ""
attestationWritten := false
initialMsg := sanitizeInitialMessage(opts.InitialMsg)
// Determine if this is a post-commit review (reviewing already-committed code, read-only)
// vs a pre-commit review (reviewing staged changes before commit, can commit from UI)
// When --commit flag is used, we're always reviewing historical commits (read-only mode)
isPostCommitReview := opts.DiffSource == "commit"
// Interactive flow (Web UI with commit actions) is the default when --serve is enabled
// BUT: disable interactive actions when reviewing historical commits (isPostCommitReview)
// Skip interactive mode if explicitly using --skip, not serving, or reviewing history
useInteractive := !opts.Skip && opts.Serve && !isPostCommitReview
// Short-circuit skip: collect diff for coverage tracking, write attestation, exit
if opts.Skip {
attestationAction = "skipped"
var cov attestation.CoverageResult
// Collect diff to record in DB for coverage tracking (best-effort)
diffContent, diffErr := collectDiffWithOptions(opts)
if diffErr != nil {
fmt.Fprintf(os.Stderr, "Warning: could not collect diff for coverage tracking: %v\n", diffErr)
} else if len(diffContent) > 0 {
parsedFiles, parseErr := parseDiffToFiles(diffContent)
if parseErr != nil {
fmt.Fprintf(os.Stderr, "Warning: could not parse diff for coverage tracking: %v\n", parseErr)
} else {
var covErr error
cov, covErr = reviewdb.RecordAndComputeCoverage("skipped", parsedFiles, "", verbose)
if covErr != nil {
fmt.Fprintf(os.Stderr, "Warning: coverage computation failed: %v\n", covErr)
}
}
}
if cov.Iterations == 0 {
cov.Iterations = 1
}
if err := ensureAttestationFull(attestationPayload{
Action: attestationAction,
Iterations: cov.Iterations,
PriorAICovPct: cov.PriorAICovPct,
PriorReviewCount: cov.PriorReviewCount,
}, verbose, &attestationWritten); err != nil {
return err
}
if verbose {
log.Printf("Review skipped by --skip; attestation recorded (iter:%d, coverage:%.0f%%)", cov.Iterations, cov.PriorAICovPct)
} else {
fmt.Printf("LiveReview: skipped (iter:%d, coverage:%.0f%%)\n", cov.Iterations, cov.PriorAICovPct)
}
return nil
}
// Short-circuit vouch: collect diff, compute coverage, write attestation, exit
if opts.Vouch {
attestationAction = "vouched"
diffContent, diffErr := collectDiffWithOptions(opts)
if diffErr != nil {
return fmt.Errorf("failed to collect diff for vouch: %w", diffErr)
}
if len(diffContent) == 0 {
return fmt.Errorf("no diff content to vouch for")
}
parsedFiles, parseErr := parseDiffToFiles(diffContent)
if parseErr != nil {
return fmt.Errorf("failed to parse diff for vouch: %w", parseErr)
}
cov, _ := reviewdb.RecordAndComputeCoverage("vouched", parsedFiles, "", verbose)
if cov.Iterations == 0 {
cov.Iterations = 1
}
if err := ensureAttestationFull(attestationPayload{
Action: attestationAction,
Iterations: cov.Iterations,
PriorAICovPct: cov.PriorAICovPct,
PriorReviewCount: cov.PriorReviewCount,
}, verbose, &attestationWritten); err != nil {
return err
}
if verbose {
log.Printf("Review vouched; attestation recorded (iter:%d, coverage:%.0f%%)", cov.Iterations, cov.PriorAICovPct)
} else {
fmt.Printf("LiveReview: vouched (iter:%d, coverage:%.0f%%)\n", cov.Iterations, cov.PriorAICovPct)
}
return nil
}
if opts.Precommit {
gitDir, err := reviewapi.ResolveGitDir()
if err != nil {
return fmt.Errorf("precommit mode requires a git repository: %w", err)
}
commitMsgPath = filepath.Join(gitDir, commitMessageFile)
_ = clearCommitMessageFile(commitMsgPath)
}
// Handle --force: delete existing attestation if present
// Skip attestation logic for post-commit reviews
if !isPostCommitReview {
if opts.Force {
if existing, err := existingAttestationAction(); err == nil && existing != "" {
if err := deleteAttestationForCurrentTree(); err != nil {
if verbose {
log.Printf("Failed to remove existing attestation for current tree: %v", err)
}
} else if verbose {
log.Printf("Removed existing attestation for current tree (action=%s); rerunning review", existing)
}
}
} else {
// Check if attestation exists and fail with guidance if --force not used
if existing, err := existingAttestationAction(); err == nil && existing != "" {
return cli.Exit(fmt.Sprintf("LiveReview: attestation already present for current tree (%s); use --force to rerun", existing), 1)
}
}
}
fakeMode := isFakeReviewBuild()
var err error
// Load configuration from config file or overrides.
// Fake mode does not require API credentials.
var config *Config
if fakeMode {
config = &Config{APIURL: reviewopts.DefaultAPIURL, APIKey: ""}
if strings.TrimSpace(opts.APIURL) != "" {
config.APIURL = opts.APIURL
}
if verbose {
log.Printf("Fake review mode enabled (reviewMode=%s)", reviewMode)
}
} else {
config, err = loadConfigValues(opts.APIKey, opts.APIURL, verbose)
if err != nil {
return err
}
}
// Determine repo name
repoName := opts.RepoName
if repoName == "" {
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current directory: %w", err)
}
repoName = filepath.Base(cwd)
}
if verbose {
log.Printf("Repository name: %s", repoName)
log.Printf("API URL: %s", config.APIURL)
}
var result *reviewmodel.DiffReviewResponse
// Collect diff
diffContent, err := collectDiffWithOptions(opts)
if err != nil {
return fmt.Errorf("failed to collect diff: %w", err)
}
if len(diffContent) == 0 {
return fmt.Errorf("no diff content collected")
}
var fakeBaseFiles []reviewmodel.DiffReviewFileResult
if fakeMode {
fakeBaseFiles, err = parseDiffToFiles(diffContent)
if err != nil {
return fmt.Errorf("failed to parse diff for fake review mode: %w", err)
}
}
if verbose {
log.Printf("Collected %d bytes of diff content", len(diffContent))
}
// Create ZIP archive
zipData, err := reviewapi.CreateZipArchive(diffContent)
if err != nil {
return fmt.Errorf("failed to create zip archive: %w", err)
}
if verbose {
log.Printf("Created ZIP archive: %d bytes", len(zipData))
}
// Base64 encode
base64Diff := base64.StdEncoding.EncodeToString(zipData)
// Save bundle if requested
if bundlePath := opts.SaveBundle; bundlePath != "" {
if err := saveBundleForInspection(bundlePath, diffContent, zipData, base64Diff, verbose); err != nil {
return fmt.Errorf("failed to save bundle: %w", err)
}
}
// Submit review
var submissionFailed bool
var submissionBlockedReason string
var submitResp reviewmodel.DiffReviewCreateResponse
if fakeMode {
submitResp = buildFakeSubmitResponse()
} else {
var updatedConfig Config
submitResp, updatedConfig, err = submitReviewWithRecovery(*config, base64Diff, repoName, verbose)
config = &updatedConfig
}
if err != nil {
// Handle 413 Request Entity Too Large - prompt user to skip if interactive
var apiErr *reviewmodel.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
return liveReviewAuthFailureError(config.APIURL, formatLiveReviewTechnicalDetails(apiErr.Body))
}
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusRequestEntityTooLarge {
isInteractive := term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd()))
if isInteractive {
fmt.Printf("\n⚠️ Review submission failed: The diff is too large for the API (Status 413).\n")
fmt.Print("Do you want to skip the review and proceed with the commit? [y/N]: ")
reader := bufio.NewReader(os.Stdin)
response, rErr := reader.ReadString('\n')
if rErr != nil {
// Fallback to error if we can't read input
return fmt.Errorf("failed to read input during 413 handling: %w (original error: %v)", rErr, err)
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
fmt.Println("Proceeding with skipped review...")
attestationAction = "skipped"
if err := ensureAttestation(attestationAction, verbose, &attestationWritten); err != nil {
return err
}
// Return nil to indicate success (review skipped, but process continues)
return nil
}
// User declined to skip, return specific error without body
return fmt.Errorf("review submission aborted by user (diff too large)")
}
}
if errors.As(err, &apiErr) && (apiErr.StatusCode == http.StatusForbidden || apiErr.StatusCode == http.StatusTooManyRequests) {
submissionFailed = true
submissionBlockedReason = "Usage quota exceeded"
err = nil // Continue to UI
}
if err != nil {
return fmt.Errorf("failed to submit review: %w", err)
}
}
reviewID := submitResp.ReviewID
reviewURL := buildReviewURL(config.APIURL, reviewID)
// Track whether progressive loading mode is active
progressiveLoadingActive := false
// Shared decision channel for progressive loading (will be used after review completes)
type progressiveDecision struct {
code int
message string
push bool
}
var progressiveDecisionChan chan progressiveDecision
var progressiveDecide func(code int, message string, push bool)
var progressiveSubmit func(source decisionruntime.Source, code int, message string, push bool) bool
var progressiveDecideOnce sync.Once
progressiveRuntime := decisionruntime.New(decisionflow.PhaseReviewRunning)
// In precommit mode, ensure unbuffered output
if opts.Precommit {
// Force flush and set unbuffered
syncFileSafely(os.Stdout)
syncFileSafely(os.Stderr)
}
// Track CLI usage (best-effort, non-blocking)
if !fakeMode {
go reviewapi.TrackCLIUsage(config.APIURL, config.APIKey, verbose)
}
selfupdate.StartAutoUpdateCheck(verbose)
var fakeWait time.Duration
if fakeMode {
fakeWait, err = fakeReviewWaitDuration()
if err != nil {
return err
}
}
// Generate and serve skeleton HTML immediately if --serve is enabled
// Auto-enable serve when no HTML path specified and not in post-commit mode
autoServeEnabled := !opts.Serve && opts.SaveHTML == "" && !isPostCommitReview
if autoServeEnabled {
opts.Serve = true
}
// Recalculate useInteractive now that opts.Serve may have been auto-enabled
// This is critical for Case 1 (hook-based terminal invocation) where serve is auto-enabled
// and we need the interactive flow with commit/push/skip options
useInteractive = !opts.Skip && opts.Serve && !isPostCommitReview
reviewMetadata := buildDecisionMetadata(reviewID, submitResp.UserEmail, submitResp.FriendlyName, reviewURL)
var runningDraftHub *draftHub
if useInteractive {
runningDraftHub = newDraftHub(initialMsg)
}
if !useInteractive && !submissionFailed {
fmt.Printf("Review submitted, ID: %s\n", reviewID)
if submitResp.UserEmail != "" {
fmt.Printf("Account: %s\n", submitResp.UserEmail)
}
if submitResp.FriendlyName != "" {
fmt.Printf("Title: %s\n", submitResp.FriendlyName)
}
if reviewURL != "" {
fmt.Printf("Review link: %s\n", highlightURL(reviewURL))
}
if submitResp.Envelope != nil {
printEnvelopeUsageSummary("submission", submitResp.Envelope)
}
}
if opts.Serve {
// Parse the diff content to generate file structures for immediate display
filesFromDiff, parseErr := parseDiffToFiles(diffContent)
if parseErr != nil && verbose {
log.Printf("Warning: failed to parse diff for skeleton HTML: %v", parseErr)
}
// Initialize global review state for API-based UI
reviewStateMu.Lock()
currentReviewState = NewReviewState(reviewID, filesFromDiff, useInteractive, isPostCommitReview, initialMsg, config.APIURL)
if submissionFailed {
currentReviewState.Status = "failed"
currentReviewState.ErrorSummary = submissionBlockedReason
currentReviewState.SetBlocked(true)
}
reviewStateMu.Unlock()
// Start serving immediately in background
serveListener, selectedPort, err := pickServePort(opts.Port, 10)
if err != nil {
return fmt.Errorf("failed to find available port: %w", err)
}
if selectedPort != opts.Port {
fmt.Printf("Port %d is busy; serving on %d instead.\n", opts.Port, selectedPort)
opts.Port = selectedPort
}
serveURL := fmt.Sprintf("http://localhost:%d", opts.Port)
if !useInteractive {
fmt.Printf("\n🌐 Review available at: %s\n", highlightURL(serveURL))
fmt.Printf(" Comments will appear progressively as review runs\n\n")
}
// Auto-open the review in the default browser
openURL(serveURL)
// Mark that progressive loading is active
progressiveLoadingActive = true
// Initialize decision channel for progressive loading
progressiveDecisionChan = make(chan progressiveDecision, 1)
progressiveDecide = func(code int, message string, push bool) {
progressiveDecideOnce.Do(func() {
progressiveDecisionChan <- progressiveDecision{code: code, message: message, push: push}
})
}
progressiveSubmit = func(source decisionruntime.Source, code int, message string, push bool) bool {
outcome := progressiveRuntime.TryDecide(decisionruntime.Decision{
Source: source,
Code: code,
Message: message,
Push: push,
})
if outcome.Err != nil || !outcome.Accepted {
return false
}
chosen, ok := progressiveRuntime.Chosen()
if !ok {
return false
}
if runningDraftHub != nil {
runningDraftHub.Freeze()
}
progressiveDecide(chosen.Code, chosen.Message, chosen.Push)
return true
}
handleProgressiveDecision := func(w http.ResponseWriter, code int, message string, push bool) {
outcome := progressiveRuntime.TryDecide(decisionruntime.Decision{Source: decisionruntime.SourceWeb, Code: code, Message: message, Push: push})
if outcome.Err != nil {
if errors.Is(outcome.Err, decisionruntime.ErrAlreadyResolved) {
http.Error(w, outcome.Err.Error(), http.StatusConflict)
return
}
reqErr, ok := outcome.Err.(*decisionflow.RequestError)
if !ok {
http.Error(w, outcome.Err.Error(), http.StatusBadRequest)
return
}
http.Error(w, reqErr.Error(), reqErr.StatusCode())
return
}
if !outcome.Accepted {
http.Error(w, "decision rejected", http.StatusConflict)
return
}
chosen, ok := progressiveRuntime.Chosen()
if !ok {
http.Error(w, "decision resolution failed", http.StatusConflict)
return
}
if runningDraftHub != nil {
runningDraftHub.Freeze()
}
progressiveDecide(chosen.Code, chosen.Message, chosen.Push)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
// Start server in background
go func() {
mux := http.NewServeMux()
// Serve static assets (JS, CSS) from embedded filesystem
mux.Handle("/static/", http.StripPrefix("/static/", staticserve.GetStaticHandler()))
// Serve index.html from embedded filesystem (no file on disk needed)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
htmlBytes, err := staticserve.ReadFile("index.html")
if err != nil {
http.Error(w, "Failed to load page", http.StatusInternalServerError)
return
}
if _, err := io.Copy(w, bytes.NewReader(htmlBytes)); err != nil && verbose {
log.Printf("failed to write index response: %v", err)
}
})
// API endpoint for review state - frontend polls this
mux.HandleFunc("/api/review", func(w http.ResponseWriter, r *http.Request) {
reviewStateMu.RLock()
state := currentReviewState
reviewStateMu.RUnlock()
if state == nil {
http.Error(w, "No review in progress", http.StatusNotFound)
return
}
state.ServeHTTP(w, r)
})
mux.HandleFunc("/api/runtime/usage-chip", func(w http.ResponseWriter, r *http.Request) {
handleRuntimeUsageChip(w, r, config, verbose)
})
if runningDraftHub != nil {
mux.HandleFunc("/api/draft", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
handleDraftGet(w, r, runningDraftHub)
return
}
if r.Method == http.MethodPost {
handleDraftUpdate(w, r, runningDraftHub, draftSourceWeb)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
})
mux.HandleFunc("/api/draft/events", func(w http.ResponseWriter, r *http.Request) {
handleDraftEvents(w, r, runningDraftHub)
})
}
// Functional commit handlers that work with the decision channel
mux.HandleFunc("/commit", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
msg := readCommitMessageFromRequest(r)
if runningDraftHub != nil {
if snap, err := runningDraftHub.Update(msg, draftSourceWeb, 0); err == nil {
msg = snap.Text
}
}
handleProgressiveDecision(w, decisionflow.DecisionCommit, msg, false)
})
mux.HandleFunc("/commit-push", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
msg := readCommitMessageFromRequest(r)
if runningDraftHub != nil {
if snap, err := runningDraftHub.Update(msg, draftSourceWeb, 0); err == nil {
msg = snap.Text
}
}
handleProgressiveDecision(w, decisionflow.DecisionCommit, msg, true)
})
mux.HandleFunc("/skip", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
msg := readCommitMessageFromRequest(r)
if runningDraftHub != nil {
if snap, err := runningDraftHub.Update(msg, draftSourceWeb, 0); err == nil {
msg = snap.Text
}
}
handleProgressiveDecision(w, decisionflow.DecisionSkip, msg, false)
})
mux.HandleFunc("/vouch", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
msg := readCommitMessageFromRequest(r)
if runningDraftHub != nil {
if snap, err := runningDraftHub.Update(msg, draftSourceWeb, 0); err == nil {
msg = snap.Text
}
}
handleProgressiveDecision(w, decisionflow.DecisionVouch, msg, false)
})
mux.HandleFunc("/abort", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if runningDraftHub != nil {
runningDraftHub.Freeze()
}
handleProgressiveDecision(w, decisionflow.DecisionAbort, "", false)
})
// Proxy endpoint for review-events API to avoid CORS
mux.HandleFunc("/api/v1/diff-review/", func(w http.ResponseWriter, r *http.Request) {
if fakeMode {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if !strings.HasSuffix(r.URL.Path, "/events") {
http.NotFound(w, r)
return
}
reviewStateMu.RLock()
state := currentReviewState
reviewStateMu.RUnlock()
if state == nil {
http.Error(w, "No review in progress", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(buildFakeEventsResponse(state.Snapshot())); err != nil {
if verbose {
log.Printf("failed to write fake events response: %v", err)
}
}
return
}
handleReviewEventsProxy(w, r, *config, reviewID, verbose)
})
server := &http.Server{Handler: mux}
if err := server.Serve(serveListener); err != nil && err != http.ErrServerClosed {
if verbose {
log.Printf("progressive server failed: %v", err)
}
}
}()
time.Sleep(100 * time.Millisecond) // Give server time to start
}
// For post-commit reviews, just poll and get results without interactive flow
if isPostCommitReview {
setStatusUI, stopStatusUI, statusUIDone, statusUIAbort := startTerminalStatusBubbleTea(
"Historical review in progress",
"Read-only mode. No commit actions are available.",
reviewMetadata,
)
setStatusUI("Status: waiting for review")
stopPoll := make(chan struct{})
var stopPollOnce sync.Once
stopPollFn := func() { stopPollOnce.Do(func() { close(stopPoll) }) }
var pollErr error
pollDone := make(chan struct{})
go func() {
if fakeMode {
result, pollErr = pollReviewFake(reviewID, opts.PollInterval, fakeWait, verbose, stopPoll, fakeBaseFiles, setStatusUI)
} else {
var updatedConfig Config
result, updatedConfig, pollErr = pollReviewWithRecovery(*config, reviewID, opts.PollInterval, opts.Timeout, verbose, stopPoll, setStatusUI)
config = &updatedConfig
}
close(pollDone)
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigChan)
pollFinished := false
select {
case <-pollDone:
pollFinished = true
case <-statusUIAbort:
stopPollFn()
<-pollDone
case <-sigChan:
stopPollFn()
<-pollDone
}
stopStatusUI()
<-statusUIDone
if !pollFinished {
if errors.Is(pollErr, reviewapi.ErrPollCancelled) {
return nil
}
}
if pollErr != nil {
var apiErr *reviewmodel.APIError
if errors.As(pollErr, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
return liveReviewAuthFailureError(config.APIURL, formatLiveReviewTechnicalDetails(apiErr.Body))
}
// If progressive loading is active, don't crash - keep server running to show error
if progressiveLoadingActive {
fmt.Printf("\n⚠️ Review failed: %v\n", pollErr)
fmt.Printf(" Error details available in browser at: http://localhost:%d\n", opts.Port)
fmt.Printf(" Press Ctrl-C to exit\n\n")
// Create result with error so HTML can display it
result = &reviewmodel.DiffReviewResponse{
Status: "failed",
Summary: fmt.Sprintf("Review failed: %v", pollErr),
Message: pollErr.Error(),
}
// Update review state with error
reviewStateMu.Lock()
if currentReviewState != nil {
currentReviewState.SetFailed(pollErr.Error())
}
reviewStateMu.Unlock()
} else {
if reviewURL != "" {
return fmt.Errorf("failed to poll review (see %s): %w", reviewURL, pollErr)
}
return fmt.Errorf("failed to poll review: %w", pollErr)
}
} else {
// Update review state with final result
reviewStateMu.Lock()
if currentReviewState != nil {
currentReviewState.UpdateFromResult(result)
}
reviewStateMu.Unlock()
}
if opts.Serve && progressiveLoadingActive {
setStatusUI, stopStatusUI, statusUIDone, statusUIAbort = startTerminalStatusBubbleTea(
"Historical review ready",
"Viewing in browser. This mode remains read-only.",
reviewMetadata,
)
if pollErr != nil {
setStatusUI("status: review failed - check browser details")
} else {
setStatusUI("status: completed - press Ctrl-C to exit")
}
select {
case <-statusUIAbort:
case <-sigChan:
}
stopStatusUI()
<-statusUIDone
return nil
}
// No attestation for post-commit reviews
}
// Interactive path (default): set up decision channels for Ctrl-C / Ctrl-S and poll
decisionCode := -1
decisionMessage := ""
decisionPush := false
if useInteractive {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigChan)
interactiveRuntime := decisionruntime.New(decisionflow.PhaseReviewRunning)
decisionChan := make(chan terminalDecision, 1)
var decisionOnce sync.Once
submitInteractiveDecision := func(source decisionruntime.Source, d terminalDecision) bool {
outcome := interactiveRuntime.TryDecide(decisionruntime.Decision{Source: source, Code: d.Code, Message: d.Message, Push: d.Push})
if outcome.Err != nil || !outcome.Accepted {
return false
}
chosen, ok := interactiveRuntime.Chosen()
if !ok {
return false
}
if runningDraftHub != nil {
runningDraftHub.Freeze()
}
decisionOnce.Do(func() {
decisionChan <- terminalDecision{Code: chosen.Code, Message: chosen.Message, Push: chosen.Push}
})
return true
}
prompt := decisionPrompt{
Title: "Review in progress",
Description: "Choose terminal action now or continue waiting.",
Metadata: reviewMetadata,
InitialText: initialMsg,
AllowAbort: true,
AllowSkip: true,
AllowVouch: true,
RequireMessageForSkip: true,
RequireMessageForVouch: true,
}
publishTerminalDraft := func(text string) int64 {
if runningDraftHub == nil {
return 0
}
snap, err := runningDraftHub.Update(text, draftSourceTerminal, 0)
if err != nil {
return 0
}
return snap.Version
}
openEditor := func() (string, int64, error) {
if runningDraftHub == nil {
return "", 0, fmt.Errorf("draft sync unavailable")
}
current := runningDraftHub.Snapshot()
edited, err := openDraftInEditor(current.Text)
if err != nil {
return "", 0, err
}
snap, err := runningDraftHub.Update(edited, draftSourceEditor, current.Version)
if err != nil {
return "", 0, err
}
return snap.Text, snap.Version, nil
}
tuiDecisionCh, setTUIStatus, setTUIDraft, stopTUI, tuiDone := startTerminalDecisionBubbleTea(prompt, publishTerminalDraft, openEditor)
if runningDraftHub != nil {
updates, unsubscribe := runningDraftHub.Subscribe()
defer unsubscribe()
go func() {
for snap := range updates {
setTUIDraft(snap.Text, snap.Version)
}
}()
}
setTUIStatus("status: waiting for review")
go func() {
for d := range tuiDecisionCh {
submitInteractiveDecision(decisionruntime.SourceTerminal, d)
}
}()
// Ctrl-C -> abort commit
go func() {
<-sigChan
submitInteractiveDecision(decisionruntime.SourceSignal, terminalDecision{Code: decisionflow.DecisionAbort})
}()
// Poll concurrently and race with decisions
var pollResult *reviewmodel.DiffReviewResponse
var pollErr error
var pollUpdatedConfig Config
pollUsedRecovery := false
pollDone := make(chan struct{})
var webDecisionChan <-chan progressiveDecision
if progressiveLoadingActive && progressiveDecisionChan != nil {
webDecisionChan = progressiveDecisionChan
}
stopPoll := make(chan struct{})
var stopPollOnce sync.Once
stopPollFn := func() { stopPollOnce.Do(func() { close(stopPoll) }) }
go func() {
defer close(pollDone)
if submissionFailed || reviewID == "" {
return
}
if fakeMode {
pollResult, pollErr = pollReviewFake(reviewID, opts.PollInterval, fakeWait, verbose, stopPoll, fakeBaseFiles, setTUIStatus)
} else {
pollUsedRecovery = true
pollResult, pollUpdatedConfig, pollErr = pollReviewWithRecovery(*config, reviewID, opts.PollInterval, opts.Timeout, verbose, stopPoll, setTUIStatus)
}
}()
var pollFinished bool
select {
case d := <-decisionChan:
decisionCode = d.Code
decisionMessage = d.Message
decisionPush = d.Push
stopTUI()
<-tuiDone
stopPollFn()
case webDecision := <-webDecisionChan:
decisionCode = webDecision.code
decisionMessage = webDecision.message
decisionPush = webDecision.push
stopTUI()
<-tuiDone
stopPollFn()
case <-pollDone:
pollFinished = true
}
if pollFinished {
stopTUI()
<-tuiDone
if pollUsedRecovery {
config = &pollUpdatedConfig
}
interactiveRuntime.SetPhase(decisionflow.PhaseReviewComplete)
if progressiveLoadingActive {
progressiveRuntime.SetPhase(decisionflow.PhaseReviewComplete)
}
// Prefer a user decision if it arrives within a short grace window after poll finishes
select {
case d := <-decisionChan:
decisionCode = d.Code
decisionMessage = d.Message
decisionPush = d.Push
// got user decision
case webDecision := <-webDecisionChan:
decisionCode = webDecision.code
decisionMessage = webDecision.message
decisionPush = webDecision.push
case <-time.After(300 * time.Millisecond):
// no decision quickly; proceed with poll result
}
if pollErr != nil {
if errors.Is(pollErr, reviewapi.ErrPollCancelled) {
if decisionCode != -1 {
message := decisionMessage
if strings.TrimSpace(message) == "" {
message = initialMsg
}
return executeDecision(decisionCode, message, decisionPush, decisionExecutionContext{
precommit: opts.Precommit,
verbose: verbose,
initialMsg: initialMsg,
commitMsgPath: commitMsgPath,
diffContent: diffContent,
reviewID: reviewID,
attestationWritten: &attestationWritten,
})
}
return nil
}
// If progressive loading is active, don't crash - let server keep running to show error
if progressiveLoadingActive {
var apiErr *reviewmodel.APIError
if errors.As(pollErr, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
syncedPrintf("\n⚠️ LiveReview authentication failed for review updates.\n")
syncedPrintf(" Run: lrc ui\n")
syncedPrintf(" Login or re-authenticate, then retry: git lrc\n")
syncedPrintf(" This is LiveReview review-submission authentication, not your AI connector provider key.\n")
syncedPrintf("\nTechnical details:\n")
syncedPrintf("%s\n\n", formatLiveReviewTechnicalDetails(apiErr.Body))
} else {
syncedPrintf("\n⚠️ Review failed: %v\n", pollErr)
syncedPrintf(" Error details available in browser at: http://localhost:%d\n\n", opts.Port)
}