Spaces:
Running
Running
Deploy eedbace1
Browse files- README.md +3 -3
- backend/api.py +11 -94
- backend/app.py +25 -189
- backend/integrations/llm_factory.py +8 -8
- eval_data/ragas_eval.py +17 -15
- frontend/src/main.jsx +3 -11
- frontend/src/styles.css +1 -1
- nodes/aggregator.py +0 -3
- nodes/correctness_reviewer.py +0 -4
- nodes/security_reviewer.py +0 -2
- nodes/test_coverage_reviewer.py +0 -2
- tests/test_cloudflare_provider.py +18 -3
- tests/test_evaluation_quality.py +37 -2
- tests/test_job_speed.py +1 -1
- tests/test_ragas_api_report.py +24 -19
README.md
CHANGED
|
@@ -68,9 +68,9 @@ The API persists job records in Supabase Postgres when configured and otherwise
|
|
| 68 |
|
| 69 |
## Model and retrieval options
|
| 70 |
|
| 71 |
-
The model factory supports
|
| 72 |
|
| 73 |
-
Set `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` to
|
| 74 |
|
| 75 |
When the direct Workers AI API is unreachable, set `CLOUDFLARE_GATEWAY_ID` to an AI Gateway ID (for example `default`) to route through Cloudflare AI Gateway. The app requests that gateway cache and stored logs be skipped. Gateway-level Logpush and account policies may still apply; review them before sending private code. Cloudflare's OpenAI-compatible gateway endpoint is marked deprecated, so this route should be migrated when Cloudflare provides a replacement reachable from the deployment environment.
|
| 76 |
|
|
@@ -140,7 +140,7 @@ Run the automated checks with:
|
|
| 140 |
python -m pytest -q
|
| 141 |
```
|
| 142 |
|
| 143 |
-
The `eval_data/` tools provide an offline scorer against human review comments and a RAGAS evaluation path for retrieval and generation metrics.
|
| 144 |
|
| 145 |
## Project map
|
| 146 |
|
|
|
|
| 68 |
|
| 69 |
## Model and retrieval options
|
| 70 |
|
| 71 |
+
The model factory supports Google Gemini, Groq and Cloudflare Workers AI, plus configured custom endpoints such as OpenAI-compatible APIs and Anthropic. An explicitly selected endpoint is used for that run; otherwise automatic selection tries Gemini, then Groq, then Cloudflare. The default Gemini model is `gemini-3.1-flash-lite`; it supports the structured output used by the review pipeline and currently has a free API tier. Google may use free-tier prompts and responses to improve its products, so use this tier only for public or non-sensitive code. Check your Google AI Studio project quota before running larger reviews. Built-in provider keys are read from environment variables. GitHub access can use a token or the OAuth Device Flow, which stores its token in the OS keyring.
|
| 72 |
|
| 73 |
+
Set `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` to enable Workers AI's `@cf/zai-org/glm-4.7-flash` as the final automatic review fallback and preferred RAGAS evaluator. `CLOUDFLARE_MODEL` can override the model, and `CLOUDFLARE_DAILY_REQUEST_LIMIT` sets a conservative local rolling request budget (default 50). Calls are paced to one every five seconds and automatic provider retries are disabled. This per-process request budget resets on restart and does not measure Cloudflare's neuron usage or enforce account-wide limits. See [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/) and [limits](https://developers.cloudflare.com/workers-ai/platform/limits/).
|
| 74 |
|
| 75 |
When the direct Workers AI API is unreachable, set `CLOUDFLARE_GATEWAY_ID` to an AI Gateway ID (for example `default`) to route through Cloudflare AI Gateway. The app requests that gateway cache and stored logs be skipped. Gateway-level Logpush and account policies may still apply; review them before sending private code. Cloudflare's OpenAI-compatible gateway endpoint is marked deprecated, so this route should be migrated when Cloudflare provides a replacement reachable from the deployment environment.
|
| 76 |
|
|
|
|
| 140 |
python -m pytest -q
|
| 141 |
```
|
| 142 |
|
| 143 |
+
The `eval_data/` tools provide an offline scorer against human review comments and a RAGAS evaluation path for retrieval and generation metrics. Live reviews skip RAGAS by default so evaluation does not add model calls or delay review jobs. To run background RAGAS on live reviews for internal evaluation, set `OCR_RUN_RAGAS_ON_REVIEWS=true`; its scores remain out of the review UI and public review API. When Langfuse is configured with `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY`, metric scores are attached to the corresponding review trace for internal inspection. LangSmith tracing can capture model calls when `LANGSMITH_API_KEY` is configured; numeric RAGAS scores are explicitly exported to Langfuse. Evaluation results are not a claim of a particular quality score and depend on the dataset, provider, and run configuration.
|
| 144 |
|
| 145 |
## Project map
|
| 146 |
|
backend/api.py
CHANGED
|
@@ -27,7 +27,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 27 |
from langgraph.types import Command
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
|
| 30 |
-
from backend.app import DB_PATH, _build_and_stream, _normalize_endpoint_name,
|
| 31 |
from backend.graph import build_graph
|
| 32 |
from backend.observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
|
| 33 |
from backend.state import Finding, Verdict
|
|
@@ -246,102 +246,19 @@ def github_logout(request: Request) -> dict[str, str]:
|
|
| 246 |
|
| 247 |
|
| 248 |
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
now = time.time()
|
| 251 |
result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
|
| 252 |
if job.get("status") == "queued":
|
| 253 |
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 254 |
return result
|
| 255 |
|
| 256 |
-
def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
|
| 257 |
-
result = _public_job(job)
|
| 258 |
-
task_id = result.get("ragas_task_id")
|
| 259 |
-
with _ragas_lock:
|
| 260 |
-
task = _ragas_tasks.get(task_id) if task_id else None
|
| 261 |
-
def finish():
|
| 262 |
-
metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
|
| 263 |
-
evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
|
| 264 |
-
result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
|
| 265 |
-
if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
|
| 266 |
-
result['ragas']['status'] = 'partial'
|
| 267 |
-
if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
|
| 268 |
-
with _lock:
|
| 269 |
-
live = _jobs.get(job.get('id'))
|
| 270 |
-
if live is not None:
|
| 271 |
-
live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
|
| 272 |
-
_save_job(live)
|
| 273 |
-
return result
|
| 274 |
-
if not task_id:
|
| 275 |
-
result["ragas"] = {
|
| 276 |
-
"status": "skipped",
|
| 277 |
-
"scores": result.get("ragas_scores") or {},
|
| 278 |
-
"reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
|
| 279 |
-
}
|
| 280 |
-
else:
|
| 281 |
-
if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
|
| 282 |
-
result["ragas"] = {
|
| 283 |
-
"status": job["ragas_status"],
|
| 284 |
-
"scores": job.get("ragas_scores") or {},
|
| 285 |
-
"error": job.get("ragas_error"),
|
| 286 |
-
}
|
| 287 |
-
return finish()
|
| 288 |
-
with _ragas_lock:
|
| 289 |
-
task = _ragas_tasks.get(task_id)
|
| 290 |
-
if not task:
|
| 291 |
-
# Task registries are process-local. A restart invalidates an
|
| 292 |
-
# in-flight task instead of making the client poll forever.
|
| 293 |
-
if result.get("ragas_scores"):
|
| 294 |
-
result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
|
| 295 |
-
else:
|
| 296 |
-
result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
|
| 297 |
-
with _lock:
|
| 298 |
-
live = _jobs.get(job.get("id"))
|
| 299 |
-
if live is not None:
|
| 300 |
-
live["ragas_status"] = "unavailable"
|
| 301 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 302 |
-
_save_job(live)
|
| 303 |
-
elif not task.get("done"):
|
| 304 |
-
timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
|
| 305 |
-
started = float(task.get("started", 0) or 0)
|
| 306 |
-
if started and datetime.now(timezone.utc).timestamp() - started > timeout:
|
| 307 |
-
result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
|
| 308 |
-
with _lock:
|
| 309 |
-
live = _jobs.get(job.get("id"))
|
| 310 |
-
if live is not None:
|
| 311 |
-
live["ragas_status"] = "failed"
|
| 312 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 313 |
-
_save_job(live)
|
| 314 |
-
else:
|
| 315 |
-
result["ragas"] = {"status": "pending"}
|
| 316 |
-
elif task.get("error"):
|
| 317 |
-
result["ragas"] = {"status": "failed", "error": task.get("error")}
|
| 318 |
-
with _lock:
|
| 319 |
-
live = _jobs.get(job.get("id"))
|
| 320 |
-
if live is not None:
|
| 321 |
-
live["ragas_status"] = "failed"
|
| 322 |
-
live["ragas_error"] = task.get("error")
|
| 323 |
-
_save_job(live)
|
| 324 |
-
else:
|
| 325 |
-
scores = task.get("scores") or {}
|
| 326 |
-
if scores:
|
| 327 |
-
result["ragas"] = {"status": "completed", "scores": scores}
|
| 328 |
-
if not job.get("ragas_scores"):
|
| 329 |
-
with _lock:
|
| 330 |
-
live = _jobs.get(job.get("id"))
|
| 331 |
-
if live is not None:
|
| 332 |
-
live["ragas_scores"] = scores
|
| 333 |
-
live["ragas_status"] = "completed"
|
| 334 |
-
_save_job(live)
|
| 335 |
-
else:
|
| 336 |
-
result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
|
| 337 |
-
with _lock:
|
| 338 |
-
live = _jobs.get(job.get("id"))
|
| 339 |
-
if live is not None:
|
| 340 |
-
live["ragas_status"] = "completed_no_scores"
|
| 341 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 342 |
-
_save_job(live)
|
| 343 |
-
return finish()
|
| 344 |
-
|
| 345 |
|
| 346 |
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 347 |
with _lock:
|
|
@@ -542,9 +459,9 @@ def create_review(request: ReviewRequest, http_request: Request, x_api_key: str
|
|
| 542 |
else:
|
| 543 |
job = existing
|
| 544 |
if existing is not None:
|
| 545 |
-
return {**
|
| 546 |
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 547 |
-
return
|
| 548 |
|
| 549 |
|
| 550 |
@app.post("/api/reviews/{job_id}/cancel")
|
|
@@ -576,7 +493,7 @@ def get_review(job_id: str, request: Request, x_api_key: str | None = Header(def
|
|
| 576 |
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 577 |
if not job or job.get("owner_id", "api-key") != owner:
|
| 578 |
raise HTTPException(status_code=404, detail="Review not found")
|
| 579 |
-
return
|
| 580 |
|
| 581 |
|
| 582 |
@app.post('/api/reviews/{job_id}/feedback')
|
|
|
|
| 27 |
from langgraph.types import Command
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
|
| 30 |
+
from backend.app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _spawn_ragas_background
|
| 31 |
from backend.graph import build_graph
|
| 32 |
from backend.observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
|
| 33 |
from backend.state import Finding, Verdict
|
|
|
|
| 246 |
|
| 247 |
|
| 248 |
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 249 |
+
private_keys = {
|
| 250 |
+
"config", "future", "request_fingerprint", "owner_id",
|
| 251 |
+
}
|
| 252 |
+
result = {
|
| 253 |
+
key: value for key, value in job.items()
|
| 254 |
+
if key not in private_keys and not key.startswith("ragas")
|
| 255 |
+
}
|
| 256 |
now = time.time()
|
| 257 |
result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
|
| 258 |
if job.get("status") == "queued":
|
| 259 |
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 260 |
return result
|
| 261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 264 |
with _lock:
|
|
|
|
| 459 |
else:
|
| 460 |
job = existing
|
| 461 |
if existing is not None:
|
| 462 |
+
return {**_public_job(job), "reused": True}
|
| 463 |
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 464 |
+
return _public_job(job)
|
| 465 |
|
| 466 |
|
| 467 |
@app.post("/api/reviews/{job_id}/cancel")
|
|
|
|
| 493 |
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 494 |
if not job or job.get("owner_id", "api-key") != owner:
|
| 495 |
raise HTTPException(status_code=404, detail="Review not found")
|
| 496 |
+
return _public_job(job)
|
| 497 |
|
| 498 |
|
| 499 |
@app.post('/api/reviews/{job_id}/feedback')
|
backend/app.py
CHANGED
|
@@ -86,7 +86,7 @@ RECOMMENDATION_ICONS = {
|
|
| 86 |
# Default dropdown choice shown in the UI. Gradio 6's Dropdown has no
|
| 87 |
# placeholder support, so a real choice is displayed and mapped back to
|
| 88 |
# the "" (auto) sentinel wherever the value enters the pipeline.
|
| 89 |
-
AUTO_ENDPOINT_CHOICE = "Auto (Gemini → Groq
|
| 90 |
|
| 91 |
|
| 92 |
def _normalize_endpoint_name(endpoint_name: str | None) -> str:
|
|
@@ -134,8 +134,8 @@ def _build_and_stream(
|
|
| 134 |
(``OCR_ENDPOINT_*``). Empty string uses the built-in provider.
|
| 135 |
ragas_background : bool
|
| 136 |
When True, RAGAS scoring runs on a background daemon thread and the
|
| 137 |
-
|
| 138 |
-
|
| 139 |
"""
|
| 140 |
graph = build_graph(DB_PATH)
|
| 141 |
thread_id = str(uuid.uuid4())
|
|
@@ -198,11 +198,8 @@ def _build_and_stream(
|
|
| 198 |
|
| 199 |
state = graph.get_state(config)
|
| 200 |
|
| 201 |
-
#
|
| 202 |
-
#
|
| 203 |
-
# so it can be used after the long-running RAGAS computation.
|
| 204 |
-
# _resolve_langfuse_trace_id() can return None after ~60s delays
|
| 205 |
-
# because contextvars may be lost.
|
| 206 |
run_trace_id = _resolve_langfuse_trace_id(handler)
|
| 207 |
|
| 208 |
verdict = state.values.get("verdict")
|
|
@@ -227,7 +224,10 @@ def _build_and_stream(
|
|
| 227 |
# Background mode spawns a thread and returns a task id so the UI
|
| 228 |
# can render results immediately; sync mode (CLI/health) waits.
|
| 229 |
ragas_out: dict[str, float | None] | str = {}
|
| 230 |
-
ragas_inputs =
|
|
|
|
|
|
|
|
|
|
| 231 |
if ragas_inputs:
|
| 232 |
if ragas_background:
|
| 233 |
# handler is not shared across threads (langfuse contextvars
|
|
@@ -341,105 +341,7 @@ def _format_verdict(verdict: Verdict | None) -> str:
|
|
| 341 |
)
|
| 342 |
|
| 343 |
|
| 344 |
-
|
| 345 |
-
"context_precision": "Context Precision",
|
| 346 |
-
"context_recall": "Context Recall",
|
| 347 |
-
"faithfulness": "Faithfulness",
|
| 348 |
-
"answer_relevancy": "Answer Relevancy",
|
| 349 |
-
"mmr": "Mean Reciprocal Rank",
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
RAGAS_METRIC_TOOLTIPS = {
|
| 353 |
-
"context_precision": "Are the most relevant code chunks ranked first?",
|
| 354 |
-
"context_recall": "Did we find ALL the relevant code? (requires ground truth)",
|
| 355 |
-
"faithfulness": "Does the review answer stick to the retrieved code?",
|
| 356 |
-
"answer_relevancy": "Does the review address the PR diff?",
|
| 357 |
-
"mmr": "How early in the list does the first useful chunk appear?",
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
def _format_ragas_scores(scores: dict[str, float | None]) -> str:
|
| 362 |
-
"""Build an HTML card showing RAGAS retrieval quality metrics."""
|
| 363 |
-
if not scores:
|
| 364 |
-
return ""
|
| 365 |
-
|
| 366 |
-
def _score_color(val: float) -> str:
|
| 367 |
-
if val >= 0.8:
|
| 368 |
-
return "#16a34a"
|
| 369 |
-
elif val >= 0.5:
|
| 370 |
-
return "#ca8a04"
|
| 371 |
-
else:
|
| 372 |
-
return "#dc2626"
|
| 373 |
-
|
| 374 |
-
rows: list[str] = []
|
| 375 |
-
failed = 0
|
| 376 |
-
for key, value in scores.items():
|
| 377 |
-
label = RAGAS_METRIC_LABELS.get(key, key.replace("_", " ").title())
|
| 378 |
-
tooltip = RAGAS_METRIC_TOOLTIPS.get(key, "")
|
| 379 |
-
tip_html = (
|
| 380 |
-
f'<span class="tip" title="{tooltip}">ℹ️</span>' if tooltip else ""
|
| 381 |
-
)
|
| 382 |
-
if value is None:
|
| 383 |
-
failed += 1
|
| 384 |
-
rows.append(
|
| 385 |
-
f'<div class="metric-row">'
|
| 386 |
-
f'<span class="metric-label">{label} {tip_html}</span>'
|
| 387 |
-
f'<span class="metric-value muted">N/A — failed</span>'
|
| 388 |
-
f"</div>"
|
| 389 |
-
)
|
| 390 |
-
continue
|
| 391 |
-
color = _score_color(value)
|
| 392 |
-
pct = int(value * 100)
|
| 393 |
-
rows.append(
|
| 394 |
-
f'<div class="metric-row">'
|
| 395 |
-
f'<span class="metric-label">{label} {tip_html}</span>'
|
| 396 |
-
f'<span class="metric-value" style="color:{color}">{value:.3f}</span>'
|
| 397 |
-
f"</div>"
|
| 398 |
-
f'<div class="metric-track"><div class="metric-fill" style="width:{pct}%;background:{color}"></div></div>'
|
| 399 |
-
)
|
| 400 |
-
|
| 401 |
-
note = ""
|
| 402 |
-
if failed:
|
| 403 |
-
note = (
|
| 404 |
-
'<p class="muted small" style="margin:10px 0 0">'
|
| 405 |
-
f"{failed} metric(s) failed (likely LLM rate-limited) and are shown as N/A."
|
| 406 |
-
"</p>"
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
return (
|
| 410 |
-
'<div class="ocr-card">'
|
| 411 |
-
'<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
|
| 412 |
-
+ "".join(rows)
|
| 413 |
-
+ note
|
| 414 |
-
+ "</div>"
|
| 415 |
-
)
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
RAGAS_PENDING_HTML = (
|
| 419 |
-
'<div class="ocr-card">'
|
| 420 |
-
'<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
|
| 421 |
-
'<div class="loading-spinner" style="justify-content:flex-start;padding:10px 0">'
|
| 422 |
-
'<div class="spinner"></div>'
|
| 423 |
-
'<span class="label">Computing RAGAS scores in the background…</span>'
|
| 424 |
-
"</div>"
|
| 425 |
-
"</div>"
|
| 426 |
-
)
|
| 427 |
-
|
| 428 |
-
RAGAS_FAILED_HTML = (
|
| 429 |
-
'<div class="ocr-card">'
|
| 430 |
-
'<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
|
| 431 |
-
'<p class="muted small">N/A — RAGAS scoring failed '
|
| 432 |
-
"(likely LLM rate-limited or timed out). Check the logs for details.</p>"
|
| 433 |
-
"</div>"
|
| 434 |
-
)
|
| 435 |
-
|
| 436 |
-
# After this long a background RAGAS task is considered stalled and the
|
| 437 |
-
# placeholder is replaced with the failure card instead of spinning forever.
|
| 438 |
-
RAGAS_TIMEOUT_SECONDS = 600
|
| 439 |
-
|
| 440 |
-
# Background RAGAS task registry: the UI spawns scoring on a daemon thread
|
| 441 |
-
# and a gr.Timer polls this dict, so review results render immediately
|
| 442 |
-
# instead of waiting minutes for the RAGAS LLM calls.
|
| 443 |
_ragas_tasks: dict[str, dict] = {}
|
| 444 |
_ragas_lock = threading.Lock()
|
| 445 |
|
|
@@ -612,7 +514,7 @@ def _spawn_ragas_background(
|
|
| 612 |
handler,
|
| 613 |
result_callback=None,
|
| 614 |
) -> str:
|
| 615 |
-
"""Start RAGAS scoring
|
| 616 |
task_id = f"ragas-{uuid.uuid4().hex[:12]}"
|
| 617 |
with _ragas_lock:
|
| 618 |
_ragas_tasks[task_id] = {"done": False, "scores": None, "started": time.time()}
|
|
@@ -914,14 +816,14 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
|
|
| 914 |
|
| 915 |
ep = get_endpoint(endpoint_name)
|
| 916 |
if ep is None:
|
| 917 |
-
yield [None, None, None, None, None
|
| 918 |
f"❌ Endpoint '{endpoint_name}' not found — pick one from "
|
| 919 |
"the list or add it in the form above."
|
| 920 |
)
|
| 921 |
return
|
| 922 |
if ep.builtin and not ep.api_key:
|
| 923 |
key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
|
| 924 |
-
yield [None, None, None, None, None
|
| 925 |
f"❌ Endpoint '{ep.name}' is selected but its key is not set — "
|
| 926 |
f"add `{key_var}` as a Space secret, or add a custom endpoint "
|
| 927 |
"in the form above."
|
|
@@ -934,12 +836,12 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
|
|
| 934 |
|
| 935 |
t0 = time.time()
|
| 936 |
try:
|
| 937 |
-
state, config, cost_summary,
|
| 938 |
repo.strip(), int(pr_number), endpoint_name, ragas_background=True,
|
| 939 |
)
|
| 940 |
except Exception as exc:
|
| 941 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
|
| 942 |
-
yield ([None, None, None, None, None
|
| 943 |
return
|
| 944 |
|
| 945 |
duration = time.time() - t0
|
|
@@ -948,7 +850,7 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
|
|
| 948 |
values = state.values
|
| 949 |
|
| 950 |
if not tasks:
|
| 951 |
-
yield [None, None, None, None, None
|
| 952 |
return
|
| 953 |
|
| 954 |
verdict: Verdict | None = values.get("verdict")
|
|
@@ -957,12 +859,6 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
|
|
| 957 |
progress(0.8, desc="Formatting results…")
|
| 958 |
|
| 959 |
verdict_html = _format_verdict(verdict)
|
| 960 |
-
if isinstance(ragas_out, str):
|
| 961 |
-
ragas_task_id = ragas_out
|
| 962 |
-
ragas_html = RAGAS_PENDING_HTML
|
| 963 |
-
else:
|
| 964 |
-
ragas_task_id = ""
|
| 965 |
-
ragas_html = _format_ragas_scores(ragas_out)
|
| 966 |
findings_html = _format_findings_table(findings)
|
| 967 |
count_html = _format_findings_count(findings)
|
| 968 |
# Strip non-serializable callbacks before saving config to state
|
|
@@ -975,7 +871,7 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
|
|
| 975 |
)
|
| 976 |
|
| 977 |
yield (
|
| 978 |
-
[run_summary_html, verdict_html,
|
| 979 |
None,
|
| 980 |
)
|
| 981 |
|
|
@@ -1322,14 +1218,6 @@ code { background: var(--bg-card-alt); padding: 1px 6px; border-radius: 6px; fon
|
|
| 1322 |
.score-track { height: 10px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; margin-top: 4px; }
|
| 1323 |
.score-fill { height: 100%; border-radius: 999px; transition: width 0.7s ease; }
|
| 1324 |
|
| 1325 |
-
/* ── RAGAS metrics ───────────────────────────────────────────────── */
|
| 1326 |
-
.metric-row { display: flex; justify-content: space-between; align-items: center; margin: 8px 0 4px; }
|
| 1327 |
-
.metric-label { font-weight: 600; color: var(--text-secondary); font-size: 0.93em; }
|
| 1328 |
-
.metric-value { font-weight: 800; font-size: 0.98em; }
|
| 1329 |
-
.metric-track { height: 8px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; }
|
| 1330 |
-
.metric-fill { height: 100%; border-radius: 999px; transition: width 0.6s ease; }
|
| 1331 |
-
.tip { cursor: help; font-size: 0.85em; }
|
| 1332 |
-
|
| 1333 |
/* ── Findings table ──────────────────────────────────────────────── */
|
| 1334 |
table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
|
| 1335 |
thead tr { background: var(--bg-table-header); border-bottom: 2px solid var(--border-color); }
|
|
@@ -1412,7 +1300,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1412 |
f'<div class="chips-row" style="margin-top:8px">'
|
| 1413 |
f'<span class="key-chip ok">{len(_configured_endpoints)} endpoint'
|
| 1414 |
f'{"s" if len(_configured_endpoints) != 1 else ""} configured</span>'
|
| 1415 |
-
'<span class="key-chip">Built-ins: Gemini · Groq</span>'
|
| 1416 |
'<span class="key-chip">Bring your own keys</span>'
|
| 1417 |
'</div>'
|
| 1418 |
'</div>'
|
|
@@ -1425,10 +1313,6 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1425 |
# ── State ────────────────────────────────────────────────────────────
|
| 1426 |
pr_state = gr.State()
|
| 1427 |
smoke_state = gr.State()
|
| 1428 |
-
# Id of this session's background RAGAS task — the gr.Timer below polls
|
| 1429 |
-
# it so review results render immediately instead of waiting on RAGAS.
|
| 1430 |
-
ragas_task_state = gr.State(value="")
|
| 1431 |
-
|
| 1432 |
# ── Tab: Review ──────────────────────────────────────────────────
|
| 1433 |
with gr.Tab("Review"):
|
| 1434 |
with gr.Row():
|
|
@@ -1451,8 +1335,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1451 |
value=AUTO_ENDPOINT_CHOICE,
|
| 1452 |
label="LLM Endpoint",
|
| 1453 |
info=(
|
| 1454 |
-
"Built-ins: Gemini
|
| 1455 |
-
"
|
| 1456 |
),
|
| 1457 |
# Grouped optgroup choices make Gradio's strict membership
|
| 1458 |
# check reject values that sit inside a group (e.g. a custom
|
|
@@ -1471,7 +1355,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1471 |
endpoint_name = _normalize_endpoint_name(endpoint_name)
|
| 1472 |
if not endpoint_name:
|
| 1473 |
return (
|
| 1474 |
-
"ℹ️ Leave the endpoint empty for auto (Gemini → Groq
|
| 1475 |
"or pick one and test it here."
|
| 1476 |
)
|
| 1477 |
from backend.integrations.endpoints import get_endpoint
|
|
@@ -1550,7 +1434,6 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1550 |
verdict_display = gr.HTML()
|
| 1551 |
count_display = gr.HTML()
|
| 1552 |
findings_display = gr.HTML()
|
| 1553 |
-
ragas_display = gr.HTML()
|
| 1554 |
|
| 1555 |
with gr.Row():
|
| 1556 |
approve_btn = gr.Button("Approve & post", variant="primary")
|
|
@@ -1565,20 +1448,16 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1565 |
_normalize_endpoint_name(a) if isinstance(a, str) else a
|
| 1566 |
for a in args
|
| 1567 |
)
|
| 1568 |
-
# Yield initial
|
| 1569 |
-
# run_btn.click in order (loading_box, cancel_btn, run_btn,
|
| 1570 |
-
# status_msg, 5 result displays, pr_state, results_panel,
|
| 1571 |
-
# ragas_task_state).
|
| 1572 |
yield [
|
| 1573 |
gr.update(visible=True),
|
| 1574 |
gr.update(visible=True, variant="stop"),
|
| 1575 |
gr.update(visible=False),
|
| 1576 |
gr.update(visible=False, value=""),
|
| 1577 |
gr.update(value=""),
|
| 1578 |
-
*[None, None, None
|
| 1579 |
None,
|
| 1580 |
gr.update(visible=False),
|
| 1581 |
-
gr.update(value=""),
|
| 1582 |
]
|
| 1583 |
|
| 1584 |
for result, err in run_review(*args):
|
|
@@ -1589,13 +1468,12 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1589 |
gr.update(visible=True),
|
| 1590 |
gr.update(visible=True, value=err),
|
| 1591 |
gr.update(value=""),
|
| 1592 |
-
*[None, None, None
|
| 1593 |
None,
|
| 1594 |
gr.update(visible=False),
|
| 1595 |
-
gr.update(value=""),
|
| 1596 |
]
|
| 1597 |
else:
|
| 1598 |
-
run_summary_html, verdict_html,
|
| 1599 |
yield [
|
| 1600 |
gr.update(visible=False),
|
| 1601 |
gr.update(visible=False),
|
|
@@ -1605,10 +1483,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1605 |
gr.update(value=verdict_html),
|
| 1606 |
gr.update(value=count_html),
|
| 1607 |
gr.update(value=findings_html),
|
| 1608 |
-
gr.update(value=ragas_html),
|
| 1609 |
config_json,
|
| 1610 |
gr.update(visible=True),
|
| 1611 |
-
gr.update(value=ragas_task_id),
|
| 1612 |
]
|
| 1613 |
|
| 1614 |
run_event = run_btn.click(
|
|
@@ -1623,10 +1499,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1623 |
verdict_display,
|
| 1624 |
count_display,
|
| 1625 |
findings_display,
|
| 1626 |
-
ragas_display,
|
| 1627 |
pr_state,
|
| 1628 |
results_panel,
|
| 1629 |
-
ragas_task_state,
|
| 1630 |
],
|
| 1631 |
)
|
| 1632 |
cancel_btn.click(fn=None, cancels=[run_event])
|
|
@@ -1650,44 +1524,6 @@ with gr.Blocks(title="OpenCodeReview") as demo:
|
|
| 1650 |
outputs=[resume_msg],
|
| 1651 |
)
|
| 1652 |
|
| 1653 |
-
# ── Background RAGAS polling ────────────────────────────────────
|
| 1654 |
-
# RAGAS scoring runs on a background thread so the review results
|
| 1655 |
-
# render immediately; this Timer polls for the finished scores and
|
| 1656 |
-
# swaps the "computing…" placeholder for the metric card.
|
| 1657 |
-
ragas_timer = gr.Timer(5, active=True)
|
| 1658 |
-
|
| 1659 |
-
def on_ragas_tick(task_id):
|
| 1660 |
-
"""Render background RAGAS scores when the task finishes."""
|
| 1661 |
-
if not task_id:
|
| 1662 |
-
return gr.update(), gr.update()
|
| 1663 |
-
with _ragas_lock:
|
| 1664 |
-
entry = _ragas_tasks.get(task_id)
|
| 1665 |
-
if entry is None:
|
| 1666 |
-
return gr.update(), gr.update()
|
| 1667 |
-
if not entry.get("done"):
|
| 1668 |
-
# Stalled guard: give up after the timeout instead of
|
| 1669 |
-
# leaving the "computing…" placeholder forever.
|
| 1670 |
-
started = entry.get("started") or 0
|
| 1671 |
-
if time.time() - started > RAGAS_TIMEOUT_SECONDS:
|
| 1672 |
-
with _ragas_lock:
|
| 1673 |
-
_ragas_tasks.pop(task_id, None)
|
| 1674 |
-
return gr.update(value=RAGAS_FAILED_HTML), gr.update(value="")
|
| 1675 |
-
return gr.update(), gr.update()
|
| 1676 |
-
scores = entry.get("scores") or {}
|
| 1677 |
-
with _ragas_lock:
|
| 1678 |
-
_ragas_tasks.pop(task_id, None)
|
| 1679 |
-
if scores:
|
| 1680 |
-
html_out = _format_ragas_scores(scores)
|
| 1681 |
-
else:
|
| 1682 |
-
html_out = RAGAS_FAILED_HTML
|
| 1683 |
-
return gr.update(value=html_out), gr.update(value="")
|
| 1684 |
-
|
| 1685 |
-
ragas_timer.tick(
|
| 1686 |
-
fn=on_ragas_tick,
|
| 1687 |
-
inputs=[ragas_task_state],
|
| 1688 |
-
outputs=[ragas_display, ragas_task_state],
|
| 1689 |
-
)
|
| 1690 |
-
|
| 1691 |
# ── Add / clear custom endpoints ─────────────────────────────
|
| 1692 |
def on_add_endpoint(name, ptype, base_url, api_key, model):
|
| 1693 |
"""Register the form values, refresh the dropdown, auto-select."""
|
|
|
|
| 86 |
# Default dropdown choice shown in the UI. Gradio 6's Dropdown has no
|
| 87 |
# placeholder support, so a real choice is displayed and mapped back to
|
| 88 |
# the "" (auto) sentinel wherever the value enters the pipeline.
|
| 89 |
+
AUTO_ENDPOINT_CHOICE = "Auto (Gemini → Groq → Cloudflare)"
|
| 90 |
|
| 91 |
|
| 92 |
def _normalize_endpoint_name(endpoint_name: str | None) -> str:
|
|
|
|
| 134 |
(``OCR_ENDPOINT_*``). Empty string uses the built-in provider.
|
| 135 |
ragas_background : bool
|
| 136 |
When True, RAGAS scoring runs on a background daemon thread and the
|
| 137 |
+
evaluation continues without delaying or changing the user-facing
|
| 138 |
+
review results.
|
| 139 |
"""
|
| 140 |
graph = build_graph(DB_PATH)
|
| 141 |
thread_id = str(uuid.uuid4())
|
|
|
|
| 198 |
|
| 199 |
state = graph.get_state(config)
|
| 200 |
|
| 201 |
+
# Capture the trace ID before background RAGAS scoring so its scores
|
| 202 |
+
# can be attached to this review in Langfuse.
|
|
|
|
|
|
|
|
|
|
| 203 |
run_trace_id = _resolve_langfuse_trace_id(handler)
|
| 204 |
|
| 205 |
verdict = state.values.get("verdict")
|
|
|
|
| 224 |
# Background mode spawns a thread and returns a task id so the UI
|
| 225 |
# can render results immediately; sync mode (CLI/health) waits.
|
| 226 |
ragas_out: dict[str, float | None] | str = {}
|
| 227 |
+
ragas_inputs = None
|
| 228 |
+
run_ragas = os.getenv("OCR_RUN_RAGAS_ON_REVIEWS", "").strip().lower() in {"1", "true", "yes"}
|
| 229 |
+
if run_ragas:
|
| 230 |
+
ragas_inputs = _ragas_inputs_from_state(state, endpoint_name)
|
| 231 |
if ragas_inputs:
|
| 232 |
if ragas_background:
|
| 233 |
# handler is not shared across threads (langfuse contextvars
|
|
|
|
| 341 |
)
|
| 342 |
|
| 343 |
|
| 344 |
+
# Background evaluation results remain internal and are sent to observability.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
_ragas_tasks: dict[str, dict] = {}
|
| 346 |
_ragas_lock = threading.Lock()
|
| 347 |
|
|
|
|
| 514 |
handler,
|
| 515 |
result_callback=None,
|
| 516 |
) -> str:
|
| 517 |
+
"""Start background RAGAS scoring and return its internal task id."""
|
| 518 |
task_id = f"ragas-{uuid.uuid4().hex[:12]}"
|
| 519 |
with _ragas_lock:
|
| 520 |
_ragas_tasks[task_id] = {"done": False, "scores": None, "started": time.time()}
|
|
|
|
| 816 |
|
| 817 |
ep = get_endpoint(endpoint_name)
|
| 818 |
if ep is None:
|
| 819 |
+
yield [None, None, None, None, None], (
|
| 820 |
f"❌ Endpoint '{endpoint_name}' not found — pick one from "
|
| 821 |
"the list or add it in the form above."
|
| 822 |
)
|
| 823 |
return
|
| 824 |
if ep.builtin and not ep.api_key:
|
| 825 |
key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
|
| 826 |
+
yield [None, None, None, None, None], (
|
| 827 |
f"❌ Endpoint '{ep.name}' is selected but its key is not set — "
|
| 828 |
f"add `{key_var}` as a Space secret, or add a custom endpoint "
|
| 829 |
"in the form above."
|
|
|
|
| 836 |
|
| 837 |
t0 = time.time()
|
| 838 |
try:
|
| 839 |
+
state, config, cost_summary, _ragas_out, _ragas_inputs = _build_and_stream(
|
| 840 |
repo.strip(), int(pr_number), endpoint_name, ragas_background=True,
|
| 841 |
)
|
| 842 |
except Exception as exc:
|
| 843 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
|
| 844 |
+
yield ([None, None, None, None, None], f"❌ Review failed: {exc}")
|
| 845 |
return
|
| 846 |
|
| 847 |
duration = time.time() - t0
|
|
|
|
| 850 |
values = state.values
|
| 851 |
|
| 852 |
if not tasks:
|
| 853 |
+
yield [None, None, None, None, None], "ℹ️ Review completed without findings."
|
| 854 |
return
|
| 855 |
|
| 856 |
verdict: Verdict | None = values.get("verdict")
|
|
|
|
| 859 |
progress(0.8, desc="Formatting results…")
|
| 860 |
|
| 861 |
verdict_html = _format_verdict(verdict)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 862 |
findings_html = _format_findings_table(findings)
|
| 863 |
count_html = _format_findings_count(findings)
|
| 864 |
# Strip non-serializable callbacks before saving config to state
|
|
|
|
| 871 |
)
|
| 872 |
|
| 873 |
yield (
|
| 874 |
+
[run_summary_html, verdict_html, count_html, findings_html, config_json],
|
| 875 |
None,
|
| 876 |
)
|
| 877 |
|
|
|
|
| 1218 |
.score-track { height: 10px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; margin-top: 4px; }
|
| 1219 |
.score-fill { height: 100%; border-radius: 999px; transition: width 0.7s ease; }
|
| 1220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1221 |
/* ── Findings table ──────────────────────────────────────────────── */
|
| 1222 |
table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
|
| 1223 |
thead tr { background: var(--bg-table-header); border-bottom: 2px solid var(--border-color); }
|
|
|
|
| 1300 |
f'<div class="chips-row" style="margin-top:8px">'
|
| 1301 |
f'<span class="key-chip ok">{len(_configured_endpoints)} endpoint'
|
| 1302 |
f'{"s" if len(_configured_endpoints) != 1 else ""} configured</span>'
|
| 1303 |
+
'<span class="key-chip">Built-ins: Gemini · Groq · Cloudflare</span>'
|
| 1304 |
'<span class="key-chip">Bring your own keys</span>'
|
| 1305 |
'</div>'
|
| 1306 |
'</div>'
|
|
|
|
| 1313 |
# ── State ────────────────────────────────────────────────────────────
|
| 1314 |
pr_state = gr.State()
|
| 1315 |
smoke_state = gr.State()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
# ── Tab: Review ──────────────────────────────────────────────────
|
| 1317 |
with gr.Tab("Review"):
|
| 1318 |
with gr.Row():
|
|
|
|
| 1335 |
value=AUTO_ENDPOINT_CHOICE,
|
| 1336 |
label="LLM Endpoint",
|
| 1337 |
info=(
|
| 1338 |
+
"Built-ins: Gemini, Groq (Llama models), and Cloudflare Workers AI. "
|
| 1339 |
+
"Automatic order: Gemini → Groq → Cloudflare."
|
| 1340 |
),
|
| 1341 |
# Grouped optgroup choices make Gradio's strict membership
|
| 1342 |
# check reject values that sit inside a group (e.g. a custom
|
|
|
|
| 1355 |
endpoint_name = _normalize_endpoint_name(endpoint_name)
|
| 1356 |
if not endpoint_name:
|
| 1357 |
return (
|
| 1358 |
+
"ℹ️ Leave the endpoint empty for auto (Gemini → Groq → Cloudflare), "
|
| 1359 |
"or pick one and test it here."
|
| 1360 |
)
|
| 1361 |
from backend.integrations.endpoints import get_endpoint
|
|
|
|
| 1434 |
verdict_display = gr.HTML()
|
| 1435 |
count_display = gr.HTML()
|
| 1436 |
findings_display = gr.HTML()
|
|
|
|
| 1437 |
|
| 1438 |
with gr.Row():
|
| 1439 |
approve_btn = gr.Button("Approve & post", variant="primary")
|
|
|
|
| 1448 |
_normalize_endpoint_name(a) if isinstance(a, str) else a
|
| 1449 |
for a in args
|
| 1450 |
)
|
| 1451 |
+
# Yield the initial state for run_btn.click's 10 outputs.
|
|
|
|
|
|
|
|
|
|
| 1452 |
yield [
|
| 1453 |
gr.update(visible=True),
|
| 1454 |
gr.update(visible=True, variant="stop"),
|
| 1455 |
gr.update(visible=False),
|
| 1456 |
gr.update(visible=False, value=""),
|
| 1457 |
gr.update(value=""),
|
| 1458 |
+
*[None, None, None],
|
| 1459 |
None,
|
| 1460 |
gr.update(visible=False),
|
|
|
|
| 1461 |
]
|
| 1462 |
|
| 1463 |
for result, err in run_review(*args):
|
|
|
|
| 1468 |
gr.update(visible=True),
|
| 1469 |
gr.update(visible=True, value=err),
|
| 1470 |
gr.update(value=""),
|
| 1471 |
+
*[None, None, None],
|
| 1472 |
None,
|
| 1473 |
gr.update(visible=False),
|
|
|
|
| 1474 |
]
|
| 1475 |
else:
|
| 1476 |
+
run_summary_html, verdict_html, count_html, findings_html, config_json = result
|
| 1477 |
yield [
|
| 1478 |
gr.update(visible=False),
|
| 1479 |
gr.update(visible=False),
|
|
|
|
| 1483 |
gr.update(value=verdict_html),
|
| 1484 |
gr.update(value=count_html),
|
| 1485 |
gr.update(value=findings_html),
|
|
|
|
| 1486 |
config_json,
|
| 1487 |
gr.update(visible=True),
|
|
|
|
| 1488 |
]
|
| 1489 |
|
| 1490 |
run_event = run_btn.click(
|
|
|
|
| 1499 |
verdict_display,
|
| 1500 |
count_display,
|
| 1501 |
findings_display,
|
|
|
|
| 1502 |
pr_state,
|
| 1503 |
results_panel,
|
|
|
|
| 1504 |
],
|
| 1505 |
)
|
| 1506 |
cancel_btn.click(fn=None, cancels=[run_event])
|
|
|
|
| 1524 |
outputs=[resume_msg],
|
| 1525 |
)
|
| 1526 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1527 |
# ── Add / clear custom endpoints ─────────────────────────────
|
| 1528 |
def on_add_endpoint(name, ptype, base_url, api_key, model):
|
| 1529 |
"""Register the form values, refresh the dropdown, auto-select."""
|
backend/integrations/llm_factory.py
CHANGED
|
@@ -268,7 +268,7 @@ def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
|
|
| 268 |
|
| 269 |
|
| 270 |
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 271 |
-
"""Create a chat LLM — selected endpoint first, else
|
| 272 |
|
| 273 |
Parameters
|
| 274 |
----------
|
|
@@ -343,22 +343,22 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
|
| 343 |
"or add it in the UI."
|
| 344 |
)
|
| 345 |
|
| 346 |
-
llm =
|
| 347 |
if llm is not None:
|
|
|
|
| 348 |
return llm
|
| 349 |
|
| 350 |
-
# Prefer Groq when configured: it has a separate quota pool and avoids
|
| 351 |
-
# stalling the review pipeline on Gemini free-tier exhaustion.
|
| 352 |
llm = _get_groq_chat(**kwargs)
|
| 353 |
if llm is not None:
|
| 354 |
-
logger.debug("
|
| 355 |
return llm
|
| 356 |
|
| 357 |
-
llm =
|
| 358 |
if llm is not None:
|
| 359 |
-
logger.debug("Falling back to
|
| 360 |
return llm
|
| 361 |
|
| 362 |
raise ValueError(
|
| 363 |
-
"No LLM available. Set GEMINI_API_KEY
|
|
|
|
| 364 |
)
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 271 |
+
"""Create a chat LLM — selected endpoint first, else Gemini → Groq → Cloudflare.
|
| 272 |
|
| 273 |
Parameters
|
| 274 |
----------
|
|
|
|
| 343 |
"or add it in the UI."
|
| 344 |
)
|
| 345 |
|
| 346 |
+
llm = _get_gemini_chat(**kwargs)
|
| 347 |
if llm is not None:
|
| 348 |
+
logger.debug("Using Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
|
| 349 |
return llm
|
| 350 |
|
|
|
|
|
|
|
| 351 |
llm = _get_groq_chat(**kwargs)
|
| 352 |
if llm is not None:
|
| 353 |
+
logger.debug("Falling back to Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
|
| 354 |
return llm
|
| 355 |
|
| 356 |
+
llm = _get_cloudflare_chat(**kwargs)
|
| 357 |
if llm is not None:
|
| 358 |
+
logger.debug("Falling back to Cloudflare (model=%s)", kwargs.get("model", CLOUDFLARE_MODEL))
|
| 359 |
return llm
|
| 360 |
|
| 361 |
raise ValueError(
|
| 362 |
+
"No LLM available. Set GEMINI_API_KEY, GROQ_API_KEY, or both "
|
| 363 |
+
"CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN."
|
| 364 |
)
|
eval_data/ragas_eval.py
CHANGED
|
@@ -179,13 +179,13 @@ class _ThrottledChatModel:
|
|
| 179 |
return getattr(self._model, name)
|
| 180 |
|
| 181 |
|
| 182 |
-
def _wrap_evaluator(llm):
|
| 183 |
from ragas.llms import LangchainLLMWrapper
|
| 184 |
from ragas.run_config import RunConfig
|
| 185 |
-
return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=
|
| 186 |
|
| 187 |
|
| 188 |
-
def _get_evaluator_llm(endpoint: Optional[str] = None):
|
| 189 |
"""Return a RAGAS-compatible LLM, reusing the project's LLM factory.
|
| 190 |
|
| 191 |
Priority:
|
|
@@ -208,29 +208,29 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 208 |
from backend.integrations.llm_factory import create_llm
|
| 209 |
from backend.integrations.endpoints import EndpointConfig, get_endpoint
|
| 210 |
configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 211 |
-
|
| 212 |
if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
|
| 213 |
import httpx
|
| 214 |
# LangChain caches HTTP clients for hashable timeout values.
|
| 215 |
# An unhashable Timeout forces a private pool for this loop.
|
| 216 |
-
|
| 217 |
-
llm = create_llm(endpoint=endpoint, temperature=0, timeout=
|
| 218 |
logger.info("RAGAS evaluator: using selected custom endpoint")
|
| 219 |
-
return _wrap_evaluator(llm)
|
| 220 |
|
| 221 |
from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
|
| 222 |
|
| 223 |
-
llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=
|
| 224 |
if llm is not None:
|
| 225 |
logger.info("RAGAS evaluator: using Cloudflare Workers AI")
|
| 226 |
-
return _wrap_evaluator(llm)
|
| 227 |
|
| 228 |
# Keep evaluation bounded: RAGAS runs several provider calls and
|
| 229 |
# retrying each one can otherwise hold a review open for minutes.
|
| 230 |
configured_model = os.getenv("RAGAS_MODEL", "").strip()
|
| 231 |
if configured_model.startswith("groq/"):
|
| 232 |
configured_model = configured_model.split("/", 1)[1]
|
| 233 |
-
groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout":
|
| 234 |
if configured_model:
|
| 235 |
groq_kwargs["model"] = configured_model
|
| 236 |
llm = _get_groq_chat(**groq_kwargs)
|
|
@@ -238,7 +238,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 238 |
logger.info(
|
| 239 |
"RAGAS evaluator: GROQ_API_KEY not set — falling back to Gemini"
|
| 240 |
)
|
| 241 |
-
llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=
|
| 242 |
if llm is None:
|
| 243 |
raise ValueError(
|
| 244 |
"No LLM available for RAGAS scoring. "
|
|
@@ -249,7 +249,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 249 |
type(llm).__name__,
|
| 250 |
_RAGAS_INTERVAL,
|
| 251 |
)
|
| 252 |
-
return _wrap_evaluator(llm)
|
| 253 |
except ValueError as exc:
|
| 254 |
logger.warning("RAGAS evaluator: %s", exc)
|
| 255 |
raise RuntimeError(
|
|
@@ -291,8 +291,8 @@ def _safe_metric_error(exc):
|
|
| 291 |
|
| 292 |
def ragas_time_limits(endpoint=None):
|
| 293 |
"""Account for paced, remote Cloudflare inference in both deadlines."""
|
| 294 |
-
total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "
|
| 295 |
-
per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "
|
| 296 |
name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
|
| 297 |
uses_cloudflare = str(name).lower() == "cloudflare" or (
|
| 298 |
not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
|
|
@@ -356,7 +356,9 @@ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=No
|
|
| 356 |
try:
|
| 357 |
# Each metric runs its own asyncio loop. Sharing an async HTTP
|
| 358 |
# client across these threads can bind its pool to another loop.
|
| 359 |
-
|
|
|
|
|
|
|
| 360 |
value = _score_one_metric(metric, sample, llm, limit)
|
| 361 |
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 362 |
raise ValueError("Invalid metric value")
|
|
|
|
| 179 |
return getattr(self._model, name)
|
| 180 |
|
| 181 |
|
| 182 |
+
def _wrap_evaluator(llm, timeout=12):
|
| 183 |
from ragas.llms import LangchainLLMWrapper
|
| 184 |
from ragas.run_config import RunConfig
|
| 185 |
+
return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=max(1, int(timeout)), max_retries=0, max_wait=0, max_workers=1))
|
| 186 |
|
| 187 |
|
| 188 |
+
def _get_evaluator_llm(endpoint: Optional[str] = None, *, timeout=12):
|
| 189 |
"""Return a RAGAS-compatible LLM, reusing the project's LLM factory.
|
| 190 |
|
| 191 |
Priority:
|
|
|
|
| 208 |
from backend.integrations.llm_factory import create_llm
|
| 209 |
from backend.integrations.endpoints import EndpointConfig, get_endpoint
|
| 210 |
configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 211 |
+
request_timeout = timeout
|
| 212 |
if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
|
| 213 |
import httpx
|
| 214 |
# LangChain caches HTTP clients for hashable timeout values.
|
| 215 |
# An unhashable Timeout forces a private pool for this loop.
|
| 216 |
+
request_timeout = httpx.Timeout(timeout)
|
| 217 |
+
llm = create_llm(endpoint=endpoint, temperature=0, timeout=request_timeout, max_retries=0)
|
| 218 |
logger.info("RAGAS evaluator: using selected custom endpoint")
|
| 219 |
+
return _wrap_evaluator(llm, timeout)
|
| 220 |
|
| 221 |
from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
|
| 222 |
|
| 223 |
+
llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=timeout)
|
| 224 |
if llm is not None:
|
| 225 |
logger.info("RAGAS evaluator: using Cloudflare Workers AI")
|
| 226 |
+
return _wrap_evaluator(llm, timeout)
|
| 227 |
|
| 228 |
# Keep evaluation bounded: RAGAS runs several provider calls and
|
| 229 |
# retrying each one can otherwise hold a review open for minutes.
|
| 230 |
configured_model = os.getenv("RAGAS_MODEL", "").strip()
|
| 231 |
if configured_model.startswith("groq/"):
|
| 232 |
configured_model = configured_model.split("/", 1)[1]
|
| 233 |
+
groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": timeout}
|
| 234 |
if configured_model:
|
| 235 |
groq_kwargs["model"] = configured_model
|
| 236 |
llm = _get_groq_chat(**groq_kwargs)
|
|
|
|
| 238 |
logger.info(
|
| 239 |
"RAGAS evaluator: GROQ_API_KEY not set — falling back to Gemini"
|
| 240 |
)
|
| 241 |
+
llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=timeout)
|
| 242 |
if llm is None:
|
| 243 |
raise ValueError(
|
| 244 |
"No LLM available for RAGAS scoring. "
|
|
|
|
| 249 |
type(llm).__name__,
|
| 250 |
_RAGAS_INTERVAL,
|
| 251 |
)
|
| 252 |
+
return _wrap_evaluator(llm, timeout)
|
| 253 |
except ValueError as exc:
|
| 254 |
logger.warning("RAGAS evaluator: %s", exc)
|
| 255 |
raise RuntimeError(
|
|
|
|
| 291 |
|
| 292 |
def ragas_time_limits(endpoint=None):
|
| 293 |
"""Account for paced, remote Cloudflare inference in both deadlines."""
|
| 294 |
+
total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90")))
|
| 295 |
+
per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "30")))
|
| 296 |
name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
|
| 297 |
uses_cloudflare = str(name).lower() == "cloudflare" or (
|
| 298 |
not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
|
|
|
|
| 356 |
try:
|
| 357 |
# Each metric runs its own asyncio loop. Sharing an async HTTP
|
| 358 |
# client across these threads can bind its pool to another loop.
|
| 359 |
+
# Keep the provider request timeout and RAGAS RunConfig aligned
|
| 360 |
+
# with this metric's actual deadline.
|
| 361 |
+
llm = _get_evaluator_llm(endpoint=endpoint, timeout=limit)
|
| 362 |
value = _score_one_metric(metric, sample, llm, limit)
|
| 363 |
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 364 |
raise ValueError("Invalid metric value")
|
frontend/src/main.jsx
CHANGED
|
@@ -48,14 +48,6 @@ function Receipt({ result }) {
|
|
| 48 |
return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Unverified findings withheld: {result.withheld_unverified || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
|
| 49 |
}
|
| 50 |
|
| 51 |
-
function Ragas({ ragas }) {
|
| 52 |
-
if (!ragas) return null;
|
| 53 |
-
const scores = ragas.scores || {};
|
| 54 |
-
const metrics = ragas.metrics || {};
|
| 55 |
-
const text = ragas.status === "pending" ? "Evaluating in the background…" : ragas.status === "failed" ? `Evaluation failed: ${ragas.error || "provider error"}` : ragas.status === "skipped" ? `Skipped: ${ragas.reason || "evaluation unavailable"}` : ragas.status === "unavailable" ? `Unavailable: ${ragas.error || "the scoring task was interrupted"}` : ragas.error || pretty(ragas.status);
|
| 56 |
-
return <section className="result-card receipt" aria-label="RAGAS evaluation"><span className="panel-kicker">Review evaluation (RAGAS)</span><p>{text}</p><p className="provider-hint">These metrics assess specific aspects of the response; they do not establish whether every code finding is correct.</p>{Object.keys(metrics).length > 0 ? <ul className="evaluation-metrics">{Object.entries(metrics).map(([key,metric]) => <li key={key}><strong>{pretty(key)}</strong><span>{pretty(metric.status)}{typeof metric.value === "number" ? ` · ${metric.value.toFixed(3)}` : ""}{metric.duration_seconds != null ? ` · ${Number(metric.duration_seconds).toFixed(1)}s` : ""}</span>{metric.error && <small>{metric.error}</small>}</li>)}</ul> : Object.keys(scores).length > 0 && <ul>{Object.entries(scores).map(([key,value]) => <li key={key}>{pretty(key)}: {typeof value === "number" ? value.toFixed(3) : String(value)}</li>)}</ul>}{ragas.evaluation && <details><summary>Evaluation configuration</summary><pre className="evidence-excerpt">{JSON.stringify(ragas.evaluation,null,2)}</pre></details>}</section>;
|
| 57 |
-
}
|
| 58 |
-
|
| 59 |
function ReviewProgress({ job }) {
|
| 60 |
if (!job) return null;
|
| 61 |
const stages = job.review_stages || [];
|
|
@@ -87,10 +79,10 @@ function App() {
|
|
| 87 |
useEffect(() => { document.documentElement.dataset.theme = theme; localStorage.setItem("ocr-theme", theme); }, [theme]);
|
| 88 |
const isTerminal = useMemo(() => TERMINAL.has(job?.status), [job?.status]);
|
| 89 |
useEffect(() => {
|
| 90 |
-
if (!job?.id ||
|
| 91 |
const poll = async () => { try { const r = await fetch(apiUrl(`/api/reviews/${job.id}`)); if (!r.ok) throw new Error(`Status check failed (${r.status})`); const next = await r.json(); if (!stopped) { setJob(next); setMessage(next.status === "awaiting_approval" ? "Review complete. Inspect the findings before posting." : next.status === "incomplete" ? "Review incomplete. Some reviewers could not finish; these findings are partial." : next.status === "cancelled" ? "Review cancelled." : `Review ${pretty(next.status)}…`); } } catch (e) { if (!stopped) setError(e.message); } };
|
| 92 |
poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
|
| 93 |
-
}, [job?.id, isTerminal
|
| 94 |
|
| 95 |
function providerDraft() {
|
| 96 |
return {name: `${provider || "openai"} / ${model.trim()}`, provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim()};
|
|
@@ -175,7 +167,7 @@ function App() {
|
|
| 175 |
} catch (err) { setError(err.message); } finally { setBusy(false); }
|
| 176 |
}
|
| 177 |
async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
|
| 178 |
-
return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>→</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Measurable quality</strong><span>RAGAS scores show retrieval quality.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} · ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s · JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="cloudflare">Cloudflare GLM 4.7 Flash</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} /><Ragas ragas={job?.ragas} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve & post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>→</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> Saved keys stay in this browser</footer></div>;
|
| 179 |
}
|
| 180 |
createRoot(document.getElementById("root")).render(<App />);
|
| 181 |
|
|
|
|
| 48 |
return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Unverified findings withheld: {result.withheld_unverified || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
|
| 49 |
}
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
function ReviewProgress({ job }) {
|
| 52 |
if (!job) return null;
|
| 53 |
const stages = job.review_stages || [];
|
|
|
|
| 79 |
useEffect(() => { document.documentElement.dataset.theme = theme; localStorage.setItem("ocr-theme", theme); }, [theme]);
|
| 80 |
const isTerminal = useMemo(() => TERMINAL.has(job?.status), [job?.status]);
|
| 81 |
useEffect(() => {
|
| 82 |
+
if (!job?.id || isTerminal) return undefined; let stopped = false;
|
| 83 |
const poll = async () => { try { const r = await fetch(apiUrl(`/api/reviews/${job.id}`)); if (!r.ok) throw new Error(`Status check failed (${r.status})`); const next = await r.json(); if (!stopped) { setJob(next); setMessage(next.status === "awaiting_approval" ? "Review complete. Inspect the findings before posting." : next.status === "incomplete" ? "Review incomplete. Some reviewers could not finish; these findings are partial." : next.status === "cancelled" ? "Review cancelled." : `Review ${pretty(next.status)}…`); } } catch (e) { if (!stopped) setError(e.message); } };
|
| 84 |
poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
|
| 85 |
+
}, [job?.id, isTerminal]);
|
| 86 |
|
| 87 |
function providerDraft() {
|
| 88 |
return {name: `${provider || "openai"} / ${model.trim()}`, provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim()};
|
|
|
|
| 167 |
} catch (err) { setError(err.message); } finally { setBusy(false); }
|
| 168 |
}
|
| 169 |
async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
|
| 170 |
+
return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>→</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Focused review</strong><span>Correctness, security, and test coverage.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} · ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s · JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="cloudflare">Cloudflare GLM 4.7 Flash</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve & post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>→</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> Saved keys stay in this browser</footer></div>;
|
| 171 |
}
|
| 172 |
createRoot(document.getElementById("root")).render(<App />);
|
| 173 |
|
frontend/src/styles.css
CHANGED
|
@@ -45,4 +45,4 @@ html:not([data-theme="dark"]) .verdict.blocking{background:#fff8f8;color:#2f3437
|
|
| 45 |
.provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
|
| 46 |
|
| 47 |
.review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
|
| 48 |
-
.finding-group{margin-top:24px}.finding-group h4{font-size:15px;display:flex;gap:8px;align-items:center}.finding-group h4 span{font-size:12px;color:var(--muted)}.evidence-label{display:inline-block;font-size:11px;line-height:1.6;margin:6px 0;color:#42614a}.evidence-label.uncertain{color:#855c20}.evidence-excerpt{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.65 'DM Mono',monospace;max-height:280px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px}.calibration-note{font-size:12px!important;color:var(--muted)!important}.finding-feedback{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.finding-feedback>span{font-size:12px;color:var(--muted)}.finding-feedback button,.provider-entry-actions button,.provider-form-heading button{width:auto;margin:0;padding:7px 11px;display:inline-flex;justify-content:center;border:1px solid var(--line);font-size:12px;font-weight:500;background:transparent;color:inherit}.finding-feedback button[aria-pressed="true"]{background:#dbe8dc;border-color:#799b7c;color:#24482b}.finding-feedback small{width:100%}.provider-entry-title,.provider-form-heading{display:flex;gap:10px;justify-content:space-between;align-items:center;flex-wrap:wrap}.provider-entry-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.provider-form-heading{margin-top:28px}.provider-form-heading h3{margin:0}.provider-entry-actions button:disabled{opacity:.5;cursor:default}.review-coverage{overflow-wrap:anywhere}.review-coverage ul
|
|
|
|
| 45 |
.provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
|
| 46 |
|
| 47 |
.review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
|
| 48 |
+
.finding-group{margin-top:24px}.finding-group h4{font-size:15px;display:flex;gap:8px;align-items:center}.finding-group h4 span{font-size:12px;color:var(--muted)}.evidence-label{display:inline-block;font-size:11px;line-height:1.6;margin:6px 0;color:#42614a}.evidence-label.uncertain{color:#855c20}.evidence-excerpt{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.65 'DM Mono',monospace;max-height:280px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px}.calibration-note{font-size:12px!important;color:var(--muted)!important}.finding-feedback{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.finding-feedback>span{font-size:12px;color:var(--muted)}.finding-feedback button,.provider-entry-actions button,.provider-form-heading button{width:auto;margin:0;padding:7px 11px;display:inline-flex;justify-content:center;border:1px solid var(--line);font-size:12px;font-weight:500;background:transparent;color:inherit}.finding-feedback button[aria-pressed="true"]{background:#dbe8dc;border-color:#799b7c;color:#24482b}.finding-feedback small{width:100%}.provider-entry-title,.provider-form-heading{display:flex;gap:10px;justify-content:space-between;align-items:center;flex-wrap:wrap}.provider-entry-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.provider-form-heading{margin-top:28px}.provider-form-heading h3{margin:0}.provider-entry-actions button:disabled{opacity:.5;cursor:default}.review-coverage{overflow-wrap:anywhere}.review-coverage ul{padding-left:18px;font-size:13px;line-height:1.7}html[data-theme="dark"] .evidence-label{color:#b2d4b7}html[data-theme="dark"] .evidence-label.uncertain{color:#e4c48c}html[data-theme="dark"] .finding-feedback button,html[data-theme="dark"] .provider-entry-actions button,html[data-theme="dark"] .provider-form-heading button{background:transparent;color:#e8edf0}html[data-theme="dark"] .finding-feedback button[aria-pressed="true"]{background:#294334;color:#d4edda;border-color:#759b7e}
|
nodes/aggregator.py
CHANGED
|
@@ -12,9 +12,6 @@ from backend.state import Finding, OpenCodeReviewState, Severity, Verdict
|
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 16 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 17 |
-
|
| 18 |
# Prompt version — tied to the file on disk
|
| 19 |
PROMPT_VERSION = "v1"
|
| 20 |
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
|
|
|
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
# Prompt version — tied to the file on disk
|
| 16 |
PROMPT_VERSION = "v1"
|
| 17 |
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
|
nodes/correctness_reviewer.py
CHANGED
|
@@ -15,10 +15,6 @@ from backend.state import Finding, OpenCodeReviewState, Severity
|
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
-
# Model used on Groq — good at function calling / structured output
|
| 19 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 20 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 21 |
-
|
| 22 |
# Prompt version — tied to the file on disk
|
| 23 |
PROMPT_VERSION = "v1"
|
| 24 |
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
|
|
|
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# Prompt version — tied to the file on disk
|
| 19 |
PROMPT_VERSION = "v1"
|
| 20 |
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
|
nodes/security_reviewer.py
CHANGED
|
@@ -14,8 +14,6 @@ from backend.state import Finding, OpenCodeReviewState
|
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 18 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 19 |
MAX_CONTEXT_CHARS = 6_000
|
| 20 |
MAX_FILE_CONTENT_CHARS = 4_000
|
| 21 |
|
|
|
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
|
|
|
|
|
|
| 17 |
MAX_CONTEXT_CHARS = 6_000
|
| 18 |
MAX_FILE_CONTENT_CHARS = 4_000
|
| 19 |
|
nodes/test_coverage_reviewer.py
CHANGED
|
@@ -18,8 +18,6 @@ __test__ = False
|
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 22 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 23 |
MAX_CONTEXT_CHARS = 6_000
|
| 24 |
MAX_FILE_CONTENT_CHARS = 4_000
|
| 25 |
|
|
|
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
|
|
|
|
|
|
| 21 |
MAX_CONTEXT_CHARS = 6_000
|
| 22 |
MAX_FILE_CONTENT_CHARS = 4_000
|
| 23 |
|
tests/test_cloudflare_provider.py
CHANGED
|
@@ -9,6 +9,8 @@ from backend.integrations.cloudflare_transport import CloudflareTransport, _rout
|
|
| 9 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
| 10 |
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
|
| 11 |
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
|
|
|
|
|
|
|
| 12 |
monkeypatch.delenv('CLOUDFLARE_GATEWAY_ID', raising=False)
|
| 13 |
model = llm_factory._get_cloudflare_chat()
|
| 14 |
assert model.model_name == '@cf/zai-org/glm-4.7-flash'
|
|
@@ -20,6 +22,19 @@ def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
|
| 20 |
assert llm_factory.create_llm().rate_limiter is model.rate_limiter
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def test_gateway_uses_cloudflare_model_and_disables_cache_and_logs(monkeypatch):
|
| 24 |
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
|
| 25 |
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
|
|
@@ -51,10 +66,10 @@ def test_daily_budget_rejects_additional_attempts():
|
|
| 51 |
|
| 52 |
|
| 53 |
def test_cloudflare_evaluation_has_room_for_paced_calls(monkeypatch):
|
| 54 |
-
monkeypatch.setenv('OCR_RAGAS_TIMEOUT_SECONDS', '
|
| 55 |
-
monkeypatch.setenv('OCR_RAGAS_METRIC_TIMEOUT_SECONDS', '
|
| 56 |
assert ragas_time_limits('Cloudflare') == (210, 150)
|
| 57 |
-
assert ragas_time_limits('Gemini') == (
|
| 58 |
|
| 59 |
|
| 60 |
def test_routing_keeps_host_and_tls_server_name():
|
|
|
|
| 9 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
| 10 |
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
|
| 11 |
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
|
| 12 |
+
monkeypatch.delenv('GEMINI_API_KEY', raising=False)
|
| 13 |
+
monkeypatch.delenv('GROQ_API_KEY', raising=False)
|
| 14 |
monkeypatch.delenv('CLOUDFLARE_GATEWAY_ID', raising=False)
|
| 15 |
model = llm_factory._get_cloudflare_chat()
|
| 16 |
assert model.model_name == '@cf/zai-org/glm-4.7-flash'
|
|
|
|
| 22 |
assert llm_factory.create_llm().rate_limiter is model.rate_limiter
|
| 23 |
|
| 24 |
|
| 25 |
+
def test_automatic_provider_order_is_gemini_then_groq_then_cloudflare(monkeypatch):
|
| 26 |
+
monkeypatch.setattr(llm_factory, '_get_gemini_chat', lambda **_: 'Gemini')
|
| 27 |
+
monkeypatch.setattr(llm_factory, '_get_groq_chat', lambda **_: 'Groq')
|
| 28 |
+
monkeypatch.setattr(llm_factory, '_get_cloudflare_chat', lambda **_: 'Cloudflare')
|
| 29 |
+
assert llm_factory.create_llm() == 'Gemini'
|
| 30 |
+
|
| 31 |
+
monkeypatch.setattr(llm_factory, '_get_gemini_chat', lambda **_: None)
|
| 32 |
+
assert llm_factory.create_llm() == 'Groq'
|
| 33 |
+
|
| 34 |
+
monkeypatch.setattr(llm_factory, '_get_groq_chat', lambda **_: None)
|
| 35 |
+
assert llm_factory.create_llm() == 'Cloudflare'
|
| 36 |
+
|
| 37 |
+
|
| 38 |
def test_gateway_uses_cloudflare_model_and_disables_cache_and_logs(monkeypatch):
|
| 39 |
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
|
| 40 |
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
|
|
|
|
| 66 |
|
| 67 |
|
| 68 |
def test_cloudflare_evaluation_has_room_for_paced_calls(monkeypatch):
|
| 69 |
+
monkeypatch.setenv('OCR_RAGAS_TIMEOUT_SECONDS', '90')
|
| 70 |
+
monkeypatch.setenv('OCR_RAGAS_METRIC_TIMEOUT_SECONDS', '30')
|
| 71 |
assert ragas_time_limits('Cloudflare') == (210, 150)
|
| 72 |
+
assert ragas_time_limits('Gemini') == (90, 30)
|
| 73 |
|
| 74 |
|
| 75 |
def test_routing_keeps_host_and_tls_server_name():
|
tests/test_evaluation_quality.py
CHANGED
|
@@ -11,7 +11,7 @@ from eval_data.offline_regression import evaluate
|
|
| 11 |
|
| 12 |
def prepare(monkeypatch):
|
| 13 |
monkeypatch.setattr(ragas_eval, "_check_ragas", lambda: True)
|
| 14 |
-
monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", lambda endpoint: object())
|
| 15 |
monkeypatch.setitem(sys.modules, "ragas.dataset_schema", SimpleNamespace(SingleTurnSample=lambda **kwargs: kwargs))
|
| 16 |
|
| 17 |
|
|
@@ -47,7 +47,7 @@ def test_no_context_is_not_a_zero_quality_measurement():
|
|
| 47 |
def test_parallel_metrics_have_independent_evaluators(monkeypatch):
|
| 48 |
prepare(monkeypatch)
|
| 49 |
evaluators = []
|
| 50 |
-
def factory(endpoint):
|
| 51 |
evaluator = object()
|
| 52 |
evaluators.append(evaluator)
|
| 53 |
return evaluator
|
|
@@ -59,6 +59,41 @@ def test_parallel_metrics_have_independent_evaluators(monkeypatch):
|
|
| 59 |
assert len(report["scores"]) == 2
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def test_metric_errors_are_actionable_without_provider_secrets():
|
| 63 |
connection_error = type("OpenAIConnectionError", (Exception,), {})
|
| 64 |
status, error = ragas_eval._safe_metric_error(connection_error("secret-api-key"))
|
|
|
|
| 11 |
|
| 12 |
def prepare(monkeypatch):
|
| 13 |
monkeypatch.setattr(ragas_eval, "_check_ragas", lambda: True)
|
| 14 |
+
monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", lambda endpoint, **kwargs: object())
|
| 15 |
monkeypatch.setitem(sys.modules, "ragas.dataset_schema", SimpleNamespace(SingleTurnSample=lambda **kwargs: kwargs))
|
| 16 |
|
| 17 |
|
|
|
|
| 47 |
def test_parallel_metrics_have_independent_evaluators(monkeypatch):
|
| 48 |
prepare(monkeypatch)
|
| 49 |
evaluators = []
|
| 50 |
+
def factory(endpoint, **kwargs):
|
| 51 |
evaluator = object()
|
| 52 |
evaluators.append(evaluator)
|
| 53 |
return evaluator
|
|
|
|
| 59 |
assert len(report["scores"]) == 2
|
| 60 |
|
| 61 |
|
| 62 |
+
def test_metric_deadline_is_passed_to_evaluator(monkeypatch):
|
| 63 |
+
prepare(monkeypatch)
|
| 64 |
+
timeouts = []
|
| 65 |
+
monkeypatch.setattr(
|
| 66 |
+
ragas_eval,
|
| 67 |
+
"_get_evaluator_llm",
|
| 68 |
+
lambda endpoint, *, timeout: timeouts.append(timeout) or object(),
|
| 69 |
+
)
|
| 70 |
+
monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
|
| 71 |
+
report = ragas_eval.compute_ragas_report(
|
| 72 |
+
"query", ["context"], answer="answer", metric_timeout=3
|
| 73 |
+
)
|
| 74 |
+
assert timeouts == [3, 3]
|
| 75 |
+
assert len(report["scores"]) == 2
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_evaluator_wrapper_uses_supplied_timeout(monkeypatch):
|
| 79 |
+
captured = {}
|
| 80 |
+
|
| 81 |
+
class FakeRunConfig:
|
| 82 |
+
def __init__(self, **kwargs):
|
| 83 |
+
captured.update(kwargs)
|
| 84 |
+
|
| 85 |
+
class FakeWrapper:
|
| 86 |
+
def __init__(self, model, *, run_config):
|
| 87 |
+
captured["model"] = model
|
| 88 |
+
captured["run_config"] = run_config
|
| 89 |
+
|
| 90 |
+
monkeypatch.setitem(sys.modules, "ragas.llms", SimpleNamespace(LangchainLLMWrapper=FakeWrapper))
|
| 91 |
+
monkeypatch.setitem(sys.modules, "ragas.run_config", SimpleNamespace(RunConfig=FakeRunConfig))
|
| 92 |
+
ragas_eval._wrap_evaluator(object(), timeout=27)
|
| 93 |
+
assert captured["timeout"] == 27
|
| 94 |
+
assert captured["max_retries"] == 0
|
| 95 |
+
|
| 96 |
+
|
| 97 |
def test_metric_errors_are_actionable_without_provider_secrets():
|
| 98 |
connection_error = type("OpenAIConnectionError", (Exception,), {})
|
| 99 |
status, error = ragas_eval._safe_metric_error(connection_error("secret-api-key"))
|
tests/test_job_speed.py
CHANGED
|
@@ -58,7 +58,7 @@ def scheduler():
|
|
| 58 |
os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
|
| 59 |
_jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
|
| 60 |
_run_job=Mock(), _load_job=Mock(return_value=None), _authorize_request=Mock(), _rate_limit=Mock(),
|
| 61 |
-
_session=lambda request: {'github_id': request.owner}
|
| 62 |
ns['requests'].RequestException = RuntimeError
|
| 63 |
ns['requests'].get.return_value.json.return_value = {'head': {'sha': 'a'*40}, 'base': {'sha': 'b'*40}}
|
| 64 |
exec(compile(ast.Module(body=nodes, type_ignores=[]), 'backend/api.py', 'exec'), ns)
|
|
|
|
| 58 |
os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
|
| 59 |
_jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
|
| 60 |
_run_job=Mock(), _load_job=Mock(return_value=None), _authorize_request=Mock(), _rate_limit=Mock(),
|
| 61 |
+
_session=lambda request: {'github_id': request.owner})
|
| 62 |
ns['requests'].RequestException = RuntimeError
|
| 63 |
ns['requests'].get.return_value.json.return_value = {'head': {'sha': 'a'*40}, 'base': {'sha': 'b'*40}}
|
| 64 |
exec(compile(ast.Module(body=nodes, type_ignores=[]), 'backend/api.py', 'exec'), ns)
|
tests/test_ragas_api_report.py
CHANGED
|
@@ -1,23 +1,28 @@
|
|
| 1 |
import ast
|
| 2 |
-
import threading
|
| 3 |
-
import time
|
| 4 |
from pathlib import Path
|
| 5 |
-
from
|
| 6 |
-
from unittest.mock import Mock
|
| 7 |
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
job = {
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import ast
|
|
|
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
+
from types import SimpleNamespace
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
+
def test_public_job_hides_ragas_results_but_keeps_review_fields():
|
| 7 |
+
job = {
|
| 8 |
+
"id": "job",
|
| 9 |
+
"status": "awaiting_approval",
|
| 10 |
+
"findings": [],
|
| 11 |
+
"ragas_task_id": "task",
|
| 12 |
+
"ragas_scores": {"faithfulness": 0.8},
|
| 13 |
+
"ragas_status": "completed",
|
| 14 |
+
"ragas_error": None,
|
| 15 |
+
"ragas_metrics": {"faithfulness": {"status": "completed"}},
|
| 16 |
+
"ragas_evaluation": {"engine": "RAGAS"},
|
| 17 |
+
"ragas_inputs": {"endpoint": {"api_key": "private"}},
|
| 18 |
+
}
|
| 19 |
+
tree = ast.parse(Path("backend/api.py").read_text(encoding="utf-8"))
|
| 20 |
+
node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_public_job")
|
| 21 |
+
ns = {"Any": object, "time": SimpleNamespace(time=lambda: 100), "_jobs": {}}
|
| 22 |
+
exec(compile(ast.Module(body=[node], type_ignores=[]), "api.py", "exec"), ns)
|
| 23 |
+
|
| 24 |
+
result = ns["_public_job"](job)
|
| 25 |
+
|
| 26 |
+
assert result["id"] == "job"
|
| 27 |
+
assert result["status"] == "awaiting_approval"
|
| 28 |
+
assert not any(key.startswith("ragas") for key in result)
|