Sdm0 commited on
Commit
da9e3ef
·
verified ·
1 Parent(s): 107d232

Deploy d8ce0011

Browse files
.env.example CHANGED
@@ -13,6 +13,10 @@
13
 
14
 
15
  # ─── AI Providers ────────────────────────────────────────────────────────────
 
 
 
 
16
  # [REQUIRED - at least one] LLM API key for the AI reviewers.
17
  #
18
  # Primary: Google Gemini API (generous free tier ~1 500 req/day).
 
13
 
14
 
15
  # ─── AI Providers ────────────────────────────────────────────────────────────
16
+ # Optional default free router. Set your OpenRouter key to enable it.
17
+ # OPENROUTER_API_KEY=your_openrouter_key
18
+ # OPENROUTER_MODEL=openrouter/free
19
+ # OPENROUTER_DAILY_REQUEST_LIMIT=50
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).
README.md CHANGED
@@ -68,7 +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 the built-in Groq and Google Gemini providers, plus configured custom endpoints such as OpenAI-compatible APIs and Anthropic. An explicitly selected endpoint is used for that run; otherwise the default path prefers Groq when configured and falls back to 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
  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.
74
 
 
68
 
69
  ## Model and retrieval options
70
 
71
+ The model factory supports OpenRouter, 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 OpenRouter 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 `OPENROUTER_API_KEY` to make the `openrouter/free` router the default for automatic reviews and evaluation. `OPENROUTER_MODEL` can override the model, and `OPENROUTER_DAILY_REQUEST_LIMIT` sets the local rolling attempt budget (default 50). Calls are paced to one every five seconds and automatic provider retries are disabled. The local budget resets on restart and is shared only within one process; OpenRouter enforces account-wide limits, including requests from other applications. Free model availability, structured output support, and quotas vary. See [OpenRouter's free model limits](https://openrouter.ai/collections/free-models/).
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,7 +472,7 @@ _hydrate_jobs()
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
  require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
478
  persistence = "local_default_path"
 
472
  def health() -> dict[str, Any]:
473
  provider_configured = any(
474
  os.getenv(name, "").strip()
475
+ for name in ("OPENROUTER_API_KEY", "GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
476
  )
477
  require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
478
  persistence = "local_default_path"
backend/integrations/endpoints.py CHANGED
@@ -222,9 +222,17 @@ 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="Gemini",
230
  provider="google",
 
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, OPENROUTER_MODEL
226
 
227
  return [
228
+ EndpointConfig(
229
+ name="OpenRouter",
230
+ provider="openai",
231
+ api_key=os.environ.get("OPENROUTER_API_KEY", "").strip(),
232
+ base_url="https://openrouter.ai/api/v1",
233
+ model=OPENROUTER_MODEL,
234
+ builtin=True,
235
+ ),
236
  EndpointConfig(
237
  name="Gemini",
238
  provider="google",
backend/integrations/llm_factory.py CHANGED
@@ -1,21 +1,14 @@
1
- """LLM factory — creates LangChain chat models with primary + fallback support.
2
-
3
- Priority
4
- --------
5
- 1. **Google Gemini** (primary) — uses ``GEMINI_API_KEY`` env var.
6
- Model: ``gemini-3.1-flash-lite`` — generous free tier.
7
- 2. **Groq** (fallback) — uses ``GROQ_API_KEY`` env var.
8
- Model: ``llama-3.3-70b-versatile`` — fast inference, lower free limit.
9
-
10
- If neither key is set, functions raise ``ValueError`` so callers can skip
11
- gracefully (as they already do for Groq-only today).
12
- """
13
 
14
  from __future__ import annotations
15
 
16
  import logging
17
  import os
 
 
 
18
  from typing import Any, Optional
 
19
 
20
  logger = logging.getLogger(__name__)
21
 
@@ -24,6 +17,41 @@ logger = logging.getLogger(__name__)
24
  # The base 'gemini-3.1-flash' does not exist in the API.
25
  GEMINI_MODEL = "gemini-3.1-flash-lite"
26
  GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  DEFAULT_TEMPERATURE = 0.0
28
  DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
29
  DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
@@ -85,6 +113,21 @@ def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
85
  return None
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
89
  """Create a chat model from a user-configured custom endpoint.
90
 
@@ -181,12 +224,14 @@ def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
181
  }
182
  if endpoint.base_url:
183
  params["base_url"] = endpoint.base_url
 
 
184
  params.update(kwargs)
185
  return ChatOpenAI(**params)
186
 
187
 
188
  def create_llm(endpoint=None, **kwargs: Any) -> Any:
189
- """Create a chat LLM — custom endpoint first, else Gemini → Groq.
190
 
191
  Parameters
192
  ----------
@@ -215,10 +260,15 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
215
  # The browser historically sent lowercase builtin ids while the
216
  # endpoint registry uses display names. Accept both for API clients.
217
  if isinstance(endpoint, str):
218
- endpoint = {"gemini": "Gemini", "groq": "Grok"}.get(endpoint.lower(), endpoint)
219
  ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
220
  if ep is not None:
221
  if getattr(ep, "builtin", False):
 
 
 
 
 
222
  # Built-in providers use their native constructors so the
223
  # behaviour is identical to the default (no-endpoint) path.
224
  if ep.name == "Gemini":
@@ -256,6 +306,10 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
256
  "or add it in the UI."
257
  )
258
 
 
 
 
 
259
  # Prefer Groq when configured: it has a separate quota pool and avoids
260
  # stalling the review pipeline on Gemini free-tier exhaustion.
261
  llm = _get_groq_chat(**kwargs)
 
1
+ """Create chat models with OpenRouter, Groq, Gemini, and custom endpoints."""
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
  import logging
6
  import os
7
+ import threading
8
+ import time
9
+ from collections import deque
10
  from typing import Any, Optional
11
+ from langchain_core.rate_limiters import BaseRateLimiter, InMemoryRateLimiter
12
 
13
  logger = logging.getLogger(__name__)
14
 
 
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
+ OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "openrouter/free")
21
+ class OpenRouterRateLimiter(BaseRateLimiter):
22
+ """Conservative per-process pacing and rolling daily attempt budget."""
23
+
24
+ def __init__(self, daily_limit: int = 50):
25
+ self.pacer = InMemoryRateLimiter(requests_per_second=0.2, check_every_n_seconds=0.1, max_bucket_size=1)
26
+ self.daily_limit = daily_limit
27
+ self.attempts = deque()
28
+ self.lock = threading.Lock()
29
+
30
+ def _reserve(self):
31
+ now = time.monotonic()
32
+ with self.lock:
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("OpenRouter 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:
40
+ if not self.pacer.acquire(blocking=blocking):
41
+ return False
42
+ self._reserve()
43
+ return True
44
+
45
+ async def aacquire(self, *, blocking: bool = True) -> bool:
46
+ if not await self.pacer.aacquire(blocking=blocking):
47
+ return False
48
+ self._reserve()
49
+ return True
50
+
51
+
52
+ # Shared by reviewers and evaluation in this process. OpenRouter enforces the
53
+ # account-wide quota across restarts, deployments, and other applications.
54
+ _openrouter_limiter = OpenRouterRateLimiter(max(1, int(os.getenv("OPENROUTER_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_openrouter_chat(**kwargs: Any) -> Optional[Any]:
117
+ """Use the OpenRouter free router when a server-side key is configured."""
118
+ api_key = os.environ.get("OPENROUTER_API_KEY", "").strip()
119
+ if not api_key:
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", _openrouter_limiter)
126
+ return ChatOpenAI(model=kwargs.pop("model", OPENROUTER_MODEL), api_key=api_key,
127
+ base_url="https://openrouter.ai/api/v1",
128
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
129
+
130
+
131
  def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
132
  """Create a chat model from a user-configured custom endpoint.
133
 
 
224
  }
225
  if endpoint.base_url:
226
  params["base_url"] = endpoint.base_url
227
+ if "openrouter.ai" in endpoint.base_url.lower():
228
+ kwargs.setdefault("rate_limiter", _openrouter_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 OpenRouter → Groq → Gemini.
235
 
236
  Parameters
237
  ----------
 
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", "openrouter": "OpenRouter"}.get(endpoint.lower(), endpoint)
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 == "OpenRouter":
268
+ llm = _get_openrouter_chat(**kwargs)
269
+ if llm is not None:
270
+ return llm
271
+ raise ValueError("OpenRouter selected but OPENROUTER_API_KEY is not set.")
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
  "or add it in the UI."
307
  )
308
 
309
+ llm = _get_openrouter_chat(**kwargs)
310
+ if llm is not None:
311
+ return llm
312
+
313
  # Prefer Groq when configured: it has a separate quota pool and avoids
314
  # stalling the review pipeline on Gemini free-tier exhaustion.
315
  llm = _get_groq_chat(**kwargs)
eval_data/ragas_eval.py CHANGED
@@ -218,7 +218,12 @@ 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 _get_groq_chat, _get_gemini_chat
 
 
 
 
 
222
 
223
  # Keep evaluation bounded: RAGAS runs several provider calls and
224
  # retrying each one can otherwise hold a review open for minutes.
 
218
  logger.info("RAGAS evaluator: using selected custom endpoint")
219
  return _wrap_evaluator(llm)
220
 
221
+ from backend.integrations.llm_factory import _get_openrouter_chat, _get_groq_chat, _get_gemini_chat
222
+
223
+ llm = _get_openrouter_chat(temperature=0, max_retries=0, timeout=15)
224
+ if llm is not None:
225
+ logger.info("RAGAS evaluator: using OpenRouter free router")
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.
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>&rarr;</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="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 &amp; 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>&rarr;</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>&rarr;</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 &amp; 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>&rarr;</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'}[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.");
 
38
  }
39
 
40
  export function reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha = "") {
41
+ const builtinEndpoint = {gemini: 'Gemini', groq: 'Grok', openrouter: 'OpenRouter'}[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_openrouter_provider.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from backend.integrations import llm_factory
4
+
5
+
6
+ def test_openrouter_default_and_shared_pacing(monkeypatch):
7
+ monkeypatch.setenv('OPENROUTER_API_KEY', 'test-key')
8
+ model = llm_factory._get_openrouter_chat()
9
+ assert model.model_name == 'openrouter/free'
10
+ assert model.max_retries == 0
11
+ assert model.rate_limiter is llm_factory._openrouter_limiter
12
+ assert llm_factory.create_llm().rate_limiter is model.rate_limiter
13
+
14
+
15
+ def test_daily_budget_rejects_additional_attempts():
16
+ limiter = llm_factory.OpenRouterRateLimiter(daily_limit=2)
17
+ limiter._reserve()
18
+ limiter._reserve()
19
+ with pytest.raises(ValueError, match='daily request budget'):
20
+ limiter._reserve()