Python
feat(providers): add OpenRouter account sign-in
Rakesh Utekar87d344ad03ae
diff --git a/README.md b/README.mdindex 60172b41..d61f32e8 100644--- a/README.md+++ b/README.md@@ -22,6 +22,15 @@ It runs on your machine and doesn't lock you into any model: bring your own APIOpen the app, add a model key (or point it at Ollama), and ask for something real.+For OpenRouter, open **Settings → Models → OpenRouter** (also available during+setup). Enter an API key and click **Test**, or choose **Sign in with OpenRouter**+below the key field. Browser sign-in uses your OpenRouter credits and stores the+issued key locally. For a remote backend, choose **Use a manual code** and paste+the code shown by OpenRouter. Signing in selects account credentials; testing and+saving an API key explicitly switches back. Disconnecting an active account does+not silently fall back to a saved or environment key. To revoke the issued key+remotely, use the **Manage or revoke keys on OpenRouter** link.+## Use casesPick a coworker, point it at real work, get a finished deliverable:diff --git a/coworker/providers/openrouter_auth.py b/coworker/providers/openrouter_auth.pynew file mode 100644index 00000000..c1c52a8a--- /dev/null+++ b/coworker/providers/openrouter_auth.py@@ -0,0 +1,197 @@+"""OpenRouter PKCE login. Account keys stay server-side; no refresh token is issued."""++from __future__ import annotations++import asyncio+import base64+import hashlib+import secrets+from collections.abc import Callable+from typing import Any+from urllib.parse import parse_qs, urlencode, urlsplit++import httpx++PROFILE = "provider:openrouter-account"+BASE_URL = "https://openrouter.ai/api/v1"+++async def exchange_key(code: str, verifier: str) -> str:+ async with httpx.AsyncClient(timeout=30) as client:+ response = await client.post(+ f"{BASE_URL}/auth/keys",+ json={+ "code": code,+ "code_verifier": verifier,+ "code_challenge_method": "S256",+ },+ )+ response.raise_for_status()+ key = response.json().get("key")+ if not isinstance(key, str) or not key.startswith("sk-or-"):+ raise ValueError("Invalid key response")+ # /models is public and cannot establish that a credential is valid.+ check = await client.get(+ f"{BASE_URL}/auth/key", headers={"Authorization": f"Bearer {key}"}+ )+ check.raise_for_status()+ return key+++class OpenRouterAuth:+ """One sidecar's login state, accessed only on its asyncio event loop."""++ def __init__(self, secrets: Any, on_changed: Callable[[], None] = lambda: None):+ self.secrets = secrets+ self.on_changed = on_changed+ self.attempt_id: str | None = None+ self.verifier: str | None = None+ self.authorize_url: str | None = None+ self.error: str | None = None+ self.server: asyncio.Server | None = None+ self.timer: asyncio.TimerHandle | None = None+ self.exchanging = False++ def status(self) -> dict[str, Any]:+ profile = self.secrets.get("provider:openrouter") or {}+ return {+ "connected": bool((self.secrets.get(PROFILE) or {}).get("api_key")),+ "active": profile.get("auth_method") == "account"+ and bool(profile.get("account_connected")),+ "authorizing": self.attempt_id is not None,+ "attempt_id": self.attempt_id,+ "authorize_url": self.authorize_url,+ "error": self.error,+ }++ def cancel(self) -> dict[str, Any]:+ self.attempt_id = self.verifier = self.authorize_url = None+ self.exchanging = False+ if self.server:+ self.server.close()+ self.server = None+ if self.timer:+ self.timer.cancel()+ self.timer = None+ return self.status()++ def _expire(self) -> None:+ self.cancel()+ self.error = "Sign-in expired. Please try again."++ async def start(self, manual: bool = False) -> dict[str, Any]:+ self.cancel()+ self.error = None+ self.attempt_id = secrets.token_urlsafe(24)+ attempt = self.attempt_id+ self.verifier = secrets.token_urlsafe(64)+ challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(self.verifier.encode()).digest())+ .rstrip(b"=")+ .decode()+ )+ params = {"code_challenge": challenge, "code_challenge_method": "S256"}+ try:+ if manual:+ params["key_label"] = "OpenWorker"+ else:+ path = f"/callback/{attempt}"+ server = await asyncio.start_server(+ lambda reader, writer: self._callback(+ reader, writer, attempt, path+ ),+ "127.0.0.1",+ 0,+ )+ if attempt != self.attempt_id:+ server.close()+ return self.status()+ self.server = server+ port = self.server.sockets[0].getsockname()[1]+ params["callback_url"] = f"http://127.0.0.1:{port}{path}"+ self.authorize_url = "https://openrouter.ai/auth?" + urlencode(params)+ self.timer = asyncio.get_running_loop().call_later(600, self._expire)+ except Exception:+ if attempt == self.attempt_id:+ self.cancel()+ self.error = "Could not start sign-in. Try the manual code option."+ return self.status()++ async def _callback(+ self,+ reader: asyncio.StreamReader,+ writer: asyncio.StreamWriter,+ attempt: str,+ path: str,+ ) -> None:+ status, message = "400 Bad Request", "Invalid callback."+ try:+ line = (await asyncio.wait_for(reader.readline(), 5)).decode("ascii")+ method, target, _ = line.split()+ parsed = urlsplit(target)+ if method == "GET" and parsed.path == path and attempt == self.attempt_id:+ query = parse_qs(parsed.query)+ code = query.get("code", [""])[0]+ if code:+ result = await self.complete(code, attempt)+ status = "200 OK" if not result["error"] else "400 Bad Request"+ message = "Return to OpenWorker to see your connection status."+ elif query.get("error"):+ self.cancel()+ self.error = (+ "OpenRouter authorization was declined. Please try again."+ )+ message = "Authorization declined. Return to OpenWorker."+ except (ValueError, UnicodeError, asyncio.TimeoutError):+ pass+ finally:+ body = message.encode()+ writer.write(+ f"HTTP/1.1 {status}\r\nContent-Type: text/plain\r\nCache-Control: no-store\r\nConnection: close\r\nContent-Length: {len(body)}\r\n\r\n".encode()+ + body+ )+ try:+ await writer.drain()+ except ConnectionError:+ pass+ writer.close()++ async def complete(self, code: Any, attempt_id: Any) -> dict[str, Any]:+ if (+ not attempt_id+ or attempt_id != self.attempt_id+ or self.exchanging+ or not self.verifier+ ):+ return {+ **self.status(),+ "error": "This sign-in attempt is no longer available.",+ }+ if not isinstance(code, str) or not code.strip() or len(code) > 4096:+ return {**self.status(), "error": "Enter a valid authorization code."}+ self.exchanging = True+ try:+ key = await exchange_key(code.strip(), self.verifier)+ if attempt_id != self.attempt_id:+ return self.status()+ self.secrets.put(PROFILE, {"api_key": key})+ profile = dict(self.secrets.get("provider:openrouter") or {})+ profile.update(auth_method="account", account_connected=True)+ self.secrets.put("provider:openrouter", profile)+ self.cancel()+ self.on_changed()+ except Exception:+ if attempt_id == self.attempt_id:+ self.cancel()+ self.error = "OpenRouter sign-in failed. The code may have expired; please try again."+ return self.status()++ def disconnect(self) -> dict[str, Any]:+ self.cancel()+ self.error = None+ self.secrets.delete(PROFILE)+ profile = dict(self.secrets.get("provider:openrouter") or {})+ profile["account_connected"] = False+ self.secrets.put("provider:openrouter", profile)+ self.on_changed()+ return self.status()diff --git a/coworker/providers/registry.py b/coworker/providers/registry.pyindex 397efee1..77744693 100644--- a/coworker/providers/registry.py+++ b/coworker/providers/registry.py@@ -210,6 +210,16 @@ def _openai_compat(vendor: str, default_base_url: str, env_key: Optional[str] ="""def build(profile: dict[str, Any], secrets: Any) -> ProviderClient:+ if vendor == "OpenRouter" and profile.get("auth_method") == "account":+ account = (secrets.get("provider:openrouter-account") or {}) if secrets else {}+ if not profile.get("account_connected") or not account.get("api_key"):+ raise RuntimeError(+ "OpenRouter account disconnected — sign in or explicitly save an API key."+ )+ # Browser credentials must never be sent to a custom gateway.+ return OpenAIProvider(+ api_key=account["api_key"], base_url="https://openrouter.ai/api/v1"+ )base_url = ((profile or {}).get("base_url") or "").strip() or default_base_urlapi_key = ((profile or {}).get("api_key") or "").strip() or (os.environ.get(env_key, "").strip() if env_key else ""@@ -717,6 +727,8 @@ def descriptor_configured(d: ProviderDescriptor, profile: dict[str, Any]) -> booa stored or env key. Multi-field cloud providers (no `api_key` field, e.g. Bedrock):every required field present — their actual credentials may be ambient (~/.aws, ADC)."""+ if d.name == "openrouter" and profile.get("auth_method") == "account":+ return bool(profile.get("account_connected"))if d.auth == "oauth":# A stored token set = signed in (the tokens live in the same profile).return bool((profile or {}).get("tokens"))diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 457c0811..5def79f9 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -169,6 +169,22 @@ from .manager import SessionManagerdef create_app(manager: SessionManager) -> FastAPI:+ from ..providers.openrouter_auth import OpenRouterAuth++ def openrouter_changed() -> None:+ manager._refresh_provider("openrouter")+ if manager._provider_configured("openrouter"):+ from ..providers.registry import get_descriptor++ model = get_descriptor("openrouter").recommended_model+ if model:+ qualified = f"openrouter:{model}"+ manager.add_model(qualified)+ if not manager._provider_configured(manager._model_provider(manager.model)):+ manager.set_default_model(qualified)++ openrouter_auth = OpenRouterAuth(manager.secrets, openrouter_changed)+@asynccontextmanagerasync def lifespan(_app: FastAPI):try:@@ -182,6 +198,7 @@ def create_app(manager: SessionManager) -> FastAPI:traceback.print_exc()yield+ openrouter_auth.cancel()await manager.aclose() # stop gateway + close MCP connections on shutdownapp = FastAPI(title="coworker", version="0.0.0", lifespan=lifespan)@@ -213,6 +230,10 @@ def create_app(manager: SessionManager) -> FastAPI:@app.middleware("http")async def require_sidecar_token(request: Request, call_next):+ if request.url.path.startswith("/v1/providers/openrouter/") and not _origin_allowed(+ request.headers.get("origin")+ ):+ return JSONResponse({"error": "origin not allowed"}, status_code=403)# Preflights carry the requested header name, not its value. CORS checks the# Origin; the actual state-changing request still must authenticate.if (@@ -1824,15 +1845,21 @@ def create_app(manager: SessionManager) -> FastAPI:return manager.get_providers()@app.post("/v1/providers")- def providers_set(body: dict) -> dict[str, Any]:+ async def providers_set(body: dict) -> dict[str, Any]:name = (body or {}).get("name", "")if not name:return {"ok": False, "error": "name required"}- return manager.set_provider(name, (body or {}).get("fields"))+ if name == "openrouter":+ openrouter_auth.cancel()+ return manager.set_provider(name, (body or {}).get("fields"))+ return await asyncio.to_thread(manager.set_provider, name, (body or {}).get("fields"))@app.delete("/v1/providers/{name}")- def providers_remove(name: str) -> dict[str, Any]:- return manager.remove_provider(name)+ async def providers_remove(name: str) -> dict[str, Any]:+ if name == "openrouter":+ openrouter_auth.cancel()+ return manager.remove_provider(name)+ return await asyncio.to_thread(manager.remove_provider, name)@app.post("/v1/providers/verify")async def providers_verify(body: dict) -> dict[str, Any]:@@ -1852,6 +1879,26 @@ def create_app(manager: SessionManager) -> FastAPI:asyncio.create_task(manager.codex_signin())return {"ok": True, "started": True}+ @app.get("/v1/providers/openrouter/status")+ async def openrouter_status():+ return openrouter_auth.status()++ @app.post("/v1/providers/openrouter/signin")+ async def openrouter_signin(body: dict):+ return await openrouter_auth.start(manual=body.get("manual") is True)++ @app.post("/v1/providers/openrouter/complete")+ async def openrouter_complete(body: dict):+ return await openrouter_auth.complete(body.get("code"), body.get("attempt_id"))++ @app.post("/v1/providers/openrouter/cancel")+ async def openrouter_cancel():+ return openrouter_auth.cancel()++ @app.post("/v1/providers/openrouter/disconnect")+ async def openrouter_disconnect():+ return openrouter_auth.disconnect()+@app.get("/v1/providers/openai-codex/status")def codex_status() -> dict[str, Any]:return manager.codex_status()diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 130ede1f..08a5c040 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -2894,6 +2894,10 @@ class SessionManager:d.name),}+ if d.name == "openrouter":+ row["api_key_configured"] = bool(+ profile.get("api_key") or os.environ.get("OPENROUTER_API_KEY")+ )if d.auth == "oauth":# Sign-in state instead of key state; the token values themselves# never leave the SecretStore.@@ -3008,7 +3012,10 @@ class SessionManager:profile[f.key] = valelif not f.required:profile.pop(f.key, None)- missing = [f.label for f in d.fields if f.required and not profile.get(f.key)]+ missing = [+ f.label for f in d.fields if f.required and not profile.get(f.key)+ and not (name == "openrouter" and f.key == "api_key" and os.environ.get("OPENROUTER_API_KEY"))+ ]if missing:return {"ok": False, "error": "missing: " + ", ".join(missing)}# A (re)pasted key stamps its save date — Settings shows "key added <date>" so stale@@ -3017,6 +3024,8 @@ class SessionManager:from datetime import dateprofile["key_set_at"] = date.today().isoformat()+ if name == "openrouter" and "api_key" in fields:+ profile["auth_method"] = "api_key"self.secrets.put(f"provider:{name}", profile)self._refresh_provider(name)# Convenience: if the provider recommends a model and it's actually available, add it to@@ -3041,7 +3050,14 @@ class SessionManager:d = get_descriptor(name)if d is None:return {"ok": False, "error": f"unknown provider: {name}"}- self.secrets.delete(f"provider:{name}")+ if name == "openrouter":+ profile = self.secrets.get("provider:openrouter") or {}+ self.secrets.put("provider:openrouter", {+ key: value for key, value in profile.items()+ if key in {"auth_method", "account_connected"}+ })+ else:+ self.secrets.delete(f"provider:{name}")self._refresh_provider(name)return {"ok": True, "provider": name}diff --git a/surfaces/gui/e2e/openrouter-signin.spec.ts b/surfaces/gui/e2e/openrouter-signin.spec.tsnew file mode 100644index 00000000..721847b0--- /dev/null+++ b/surfaces/gui/e2e/openrouter-signin.spec.ts@@ -0,0 +1,107 @@+import { expect, type Page } from "@playwright/test";+import { test } from "./fixtures";++async function mockOpenRouter(page: Page) {+ let connected = false;+ let authorizing = false;+ await page.addInitScript(() => {+ window.open = () => null;+ });+ await page.route("**/v1/providers", (route) =>+ route.fulfill({+ json: [+ {+ name: "openrouter",+ title: "OpenRouter",+ needs_key: true,+ configured: connected,+ values: {},+ suggested_models: [],+ recommended_model: null,+ fields: [+ {+ key: "api_key",+ label: "API key",+ secret: true,+ required: true,+ help: "",+ placeholder: "sk-or-…",+ },+ ],+ },+ ],+ }),+ );+ await page.route("**/v1/providers/openrouter/**", async (route) => {+ const action = new URL(route.request().url()).pathname.split("/").pop();+ if (action === "signin") {+ expect(route.request().postDataJSON()).toEqual({ manual: true });+ authorizing = true;+ } else if (action === "complete") {+ expect(route.request().postDataJSON()).toEqual({+ code: "test-authorization-code",+ attempt_id: "attempt-1",+ });+ connected = true;+ authorizing = false;+ } else if (action === "disconnect") {+ connected = false;+ authorizing = false;+ }+ await route.fulfill({+ json: {+ connected,+ active: connected,+ authorizing,+ error: null,+ attempt_id: authorizing ? "attempt-1" : null,+ authorize_url: authorizing+ ? "https://openrouter.ai/auth?code_challenge=test&key_label=OpenWorker"+ : null,+ },+ });+ });+}++for (const surface of ["settings", "onboarding"] as const) {+ test(`${surface}: OpenRouter API key precedes account login, manual login and disconnect work`, async ({+ page,+ }) => {+ await mockOpenRouter(page);+ await page.goto("/");+ await page.getByTestId("account-row").click();+ await page.getByRole("button", { name: "Settings", exact: true }).click();+ if (surface === "settings") {+ await page.getByRole("button", { name: "Models", exact: true }).click();+ } else {+ await page.getByRole("button", { name: "Run setup again" }).click();+ }+ const prefix = surface === "settings" ? "set" : "ob";+ await page.getByTestId(`${prefix}-provider-openrouter`).click();+ const key = page.getByTestId(`${prefix}-field-api_key`);+ const signIn = page.getByTestId(`${prefix}-openrouter-signin`);+ await expect(key).toBeVisible();+ await expect(signIn).toBeVisible();+ const keyBox = await key.boundingBox();+ const signInBox = await signIn.boundingBox();+ expect(keyBox!.y + keyBox!.height).toBeLessThan(signInBox!.y);+ await page+ .getByRole("button", { name: "Use a manual code", exact: true })+ .click();+ await page+ .getByLabel("Authorization code", { exact: true })+ .fill("test-authorization-code");+ await page.getByRole("button", { name: "Connect", exact: true }).click();+ await expect(+ page.getByTestId(`${prefix}-openrouter-connected`),+ ).toContainText("account credentials active");+ await expect(key).toHaveValue("");+ await page+ .getByRole("button", { name: "Disconnect account", exact: true })+ .click();+ await expect(+ page.getByTestId(`${prefix}-openrouter-connected`),+ ).toHaveCount(0);+ await expect(signIn).toBeEnabled();+ });+}diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex d87322d3..0651166c 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -1809,6 +1809,7 @@ export interface ProviderField {}export interface ProviderInfo {+ api_key_configured?: boolean;name: string;title: string;needs_key: boolean;@@ -1829,6 +1830,26 @@ export interface ProviderInfo {}// -- ChatGPT-subscription provider sign-in (OAuth; tokens never reach the GUI) ------+export interface OpenRouterAuthStatus {+ connected: boolean;+ active: boolean;+ authorizing: boolean;+ attempt_id: string | null;+ authorize_url: string | null;+ error: string | null;+}++export async function openRouterAuth(+ action: "status" | "signin" | "complete" | "cancel" | "disconnect",+ body: Record<string, unknown> = {},+): Promise<OpenRouterAuthStatus> {+ const response = await fetch(`${httpBase()}/v1/providers/openrouter/${action}`, action === "status" ? undefined : {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),+ });+ if (!response.ok) throw new Error("OpenRouter authentication request failed");+ return response.json();+}+export interface CodexAuthStatus {signed_in: boolean;account?: string | null;diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 25cbc260..e45ae97c 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -1,4 +1,20 @@{+ "openrouter": {+ "title": "Or connect your OpenRouter account",+ "note": "Uses your OpenRouter credits. Signing in selects account billing; testing and saving an API key selects that key instead.",+ "signin": "Sign in with OpenRouter",+ "manual": "Use a manual code",+ "waiting": "Complete sign-in in your browser.",+ "reopen": "Reopen browser",+ "cancel": "Cancel",+ "code": "Authorization code",+ "connect": "Connect",+ "active": "Connected · account credentials active",+ "saved": "Account saved · API key active",+ "disconnect": "Disconnect account",+ "manage": "Manage or revoke keys on OpenRouter",+ "unreachable": "Could not complete the request. Check the connection and try again."+ },"boot": {"starting": "Starting OpenWorker…","restoring": "Restoring your session…"diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 65c3389d..ea236de4 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -1,4 +1,20 @@{+ "openrouter": {+ "title": "或连接您的 OpenRouter 账户",+ "note": "使用您的 OpenRouter 额度。登录后使用账户凭据;测试并保存 API 密钥后改用该密钥。",+ "signin": "使用 OpenRouter 登录",+ "manual": "手动输入授权码",+ "waiting": "请在浏览器中完成登录。",+ "reopen": "重新打开浏览器",+ "cancel": "取消",+ "code": "授权码",+ "connect": "连接",+ "active": "已连接 · 正在使用账户凭据",+ "saved": "账户已保存 · 正在使用 API 密钥",+ "disconnect": "断开账户连接",+ "manage": "在 OpenRouter 管理或撤销密钥",+ "unreachable": "无法完成请求。请检查连接后重试。"+ },"boot": {"starting": "正在启动 OpenWorker…","restoring": "正在恢复你的会话…"diff --git a/surfaces/gui/src/providers/OpenRouterSignIn.test.tsx b/surfaces/gui/src/providers/OpenRouterSignIn.test.tsxnew file mode 100644index 00000000..34a1b2fa--- /dev/null+++ b/surfaces/gui/src/providers/OpenRouterSignIn.test.tsx@@ -0,0 +1,253 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { openRouterAuth, type OpenRouterAuthStatus } from "../api";+import { openExternal } from "../tauri";+import { OpenRouterSignIn } from "./OpenRouterSignIn";+import { ProviderForm, type ProviderSetupState } from "./ProviderSetup";++vi.mock("../api", () => ({ openRouterAuth: vi.fn() }));+vi.mock("../tauri", () => ({ openExternal: vi.fn() }));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: translate }) }));+const translate = (key: string) => key;++const idle: OpenRouterAuthStatus = {+ connected: false,+ active: false,+ authorizing: false,+ attempt_id: null,+ authorize_url: null,+ error: null,+};+const pending: OpenRouterAuthStatus = {+ ...idle,+ authorizing: true,+ attempt_id: "attempt-1",+ authorize_url: "https://openrouter.ai/auth?code_challenge=test",+};+const connected: OpenRouterAuthStatus = {+ ...idle,+ connected: true,+ active: true,+};++beforeEach(() => {+ vi.resetAllMocks();+ vi.mocked(openRouterAuth).mockResolvedValue(idle);+});+afterEach(cleanup);++it("places account sign-in below the API key in the shared provider form", async () => {+ const info = {+ name: "openrouter",+ title: "OpenRouter",+ needs_key: true,+ configured: false,+ values: {},+ suggested_models: [],+ recommended_model: null,+ fields: [+ {+ key: "api_key",+ label: "API key",+ secret: true,+ required: true,+ help: "",+ placeholder: "sk-or-…",+ },+ ],+ };+ const ps: ProviderSetupState = {+ providers: [info],+ ordered: [info],+ info,+ sel: "openrouter",+ fields: {},+ refreshProviders: async () => {},+ setFieldValue: vi.fn(),+ dirty: false,+ verify: { state: "idle" },+ showEndpoint: false,+ setShowEndpoint: vi.fn(),+ keylessOk: new Set(),+ credentialed: false,+ savedState: false,+ secretFilled: false,+ openProvider: vi.fn(),+ backToGallery: vi.fn(),+ runTestAndSave: async () => true,+ removeKey: async () => {},+ cancelBackTimer: vi.fn(),+ statusFor: () => null,+ saveField: async () => {},+ fieldSaved: null,+ };+ render(<ProviderForm ps={ps} tp="shared" />);+ const key = screen.getByTestId("shared-field-api_key");+ const signIn = screen.getByTestId("shared-openrouter-signin");+ expect(+ key.compareDocumentPosition(signIn) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ await waitFor(() => expect(openRouterAuth).toHaveBeenCalledWith("status"));+});++it("opens browser login, allows reopening, and cancels the pending attempt", async () => {+ vi.mocked(openRouterAuth).mockImplementation(async (action) =>+ action === "signin" ? pending : idle,+ );+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ await waitFor(() => expect(openRouterAuth).toHaveBeenCalledWith("status"));+ fireEvent.click(screen.getByTestId("test-openrouter-signin"));+ await screen.findByRole("status");+ expect(openRouterAuth).toHaveBeenCalledWith("signin", { manual: false });+ expect(openExternal).toHaveBeenCalledWith(pending.authorize_url);+ fireEvent.click(screen.getByText("openrouter.reopen"));+ expect(openExternal).toHaveBeenCalledTimes(2);+ fireEvent.click(screen.getByText("openrouter.cancel"));+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());+ expect(openRouterAuth).toHaveBeenCalledWith(+ "cancel",+ expect.objectContaining({ attempt_id: "attempt-1" }),+ );+});++it("does not let an older status response replace a newly started login", async () => {+ let resolveStatus!: (status: OpenRouterAuthStatus) => void;+ const oldStatus = new Promise<OpenRouterAuthStatus>((resolve) => {+ resolveStatus = resolve;+ });+ vi.mocked(openRouterAuth).mockImplementation((action) =>+ action === "status" ? oldStatus : Promise.resolve(pending),+ );+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ fireEvent.click(screen.getByTestId("test-openrouter-signin"));+ await screen.findByRole("status");+ await act(async () => {+ resolveStatus(idle);+ await oldStatus;+ });+ expect(screen.getByRole("status")).toBeTruthy();+});++it("restores manual code entry when reopening an active manual login", async () => {+ vi.mocked(openRouterAuth).mockResolvedValue({+ ...pending,+ authorize_url:+ "https://openrouter.ai/auth?code_challenge=test&key_label=OpenWorker",+ });+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ await screen.findByRole("status");+ expect(screen.getByLabelText("openrouter.code")).toBeTruthy();+});++it("ignores a poll started during an action when it resolves after that action", async () => {+ vi.useFakeTimers();+ let finishAction!: (status: OpenRouterAuthStatus) => void;+ let finishPoll!: (status: OpenRouterAuthStatus) => void;+ const actionResponse = new Promise<OpenRouterAuthStatus>((resolve) => {+ finishAction = resolve;+ });+ const stalePoll = new Promise<OpenRouterAuthStatus>((resolve) => {+ finishPoll = resolve;+ });+ let polls = 0;+ vi.mocked(openRouterAuth).mockImplementation((action) => {+ if (action === "status")+ return ++polls === 1 ? Promise.resolve(idle) : stalePoll;+ return actionResponse;+ });+ try {+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ await act(async () => {});+ fireEvent.click(screen.getByTestId("test-openrouter-signin"));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ await act(async () => {+ finishAction(pending);+ await actionResponse;+ });+ expect(screen.getByRole("status")).toBeTruthy();+ await act(async () => {+ finishPoll(idle);+ await stalePoll;+ });+ expect(screen.getByRole("status")).toBeTruthy();+ } finally {+ cleanup();+ vi.useRealTimers();+ }+});++it("submits a manual code bound to its attempt and shows connected state", async () => {+ vi.mocked(openRouterAuth).mockImplementation(async (action) => {+ if (action === "signin") return pending;+ if (action === "complete") return connected;+ return idle;+ });+ const changed = vi.fn(async () => {});+ render(<OpenRouterSignIn tp="test" onChanged={changed} />);+ fireEvent.click(screen.getByText("openrouter.manual"));+ const input = await screen.findByLabelText("openrouter.code");+ expect(openRouterAuth).toHaveBeenCalledWith("signin", { manual: true });+ expect(+ (screen.getByText("openrouter.connect") as HTMLButtonElement).disabled,+ ).toBe(true);+ fireEvent.change(input, { target: { value: "returned-code" } });+ fireEvent.click(screen.getByText("openrouter.connect"));+ await screen.findByTestId("test-openrouter-connected");+ expect(openRouterAuth).toHaveBeenCalledWith("complete", {+ code: "returned-code",+ attempt_id: "attempt-1",+ });+ expect(screen.getByText("openrouter.active")).toBeTruthy();+ expect(changed).toHaveBeenCalled();+});++it("shows provider errors and permits retry", async () => {+ vi.mocked(openRouterAuth).mockImplementation(async (action) =>+ action === "signin" ? { ...idle, error: "Code expired. Try again." } : idle,+ );+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ fireEvent.click(screen.getByTestId("test-openrouter-signin"));+ expect((await screen.findByRole("alert")).textContent).toBe(+ "Code expired. Try again.",+ );+ expect(+ (screen.getByTestId("test-openrouter-signin") as HTMLButtonElement)+ .disabled,+ ).toBe(false);+});++it("shows a safe connection error when a request fails", async () => {+ vi.mocked(openRouterAuth).mockImplementation(async (action) => {+ if (action === "signin") throw new Error("private server response");+ return idle;+ });+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ fireEvent.click(screen.getByTestId("test-openrouter-signin"));+ expect((await screen.findByRole("alert")).textContent).toBe(+ "openrouter.unreachable",+ );+});++it("disconnects an existing account and links to remote key management", async () => {+ vi.mocked(openRouterAuth).mockImplementation(async (action) =>+ action === "status" ? connected : idle,+ );+ render(<OpenRouterSignIn tp="test" onChanged={vi.fn(async () => {})} />);+ await screen.findByTestId("test-openrouter-connected");+ fireEvent.click(screen.getByText("openrouter.manage"));+ expect(openExternal).toHaveBeenCalledWith("https://openrouter.ai/keys");+ fireEvent.click(screen.getByText("openrouter.disconnect"));+ await waitFor(() =>+ expect(screen.queryByTestId("test-openrouter-connected")).toBeNull(),+ );+ expect(openRouterAuth).toHaveBeenCalledWith("disconnect", expect.any(Object));+});diff --git a/surfaces/gui/src/providers/OpenRouterSignIn.tsx b/surfaces/gui/src/providers/OpenRouterSignIn.tsxnew file mode 100644index 00000000..cbb4f66e--- /dev/null+++ b/surfaces/gui/src/providers/OpenRouterSignIn.tsx@@ -0,0 +1,198 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { openExternal } from "../tauri";+import { openRouterAuth, type OpenRouterAuthStatus } from "../api";++export function OpenRouterSignIn({+ tp,+ onChanged,+}: {+ tp: string;+ onChanged: () => Promise<void>;+}) {+ const { t } = useTranslation();+ const [status, setStatus] = useState<OpenRouterAuthStatus | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const [code, setCode] = useState("");+ const generation = useRef(0);+ const acting = useRef(false);+ const mounted = useRef(true);+ const manual =+ !!status?.authorize_url &&+ !new URL(status.authorize_url).searchParams.has("callback_url");++ useEffect(() => {+ let alive = true;+ mounted.current = true;+ let timer: ReturnType<typeof setTimeout>;+ const poll = async () => {+ const version = generation.current;+ try {+ const next = await openRouterAuth("status");+ if (alive && version === generation.current && !acting.current) {+ setStatus(next);+ setError("");+ }+ } catch {+ if (alive && version === generation.current && !acting.current)+ setError(t("openrouter.unreachable"));+ }+ if (alive) timer = setTimeout(poll, 2000);+ };+ void poll();+ return () => {+ alive = false;+ mounted.current = false;+ clearTimeout(timer);+ };+ }, [t]);++ useEffect(() => {+ if (status && !status.authorizing) void onChanged();+ }, [status?.connected, status?.active, status?.authorizing]);++ const action = async (+ name: "signin" | "complete" | "cancel" | "disconnect",+ useManual = false,+ ) => {+ const version = ++generation.current;+ acting.current = true;+ setBusy(true);+ setError("");+ try {+ const next = await openRouterAuth(+ name,+ name === "signin"+ ? { manual: useManual }+ : {+ code,+ attempt_id: status?.attempt_id,+ },+ );+ if (!mounted.current || version !== generation.current) return;+ setStatus(next);+ if (name === "signin") {+ setCode("");+ if (next.authorize_url) await openExternal(next.authorize_url);+ }+ if (!next.authorizing) await onChanged();+ } catch {+ if (mounted.current && version === generation.current)+ setError(t("openrouter.unreachable"));+ } finally {+ if (version === generation.current) {+ // Also invalidate polls started while the action was awaiting its response.+ generation.current++;+ acting.current = false;+ if (mounted.current) setBusy(false);+ }+ }+ };+ const button =+ "rounded-lg border border-line px-3 py-2 text-[13px] text-ink hover:border-lineStrong disabled:opacity-40";+ return (+ <section+ className="mt-4 border-t border-line pt-4"+ aria-label={t("openrouter.title")}+ >+ <p className="text-[13px] font-medium text-ink">+ {t("openrouter.title")}+ </p>+ <p className="text-[12px] text-faint mt-1 mb-3">{t("openrouter.note")}</p>+ {status?.connected && (+ <p+ className="text-[12px] text-ok mb-2"+ data-testid={`${tp}-openrouter-connected`}+ >+ {t(status.active ? "openrouter.active" : "openrouter.saved")}+ </p>+ )}+ {status?.authorizing ? (+ <div className="space-y-2">+ <p role="status" className="text-[12px] text-muted">+ {t("openrouter.waiting")}+ </p>+ {status.authorize_url && (+ <button+ className={button}+ onClick={() => void openExternal(status.authorize_url!)}+ >+ {t("openrouter.reopen")}+ </button>+ )}+ <button+ className={button + " ml-2"}+ onClick={() => void action("cancel")}+ >+ {t("openrouter.cancel")}+ </button>+ {manual && (+ <div>+ <label+ className="block text-[12px] text-muted"+ htmlFor={`${tp}-openrouter-code`}+ >+ {t("openrouter.code")}+ </label>+ <input+ id={`${tp}-openrouter-code`}+ className="w-full rounded-lg border border-line bg-panel px-3 py-2 text-[13px]"+ autoComplete="off"+ value={code}+ onChange={(e) => setCode(e.target.value)}+ />+ <button+ className={button + " mt-2"}+ disabled={busy || !code.trim()}+ onClick={() => void action("complete")}+ >+ {t("openrouter.connect")}+ </button>+ </div>+ )}+ </div>+ ) : (+ <div className="flex flex-wrap gap-2">+ <button+ className="rounded-lg border border-accent bg-accent px-4 py-2 text-[13px] font-medium text-white disabled:opacity-40"+ data-testid={`${tp}-openrouter-signin`}+ disabled={busy}+ onClick={() => void action("signin")}+ >+ {t("openrouter.signin")}+ </button>+ <button+ className={button}+ disabled={busy}+ onClick={() => void action("signin", true)}+ >+ {t("openrouter.manual")}+ </button>+ {status?.connected && (+ <button+ className={button}+ disabled={busy}+ onClick={() => void action("disconnect")}+ >+ {t("openrouter.disconnect")}+ </button>+ )}+ </div>+ )}+ {status?.connected && (+ <button+ className="mt-2 text-[12px] text-muted underline"+ onClick={() => void openExternal("https://openrouter.ai/keys")}+ >+ {t("openrouter.manage")}+ </button>+ )}+ {(error || status?.error) && (+ <p role="alert" className="mt-2 text-[12px] text-warnInk">+ {error || status?.error}+ </p>+ )}+ </section>+ );+}diff --git a/surfaces/gui/src/providers/ProviderSetup.tsx b/surfaces/gui/src/providers/ProviderSetup.tsxindex 1f7559c9..68dd5c19 100644--- a/surfaces/gui/src/providers/ProviderSetup.tsx+++ b/surfaces/gui/src/providers/ProviderSetup.tsx@@ -14,6 +14,7 @@ import {} from "../api";import { openExternal } from "../tauri";import { PROVIDER_LOGOS, providerRank } from "./logos";+import { OpenRouterSignIn } from "./OpenRouterSignIn";// The provider gallery ⇄ key form, shared by Onboarding step 1 (§39) and// Settings ▸ Models (UX-021) so the two can never drift apart visually. The hook@@ -133,7 +134,7 @@ export function useProviderSetup(opts?: { onSaved?: () => void }): ProviderSetup}, []);const info = providers.find((p) => p.name === sel);- const credentialed = !!info?.configured && !!info?.needs_key;+ const credentialed = (info?.api_key_configured ?? !!info?.configured) && !!info?.needs_key;const openProvider = (name: string) => {const p = providers.find((x) => x.name === name);@@ -168,7 +169,13 @@ export function useProviderSetup(opts?: { onSaved?: () => void }): ProviderSetupsetVerify({ state: "error", msg: res.error || t("provider.err_couldnt_verify") });return false;}- if (dirty || !info?.configured) await setProvider(sel, fields).catch(() => {});+ if (dirty || !info?.configured || sel === "openrouter") {+ const saved = await setProvider(sel, fields).catch(() => ({ ok: false }));+ if (!saved.ok) {+ setVerify({ state: "error", msg: t("provider.err_unreachable") });+ return false;+ }+ }if (!info?.needs_key) setKeylessOk((s) => new Set(s).add(sel));setVerify({ state: "ok" });setDirty(false);@@ -534,6 +541,8 @@ export function ProviderForm({).map((f) => fieldRow(f, !choice && f.key === testKey))}+ {sel === "openrouter" && <OpenRouterSignIn tp={tp} onChanged={ps.refreshProviders} />}+{/* Auth-method segmented control + the selected method's panel (owner call2026-07-26): one joined track, then a soft inset card holding only thatmethod's description, fields, and its own Test & save footer. */}diff --git a/tests/test_openrouter_auth.py b/tests/test_openrouter_auth.pynew file mode 100644index 00000000..58255c1e--- /dev/null+++ b/tests/test_openrouter_auth.py@@ -0,0 +1,288 @@+"""OpenRouter account login: PKCE, isolated credentials, and stale-flow safety."""++from __future__ import annotations++import asyncio+import base64+import hashlib+import json+from urllib.parse import parse_qs, urlsplit++import httpx+import pytest++from coworker.providers import openrouter_auth+from coworker.secrets import SecretStore+++def test_manual_login_uses_pkce_and_keeps_credentials_out_of_status(+ tmp_path, monkeypatch+):+ store = SecretStore(tmp_path / "secrets.json")+ store.put("provider:openrouter", {"api_key": "manual-existing"})+ exchanged = []++ async def exchange(code, verifier):+ exchanged.append((code, verifier))+ return "account-secret"++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)+ auth = openrouter_auth.OpenRouterAuth(store)++ async def run():+ started = await auth.start(manual=True)+ assert started["authorizing"]+ assert not started["connected"]+ url = urlsplit(started["authorize_url"])+ assert url.scheme == "https" and url.netloc == "openrouter.ai"+ query = parse_qs(url.query)+ assert query["code_challenge_method"] == ["S256"]+ completed = await auth.complete("returned-code", started["attempt_id"])+ assert completed["connected"]+ assert not completed["authorizing"]+ code, verifier = exchanged[0]+ assert code == "returned-code"+ challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest())+ .rstrip(b"=")+ .decode("ascii")+ )+ assert query["code_challenge"] == [challenge]+ assert verifier not in json.dumps(started)+ assert "account-secret" not in json.dumps(completed)+ assert "account-secret" not in json.dumps(auth.status())++ asyncio.run(run())+ assert store.get("provider:openrouter-account")["api_key"] == "account-secret"+ assert store.get("provider:openrouter")["api_key"] == "manual-existing"+ assert openrouter_auth.OpenRouterAuth(store).status()["connected"]+++def test_expired_attempt_cannot_complete(tmp_path, monkeypatch):+ auth = openrouter_auth.OpenRouterAuth(SecretStore(tmp_path / "secrets.json"))++ async def exchange(code, verifier):+ raise AssertionError("Expired attempts must not exchange credentials")++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)++ async def run():+ started = await auth.start(manual=True)+ auth._expire()+ assert not auth.status()["authorizing"]+ assert "expired" in auth.status()["error"].lower()+ await auth.complete("code", started["attempt_id"])+ assert not auth.status()["connected"]++ asyncio.run(run())+++def test_cancel_during_listener_creation_closes_stale_listener(tmp_path, monkeypatch):+ auth = openrouter_auth.OpenRouterAuth(SecretStore(tmp_path / "secrets.json"))++ async def run():+ entered, release = asyncio.Event(), asyncio.Event()++ class Listener:+ closed = False++ def close(self):+ self.closed = True++ listener = Listener()++ async def bind(*args, **kwargs):+ entered.set()+ await release.wait()+ return listener++ monkeypatch.setattr(openrouter_auth.asyncio, "start_server", bind)+ pending = asyncio.create_task(auth.start())+ await entered.wait()+ auth.cancel()+ release.set()+ status = await pending+ assert listener.closed+ assert not status["authorizing"]+ assert status["authorize_url"] is None+ assert auth.server is None+ assert auth.timer is None++ asyncio.run(run())+++def test_account_uses_official_endpoint_and_ignores_other_keys(tmp_path, monkeypatch):+ from coworker.providers import registry++ store = SecretStore(tmp_path / "secrets.json")+ store.put("provider:openrouter-account", {"api_key": "account-key"})+ monkeypatch.setenv("OPENROUTER_API_KEY", "environment-key")+ monkeypatch.setattr(registry, "OpenAIProvider", lambda **kwargs: kwargs)+ builder = registry._openai_compat(+ "OpenRouter", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"+ )+ profile = {+ "auth_method": "account",+ "account_connected": True,+ "api_key": "manual-key",+ "base_url": "https://untrusted.example",+ }+ assert builder(profile, store) == {+ "api_key": "account-key",+ "base_url": "https://openrouter.ai/api/v1",+ }+ profile["account_connected"] = False+ with pytest.raises(RuntimeError, match="disconnected"):+ builder(profile, store)+++def test_cancel_during_exchange_cannot_restore_account(tmp_path, monkeypatch):+ store = SecretStore(tmp_path / "secrets.json")+ auth = openrouter_auth.OpenRouterAuth(store)++ async def run():+ entered, release = asyncio.Event(), asyncio.Event()++ async def exchange(code, verifier):+ entered.set()+ await release.wait()+ return "late-secret"++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)+ started = await auth.start(manual=True)+ pending = asyncio.create_task(auth.complete("code", started["attempt_id"]))+ await entered.wait()+ assert not auth.cancel()["authorizing"]+ release.set()+ await pending+ assert not auth.status()["connected"]++ asyncio.run(run())+ assert store.get("provider:openrouter-account") is None+++def test_replaced_attempt_cannot_complete(tmp_path, monkeypatch):+ store = SecretStore(tmp_path / "secrets.json")+ calls = []++ async def exchange(code, verifier):+ calls.append(code)+ return "new-secret"++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)+ auth = openrouter_auth.OpenRouterAuth(store)++ async def run():+ first = await auth.start(manual=True)+ second = await auth.start(manual=True)+ assert first["attempt_id"] != second["attempt_id"]+ await auth.complete("stale-code", first["attempt_id"])+ assert calls == []+ assert store.get("provider:openrouter-account") is None+ await auth.complete("current-code", second["attempt_id"])+ assert calls == ["current-code"]++ asyncio.run(run())+++def test_exchange_failure_preserves_previous_account(tmp_path, monkeypatch):+ store = SecretStore(tmp_path / "secrets.json")+ store.put("provider:openrouter-account", {"api_key": "previous-secret"})++ async def exchange(code, verifier):+ raise RuntimeError("remote response included sensitive-provider-data")++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)+ auth = openrouter_auth.OpenRouterAuth(store)++ async def run():+ started = await auth.start(manual=True)+ result = await auth.complete("code", started["attempt_id"])+ assert result["connected"]+ assert result["error"]+ assert "sensitive-provider-data" not in json.dumps(result)++ asyncio.run(run())+ assert store.get("provider:openrouter-account")["api_key"] == "previous-secret"+++def test_disconnect_only_removes_account_and_rejects_pending_completion(+ tmp_path, monkeypatch+):+ store = SecretStore(tmp_path / "secrets.json")+ store.put("provider:openrouter", {"api_key": "manual-secret"})+ store.put("provider:openrouter-account", {"api_key": "account-secret"})+ auth = openrouter_auth.OpenRouterAuth(store)++ async def exchange(code, verifier):+ raise AssertionError("Disconnected attempts must not exchange credentials")++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)++ async def run():+ started = await auth.start(manual=True)+ result = auth.disconnect()+ assert not result["connected"] and not result["authorizing"]+ await auth.complete("old-code", started["attempt_id"])++ asyncio.run(run())+ assert store.get("provider:openrouter-account") is None+ assert store.get("provider:openrouter")["api_key"] == "manual-secret"+++def test_exchange_validates_key_with_authenticated_endpoint(monkeypatch):+ requests = []++ def respond(request):+ requests.append(request)+ if request.method == "POST":+ return httpx.Response(200, json={"key": "sk-or-test-secret"})+ return httpx.Response(200, json={"data": {"label": "OpenWorker"}})++ client = httpx.AsyncClient(transport=httpx.MockTransport(respond))+ monkeypatch.setattr(openrouter_auth.httpx, "AsyncClient", lambda **kwargs: client)+ assert (+ asyncio.run(openrouter_auth.exchange_key("code", "verifier"))+ == "sk-or-test-secret"+ )+ assert len(requests) == 2+ assert str(requests[0].url) == "https://openrouter.ai/api/v1/auth/keys"+ assert json.loads(requests[0].content) == {+ "code": "code",+ "code_verifier": "verifier",+ "code_challenge_method": "S256",+ }+ assert str(requests[1].url) == "https://openrouter.ai/api/v1/auth/key"+ assert requests[1].headers["authorization"] == "Bearer sk-or-test-secret"+++def test_loopback_callback_requires_attempt_specific_path(tmp_path, monkeypatch):+ store = SecretStore(tmp_path / "secrets.json")+ auth = openrouter_auth.OpenRouterAuth(store)+ codes = []++ async def exchange(code, verifier):+ codes.append(code)+ return "sk-or-callback-secret"++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)++ async def run():+ started = await auth.start()+ callback = parse_qs(urlsplit(started["authorize_url"]).query)["callback_url"][0]+ address = urlsplit(callback)+ assert address.hostname in {"127.0.0.1", "localhost"}+ try:+ async with httpx.AsyncClient() as client:+ wrong = await client.get(f"http://{address.netloc}/wrong?code=bad")+ assert wrong.status_code == 400+ assert codes == []+ correct = await client.get(callback, params={"code": "valid-code"})+ assert correct.status_code == 200+ assert "sk-or-callback-secret" not in correct.text+ assert codes == ["valid-code"]+ assert auth.status()["connected"]+ finally:+ auth.cancel()++ asyncio.run(run())diff --git a/tests/test_openrouter_routes.py b/tests/test_openrouter_routes.pynew file mode 100644index 00000000..059872d9--- /dev/null+++ b/tests/test_openrouter_routes.py@@ -0,0 +1,82 @@+"""Provider account login through the real sidecar routes and credential resolver."""++from fastapi.testclient import TestClient++from coworker.providers import openrouter_auth+from coworker.server import SessionManager, create_app+++def test_account_login_switching_and_disconnect(tmp_path, monkeypatch):+ async def exchange(code, verifier):+ assert code == "valid-code"+ return "sk-or-account-secret"++ monkeypatch.setattr(openrouter_auth, "exchange_key", exchange)+ manager = SessionManager(workspace=tmp_path)+ manager.secrets.put("provider:openrouter", {"api_key": "sk-or-manual"})+ client = TestClient(create_app(manager))+ with client:+ start = client.post(+ "/v1/providers/openrouter/signin", json={"manual": True}+ ).json()+ done = client.post(+ "/v1/providers/openrouter/complete",+ json={+ "code": "valid-code",+ "attempt_id": start["attempt_id"],+ },+ ).json()+ assert done["active"] and done["connected"]+ rows = client.get("/v1/providers").json()+ row = next(row for row in rows if row["name"] == "openrouter")+ assert row["configured"] and row["api_key_configured"]+ assert "sk-or-" not in str(rows)+ assert manager._provider_configured("openrouter")++ # Explicitly saving the existing manual key switches billing methods.+ saved = client.post(+ "/v1/providers", json={"name": "openrouter", "fields": {"api_key": ""}}+ ).json()+ assert saved["ok"]+ status = client.get("/v1/providers/openrouter/status").json()+ assert status["connected"] and not status["active"]++ start = client.post(+ "/v1/providers/openrouter/signin", json={"manual": True}+ ).json()+ client.post(+ "/v1/providers/openrouter/complete",+ json={"code": "valid-code", "attempt_id": start["attempt_id"]},+ )+ client.delete("/v1/providers/openrouter")+ assert client.get("/v1/providers/openrouter/status").json()["active"]+ assert not (manager.secrets.get("provider:openrouter") or {}).get("api_key")+ disconnected = client.post("/v1/providers/openrouter/disconnect").json()+ assert not disconnected["connected"]+ assert not manager._provider_configured("openrouter")+++def test_routes_reject_invalid_input_and_cancel_pending_login(tmp_path):+ manager = SessionManager(workspace=tmp_path)+ with TestClient(create_app(manager)) as client:+ assert (+ client.post("/v1/providers/openrouter/signin", json=[]).status_code == 422+ )+ started = client.post(+ "/v1/providers/openrouter/signin", json={"manual": True}+ ).json()+ assert started["authorizing"]+ assert not client.post("/v1/providers/openrouter/cancel").json()["authorizing"]+ result = client.post(+ "/v1/providers/openrouter/complete",+ json={"code": "old", "attempt_id": started["attempt_id"]},+ ).json()+ assert result["error"] and not result["connected"]+ assert (+ client.post(+ "/v1/providers/openrouter/signin",+ json={},+ headers={"Origin": "https://evil.example"},+ ).status_code+ == 403+ )