{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[8ec3e9c4] nice\n\nSide A — unified diff (full patch):\ndiff --git a/deploy/open-webui/README.md b/deploy/open-webui/README.md\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..0f1317f745f31530fa687c8a35e5e3a726d1dda2\n--- /dev/null\n+++ b/deploy/open-webui/README.md\n@@ -0,0 +1,71 @@\n+# Open WebUI on Fly.io (minimal, OpenRouter)\n+\n+You do **not** need to host your own model. [OpenRouter](https://openrouter.ai/) runs the LLMs; this Fly app only runs the Open WebUI shell.\n+\n+### Disk vs RAM\n+\n+The container image still includes ML libraries on **disk** (upstream wheels). These settings target **runtime memory**: chat and API proxy use remote inference, and `RAG_EMBEDDING_ENGINE=openai` plus `AUDIO_STT_ENGINE=openai` tell Open WebUI to call your configured OpenAI-compatible API for embeddings and speech-to-text instead of loading local SentenceTransformers / Whisper models into RAM (see Open WebUI [performance](https://docs.openwebui.com/troubleshooting/performance/) notes on embedding offload).\n+\n+You may still see higher RSS if you use features that pull in other local code paths. For a fresh volume, the `[env]` values apply on first boot; if you already ran Open WebUI, stored admin settings can override some env vars ([PersistentConfig](https://docs.openwebui.com/reference/env-configuration/) — adjust in Admin or reset the volume for a clean slate).\n+\n+## Prerequisites\n+\n+- [Fly CLI](https://fly.io/docs/hands-on/install-flyctl/) and `fly auth login`\n+- An OpenRouter API key (`sk-or-…` from [openrouter.ai/keys](https://openrouter.ai/keys))\n+\n+## One-time setup\n+\n+1. Edit `fly.toml` and set `app = \"your-unique-name\"` (globally unique on Fly).\n+\n+2. Create the app (if it does not exist):\n+\n+ ```bash\n+ fly apps create your-unique-name\n+ ```\n+\n+3. Create a volume for SQLite and uploads (region must match `primary_region` in `fly.toml`):\n+\n+ ```bash\n+ fly volumes create open_webui_data --region iad --size 3\n+ ```\n+\n+4. Set secrets:\n+\n+ ```bash\n+ fly secrets set OPENAI_API_KEY=\"sk-or-...\" \\\n+ WEBUI_SECRET_KEY=\"$(openssl rand -hex 32)\" \\\n+ WEBUI_URL=\"https://your-unique-name.fly.dev\"\n+ ```\n+\n+ Optional but convenient: create the first admin in one step (disables open signup on first boot):\n+\n+ ```bash\n+ fly secrets set WEBUI_ADMIN_EMAIL=\"you@example.com\" WEBUI_ADMIN_PASSWORD='strong-password-here'\n+ ```\n+\n+5. Deploy:\n+\n+ ```bash\n+ cd deploy/open-webui && fly deploy\n+ ```\n+\n+Open `https://your-unique-name.fly.dev`. In the UI, pick a model served by OpenRouter (IDs like `openai/gpt-4o`, `anthropic/claude-3.5-sonnet`, etc.).\n+\n+## If the machine runs out of memory\n+\n+The `fly.toml` env is tuned to avoid local embedding/STT models in RAM; if it still OOMs (large chats, document uploads, many users), scale up:\n+\n+```bash\n+fly scale memory 2048\n+# or 4096 if needed\n+```\n+\n+## When you *would* self-host a model\n+\n+Only if you want **local / private inference** (no third-party API). That usually means **Ollama** or similar on a GPU-capable host, not this minimal Fly setup. For “just chat via API,” OpenRouter (or direct OpenAI) is enough.\n+\n+## Notes\n+\n+- `OPENAI_API_BASE_URL` points at OpenRouter’s OpenAI-compatible API; `OPENAI_API_KEY` is your OpenRouter key.\n+- After the first run, some settings are stored in the volume under `/app/backend/data` (see Open WebUI docs on `PersistentConfig`).\n+- Pin the image tag instead of `:main` in `fly.toml` if you want reproducible deploys.\ndiff --git a/deploy/open-webui/fly.toml b/deploy/open-webui/fly.toml\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..684ae6d108e6a90906ef95c5075b468fe8280134\n--- /dev/null\n+++ b/deploy/open-webui/fly.toml\n@@ -0,0 +1,59 @@\n+# Open WebUI on Fly.io — OpenRouter only (no Ollama).\n+# Runtime RAM: RAG_EMBEDDING_ENGINE + AUDIO_STT_ENGINE use your OpenRouter HTTP API so local\n+# SentenceTransformers / Whisper weights are not loaded into memory (torch may still exist on disk in the image).\n+# Replace `app` with your Fly app name, then:\n+# fly volumes create open_webui_data --region --size 3\n+# fly secrets set OPENAI_API_KEY=sk-or-... WEBUI_SECRET_KEY=$(openssl rand -hex 32)\n+# fly secrets set WEBUI_URL=https://.fly.dev\n+# Optional (recommended): headless admin, signup disabled automatically:\n+# fly secrets set WEBUI_ADMIN_EMAIL=you@example.com WEBUI_ADMIN_PASSWORD='...'\n+# fly deploy\n+\n+app = \"open-webui\"\n+primary_region = \"iad\"\n+\n+[build]\n+ image = \"ghcr.io/open-webui/open-webui:main\"\n+\n+[env]\n+ OPENAI_API_BASE_URL = \"https://openrouter.ai/api/v1\"\n+ ENABLE_OLLAMA_API = \"false\"\n+ # One worker so we do not duplicate in-RAM state (see Open WebUI scaling docs).\n+ UVICORN_WORKERS = \"1\"\n+ # Remote embeddings via OpenAI-compatible API (OpenRouter) — avoids ~500MB+ local embedding model in RAM.\n+ RAG_EMBEDDING_ENGINE = \"openai\"\n+ # Remote speech-to-text when using voice — avoids loading faster-whisper into RAM.\n+ AUDIO_STT_ENGINE = \"openai\"\n+ # Speeds up model list with OpenRouter’s large catalog (small in-memory cache).\n+ ENABLE_BASE_MODELS_CACHE = \"true\"\n+\n+[[mounts]]\n+ source = \"open_webui_data\"\n+ destination = \"/app/backend/data\"\n+\n+[[services]]\n+ internal_port = 8080\n+ protocol = \"tcp\"\n+\n+ [[services.ports]]\n+ port = 80\n+ handlers = [\"http\"]\n+ force_https = true\n+\n+ [[services.ports]]\n+ port = 443\n+ handlers = [\"tls\", \"http\"]\n+\n+ [services.concurrency]\n+ type = \"connections\"\n+ hard_limit = 250\n+ soft_limit = 200\n+\n+ [[services.http_checks]]\n+ interval = \"15s\"\n+ timeout = \"5s\"\n+ grace_period = \"60s\"\n+ method = \"GET\"\n+ path = \"/health\"\n+ protocol = \"http\"\n+ tls_skip_verify = false\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[8f69c309] Require Reddit OAuth when credentials are set and refresh on 401/403.\n\nAvoid falling back to the public www.reddit.com API from cloud IPs, which\nreturns Reddit's network-security block page. Also pin SORTER2_BASE_URL in fly.toml.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/fly.toml b/fly.toml\nindex f0c6a39f643c204987debc177234d95a8ef44b65..ca7e0088a7efd7d58d29d808f8d89080b2bff233 100644\n--- a/fly.toml\n+++ b/fly.toml\n@@ -5,6 +5,7 @@ primary_region = \"iad\"\n dockerfile = \"Dockerfile\"\n \n [env]\n+ SORTER2_BASE_URL = \"https://reddit.sorter.social\"\n SORTER2_DATA_DIR = \"/data\"\n SORTER2_EVENT_LOG = \"/data/events.jsonl\"\n PORT = \"8080\"\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nindex a874814f8927192ee62cab2d0db1efd27dcd57b7..f409764c1e1f36216f1b08107043c2eab905694c 100644\n--- a/server/src/reddit.rs\n+++ b/server/src/reddit.rs\n@@ -283,26 +283,35 @@ async fn reddit_worker(\n );\n tokio::time::sleep(current_delay).await;\n \n- if let Some(c) = &creds {\n- oauth = ensure_oauth_token(&client, &oauth_token_base, c, oauth.take()).await;\n- }\n-\n- let token = oauth.as_ref().map(|t| t.access_token.as_str());\n- let fetch_base = if token.is_some() {\n- tracing::debug!(\n- item = %fetch_id,\n- base = %oauth_api_base,\n- \"reddit fetch using OAuth bearer\"\n- );\n- &oauth_api_base\n- } else {\n- &api_base\n- };\n- let url = match kind {\n- FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, fetch_base),\n- FetchKind::Children => map_children_url(&fetch_id, fetch_base),\n+ let outcome = match &creds {\n+ Some(c) => {\n+ // OAuth is required when credentials are configured — never fall\n+ // back to the public www.reddit.com JSON endpoints (cloud IPs\n+ // get blocked with a 403 HTML interstitial).\n+ fetch_with_oauth(\n+ &client,\n+ &oauth_token_base,\n+ &oauth_api_base,\n+ c,\n+ &mut oauth,\n+ &fetch_id,\n+ kind,\n+ )\n+ .await\n+ }\n+ None => {\n+ let url = match kind {\n+ FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, &api_base),\n+ FetchKind::Children => map_children_url(&fetch_id, &api_base),\n+ };\n+ match do_fetch(&client, &url, &fetch_id, None).await {\n+ Ok(FetchOutcome::AuthRejected { status, detail }) => {\n+ Err(format!(\"Reddit API {status}: {detail}\"))\n+ }\n+ other => other,\n+ }\n+ }\n };\n- let outcome = do_fetch(&client, &url, &fetch_id, token).await;\n \n match outcome {\n Ok(FetchOutcome::Payload(payload)) => {\n@@ -342,6 +351,12 @@ async fn reddit_worker(\n current_delay = (current_delay * 2).min(Duration::from_secs(60));\n notify(done, FetchJobResult::RateLimited { reset_secs });\n }\n+ Ok(FetchOutcome::AuthRejected { status, detail }) => {\n+ let e = format!(\"Reddit API {status}: {detail}\");\n+ tracing::warn!(item = %fetch_id, err = %e, \"reddit fetch auth rejected\");\n+ current_delay = (current_delay * 2).min(Duration::from_secs(60));\n+ notify(done, FetchJobResult::Failed(e));\n+ }\n Err(e) => {\n tracing::warn!(item = %fetch_id, err = %e, \"reddit fetch failed\");\n current_delay = (current_delay * 2).min(Duration::from_secs(60));\n@@ -357,6 +372,60 @@ enum FetchOutcome {\n Payload(Value),\n NotFound,\n RateLimited { reset_secs: u64 },\n+ /// Bearer rejected — caller should drop the cached token and retry once.\n+ AuthRejected { status: StatusCode, detail: String },\n+}\n+\n+async fn fetch_with_oauth(\n+ client: &Client,\n+ oauth_token_base: &str,\n+ oauth_api_base: &str,\n+ creds: &RedditCredentials,\n+ oauth: &mut Option,\n+ fetch_id: &ItemId,\n+ kind: FetchKind,\n+) -> Result {\n+ for attempt in 0..2 {\n+ let force_refresh = attempt > 0;\n+ *oauth = Some(\n+ ensure_oauth_token(client, oauth_token_base, creds, oauth.take(), force_refresh)\n+ .await?,\n+ );\n+ let token = oauth\n+ .as_ref()\n+ .expect(\"token set above\")\n+ .access_token\n+ .clone();\n+\n+ tracing::debug!(\n+ item = %fetch_id,\n+ base = %oauth_api_base,\n+ attempt,\n+ \"reddit fetch using OAuth bearer\"\n+ );\n+\n+ let url = match kind {\n+ FetchKind::SelfEntity => map_item_to_reddit_api(fetch_id, oauth_api_base),\n+ FetchKind::Children => map_children_url(fetch_id, oauth_api_base),\n+ };\n+ match do_fetch(client, &url, fetch_id, Some(&token)).await? {\n+ FetchOutcome::AuthRejected { status, detail } if attempt == 0 => {\n+ tracing::warn!(\n+ item = %fetch_id,\n+ %status,\n+ %detail,\n+ \"reddit OAuth rejected; refreshing token and retrying\"\n+ );\n+ *oauth = None;\n+ continue;\n+ }\n+ FetchOutcome::AuthRejected { status, detail } => {\n+ return Err(format!(\"Reddit API {status}: {detail}\"));\n+ }\n+ other => return Ok(other),\n+ }\n+ }\n+ unreachable!(\"loop always returns\")\n }\n \n async fn ensure_oauth_token(\n@@ -364,35 +433,35 @@ async fn ensure_oauth_token(\n oauth_base: &str,\n creds: &RedditCredentials,\n existing: Option,\n-) -> Option {\n- if let Some(t) = existing {\n- if Instant::now() < t.expires_at - Duration::from_secs(60) {\n- tracing::debug!(\"reddit OAuth token still valid\");\n- return Some(t);\n+ force_refresh: bool,\n+) -> Result {\n+ if !force_refresh {\n+ if let Some(t) = existing {\n+ if Instant::now() < t.expires_at - Duration::from_secs(60) {\n+ tracing::debug!(\"reddit OAuth token still valid\");\n+ return Ok(t);\n+ }\n }\n }\n \n let url = format!(\"{}/api/v1/access_token\", oauth_base.trim_end_matches('/'));\n- tracing::debug!(%url, \"reddit OAuth token request\");\n+ tracing::debug!(%url, force_refresh, \"reddit OAuth token request\");\n \n let resp = client\n .post(&url)\n .basic_auth(&creds.client_id, Some(&creds.client_secret))\n .form(&[(\"grant_type\", \"client_credentials\")])\n .send()\n- .await;\n-\n- let resp = match resp {\n- Ok(r) => r,\n- Err(e) => {\n- tracing::warn!(\"reddit OAuth token request failed: {e}\");\n- return None;\n- }\n- };\n+ .await\n+ .map_err(|e| format!(\"Reddit OAuth token request failed: {e}\"))?;\n \n if !resp.status().is_success() {\n- tracing::warn!(\"reddit OAuth token HTTP {}\", resp.status());\n- return None;\n+ let status = resp.status();\n+ let body = resp.text().await.unwrap_or_default();\n+ return Err(format!(\n+ \"Reddit OAuth token HTTP {status}: {}\",\n+ truncate_for_error(&body)\n+ ));\n }\n \n #[derive(Deserialize)]\n@@ -401,21 +470,40 @@ async fn ensure_oauth_token(\n expires_in: u64,\n }\n \n- let body: TokenResponse = match resp.json().await {\n- Ok(b) => b,\n- Err(e) => {\n- tracing::warn!(\"reddit OAuth token parse failed: {e}\");\n- return None;\n- }\n- };\n+ let body: TokenResponse = resp\n+ .json()\n+ .await\n+ .map_err(|e| format!(\"Reddit OAuth token parse failed: {e}\"))?;\n \n- tracing::debug!(expires_in = body.expires_in, \"reddit OAuth token acquired\");\n- Some(OAuthToken {\n+ tracing::info!(expires_in = body.expires_in, \"reddit OAuth token acquired\");\n+ Ok(OAuthToken {\n access_token: body.access_token,\n expires_at: Instant::now() + Duration::from_secs(body.expires_in),\n })\n }\n \n+fn truncate_for_error(body: &str) -> String {\n+ let compact: String = body.split_whitespace().collect::>().join(\" \");\n+ if compact.is_empty() {\n+ return \"(empty body)\".into();\n+ }\n+ // Prefer the human-readable block message over dumping Reddit's CSS.\n+ if let Some(idx) = compact.find(\"You've been blocked\") {\n+ let slice: String = compact.chars().skip(idx).take(160).collect();\n+ return if compact.chars().count() > idx + 160 {\n+ format!(\"{slice}…\")\n+ } else {\n+ slice\n+ };\n+ }\n+ let chars: String = compact.chars().take(200).collect();\n+ if compact.chars().count() > 200 {\n+ format!(\"{chars}…\")\n+ } else {\n+ chars\n+ }\n+}\n+\n async fn do_fetch(\n client: &Client,\n url: &str,\n@@ -460,15 +548,16 @@ async fn do_fetch(\n \n if !status.is_success() {\n let body = resp.text().await.unwrap_or_default();\n+ let detail = truncate_for_error(&body);\n tracing::debug!(\n item = %id,\n %status,\n body_len = body.len(),\n- body_prefix = %body.chars().take(240).collect::(),\n+ %detail,\n \"reddit non-success body\"\n );\n if status == StatusCode::FORBIDDEN || status == StatusCode::UNAUTHORIZED {\n- return Err(format!(\"Reddit API {status}: {body}\"));\n+ return Ok(FetchOutcome::AuthRejected { status, detail });\n }\n return Ok(FetchOutcome::NotFound);\n }\n@@ -716,6 +805,15 @@ fn reddit_direct_image_url(url: &str) -> bool {\n mod tests {\n use super::*;\n \n+ #[test]\n+ fn truncate_error_prefers_block_message() {\n+ let html = r#\"
You've been blocked by network security. To continue, log in
\"#;\n+ let msg = truncate_for_error(html);\n+ assert!(msg.starts_with(\"You've been blocked\"));\n+ assert!(msg.len() < 200);\n+ assert!(!msg.contains(\".x{color\"));\n+ }\n+\n #[test]\n fn map_subreddit_about_url() {\n let id = ItemId::from_url(\"https://reddit.com/r/rust\").unwrap();\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}