Spaces:
Running
Running
Deploy ae6857eb
Browse files- .env.example +5 -4
- README.md +2 -2
- backend/api.py +2 -1
- backend/integrations/endpoints.py +4 -5
- backend/integrations/llm_factory.py +23 -22
- eval_data/ragas_eval.py +3 -3
- frontend/src/main.jsx +1 -1
- frontend/src/review-client.js +1 -1
- tests/test_cloudflare_provider.py +22 -0
.env.example
CHANGED
|
@@ -13,10 +13,11 @@
|
|
| 13 |
|
| 14 |
|
| 15 |
# ─── AI Providers ────────────────────────────────────────────────────────────
|
| 16 |
-
# Optional
|
| 17 |
-
#
|
| 18 |
-
#
|
| 19 |
-
#
|
|
|
|
| 20 |
# [REQUIRED - at least one] LLM API key for the AI reviewers.
|
| 21 |
#
|
| 22 |
# Primary: Google Gemini API (generous free tier ~1 500 req/day).
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
# ─── AI Providers ────────────────────────────────────────────────────────────
|
| 16 |
+
# Optional Cloudflare Workers AI default. Set both account ID and API token.
|
| 17 |
+
# CLOUDFLARE_ACCOUNT_ID=your_account_id
|
| 18 |
+
# CLOUDFLARE_API_TOKEN=your_workers_ai_token
|
| 19 |
+
# CLOUDFLARE_MODEL=@cf/zai-org/glm-4.7-flash
|
| 20 |
+
# CLOUDFLARE_DAILY_REQUEST_LIMIT=50
|
| 21 |
# [REQUIRED - at least one] LLM API key for the AI reviewers.
|
| 22 |
#
|
| 23 |
# Primary: Google Gemini API (generous free tier ~1 500 req/day).
|
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 `
|
| 74 |
|
| 75 |
Retrieval is optional. It uses ChromaDB with local embeddings when enabled; the hosted workflow can continue with the pull request diff when retrieval is disabled or unavailable. The index is selective and revision-aware, rather than a blind copy of every repository file.
|
| 76 |
|
|
|
|
| 68 |
|
| 69 |
## Model and retrieval options
|
| 70 |
|
| 71 |
+
The model factory supports Cloudflare Workers AI, Groq and Google Gemini, plus configured custom endpoints such as OpenAI-compatible APIs and Anthropic. An explicitly selected endpoint is used for that run; otherwise the default path selects Cloudflare when configured, followed by Groq and Gemini. 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 use Workers AI's `@cf/zai-org/glm-4.7-flash` by default for automatic reviews and evaluation. `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 |
Retrieval is optional. It uses ChromaDB with local embeddings when enabled; the hosted workflow can continue with the pull request diff when retrieval is disabled or unavailable. The index is selective and revision-aware, rather than a blind copy of every repository file.
|
| 76 |
|
backend/api.py
CHANGED
|
@@ -472,8 +472,9 @@ _hydrate_jobs()
|
|
| 472 |
def health() -> dict[str, Any]:
|
| 473 |
provider_configured = any(
|
| 474 |
os.getenv(name, "").strip()
|
| 475 |
-
for name in ("
|
| 476 |
)
|
|
|
|
| 477 |
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 478 |
persistence = "local_default_path"
|
| 479 |
if os.getenv("SUPABASE_DB_URL"):
|
|
|
|
| 472 |
def health() -> dict[str, Any]:
|
| 473 |
provider_configured = any(
|
| 474 |
os.getenv(name, "").strip()
|
| 475 |
+
for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
|
| 476 |
)
|
| 477 |
+
provider_configured = provider_configured or bool(os.getenv("CLOUDFLARE_API_TOKEN", "").strip() and os.getenv("CLOUDFLARE_ACCOUNT_ID", "").strip())
|
| 478 |
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 479 |
persistence = "local_default_path"
|
| 480 |
if os.getenv("SUPABASE_DB_URL"):
|
backend/integrations/endpoints.py
CHANGED
|
@@ -222,15 +222,14 @@ def builtin_endpoints() -> list[EndpointConfig]:
|
|
| 222 |
``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
|
| 223 |
models as the default (no-endpoint) path.
|
| 224 |
"""
|
| 225 |
-
from backend.integrations.llm_factory import GEMINI_MODEL, GROQ_MODEL,
|
| 226 |
|
| 227 |
return [
|
| 228 |
EndpointConfig(
|
| 229 |
-
name="
|
| 230 |
provider="openai",
|
| 231 |
-
api_key=os.environ.get("
|
| 232 |
-
|
| 233 |
-
model=OPENROUTER_MODEL,
|
| 234 |
builtin=True,
|
| 235 |
),
|
| 236 |
EndpointConfig(
|
|
|
|
| 222 |
``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
|
| 223 |
models as the default (no-endpoint) path.
|
| 224 |
"""
|
| 225 |
+
from backend.integrations.llm_factory import GEMINI_MODEL, GROQ_MODEL, CLOUDFLARE_MODEL
|
| 226 |
|
| 227 |
return [
|
| 228 |
EndpointConfig(
|
| 229 |
+
name="Cloudflare",
|
| 230 |
provider="openai",
|
| 231 |
+
api_key=os.environ.get("CLOUDFLARE_API_TOKEN", "").strip(),
|
| 232 |
+
model=CLOUDFLARE_MODEL,
|
|
|
|
| 233 |
builtin=True,
|
| 234 |
),
|
| 235 |
EndpointConfig(
|
backend/integrations/llm_factory.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Create chat models with
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -17,8 +17,8 @@ logger = logging.getLogger(__name__)
|
|
| 17 |
# The base 'gemini-3.1-flash' does not exist in the API.
|
| 18 |
GEMINI_MODEL = "gemini-3.1-flash-lite"
|
| 19 |
GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
|
| 20 |
-
|
| 21 |
-
class
|
| 22 |
"""Conservative per-process pacing and rolling daily attempt budget."""
|
| 23 |
|
| 24 |
def __init__(self, daily_limit: int = 50):
|
|
@@ -33,7 +33,7 @@ class OpenRouterRateLimiter(BaseRateLimiter):
|
|
| 33 |
while self.attempts and self.attempts[0] <= now - 86400:
|
| 34 |
self.attempts.popleft()
|
| 35 |
if len(self.attempts) >= self.daily_limit:
|
| 36 |
-
raise ValueError("
|
| 37 |
self.attempts.append(now)
|
| 38 |
|
| 39 |
def acquire(self, *, blocking: bool = True) -> bool:
|
|
@@ -49,9 +49,9 @@ class OpenRouterRateLimiter(BaseRateLimiter):
|
|
| 49 |
return True
|
| 50 |
|
| 51 |
|
| 52 |
-
# Shared by reviewers and evaluation in this process.
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
DEFAULT_TEMPERATURE = 0.0
|
| 56 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 57 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
@@ -113,18 +113,19 @@ def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
|
|
| 113 |
return None
|
| 114 |
|
| 115 |
|
| 116 |
-
def
|
| 117 |
-
"""Use
|
| 118 |
-
api_key = os.environ.get("
|
| 119 |
-
|
|
|
|
| 120 |
return None
|
| 121 |
from langchain_openai import ChatOpenAI
|
| 122 |
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 123 |
kwargs.setdefault("max_retries", 0)
|
| 124 |
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 125 |
-
kwargs.setdefault("rate_limiter",
|
| 126 |
-
return ChatOpenAI(model=kwargs.pop("model",
|
| 127 |
-
base_url="https://
|
| 128 |
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
|
| 129 |
|
| 130 |
|
|
@@ -224,14 +225,14 @@ def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
|
|
| 224 |
}
|
| 225 |
if endpoint.base_url:
|
| 226 |
params["base_url"] = endpoint.base_url
|
| 227 |
-
if "
|
| 228 |
-
kwargs.setdefault("rate_limiter",
|
| 229 |
params.update(kwargs)
|
| 230 |
return ChatOpenAI(**params)
|
| 231 |
|
| 232 |
|
| 233 |
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 234 |
-
"""Create a chat LLM — selected endpoint first, else
|
| 235 |
|
| 236 |
Parameters
|
| 237 |
----------
|
|
@@ -260,15 +261,15 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
|
| 260 |
# The browser historically sent lowercase builtin ids while the
|
| 261 |
# endpoint registry uses display names. Accept both for API clients.
|
| 262 |
if isinstance(endpoint, str):
|
| 263 |
-
endpoint = {"gemini": "Gemini", "groq": "Grok", "
|
| 264 |
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 265 |
if ep is not None:
|
| 266 |
if getattr(ep, "builtin", False):
|
| 267 |
-
if ep.name == "
|
| 268 |
-
llm =
|
| 269 |
if llm is not None:
|
| 270 |
return llm
|
| 271 |
-
raise ValueError("
|
| 272 |
# Built-in providers use their native constructors so the
|
| 273 |
# behaviour is identical to the default (no-endpoint) path.
|
| 274 |
if ep.name == "Gemini":
|
|
@@ -306,7 +307,7 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
|
| 306 |
"or add it in the UI."
|
| 307 |
)
|
| 308 |
|
| 309 |
-
llm =
|
| 310 |
if llm is not None:
|
| 311 |
return llm
|
| 312 |
|
|
|
|
| 1 |
+
"""Create chat models with Cloudflare, Groq, Gemini, and custom endpoints."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 17 |
# The base 'gemini-3.1-flash' does not exist in the API.
|
| 18 |
GEMINI_MODEL = "gemini-3.1-flash-lite"
|
| 19 |
GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
|
| 20 |
+
CLOUDFLARE_MODEL = os.getenv("CLOUDFLARE_MODEL", "@cf/zai-org/glm-4.7-flash")
|
| 21 |
+
class CloudflareRateLimiter(BaseRateLimiter):
|
| 22 |
"""Conservative per-process pacing and rolling daily attempt budget."""
|
| 23 |
|
| 24 |
def __init__(self, daily_limit: int = 50):
|
|
|
|
| 33 |
while self.attempts and self.attempts[0] <= now - 86400:
|
| 34 |
self.attempts.popleft()
|
| 35 |
if len(self.attempts) >= self.daily_limit:
|
| 36 |
+
raise ValueError("Cloudflare local daily request budget reached; try later or choose another provider.")
|
| 37 |
self.attempts.append(now)
|
| 38 |
|
| 39 |
def acquire(self, *, blocking: bool = True) -> bool:
|
|
|
|
| 49 |
return True
|
| 50 |
|
| 51 |
|
| 52 |
+
# Shared by reviewers and evaluation in this process. This request budget is
|
| 53 |
+
# a conservative application cap, not a measurement of Cloudflare neurons.
|
| 54 |
+
_cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
|
| 55 |
DEFAULT_TEMPERATURE = 0.0
|
| 56 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 57 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
|
|
| 113 |
return None
|
| 114 |
|
| 115 |
|
| 116 |
+
def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
|
| 117 |
+
"""Use Workers AI when an account ID and API token are configured."""
|
| 118 |
+
api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
|
| 119 |
+
account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
|
| 120 |
+
if not api_key or not account_id:
|
| 121 |
return None
|
| 122 |
from langchain_openai import ChatOpenAI
|
| 123 |
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 124 |
kwargs.setdefault("max_retries", 0)
|
| 125 |
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 126 |
+
kwargs.setdefault("rate_limiter", _cloudflare_limiter)
|
| 127 |
+
return ChatOpenAI(model=kwargs.pop("model", CLOUDFLARE_MODEL), api_key=api_key,
|
| 128 |
+
base_url=f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1",
|
| 129 |
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
|
| 130 |
|
| 131 |
|
|
|
|
| 225 |
}
|
| 226 |
if endpoint.base_url:
|
| 227 |
params["base_url"] = endpoint.base_url
|
| 228 |
+
if "api.cloudflare.com/client/v4/accounts/" in endpoint.base_url.lower():
|
| 229 |
+
kwargs.setdefault("rate_limiter", _cloudflare_limiter)
|
| 230 |
params.update(kwargs)
|
| 231 |
return ChatOpenAI(**params)
|
| 232 |
|
| 233 |
|
| 234 |
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 235 |
+
"""Create a chat LLM — selected endpoint first, else Cloudflare → Groq → Gemini.
|
| 236 |
|
| 237 |
Parameters
|
| 238 |
----------
|
|
|
|
| 261 |
# The browser historically sent lowercase builtin ids while the
|
| 262 |
# endpoint registry uses display names. Accept both for API clients.
|
| 263 |
if isinstance(endpoint, str):
|
| 264 |
+
endpoint = {"gemini": "Gemini", "groq": "Grok", "cloudflare": "Cloudflare"}.get(endpoint.lower(), endpoint)
|
| 265 |
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 266 |
if ep is not None:
|
| 267 |
if getattr(ep, "builtin", False):
|
| 268 |
+
if ep.name == "Cloudflare":
|
| 269 |
+
llm = _get_cloudflare_chat(**kwargs)
|
| 270 |
if llm is not None:
|
| 271 |
return llm
|
| 272 |
+
raise ValueError("Cloudflare selected but CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set.")
|
| 273 |
# Built-in providers use their native constructors so the
|
| 274 |
# behaviour is identical to the default (no-endpoint) path.
|
| 275 |
if ep.name == "Gemini":
|
|
|
|
| 307 |
"or add it in the UI."
|
| 308 |
)
|
| 309 |
|
| 310 |
+
llm = _get_cloudflare_chat(**kwargs)
|
| 311 |
if llm is not None:
|
| 312 |
return llm
|
| 313 |
|
eval_data/ragas_eval.py
CHANGED
|
@@ -218,11 +218,11 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
|
|
| 218 |
logger.info("RAGAS evaluator: using selected custom endpoint")
|
| 219 |
return _wrap_evaluator(llm)
|
| 220 |
|
| 221 |
-
from backend.integrations.llm_factory import
|
| 222 |
|
| 223 |
-
llm =
|
| 224 |
if llm is not None:
|
| 225 |
-
logger.info("RAGAS evaluator: using
|
| 226 |
return _wrap_evaluator(llm)
|
| 227 |
|
| 228 |
# Keep evaluation bounded: RAGAS runs several provider calls and
|
|
|
|
| 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=15)
|
| 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
|
frontend/src/main.jsx
CHANGED
|
@@ -175,7 +175,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="openrouter">OpenRouter free</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 |
|
|
|
|
| 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 |
|
frontend/src/review-client.js
CHANGED
|
@@ -38,7 +38,7 @@ export function upsertProvider(entries, item, previousName = null) {
|
|
| 38 |
}
|
| 39 |
|
| 40 |
export function reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha = "") {
|
| 41 |
-
const builtinEndpoint = {gemini: 'Gemini', groq: 'Grok',
|
| 42 |
const payload = { repo: repo.trim(), pr_number: Number(pr), endpoint: builtinEndpoint, review_mode: reviewMode };
|
| 43 |
if (baselineSha.trim()) {
|
| 44 |
if (!/^[a-fA-F0-9]{40}$/.test(baselineSha.trim())) throw new Error("Enter the full 40-character baseline commit SHA.");
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
export function reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha = "") {
|
| 41 |
+
const builtinEndpoint = {gemini: 'Gemini', groq: 'Grok', cloudflare: 'Cloudflare'}[endpoint] || endpoint;
|
| 42 |
const payload = { repo: repo.trim(), pr_number: Number(pr), endpoint: builtinEndpoint, review_mode: reviewMode };
|
| 43 |
if (baselineSha.trim()) {
|
| 44 |
if (!/^[a-fA-F0-9]{40}$/.test(baselineSha.trim())) throw new Error("Enter the full 40-character baseline commit SHA.");
|
tests/test_cloudflare_provider.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from backend.integrations import llm_factory
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
| 7 |
+
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
|
| 8 |
+
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'test-account')
|
| 9 |
+
model = llm_factory._get_cloudflare_chat()
|
| 10 |
+
assert model.model_name == '@cf/zai-org/glm-4.7-flash'
|
| 11 |
+
assert str(model.openai_api_base) == 'https://api.cloudflare.com/client/v4/accounts/test-account/ai/v1'
|
| 12 |
+
assert model.max_retries == 0
|
| 13 |
+
assert model.rate_limiter is llm_factory._cloudflare_limiter
|
| 14 |
+
assert llm_factory.create_llm().rate_limiter is model.rate_limiter
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_daily_budget_rejects_additional_attempts():
|
| 18 |
+
limiter = llm_factory.CloudflareRateLimiter(daily_limit=2)
|
| 19 |
+
limiter._reserve()
|
| 20 |
+
limiter._reserve()
|
| 21 |
+
with pytest.raises(ValueError, match='daily request budget'):
|
| 22 |
+
limiter._reserve()
|