-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwebapp.py
More file actions
2006 lines (1810 loc) · 74 KB
/
Copy pathwebapp.py
File metadata and controls
2006 lines (1810 loc) · 74 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
"""Interactive web mode: a small FastAPI app that lets a logged-in user
trigger a Serge review on a PR, watch it stream live, then tweak the
summary + per-comment text (or discard individual inline comments)
before publishing. The published review still goes out under the
GitHub App identity — OAuth is only used for access control.
"""
import asyncio
import dataclasses
import hashlib
import html as _html
import hmac
import json as _json
import logging
import os
import re
import secrets
import threading
import time
import urllib.parse
import uuid
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from typing import Any, Optional
import httpx
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.responses import (
HTMLResponse,
JSONResponse,
RedirectResponse,
Response,
StreamingResponse,
)
from fastapi.staticfiles import StaticFiles
from itsdangerous import BadSignature, URLSafeSerializer
from .clone_cache import CloneCache, Checkout
from .config import Config
from .github_auth import (
AppNotInstalledError,
installation_id_for_repo,
installation_token,
user_is_org_member,
)
from .github_client import GitHubClient
from .llm_client import LLMResponseError
from .reviewer import (
DraftComment,
ReviewDraft,
ReviewEdits,
ReviewRequest,
_UnparseableLLMOutput,
prepare_review,
publish_review,
run_followup,
)
from .store import JobStore, decode_draft
from .triggers import build_review_request
logging.basicConfig(
level=os.environ.get("LOG_LEVEL", "INFO"),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
log = logging.getLogger("ai-reviewer.web")
cfg = Config.from_env(require_app=False, require_web=True)
log.info(
"Config: llm_stream=%s, llm_max_tokens=%d, tool_max_iterations=%s, "
"llm_max_input_tokens=%s, max_diff_chars=%d, mention_trigger=%r",
cfg.llm_stream,
cfg.llm_max_tokens,
cfg.tool_max_iterations if cfg.tool_max_iterations > 0 else "unlimited",
cfg.llm_max_input_tokens if cfg.llm_max_input_tokens > 0 else "unlimited",
cfg.max_diff_chars,
cfg.mention_trigger,
)
_SESSION_COOKIE = "serge_session"
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
# GitHub limits owner / repo names to ASCII alphanumerics plus a few
# punctuation chars; we enforce the same so URL-pattern attacks (`..`,
# encoded slashes, empty strings) can't leak through into API calls.
_GH_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
_MAX_TRIGGER_COMMENT_CHARS = 4000
_LLM_PROVIDER_HF = "hf"
_LLM_PROVIDER_OPENAI = "openai"
_LLM_PROVIDER_ANTHROPIC = "anthropic"
_LLM_PROVIDER_CUSTOM = "custom"
_LLM_PROVIDER_BASES = {
_LLM_PROVIDER_HF: "https://router.huggingface.co/v1",
_LLM_PROVIDER_OPENAI: "https://api.openai.com/v1",
_LLM_PROVIDER_ANTHROPIC: "https://api.anthropic.com",
}
_LLM_PROVIDER_DEFAULT_MODELS = {
_LLM_PROVIDER_ANTHROPIC: "claude-opus-4-6",
}
# HF Inference Providers catalogue. The public router /v1/models endpoint
# lists every model the HF Router can serve along with per-provider tool
# support; we surface the tool-capable subset as a dropdown on the submit /
# admin forms so users don't have to hand-type model ids. Cached in-process
# (the list is large and changes slowly) and refreshed lazily on expiry.
_HF_MODELS_URL = f"{_LLM_PROVIDER_BASES[_LLM_PROVIDER_HF]}/models"
_HF_MODELS_TTL_SECONDS = 15 * 60
_hf_models_lock = threading.Lock()
_hf_models_cache: dict[str, Any] = {"fetched_at": 0.0, "models": []}
# ---------------------------------------------------------------------------
# Session handling: signed cookies via itsdangerous (no DB).
# ---------------------------------------------------------------------------
def _resolve_session_secret() -> str:
secret = (cfg.web_session_secret or "").strip()
if secret:
return secret
if not cfg.web_dev_no_auth:
# Config.from_env(require_web=True) already enforces this when
# DEV_NO_AUTH is off; the assert is a belt-and-braces guard so we
# never silently fall back to a known string in production.
raise RuntimeError("WEB_SESSION_SECRET is required when DEV_NO_AUTH is off")
# Dev-only path: mint a fresh random secret per process so sessions
# don't survive restarts (which is fine in dev), and never share a
# well-known string between deployments.
ephemeral = secrets.token_urlsafe(32)
log.warning(
"DEV_NO_AUTH=1 and no WEB_SESSION_SECRET set; using an ephemeral "
"random session secret. Existing sessions will not survive restart."
)
return ephemeral
_serializer = URLSafeSerializer(_resolve_session_secret(), salt="serge.session")
def _load_session(request: Request) -> dict[str, Any]:
raw = request.cookies.get(_SESSION_COOKIE)
if not raw:
return {}
try:
data = _serializer.loads(raw)
except BadSignature:
return {}
return data if isinstance(data, dict) else {}
def _save_session(response: Response, data: dict[str, Any]) -> None:
response.set_cookie(
_SESSION_COOKIE,
_serializer.dumps(data),
httponly=True,
samesite="lax",
# Cookie must travel only over HTTPS in production. Set
# WEB_INSECURE_COOKIES=1 to relax this for VPN-private HTTP
# deployments where TLS isn't terminated locally.
secure=not cfg.web_insecure_cookies,
max_age=60 * 60 * 24 * 7,
)
def _clear_session(response: Response) -> None:
response.delete_cookie(_SESSION_COOKIE)
def _current_user(request: Request) -> Optional[str]:
if cfg.web_dev_no_auth:
return "dev"
sess = _load_session(request)
user = sess.get("user")
return user if isinstance(user, str) and user else None
def _current_user_orgs(request: Request) -> list[str]:
"""Orgs the current user belongs to, cached in the signed session
cookie at login time. Used to match provider_configs that grant
access to a whole org. Returns [] in dev-no-auth mode."""
if cfg.web_dev_no_auth:
return []
sess = _load_session(request)
orgs = sess.get("orgs")
if isinstance(orgs, list):
return [o for o in orgs if isinstance(o, str)]
return []
def _effective_user_orgs_for_repo(
request: Request,
response: Optional[Response],
user: str,
owner: str,
repo: str,
) -> list[str]:
"""Return the user's effective orgs for matching configs on this
repo: session-cached orgs plus any App-verified memberships among
the ``allowed_orgs`` of candidate configs. This is the workaround
for SAML-protected orgs (which never appear in the user's
``/user/orgs`` response, so the login-time cache is empty) and for
legacy sessions minted before orgs were persisted.
When new orgs are discovered, the merged list is written back to
the session cookie so subsequent requests skip the App round-trip.
"""
base = _current_user_orgs(request)
if cfg.web_dev_no_auth or not (cfg.github_app_id and cfg.github_private_key):
return base
candidates = _store.allowed_orgs_for_repo(owner, repo)
if not candidates:
return base
base_lc = {o.lower() for o in base}
extra: list[str] = []
for org in candidates:
if org.lower() in base_lc:
continue
try:
if user_is_org_member(cfg.github_app_id, cfg.github_private_key, org, user):
extra.append(org)
except Exception: # noqa: BLE001
log.warning(
"App-based org membership check failed for %s in %s",
user,
org,
exc_info=True,
)
if not extra:
return base
merged = list(dict.fromkeys([*base, *extra]))
log.info("expanded session orgs for %s: %s -> %s", user, base, merged)
if response is not None:
sess = _load_session(request)
sess["user"] = user
sess["orgs"] = merged
_save_session(response, sess)
return merged
def _user_is_allowed(login: str, orgs: list[str]) -> bool:
if cfg.web_dev_no_auth:
return True
if login.lower() in cfg.web_allowed_users:
return True
if any(o.lower() in cfg.web_allowed_orgs for o in orgs):
return True
return False
# ---------------------------------------------------------------------------
# In-memory job registry. Each Job owns an asyncio.Queue the SSE endpoint
# consumes; the worker thread pushes events via call_soon_threadsafe.
# ---------------------------------------------------------------------------
@dataclass
class Job:
id: str
user: str
target_owner: str
target_repo: str
target_number: int
trigger_comment: str
llm_provider: str
llm_api_base: str
llm_model: Optional[str]
created_at: float
# In-memory only — never persisted, never returned through any API.
# Picked from the matched provider_config at submit time so the
# worker doesn't need to hit the store again. "" for reconstructed
# finished jobs that won't be re-executed.
llm_api_key: str = ""
# "web" for jobs the logged-in user submitted through the UI; "webhook"
# for reviews kicked off by a GitHub comment. Webhook jobs have no
# owning UI user, so any authenticated viewer may follow them.
source: str = "web"
status: str = "running" # running | done | error | discarded | published
draft: Optional[ReviewDraft] = None
error: Optional[str] = None
raw_llm_output: Optional[str] = None # only set on parse-failure errors
queue: "asyncio.Queue[dict[str, Any]]" = field(default_factory=asyncio.Queue)
loop: Optional[asyncio.AbstractEventLoop] = None
# Replay buffer so a client reconnecting (or arriving late) gets the
# full console history instead of just events emitted after they
# opened the EventSource.
history: list[dict[str, Any]] = field(default_factory=list)
history_lock: threading.Lock = field(default_factory=threading.Lock)
# Running tally of "noisy" (token/reasoning) entries currently in
# history. Lets _push_event do bounded-FIFO eviction in O(1) average
# instead of scanning the full history on every streaming chunk.
noisy_history_count: int = 0
_jobs: dict[str, Job] = {}
_jobs_lock = threading.Lock()
# Persistent backing store. The in-memory `_jobs` dict is still used as
# a hot cache for live SSE streams (asyncio.Queue, event loop reference)
# — only running jobs strictly need to live here, but we keep finished
# jobs around too until process restart since the bound is tiny.
_store = JobStore(cfg.web_store_path)
_crashed = _store.mark_running_as_crashed()
if _crashed:
log.warning(
"Marked %d job(s) left in 'running' state as crashed (server restart)",
_crashed,
)
# Shared bare-clone + per-job worktree cache. One fetch per repo, cheap
# worktrees per review (see clone_cache.py / SCALE_UP_PLAN.md phase 3).
_clone_cache = CloneCache(cfg.web_clone_cache_dir)
# Jobs left mid-flight by a previous process are marked crashed above;
# their worktrees are orphaned, so clear them on startup.
_clone_cache.reset_worktrees()
# Same immediate-review webhook behavior as the legacy Flask app, now
# hosted by reviewbot-web at /webhook. Keep this separate from the staged
# review worker pool so a burst of GitHub comments cannot starve UI jobs.
_WEBHOOK_MAX_WORKERS = int(os.environ.get("WEBHOOK_MAX_WORKERS", "2"))
_WEBHOOK_REVIEW_POOL = ThreadPoolExecutor(
max_workers=_WEBHOOK_MAX_WORKERS,
thread_name_prefix="webhook-review-worker",
)
def _verify_webhook_signature(body: bytes, header: str) -> bool:
secret = cfg.github_webhook_secret
if not secret or not header or not header.startswith("sha256="):
return False
mac = hmac.new(secret.encode(), body, hashlib.sha256)
expected = "sha256=" + mac.hexdigest()
return hmac.compare_digest(expected, header)
def _resolve_webhook_worker_cfg(
req: ReviewRequest,
) -> Optional[tuple[Config, str, str, Optional[str]]]:
"""Resolve the LLM credentials a webhook review should run with.
Matched on repo only — a webhook has no logged-in user to gate
``allowed_users`` / ``allowed_orgs`` on, so the App being installed on
the repo is the authorization. Falls back to the global env config
when no ``provider_config`` matches the repo. Returns
``(worker_cfg, provider, api_base, model)`` or ``None`` when no usable
API key is available (misconfiguration — the caller skips the review).
"""
matched = _store.find_provider_config_for_repo(owner=req.owner, repo=req.repo)
if matched is not None:
provider = matched["provider"]
llm_api_key = (matched.get("api_key") or "").strip()
llm_api_base = _api_base_for_provider(
provider, custom_base=matched.get("api_base")
)
llm_model = (
(matched.get("default_model") or "").strip()
or _LLM_PROVIDER_DEFAULT_MODELS.get(provider, "")
or cfg.llm_model
)
worker_cfg = dataclasses.replace(
cfg,
llm_api_key=llm_api_key,
llm_api_base=llm_api_base,
llm_model=llm_model,
llm_bill_to=_llm_bill_to_for_provider(provider),
)
else:
provider = _infer_llm_provider(cfg.llm_api_base)
llm_api_key = cfg.llm_api_key.strip()
llm_api_base = cfg.llm_api_base
llm_model = cfg.llm_model
worker_cfg = dataclasses.replace(cfg, llm_api_key=llm_api_key)
if not llm_api_key:
return None
return worker_cfg, provider, llm_api_base, llm_model or None
def _run_webhook_review_worker(
job: Job, worker_cfg: Config, installation_id: int, req: ReviewRequest
) -> None:
"""Run a webhook-triggered review on the dedicated webhook pool.
Mirrors the UI worker (streaming events into the job so the review
page can follow live), but auto-publishes the result to GitHub —
there is no human in the loop to edit + publish a draft."""
try:
assert cfg.github_app_id and cfg.github_private_key
token = installation_token(
cfg.github_app_id, cfg.github_private_key, installation_id
)
gh = GitHubClient(token)
def emit(kind: str, text: str) -> None:
_push_event(job, kind, text)
if req.inline is not None:
# Inline follow-up: a focused reply on the comment thread.
# There is no draft, so the page just streams the console.
run_followup(worker_cfg, gh, req, chunk_callback=emit)
job.status = "done"
emit("step", "done")
emit("done", "")
else:
_execute_review(job, worker_cfg, gh, token, req, auto_publish=True)
except _UnparseableLLMOutput as exc:
# run_followup never raises this (it posts plain markdown); only
# reachable on the follow-up path if the agentic loop misbehaves.
job.status = "error"
job.raw_llm_output = exc.content
job.error = exc.user_message()
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except AppNotInstalledError as exc:
log.warning("App not installed for %s/%s (job %s)", exc.owner, exc.repo, job.id)
job.status = "error"
job.error = str(exc)
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except LLMResponseError as exc:
log.warning(
"LLM endpoint returned %d for webhook job %s: %s",
exc.status_code,
job.id,
exc.body_preview[:400],
)
job.status = "error"
job.error = _format_llm_error(exc)
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except Exception as exc: # noqa: BLE001
log.exception("webhook review worker crashed for job %s", job.id)
job.status = "error"
job.error = f"{type(exc).__name__}: review crashed (see server log)"
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
finally:
# Follow-ups stop here; full reviews already persisted inside
# _execute_review's own finally. Persisting twice is harmless (the
# second call just re-snapshots the terminal state).
_persist_terminal(job)
def _infer_llm_provider(api_base: str) -> str:
normalized = api_base.rstrip("/")
for provider, base in _LLM_PROVIDER_BASES.items():
if normalized == base or normalized == base.removesuffix("/v1"):
return provider
return _LLM_PROVIDER_CUSTOM
def _normalize_llm_base_url(raw: str) -> str:
base = raw.strip().rstrip("/")
parsed = urllib.parse.urlparse(base)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise HTTPException(status_code=400, detail="bad_llm_base_url")
return base
def _parse_provider(payload: dict[str, Any]) -> str:
default_provider = _infer_llm_provider(cfg.llm_api_base)
provider = (payload.get("llm_provider") or default_provider).strip().lower()
if provider not in (
_LLM_PROVIDER_HF,
_LLM_PROVIDER_OPENAI,
_LLM_PROVIDER_ANTHROPIC,
_LLM_PROVIDER_CUSTOM,
):
raise HTTPException(status_code=400, detail="bad_llm_provider")
return provider
# A repo pattern is either an exact "owner/repo" or "owner/*". Both
# pieces follow GitHub's name rules (alphanumerics plus . _ -). The
# wildcard is a literal "*", not a glob, so the matcher stays trivial.
_REPO_PATTERN_RE = re.compile(r"^[A-Za-z0-9._-]+/([A-Za-z0-9._-]+|\*)$")
_VALID_PROVIDERS = (
_LLM_PROVIDER_HF,
_LLM_PROVIDER_OPENAI,
_LLM_PROVIDER_ANTHROPIC,
_LLM_PROVIDER_CUSTOM,
)
def _parse_provider_config_payload(
payload: dict[str, Any], *, require_api_key: bool
) -> dict[str, Any]:
provider = (payload.get("provider") or "").strip().lower()
if provider not in _VALID_PROVIDERS:
raise HTTPException(status_code=400, detail="bad_provider")
api_key = payload.get("api_key")
if require_api_key:
if not isinstance(api_key, str) or not api_key.strip():
raise HTTPException(status_code=400, detail="api_key_required")
api_key = api_key.strip()
elif api_key is not None:
if not isinstance(api_key, str):
raise HTTPException(status_code=400, detail="api_key_must_be_string")
api_key = api_key.strip() or None
repo_pattern = (payload.get("repo_pattern") or "").strip()
if not _REPO_PATTERN_RE.match(repo_pattern):
raise HTTPException(status_code=400, detail="bad_repo_pattern")
api_base_raw = (payload.get("api_base") or "").strip()
api_base: Optional[str] = None
if provider == _LLM_PROVIDER_CUSTOM:
if not api_base_raw:
raise HTTPException(status_code=400, detail="api_base_required_for_custom")
api_base = _normalize_llm_base_url(api_base_raw)
default_model = (payload.get("default_model") or "").strip() or None
allowed_users = _parse_login_list(payload.get("allowed_users"), "allowed_users")
allowed_orgs = _parse_login_list(payload.get("allowed_orgs"), "allowed_orgs")
if not allowed_users and not allowed_orgs:
raise HTTPException(
status_code=400,
detail="allowed_users_or_orgs_required",
)
return {
"provider": provider,
"api_key": api_key,
"repo_pattern": repo_pattern,
"api_base": api_base,
"default_model": default_model,
"allowed_users": allowed_users,
"allowed_orgs": allowed_orgs,
}
def _parse_login_list(raw: Any, field_name: str) -> list[str]:
if raw is None or raw == "":
return []
if isinstance(raw, str):
items = [s.strip() for s in raw.split(",")]
elif isinstance(raw, list):
items = []
for item in raw:
if not isinstance(item, str):
raise HTTPException(
status_code=400, detail=f"{field_name}_must_be_string_list"
)
items.append(item.strip())
else:
raise HTTPException(
status_code=400, detail=f"{field_name}_must_be_string_or_list"
)
cleaned: list[str] = []
for item in items:
if not item:
continue
if not _GH_NAME_RE.match(item):
raise HTTPException(
status_code=400,
detail=f"{field_name}_contains_invalid_login",
)
cleaned.append(item.lower())
# De-dup while preserving order.
seen: set[str] = set()
deduped: list[str] = []
for item in cleaned:
if item not in seen:
seen.add(item)
deduped.append(item)
return deduped
def _provider_config_summary(row: dict[str, Any]) -> dict[str, Any]:
"""Scrub api_key before returning to the UI — replaced with a
short non-reversible hint so admins can tell which row a key
belongs to without exposing the secret."""
raw_key = row.get("api_key") or ""
if raw_key:
# Length and last-4 chars give just enough fingerprint to spot a
# stale row without leaking the secret. Short keys (<8 chars)
# show no tail.
tail = raw_key[-4:] if len(raw_key) >= 8 else ""
key_hint = f"set (len={len(raw_key)}, ends={tail})" if tail else "set"
else:
key_hint = ""
return {
"id": row["id"],
"provider": row["provider"],
"api_base": row.get("api_base") or "",
"default_model": row.get("default_model") or "",
"repo_pattern": row["repo_pattern"],
"allowed_users": row.get("allowed_users") or [],
"allowed_orgs": row.get("allowed_orgs") or [],
"created_by": row.get("created_by") or "",
"created_at": row.get("created_at"),
"updated_at": row.get("updated_at"),
"api_key_status": key_hint,
}
def _api_base_for_provider(provider: str, custom_base: Optional[str]) -> str:
"""Resolve the base URL for a provider. Built-ins are looked up
from the static table; custom uses the per-config api_base. Falls
back to cfg.llm_api_base only when nothing else is available, so
older deployments don't break mid-rollout."""
if provider == _LLM_PROVIDER_CUSTOM:
raw_base = (custom_base or "").strip()
if not raw_base:
default_provider = _infer_llm_provider(cfg.llm_api_base)
raw_base = (
cfg.llm_api_base if default_provider == _LLM_PROVIDER_CUSTOM else ""
)
if not raw_base:
raise HTTPException(status_code=400, detail="llm_base_url_required")
return _normalize_llm_base_url(raw_base)
return _LLM_PROVIDER_BASES[provider]
def _llm_bill_to_for_provider(provider: str) -> Optional[str]:
return cfg.llm_bill_to if provider == _LLM_PROVIDER_HF else None
def _prune_store() -> None:
"""Keep only the most recent ``web_job_retention`` jobs globally.
Called on each new submission so we don't need a background sweeper."""
pruned = _store.prune(cfg.web_job_retention)
if pruned:
log.info("Pruned %d old job(s) (retention=%d)", pruned, cfg.web_job_retention)
# Per-kind cap on the replay buffer. "token" and "reasoning" are emitted
# once per LLM streaming chunk and can easily reach 10^5 entries on a
# huge PR (e.g. transformers#44794), which then drowns the SSE replay and
# freezes the page on reload. Structural events ("log", "step", "tool",
# "error", "metrics", "done") are inherently bounded by the agentic loop
# turn count, so they stay unbounded. The cap is FIFO — newer chunks
# evict older ones, since the tail is more relevant on reload.
_NOISY_KINDS = frozenset({"token", "reasoning"})
_NOISY_HISTORY_CAP = 2000
def _push_event(job: Job, kind: str, text: str) -> None:
"""Thread-safe push from the worker thread into the job's queue.
Also appends to the replay buffer so late SSE subscribers get the
full transcript."""
event = {"kind": kind, "text": text, "ts": time.time()}
with job.history_lock:
job.history.append(event)
if kind in _NOISY_KINDS:
job.noisy_history_count += 1
if job.noisy_history_count > _NOISY_HISTORY_CAP:
for i, e in enumerate(job.history):
if e["kind"] in _NOISY_KINDS:
del job.history[i]
job.noisy_history_count -= 1
break
if job.loop is not None:
job.loop.call_soon_threadsafe(job.queue.put_nowait, event)
def _persist_terminal(job: Job) -> None:
"""Snapshot a finished job into the store so it survives a restart."""
with job.history_lock:
history_copy = list(job.history)
try:
_store.save_terminal(
job.id,
status=job.status,
error=job.error,
raw_llm_output=job.raw_llm_output,
draft=job.draft,
history=history_copy,
)
except Exception: # noqa: BLE001
log.exception("failed to persist terminal state for job %s", job.id)
def _format_llm_error(exc: LLMResponseError) -> str:
"""Render an LLMResponseError for the SSE client. Surfaces the status
code + a body excerpt so the UI shows whether it was a 429 (rate
limit), 400 (bad schema), auth, etc. instead of a generic "review
crashed". The body comes from the LLM provider's own error response —
no auth tokens of ours are echoed there."""
excerpt = exc.body_preview.strip()
if len(excerpt) > 600:
excerpt = excerpt[:600] + "…"
reason_part = f" {exc.reason}" if exc.reason else ""
if excerpt:
return f"LLM endpoint returned {exc.status_code}{reason_part}: {excerpt}"
return f"LLM endpoint returned {exc.status_code}{reason_part}"
def _execute_review(
job: Job,
worker_cfg: Config,
gh: GitHubClient,
token: str,
req: ReviewRequest,
*,
auto_publish: bool,
) -> None:
"""Shared review pipeline for both UI and webhook jobs.
Shallow-clones the PR head so the LLM gets browse tools, runs
prepare_review streaming events back to the SSE consumer, then either
stops at the draft (``auto_publish=False`` — UI flow, a human edits +
publishes) or posts the review immediately (``auto_publish=True`` —
webhook flow, no human in the loop). Owns its own checkout cleanup +
terminal persistence in a finally block."""
checkout: Optional[Checkout] = None
try:
# Check out the PR head so the LLM has browse tools (matches Action
# mode, which gets a checkout via actions/checkout). Backed by the
# shared clone cache: a worktree off a per-repo bare clone, not a
# cold clone. If it fails we still run the review — just without tools.
if not _bool_env_safe("WEB_DISABLE_CHECKOUT", False):
_push_event(job, "step", "clone")
_push_event(job, "log", "Preparing PR checkout…")
t0 = time.monotonic()
checkout = _clone_cache.acquire(
token,
job.target_owner,
job.target_repo,
job.target_number,
job_id=job.id,
depth=cfg.web_clone_depth,
)
if checkout:
_push_event(
job,
"log",
f"Checkout ready in {time.monotonic() - t0:.1f}s ({checkout.path})",
)
worker_cfg = dataclasses.replace(
worker_cfg, repo_checkout_path=checkout.path
)
else:
_push_event(
job,
"log",
"Checkout failed; continuing without browse tools",
)
draft = prepare_review(
worker_cfg,
gh,
req,
chunk_callback=lambda kind, text: _push_event(job, kind, text),
)
if draft is None:
job.status = "done"
job.error = "no reviewable diff (notice was posted to the PR)"
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
return
job.draft = draft
if auto_publish:
_push_event(job, "log", "Publishing review to GitHub…")
publish_review(worker_cfg, gh, draft)
job.status = "published"
_push_event(
job,
"log",
f"Published review: {len(draft.comments)} inline comment(s), "
f"event={draft.event}",
)
else:
job.status = "done"
_push_event(
job,
"log",
f"Draft ready: {len(draft.comments)} inline comment(s), "
f"event={draft.event}",
)
_push_event(job, "step", "done")
_push_event(job, "done", "")
except _UnparseableLLMOutput as exc:
job.status = "error"
job.raw_llm_output = exc.content
job.error = exc.user_message()
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except AppNotInstalledError as exc:
# Expected failure mode — the App isn't installed on the target
# repo. Surface the actionable message verbatim instead of the
# generic "see server log".
log.warning("App not installed for %s/%s (job %s)", exc.owner, exc.repo, job.id)
job.status = "error"
job.error = str(exc)
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except LLMResponseError as exc:
log.warning(
"LLM endpoint returned %d for job %s: %s",
exc.status_code,
job.id,
exc.body_preview[:400],
)
job.status = "error"
job.error = _format_llm_error(exc)
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
except Exception as exc: # noqa: BLE001
log.exception("review worker crashed for job %s", job.id)
job.status = "error"
# Exception messages occasionally echo upstream response bodies
# that may contain auth tokens (e.g. httpx HTTPError). Don't ship
# the raw repr to the SSE client — the full traceback is in the
# server log via log.exception above.
job.error = f"{type(exc).__name__}: review crashed (see server log)"
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
finally:
# Drop this job's worktree + branch; the bare repo and its objects
# stay warm for the next review on the same repo.
_clone_cache.release(checkout)
# Snapshot the final state into SQLite. Every terminal branch
# above sets job.status to a non-'running' value, so this also
# clears the 'running' marker we'd otherwise reap on next restart.
_persist_terminal(job)
def _run_review_worker(job: Job) -> None:
"""UI entry point. Runs in a background thread: pulls an installation
token for the target repo, builds the review request from the job, and
delegates to _execute_review (which streams + stops at the draft for a
human to edit + publish)."""
assert cfg.github_app_id and cfg.github_private_key
try:
installation_id = installation_id_for_repo(
cfg.github_app_id,
cfg.github_private_key,
job.target_owner,
job.target_repo,
)
token = installation_token(
cfg.github_app_id, cfg.github_private_key, installation_id
)
gh = GitHubClient(token)
except Exception as exc: # noqa: BLE001
# Token / installation lookup failed before we could even start.
# Mark the job errored + persist so it doesn't hang in 'running'.
if isinstance(exc, AppNotInstalledError):
log.warning(
"App not installed for %s/%s (job %s)", exc.owner, exc.repo, job.id
)
job.error = str(exc)
else:
log.exception("review worker setup failed for job %s", job.id)
job.error = f"{type(exc).__name__}: review crashed (see server log)"
job.status = "error"
_push_event(job, "step", "error")
_push_event(job, "error", job.error)
_push_event(job, "done", "")
_persist_terminal(job)
return
req = ReviewRequest(
owner=job.target_owner,
repo=job.target_repo,
number=job.target_number,
trigger_comment_id=0,
trigger_comment_body=job.trigger_comment,
commenter=job.user,
)
worker_cfg = dataclasses.replace(
cfg,
llm_api_base=job.llm_api_base,
llm_api_key=job.llm_api_key,
llm_model=job.llm_model,
llm_bill_to=_llm_bill_to_for_provider(job.llm_provider),
)
_execute_review(job, worker_cfg, gh, token, req, auto_publish=False)
def _bool_env_safe(name: str, default: bool) -> bool:
raw = (os.environ.get(name) or "").strip().lower()
if not raw:
return default
return raw in ("1", "true", "yes", "on")
# ---------------------------------------------------------------------------
# FastAPI app + routes.
# ---------------------------------------------------------------------------
app = FastAPI(title="Serge web reviewer")
app.mount("/static", StaticFiles(directory=_STATIC_DIR), name="static")
@app.on_event("startup")
async def _start_clone_cache_gc() -> None:
"""Hourly GC of the clone cache: drop bare repos untouched for longer
than the TTL. Runs in a thread so it never blocks the event loop."""
ttl = cfg.web_clone_cache_ttl_seconds
async def _loop() -> None:
while True:
await asyncio.sleep(3600)
try:
await asyncio.to_thread(_clone_cache.gc, ttl)
except Exception: # noqa: BLE001
log.exception("clone cache GC failed")
asyncio.create_task(_loop())
@app.middleware("http")
async def _no_cache_static(request: Request, call_next):
"""Force browsers to revalidate /static/* on every load. Saves
users from staring at a stale review.js after we push fixes."""
response = await call_next(request)
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
@app.post("/webhook")
async def github_app_webhook(request: Request) -> Response:
body = await request.body()
if not cfg.github_webhook_secret:
log.error("rejected GitHub webhook: GITHUB_WEBHOOK_SECRET is not configured")
raise HTTPException(status_code=503, detail="webhook_not_configured")
sig = request.headers.get("X-Hub-Signature-256", "")
if not _verify_webhook_signature(body, sig):
log.warning("rejected GitHub webhook with bad signature")
raise HTTPException(status_code=401, detail="bad_signature")
event = request.headers.get("X-GitHub-Event", "")
try:
payload = _json.loads(body.decode("utf-8") or "{}")
except ValueError as exc:
raise HTTPException(status_code=400, detail="bad_json") from exc
if event == "ping":
return JSONResponse({"pong": True})
req = build_review_request(event, payload, cfg.mention_trigger)
if req is None:
return Response(status_code=204)
installation = payload.get("installation") or {}
installation_id = installation.get("id")
if not isinstance(installation_id, int):
return Response(status_code=204)
resolved = _resolve_webhook_worker_cfg(req)
if resolved is None:
log.error(
"webhook review for %s/%s#%d skipped: no LLM API key "
"(no matching provider_config and LLM_API_KEY is unset)",
req.owner,
req.repo,
req.number,
)
return JSONResponse({"status": "skipped_no_key"}, status_code=202)
worker_cfg, provider, llm_api_base, llm_model = resolved
# Register a persisted job so the review shows up in the journal and
# gets a live review page (same as UI-submitted reviews). The
# triggering commenter is recorded as the "user" for the journal; the
# "webhook" source lets any authenticated viewer follow it.
job = Job(
id=uuid.uuid4().hex,
user=req.commenter,
target_owner=req.owner,
target_repo=req.repo,
target_number=req.number,
trigger_comment=req.trigger_comment_body,
llm_provider=provider,
llm_api_base=llm_api_base,
llm_model=llm_model,
created_at=time.time(),
llm_api_key=worker_cfg.llm_api_key,
source="webhook",
)
job.loop = asyncio.get_running_loop()
with _jobs_lock:
_jobs[job.id] = job
_store.insert_job(
id=job.id,
user=job.user,
target_owner=job.target_owner,
target_repo=job.target_repo,
target_number=job.target_number,
trigger_comment=job.trigger_comment,
llm_provider=job.llm_provider,
llm_api_base=job.llm_api_base,
llm_model=job.llm_model,
created_at=job.created_at,
status=job.status,
source=job.source,
)
_prune_store()
_WEBHOOK_REVIEW_POOL.submit(
_run_webhook_review_worker, job, worker_cfg, installation_id, req
)
log.info(
"queued webhook job %s for %s/%s#%d (triggered by %s) using %s model=%s",
job.id,
req.owner,
req.repo,
req.number,
req.commenter,
provider,
llm_model or "<auto>",