Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

Release v3.8.22 (#3623)

Diego Rodrigues de Sa e Souza9350a5d6c648
diff --git a/.env.example b/.env.example
index 0be8cec9d4..df5703dd70 100644
--- a/.env.example
+++ b/.env.example
@@ -292,6 +292,12 @@ ALLOW_API_KEY_REVEAL=false
# Default: 5000 | Minimum: 1000
# OMNIROUTE_PAYLOAD_RULES_RELOAD_MS=5000
+# Prefer Claude Code OAuth for unprefixed Claude-family model IDs such as
+# claude-sonnet-4-6 or newly released IDs like claude-fable-5.
+# Used by: open-sse/services/model.ts. Explicit provider prefixes still win.
+# Default: false
+# OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS=false
+
# ═══════════════════════════════════════════════════════════════════════════════
# 7. URLS & CLOUD SYNC
# ═══════════════════════════════════════════════════════════════════════════════
@@ -421,6 +427,12 @@ NEXT_PUBLIC_ENABLE_SOCKS5_PROXY=true
# CLI_QODER_BIN=qoder
# CLI_QWEN_BIN=qwen
+# Override the Hermes Agent home directory (where OmniRoute reads/writes the
+# Hermes CLI config). Matches the env var the Hermes PowerShell installer sets
+# on Windows (%LOCALAPPDATA%\hermes); defaults to ~/.hermes when unset.
+# Used by: src/lib/cli-helper/config-generator/hermesHome.ts
+# HERMES_HOME=~/.hermes
+
# ═══════════════════════════════════════════════════════════════════════════════
# 10. INTERNAL AGENT & MCP INTEGRATIONS
# ═══════════════════════════════════════════════════════════════════════════════
@@ -1519,4 +1531,3 @@ QUOTA_STORE_DRIVER=sqlite # sqlite | redis
# OpenCode-style API key (sk-...) for the regenerated opencode.json. Used by:
# scripts/ad-hoc/regen-opencode-config.ts. Falls back to OMNIROUTE_KEY.
# OPENCODE_API_KEY=
-
diff --git a/@omniroute/opencode-plugin/package.json b/@omniroute/opencode-plugin/package.json
index 8489bbd9e1..c36a77f011 100644
--- a/@omniroute/opencode-plugin/package.json
+++ b/@omniroute/opencode-plugin/package.json
@@ -26,7 +26,7 @@
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
- "test": "node --import tsx/esm --test tests/scaffold.test.ts tests/auth.test.ts tests/options-schema.test.ts tests/multi-instance.test.ts tests/fetch-interceptor.test.ts tests/provider.test.ts tests/gemini-sanitize.test.ts tests/combos.test.ts tests/config-shim.test.ts tests/features.test.ts tests/usable-combo.test.ts tests/disk-snapshot-perms.test.ts tests/fork-features.test.ts",
+ "test": "node --import tsx/esm --test tests/scaffold.test.ts tests/auth.test.ts tests/options-schema.test.ts tests/multi-instance.test.ts tests/fetch-interceptor.test.ts tests/provider.test.ts tests/gemini-sanitize.test.ts tests/combos.test.ts tests/config-shim.test.ts tests/features.test.ts tests/usable-combo.test.ts tests/disk-snapshot-perms.test.ts tests/fork-features.test.ts tests/auto-combo-context.test.ts",
"prepublishOnly": "npm run clean && npm run build && npm test"
},
"keywords": [
diff --git a/@omniroute/opencode-plugin/src/index.ts b/@omniroute/opencode-plugin/src/index.ts
index 19aaf6cf21..8ad06edfe6 100644
--- a/@omniroute/opencode-plugin/src/index.ts
+++ b/@omniroute/opencode-plugin/src/index.ts
@@ -1121,6 +1121,11 @@ export interface OmniRouteRawAutoCombo {
candidatePool?: string[];
/** Number of candidates resolved at fetch time. */
candidateCount?: number;
+ /** MAX of candidates' context windows, served by newer OmniRoute builds.
+ * Absent on older servers — mapper falls back to a safe positive default. */
+ context_length?: number;
+ /** MAX of candidates' max output tokens (same provenance as context_length). */
+ max_output_tokens?: number;
/** Whether this auto combo should be hidden from the picker. */
isHidden?: boolean;
/** Auto-combo configuration. */
@@ -1211,24 +1216,42 @@ export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher =
}
};
+/** Fallbacks when the server does not advertise auto-combo limits (older
+ * OmniRoute builds). MUST be positive: OpenCode's overflow guard treats
+ * `limit.context === 0` as "never overflow" and silently DISABLES smart
+ * auto-compaction, letting the session grow until the gateway's destructive
+ * history purge kicks in (the "agent keeps forgetting things" bug). */
+const AUTO_COMBO_FALLBACK_CONTEXT = 128_000;
+const AUTO_COMBO_FALLBACK_OUTPUT = 8_192;
+
/**
* Convert a raw auto combo into a static model entry for the OpenCode picker.
* Auto combos have tool_call=true, reasoning=true by default (they route
- * to capable models). Context/output limits are set to 0 since the actual
- * limits depend on which provider is selected at runtime.
+ * to capable models). Context/output limits come from the server (MAX of
+ * the candidate pool's windows — the gateway's context pre-filter routes
+ * oversized requests to large-window candidates); a safe positive fallback
+ * applies when the server omits them. Never 0.
*/
export function mapAutoComboToStaticEntry(
autoCombo: OmniRouteRawAutoCombo,
): OmniRouteStaticModelEntry {
const variant = autoCombo.variant;
const name = formatAutoComboName(variant, autoCombo.candidateCount);
+ const context =
+ typeof autoCombo.context_length === "number" && autoCombo.context_length > 0
+ ? autoCombo.context_length
+ : AUTO_COMBO_FALLBACK_CONTEXT;
+ const output =
+ typeof autoCombo.max_output_tokens === "number" && autoCombo.max_output_tokens > 0
+ ? autoCombo.max_output_tokens
+ : AUTO_COMBO_FALLBACK_OUTPUT;
return {
name,
attachment: false,
reasoning: true,
temperature: true,
tool_call: true,
- limit: { context: 0, output: 0 },
+ limit: { context, output },
modalities: {
input: ["text"],
output: ["text"],
diff --git a/@omniroute/opencode-plugin/tests/auto-combo-context.test.ts b/@omniroute/opencode-plugin/tests/auto-combo-context.test.ts
new file mode 100644
index 0000000000..73213dde02
--- /dev/null
+++ b/@omniroute/opencode-plugin/tests/auto-combo-context.test.ts
@@ -0,0 +1,74 @@
+/**
+ * TDD regression — auto combos must never advertise `limit.context: 0`.
+ *
+ * opencode's overflow guard (packages/opencode/src/session/overflow.ts)
+ * short-circuits when `model.limit.context === 0`:
+ *
+ * if (input.model.limit.context === 0) return false // never overflow
+ *
+ * so a zero context silently DISABLES opencode's smart auto-compaction for
+ * auto combos. The session then grows unbounded until OmniRoute's
+ * server-side purifyHistory() destructively drops old messages — the
+ * "coding agent keeps forgetting things" bug.
+ *
+ * Fix under test: mapAutoComboToStaticEntry consumes the context_length /
+ * max_output_tokens now served by GET /api/combos/auto, and falls back to a
+ * safe positive default (128000 / 8192) for older servers that do not send
+ * the fields yet.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { mapAutoComboToStaticEntry } from "../src/index.ts";
+import type { OmniRouteRawAutoCombo } from "../src/index.ts";
+
+test("uses server-provided context_length and max_output_tokens", () => {
+ const raw = {
+ id: "auto/coding",
+ name: "Auto Coding",
+ variant: "coding",
+ candidateCount: 5,
+ context_length: 1048576,
+ max_output_tokens: 65536,
+ } as OmniRouteRawAutoCombo;
+
+ const entry = mapAutoComboToStaticEntry(raw);
+ assert.equal(entry.limit?.context, 1048576);
+ assert.equal(entry.limit?.output, 65536);
+});
+
+test("falls back to a safe positive default when the server omits limits (old servers)", () => {
+ const raw = {
+ id: "auto",
+ name: "Auto",
+ candidateCount: 3,
+ } as OmniRouteRawAutoCombo;
+
+ const entry = mapAutoComboToStaticEntry(raw);
+ assert.ok(
+ typeof entry.limit?.context === "number" && entry.limit.context > 0,
+ `context must be a positive number (never 0 — zero disables opencode auto-compaction), got ${entry.limit?.context}`
+ );
+ assert.ok(
+ typeof entry.limit?.output === "number" && entry.limit.output > 0,
+ `output must be a positive number, got ${entry.limit?.output}`
+ );
+});
+
+test("ignores non-positive server values and keeps the safe fallback", () => {
+ const raw = {
+ id: "auto/fast",
+ name: "Auto Fast",
+ variant: "fast",
+ candidateCount: 2,
+ context_length: 0,
+ max_output_tokens: -1,
+ } as OmniRouteRawAutoCombo;
+
+ const entry = mapAutoComboToStaticEntry(raw);
+ assert.ok(
+ typeof entry.limit?.context === "number" && entry.limit.context > 0,
+ "zero/negative server values must not propagate"
+ );
+ assert.ok(typeof entry.limit?.output === "number" && entry.limit.output > 0);
+});
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3e24dea84..942ca20da9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,70 @@
---
+## [3.8.22] — 2026-06-11
+
+### ✨ Added
+
+- **MiMoCode free-tier provider** ([#3659] — thanks @pizzav-xyz): new no-auth provider `mimocode` (alias `mcode`) exposing Xiaomi's `mimo-auto` model (1M context) via device-fingerprint bootstrap-JWT auth (`/api/free-ai/bootstrap` → Bearer JWT → `/api/free-ai/openai/chat`). Supports multiple accounts (N fingerprints → round-robin with exponential cooldown), re-bootstrap on 401/403, and cooldown on 429. Reuses a new generic `NoAuthAccountCard` dashboard component (also wired for `opencode`). 22 unit tests; upstream validated live during review. (Maintainer follow-up: added the required `authHeader: "none"` field to the registry entry.) Co-authored with @pizzav-xyz.
+- **Prefer Claude Code for unprefixed `claude-*` model IDs** ([#3540] — thanks @Witroch4): opt-in setting (default off) that routes bare `claude-*` model IDs from Claude Code clients through the Claude Code OAuth account instead of requiring a provider prefix. Configurable via the `OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS` env flag or a dashboard toggle on the Claude provider page; explicit provider prefixes still win. Full layer coverage (resolver + DB setting + zod schemas + types + UI) with 6 tests. Co-authored with @Witroch4.
+- **Codex Responses-WebSocket call history** ([#3616] — thanks @kkkayye): Codex `/v1/responses` WebSocket calls are now persisted to request history — success completions plus prepare-failures, upstream WS errors and premature closes — with `sanitizeErrorMessage` applied to the stored error. Two proxy-side integration tests cover the success and failure paths.
+- **Obsidian/WebDAV**: add the `/api/v1/webdav` file server (PROPFIND/GET/PUT/DELETE/MKCOL/MOVE, Basic-Auth, path-traversal hardened) so Obsidian mobile can sync the vault (#3485, part 2). Implemented in the custom server layer (`scripts/dev/webdav-handler.mjs`) — intercepted before Next.js to support non-standard HTTP methods (`PROPFIND`, `MKCOL`, `MOVE`, `LOCK`). Reads vault path and credentials (with enc:v1: AES-256-GCM decryption) directly from the SQLite `key_value` table; credentials configured via PR1's `/api/settings/obsidian/webdav` endpoint. 36 TDD unit tests covering traversal guard, constant-time auth, decrypt round-trip, XML generation, and full CRUD cycle.
+- **Quota overview**: deactivate/activate an account directly from the quota card header (toggle button) so users can park a near-zero-quota account without navigating to the provider detail page. ([#3675](https://github.com/diegosouzapw/OmniRoute/pull/3675) — thanks @leninejunior)
+
+### ♻️ Code Quality
+
+- **providers/[id]**: extract `useProviderConnections`, `useProviderSettings`, `useProviderModels` hooks from the god-component — #3501 Phase 1f. `ProviderDetailPageClient.tsx`: 4,948 → 4,063 LOC (−885 lines). New hooks in `hooks/`: `useProviderConnections.ts` (954 LOC — all connection management, batch ops, proxy/CLIProxyAPI state, batch-test runner with MAX_BULK_IDS chunking), `useProviderSettings.ts` (264 LOC — Codex global service mode + Claude routing preference), `useProviderModels.ts` (155 LOC — model metadata, aliases). Frozen baselines updated. 10 Phase-1f smoke tests; typecheck/cycles/lint green. Co-authored with @oyi77.
+- **providers/[id]**: extract `useModelCompatState` hook + model sections (`ModelRow`, `PassthroughModelRow`, `PassthroughModelsSection`, `CustomModelsSection`, `CompatibleModelsSection`) from the god-component — #3501 Phase 1e. `ProviderDetailPageClient.tsx`: 6,838 → 4,922 LOC (−1,916 lines). New leaf `hooks/useModelCompatState.ts` (101 LOC); compat helpers moved to `providerPageHelpers.ts`. Frozen baselines: `providerPageHelpers.ts: 822`. 12 Phase-1e smoke tests; typecheck/cycles/lint green; #3610 auto-hide fix preserved.
+- **providers/[id]**: extract `ConnectionRow` (+ `CooldownTimer`/`inferErrorType`/`getStatusPresentation`), `ModelCompatPopover` (+ `recordToHeaderRows`), and `SiliconFlowEndpointModal` from the god-component into `components/` — #3501 Phase 1d. `ProviderDetailPageClient.tsx`: 8,092 → 6,838 LOC (−1,254 lines). Frozen baselines: `ConnectionRow.tsx: 941`. 7 new Phase-1d smoke tests; typecheck/cycles/lint green.
+- **providers/[id]: extract AddApiKeyModal + EditConnectionModal (+ WebSessionCredentialGuide) from the god-component into components/** ([#3501] Phase 1c): extracted the two heaviest inline modals — `AddApiKeyModal` (~787-LOC body) and `EditConnectionModal` (~1091-LOC body) — plus shared `WebSessionCredentialGuide` (~103 LOC) into standalone files under `providers/[id]/components/modals/` and `providers/[id]/components/` respectively. Added `ERROR_TYPE_LABELS` and `formatTimeAgo` to `providerPageHelpers.ts` (leaf) so `EditConnectionModal` and `ConnectionRow` share them without cycles. Pruned 14 now-unused imports from the god-component. `ProviderDetailPageClient.tsx`: 9,981 → 8,092 LOC (−1,889 lines). Frozen baselines: `AddApiKeyModal.tsx: 842`, `EditConnectionModal.tsx: 1170`. 6 new Phase-1c smoke tests; all 21 vitest modal tests pass; typecheck/cycles/lint green.
+- **refactor: small db/utils cleanup** ([#3523] — thanks @androw): table-driven `compression_analytics` column migration (replaces 17 repeated `ALTER TABLE` calls), a single merged `serializeJsonField` helper in `db/providers.ts` (folded two byte-identical serializers), and removal of the dead no-op `syncProviderDataToCloud`/`getProvidersNeedingRefresh` stubs from `shared/utils/machine.ts` (no remaining callers). Pure refactor; behavior unchanged.
+- **Provider-detail god-component decomposition — Phase 2b (remaining shared helpers→leaf)** ([#3501]): extended `providers/[id]/providerPageHelpers.ts` with all remaining pure helpers needed by the heavy modals (`AddApiKeyModal`/`EditConnectionModal`) before they can be extracted. Moved 22 symbols: web-session credential label/hint/check/title helpers; upstream-headers helpers (`upstreamHeadersRecordsEqual`, `headerRowsToRecord`, `effectiveUpstreamHeadersForProtocol`, `anyUpstreamHeadersBadge`, `getProtoSlice`) plus their `HeaderDraftRow`/`CompatModelRow`/`CompatModelMap`/`CompatByProtocolMap` types; Codex consts and helpers (`CODEX_REASONING_STRENGTH_OPTIONS`, `CODEX_ACCOUNT_SERVICE_TIER_VALUES`, `CODEX_GLOBAL_SERVICE_MODE_VALUES`, `getCodexServiceTierLabel`, `normalizeCodexLimitPolicy`, `getCodexRequestDefaults`, `getClaudeCodeCompatibleRequestDefaults`); misc helpers (`compatProtocolLabelKey`, `extractCommandCodeCredentialInput`, `normalizeAndValidateHttpBaseUrl`, `SILICONFLOW_ENDPOINTS`, `CommandCodeAuthFlowState`). New transitive imports wired into the leaf: `MODEL_COMPAT_PROTOCOL_KEYS` (`@/shared/constants/modelCompat`), `CodexServiceTier`/`getCodexRequestDefaults`/`getClaudeCodeCompatibleRequestDefaults` (`@/lib/providers/requestDefaults`), `CodexGlobalServiceMode` (`@/lib/providers/codexFastTier`), `WebSessionCredentialRequirement` (`./webSessionCredentials`). `ProviderDetailPageClient.tsx`: 10,288 → 9,980 LOC. Leaf module: 589 LOC (acyclic). 25-assertion unit test suite passes; smoke test 3/3; no import cycles. Co-authored with @oyi77.
+- **Provider-detail god-component decomposition — Phase 2 (helpers→lib)** ([#3501]): extracted the pure shared helpers — `ProviderMessageTranslator`/`LocalProviderMetadata` types, `providerText`/`providerCountText`/`readBooleanToggle`, and the provider base-URL + routing-tag/excluded-model parse/format block — into a new leaf `providers/[id]/providerPageHelpers.ts` (imports only `@/shared`, so the client and modals share them with no import cycle). `ProviderDetailPageClient.tsx`: 10,435 → 10,288 LOC. Unblocks extracting the heavier `AddApiKeyModal`/`EditConnectionModal` (which depend on these helpers) without cycling. The Phase 0 smoke test caught a missing transitive import (`isSelfHostedChatProvider`) at mount — now wired + locked by a new helpers unit test (12 assertions). Co-authored with @oyi77.
+
+- **#3500 fully resolved** — Hard Rule #5 (no raw SQL in route handlers): all 13 internal offenders migrated to `src/lib/db/` modules across slices (call*logs, usage_history/daily_usage_summary, community_servers, usage_logs, semantic_cache, proxy_logs, skills UPDATE, db-backups). The gate's `KNOWN_RAW_SQL` set is renamed to `EXTERNAL_DB_ALLOWED` (with a back-compat alias) and now holds only the **2 external-DB reads** (`oauth/cursor/auto-import`, `oauth/kiro/auto-import`) — these open \_another app's* SQLite to import credentials, so by design they cannot live in OmniRoute's `db/` domain. The gate still blocks any NEW raw SQL against OmniRoute's DB.
+- **chore(db-gate):** reclassify `KNOWN_UNEXPORTED` → `INTENTIONALLY_INTERNAL` in `scripts/check/check-db-rules.mjs` ([#3499]): a full audit of all 25 db modules confirmed each is consumed via direct/dynamic import per Hard Rule #2 ("Never barrel-import from localDb.ts"). The old framing labelled them as "debt", which was misleading — they are the correct pattern. The gate's blocking behaviour is unchanged (a NEW unexported module still fails); only the name, comments, and per-module justifications were updated to reflect audited truth. Four modules flagged `DEAD?` (`compressionScheduler`, `discovery`, `pluginMetrics`, `prompts`) have zero production importers and are documented as schema-reserved. A new regression-guard test (`tests/unit/check-db-rules-classification.test.ts`) asserts every non-dead module in the set has ≥1 real importer, so a future consumer removal surfaces as a test failure requiring explicit reclassification.
+- **refactor(db): move `call_logs` aggregations into `callLogStats` db module** ([#3500]): extracted raw SQL from three route handlers (`/api/provider-metrics`, `/api/search/stats`, `/api/v1/search/analytics`) into a new `src/lib/db/callLogStats.ts` domain module (`getProviderMetrics`, `getSearchProviderStats`, `getRecentSearchLogs`, `getSearchAggregateStats`, `getSearchProviderCounts`). First slice of #3500 (call_logs cluster). Behavior unchanged; the three routes are removed from `KNOWN_RAW_SQL` in the gate. Validated with TDD unit tests (6 assertions seeding an in-memory SQLite fixture).
+- **refactor(db): move `usage_history`/`daily_usage_summary` SQL into `usageAnalytics` db module** ([#3500]): extracted all inline `db.prepare(...)` calls from two route handlers (`/api/usage/analytics`, `/api/settings/export-json`) into a new `src/lib/db/usageAnalytics.ts` module and extended `src/lib/db/callLogStats.ts` with `getFallbackStats`. New exports: `buildUnifiedSource`, `buildPresetUnifiedSource` (UNION CTE builders), plus 12 typed query functions covering summary, daily, daily-cost, heatmap, model, provider, account, api-key, service-tier, weekly-pattern, and preset-cost aggregations, plus `getAllUsageHistory`/`getAllDomainCostHistory`/`getAllDomainBudgets` for backup export. Second slice of #3500. `KNOWN_RAW_SQL` drops from 12 → 10. Validated with 21 TDD unit tests (`tests/unit/db-usage-analytics-3500.test.ts`) seeding a temp SQLite fixture.
+
+- **refactor(db): move `community_servers` auth look-up into `gamification` db module** ([#3500]): extracted raw SQL from two federation route handlers (`/api/gamification/federation/leaderboard`, `/api/gamification/federation/score`) into a new `getConnectedServerByKeyHash(apiKeyHash)` function in `src/lib/db/gamification.ts`. Third slice of #3500 (gamification federation cluster). Behavior unchanged; the two routes are removed from `KNOWN_RAW_SQL` in the gate. Validated with TDD unit tests (3 assertions seeding a temp SQLite fixture).
+
+- **refactor(db): move `skills UPDATE` + `db-backups` SQL into db modules** ([#3500]): fifth slice of #3500. Extracted the dynamic `UPDATE skills SET …` from `src/app/api/skills/[id]/route.ts` into a new `src/lib/db/skills.ts` module (`updateSkill(id, patch)`). The dynamic SET clause is injection-safe: column names are validated against a hard-coded allowlist of known writable columns before being interpolated; unknown keys are silently ignored. Extended `src/lib/db/backup.ts` with three new functions: `exportAllSummaryRows()` (multi-table SELECT for key_value / combos / provider_connections / api_keys, used by exportAll), `getTableNamesFromAdapter()` (sqlite_master introspection via an adapter arg, used by import validation), and `countImportedRows()` (post-import COUNT(\*) per table). The backup domain module is the correct home for sqlite_master introspection — it is not "raw SQL in a route" once moved there. `KNOWN_RAW_SQL` drops by 3 (from 8 → 5). Validated with 11 TDD unit tests (`tests/unit/db-backups-skills-3500.test.ts`).
+- **refactor(db): move `usage_logs`/`semantic_cache`/`proxy_logs` SQL into db modules** ([#3500]): extracted raw `db.prepare(...)` SQL from three route handlers (`/api/analytics/auto-routing` → `usageLogs.ts`; `/api/cache/entries` → `semanticCache.ts`; `/api/logs/export` → `proxyLogs.ts`) into new `src/lib/db/` domain modules. New exports: `getAutoRoutingTotalCount`, `getAutoRoutingVariantBreakdown`, `getAutoRoutingTopProviders` (usage_logs), `listSemanticCacheEntries`, `deleteSemanticCacheBySignature`, `deleteSemanticCacheByModel` (semantic_cache), and `exportProxyLogsSince` (proxy_logs). Fourth slice of #3500. `KNOWN_RAW_SQL` drops from 8 → 5. Validated with 13 TDD unit tests (`tests/unit/db-logs-cache-3500.test.ts`) seeding temp SQLite fixtures.
+
+- **Provider-detail god-component decomposition — Phase 0** ([#3501]): introduced `ProviderDetailPageClient.tsx` and reduced `providers/[id]/page.tsx` to a thin 9-line route wrapper (was 12,882 LOC), following the repo's `*PageClient` convention. Added the first-ever smoke render test for the page (Hard Rule #8) as the safety net every later extraction phase is diffed against. Behavior unchanged; the `check-file-size` ratchet now tracks the extracted client. Foundation for Phases 1–6 (strangler-fig). Thanks @oyi77 for the parallel modularization effort in #3627.
+- **Provider-detail god-component decomposition — Phase 1a** ([#3501]): extracted the three self-contained auth-import modal clusters (Codex/Claude/Gemini `Import*AuthModal` + `Apply*AuthModal` + their co-located helpers, ~2,160 LOC) into `providers/[id]/components/modals/`. `ProviderDetailPageClient.tsx` drops 12,882 → 10,719 LOC. Behavior unchanged (smoke test green; clusters had clean `{ onClose, onSuccess }` / inline-prop interfaces). Co-authored with @oyi77.
+- **Provider-detail god-component decomposition — Phase 1b** ([#3501]): extracted `EditCompatibleNodeModal` (+ its node/props types) into `providers/[id]/components/modals/`, and moved the shared `CC_COMPATIBLE_DEFAULT_CHAT_PATH` constant into a leaf `providerDetailConstants.ts` so the page client and the modal can both import it without a circular dependency. Also removed two dangling section comments left by Phase 1a. `ProviderDetailPageClient.tsx`: 10,719 → 10,435 LOC. Behavior unchanged (smoke test + a new standalone modal render test green; `check:cycles` clean). Co-authored with @oyi77.
+
+### 🔧 Bug Fixes
+
+- **Combos / Auto-Combo: premature context compaction ("agent keeps forgetting things")** ([#3680]): two related context-window bugs fixed. (1) `GET /api/combos/auto` now advertises `context_length` / `max_output_tokens` (MAX across the candidate pool — safe because the auto-combo context pre-filter routes oversized requests to large-window candidates), and the opencode plugin consumes them instead of hardcoding `limit: { context: 0 }` — a zero context silently disables opencode's smart auto-compaction, letting sessions grow until the gateway's destructive history purge kicks in. (2) chatCore's proactive compression for DB combos (incl. quota-shared pools) no longer compresses at `min(...allTargets)`: it now uses the EXECUTING target's own window (`resolveComboContextLimit`), keeping min-of-targets only as a defensive fallback when the current provider/model resolves no specific limit. TDD: 8 server tests (`tests/unit/auto-combo-context-advertising.test.ts`) + 3 plugin tests (`tests/auto-combo-context.test.ts`).
+- **Obsidian/WebDAV**: add the `/api/settings/obsidian/webdav` config route (enable/disable vault sync), encrypt WebDAV credentials at rest, and remove the duplicate UI block (#3485, part 1).
+
+- **OpenCode Free / passthrough**: "Test all models" now respects "Auto-hide failed models" and switches the list to the visible filter so hidden models actually disappear (#3610). Three related bugs fixed: `autoHideFailed` is now threaded from the outer component into `PassthroughModelsSection` via a prop (single shared checkbox); the `/api/models/test-all` request body now includes `autoHideFailed: true` so the server persists the hide; and after the loop, `visibilityFilter` is switched to `"visible"` when ≥1 model was hidden. Two pure-function helpers (`buildPassthroughTestBody`, `shouldSwitchToVisibleFilter`) extracted to `providerPageHelpers.ts` with 7 unit tests.
+- **Resilience**: clear stale transient connection cooldowns on startup so a prior unclean crash no longer makes every request time out at 120s after restart (#3625)
+
+- **fix(home topology): restore live in-flight request pulse** ([#3507]): the animated "pulse" edges in the home Provider Topology panel went dead after PR #3401 unified request visibility, because `activeRequests` was hardcoded to `[]`. Re-wired to `useLiveRequests()` (the existing WebSocket hook on port 20129) so that every pending/running request drives the animation in real time. A pure `selectActiveRequests` mapping helper was extracted to `home/topologyUtils.ts` with 5 unit tests.
+- **Electron desktop**: launch the peer-stamping `server-ws.mjs` entrypoint so local-only routes (AgentBridge, MCP, services) no longer return 403 LOCAL_ONLY (#3386)
+- **Provider Topology**: stop flagging healthy providers as errored based on stale historical failures; use current request status (#3619)
+- **OpenCode Free**: fetch the live model catalog from the provider's `modelsUrl` for the no-auth model picker instead of serving a stale hardcoded list (#3611)
+- **Hermes Agent**: honour the `HERMES_HOME` env var when writing/reading the agent config instead of always using `~/.hermes` (#3628). Introduced `getHermesHome()` / `getHermesConfigPath()` helpers (read at call-time) and routed all four hardcoded callsites through them so OmniRoute's config lands in the same directory that the Hermes PowerShell installer configures on Windows.
+- **MITM/cert**: remove the duplicated "Command failed:" prefix in system-command error messages ([#3641](https://github.com/diegosouzapw/OmniRoute/issues/3641)): `execFileText` was prepending its own `"Command failed: "` prefix on top of Node's `execFile` error message, which already begins with `"Command failed: <cmd>"` for non-zero exits. The error message now surfaces Node's message directly (no double prefix), with stderr appended only when non-empty.
+
+- **fix(reasoning): replay `reasoning_content` on plain DeepSeek turns** ([#3632] — thanks @adivekar-utexas): the reasoning-replay gate previously only fired when an assistant message already carried `reasoning_content`. Plain (non-tool-call) turns whose `reasoning_content` was stripped by the client (e.g. Cursor) were forwarded without it, so DeepSeek V4+ rejected the request with 400 "the reasoning_content in the thinking mode must be passed back". The gate now also covers missing/empty `reasoning_content` on DeepSeek replay targets, injecting the cached reasoning (or the non-Anthropic placeholder) so multi-turn text conversations no longer 400. Fixes #1682. 2 regression tests.
+- **fix(kiro): route enterprise IAM Identity Center accounts to their regional endpoint** ([#3631] — thanks @artickc): Kiro/CodeWhisperer access tokens and Q Developer profile ARNs are region-bound, so enterprise IAM Identity Center accounts outside `us-east-1` (e.g. `eu-central-1`) were rejected by the default host. Adds `resolveKiroRegion` (stored region → profileArn region → `us-east-1`) and `kiroRuntimeHost` (regional `q.{region}.amazonaws.com`, legacy `codewhisperer.us-east-1` for the default), routes chat + usage to the regional endpoint, and discovers the region-matched `profileArn` via `ListAvailableProfiles` in a best-effort `postExchange` hook. 9 tests.
+- **fix(combo): skip same-provider/connection targets on connection-level errors** ([#3637] — thanks @herjarsa): on connection-level upstream errors (408/500/502/503/504/524), remaining same-`provider:connection` targets in a combo request are now skipped to avoid hammering a known-bad connection, in both the priority and round-robin paths. Adjusted in review to **exclude OmniRoute circuit-breaker-open responses** (503 + `X-OmniRoute-Provider-Breaker` / `provider_circuit_open`) from this skip, preserving the invariant that a breaker-open is an ordinary target failure (the next same-provider target is still tried). Co-authored with @herjarsa.
+- **/v1/responses**: detect stream readiness for tool-call-only and `object`-less chunks so Codex-shaped (reasoning + tools) requests no longer fail with "Stream ended before producing useful content" (#3612)
+- **RTL locales (ar/fa/he/ur)**: use logical CSS direction utilities for the sidebar and key overlays so the layout mirrors correctly under `dir=rtl` (#3541, partial — core layout)
+- **Kiro/AWS auto-import**: set a descriptive account name and dedupe by `profileArn` so imports no longer create nameless duplicate "OAuth Account" rows (#3615)
+- **fix(guardrails):** the `/api/guardrails/test` route now validates its body through `validateBody()` (Zod) instead of parsing raw JSON directly, aligning it with the repo-wide input-validation pattern (Hard Rule #7). ([#3621](https://github.com/diegosouzapw/OmniRoute/pull/3621) — thanks @diegosouzapw)
+- **fix(dashboard): bulk provider connection actions** — close audit, API, and UX gaps in the batch activate/deactivate flow: register the `provider.credentials.batch_updated` event in `HIGH_LEVEL_ACTIONS` and `ACTIVITY_ICONS` (was silently dropped from the Activity feed); fix `/api/providers` PATCH to return `warn` status when `notFound` is non-empty instead of always `success`; `/api/providers/test-batch` empty-result early-return now includes a `summary` so stale-ID mode reports to the user; bulk activate/deactivate chunks selection by 100 to avoid the Zod 400 cap on large provider accounts. ([#3673](https://github.com/diegosouzapw/OmniRoute/pull/3673) — thanks @leninejunior)
+
+### 📝 Maintenance
+
+- **fix(ci):** increase the `execFileSync` `maxBuffer` in `validate-pack-artifact` so the npm-pack inventory no longer overflows on large tarballs during release validation — follow-up to the v3.8.21 pack-artifact hotfix. ([#3622](https://github.com/diegosouzapw/OmniRoute/pull/3622) — thanks @diegosouzapw)
+
+---
+
## [3.8.21] — 2026-06-11
### ✨ Added
@@ -235,12 +299,12 @@
Thanks to everyone whose work landed in v3.8.15:
-| Contributor | PRs / Issues |
-| --- | --- |
-| [@herjarsa](https://github.com/herjarsa) | #3366, #3369, #3370 |
-| [@oyi77](https://github.com/oyi77) | #3365, #3371 |
-| [@TapZe](https://github.com/TapZe) | #3372 |
-| [@Gerashka2](https://github.com/Gerashka2) | reported #3363 |
+| Contributor | PRs / Issues |
+| ------------------------------------------------ | -------------------------------------------------- |
+| [@herjarsa](https://github.com/herjarsa) | #3366, #3369, #3370 |
+| [@oyi77](https://github.com/oyi77) | #3365, #3371 |
+| [@TapZe](https://github.com/TapZe) | #3372 |
+| [@Gerashka2](https://github.com/Gerashka2) | reported #3363 |
| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3375 shepherding, migration restores |
---
@@ -290,22 +354,22 @@ Thanks to everyone whose work landed in v3.8.15:
Thanks to everyone whose work landed in v3.8.14:
-| Contributor | PRs / Issues |
-| --- | --- |
-| [@pizzav-xyz](https://github.com/pizzav-xyz) | #3338 |
-| [@quanturbo](https://github.com/quanturbo) | #3333 |
-| [@oyi77](https://github.com/oyi77) | #3323, #3345 |
-| [@rdself](https://github.com/rdself) | #3349 |
-| [@wilsonicdev](https://github.com/wilsonicdev) | #3346 |
-| [@hertznsk](https://github.com/hertznsk) | #3332 |
-| [@abdulkadirozyurt](https://github.com/abdulkadirozyurt) | #3330 |
-| [@mikmaneggahommie](https://github.com/mikmaneggahommie) | #3329 |
-| [@Flexible78](https://github.com/Flexible78) | #3347 |
-| [@Lang-Qiu](https://github.com/Lang-Qiu) | #3337 |
-| [@KrisnaSantosa15](https://github.com/KrisnaSantosa15) | #3348 |
-| [@nullbytef0x](https://github.com/nullbytef0x) | #3357 |
-| [@Ardem2025](https://github.com/Ardem2025) | #3358 |
-| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3334, #3335, #3336, #3339, #3350, #3352, #3353, #3356; review/hardening across the cycle |
+| Contributor | PRs / Issues |
+| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
+| [@pizzav-xyz](https://github.com/pizzav-xyz) | #3338 |
+| [@quanturbo](https://github.com/quanturbo) | #3333 |
+| [@oyi77](https://github.com/oyi77) | #3323, #3345 |
+| [@rdself](https://github.com/rdself) | #3349 |
+| [@wilsonicdev](https://github.com/wilsonicdev) | #3346 |
+| [@hertznsk](https://github.com/hertznsk) | #3332 |
+| [@abdulkadirozyurt](https://github.com/abdulkadirozyurt) | #3330 |
+| [@mikmaneggahommie](https://github.com/mikmaneggahommie) | #3329 |
+| [@Flexible78](https://github.com/Flexible78) | #3347 |
+| [@Lang-Qiu](https://github.com/Lang-Qiu) | #3337 |
+| [@KrisnaSantosa15](https://github.com/KrisnaSantosa15) | #3348 |
+| [@nullbytef0x](https://github.com/nullbytef0x) | #3357 |
+| [@Ardem2025](https://github.com/Ardem2025) | #3358 |
+| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3334, #3335, #3336, #3339, #3350, #3352, #3353, #3356; review/hardening across the cycle |
---
@@ -332,7 +396,7 @@ Thanks to everyone whose work landed in v3.8.14:
- **fix(theoldllm):** stop the `[502]: Body is unusable: Body has already been read` error on the cached-token path — the executor read the same upstream `Response` body with `.text()` twice; it now reads it once and only re-reads after a token-rejection refetch. (#3296 — thanks @onizukashonan14-png)
- **fix(dashboard):** keep no-auth providers (opencode, duckduckgo-web, theoldllm, veoaifree-web) visible under the "Show configured only" filter — they never create a connection row (`stats.total === 0`) but are always usable and already appear in `/v1/models`, so the filter now treats `displayAuthType === "no-auth"` as configured. (#3290 — thanks @uniQta)
- **fix(dashboard):** refresh the connection list after a Codex/Claude/Gemini auth import — the import modals called `fetchData()` (which only reloads provider metadata), so a freshly-imported connection stayed invisible until a manual reload; they now call `fetchConnections()`. ([#3320](https://github.com/diegosouzapw/OmniRoute/pull/3320) — thanks @zhiru)
-- **fix(cli):** `omniroute update` no longer always fails on a global install — `getCurrentVersion()` and `createBackup()` now resolve `package.json`/`bin` relative to the script (`import.meta.url`) instead of `process.cwd()` (the user's working dir on a global npm/brew install → *"Could not determine current version"*), and the backup copies the `cli` directory with `cpSync({recursive:true})` instead of `copyFileSync`, which threw a swallowed `EISDIR` → *"Failed to create backup. Aborting"*. (#3295 — thanks @uniQta)
+- **fix(cli):** `omniroute update` no longer always fails on a global install — `getCurrentVersion()` and `createBackup()` now resolve `package.json`/`bin` relative to the script (`import.meta.url`) instead of `process.cwd()` (the user's working dir on a global npm/brew install → _"Could not determine current version"_), and the backup copies the `cli` directory with `cpSync({recursive:true})` instead of `copyFileSync`, which threw a swallowed `EISDIR` → _"Failed to create backup. Aborting"_. (#3295 — thanks @uniQta)
- **fix(sse):** harden the passthrough stream against empty upstream responses — emit a synthetic retry chunk on an empty `choices: []` (fixes a Copilot Chat crash) and log empty post-`tool_calls` completions; also registers **MiniMax M3** (1M context) across 8 provider tiers. ([#3297](https://github.com/diegosouzapw/OmniRoute/pull/3297), #3110 — thanks @wilsonicdev)
- **fix(opencode-provider):** extract `contextLength` from the live `/v1/models` catalog (live > `modelContextLengths` > static map) so passthrough models outside the legacy 8-model map no longer silently truncate to OpenCode's 128K default. ([#3298](https://github.com/diegosouzapw/OmniRoute/pull/3298) — thanks @herjarsa / @diegosouzapw)
- **fix(dev):** auto-rebuild `better-sqlite3` on a Node ABI mismatch at `npm run dev` startup (nvm 22↔24) — dev-only, no-op on the healthy path, unrelated errors not swallowed. ([#3301](https://github.com/diegosouzapw/OmniRoute/pull/3301) — thanks @zhiru)
@@ -353,18 +417,18 @@ Thanks to everyone whose work landed in v3.8.14:
Thanks to everyone whose work landed in v3.8.13:
-| Contributor | PRs / Issues |
-| --- | --- |
-| [@zhiru](https://github.com/zhiru) | #3300, #3306, #3307 / #3310, #3309, #3301, #3311, #3320, #3319, #3316 |
-| [@tycronk20](https://github.com/tycronk20) | #3317, #3318 |
-| [@Vinayrnani](https://github.com/Vinayrnani) | #3267 |
-| [@oyi77](https://github.com/oyi77) | #3292 (closes #3070), #3322 |
-| [@onizukashonan14-png](https://github.com/onizukashonan14-png) | #3296 |
-| [@uniQta](https://github.com/uniQta) | #3290, #3295 |
-| [@wilsonicdev](https://github.com/wilsonicdev) | #3297 |
-| [@herjarsa](https://github.com/herjarsa) | #3298, #3304 |
-| [@mikmaneggahommie](https://github.com/mikmaneggahommie) | reported the Completions.me rickroll (discussion #3293) |
-| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3299, #3302, #3303; co-author on #3292 / #3306 / #3298 / #3304 / #3309 |
+| Contributor | PRs / Issues |
+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
+| [@zhiru](https://github.com/zhiru) | #3300, #3306, #3307 / #3310, #3309, #3301, #3311, #3320, #3319, #3316 |
+| [@tycronk20](https://github.com/tycronk20) | #3317, #3318 |
+| [@Vinayrnani](https://github.com/Vinayrnani) | #3267 |
+| [@oyi77](https://github.com/oyi77) | #3292 (closes #3070), #3322 |
+| [@onizukashonan14-png](https://github.com/onizukashonan14-png) | #3296 |
+| [@uniQta](https://github.com/uniQta) | #3290, #3295 |
+| [@wilsonicdev](https://github.com/wilsonicdev) | #3297 |
+| [@herjarsa](https://github.com/herjarsa) | #3298, #3304 |
+| [@mikmaneggahommie](https://github.com/mikmaneggahommie) | reported the Completions.me rickroll (discussion #3293) |
+| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3299, #3302, #3303; co-author on #3292 / #3306 / #3298 / #3304 / #3309 |
---
@@ -406,14 +470,14 @@ Thanks to everyone whose work landed in v3.8.13:
Thanks to everyone whose work landed in v3.8.12:
-| Contributor | PRs / Issues |
-| --- | --- |
-| [@oyi77](https://github.com/oyi77) | #3250, #3259, #3280, #3285, #3286 |
-| [@wilsonicdev](https://github.com/wilsonicdev) | #3249, #3268, #3282 / #3283 (co-author, #3247 diagnosis), #3287 |
-| [@strangersp](https://github.com/strangersp) | #3261 |
-| [@MikeTuev](https://github.com/MikeTuev) | #3248 |
-| [@leninejunior](https://github.com/leninejunior) | #3271 |
-| [@zhiru](https://github.com/zhiru) | #3274 |
+| Contributor | PRs / Issues |
+| ------------------------------------------------ | --------------------------------------------------------------------------------- |
+| [@oyi77](https://github.com/oyi77) | #3250, #3259, #3280, #3285, #3286 |
+| [@wilsonicdev](https://github.com/wilsonicdev) | #3249, #3268, #3282 / #3283 (co-author, #3247 diagnosis), #3287 |
+| [@strangersp](https://github.com/strangersp) | #3261 |
+| [@MikeTuev](https://github.com/MikeTuev) | #3248 |
+| [@leninejunior](https://github.com/leninejunior) | #3271 |
+| [@zhiru](https://github.com/zhiru) | #3274 |
| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3256, #3263, #3270, #3275, #3277, #3278, #3279, #3281, #3284, #3289 |
---
@@ -462,26 +526,26 @@ Thanks to everyone whose work landed in v3.8.12:
Thanks to everyone whose work landed in v3.8.11:
-| Contributor | PRs / Issues |
-| --- | --- |
-| [@wilsonicdev](https://github.com/wilsonicdev) | #3189, #3201, #3203, #3204, #3232, #3240, #3241 |
-| [@pizzav-xyz](https://github.com/pizzav-xyz) | #3170, #3171, #3172 |
-| [@zhiru](https://github.com/zhiru) | #3185, #3195 |
-| [@oyi77](https://github.com/oyi77) | #3217 |
-| [@miracuves](https://github.com/miracuves) | #3116, #3226 |
-| [@ngocquynh85](https://github.com/ngocquynh85) | #3205, #3214, #3215 |
-| [@xz-dev](https://github.com/xz-dev) | #3188 |
-| [@bypanghu](https://github.com/bypanghu) | #3191 |
-| [@juandisay](https://github.com/juandisay) | #3206 |
-| [@tjengbudi](https://github.com/tjengbudi) | #3197, #3198, #3199 |
-| [@naimo84](https://github.com/naimo84) | #3151 |
-| [@yeardie](https://github.com/yeardie) | #3025 |
-| [@pulyankote](https://github.com/pulyankote) | #3202 |
-| [@YoursSweetDom](https://github.com/YoursSweetDom) | #3180 |
-| [@Guru01100101](https://github.com/Guru01100101) | #3091 |
-| [@androw](https://github.com/androw) | #3167 (co-author) |
-| [@ibanunmangun](https://github.com/ibanunmangun) | #3193 (co-author) |
-| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3187, #3200, issue-fix batches |
+| Contributor | PRs / Issues |
+| -------------------------------------------------- | ----------------------------------------------- |
+| [@wilsonicdev](https://github.com/wilsonicdev) | #3189, #3201, #3203, #3204, #3232, #3240, #3241 |
+| [@pizzav-xyz](https://github.com/pizzav-xyz) | #3170, #3171, #3172 |
+| [@zhiru](https://github.com/zhiru) | #3185, #3195 |
+| [@oyi77](https://github.com/oyi77) | #3217 |
+| [@miracuves](https://github.com/miracuves) | #3116, #3226 |
+| [@ngocquynh85](https://github.com/ngocquynh85) | #3205, #3214, #3215 |
+| [@xz-dev](https://github.com/xz-dev) | #3188 |
+| [@bypanghu](https://github.com/bypanghu) | #3191 |
+| [@juandisay](https://github.com/juandisay) | #3206 |
+| [@tjengbudi](https://github.com/tjengbudi) | #3197, #3198, #3199 |
+| [@naimo84](https://github.com/naimo84) | #3151 |
+| [@yeardie](https://github.com/yeardie) | #3025 |
+| [@pulyankote](https://github.com/pulyankote) | #3202 |
+| [@YoursSweetDom](https://github.com/YoursSweetDom) | #3180 |
+| [@Guru01100101](https://github.com/Guru01100101) | #3091 |
+| [@androw](https://github.com/androw) | #3167 (co-author) |
+| [@ibanunmangun](https://github.com/ibanunmangun) | #3193 (co-author) |
+| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3187, #3200, issue-fix batches |
---
@@ -697,9 +761,9 @@ And thank you to the OmniRoute community for the bug reports, reproductions, and
refreshed siblings concurrently, so Auth0 revoked the whole token family
(`openai/codex#9648`) and every account but the last died with
`[403] <!DOCTYPE html>`. The quota path now skips proactive refresh for
- rotating providers (`rotationGroupFor`) and reuses the current access_token,
+ rotating providers (`rotationGroupFor`) and reuses the current access*token,
deferring genuine expiry to the reactive, serialized 401 path. Defense in
- depth: `serializeRefresh` now leaves a settle gap between two *queued* sibling
+ depth: `serializeRefresh` now leaves a settle gap between two \_queued* sibling
refreshes (default 2000 ms, tunable via `CODEX_REFRESH_SPACING_MS`, `"0"` to
opt out) while releasing a lone refresh immediately, so the reactive path adds
no latency.
@@ -762,7 +826,7 @@ And thank you to the OmniRoute community for the bug reports, reproductions, and
via a new `RegistryModel.interleavedField` field, so follow-up/tool-use turns
replay reasoning_content. Previously `big-pickle` matched no replay pattern and
failed with `[400] The reasoning_content in the thinking mode must be passed
- back to the API` (its DeepSeek-thinking upstream is not detectable from the
+back to the API` (its DeepSeek-thinking upstream is not detectable from the
model id, and `requiresReasoningReplay` does not consume `supportsReasoning`).
`getResolvedModelCapabilities` now surfaces the registry `interleavedField`. (#2900)
- **providers/github-copilot:** built-in GitHub Copilot Claude Opus and Gemini
@@ -795,7 +859,7 @@ And thank you to the OmniRoute community for the bug reports, reproductions, and
instead of failing with "No credentials for provider: opencode-zen". A
configured, active key is still used when present. (#2962)
- **translator/responses:** fixed an upstream `[400] Messages with role 'tool'
- must be a response to a preceding message with 'tool_calls'` when a Codex
+must be a response to a preceding message with 'tool_calls'` when a Codex
client sent a `function_call` with an empty/missing `call_id`. The orphaned
`function_call_output` previously slipped past the orphan filter. Now
empty-`call_id` function calls are skipped (no dangling assistant tool_call)
@@ -837,7 +901,7 @@ And thank you to the OmniRoute community for the bug reports, reproductions, and
- **sse/chatCore:** the heap-pressure guard now auto-calibrates its threshold to 85%
of the live V8 heap ceiling (floor 400 MB) instead of a fixed 200 MB that sat below
the app's ~260 MB baseline and returned `503 Service temporarily unavailable due to
- resource pressure` for every request once the heap warmed up. It now tracks
+resource pressure` for every request once the heap warmed up. It now tracks
`--max-old-space-size` across 1 GB / 2 GB / large VPS; `HEAP_PRESSURE_THRESHOLD_MB`
still overrides. (#3052)
- **proxy:** fail closed for OAuth usage-account proxies (#3051 — thanks @terence71-glitch)
@@ -852,33 +916,33 @@ And thank you to the OmniRoute community for the bug reports, reproductions, and
A special thanks to everyone who contributed to this release — 746 commits since `v3.8.7`:
-| Contributor | PRs / Contribution |
-| --- | --- |
-| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — AgentBridge, Traffic Inspector, Quota Share Engine, Nav Restructure, Plugins integration, releases & upstream ports |
-| [@oyi77](https://github.com/oyi77) | #2913, #2947, #2954, #2978, #3015, #3018, #3039, #3041, #3045, #3046, #3049 |
-| [@terence71-glitch](https://github.com/terence71-glitch) | #2956, #2960, #2963, #2984, #3000, #3006, #3012, #3048, #3051 |
-| [@soyelmismo](https://github.com/soyelmismo) | #2951, #2965, #2973 |
-| [@branben](https://github.com/branben) | #2958, #2959 |
-| [@makcimbx](https://github.com/makcimbx) | #2937, #2938 |
-| [@guanbear](https://github.com/guanbear) | #2931, #3031 |
-| [@Lion-killer](https://github.com/Lion-killer) | #2981, #2988 |
-| [@JxnLexn](https://github.com/JxnLexn) | per-API-key stream default mode |
-| [@androw](https://github.com/androw) | #3017 |
-| [@xz-dev](https://github.com/xz-dev) | #2975, #3064 |
-| [@S0yora](https://github.com/S0yora) | #2964 |
-| [@NekoMonci12](https://github.com/NekoMonci12) | #3008 |
-| [@Tentoxa](https://github.com/Tentoxa) | #3010 |
-| [@ReqX](https://github.com/ReqX) | #2957 |
-| [@NomenAK](https://github.com/NomenAK) | #2943 |
-| [@charithharshana](https://github.com/charithharshana) | #2940 |
-| [@dhaern](https://github.com/dhaern) | #2927 |
-| [@dangeReis](https://github.com/dangeReis) | #3021 |
-| [@bobbyunknown](https://github.com/bobbyunknown) | #3029 |
-| [@CitrusIce](https://github.com/CitrusIce) | #3035, #3058 |
-| [@wussh](https://github.com/wussh) | #3036 |
-| [@Chewji9875](https://github.com/Chewji9875) | #3037 |
-| [@herjarsa](https://github.com/herjarsa) | #3043 |
-| [@freefrank](https://github.com/freefrank) | #3066 (reported the Docker build failure) |
+| Contributor | PRs / Contribution |
+| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
+| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — AgentBridge, Traffic Inspector, Quota Share Engine, Nav Restructure, Plugins integration, releases & upstream ports |
+| [@oyi77](https://github.com/oyi77) | #2913, #2947, #2954, #2978, #3015, #3018, #3039, #3041, #3045, #3046, #3049 |
+| [@terence71-glitch](https://github.com/terence71-glitch) | #2956, #2960, #2963, #2984, #3000, #3006, #3012, #3048, #3051 |
+| [@soyelmismo](https://github.com/soyelmismo) | #2951, #2965, #2973 |
+| [@branben](https://github.com/branben) | #2958, #2959 |
+| [@makcimbx](https://github.com/makcimbx) | #2937, #2938 |
+| [@guanbear](https://github.com/guanbear) | #2931, #3031 |
+| [@Lion-killer](https://github.com/Lion-killer) | #2981, #2988 |
+| [@JxnLexn](https://github.com/JxnLexn) | per-API-key stream default mode |
+| [@androw](https://github.com/androw) | #3017 |
+| [@xz-dev](https://github.com/xz-dev) | #2975, #3064 |
+| [@S0yora](https://github.com/S0yora) | #2964 |
+| [@NekoMonci12](https://github.com/NekoMonci12) | #3008 |
+| [@Tentoxa](https://github.com/Tentoxa) | #3010 |
+| [@ReqX](https://github.com/ReqX) | #2957 |
+| [@NomenAK](https://github.com/NomenAK) | #2943 |
+| [@charithharshana](https://github.com/charithharshana) | #2940 |
+| [@dhaern](https://github.com/dhaern) | #2927 |
+| [@dangeReis](https://github.com/dangeReis) | #3021 |
+| [@bobbyunknown](https://github.com/bobbyunknown) | #3029 |
+| [@CitrusIce](https://github.com/CitrusIce) | #3035, #3058 |
+| [@wussh](https://github.com/wussh) | #3036 |
+| [@Chewji9875](https://github.com/Chewji9875) | #3037 |
+| [@herjarsa](https://github.com/herjarsa) | #3043 |
+| [@freefrank](https://github.com/freefrank) | #3066 (reported the Docker build failure) |
A special thanks to everyone who contributed code, reviews, and tests for this release:
@androw, @bobbyunknown, @branben, @charithharshana, @Chewji9875, @CitrusIce, @dangeReis, @dhaern, @diegosouzapw, @freefrank, @guanbear, @herjarsa, @JxnLexn, @Lion-killer, @makcimbx, @NekoMonci12, @NomenAK, @oyi77, @ReqX, @S0yora, @soyelmismo, @Tentoxa, @terence71-glitch, @wussh, @xz-dev
@@ -983,7 +1047,7 @@ A special thanks to everyone who contributed code, reviews, and tests for this r
- **warning-cleanup:** relax node engine constraint to `>=22.0.0` and clean dependencies (keeping `marked-terminal` to prevent TUI REPL crash) (#2792 — thanks @oyi77)
- **combo:** normalize upstream Headers into a plain object before classification to avoid Node 24 / undici cross-instance `Cannot read private member #headers` crash on combo failover (#2751)
- **translator:** silently drop `tool_search` built-in tool type instead of returning 400 — newer Codex clients send `tool_search` as a Responses API built-in with no Chat Completions equivalent (#2766)
-- **usage:** un-invert GitHub Copilot Free / limited plan quota — `limited_user_quotas` is the *remaining* count, not used, so the dashboard now shows 100% when the quota is untouched and 0% when fully exhausted (#2876 — thanks @androw)
+- **usage:** un-invert GitHub Copilot Free / limited plan quota — `limited_user_quotas` is the _remaining_ count, not used, so the dashboard now shows 100% when the quota is untouched and 0% when fully exhausted (#2876 — thanks @androw)
- **fix(cli):** register openclaw in the CLI tool-detector so it appears in `omniroute status` alongside its existing API and config support ([#2833](https://github.com/diegosouzapw/OmniRoute/issues/2833))
- **oauth (windsurf):** hotfix Windsurf login — drop the dead PKCE flow and promote the import-token flow as the default ([#2884](https://github.com/diegosouzapw/OmniRoute/pull/2884) — thanks @yunaamelia)
- **antigravity:** normalize textual SSE tool calls and classify Gemini Antigravity resource exhaustion as a model lockout instead of a connection failure ([#2828](https://github.com/diegosouzapw/OmniRoute/pull/2828) — thanks @Ardem2025)
@@ -1018,33 +1082,33 @@ A special thanks to everyone who contributed code, reviews, and tests for this r
A special thanks to everyone who contributed to this release. Ranked by commits since `v3.8.6` (105 commits total):
-| Contributor | Commits | PRs |
-| --- | ---: | --- |
-| [@diegosouzapw](https://github.com/diegosouzapw) | 38 | maintainer — releases, upstream ports & fixes |
-| [@oyi77](https://github.com/oyi77) | 10 | #2887, #2862, #2866, #2837, #2885, #2792, #2793 |
-| [@yunaamelia](https://github.com/yunaamelia) | 7 | #2884 |
-| [@herjarsa](https://github.com/herjarsa) | 6 | #2868, #2886, #2865, #2860, #2857, #2801 |
-| [@leninejunior](https://github.com/leninejunior) | 4 | #2818, #2824, #2825, #2816 |
-| [@jeferssonlemes](https://github.com/jeferssonlemes) | 3 | #2791, #2802, #2815, #2817 |
-| [@rdself](https://github.com/rdself) | 3 | #2874, #2875, #2880 |
-| Dmitry Kuznetsov | 3 | textual tool-call & lockout hardening |
-| [@apoapostolov](https://github.com/apoapostolov) | 2 | #2799, #2800 |
-| [@unitythemaker](https://github.com/unitythemaker) | 2 | #2904 |
-| Nikolay Alafuzov | 2 | reasoning interleaved gating |
-| [@Tushar49](https://github.com/Tushar49) | 2 | #2854, #2855, #2807 |
-| [@guanbear](https://github.com/guanbear) | 2 | #2908 |
-| [@soyelmismo](https://github.com/soyelmismo) | 2 | #2903, #2842 |
-| [@RajvardhanPatil07](https://github.com/RajvardhanPatil07) | 1 | #2861 |
-| [@mugnimaestra](https://github.com/mugnimaestra) | 1 | #2888 |
-| [@dhaern](https://github.com/dhaern) | 1 | #2878 |
-| [@hartmark](https://github.com/hartmark) | 1 | #2795, #2771 |
-| [@marchlhw](https://github.com/marchlhw) | 1 | #2821 |
-| [@alltomatos](https://github.com/alltomatos) | 1 | i18n pt-BR |
-| [@akarray](https://github.com/akarray) | 1 | #2796 |
-| [@gogones](https://github.com/gogones) | 1 | #2845 |
-| [@disonjer](https://github.com/disonjer) | 1 | #2840 |
-| [@nickwizard](https://github.com/nickwizard) | 1 | #2841 |
-| [@levonk](https://github.com/levonk) | 1 | #2806 |
+| Contributor | Commits | PRs |
+| ---------------------------------------------------------- | ------: | ----------------------------------------------- |
+| [@diegosouzapw](https://github.com/diegosouzapw) | 38 | maintainer — releases, upstream ports & fixes |
+| [@oyi77](https://github.com/oyi77) | 10 | #2887, #2862, #2866, #2837, #2885, #2792, #2793 |
+| [@yunaamelia](https://github.com/yunaamelia) | 7 | #2884 |
+| [@herjarsa](https://github.com/herjarsa) | 6 | #2868, #2886, #2865, #2860, #2857, #2801 |
+| [@leninejunior](https://github.com/leninejunior) | 4 | #2818, #2824, #2825, #2816 |
+| [@jeferssonlemes](https://github.com/jeferssonlemes) | 3 | #2791, #2802, #2815, #2817 |
+| [@rdself](https://github.com/rdself) | 3 | #2874, #2875, #2880 |
+| Dmitry Kuznetsov | 3 | textual tool-call & lockout hardening |
+| [@apoapostolov](https://github.com/apoapostolov) | 2 | #2799, #2800 |
+| [@unitythemaker](https://github.com/unitythemaker) | 2 | #2904 |
+| Nikolay Alafuzov | 2 | reasoning interleaved gating |
+| [@Tushar49](https://github.com/Tushar49) | 2 | #2854, #2855, #2807 |
+| [@guanbear](https://github.com/guanbear) | 2 | #2908 |
+| [@soyelmismo](https://github.com/soyelmismo) | 2 | #2903, #2842 |
+| [@RajvardhanPatil07](https://github.com/RajvardhanPatil07) | 1 | #2861 |
+| [@mugnimaestra](https://github.com/mugnimaestra) | 1 | #2888 |
+| [@dhaern](https://github.com/dhaern) | 1 | #2878 |
+| [@hartmark](https://github.com/hartmark) | 1 | #2795, #2771 |
+| [@marchlhw](https://github.com/marchlhw) | 1 | #2821 |
+| [@alltomatos](https://github.com/alltomatos) | 1 | i18n pt-BR |
+| [@akarray](https://github.com/akarray) | 1 | #2796 |
+| [@gogones](https://github.com/gogones) | 1 | #2845 |
+| [@disonjer](https://github.com/disonjer) | 1 | #2840 |
+| [@nickwizard](https://github.com/nickwizard) | 1 | #2841 |
+| [@levonk](https://github.com/levonk) | 1 | #2806 |
_Reviews & additional contributions: @androw, @Ardem2025, @InkshadeWoods._
A special thanks to everyone who contributed code, reviews, and tests for this release:
@@ -1082,7 +1146,6 @@ A special thanks to everyone who contributed code, reviews, and tests for this r
A special thanks to everyone who contributed code, reviews, and tests for this release:
@akarray, @hartmark, @hijak, @JxnLexn, @kjhq, @rdself, @thanet-s
-
---
## [3.8.4] — 2026-05-26
diff --git a/docs/i18n/ar/CHANGELOG.md b/docs/i18n/ar/CHANGELOG.md
index 1cfab7e70b..087aa8fe97 100644
--- a/docs/i18n/ar/CHANGELOG.md
+++ b/docs/i18n/ar/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/az/CHANGELOG.md b/docs/i18n/az/CHANGELOG.md
index 3b29b29bfa..6c3e4d337c 100644
--- a/docs/i18n/az/CHANGELOG.md
+++ b/docs/i18n/az/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/bg/CHANGELOG.md b/docs/i18n/bg/CHANGELOG.md
index 3b29b29bfa..6c3e4d337c 100644
--- a/docs/i18n/bg/CHANGELOG.md
+++ b/docs/i18n/bg/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/bn/CHANGELOG.md b/docs/i18n/bn/CHANGELOG.md
index b07767b2c5..d1e38220e5 100644
--- a/docs/i18n/bn/CHANGELOG.md
+++ b/docs/i18n/bn/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/cs/CHANGELOG.md b/docs/i18n/cs/CHANGELOG.md
index e6098ae41c..856d776d61 100644
--- a/docs/i18n/cs/CHANGELOG.md
+++ b/docs/i18n/cs/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/da/CHANGELOG.md b/docs/i18n/da/CHANGELOG.md
index 2e08ce2cba..420b57b239 100644
--- a/docs/i18n/da/CHANGELOG.md
+++ b/docs/i18n/da/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/de/CHANGELOG.md b/docs/i18n/de/CHANGELOG.md
index a69c70c8e0..dd29ccc899 100644
--- a/docs/i18n/de/CHANGELOG.md
+++ b/docs/i18n/de/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/es/CHANGELOG.md b/docs/i18n/es/CHANGELOG.md
index 7e11043430..cbc8be128d 100644
--- a/docs/i18n/es/CHANGELOG.md
+++ b/docs/i18n/es/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/fa/CHANGELOG.md b/docs/i18n/fa/CHANGELOG.md
index 255bb62609..7b8246e1e4 100644
--- a/docs/i18n/fa/CHANGELOG.md
+++ b/docs/i18n/fa/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/fi/CHANGELOG.md b/docs/i18n/fi/CHANGELOG.md
index e2622b2a5c..9ae8fc57e6 100644
--- a/docs/i18n/fi/CHANGELOG.md
+++ b/docs/i18n/fi/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/fr/CHANGELOG.md b/docs/i18n/fr/CHANGELOG.md
index 4f67ca09de..12446f97d8 100644
--- a/docs/i18n/fr/CHANGELOG.md
+++ b/docs/i18n/fr/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/gu/CHANGELOG.md b/docs/i18n/gu/CHANGELOG.md
index 6df9e404fb..f7115d78d2 100644
--- a/docs/i18n/gu/CHANGELOG.md
+++ b/docs/i18n/gu/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/he/CHANGELOG.md b/docs/i18n/he/CHANGELOG.md
index 8dbc0d6d52..ce4f834626 100644
--- a/docs/i18n/he/CHANGELOG.md
+++ b/docs/i18n/he/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/hi/CHANGELOG.md b/docs/i18n/hi/CHANGELOG.md
index 7805c4af00..67952135d7 100644
--- a/docs/i18n/hi/CHANGELOG.md
+++ b/docs/i18n/hi/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/hu/CHANGELOG.md b/docs/i18n/hu/CHANGELOG.md
index 539f22e96f..4153d89e7a 100644
--- a/docs/i18n/hu/CHANGELOG.md
+++ b/docs/i18n/hu/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/id/CHANGELOG.md b/docs/i18n/id/CHANGELOG.md
index 625e8ebea5..1a4946a8a8 100644
--- a/docs/i18n/id/CHANGELOG.md
+++ b/docs/i18n/id/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/in/CHANGELOG.md b/docs/i18n/in/CHANGELOG.md
index b7dc11289f..287f5e74ad 100644
--- a/docs/i18n/in/CHANGELOG.md
+++ b/docs/i18n/in/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/it/CHANGELOG.md b/docs/i18n/it/CHANGELOG.md
index e6dbca0c37..ea20c5e0a9 100644
--- a/docs/i18n/it/CHANGELOG.md
+++ b/docs/i18n/it/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ja/CHANGELOG.md b/docs/i18n/ja/CHANGELOG.md
index fcefa3572e..bee3830813 100644
--- a/docs/i18n/ja/CHANGELOG.md
+++ b/docs/i18n/ja/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ko/CHANGELOG.md b/docs/i18n/ko/CHANGELOG.md
index b5c0e18a64..2d4a4bc119 100644
--- a/docs/i18n/ko/CHANGELOG.md
+++ b/docs/i18n/ko/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/mr/CHANGELOG.md b/docs/i18n/mr/CHANGELOG.md
index 3f22ab050f..2d6d31b79b 100644
--- a/docs/i18n/mr/CHANGELOG.md
+++ b/docs/i18n/mr/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ms/CHANGELOG.md b/docs/i18n/ms/CHANGELOG.md
index 1a67082ce6..941dbf55ec 100644
--- a/docs/i18n/ms/CHANGELOG.md
+++ b/docs/i18n/ms/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/nl/CHANGELOG.md b/docs/i18n/nl/CHANGELOG.md
index 89c258d8dd..c957a171fd 100644
--- a/docs/i18n/nl/CHANGELOG.md
+++ b/docs/i18n/nl/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/no/CHANGELOG.md b/docs/i18n/no/CHANGELOG.md
index a0c44a40fb..2620b21135 100644
--- a/docs/i18n/no/CHANGELOG.md
+++ b/docs/i18n/no/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/phi/CHANGELOG.md b/docs/i18n/phi/CHANGELOG.md
index 30a29f311f..d149e3c9e0 100644
--- a/docs/i18n/phi/CHANGELOG.md
+++ b/docs/i18n/phi/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/pl/CHANGELOG.md b/docs/i18n/pl/CHANGELOG.md
index f6a3b6a827..0688bb4b92 100644
--- a/docs/i18n/pl/CHANGELOG.md
+++ b/docs/i18n/pl/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/pt-BR/CHANGELOG.md b/docs/i18n/pt-BR/CHANGELOG.md
index 32fb1ef583..afeeb61e5b 100644
--- a/docs/i18n/pt-BR/CHANGELOG.md
+++ b/docs/i18n/pt-BR/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/pt/CHANGELOG.md b/docs/i18n/pt/CHANGELOG.md
index 136ca1e910..46cd4ffbf2 100644
--- a/docs/i18n/pt/CHANGELOG.md
+++ b/docs/i18n/pt/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ro/CHANGELOG.md b/docs/i18n/ro/CHANGELOG.md
index adc758d997..ee4c92d430 100644
--- a/docs/i18n/ro/CHANGELOG.md
+++ b/docs/i18n/ro/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ru/CHANGELOG.md b/docs/i18n/ru/CHANGELOG.md
index a07795f8a1..31a5da7e2d 100644
--- a/docs/i18n/ru/CHANGELOG.md
+++ b/docs/i18n/ru/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/sk/CHANGELOG.md b/docs/i18n/sk/CHANGELOG.md
index 0c25e47a48..63117457b1 100644
--- a/docs/i18n/sk/CHANGELOG.md
+++ b/docs/i18n/sk/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/sv/CHANGELOG.md b/docs/i18n/sv/CHANGELOG.md
index 791ecf4f83..f071c2e757 100644
--- a/docs/i18n/sv/CHANGELOG.md
+++ b/docs/i18n/sv/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/sw/CHANGELOG.md b/docs/i18n/sw/CHANGELOG.md
index 56dece5f42..6307211fb3 100644
--- a/docs/i18n/sw/CHANGELOG.md
+++ b/docs/i18n/sw/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ta/CHANGELOG.md b/docs/i18n/ta/CHANGELOG.md
index 5e8935c520..bb5ca0b214 100644
--- a/docs/i18n/ta/CHANGELOG.md
+++ b/docs/i18n/ta/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/te/CHANGELOG.md b/docs/i18n/te/CHANGELOG.md
index d3c0814e26..926726b61f 100644
--- a/docs/i18n/te/CHANGELOG.md
+++ b/docs/i18n/te/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/th/CHANGELOG.md b/docs/i18n/th/CHANGELOG.md
index 340f21de7e..ef1d0a62ce 100644
--- a/docs/i18n/th/CHANGELOG.md
+++ b/docs/i18n/th/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/tr/CHANGELOG.md b/docs/i18n/tr/CHANGELOG.md
index 7aa6322885..1eb1306787 100644
--- a/docs/i18n/tr/CHANGELOG.md
+++ b/docs/i18n/tr/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/uk-UA/CHANGELOG.md b/docs/i18n/uk-UA/CHANGELOG.md
index 55e35c0467..e606dd07dd 100644
--- a/docs/i18n/uk-UA/CHANGELOG.md
+++ b/docs/i18n/uk-UA/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/ur/CHANGELOG.md b/docs/i18n/ur/CHANGELOG.md
index 3f29ab46ec..21e84b8e72 100644
--- a/docs/i18n/ur/CHANGELOG.md
+++ b/docs/i18n/ur/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/vi/CHANGELOG.md b/docs/i18n/vi/CHANGELOG.md
index 218477da41..ba1ca85bcc 100644
--- a/docs/i18n/vi/CHANGELOG.md
+++ b/docs/i18n/vi/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/i18n/zh-CN/CHANGELOG.md b/docs/i18n/zh-CN/CHANGELOG.md
index 36d5fb4746..630537e06f 100644
--- a/docs/i18n/zh-CN/CHANGELOG.md
+++ b/docs/i18n/zh-CN/CHANGELOG.md
@@ -4,6 +4,12 @@
---
+## [3.8.22] — TBD
+
+_See English CHANGELOG for v3.8.22 details._
+
+---
+
## [3.8.21] — 2026-06-11
_See [English CHANGELOG](/CHANGELOG.md) for v3.8.21 details._
diff --git a/docs/reference/ENVIRONMENT.md b/docs/reference/ENVIRONMENT.md
index b014560092..333bc4b697 100644
--- a/docs/reference/ENVIRONMENT.md
+++ b/docs/reference/ENVIRONMENT.md
@@ -52,13 +52,13 @@ lastUpdated: 2026-05-13
These **must** be set before the first run. Without them, the application will either refuse to start or operate with insecure defaults.
-| Variable | Required | Default | Source File | Description |
-| ---------------------------- | -------------------- | ---------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `JWT_SECRET` | **Yes** | _(none)_ | `src/lib/auth` | Signs/verifies all dashboard session cookies (JWT). Generate with `openssl rand -base64 48`. |
-| `API_KEY_SECRET` | **Yes** | _(none)_ | `src/lib/db/apiKeys.ts` | AES encryption key for API key values at rest in SQLite. Generate with `openssl rand -hex 32`. |
-| `INITIAL_PASSWORD` | **Yes** | `CHANGEME` | Bootstrap script | Sets the initial admin dashboard password (matches `.env.example` default — kept obviously insecure to force a change). **Change before first use.** After login, change via Dashboard → Settings → Security. |
-| `OMNIROUTE_WS_BRIDGE_SECRET` | **Yes** (production) | _(unset)_ | `src/app/api/internal/codex-responses-ws/route.ts` | Shared secret for the internal Codex Responses WebSocket bridge. Authenticates bridge requests between the Electron/browser WS relay and OmniRoute. ⚠️ **REQUIRED in production — when unset, all WS bridge requests are rejected.** Generate with `openssl rand -base64 32`. |
-| `OMNIROUTE_PEER_STAMP_TOKEN` | No (auto) | _(auto per boot)_ | `src/server/authz/policies/management.ts` | Per-process secret proving the trusted peer-IP stamp came from OmniRoute's own HTTP server (`scripts/dev/peer-stamp.mjs`). The authz middleware trusts request locality (loopback/LAN gating of LOCAL_ONLY routes) only when the stamp carries this token. Auto-generated each boot — leave unset; only pin it for multi-process setups that must share the stamp. |
+| Variable | Required | Default | Source File | Description |
+| ---------------------------- | -------------------- | ----------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `JWT_SECRET` | **Yes** | _(none)_ | `src/lib/auth` | Signs/verifies all dashboard session cookies (JWT). Generate with `openssl rand -base64 48`. |
+| `API_KEY_SECRET` | **Yes** | _(none)_ | `src/lib/db/apiKeys.ts` | AES encryption key for API key values at rest in SQLite. Generate with `openssl rand -hex 32`. |
+| `INITIAL_PASSWORD` | **Yes** | `CHANGEME` | Bootstrap script | Sets the initial admin dashboard password (matches `.env.example` default — kept obviously insecure to force a change). **Change before first use.** After login, change via Dashboard → Settings → Security. |
+| `OMNIROUTE_WS_BRIDGE_SECRET` | **Yes** (production) | _(unset)_ | `src/app/api/internal/codex-responses-ws/route.ts` | Shared secret for the internal Codex Responses WebSocket bridge. Authenticates bridge requests between the Electron/browser WS relay and OmniRoute. ⚠️ **REQUIRED in production — when unset, all WS bridge requests are rejected.** Generate with `openssl rand -base64 32`. |
+| `OMNIROUTE_PEER_STAMP_TOKEN` | No (auto) | _(auto per boot)_ | `src/server/authz/policies/management.ts` | Per-process secret proving the trusted peer-IP stamp came from OmniRoute's own HTTP server (`scripts/dev/peer-stamp.mjs`). The authz middleware trusts request locality (loopback/LAN gating of LOCAL_ONLY routes) only when the stamp carries this token. Auto-generated each boot — leave unset; only pin it for multi-process setups that must share the stamp. |
### Generation Commands
@@ -224,11 +224,12 @@ OmniRoute provides a two-layer defense: request-side injection scanning and resp
## 6. Tool & Routing Policies
-| Variable | Default | Source File | Description |
-| ----------------------------------- | ---------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
-| `TOOL_POLICY_MODE` | `disabled` | `src/lib/toolPolicy.ts` | Controls LLM tool/function-calling access. `allowlist` = only listed tools, `denylist` = all except listed, `disabled` = no restrictions. |
-| `OMNIROUTE_PAYLOAD_RULES_PATH` | `./config/payloadRules.json` | `open-sse/services/payloadRules.ts` | Path to payload manipulation rules JSON file (per-model/protocol upstream tweaks). |
-| `OMNIROUTE_PAYLOAD_RULES_RELOAD_MS` | `5000` | `open-sse/services/payloadRules.ts` | Reload interval (ms) for hot-reloading the payload rules file. Minimum `1000`. |
+| Variable | Default | Source File | Description |
+| ----------------------------------------------------------- | ---------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `TOOL_POLICY_MODE` | `disabled` | `src/lib/toolPolicy.ts` | Controls LLM tool/function-calling access. `allowlist` = only listed tools, `denylist` = all except listed, `disabled` = no restrictions. |
+| `OMNIROUTE_PAYLOAD_RULES_PATH` | `./config/payloadRules.json` | `open-sse/services/payloadRules.ts` | Path to payload manipulation rules JSON file (per-model/protocol upstream tweaks). |
+| `OMNIROUTE_PAYLOAD_RULES_RELOAD_MS` | `5000` | `open-sse/services/payloadRules.ts` | Reload interval (ms) for hot-reloading the payload rules file. Minimum `1000`. |
+| `OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS` | `false` | `open-sse/services/model.ts` | Opt-in: route bare `claude-*` model IDs from Claude Code clients through the Claude Code OAuth account instead of requiring a provider prefix. Explicit provider prefixes still win. Also configurable via a dashboard toggle on the Claude provider page. |
---
@@ -240,9 +241,9 @@ OmniRoute provides a two-layer defense: request-side injection scanning and resp
| `CLOUD_URL` | _(empty)_ | `src/lib/cloudSync.ts` | Cloud relay endpoint URL (premium feature). |
| `CLOUD_SYNC_TIMEOUT_MS` | `12000` | `src/lib/cloudSync.ts` | HTTP timeout for cloud sync requests. |
| `OMNIROUTE_BUILD_PROFILE` | `full` | Webpack build config | Build-time profile (set to `minimal` to physically exclude privileged modules from bundle). |
-| `OMNIROUTE_CLOUD_SYNC_SECRET` | _(empty)_ | `src/lib/cloudSync.ts` | Shared secret used to verify the HMAC-SHA256 signature of Cloud Sync responses. |
-| `OMNIROUTE_CLOUD_SYNC_SECRETS` | `false` | `src/lib/cloudSync.ts` | Set to `true` to allow the Cloud Sync endpoint to overwrite local credentials. Default is `false`. |
-| `OMNIROUTE_ZED_IMPORT_LEGACY_ONE_STEP` | `false` | `src/app/api/providers/zed/import/route.ts` | Set to `true` to fall back to the v3.8.5 one-step "import everything" behavior without user confirmation. |
+| `OMNIROUTE_CLOUD_SYNC_SECRET` | _(empty)_ | `src/lib/cloudSync.ts` | Shared secret used to verify the HMAC-SHA256 signature of Cloud Sync responses. |
+| `OMNIROUTE_CLOUD_SYNC_SECRETS` | `false` | `src/lib/cloudSync.ts` | Set to `true` to allow the Cloud Sync endpoint to overwrite local credentials. Default is `false`. |
+| `OMNIROUTE_ZED_IMPORT_LEGACY_ONE_STEP` | `false` | `src/app/api/providers/zed/import/route.ts` | Set to `true` to fall back to the v3.8.5 one-step "import everything" behavior without user confirmation. |
| `NEXT_PUBLIC_BASE_URL` | `http://localhost:20128` | OAuth, Dashboard, sync | Public-facing URL for OAuth redirect_uri, Dashboard links. **Must match your public URL behind reverse proxy.** |
| `NEXT_PUBLIC_CLOUD_URL` | _(empty)_ | Client-side | Client-side mirror of `CLOUD_URL`. |
| `NEXT_PUBLIC_APP_URL` | _(unset)_ | `src/shared/services/cloudSyncScheduler.ts` | Legacy fallback for `NEXT_PUBLIC_BASE_URL`. |
@@ -293,22 +294,23 @@ Route upstream LLM provider calls through an HTTP or SOCKS5 proxy for egress con
Controls how OmniRoute discovers and launches CLI sidecars (Claude Code, Codex, etc.).
-| Variable | Default | Source File | Description |
-| ------------------------- | ---------- | ----------------------------------- | ---------------------------------------------------------------------------------- |
-| `CLI_MODE` | `auto` | `src/shared/services/cliRuntime.ts` | `auto` = search system PATH; `manual` = use explicit paths only. |
-| `CLI_EXTRA_PATHS` | _(unset)_ | `src/shared/services/cliRuntime.ts` | Additional PATH entries for CLI binary discovery (colon-separated). |
-| `CLI_CONFIG_HOME` | _(unset)_ | `src/shared/services/cliRuntime.ts` | Override home directory for reading CLI configs (`~/.claude`, `~/.codex`). |
-| `CLI_ALLOW_CONFIG_WRITES` | `false` | `src/shared/services/cliRuntime.ts` | Allow OmniRoute to write CLI config files (token refresh, session data). |
-| `CLI_CLAUDE_BIN` | `claude` | `src/shared/services/cliRuntime.ts` | Custom path to Claude CLI binary. |
-| `CLI_CODEX_BIN` | `codex` | `src/shared/services/cliRuntime.ts` | Custom path to Codex CLI binary. |
-| `CLI_DROID_BIN` | `droid` | `src/shared/services/cliRuntime.ts` | Custom path to Droid CLI binary. |
-| `CLI_OPENCLAW_BIN` | `openclaw` | `src/shared/services/cliRuntime.ts` | Custom path to OpenClaw CLI binary. |
-| `CLI_CURSOR_BIN` | `agent` | `src/shared/services/cliRuntime.ts` | Custom path to Cursor agent binary. |
-| `CLI_CLINE_BIN` | `cline` | `src/shared/services/cliRuntime.ts` | Custom path to Cline CLI binary. |
-| `CLI_CONTINUE_BIN` | `cn` | `src/shared/services/cliRuntime.ts` | Custom path to Continue CLI binary. |
-| `CLI_QODER_BIN` | `qoder` | `src/shared/services/cliRuntime.ts` | Custom path to Qoder CLI binary. |
-| `CLI_QWEN_BIN` | `qwen` | `src/shared/services/cliRuntime.ts` | Custom path to the Qwen Code CLI binary. |
-| `CLI_DEVIN_BIN` | `devin` | `open-sse/executors/devin-cli.ts` | Custom path to the Devin CLI binary (v3.8.0). Used by the Windsurf/Devin executor. |
+| Variable | Default | Source File | Description |
+| ------------------------- | ----------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `CLI_MODE` | `auto` | `src/shared/services/cliRuntime.ts` | `auto` = search system PATH; `manual` = use explicit paths only. |
+| `CLI_EXTRA_PATHS` | _(unset)_ | `src/shared/services/cliRuntime.ts` | Additional PATH entries for CLI binary discovery (colon-separated). |
+| `CLI_CONFIG_HOME` | _(unset)_ | `src/shared/services/cliRuntime.ts` | Override home directory for reading CLI configs (`~/.claude`, `~/.codex`). |
+| `CLI_ALLOW_CONFIG_WRITES` | `false` | `src/shared/services/cliRuntime.ts` | Allow OmniRoute to write CLI config files (token refresh, session data). |
+| `CLI_CLAUDE_BIN` | `claude` | `src/shared/services/cliRuntime.ts` | Custom path to Claude CLI binary. |
+| `CLI_CODEX_BIN` | `codex` | `src/shared/services/cliRuntime.ts` | Custom path to Codex CLI binary. |
+| `CLI_DROID_BIN` | `droid` | `src/shared/services/cliRuntime.ts` | Custom path to Droid CLI binary. |
+| `CLI_OPENCLAW_BIN` | `openclaw` | `src/shared/services/cliRuntime.ts` | Custom path to OpenClaw CLI binary. |
+| `CLI_CURSOR_BIN` | `agent` | `src/shared/services/cliRuntime.ts` | Custom path to Cursor agent binary. |
+| `CLI_CLINE_BIN` | `cline` | `src/shared/services/cliRuntime.ts` | Custom path to Cline CLI binary. |
+| `CLI_CONTINUE_BIN` | `cn` | `src/shared/services/cliRuntime.ts` | Custom path to Continue CLI binary. |
+| `CLI_QODER_BIN` | `qoder` | `src/shared/services/cliRuntime.ts` | Custom path to Qoder CLI binary. |
+| `CLI_QWEN_BIN` | `qwen` | `src/shared/services/cliRuntime.ts` | Custom path to the Qwen Code CLI binary. |
+| `CLI_DEVIN_BIN` | `devin` | `open-sse/executors/devin-cli.ts` | Custom path to the Devin CLI binary (v3.8.0). Used by the Windsurf/Devin executor. |
+| `HERMES_HOME` | `~/.hermes` | `src/lib/cli-helper/config-generator/hermesHome.ts` | Hermes Agent home directory where OmniRoute reads/writes the Hermes CLI config. Matches the env var the Hermes PowerShell installer sets on Windows (`%LOCALAPPDATA%\hermes`). |
### Docker Example
@@ -325,45 +327,45 @@ CLI_CLAUDE_BIN=/host-cli/bin/claude
These variables tune the `omniroute` CLI binary's own behavior (not the sidecar
detection above).
-| Variable | Default | Source File | Description |
-| --------------------------- | ---------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
-| `OMNIROUTE_LANG` | _(system)_ | `bin/cli/i18n.mjs` | Force CLI output language. BCP-47 locale (e.g. `en`, `pt-BR`). Overrides system locale env vars (LC_ALL, LC_MESSAGES). |
-| `OMNIROUTE_SHOW_LOG` | _(unset)_ | `bin/cli/runtime/processSupervisor.mjs` | Set to `1` to forward server stdout/stderr to the terminal in supervised mode. Equivalent to `--log` flag on `omniroute serve`. |
-| `OMNIROUTE_CLI_TOKEN` | _(unset)_ | `bin/cli/api.mjs` | Machine-auth token injected as `x-omniroute-cli-token` header. Auto-generated in task 8.12. |
-| `OMNIROUTE_HTTP_TIMEOUT_MS` | `30000` | `bin/cli/api.mjs` | Per-attempt HTTP timeout (ms) for CLI → server requests. |
-| `OMNIROUTE_VERBOSE` | `0` | `bin/cli/api.mjs` | Set to `1` to print retry/backoff diagnostics to stderr during CLI commands. |
-| `OMNIROUTE_PLUGIN_PATH` | _(unset)_ | `bin/cli/plugins.mjs` | Custom directory for CLI plugin discovery (`omniroute-cmd-*` packages). Defaults to `~/.omniroute/plugins/` when unset. |
-| `OMNIROUTE_PLUGINS_ALLOW_EXEC` | `0` | `src/lib/plugins/pluginWorker.ts` | Set to `1` to allow plugins to request the `exec` permission (spawn child processes from the worker sandbox). Local operator only. |
+| Variable | Default | Source File | Description |
+| ------------------------------ | ---------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
+| `OMNIROUTE_LANG` | _(system)_ | `bin/cli/i18n.mjs` | Force CLI output language. BCP-47 locale (e.g. `en`, `pt-BR`). Overrides system locale env vars (LC_ALL, LC_MESSAGES). |
+| `OMNIROUTE_SHOW_LOG` | _(unset)_ | `bin/cli/runtime/processSupervisor.mjs` | Set to `1` to forward server stdout/stderr to the terminal in supervised mode. Equivalent to `--log` flag on `omniroute serve`. |
+| `OMNIROUTE_CLI_TOKEN` | _(unset)_ | `bin/cli/api.mjs` | Machine-auth token injected as `x-omniroute-cli-token` header. Auto-generated in task 8.12. |
+| `OMNIROUTE_HTTP_TIMEOUT_MS` | `30000` | `bin/cli/api.mjs` | Per-attempt HTTP timeout (ms) for CLI → server requests. |
+| `OMNIROUTE_VERBOSE` | `0` | `bin/cli/api.mjs` | Set to `1` to print retry/backoff diagnostics to stderr during CLI commands. |
+| `OMNIROUTE_PLUGIN_PATH` | _(unset)_ | `bin/cli/plugins.mjs` | Custom directory for CLI plugin discovery (`omniroute-cmd-*` packages). Defaults to `~/.omniroute/plugins/` when unset. |
+| `OMNIROUTE_PLUGINS_ALLOW_EXEC` | `0` | `src/lib/plugins/pluginWorker.ts` | Set to `1` to allow plugins to request the `exec` permission (spawn child processes from the worker sandbox). Local operator only. |
---
## 10. Internal Agent & MCP Integrations
-| Variable | Default | Source File | Description |
-| ----------------------------------------------- | ----------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
-| `OMNIROUTE_BASE_URL` | auto-detect | `open-sse/mcp-server/server.ts` | Explicit URL for MCP/A2A tools to reach OmniRoute. Overrides localhost auto-detection. |
-| `OMNIROUTE_API_KEY` | _(unset)_ | MCP/A2A modules | API key for internal MCP tool and A2A skill calls. |
-| `OMNIROUTE_API_KEY_ID` | _(unset)_ | `open-sse/mcp-server/audit.ts` | Key ID for MCP audit log attribution. |
-| `ROUTER_API_KEY` | _(unset)_ | Legacy | Legacy alias for `OMNIROUTE_API_KEY`. |
-| `OMNIROUTE_MCP_ENFORCE_SCOPES` | `false` | `open-sse/mcp-server/server.ts` | Enforce scope-based access control on MCP tool calls. |
-| `OMNIROUTE_MCP_SCOPES` | _(all)_ | `open-sse/mcp-server/server.ts` | Comma-separated scopes: `admin`, `combos`, `health`, `models`, `routing`, `budget`, `metrics`, `pricing`, `memory`, `skills`. |
-| `OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS` | enabled | `open-sse/mcp-server/descriptionCompressor.ts` | Compress MCP tool descriptions before serializing the manifest. Disable values: `0`, `false`, `off`. |
-| `OMNIROUTE_MCP_DESCRIPTION_COMPRESSION` | `rtk` | `open-sse/mcp-server/descriptionCompressor.ts` | Compression algorithm/profile. Disable values: `0`, `false`, `off`. |
-| `MODEL_SYNC_INTERVAL_HOURS` | `24` | `src/shared/services/modelSyncScheduler.ts` | Model catalog sync interval in hours. |
-| `PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES` | `70` | `src/server-init.ts` | Provider rate-limit and quota polling interval. |
-| `PROVIDER_LIMITS_SYNC_SPACING_MS` | `1500` | `src/lib/usage/providerLimits.ts` | Gap (ms) between consecutive OAuth quota fetches in a bulk sync; OAuth connections are fetched one at a time to avoid bursting an upstream. `0` opts out (concurrent). |
-| `PROVIDER_LIMITS_POST_USAGE_REFRESH_DELAY_MS` | `5000` | `src/lib/usage/providerLimits.ts` | Delay (ms) before refreshing provider limits after a real usage event, giving the upstream quota API time to register consumption. |
-| `OMNIROUTE_DISABLE_BACKGROUND_SERVICES` | `false` | `src/instrumentation-node.ts` | Disable all background services (sync, pricing, model refresh). Useful for CI/test. |
-| `OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS` | _(unset)_ | `src/lib/config/runtimeSettings.ts` | Force background tasks on under automated test detection. Set `1` to override the test heuristic. |
-| `OMNIROUTE_BUDGET_RESET_JOB_INTERVAL_MS` | `600000` | `src/lib/jobs/budgetResetJob.ts` | Budget reset check cadence (ms). Floor `10000`. |
-| `OMNIROUTE_REASONING_CACHE_CLEANUP_INTERVAL_MS` | `1800000` | `src/lib/jobs/reasoningCacheCleanupJob.ts` | Reasoning cache cleanup cadence (ms). Floor `60000`. |
-| `OMNIROUTE_CONFIG_HOT_RELOAD_MS` | `5000` | `src/lib/config/hotReload.ts` | Polling interval (ms) for config hot-reload. Lower than `1000` is rejected. |
-| `OMNIROUTE_DISABLE_REDIS_AUTH_CACHE` | _(enabled)_ | `src/lib/db/apiKeys.ts` | Set `1` to bypass the Redis-backed API-key auth cache (forces DB reads). |
-| `OMNIROUTE_RTK_TRUST_PROJECT_FILTERS` | `0` | `open-sse/services/compression/engines/rtk/filterLoader.ts` | Trust user-managed RTK project filter rules without strict signature checks. |
-| `OMNIROUTE_BOOTSTRAPPED` | `false` | `src/app/(dashboard)/dashboard/page.tsx` | Set `true` by bootstrap script after initial setup. Controls setup wizard visibility. |
-| `OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE` | `0` | `open-sse/executors/antigravity.ts` | Escape hatch: allow request body to override the Antigravity project field. |
-| `ANTIGRAVITY_CREDITS` | _(unset)_ | `open-sse/services/antigravityCredits.ts` | Override Antigravity's advertised remaining credits (testing / forced values). |
-| `AGY_TOKEN_FILE` | `~/.gemini/antigravity-cli/antigravity-oauth-token` | `src/app/api/providers/agy-auth/apply-local/route.ts` | Override the Antigravity CLI (agy) token-file path for the auto-detect local login import. |
+| Variable | Default | Source File | Description |
+| ----------------------------------------------- | --------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OMNIROUTE_BASE_URL` | auto-detect | `open-sse/mcp-server/server.ts` | Explicit URL for MCP/A2A tools to reach OmniRoute. Overrides localhost auto-detection. |
+| `OMNIROUTE_API_KEY` | _(unset)_ | MCP/A2A modules | API key for internal MCP tool and A2A skill calls. |
+| `OMNIROUTE_API_KEY_ID` | _(unset)_ | `open-sse/mcp-server/audit.ts` | Key ID for MCP audit log attribution. |
+| `ROUTER_API_KEY` | _(unset)_ | Legacy | Legacy alias for `OMNIROUTE_API_KEY`. |
+| `OMNIROUTE_MCP_ENFORCE_SCOPES` | `false` | `open-sse/mcp-server/server.ts` | Enforce scope-based access control on MCP tool calls. |
+| `OMNIROUTE_MCP_SCOPES` | _(all)_ | `open-sse/mcp-server/server.ts` | Comma-separated scopes: `admin`, `combos`, `health`, `models`, `routing`, `budget`, `metrics`, `pricing`, `memory`, `skills`. |
+| `OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS` | enabled | `open-sse/mcp-server/descriptionCompressor.ts` | Compress MCP tool descriptions before serializing the manifest. Disable values: `0`, `false`, `off`. |
+| `OMNIROUTE_MCP_DESCRIPTION_COMPRESSION` | `rtk` | `open-sse/mcp-server/descriptionCompressor.ts` | Compression algorithm/profile. Disable values: `0`, `false`, `off`. |
+| `MODEL_SYNC_INTERVAL_HOURS` | `24` | `src/shared/services/modelSyncScheduler.ts` | Model catalog sync interval in hours. |
+| `PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES` | `70` | `src/server-init.ts` | Provider rate-limit and quota polling interval. |
+| `PROVIDER_LIMITS_SYNC_SPACING_MS` | `1500` | `src/lib/usage/providerLimits.ts` | Gap (ms) between consecutive OAuth quota fetches in a bulk sync; OAuth connections are fetched one at a time to avoid bursting an upstream. `0` opts out (concurrent). |
+| `PROVIDER_LIMITS_POST_USAGE_REFRESH_DELAY_MS` | `5000` | `src/lib/usage/providerLimits.ts` | Delay (ms) before refreshing provider limits after a real usage event, giving the upstream quota API time to register consumption. |
+| `OMNIROUTE_DISABLE_BACKGROUND_SERVICES` | `false` | `src/instrumentation-node.ts` | Disable all background services (sync, pricing, model refresh). Useful for CI/test. |
+| `OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS` | _(unset)_ | `src/lib/config/runtimeSettings.ts` | Force background tasks on under automated test detection. Set `1` to override the test heuristic. |
+| `OMNIROUTE_BUDGET_RESET_JOB_INTERVAL_MS` | `600000` | `src/lib/jobs/budgetResetJob.ts` | Budget reset check cadence (ms). Floor `10000`. |
+| `OMNIROUTE_REASONING_CACHE_CLEANUP_INTERVAL_MS` | `1800000` | `src/lib/jobs/reasoningCacheCleanupJob.ts` | Reasoning cache cleanup cadence (ms). Floor `60000`. |
+| `OMNIROUTE_CONFIG_HOT_RELOAD_MS` | `5000` | `src/lib/config/hotReload.ts` | Polling interval (ms) for config hot-reload. Lower than `1000` is rejected. |
+| `OMNIROUTE_DISABLE_REDIS_AUTH_CACHE` | _(enabled)_ | `src/lib/db/apiKeys.ts` | Set `1` to bypass the Redis-backed API-key auth cache (forces DB reads). |
+| `OMNIROUTE_RTK_TRUST_PROJECT_FILTERS` | `0` | `open-sse/services/compression/engines/rtk/filterLoader.ts` | Trust user-managed RTK project filter rules without strict signature checks. |
+| `OMNIROUTE_BOOTSTRAPPED` | `false` | `src/app/(dashboard)/dashboard/page.tsx` | Set `true` by bootstrap script after initial setup. Controls setup wizard visibility. |
+| `OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE` | `0` | `open-sse/executors/antigravity.ts` | Escape hatch: allow request body to override the Antigravity project field. |
+| `ANTIGRAVITY_CREDITS` | _(unset)_ | `open-sse/services/antigravityCredits.ts` | Override Antigravity's advertised remaining credits (testing / forced values). |
+| `AGY_TOKEN_FILE` | `~/.gemini/antigravity-cli/antigravity-oauth-token` | `src/app/api/providers/agy-auth/apply-local/route.ts` | Override the Antigravity CLI (agy) token-file path for the auto-detect local login import. |
### OAuth CLI Bridge (Internal)
@@ -437,20 +439,20 @@ process.env[`${PROVIDER_ID}_USER_AGENT`]
> **Source:** `open-sse/executors/base.ts` → `buildHeaders()`
-| Variable | Default Value | When to Update |
-| ------------------------ | --------------------------------------------- | ------------------------------------------------------------- |
-| `CLAUDE_USER_AGENT` | `claude-cli/2.1.145 (external, cli)` | When Anthropic releases a new CLI version |
-| `CLAUDE_DISABLE_TOOL_NAME_CLOAK` | `false` | `executors/base.ts` + `executors/cliproxyapi.ts` | Set to `1`/`true` to forward third-party harness tool names verbatim to Anthropic on both Anthropic-bound paths (native OAuth and CLIProxyAPI). By default the executor deterministically aliases non-Claude-Code tool names (Claude Code canonical mapping where one exists, otherwise PascalCase) and reverses them on the response via `_toolNameMap`, so harnesses with snake_case tools are not refused as fingerprinted third-party clients. Debugging only. |
-| `CODEX_USER_AGENT` | `codex-cli/0.132.0 (Windows 10.0.26200; x64)` | When OpenAI updates the Codex CLI |
-| `CODEX_CLIENT_VERSION` | `0.131.0` | Override Codex client version independently of full UA string |
-| `GITHUB_USER_AGENT` | `GitHubCopilotChat/0.45.1` | When GitHub Copilot Chat updates |
-| `ANTIGRAVITY_USER_AGENT` | `antigravity/2.0.1 darwin/arm64` | When Antigravity IDE updates |
-| `KIRO_USER_AGENT` | `AWS-SDK-JS/3.0.0 kiro-ide/1.0.0` | When Kiro IDE updates |
-| `KIRO_OAUTH_CLIENT_ID` | `kiro-cli` | Override the Kiro social device-code `clientId` (public id) |
-| `QODER_USER_AGENT` | `Qoder-Cli` | When Qoder CLI updates |
-| `QWEN_USER_AGENT` | `QwenCode/0.15.9 (linux; x64)` | When Qwen Code updates |
-| `CURSOR_USER_AGENT` | `Cursor/3.3` | When Cursor updates |
-| `GEMINI_CLI_USER_AGENT` | `google-api-nodejs-client/10.3.0` | When Google API client updates |
+| Variable | Default Value | When to Update |
+| -------------------------------- | --------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `CLAUDE_USER_AGENT` | `claude-cli/2.1.145 (external, cli)` | When Anthropic releases a new CLI version |
+| `CLAUDE_DISABLE_TOOL_NAME_CLOAK` | `false` | `executors/base.ts` + `executors/cliproxyapi.ts` | Set to `1`/`true` to forward third-party harness tool names verbatim to Anthropic on both Anthropic-bound paths (native OAuth and CLIProxyAPI). By default the executor deterministically aliases non-Claude-Code tool names (Claude Code canonical mapping where one exists, otherwise PascalCase) and reverses them on the response via `_toolNameMap`, so harnesses with snake_case tools are not refused as fingerprinted third-party clients. Debugging only. |
+| `CODEX_USER_AGENT` | `codex-cli/0.132.0 (Windows 10.0.26200; x64)` | When OpenAI updates the Codex CLI |
+| `CODEX_CLIENT_VERSION` | `0.131.0` | Override Codex client version independently of full UA string |
+| `GITHUB_USER_AGENT` | `GitHubCopilotChat/0.45.1` | When GitHub Copilot Chat updates |
+| `ANTIGRAVITY_USER_AGENT` | `antigravity/2.0.1 darwin/arm64` | When Antigravity IDE updates |
+| `KIRO_USER_AGENT` | `AWS-SDK-JS/3.0.0 kiro-ide/1.0.0` | When Kiro IDE updates |
+| `KIRO_OAUTH_CLIENT_ID` | `kiro-cli` | Override the Kiro social device-code `clientId` (public id) |
+| `QODER_USER_AGENT` | `Qoder-Cli` | When Qoder CLI updates |
+| `QWEN_USER_AGENT` | `QwenCode/0.15.9 (linux; x64)` | When Qwen Code updates |
+| `CURSOR_USER_AGENT` | `Cursor/3.3` | When Cursor updates |
+| `GEMINI_CLI_USER_AGENT` | `google-api-nodejs-client/10.3.0` | When Google API client updates |
> [!TIP]
> You can add User-Agent overrides for **any** provider using the pattern `{PROVIDER_ID}_USER_AGENT`. The executor dynamically constructs the env var name.
@@ -538,33 +540,33 @@ REQUEST_TIMEOUT_MS (global override)
└── API_BRIDGE_SERVER_SOCKET_TIMEOUT_MS (default: 0 = disabled)
```
-| Variable | Default | Description |
-| ---------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------- |
-| `REQUEST_TIMEOUT_MS` | _(unset)_ | Global shortcut — overrides both `FETCH_TIMEOUT_MS` and `STREAM_IDLE_TIMEOUT_MS` defaults. |
-| `FETCH_TIMEOUT_MS` | `600000` | Total HTTP request timeout for upstream provider calls. |
-| `STREAM_IDLE_TIMEOUT_MS` | `600000` | Max silence between SSE chunks before aborting. Extended-thinking models rarely pause >90s. |
-| `FETCH_HEADERS_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | Time to receive response headers. |
-| `FETCH_BODY_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | Time to receive the full response body. |
-| `FETCH_CONNECT_TIMEOUT_MS` | `30000` | TCP connection establishment timeout. |
-| `FETCH_KEEPALIVE_TIMEOUT_MS` | `4000` | Keep-alive socket idle timeout. |
-| `TLS_CLIENT_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | TLS fingerprint proxy (wreq-js) timeout. |
-| `API_BRIDGE_PROXY_TIMEOUT_MS` | `30000` | Proxy hop timeout for `/v1` bridge requests. |
-| `API_BRIDGE_SERVER_REQUEST_TIMEOUT_MS` | `300000` | Overall server request timeout for the bridge. |
-| `API_BRIDGE_SERVER_HEADERS_TIMEOUT_MS` | `60000` | Time to send response headers via the bridge. |
-| `API_BRIDGE_SERVER_KEEPALIVE_TIMEOUT_MS` | `5000` | Bridge keep-alive idle timeout. |
-| `API_BRIDGE_SERVER_SOCKET_TIMEOUT_MS` | `0` | Raw socket timeout (0 = disabled). |
-| `SHUTDOWN_TIMEOUT_MS` | `30000` | Grace period on SIGTERM/SIGINT before force-exit. |
-| `OMNIROUTE_DEFAULT_FETCH_TIMEOUT_MS` | `120000` | Fallback used by `src/shared/utils/fetchTimeout.ts` when `FETCH_TIMEOUT_MS` is unset. |
-| `OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`chatgptTlsClient.ts`). |
-| `OMNIROUTE_CHATGPT_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
-| `OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`claudeTlsClient.ts`). |
-| `OMNIROUTE_CLAUDE_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
-| `OMNIROUTE_PPLX_TLS_TIMEOUT_MS` | `30000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`perplexityTlsClient.ts`). |
-| `OMNIROUTE_PPLX_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
-| `OMNIROUTE_GROK_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`grokTlsClient.ts`). |
-| `OMNIROUTE_GROK_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
-| `OMNIROUTE_BROWSER_POOL` | `on` | Shared Playwright browser pool for browser-backed web-cookie chat (`browserPool.ts`); set `off` to disable. |
-| `WEB_COOKIE_USE_BROWSER` | `0` | Opt a web-cookie chat request into the browser-backed path (`browserBackedChat.ts`); `1` to enable. |
+| Variable | Default | Description |
+| ---------------------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------- |
+| `REQUEST_TIMEOUT_MS` | _(unset)_ | Global shortcut — overrides both `FETCH_TIMEOUT_MS` and `STREAM_IDLE_TIMEOUT_MS` defaults. |
+| `FETCH_TIMEOUT_MS` | `600000` | Total HTTP request timeout for upstream provider calls. |
+| `STREAM_IDLE_TIMEOUT_MS` | `600000` | Max silence between SSE chunks before aborting. Extended-thinking models rarely pause >90s. |
+| `FETCH_HEADERS_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | Time to receive response headers. |
+| `FETCH_BODY_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | Time to receive the full response body. |
+| `FETCH_CONNECT_TIMEOUT_MS` | `30000` | TCP connection establishment timeout. |
+| `FETCH_KEEPALIVE_TIMEOUT_MS` | `4000` | Keep-alive socket idle timeout. |
+| `TLS_CLIENT_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | TLS fingerprint proxy (wreq-js) timeout. |
+| `API_BRIDGE_PROXY_TIMEOUT_MS` | `30000` | Proxy hop timeout for `/v1` bridge requests. |
+| `API_BRIDGE_SERVER_REQUEST_TIMEOUT_MS` | `300000` | Overall server request timeout for the bridge. |
+| `API_BRIDGE_SERVER_HEADERS_TIMEOUT_MS` | `60000` | Time to send response headers via the bridge. |
+| `API_BRIDGE_SERVER_KEEPALIVE_TIMEOUT_MS` | `5000` | Bridge keep-alive idle timeout. |
+| `API_BRIDGE_SERVER_SOCKET_TIMEOUT_MS` | `0` | Raw socket timeout (0 = disabled). |
+| `SHUTDOWN_TIMEOUT_MS` | `30000` | Grace period on SIGTERM/SIGINT before force-exit. |
+| `OMNIROUTE_DEFAULT_FETCH_TIMEOUT_MS` | `120000` | Fallback used by `src/shared/utils/fetchTimeout.ts` when `FETCH_TIMEOUT_MS` is unset. |
+| `OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`chatgptTlsClient.ts`). |
+| `OMNIROUTE_CHATGPT_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
+| `OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`claudeTlsClient.ts`). |
+| `OMNIROUTE_CLAUDE_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
+| `OMNIROUTE_PPLX_TLS_TIMEOUT_MS` | `30000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`perplexityTlsClient.ts`). |
+| `OMNIROUTE_PPLX_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
+| `OMNIROUTE_GROK_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`grokTlsClient.ts`). |
+| `OMNIROUTE_GROK_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
+| `OMNIROUTE_BROWSER_POOL` | `on` | Shared Playwright browser pool for browser-backed web-cookie chat (`browserPool.ts`); set `off` to disable. |
+| `WEB_COOKIE_USE_BROWSER` | `0` | Opt a web-cookie chat request into the browser-backed path (`browserBackedChat.ts`); `1` to enable. |
Combo target attempts inherit the resolved upstream request timeout (`FETCH_TIMEOUT_MS`, or
`REQUEST_TIMEOUT_MS` when it supplies the fetch default). Set `targetTimeoutMs` in a combo,
@@ -624,18 +626,18 @@ The logging system writes to both stdout and rotated log files. All configuratio
## 17. Memory Optimization
-| Variable | Default | Description |
-| -------------------------- | ------------------------------- | ---------------------------------------------------------------------- |
-| `OMNIROUTE_MEMORY_MB` | `512` | Runtime V8 heap limit. Docker standalone and `omniroute serve` use it to set `--max-old-space-size`. |
-| `PROMPT_CACHE_MAX_SIZE` | `50` | Max cached system prompt entries. |
-| `PROMPT_CACHE_MAX_BYTES` | `2097152` (2 MB) | Max total prompt cache size. |
-| `PROMPT_CACHE_TTL_MS` | `300000` (5 min) | Prompt cache entry TTL. |
-| `SEMANTIC_CACHE_MAX_SIZE` | `100` | Max cached temperature=0 responses. |
-| `SEMANTIC_CACHE_MAX_BYTES` | `4194304` (4 MB) | Max total semantic cache size. |
-| `SEMANTIC_CACHE_TTL_MS` | `1800000` (30 min) | Semantic cache entry TTL. |
-| `STREAM_HISTORY_MAX` | `50` | Max recent stream events in the Dashboard live view buffer. |
-| `CONTEXT_LENGTH_DEFAULT` | `128000` | Global fallback max context length for models without explicit config. |
-| `USAGE_TOKEN_BUFFER` | `100` | Extra token headroom reserved when tracking usage quotas. |
+| Variable | Default | Description |
+| -------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
+| `OMNIROUTE_MEMORY_MB` | `512` | Runtime V8 heap limit. Docker standalone and `omniroute serve` use it to set `--max-old-space-size`. |
+| `PROMPT_CACHE_MAX_SIZE` | `50` | Max cached system prompt entries. |
+| `PROMPT_CACHE_MAX_BYTES` | `2097152` (2 MB) | Max total prompt cache size. |
+| `PROMPT_CACHE_TTL_MS` | `300000` (5 min) | Prompt cache entry TTL. |
+| `SEMANTIC_CACHE_MAX_SIZE` | `100` | Max cached temperature=0 responses. |
+| `SEMANTIC_CACHE_MAX_BYTES` | `4194304` (4 MB) | Max total semantic cache size. |
+| `SEMANTIC_CACHE_TTL_MS` | `1800000` (30 min) | Semantic cache entry TTL. |
+| `STREAM_HISTORY_MAX` | `50` | Max recent stream events in the Dashboard live view buffer. |
+| `CONTEXT_LENGTH_DEFAULT` | `128000` | Global fallback max context length for models without explicit config. |
+| `USAGE_TOKEN_BUFFER` | `100` | Extra token headroom reserved when tracking usage quotas. |
### Compression
@@ -647,16 +649,16 @@ The logging system writes to both stdout and rotated log files. All configuratio
Embedding layer, vector store and reranking knobs for the persistent memory subsystem (`src/lib/memory/`).
-| Variable | Default | Description |
-| ------------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
-| `MEMORY_EMBEDDING_CACHE_TTL_MS` | `300000` (5 min) | TTL for the in-memory embedding cache (per source/model/dim signature). |
-| `MEMORY_EMBEDDING_CACHE_MAX` | `1000` | Max LRU entries kept in the embedding cache. |
-| `MEMORY_TRANSFORMERS_MODEL` | `Xenova/all-MiniLM-L6-v2` | HF repo id for the opt-in `@huggingface/transformers` local MiniLM pipeline (~23 MB int8, ~400 MB RAM). |
-| `MEMORY_STATIC_MODEL` | `minishlab/potion-base-8M` | HF repo id for the static potion/Model2Vec lookup-table embedder. Downloaded lazily into the cache dir. |
-| `MEMORY_STATIC_CACHE_DIR` | `<DATA_DIR>/embeddings` | Directory used to cache the static potion model files. Defaults under `DATA_DIR` when unset. |
-| `MEMORY_VEC_TOP_K` | `20` | Default top-K used by the `sqlite-vec` brute-force vector search inside `src/lib/memory/vectorStore.ts`. |
-| `MEMORY_RRF_K` | `60` | Reciprocal Rank Fusion constant `k` for hybrid FTS5 + vector retrieval (sqlite-vec recipe). |
-| `HF_HUB_ENDPOINT` | `https://huggingface.co` | Override Hugging Face Hub base URL used by `staticPotion.ts` (e.g. mirror endpoint for air-gapped setups). |
+| Variable | Default | Description |
+| ------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------- |
+| `MEMORY_EMBEDDING_CACHE_TTL_MS` | `300000` (5 min) | TTL for the in-memory embedding cache (per source/model/dim signature). |
+| `MEMORY_EMBEDDING_CACHE_MAX` | `1000` | Max LRU entries kept in the embedding cache. |
+| `MEMORY_TRANSFORMERS_MODEL` | `Xenova/all-MiniLM-L6-v2` | HF repo id for the opt-in `@huggingface/transformers` local MiniLM pipeline (~23 MB int8, ~400 MB RAM). |
+| `MEMORY_STATIC_MODEL` | `minishlab/potion-base-8M` | HF repo id for the static potion/Model2Vec lookup-table embedder. Downloaded lazily into the cache dir. |
+| `MEMORY_STATIC_CACHE_DIR` | `<DATA_DIR>/embeddings` | Directory used to cache the static potion model files. Defaults under `DATA_DIR` when unset. |
+| `MEMORY_VEC_TOP_K` | `20` | Default top-K used by the `sqlite-vec` brute-force vector search inside `src/lib/memory/vectorStore.ts`. |
+| `MEMORY_RRF_K` | `60` | Reciprocal Rank Fusion constant `k` for hybrid FTS5 + vector retrieval (sqlite-vec recipe). |
+| `HF_HUB_ENDPOINT` | `https://huggingface.co` | Override Hugging Face Hub base URL used by `staticPotion.ts` (e.g. mirror endpoint for air-gapped setups). |
### Low-RAM Docker Example
@@ -693,27 +695,27 @@ Automatic model pricing data synchronization from external sources.
## 20. Provider-Specific Settings
-| Variable | Default | Source File | Description |
-| ----------------------------------------- | ------------------ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| `OPENROUTER_CATALOG_TTL_MS` | `86400000` (24h) | `src/lib/catalog/openrouterCatalog.ts` | OpenRouter model catalog cache TTL. |
+| Variable | Default | Source File | Description |
+| ----------------------------------------- | ------------------ | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
+| `OPENROUTER_CATALOG_TTL_MS` | `86400000` (24h) | `src/lib/catalog/openrouterCatalog.ts` | OpenRouter model catalog cache TTL. |
| `MODEL_CATALOG_INCLUDE_NAMES` | `true` | `src/shared/constants/featureFlagDefinitions.ts` | Include display-friendly `name` fields in `/v1/models` responses. Disable for clients that expect IDs only. |
-| `NANOBANANA_POLL_TIMEOUT_MS` | `120000` | `open-sse/handlers/imageGeneration.ts` | Max wait for NanoBanana image generation jobs. |
-| `NANOBANANA_POLL_INTERVAL_MS` | `2500` | `open-sse/handlers/imageGeneration.ts` | NanoBanana job polling frequency. |
-| `AWS_REGION` | _(unset)_ | `src/lib/providers/validation.ts`, `open-sse/handlers/audioSpeech.ts` | Region used to construct AWS Bedrock endpoints (Kiro, audio). |
-| `AWS_DEFAULT_REGION` | _(unset)_ | `src/lib/providers/validation.ts`, `open-sse/handlers/audioSpeech.ts` | Fallback when `AWS_REGION` is not set. |
-| `CLOUDFLARE_ACCOUNT_ID` | _(unset)_ | `open-sse/executors/cloudflare-ai.ts` | Account ID for Cloudflare Workers AI. |
-| `CLOUDFLARED_BIN` | auto-detect | `src/lib/cloudflaredTunnel.ts` | Custom path to `cloudflared` binary. |
-| `SEARCH_CACHE_TTL_MS` | `300000` (5 min) | `open-sse/services/searchCache.ts` | TTL for search API (Perplexity, Brave, etc.) response caching. |
-| `ALLOW_MULTI_CONNECTIONS_PER_COMPAT_NODE` | `false` | `src/app/api/providers/route.ts` | Allow multiple simultaneous connections per OpenAI-compatible provider. |
-| `ENABLE_CC_COMPATIBLE_PROVIDER` | `false` | `src/shared/utils/featureFlags.ts` | Reveal the experimental CC-compatible provider UI for Claude Code-only relays. |
-| `NINEROUTER_HOST` | `127.0.0.1` | `open-sse/executors/ninerouter.ts` | Override the host where the embedded 9router instance listens. |
-| `NINEROUTER_PORT` | `20130` | `open-sse/executors/ninerouter.ts` | Override the port where the embedded 9router instance listens. |
-| `EMBED_WS_PROXY_HOST` | `127.0.0.1` | `src/lib/services/embedWsProxy.ts` | Bind host for the embedded-service WebSocket proxy (loopback only by default). |
-| `EMBED_WS_PROXY_PORT` | `20131` | `src/lib/services/embedWsProxy.ts` | Port for the embedded-service WebSocket proxy server. |
-| `CLIPROXYAPI_HOST` | `127.0.0.1` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge host (legacy integration). |
-| `CLIPROXYAPI_PORT` | `5544` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge port. |
-| `CLIPROXYAPI_CONFIG_DIR` | `~/.cli-proxy-api` | `src/lib/versionManager/processManager.ts` | CLIProxyAPI config directory. |
-| `LOCAL_HOSTNAMES` | _(empty)_ | `open-sse/config/providerRegistry.ts` | Comma-separated additional hostnames treated as "local" (Docker service names, etc.). |
+| `NANOBANANA_POLL_TIMEOUT_MS` | `120000` | `open-sse/handlers/imageGeneration.ts` | Max wait for NanoBanana image generation jobs. |
+| `NANOBANANA_POLL_INTERVAL_MS` | `2500` | `open-sse/handlers/imageGeneration.ts` | NanoBanana job polling frequency. |
+| `AWS_REGION` | _(unset)_ | `src/lib/providers/validation.ts`, `open-sse/handlers/audioSpeech.ts` | Region used to construct AWS Bedrock endpoints (Kiro, audio). |
+| `AWS_DEFAULT_REGION` | _(unset)_ | `src/lib/providers/validation.ts`, `open-sse/handlers/audioSpeech.ts` | Fallback when `AWS_REGION` is not set. |
+| `CLOUDFLARE_ACCOUNT_ID` | _(unset)_ | `open-sse/executors/cloudflare-ai.ts` | Account ID for Cloudflare Workers AI. |
+| `CLOUDFLARED_BIN` | auto-detect | `src/lib/cloudflaredTunnel.ts` | Custom path to `cloudflared` binary. |
+| `SEARCH_CACHE_TTL_MS` | `300000` (5 min) | `open-sse/services/searchCache.ts` | TTL for search API (Perplexity, Brave, etc.) response caching. |
+| `ALLOW_MULTI_CONNECTIONS_PER_COMPAT_NODE` | `false` | `src/app/api/providers/route.ts` | Allow multiple simultaneous connections per OpenAI-compatible provider. |
+| `ENABLE_CC_COMPATIBLE_PROVIDER` | `false` | `src/shared/utils/featureFlags.ts` | Reveal the experimental CC-compatible provider UI for Claude Code-only relays. |
+| `NINEROUTER_HOST` | `127.0.0.1` | `open-sse/executors/ninerouter.ts` | Override the host where the embedded 9router instance listens. |
+| `NINEROUTER_PORT` | `20130` | `open-sse/executors/ninerouter.ts` | Override the port where the embedded 9router instance listens. |
+| `EMBED_WS_PROXY_HOST` | `127.0.0.1` | `src/lib/services/embedWsProxy.ts` | Bind host for the embedded-service WebSocket proxy (loopback only by default). |
+| `EMBED_WS_PROXY_PORT` | `20131` | `src/lib/services/embedWsProxy.ts` | Port for the embedded-service WebSocket proxy server. |
+| `CLIPROXYAPI_HOST` | `127.0.0.1` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge host (legacy integration). |
+| `CLIPROXYAPI_PORT` | `5544` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge port. |
+| `CLIPROXYAPI_CONFIG_DIR` | `~/.cli-proxy-api` | `src/lib/versionManager/processManager.ts` | CLIProxyAPI config directory. |
+| `LOCAL_HOSTNAMES` | _(empty)_ | `open-sse/config/providerRegistry.ts` | Comma-separated additional hostnames treated as "local" (Docker service names, etc.). |
`ENABLE_CC_COMPATIBLE_PROVIDER` is only for third-party relays that accept Claude Code clients
exclusively. OmniRoute rewrites requests so those relays accept them. If you only want to use
@@ -724,18 +726,18 @@ Anthropic-compatible provider instead.
## 21. Proxy Health
-| Variable | Default | Source File | Description |
-| ---------------------------- | ---------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `PROXY_FAST_FAIL_TIMEOUT_MS` | `2000` | `src/lib/proxyHealth.ts` | Fast-fail health check timeout. |
-| `PROXY_HEALTH_CACHE_TTL_MS` | `30000` | `src/lib/proxyHealth.ts` | Health check result cache TTL. |
-| `RATE_LIMIT_MAX_WAIT_MS` | `120000` (2 min) | `open-sse/services/rateLimitManager.ts` | Max time to wait on a 429 before failing the request. |
-| `RATE_LIMIT_AUTO_ENABLE` | _(unset)_ | `open-sse/services/rateLimitManager.ts` | Force the auto-enable rate limit safety net on/off regardless of the persisted Dashboard setting. Accepts `true`/`1`/`on` to force on, `false`/`0`/`off` to force off. |
+| Variable | Default | Source File | Description |
+| ---------------------------- | ---------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `PROXY_FAST_FAIL_TIMEOUT_MS` | `2000` | `src/lib/proxyHealth.ts` | Fast-fail health check timeout. |
+| `PROXY_HEALTH_CACHE_TTL_MS` | `30000` | `src/lib/proxyHealth.ts` | Health check result cache TTL. |
+| `RATE_LIMIT_MAX_WAIT_MS` | `120000` (2 min) | `open-sse/services/rateLimitManager.ts` | Max time to wait on a 429 before failing the request. |
+| `RATE_LIMIT_AUTO_ENABLE` | _(unset)_ | `open-sse/services/rateLimitManager.ts` | Force the auto-enable rate limit safety net on/off regardless of the persisted Dashboard setting. Accepts `true`/`1`/`on` to force on, `false`/`0`/`off` to force off. |
| `PROVIDER_COOLDOWN_ENABLED` | _(unset → off)_ | `open-sse/services/providerCooldownTracker.ts` | Opt-in global cross-request provider/connection cooldown tracking. OFF by default (overlaps Connection Cooldown / Provider Circuit Breaker). Accepts `true`/`1`/`on` to enable. |
-| `PROVIDER_COOLDOWN_MIN_MS` | `5000` | `open-sse/services/providerCooldownTracker.ts` | Minimum cooldown (ms) before a failed provider/connection is retried. Scaled exponentially with consecutive failures. Only used when `PROVIDER_COOLDOWN_ENABLED`. |
-| `PROVIDER_COOLDOWN_MAX_MS` | `300000` (5 min) | `open-sse/services/providerCooldownTracker.ts` | Maximum cooldown (ms) cap before a failed provider/connection is retried regardless. Only used when `PROVIDER_COOLDOWN_ENABLED`. |
-| `HEALTHCHECK_STAGGER_MS` | `3000` | `src/lib/tokenHealthCheck.ts` | Stagger interval (ms) between provider token healthchecks at startup. |
-| `REQUEST_RETRY` | `2` | `src/sse/services/cooldownAwareRetry.ts` | Number of automatic retries on model-scoped cooldown responses before returning error to client. |
-| `MAX_RETRY_INTERVAL_SEC` | `30` | `src/sse/services/cooldownAwareRetry.ts` | Max backoff interval (seconds) between cooldown retries. Capped by this value regardless of upstream `Retry-After`. |
+| `PROVIDER_COOLDOWN_MIN_MS` | `5000` | `open-sse/services/providerCooldownTracker.ts` | Minimum cooldown (ms) before a failed provider/connection is retried. Scaled exponentially with consecutive failures. Only used when `PROVIDER_COOLDOWN_ENABLED`. |
+| `PROVIDER_COOLDOWN_MAX_MS` | `300000` (5 min) | `open-sse/services/providerCooldownTracker.ts` | Maximum cooldown (ms) cap before a failed provider/connection is retried regardless. Only used when `PROVIDER_COOLDOWN_ENABLED`. |
+| `HEALTHCHECK_STAGGER_MS` | `3000` | `src/lib/tokenHealthCheck.ts` | Stagger interval (ms) between provider token healthchecks at startup. |
+| `REQUEST_RETRY` | `2` | `src/sse/services/cooldownAwareRetry.ts` | Number of automatic retries on model-scoped cooldown responses before returning error to client. |
+| `MAX_RETRY_INTERVAL_SEC` | `30` | `src/sse/services/cooldownAwareRetry.ts` | Max backoff interval (seconds) between cooldown retries. Capped by this value regardless of upstream `Retry-After`. |
---
@@ -744,19 +746,19 @@ Anthropic-compatible provider instead.
> [!CAUTION]
> These variables produce **verbose output** and may leak sensitive data. **Never enable in production.**
-| Variable | Default | Source File | Description |
-| -------------------------------- | ------------------- | ------------------------------------------ | --------------------------------------------------------------------------------- |
-| `CURSOR_DEBUG` | _(unset)_ | `open-sse/executors/cursor.ts` | Set `1` to enable verbose Cursor executor logs (decoded SSE chunks, etc.). |
-| `CURSOR_STREAM_DEBUG` | _(unset)_ | `open-sse/executors/cursor.ts` | Backward-compatible alias of `CURSOR_DEBUG`. |
-| `CURSOR_DUMP_FILE` | _(unset)_ | `open-sse/executors/cursor.ts` | Optional file path that receives raw decoded Cursor chunks when `CURSOR_DEBUG=1`. |
-| `CURSOR_STREAM_TIMEOUT_MS` | `300000` | `open-sse/executors/cursor.ts` | Stream idle timeout (ms) for the Cursor executor. |
+| Variable | Default | Source File | Description |
+| -------------------------------- | ------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
+| `CURSOR_DEBUG` | _(unset)_ | `open-sse/executors/cursor.ts` | Set `1` to enable verbose Cursor executor logs (decoded SSE chunks, etc.). |
+| `CURSOR_STREAM_DEBUG` | _(unset)_ | `open-sse/executors/cursor.ts` | Backward-compatible alias of `CURSOR_DEBUG`. |
+| `CURSOR_DUMP_FILE` | _(unset)_ | `open-sse/executors/cursor.ts` | Optional file path that receives raw decoded Cursor chunks when `CURSOR_DEBUG=1`. |
+| `CURSOR_STREAM_TIMEOUT_MS` | `300000` | `open-sse/executors/cursor.ts` | Stream idle timeout (ms) for the Cursor executor. |
| `CURSOR_TOOL_DIRECTIVE` | enabled (`!== "0"`) | `open-sse/executors/cursor.ts` | Tool-commit directive that makes composer-2.5 reliably issue tool calls. Set `0` to disable. |
-| `CURSOR_IMAGE_FETCH_TIMEOUT_MS` | `15000` | `open-sse/utils/cursorImages.ts` | Per-image fetch timeout (ms) for remote `image_url` vision input. |
-| `CURSOR_STATE_DB_PATH` | _(probed)_ | `open-sse/utils/cursorVersionDetector.ts` | Override the Cursor state DB lookup used for version detection. |
-| `CURSOR_TOKEN` | _(unset)_ | `scripts/ad-hoc/cursor-tap.cjs` | Direct Cursor bearer token used by developer tooling. |
-| `OMNIROUTE_LOG_REQUEST_SHAPE` | enabled (`!== "0"`) | `src/app/api/v1/chat/completions/route.ts` | Log content-type/length markers for large chat payloads. Set `"0"` to silence. |
-| `DEBUG_RESPONSES_SSE_TO_JSON` | _(unset)_ | `open-sse/handlers/responseTranslator.ts` | Set `true` to log Responses API SSE→JSON translation details. |
-| `NEXT_PUBLIC_OMNIROUTE_E2E_MODE` | _(unset)_ | E2E test harness | Set `true` to enable E2E test mode (relaxed auth, test hooks). |
+| `CURSOR_IMAGE_FETCH_TIMEOUT_MS` | `15000` | `open-sse/utils/cursorImages.ts` | Per-image fetch timeout (ms) for remote `image_url` vision input. |
+| `CURSOR_STATE_DB_PATH` | _(probed)_ | `open-sse/utils/cursorVersionDetector.ts` | Override the Cursor state DB lookup used for version detection. |
+| `CURSOR_TOKEN` | _(unset)_ | `scripts/ad-hoc/cursor-tap.cjs` | Direct Cursor bearer token used by developer tooling. |
+| `OMNIROUTE_LOG_REQUEST_SHAPE` | enabled (`!== "0"`) | `src/app/api/v1/chat/completions/route.ts` | Log content-type/length markers for large chat payloads. Set `"0"` to silence. |
+| `DEBUG_RESPONSES_SSE_TO_JSON` | _(unset)_ | `open-sse/handlers/responseTranslator.ts` | Set `true` to log Responses API SSE→JSON translation details. |
+| `NEXT_PUBLIC_OMNIROUTE_E2E_MODE` | _(unset)_ | E2E test harness | Set `true` to enable E2E test mode (relaxed auth, test hooks). |
---
@@ -856,57 +858,57 @@ Limits and safety knobs applied when the Skills framework (`src/lib/skills/`) ex
Provider quota endpoints, network tunnels (Tailscale, Ngrok, MITM debug proxy), the 1Proxy egress pool, database backups and small per-feature overrides referenced by the executor layer or scripts.
-| Variable | Default | Source File | Description |
-| ------------------------------------------ | --------------------------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------- |
-| `REDIS_URL` | `redis://localhost:6379` | `src/shared/utils/rateLimiter.ts` | Redis connection string for the rate limiter backend. |
-| `ALIBABA_CODING_PLAN_HOST` | _(production host)_ | `open-sse/services/bailianQuotaFetcher.ts` | Override the host used to fetch Alibaba Bailian coding-plan quotas. |
-| `ALIBABA_CODING_PLAN_QUOTA_URL` | derived from host | `open-sse/services/bailianQuotaFetcher.ts` | Full quota URL override for Alibaba Bailian. |
-| `CONTEXT_RESERVE_TOKENS` | `1024` | `open-sse/services/contextManager.ts` | Tokens reserved for completion output when computing prompt budgets. |
-| `MODEL_ALIAS_COMPAT_ENABLED` | enabled | `open-sse/services/model.ts` | Toggle the legacy model-alias compatibility layer used by older clients. |
-| `COMMAND_CODE_CALLBACK_PORT` | _(unset)_ | `src/app/api/providers/command-code/auth/shared.ts` | Local port used for OAuth-style callbacks from the Command Code CLI helper. |
-| `COMMAND_CODE_VERSION` | `0.33.2` | `open-sse/executors/commandCode.ts` | Value sent as the `x-command-code-version` header to the Command Code upstream. Override to bump the CLI version. |
-| `MITM_LOCAL_PORT` | `443` | `src/mitm/server.cjs` | Local bind port for the MITM debug proxy. |
-| `MITM_DISABLE_TLS_VERIFY` | `0` | `src/mitm/server.cjs` | Set `1` to disable upstream TLS verification (development only). |
-| `ONEPROXY_ENABLED` | `true` | `src/lib/oneproxySync.ts` | Enable the 1Proxy egress pool sync. |
-| `ONEPROXY_API_URL` | `https://1proxy-api.aitradepulse.com` | `src/lib/oneproxySync.ts` | 1Proxy service API URL override. |
-| `ONEPROXY_MAX_PROXIES` | `500` | `src/lib/oneproxySync.ts` | Maximum proxies imported per sync. |
-| `ONEPROXY_MIN_QUALITY_THRESHOLD` | `50` | `src/lib/oneproxySync.ts` | Minimum quality score for imported proxies. |
-| `FREE_PROXY_1PROXY_ENABLED` | `true` | `src/lib/freeProxyProviders/oneproxy.ts` | Enable the 1proxy free proxy source. Set to `false` to disable. |
-| `FREE_PROXY_1PROXY_API_URL` | _(see oneproxy.ts)_ | `src/lib/freeProxyProviders/oneproxy.ts` | 1proxy API URL override. |
-| `FREE_PROXY_1PROXY_MAX` | `500` | `src/lib/freeProxyProviders/oneproxy.ts` | Maximum proxies fetched per sync from 1proxy. |
-| `FREE_PROXY_1PROXY_MIN_QUALITY` | `50` | `src/lib/freeProxyProviders/oneproxy.ts` | Minimum quality score threshold for 1proxy imports. |
-| `FREE_PROXY_PROXIFLY_ENABLED` | `true` | `src/lib/freeProxyProviders/proxifly.ts` | Enable the Proxifly free proxy source. Set to `false` to disable. |
-| `FREE_PROXY_PROXIFLY_QUANTITY` | `100` | `src/lib/freeProxyProviders/proxifly.ts` | Number of proxies to fetch per Proxifly sync. |
-| `FREE_PROXY_PROXIFLY_ANONYMITY` | `elite` | `src/lib/freeProxyProviders/proxifly.ts` | Anonymity level filter for Proxifly (`elite`, `anonymous`, `transparent`). |
-| `FREE_PROXY_IPLOCATE_ENABLED` | `false` | `src/lib/freeProxyProviders/iplocate.ts` | Enable the IPLocate free proxy source. Opt-in only. |
-| `FREE_PROXY_IPLOCATE_BASE_URL` | `https://raw.githubusercontent.com/iplocate/free-proxy-list/main/protocols` | `src/lib/freeProxyProviders/iplocate.ts` | IPLocate proxy list base URL override. |
-| `NEXT_PUBLIC_VERCEL_RELAY_ENABLED` | `true` | `src/app/(dashboard)/…/ProxyPoolTab.tsx` | Show/hide the Deploy Vercel Relay button in the Proxy Pool tab. |
-| `VERCEL_API_BASE` | `https://api.vercel.com` | `src/app/api/settings/proxy/vercel-deploy/route.ts` | Vercel API base URL override (for testing). |
-| `NEXT_PUBLIC_VERCEL_RELAY_DEFAULT_PROJECT` | `omniroute-relay` | `src/app/(dashboard)/…/VercelRelayModal.tsx` | Default project name pre-filled in the Vercel Relay deploy modal. |
-| `TAILSCALE_BIN` | _(auto-detect)_ | `src/lib/tailscaleTunnel.ts` | Explicit path to the `tailscale` binary. |
-| `TAILSCALED_BIN` | _(auto-detect)_ | `src/lib/tailscaleTunnel.ts` | Explicit path to the `tailscaled` daemon binary. |
-| `NGROK_AUTHTOKEN` | _(unset)_ | `src/lib/ngrokTunnel.ts` | Authenticates outbound ngrok tunnels. |
-| `DB_BACKUP_MAX_FILES` | `20` | `src/lib/db/backup.ts` | Maximum SQLite backup files retained on disk. |
-| `DB_BACKUP_RETENTION_DAYS` | `0` | `src/lib/db/backup.ts` | Maximum age (days) of retained backups. `0` disables age-based pruning. |
-| `OMNIROUTE_TLS_PROXY_URL` | _(unset)_ | `open-sse/services/chatgptTlsClient.ts` | Override the TLS sidecar URL for tests. Production should leave unset. |
-| `CONTAINER_HOST` | `docker` | `scripts/check-permissions.sh` | Container runtime hint for the entrypoint permission check. Set to `podman` under rootless Podman so the fix instructions use `podman unshare chown` instead of `sudo chown`. |
-| `QUOTA_STORE_DRIVER` | `sqlite` | `src/lib/quota/storeFactory.ts` | Quota-share consumption store backend: `sqlite` (default) or `redis`. |
-| `QUOTA_STORE_REDIS_URL` | _(unset)_ | `src/lib/quota/storeFactory.ts` | Redis connection string used when `QUOTA_STORE_DRIVER=redis` (e.g. `redis://localhost:6379`). |
-| `QUOTA_SATURATION_THRESHOLD` | `0.5` | `src/lib/quota/enforce.ts` | Pool saturation ratio (0..1); at/above it the pool enters strict mode (no borrowing). |
-| `QUOTA_SOFT_DEPRIORITIZE_FACTOR` | `0.7` | `open-sse/services/combo.ts` | Score multiplier (0..1) applied to a target when the soft quota policy deprioritizes it. |
-| `QUOTA_CONSUMPTION_RETENTION_DAYS` | `14` | `src/lib/db/quotaConsumption.ts` | Retention window (days) for `quota_consumption` buckets before GC (`gcQuotaConsumption`). |
-| `AGENTBRIDGE_UPSTREAM_CA_CERT` | _(unset)_ | `src/mitm/manager.ts` | Extra CA certificate (PEM) trusted for AgentBridge upstream TLS connections. |
-| `INSPECTOR_BUFFER_SIZE` | `1000` | `src/mitm/inspector/buffer.ts` | Max captured requests held in the Traffic Inspector ring buffer. |
-| `INSPECTOR_MAX_BODY_KB` | `1024` | `src/mitm/inspector/buffer.ts` | Max captured request/response body size (KB) before truncation. |
-| `INSPECTOR_HTTP_PROXY_PORT` | `8080` | `src/mitm/inspector/httpProxyServer.ts` | Local port for the Traffic Inspector HTTP proxy. |
-| `INSPECTOR_HTTP_PROXY_AUTOSTART` | `false` | `src/mitm/inspector/httpProxyServer.ts` | Auto-start the inspector HTTP proxy on boot. |
-| `INSPECTOR_TLS_INTERCEPT` | `false` | `src/lib/inspector/captureState.ts` | Enable TLS interception (MITM) for captured HTTPS traffic. |
-| `INSPECTOR_LLM_HOSTS_EXTRA` | _(unset)_ | `src/lib/inspector/captureState.ts` | Extra hostnames (comma-separated) treated as LLM endpoints for capture. |
-| `INSPECTOR_MASK_SECRETS` | `true` | `src/mitm/inspector/buffer.ts` | Mask secrets (auth headers / API keys) in captured traffic. |
-| `INSPECTOR_SYSTEM_PROXY_GUARD_MINUTES` | `30` | `src/app/api/tools/traffic-inspector/capture-modes/system-proxy/route.ts` | Minutes before the system-proxy guard auto-reverts OS proxy settings. |
-| `INSPECTOR_INTERNAL_INGEST_TOKEN` | _(auto)_ | `src/app/api/tools/traffic-inspector/internal/ingest/route.ts` | Token authenticating internal capture ingest into the inspector. |
-| `PLAYGROUND_COMPARE_MAX_COLUMNS` | `4` | `src/app/(dashboard)/dashboard/playground/` | Max number of side-by-side columns in the Playground compare mode. |
-| `PLAYGROUND_IMPROVE_PROMPT_DEFAULT_MODEL` | _(unset)_ | `src/app/(dashboard)/dashboard/playground/` | Default model for the Playground 'improve prompt' action (falls back to the active model when unset). |
+| Variable | Default | Source File | Description |
+| ------------------------------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `REDIS_URL` | `redis://localhost:6379` | `src/shared/utils/rateLimiter.ts` | Redis connection string for the rate limiter backend. |
+| `ALIBABA_CODING_PLAN_HOST` | _(production host)_ | `open-sse/services/bailianQuotaFetcher.ts` | Override the host used to fetch Alibaba Bailian coding-plan quotas. |
+| `ALIBABA_CODING_PLAN_QUOTA_URL` | derived from host | `open-sse/services/bailianQuotaFetcher.ts` | Full quota URL override for Alibaba Bailian. |
+| `CONTEXT_RESERVE_TOKENS` | `1024` | `open-sse/services/contextManager.ts` | Tokens reserved for completion output when computing prompt budgets. |
+| `MODEL_ALIAS_COMPAT_ENABLED` | enabled | `open-sse/services/model.ts` | Toggle the legacy model-alias compatibility layer used by older clients. |
+| `COMMAND_CODE_CALLBACK_PORT` | _(unset)_ | `src/app/api/providers/command-code/auth/shared.ts` | Local port used for OAuth-style callbacks from the Command Code CLI helper. |
+| `COMMAND_CODE_VERSION` | `0.33.2` | `open-sse/executors/commandCode.ts` | Value sent as the `x-command-code-version` header to the Command Code upstream. Override to bump the CLI version. |
+| `MITM_LOCAL_PORT` | `443` | `src/mitm/server.cjs` | Local bind port for the MITM debug proxy. |
+| `MITM_DISABLE_TLS_VERIFY` | `0` | `src/mitm/server.cjs` | Set `1` to disable upstream TLS verification (development only). |
+| `ONEPROXY_ENABLED` | `true` | `src/lib/oneproxySync.ts` | Enable the 1Proxy egress pool sync. |
+| `ONEPROXY_API_URL` | `https://1proxy-api.aitradepulse.com` | `src/lib/oneproxySync.ts` | 1Proxy service API URL override. |
+| `ONEPROXY_MAX_PROXIES` | `500` | `src/lib/oneproxySync.ts` | Maximum proxies imported per sync. |
+| `ONEPROXY_MIN_QUALITY_THRESHOLD` | `50` | `src/lib/oneproxySync.ts` | Minimum quality score for imported proxies. |
+| `FREE_PROXY_1PROXY_ENABLED` | `true` | `src/lib/freeProxyProviders/oneproxy.ts` | Enable the 1proxy free proxy source. Set to `false` to disable. |
+| `FREE_PROXY_1PROXY_API_URL` | _(see oneproxy.ts)_ | `src/lib/freeProxyProviders/oneproxy.ts` | 1proxy API URL override. |
+| `FREE_PROXY_1PROXY_MAX` | `500` | `src/lib/freeProxyProviders/oneproxy.ts` | Maximum proxies fetched per sync from 1proxy. |
+| `FREE_PROXY_1PROXY_MIN_QUALITY` | `50` | `src/lib/freeProxyProviders/oneproxy.ts` | Minimum quality score threshold for 1proxy imports. |
+| `FREE_PROXY_PROXIFLY_ENABLED` | `true` | `src/lib/freeProxyProviders/proxifly.ts` | Enable the Proxifly free proxy source. Set to `false` to disable. |
+| `FREE_PROXY_PROXIFLY_QUANTITY` | `100` | `src/lib/freeProxyProviders/proxifly.ts` | Number of proxies to fetch per Proxifly sync. |
+| `FREE_PROXY_PROXIFLY_ANONYMITY` | `elite` | `src/lib/freeProxyProviders/proxifly.ts` | Anonymity level filter for Proxifly (`elite`, `anonymous`, `transparent`). |
+| `FREE_PROXY_IPLOCATE_ENABLED` | `false` | `src/lib/freeProxyProviders/iplocate.ts` | Enable the IPLocate free proxy source. Opt-in only. |
+| `FREE_PROXY_IPLOCATE_BASE_URL` | `https://raw.githubusercontent.com/iplocate/free-proxy-list/main/protocols` | `src/lib/freeProxyProviders/iplocate.ts` | IPLocate proxy list base URL override. |
+| `NEXT_PUBLIC_VERCEL_RELAY_ENABLED` | `true` | `src/app/(dashboard)/…/ProxyPoolTab.tsx` | Show/hide the Deploy Vercel Relay button in the Proxy Pool tab. |
+| `VERCEL_API_BASE` | `https://api.vercel.com` | `src/app/api/settings/proxy/vercel-deploy/route.ts` | Vercel API base URL override (for testing). |
+| `NEXT_PUBLIC_VERCEL_RELAY_DEFAULT_PROJECT` | `omniroute-relay` | `src/app/(dashboard)/…/VercelRelayModal.tsx` | Default project name pre-filled in the Vercel Relay deploy modal. |
+| `TAILSCALE_BIN` | _(auto-detect)_ | `src/lib/tailscaleTunnel.ts` | Explicit path to the `tailscale` binary. |
+| `TAILSCALED_BIN` | _(auto-detect)_ | `src/lib/tailscaleTunnel.ts` | Explicit path to the `tailscaled` daemon binary. |
+| `NGROK_AUTHTOKEN` | _(unset)_ | `src/lib/ngrokTunnel.ts` | Authenticates outbound ngrok tunnels. |
+| `DB_BACKUP_MAX_FILES` | `20` | `src/lib/db/backup.ts` | Maximum SQLite backup files retained on disk. |
+| `DB_BACKUP_RETENTION_DAYS` | `0` | `src/lib/db/backup.ts` | Maximum age (days) of retained backups. `0` disables age-based pruning. |
+| `OMNIROUTE_TLS_PROXY_URL` | _(unset)_ | `open-sse/services/chatgptTlsClient.ts` | Override the TLS sidecar URL for tests. Production should leave unset. |
+| `CONTAINER_HOST` | `docker` | `scripts/check-permissions.sh` | Container runtime hint for the entrypoint permission check. Set to `podman` under rootless Podman so the fix instructions use `podman unshare chown` instead of `sudo chown`. |
+| `QUOTA_STORE_DRIVER` | `sqlite` | `src/lib/quota/storeFactory.ts` | Quota-share consumption store backend: `sqlite` (default) or `redis`. |
+| `QUOTA_STORE_REDIS_URL` | _(unset)_ | `src/lib/quota/storeFactory.ts` | Redis connection string used when `QUOTA_STORE_DRIVER=redis` (e.g. `redis://localhost:6379`). |
+| `QUOTA_SATURATION_THRESHOLD` | `0.5` | `src/lib/quota/enforce.ts` | Pool saturation ratio (0..1); at/above it the pool enters strict mode (no borrowing). |
+| `QUOTA_SOFT_DEPRIORITIZE_FACTOR` | `0.7` | `open-sse/services/combo.ts` | Score multiplier (0..1) applied to a target when the soft quota policy deprioritizes it. |
+| `QUOTA_CONSUMPTION_RETENTION_DAYS` | `14` | `src/lib/db/quotaConsumption.ts` | Retention window (days) for `quota_consumption` buckets before GC (`gcQuotaConsumption`). |
+| `AGENTBRIDGE_UPSTREAM_CA_CERT` | _(unset)_ | `src/mitm/manager.ts` | Extra CA certificate (PEM) trusted for AgentBridge upstream TLS connections. |
+| `INSPECTOR_BUFFER_SIZE` | `1000` | `src/mitm/inspector/buffer.ts` | Max captured requests held in the Traffic Inspector ring buffer. |
+| `INSPECTOR_MAX_BODY_KB` | `1024` | `src/mitm/inspector/buffer.ts` | Max captured request/response body size (KB) before truncation. |
+| `INSPECTOR_HTTP_PROXY_PORT` | `8080` | `src/mitm/inspector/httpProxyServer.ts` | Local port for the Traffic Inspector HTTP proxy. |
+| `INSPECTOR_HTTP_PROXY_AUTOSTART` | `false` | `src/mitm/inspector/httpProxyServer.ts` | Auto-start the inspector HTTP proxy on boot. |
+| `INSPECTOR_TLS_INTERCEPT` | `false` | `src/lib/inspector/captureState.ts` | Enable TLS interception (MITM) for captured HTTPS traffic. |
+| `INSPECTOR_LLM_HOSTS_EXTRA` | _(unset)_ | `src/lib/inspector/captureState.ts` | Extra hostnames (comma-separated) treated as LLM endpoints for capture. |
+| `INSPECTOR_MASK_SECRETS` | `true` | `src/mitm/inspector/buffer.ts` | Mask secrets (auth headers / API keys) in captured traffic. |
+| `INSPECTOR_SYSTEM_PROXY_GUARD_MINUTES` | `30` | `src/app/api/tools/traffic-inspector/capture-modes/system-proxy/route.ts` | Minutes before the system-proxy guard auto-reverts OS proxy settings. |
+| `INSPECTOR_INTERNAL_INGEST_TOKEN` | _(auto)_ | `src/app/api/tools/traffic-inspector/internal/ingest/route.ts` | Token authenticating internal capture ingest into the inspector. |
+| `PLAYGROUND_COMPARE_MAX_COLUMNS` | `4` | `src/app/(dashboard)/dashboard/playground/` | Max number of side-by-side columns in the Playground compare mode. |
+| `PLAYGROUND_IMPROVE_PROMPT_DEFAULT_MODEL` | _(unset)_ | `src/app/(dashboard)/dashboard/playground/` | Default model for the Playground 'improve prompt' action (falls back to the active model when unset). |
---
@@ -916,25 +918,25 @@ Used by `scripts/dev/run-next-playwright.mjs`, `scripts/dev/smoke-electron-packa
`scripts/dev/run-ecosystem-tests.mjs`, and `scripts/build/uninstall.mjs`. Leave every
value below unset in production deployments.
-| Variable | Default | Source File | Description |
-| ------------------------------------- | -------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------- |
-| `OMNIROUTE_E2E_BOOTSTRAP_MODE` | `auth` | `scripts/dev/run-next-playwright.mjs` | E2E bootstrap mode (`auth`, `fresh`, `reuse`) for the Playwright runner. |
-| `OMNIROUTE_E2E_PASSWORD` | falls back to `INITIAL_PASSWORD` | `scripts/dev/run-next-playwright.mjs` | Admin password injected into the Playwright environment. |
-| `OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the local healthcheck poll during Playwright runs. |
-| `OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the OAuth token healthcheck loop during tests. |
-| `OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS` | _(unset)_ | `src/lib/tokenHealthCheck.ts` | Comma-separated providers excluded from the proactive token-refresh sweep (e.g. `codex,openai`). Targeted alternative to fully disabling the healthcheck — short-TTL providers keep refreshing while cascade providers stay reactive-only. |
-| `OMNIROUTE_HIDE_HEALTHCHECK_LOGS` | `true` | `scripts/dev/run-next-playwright.mjs` | Silence healthcheck noise in Playwright stdout. |
-| `OMNIROUTE_PLAYWRIGHT_SKIP_BUILD` | `0` | `scripts/dev/run-next-playwright.mjs` | Skip the Next.js production build before Playwright starts (CI optimization). |
-| `OMNIROUTE_SKIP_UNINSTALL_HOOK` | `0` | `scripts/build/uninstall.mjs` | Skip the OmniRoute uninstall hook (used by CI to keep `node_modules` intact). |
-| `ECOSYSTEM_SERVER_WAIT_MS` | `180000` | `scripts/dev/run-ecosystem-tests.mjs` | Wait time (ms) for the server to become healthy before running ecosystem/protocol tests. |
-| `ELECTRON_SMOKE_URL` | `http://127.0.0.1:20128/login` | `scripts/dev/smoke-electron-packaged.mjs` | URL the Electron smoke harness expects the packaged app to serve. |
-| `ELECTRON_SMOKE_TIMEOUT_MS` | `45000` | `scripts/dev/smoke-electron-packaged.mjs` | Total timeout (ms) before the smoke harness gives up. |
-| `ELECTRON_SMOKE_SETTLE_MS` | `2000` | `scripts/dev/smoke-electron-packaged.mjs` | Settle window (ms) after the page loads. |
-| `ELECTRON_SMOKE_APP_EXECUTABLE` | _(auto)_ | `scripts/dev/smoke-electron-packaged.mjs` | Explicit path to the packaged Electron executable. |
-| `ELECTRON_SMOKE_DATA_DIR` | _(tmpdir)_ | `scripts/dev/smoke-electron-packaged.mjs` | Data directory for the Electron smoke run. |
-| `ELECTRON_SMOKE_KEEP_DATA` | `0` | `scripts/dev/smoke-electron-packaged.mjs` | Set `1` to preserve the smoke data directory after the run. |
-| `ELECTRON_SMOKE_STREAM_LOGS` | `0` | `scripts/dev/smoke-electron-packaged.mjs` | Set `1` to stream Electron logs to stdout during the run. |
-| `CLI_DEVIN_BIN` | _(PATH lookup)_ | `open-sse/executors/devin-cli.ts` | Override the Devin CLI binary path. |
+| Variable | Default | Source File | Description |
+| -------------------------------------- | -------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `OMNIROUTE_E2E_BOOTSTRAP_MODE` | `auth` | `scripts/dev/run-next-playwright.mjs` | E2E bootstrap mode (`auth`, `fresh`, `reuse`) for the Playwright runner. |
+| `OMNIROUTE_E2E_PASSWORD` | falls back to `INITIAL_PASSWORD` | `scripts/dev/run-next-playwright.mjs` | Admin password injected into the Playwright environment. |
+| `OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the local healthcheck poll during Playwright runs. |
+| `OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the OAuth token healthcheck loop during tests. |
+| `OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS` | _(unset)_ | `src/lib/tokenHealthCheck.ts` | Comma-separated providers excluded from the proactive token-refresh sweep (e.g. `codex,openai`). Targeted alternative to fully disabling the healthcheck — short-TTL providers keep refreshing while cascade providers stay reactive-only. |
+| `OMNIROUTE_HIDE_HEALTHCHECK_LOGS` | `true` | `scripts/dev/run-next-playwright.mjs` | Silence healthcheck noise in Playwright stdout. |
+| `OMNIROUTE_PLAYWRIGHT_SKIP_BUILD` | `0` | `scripts/dev/run-next-playwright.mjs` | Skip the Next.js production build before Playwright starts (CI optimization). |
+| `OMNIROUTE_SKIP_UNINSTALL_HOOK` | `0` | `scripts/build/uninstall.mjs` | Skip the OmniRoute uninstall hook (used by CI to keep `node_modules` intact). |
+| `ECOSYSTEM_SERVER_WAIT_MS` | `180000` | `scripts/dev/run-ecosystem-tests.mjs` | Wait time (ms) for the server to become healthy before running ecosystem/protocol tests. |
+| `ELECTRON_SMOKE_URL` | `http://127.0.0.1:20128/login` | `scripts/dev/smoke-electron-packaged.mjs` | URL the Electron smoke harness expects the packaged app to serve. |
+| `ELECTRON_SMOKE_TIMEOUT_MS` | `45000` | `scripts/dev/smoke-electron-packaged.mjs` | Total timeout (ms) before the smoke harness gives up. |
+| `ELECTRON_SMOKE_SETTLE_MS` | `2000` | `scripts/dev/smoke-electron-packaged.mjs` | Settle window (ms) after the page loads. |
+| `ELECTRON_SMOKE_APP_EXECUTABLE` | _(auto)_ | `scripts/dev/smoke-electron-packaged.mjs` | Explicit path to the packaged Electron executable. |
+| `ELECTRON_SMOKE_DATA_DIR` | _(tmpdir)_ | `scripts/dev/smoke-electron-packaged.mjs` | Data directory for the Electron smoke run. |
+| `ELECTRON_SMOKE_KEEP_DATA` | `0` | `scripts/dev/smoke-electron-packaged.mjs` | Set `1` to preserve the smoke data directory after the run. |
+| `ELECTRON_SMOKE_STREAM_LOGS` | `0` | `scripts/dev/smoke-electron-packaged.mjs` | Set `1` to stream Electron logs to stdout during the run. |
+| `CLI_DEVIN_BIN` | _(PATH lookup)_ | `open-sse/executors/devin-cli.ts` | Override the Devin CLI binary path. |
### Docs translation pipeline
@@ -984,8 +986,8 @@ with accurate `limit.context` and `limit.output` values pulled from the running
OmniRoute instance. None of these are required for normal operation — the script
is developer tooling only.
-| Variable | Default | Source File | Description |
-| ------------------- | ------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
-| `OMNIROUTE_URL` | `http://localhost:20128` | `scripts/ad-hoc/regen-opencode-config.ts` | Base URL of the OmniRoute instance to query for `/v1/models`. |
-| `OMNIROUTE_KEY` | _(unset)_ | `scripts/ad-hoc/regen-opencode-config.ts` | API key to authenticate against the OmniRoute `/v1/models` endpoint. Falls back to `OPENCODE_API_KEY` when unset. |
-| `OPENCODE_API_KEY` | _(unset)_ | `scripts/ad-hoc/regen-opencode-config.ts` | OpenCode-style API key (`sk-...`) written into the regenerated `opencode.json`. Falls back to `OMNIROUTE_KEY` when unset. |
+| Variable | Default | Source File | Description |
+| ------------------ | ------------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
+| `OMNIROUTE_URL` | `http://localhost:20128` | `scripts/ad-hoc/regen-opencode-config.ts` | Base URL of the OmniRoute instance to query for `/v1/models`. |
+| `OMNIROUTE_KEY` | _(unset)_ | `scripts/ad-hoc/regen-opencode-config.ts` | API key to authenticate against the OmniRoute `/v1/models` endpoint. Falls back to `OPENCODE_API_KEY` when unset. |
+| `OPENCODE_API_KEY` | _(unset)_ | `scripts/ad-hoc/regen-opencode-config.ts` | OpenCode-style API key (`sk-...`) written into the regenerated `opencode.json`. Falls back to `OMNIROUTE_KEY` when unset. |
diff --git a/docs/reference/openapi.yaml b/docs/reference/openapi.yaml
index a93fb1dea2..3b8cdb8ff0 100644
--- a/docs/reference/openapi.yaml
+++ b/docs/reference/openapi.yaml
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: OmniRoute API
- version: 3.8.21
+ version: 3.8.22
description: |
OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatible
endpoint that routes requests to multiple AI providers with load balancing,
diff --git a/docs/routing/AUTO-COMBO.md b/docs/routing/AUTO-COMBO.md
index c470a407d0..94596e756c 100644
--- a/docs/routing/AUTO-COMBO.md
+++ b/docs/routing/AUTO-COMBO.md
@@ -182,6 +182,8 @@ There is **no dedicated `POST /api/combos/auto` endpoint** — Auto-Combo is con
2. **Persisted combo with `strategy: "auto"`:** Create a regular combo via `POST /api/combos` and set `strategy: "auto"` plus `config.auto.weights` / `config.auto.candidatePool`. The same scoring engine is used; the combo is stored in `combos` and reusable by ID.
+For discovery, `GET /api/combos/auto` lists every variant with its resolved candidate pool plus `context_length` / `max_output_tokens` — the MAX across the candidate pool's windows. Clients (e.g. the opencode plugin) must advertise these values instead of `0`: a zero context disables opencode's auto-compaction entirely, letting sessions grow until the gateway's history purge destroys context. MAX is safe to advertise because the auto-combo context pre-filter routes oversized requests to large-window candidates.
+
```bash
# Zero-config usage (no combo creation)
curl -X POST http://localhost:20128/v1/chat/completions \
diff --git a/electron/lib/resolveServerEntry.js b/electron/lib/resolveServerEntry.js
new file mode 100644
index 0000000000..836cf22acf
--- /dev/null
+++ b/electron/lib/resolveServerEntry.js
@@ -0,0 +1,26 @@
+/**
+ * resolveServerEntry.js — pure helper for selecting the Next.js server entrypoint.
+ *
+ * The WS-aware wrapper `server-ws.mjs` installs the trusted peer-IP stamp
+ * (peer-stamp.mjs) that the authz middleware needs to allow loopback/LAN access
+ * to LOCAL_ONLY routes (AgentBridge, MCP, services, etc.). Without it every
+ * LOCAL_ONLY request returns 403.
+ *
+ * We prefer `server-ws.mjs` when it exists — mirroring run-standalone.mjs — and
+ * fall back to the bare `server.js` only when the wrapper is absent (e.g. an
+ * older build or a stripped bundle).
+ *
+ * Extracted as a pure helper so it can be unit-tested without importing the full
+ * Electron main process (which requires the Electron binary).
+ *
+ * @param {string} serverDir - directory that contains server.js / server-ws.mjs
+ * @param {Function} existsSyncFn - injectable fs.existsSync (for unit tests)
+ * @returns {string} filename ("server-ws.mjs" or "server.js")
+ */
+function resolveServerEntry(serverDir, existsSyncFn) {
+ const path = require("path");
+ const wsEntry = path.join(serverDir, "server-ws.mjs");
+ return existsSyncFn(wsEntry) ? "server-ws.mjs" : "server.js";
+}
+
+module.exports = { resolveServerEntry };
diff --git a/electron/main.js b/electron/main.js
index a439157eb4..b9e9ff486f 100644
--- a/electron/main.js
+++ b/electron/main.js
@@ -35,6 +35,7 @@ const { autoUpdater } = require("electron-updater");
const { hasEncryptedCredentials } = require("./sqlite-inspection");
const { loginManager } = require("./loginManager");
const { killProcessTree } = require("./processTree");
+const { resolveServerEntry } = require("./lib/resolveServerEntry");
// ── Single Instance Lock ───────────────────────────────────
const gotTheLock = app.requestSingleInstanceLock();
@@ -525,7 +526,11 @@ function startNextServer() {
return;
}
- const serverScript = path.join(NEXT_SERVER_PATH, "server.js");
+ // Prefer server-ws.mjs (peer-stamp wrapper) when present; fall back to server.js.
+ // Without server-ws.mjs every LOCAL_ONLY route (AgentBridge, MCP, services, …) returns
+ // 403 because the authz middleware can't verify the trusted loopback peer-stamp. (#3386)
+ const serverEntryName = resolveServerEntry(NEXT_SERVER_PATH, fs.existsSync.bind(fs));
+ const serverScript = path.join(NEXT_SERVER_PATH, serverEntryName);
if (!fs.existsSync(serverScript)) {
console.error("[Electron] Server script not found:", serverScript);
sendToRenderer("server-status", { status: "error", port: serverPort });
diff --git a/electron/package.json b/electron/package.json
index 4d007c3c13..888f249bd0 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "omniroute-desktop",
- "version": "3.8.21",
+ "version": "3.8.22",
"description": "OmniRoute Desktop Application",
"main": "main.js",
"author": {
@@ -54,6 +54,7 @@
"loginManager.js",
"processTree.js",
"sqlite-inspection.js",
+ "lib/resolveServerEntry.js",
"package.json",
"node_modules/**/*"
],
diff --git a/file-size-baseline.json b/file-size-baseline.json
index 0f69af4d03..fbd4cd6e9b 100644
--- a/file-size-baseline.json
+++ b/file-size-baseline.json
@@ -48,7 +48,14 @@
"src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx": 2570,
"src/app/(dashboard)/dashboard/health/page.tsx": 1091,
"src/app/(dashboard)/dashboard/playground/components/tabs/ApiTab.tsx": 847,
- "src/app/(dashboard)/dashboard/providers/[id]/page.tsx": 12883,
+ "src/app/(dashboard)/dashboard/providers/[id]/ProviderDetailPageClient.tsx": 4063,
+ "src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderConnections.ts": 954,
+ "src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderSettings.ts": 264,
+ "src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderModels.ts": 155,
+ "src/app/(dashboard)/dashboard/providers/[id]/providerPageHelpers.ts": 822,
+ "src/app/(dashboard)/dashboard/providers/[id]/components/ConnectionRow.tsx": 941,
+ "src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal.tsx": 843,
+ "src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx": 1171,
"src/app/(dashboard)/dashboard/providers/components/onboarding/ProviderOnboardingWizard.tsx": 906,
"src/app/(dashboard)/dashboard/providers/page.tsx": 1925,
"src/app/(dashboard)/dashboard/runtime/RuntimePageClient.tsx": 1127,
@@ -76,6 +83,7 @@
"src/lib/db/providers.ts": 993,
"src/lib/db/proxies.ts": 1031,
"src/lib/db/settings.ts": 1101,
+ "src/lib/db/usageAnalytics.ts": 873,
"src/lib/evals/evalRunner.ts": 961,
"src/lib/memory/retrieval.ts": 1171,
"src/lib/modelsDevSync.ts": 934,
@@ -95,5 +103,6 @@
"src/sse/handlers/chat.ts": 1381,
"src/sse/services/auth.ts": 2198
},
- "_rebaseline_2026_06_09": "Re-baseline consciente pre-release v3.8.19: 9 arquivos cresceram durante o ciclo (features mergeadas: RequestLoggerV2 +281 request-logger rework, stream +101, combo +73, chatCore +45, catalog +32 fable-5/catalog-flag, callLogs +4, accountFallback +2, usageHistory novo 840) + core.ts +7 (fix resetAllDbModuleState, PR 3536). A catraca segue valendo destes valores — proximo crescimento falha. Decisao: encolher (esp. RequestLoggerV2/chatCore) e a issue #3501 ficam para o ciclo seguinte."
+ "_rebaseline_2026_06_09": "Re-baseline consciente pre-release v3.8.19: 9 arquivos cresceram durante o ciclo (features mergeadas: RequestLoggerV2 +281 request-logger rework, stream +101, combo +73, chatCore +45, catalog +32 fable-5/catalog-flag, callLogs +4, accountFallback +2, usageHistory novo 840) + core.ts +7 (fix resetAllDbModuleState, PR 3536). A catraca segue valendo destes valores — proximo crescimento falha. Decisao: encolher (esp. RequestLoggerV2/chatCore) e a issue #3501 ficam para o ciclo seguinte.",
+ "_rebaseline_2026_06_11_phase1f": "Phase 1f (#3501): ProviderDetailPageClient.tsx 4948→4062 (-886 LOC); 3 novos hooks extraídos. useProviderConnections.ts=954 acima do cap=800 — justificado: extração direta do god-component (zero lógica nova), própria redução do cliente supera o custo. useProviderSettings.ts=263 e useProviderModels.ts=154 já abaixo do cap."
}
diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.ts
index 278593bac2..d017b25a18 100644
--- a/open-sse/config/providerRegistry.ts
+++ b/open-sse/config/providerRegistry.ts
@@ -343,6 +343,9 @@ const CHAT_OPENAI_COMPAT_MODELS: Record<string, RegistryModel[]> = {
{ id: "mimo-v2-omni", name: "MiMo-V2-Omni", contextLength: 262144, maxOutputTokens: 131072 },
{ id: "mimo-v2-flash", name: "MiMo-V2-Flash", contextLength: 262144, maxOutputTokens: 65536 },
],
+ mimocode: [
+ { id: "mimo-auto", name: "MiMo Auto", contextLength: 1000000, maxOutputTokens: 128000 },
+ ],
gitlawb: [
{ id: "mimo-v2.5-pro", name: "MiMo-V2.5-Pro", contextLength: 1048576, maxOutputTokens: 131072 },
{ id: "mimo-v2.5", name: "MiMo-V2.5", contextLength: 1048576, maxOutputTokens: 131072 },
@@ -4067,6 +4070,18 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {
models: CHAT_OPENAI_COMPAT_MODELS["xiaomi-mimo"],
},
+ mimocode: {
+ id: "mimocode",
+ alias: "mcode",
+ format: "openai",
+ executor: "mimocode",
+ baseUrl: "https://api.xiaomimimo.com",
+ chatPath: "/api/free-ai/openai/chat",
+ authType: "none",
+ authHeader: "none",
+ models: CHAT_OPENAI_COMPAT_MODELS["mimocode"],
+ },
+
gitlawb: {
id: "gitlawb",
alias: "glb",
diff --git a/open-sse/executors/index.ts b/open-sse/executors/index.ts
index 2379eb6e22..62f833f6ab 100644
--- a/open-sse/executors/index.ts
+++ b/open-sse/executors/index.ts
@@ -51,6 +51,7 @@ import { KimiExecutor } from "./kimi.ts"
import { TheOldLlmExecutor } from "./theoldllm.ts";
import { ChipotleExecutor } from "./chipotle.ts";
import { LMArenaExecutor } from "./lmarena.ts";
+import { MimocodeExecutor } from "./mimocode.ts";
const executors = {
antigravity: new AntigravityExecutor(),
@@ -146,6 +147,8 @@ const executors = {
pepper: new ChipotleExecutor(), // Alias
lmarena: new LMArenaExecutor(),
lma: new LMArenaExecutor(), // Alias
+ mimocode: new MimocodeExecutor(),
+ mcode: new MimocodeExecutor(), // Alias
};
const defaultCache = new Map();
@@ -205,3 +208,4 @@ export { QwenWebExecutor } from "./qwen-web.ts";
export { TheOldLlmExecutor } from "./theoldllm.ts";
export { ChipotleExecutor } from "./chipotle.ts";
export { LMArenaExecutor } from "./lmarena.ts";
+export { MimocodeExecutor } from "./mimocode.ts";
diff --git a/open-sse/executors/kiro.ts b/open-sse/executors/kiro.ts
index 379933f0d7..bb26d5f7d6 100644
--- a/open-sse/executors/kiro.ts
+++ b/open-sse/executors/kiro.ts
@@ -168,6 +168,37 @@ function ensureKiroUsage(state: KiroStreamState) {
};
}
+/**
+ * Resolve the AWS region for a Kiro/CodeWhisperer connection. Enterprise AWS IAM Identity
+ * Center accounts are region-bound: the access token, the Q Developer profile ARN and the
+ * runtime endpoint must all match the region the IdC instance lives in (e.g. eu-central-1).
+ * A request signed for one region is rejected by another ("bearer token is invalid"), and a
+ * regional profileArn sent to us-east-1 fails with "Improperly formed request". Falls back to
+ * the region embedded in the profileArn, then us-east-1 (the AWS Builder ID default).
+ */
+export function resolveKiroRegion(
+ credentials: { providerSpecificData?: unknown } | null | undefined
+): string {
+ const psd = (credentials?.providerSpecificData || {}) as Record<string, unknown>;
+ const region = typeof psd.region === "string" ? psd.region.trim().toLowerCase() : "";
+ if (region) return region;
+ const arn = typeof psd.profileArn === "string" ? psd.profileArn.toLowerCase() : "";
+ const match = arn.match(/^arn:aws:codewhisperer:([a-z0-9-]+):/);
+ return match ? match[1] : "us-east-1";
+}
+
+/**
+ * CodeWhisperer/Amazon Q runtime host for a region. us-east-1 keeps the legacy
+ * codewhisperer.us-east-1 host (AWS Builder ID); other regions use the regional Amazon Q
+ * endpoint q.{region}.amazonaws.com — codewhisperer.{region}.amazonaws.com does not resolve
+ * for non-us-east-1 regions.
+ */
+export function kiroRuntimeHost(region: string): string {
+ return region === "us-east-1"
+ ? "https://codewhisperer.us-east-1.amazonaws.com"
+ : `https://q.${region}.amazonaws.com`;
+}
+
/**
* KiroExecutor - Executor for Kiro AI (AWS CodeWhisperer)
* Uses AWS CodeWhisperer streaming API with AWS EventStream binary format
@@ -228,7 +259,11 @@ export class KiroExecutor extends BaseExecutor {
log,
upstreamExtraHeaders,
}: ExecuteInput) {
- const url = this.buildUrl(model, stream, 0);
+ // Route to the region-specific CodeWhisperer/Amazon Q endpoint. Enterprise IAM Identity
+ // Center accounts (e.g. eu-central-1) are rejected by the default us-east-1 host; only the
+ // regional endpoint accepts the region-bound token + profileArn.
+ const region = resolveKiroRegion(credentials);
+ const url = `${kiroRuntimeHost(region)}/generateAssistantResponse`;
const headers = this.buildHeaders(credentials, stream);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const transformedBody = await this.transformRequest(model, body, stream, credentials);
diff --git a/open-sse/executors/mimocode.ts b/open-sse/executors/mimocode.ts
new file mode 100644
index 0000000000..d75d24174f
--- /dev/null
+++ b/open-sse/executors/mimocode.ts
@@ -0,0 +1,328 @@
+/**
+ * MiMoCode Executor — Free-tier Xiaomi MiMo models via bootstrap JWT auth.
+ *
+ * Implements the auth flow from the official MiMo-Code repository:
+ * https://github.com/XiaomiMiMo/MiMo-Code/blob/main/packages/opencode/src/plugin/mimo-free.ts
+ *
+ * 1. Generate device fingerprint from hostname + OS + arch + CPU + username
+ * 2. POST /api/free-ai/bootstrap with fingerprint → JWT
+ * 3. Use JWT as Bearer token for chat requests
+ * 4. Custom endpoint: /api/free-ai/openai/chat (not /v1/chat/completions)
+ * 5. Custom header: X-Mimo-Source: mimocode-cli-free
+ *
+ * Only the "mimo-auto" model is supported (1M context, 128K output).
+ * Supports multiple accounts: N fingerprints → N JWTs → round-robin with cooldown.
+ * On 429, account enters cooldown (exponential backoff). On 401/403, JWT is re-bootstrapped.
+ */
+
+import * as crypto from "node:crypto";
+import * as os from "node:os";
+import { BaseExecutor, type ExecuteInput, type ProviderCredentials } from "./base.ts";
+
+const BOOTSTRAP_PATH = "/api/free-ai/bootstrap";
+const CHAT_PATH = "/api/free-ai/openai/chat";
+const JWT_REFRESH_BUFFER_MS = 5 * 60 * 1000;
+const BOOTSTRAP_TIMEOUT_MS = 15_000;
+const COOLDOWN_BASE_MS = 5_000;
+const COOLDOWN_MAX_MS = 60_000;
+
+const MIMO_SOURCE = "mimocode-cli-free";
+
+const USER_AGENTS = [
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
+];
+
+// ── Account State ──────────────────────────────────────────────────────────
+
+interface AccountState {
+ fingerprint: string;
+ jwt: string;
+ expiresAt: number;
+ cooldownUntil: number;
+ consecutiveFails: number;
+}
+
+function parseJwtExp(jwt: string): number {
+ try {
+ const parts = jwt.split(".");
+ if (parts.length < 2) return Date.now() + 50 * 60 * 1000;
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
+ return (payload.exp ?? Math.floor(Date.now() / 1000) + 3000) * 1000;
+ } catch {
+ return Date.now() + 50 * 60 * 1000;
+ }
+}
+
+function isAccountReady(account: AccountState): boolean {
+ if (account.cooldownUntil > Date.now()) return false;
+ if (account.jwt && account.expiresAt - Date.now() > JWT_REFRESH_BUFFER_MS) return true;
+ return false;
+}
+
+// ── Fingerprint Generation ─────────────────────────────────────────────────
+
+function getCpuModel(): string {
+ try {
+ const cpus = os.cpus();
+ if (cpus.length > 0 && cpus[0].model) return cpus[0].model.trim();
+ } catch { /* ignore */ }
+ return "unknown-cpu";
+}
+
+export function generateFingerprint(seed?: string): string {
+ if (seed) return crypto.createHash("sha256").update(seed).digest("hex");
+ const hostname = os.hostname();
+ const platform = os.platform();
+ const arch = os.arch();
+ const cpu = getCpuModel();
+ let username = "unknown-user";
+ try {
+ username = os.userInfo().username;
+ } catch { /* ignore */ }
+ return crypto.createHash("sha256").update(`${hostname}|${platform}|${arch}|${cpu}|${username}`).digest("hex");
+}
+
+// ── Bootstrap ──────────────────────────────────────────────────────────────
+
+const bootstrapInflight = new Map<string, Promise<{ jwt: string; expiresAt: number }>>();
+
+async function bootstrapJwt(
+ baseUrl: string,
+ fingerprint: string,
+ signal?: AbortSignal | null,
+): Promise<{ jwt: string; expiresAt: number }> {
+ const existing = bootstrapInflight.get(fingerprint);
+ if (existing) return existing;
+
+ const url = `${baseUrl}${BOOTSTRAP_PATH}`;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), BOOTSTRAP_TIMEOUT_MS);
+ const onSignal = signal ? () => controller.abort(signal.reason) : null;
+ if (signal && onSignal) signal.addEventListener("abort", onSignal, { once: true });
+
+ const promise = (async () => {
+ try {
+ const resp = await fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ client: fingerprint }),
+ signal: controller.signal,
+ });
+ if (!resp.ok) {
+ const body = await resp.text().catch(() => "");
+ throw new Error(`Bootstrap failed: ${resp.status} ${body.slice(0, 200)}`);
+ }
+ const data = (await resp.json()) as { jwt?: string };
+ if (!data.jwt) throw new Error("Bootstrap response missing jwt field");
+ return { jwt: data.jwt, expiresAt: parseJwtExp(data.jwt) };
+ } finally {
+ clearTimeout(timer);
+ if (signal && onSignal) signal.removeEventListener("abort", onSignal);
+ bootstrapInflight.delete(fingerprint);
+ }
+ })();
+
+ bootstrapInflight.set(fingerprint, promise);
+ return promise;
+}
+
+// ── Model Rewriting ────────────────────────────────────────────────────────
+
+function rewriteModelName(model: string): string {
+ const idx = model.lastIndexOf("/");
+ return idx >= 0 ? model.slice(idx + 1) : model;
+}
+
+// ── Executor ───────────────────────────────────────────────────────────────
+
+export class MimocodeExecutor extends BaseExecutor {
+ private accounts: AccountState[] = [];
+ private nextAccountIdx = 0;
+ private baseUrl: string;
+ private static encoder = new TextEncoder();
+
+ constructor() {
+ super("mimocode", { format: "openai" });
+ this.baseUrl = this.getBaseUrls()[0] || "https://api.xiaomimimo.com";
+ this.accounts.push({ fingerprint: generateFingerprint(), jwt: "", expiresAt: 0, cooldownUntil: 0, consecutiveFails: 0 });
+ }
+
+ private syncAccountsFromCredentials(credentials: ProviderCredentials): void {
+ const fingerprints = credentials?.providerSpecificData?.fingerprints;
+ if (!Array.isArray(fingerprints)) return;
+ const existing = new Set(this.accounts.map((a) => a.fingerprint));
+ for (const fp of fingerprints) {
+ if (typeof fp === "string" && !existing.has(fp)) {
+ this.accounts.push({ fingerprint: fp, jwt: "", expiresAt: 0, cooldownUntil: 0, consecutiveFails: 0 });
+ existing.add(fp);
+ }
+ }
+ }
+
+ private async getJwtForAccount(account: AccountState, signal?: AbortSignal | null): Promise<string> {
+ if (isAccountReady(account)) return account.jwt;
+ const result = await bootstrapJwt(this.baseUrl, account.fingerprint, signal);
+ account.jwt = result.jwt;
+ account.expiresAt = result.expiresAt;
+ return account.jwt;
+ }
+
+ private pickAccount(): AccountState {
+ for (let i = 0; i < this.accounts.length; i++) {
+ const idx = (this.nextAccountIdx + i) % this.accounts.length;
+ const acct = this.accounts[idx];
+ if (isAccountReady(acct)) {
+ this.nextAccountIdx = (idx + 1) % this.accounts.length;
+ return acct;
+ }
+ }
+ const fallbackIdx = this.nextAccountIdx % this.accounts.length;
+ this.nextAccountIdx = (this.nextAccountIdx + 1) % this.accounts.length;
+ return this.accounts[fallbackIdx];
+ }
+
+ private markCooldown(account: AccountState): void {
+ account.consecutiveFails++;
+ const backoff = Math.min(COOLDOWN_BASE_MS * Math.pow(2, account.consecutiveFails - 1), COOLDOWN_MAX_MS);
+ account.cooldownUntil = Date.now() + backoff + Math.random() * 1000;
+ }
+
+ private markSuccess(account: AccountState): void {
+ account.consecutiveFails = 0;
+ }
+
+ buildUrl(_model: string, _stream: boolean, _urlIndex = 0, _credentials?: ProviderCredentials | null): string {
+ return `${this.baseUrl.replace(/\/$/, "")}${CHAT_PATH}`;
+ }
+
+ buildHeaders(
+ _credentials: ProviderCredentials,
+ stream = true,
+ _clientHeaders?: Record<string, string> | null,
+ _model?: string,
+ ): Record<string, string> {
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ "X-Mimo-Source": MIMO_SOURCE,
+ "User-Agent": USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)],
+ };
+ if (stream) headers["Accept"] = "text/event-stream, application/json";
+ return headers;
+ }
+
+ transformRequest(model: string, body: unknown, _stream: boolean, _credentials?: ProviderCredentials | null): unknown {
+ if (typeof body === "object" && body !== null) {
+ return { ...(body as Record<string, unknown>), model: rewriteModelName(model) };
+ }
+ return body;
+ }
+
+ async testConnection(
+ _credentials: ProviderCredentials,
+ _signal?: AbortSignal | null,
+ log?: ExecuteInput["log"],
+ ): Promise<boolean> {
+ try {
+ const account = this.accounts[0];
+ const jwt = await this.getJwtForAccount(account, _signal);
+ const resp = await fetch(this.buildUrl("mimo-auto", false), {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${jwt}`, "X-Mimo-Source": MIMO_SOURCE },
+ body: JSON.stringify({ model: "mimo-auto", messages: [{ role: "user", content: "ping" }], stream: false }),
+ signal: _signal ?? undefined,
+ });
+ return resp.status === 200;
+ } catch {
+ log?.warn?.("MIMOCODE", "testConnection network error");
+ return false;
+ }
+ }
+
+ async execute(input: ExecuteInput): Promise<{
+ response: Response;
+ url: string;
+ headers: Record<string, string>;
+ transformedBody: unknown;
+ }> {
+ const { model, stream, body, signal, log } = input;
+ const encoder = MimocodeExecutor.encoder;
+
+ if (signal?.aborted) {
+ return {
+ response: new Response(encoder.encode(JSON.stringify({
+ error: { message: "Request aborted", type: "abort", code: "ABORTED" },
+ })), { status: 499, headers: { "Content-Type": "application/json" } }),
+ url: this.buildUrl(model, stream),
+ headers: this.buildHeaders(input.credentials, stream),
+ transformedBody: body,
+ };
+ }
+
+ const url = this.buildUrl(model, stream);
+ const reqBody = this.transformRequest(model, body, stream, input.credentials);
+
+ this.syncAccountsFromCredentials(input.credentials);
+
+ // Try each account, skip cooldown ones
+ for (let attempt = 0; attempt < this.accounts.length; attempt++) {
+ const account = this.pickAccount();
+ try {
+ const jwt = await this.getJwtForAccount(account, signal);
+ const headers = this.buildHeaders(input.credentials, stream);
+ headers["Authorization"] = `Bearer ${jwt}`;
+
+ let resp = await fetch(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(reqBody),
+ signal: signal ?? undefined,
+ });
+
+ // On auth failure, re-bootstrap this account and retry once
+ if (resp.status === 401 || resp.status === 403) {
+ log?.warn?.("MIMOCODE", `Auth failed (${resp.status}) on account ${account.fingerprint.slice(0, 8)}…`);
+ account.jwt = "";
+ account.expiresAt = 0;
+ account.consecutiveFails = 0;
+ const freshJwt = await this.getJwtForAccount(account, signal);
+ headers["Authorization"] = `Bearer ${freshJwt}`;
+ resp = await fetch(url, { method: "POST", headers, body: JSON.stringify(reqBody), signal: signal ?? undefined });
+ }
+
+ if (resp.status === 429) {
+ this.markCooldown(account);
+ log?.warn?.("MIMOCODE", `Rate limited on account ${account.fingerprint.slice(0, 8)}, trying next…`);
+ continue;
+ }
+
+ this.markSuccess(account);
+ const respHeaders: Record<string, string> = {};
+ resp.headers.forEach((v, k) => { respHeaders[k] = v; });
+ return { response: resp as unknown as Response, url, headers: respHeaders, transformedBody: reqBody };
+ } catch (err) {
+ this.markCooldown(account);
+ if (attempt === this.accounts.length - 1) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log?.error?.("MIMOCODE", `Executor error: ${msg}`);
+ return {
+ response: new Response(encoder.encode(JSON.stringify({
+ error: { message: msg, type: "upstream_error", code: "EXECUTOR_ERROR" },
+ })), { status: 502, headers: { "Content-Type": "application/json" } }),
+ url, headers: this.buildHeaders(input.credentials, stream), transformedBody: body,
+ };
+ }
+ }
+ }
+
+ return {
+ response: new Response(encoder.encode(JSON.stringify({
+ error: { message: "All accounts exhausted", type: "upstream_error", code: "NO_ACCOUNTS" },
+ })), { status: 502, headers: { "Content-Type": "application/json" } }),
+ url, headers: this.buildHeaders(input.credentials, stream), transformedBody: body,
+ };
+ }
+}
+
+export default MimocodeExecutor;
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index cf8008f5c4..5198a21a7d 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -192,7 +192,12 @@ import {
getModelFamily,
} from "../services/modelFamilyFallback.ts";
import { computeRequestHash, deduplicate, shouldDeduplicate } from "../services/requestDedup.ts";
-import { compressContext, estimateTokens, getTokenLimit } from "../services/contextManager.ts";
+import {
+ compressContext,
+ estimateTokens,
+ getTokenLimit,
+ resolveComboContextLimit,
+} from "../services/contextManager.ts";
import {
getBackgroundTaskReason,
getDegradedModel,
@@ -2741,21 +2746,30 @@ export async function handleChatCore({
if (!comboConfig && comboName.startsWith("combo/")) {
comboConfig = await getComboByName(comboName.substring(6));
}
+ let comboTargetLimits: number[] = [];
if (comboConfig) {
const allCombosData = await getCombosCached();
const targets = resolveComboTargets(
comboConfig as unknown as { name: string; models: unknown[] },
allCombosData as unknown as { name: string; models: unknown[] }[]
);
- const limits = targets.map((t: { modelStr?: string }) => {
+ comboTargetLimits = targets.map((t: { modelStr?: string }) => {
const parsed = parseModel(t.modelStr);
return getTokenLimit(parsed.provider, parsed.model);
});
- if (limits.length > 0) {
- contextLimit = Math.min(...limits);
- log?.info?.("CONTEXT", `Combo min limit: ${contextLimit}`);
- }
}
+ // chatCore executes per concrete target (handleSingleModel resolves
+ // provider/effectiveModel before delegating). Compress against THIS
+ // target's window; min(...allTargets) is only a defensive fallback —
+ // the old unconditional min compressed a 1M-target request at the
+ // smallest sibling's window ("agent keeps forgetting things").
+ const resolved = resolveComboContextLimit({
+ provider,
+ model: effectiveModel,
+ comboTargetLimits,
+ });
+ contextLimit = resolved.limit;
+ log?.info?.("CONTEXT", `Combo context limit: ${resolved.limit} (source=${resolved.source})`);
} catch (err) {
log?.warn?.("CONTEXT", "Failed to resolve combo limits for compression: " + err);
}
diff --git a/open-sse/package.json b/open-sse/package.json
index d3ac81a28d..88578a28bd 100644
--- a/open-sse/package.json
+++ b/open-sse/package.json
@@ -1,6 +1,6 @@
{
"name": "@omniroute/open-sse",
- "version": "3.8.21",
+ "version": "3.8.22",
"description": "Express SSE sidecar for OmniRoute — handles streaming, protocol translation, and provider orchestration",
"type": "module",
"main": "index.js",
diff --git a/open-sse/services/autoCombo/virtualFactory.ts b/open-sse/services/autoCombo/virtualFactory.ts
index eb743f9959..e708fe70f7 100644
--- a/open-sse/services/autoCombo/virtualFactory.ts
+++ b/open-sse/services/autoCombo/virtualFactory.ts
@@ -8,6 +8,8 @@ import type { ConnectionFields } from "@/lib/db/encryption";
import { NOAUTH_PROVIDERS } from "@/shared/constants/providers";
import { hasUsableWebSessionCredential } from "@/shared/providers/webSessionCredentials";
import { defaultLogger as log } from "@omniroute/open-sse/utils/logger";
+import { getTokenLimit } from "../contextManager";
+import { getResolvedModelCapabilities } from "@/lib/modelCapabilities";
/** Minimal connection shape needed for virtual auto-combo factory */
interface VirtualFactoryConn extends ConnectionFields {
@@ -45,6 +47,11 @@ type VirtualAutoCombo = AutoComboConfig & {
weight: number;
label: string;
}>;
+ /** MAX of candidates' context windows — safe to advertise because the
+ * auto-combo context pre-filter routes oversized requests to large-window
+ * candidates. null when the pool is empty. */
+ advertisedContextLength: number | null;
+ advertisedMaxOutputTokens: number | null;
autoConfig: {
candidatePool: string[];
weights: ScoringWeights;
@@ -156,6 +163,46 @@ function getNoAuthCandidates(excludedProviders: Set<string>): VirtualAutoComboCa
* Creates a virtual AutoCombo configuration dynamically based on connected providers and a specified variant.
* This combo is not persisted in the DB.
*/
+/**
+ * Aggregate the context window / max output to ADVERTISE for an auto combo.
+ *
+ * MAX across candidates (not min): the auto-combo context pre-filter
+ * (combo.ts::filterTargetsByRequestCompatibility + the estimated-tokens
+ * pre-filter) already routes oversized requests away from small-window
+ * candidates, so advertising the largest window lets clients (e.g. opencode)
+ * keep their smart auto-compaction calibrated to the best candidate instead
+ * of compacting prematurely — or, worse, receiving 0 and disabling
+ * compaction entirely (the "agent keeps forgetting things" bug).
+ *
+ * Unknown candidates resolve through getTokenLimit()'s fallback chain, so a
+ * non-empty pool always yields a positive contextLength.
+ */
+export function computeAdvertisedLimits(candidates: Array<{ provider: string; model: string }>): {
+ contextLength: number | null;
+ maxOutputTokens: number | null;
+} {
+ if (!Array.isArray(candidates) || candidates.length === 0) {
+ return { contextLength: null, maxOutputTokens: null };
+ }
+
+ let contextLength: number | null = null;
+ let maxOutputTokens: number | null = null;
+ for (const candidate of candidates) {
+ const limit = getTokenLimit(candidate.provider, candidate.model);
+ if (Number.isFinite(limit) && limit > 0) {
+ contextLength = contextLength === null ? limit : Math.max(contextLength, limit);
+ }
+ const output = getResolvedModelCapabilities({
+ provider: candidate.provider,
+ model: candidate.model,
+ }).maxOutputTokens;
+ if (typeof output === "number" && Number.isFinite(output) && output > 0) {
+ maxOutputTokens = maxOutputTokens === null ? output : Math.max(maxOutputTokens, output);
+ }
+ }
+ return { contextLength, maxOutputTokens };
+}
+
export async function createVirtualAutoCombo(
variant: AutoVariant | undefined
): Promise<VirtualAutoCombo> {
@@ -209,6 +256,8 @@ export async function createVirtualAutoCombo(
routerStrategy: autoConfig.routerStrategy,
autoConfig,
config: { auto: autoConfig },
+ advertisedContextLength: null,
+ advertisedMaxOutputTokens: null,
};
}
@@ -259,6 +308,8 @@ export async function createVirtualAutoCombo(
routerStrategy,
};
+ const advertisedLimits = computeAdvertisedLimits(candidatePool);
+
return {
id: `virtual-auto-${variant || "default"}`,
name: `Auto ${variant || "Default"}`,
@@ -271,5 +322,7 @@ export async function createVirtualAutoCombo(
routerStrategy,
autoConfig,
config: { auto: autoConfig },
+ advertisedContextLength: advertisedLimits.contextLength,
+ advertisedMaxOutputTokens: advertisedLimits.maxOutputTokens,
};
}
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index 84425f276f..5095207bcc 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -125,6 +125,21 @@ function isAllAccountsRateLimitedResponse(
return ALL_ACCOUNTS_RATE_LIMITED_PATTERNS.some((p) => p.test(errorText));
}
+// #1731v2 guard: a provider circuit-breaker-open response (503 + `X-OmniRoute-Provider-Breaker`
+// header / `provider_circuit_open` error code, see providerCircuitOpenResponse) is an OmniRoute
+// resilience signal, NOT a per-connection upstream failure. It must keep being treated as an
+// ordinary target failure (try the next target, including same-provider ones) — so it must NOT
+// poison exhaustedConnections/exhaustedProviders, otherwise remaining same-provider targets get
+// wrongly skipped while the breaker is open.
+function isProviderCircuitOpenResult(
+ result: { headers?: Headers | null; status?: number },
+ errorText: string
+): boolean {
+ const breakerHeader = result.headers?.get?.("x-omniroute-provider-breaker");
+ if (typeof breakerHeader === "string" && breakerHeader.toLowerCase() === "open") return true;
+ return /provider_circuit_open/i.test(errorText);
+}
+
const MAX_COMBO_DEPTH = 3;
const MAX_FALLBACK_WAIT_MS = 5000;
const MAX_GLOBAL_ATTEMPTS = 30;
@@ -3334,6 +3349,7 @@ export async function handleComboChat({
// #1731: Per-set-iteration set of providers whose quota is fully exhausted.
// Reset each retry so providers excluded in a previous attempt get another chance.
const exhaustedProviders = new Set<string>();
+ const exhaustedConnections = new Set<string>();
const transientRateLimitedProviders = new Set<string>();
if (setTry > 0) {
log.info("COMBO", `All targets failed — retrying set (${setTry}/${maxSetRetries})`);
@@ -3409,6 +3425,18 @@ export async function handleComboChat({
}
: { ...target, modelAbortSignal: abortControllers.get(i)!.signal };
+ // #1731v2: Skip targets whose provider:connection pair had a connection-level error.
+ if (provider && target.connectionId) {
+ const connKey = `${provider}:${target.connectionId}`;
+ if (exhaustedConnections.has(connKey)) {
+ log.info(
+ "COMBO",
+ `Skipping ${modelStr} — connection ${target.connectionId} for provider ${provider} had connection error (#1731v2)`
+ );
+ if (i > 0) fallbackCount++;
+ return null;
+ }
+ }
// #1731: Skip targets from a provider that already signaled full quota exhaustion this request.
if (provider && exhaustedProviders.has(provider)) {
log.info(
@@ -3917,6 +3945,31 @@ export async function handleComboChat({
) {
transientRateLimitedProviders.add(provider);
}
+ // #1731: Connection-level errors (502/503/504) suggest the provider itself is having
+ // issues (e.g. upstream unreachable, proxy error). Skip remaining same-provider
+ // targets in this request to avoid hammering a known-bad connection.
+ if (
+ !providerExhausted &&
+ provider &&
+ provider !== "unknown" &&
+ [408, 500, 502, 503, 504, 524].includes(result.status) &&
+ !isProviderCircuitOpenResult(result, errorText)
+ ) {
+ const connId = target.connectionId as string | undefined;
+ if (connId) {
+ exhaustedConnections.add(`${provider}:${connId}`);
+ log.info(
+ "COMBO",
+ `Provider ${provider} connection ${connId} error (${result.status}) — marking for skip on remaining targets (#1731v2)`
+ );
+ } else {
+ exhaustedProviders.add(provider);
+ log.info(
+ "COMBO",
+ `Provider ${provider} connection error (${result.status}) — marking for skip on remaining targets (#1731)`
+ );
+ }
+ }
// #2101: Prevent infinite fallback loops with 400 Bad Request errors that indicate
// request-body-specific issues (context overflow, malformed request, model access denied).
@@ -4221,6 +4274,7 @@ async function handleRoundRobinCombo({
// When a target returns a quota-exhausted 429, remaining targets from the same
// provider are skipped to avoid the cascade through N same-provider targets.
const exhaustedProviders = new Set<string>();
+ const exhaustedConnections = new Set<string>();
const transientRateLimitedProviders = new Set<string>();
// Try each model starting from the round-robin target
@@ -4262,6 +4316,18 @@ async function handleRoundRobinCombo({
// #1731: Skip targets from a provider that already signaled full quota exhaustion
// this request.
+ // #1731v2: Skip targets whose provider:connection pair had a connection-level error.
+ if (provider && target.connectionId) {
+ const connKey = `${provider}:${target.connectionId}`;
+ if (exhaustedConnections.has(connKey)) {
+ log.info(
+ "COMBO-RR",
+ `Skipping ${modelStr} — connection ${target.connectionId} for provider ${provider} had connection error (#1731v2)`
+ );
+ if (offset > 0) fallbackCount++;
+ continue;
+ }
+ }
if (provider && exhaustedProviders.has(provider)) {
log.info(
"COMBO-RR",
@@ -4538,6 +4604,30 @@ async function handleRoundRobinCombo({
transientRateLimitedProviders.add(provider);
}
+ // #1731v2: Connection-level errors (502/503/504) — skip remaining same-connection targets
+ if (
+ !providerExhausted &&
+ provider &&
+ provider !== "unknown" &&
+ [408, 500, 502, 503, 504, 524].includes(result.status) &&
+ !isProviderCircuitOpenResult(result, errorText)
+ ) {
+ const connId = target.connectionId as string | undefined;
+ if (connId) {
+ exhaustedConnections.add(`${provider}:${connId}`);
+ log.info(
+ "COMBO-RR",
+ `Provider ${provider} connection ${connId} error (${result.status}) — marking for skip (#1731v2)`
+ );
+ } else {
+ exhaustedProviders.add(provider);
+ log.info(
+ "COMBO-RR",
+ `Provider ${provider} connection error (${result.status}) — marking for skip (#1731)`
+ );
+ }
+ }
+
// Transient errors → mark in semaphore so round-robin stops stampeding this target.
if (
!isStreamReadinessFailure &&
diff --git a/open-sse/services/contextManager.ts b/open-sse/services/contextManager.ts
index baad8b0204..e2c4917132 100644
--- a/open-sse/services/contextManager.ts
+++ b/open-sse/services/contextManager.ts
@@ -61,27 +61,40 @@ export function estimateTokens(text: string | object | null | undefined): number
* Priority: Env override > models.dev DB > Registry defaultContextLength > DEFAULT_LIMITS
*/
export function getTokenLimit(provider: string, model: string | null = null): number {
+ return resolveTokenLimit(provider, model).limit;
+}
+
+/**
+ * Same chain as getTokenLimit, but also reports whether the limit came from
+ * a provider/model-specific source (env override, synced DB, registry,
+ * name heuristic, curated per-provider default) or only from the generic
+ * catch-all default.
+ */
+function resolveTokenLimit(
+ provider: string,
+ model: string | null = null
+): { limit: number; specific: boolean } {
// 1. Check environment variable override first
const envOverride = getEnvOverride(provider);
- if (envOverride) return envOverride;
+ if (envOverride) return { limit: envOverride, specific: true };
// 2. Check models.dev synced DB for per-model context limit
if (model) {
const dbLimit = getModelContextLimit(provider, model);
- if (dbLimit && dbLimit > 0) return dbLimit;
+ if (dbLimit && dbLimit > 0) return { limit: dbLimit, specific: true };
}
// 3. Check registry for provider default
const registryEntry = REGISTRY[provider];
if (registryEntry?.defaultContextLength) {
- return registryEntry.defaultContextLength;
+ return { limit: registryEntry.defaultContextLength, specific: true };
}
// 4. Check if model name hints at a known limit
if (model) {
const lower = model.toLowerCase();
- if (lower.includes("claude")) return DEFAULT_LIMITS.claude;
- if (lower.includes("gemini")) return DEFAULT_LIMITS.gemini;
+ if (lower.includes("claude")) return { limit: DEFAULT_LIMITS.claude, specific: true };
+ if (lower.includes("gemini")) return { limit: DEFAULT_LIMITS.gemini, specific: true };
if (
lower.includes("gpt") ||
lower.includes("o1") ||
@@ -89,11 +102,44 @@ export function getTokenLimit(provider: string, model: string | null = null): nu
lower.includes("o4") ||
lower.includes("codex")
)
- return DEFAULT_LIMITS.codex;
+ return { limit: DEFAULT_LIMITS.codex, specific: true };
}
// 5. Fallback to DEFAULT_LIMITS or default
- return DEFAULT_LIMITS[provider] || DEFAULT_LIMITS.default;
+ if (DEFAULT_LIMITS[provider]) return { limit: DEFAULT_LIMITS[provider], specific: true };
+ return { limit: DEFAULT_LIMITS.default, specific: false };
+}
+
+/**
+ * Resolve the context limit to use for proactive compression of a COMBO
+ * request.
+ *
+ * chatCore always executes with the CONCRETE target's provider/model
+ * (handleSingleModel resolves the target before delegating), so the
+ * executing target's own limit is authoritative. Using min(...allTargets)
+ * here — the previous behavior — compressed at the smallest sibling's
+ * window even when running on the largest target, destructively purging
+ * history long before the real window filled ("agent keeps forgetting").
+ *
+ * min(...comboTargetLimits) is kept only as a defensive fallback for the
+ * case where the current provider/model resolves no specific limit at all.
+ */
+export function resolveComboContextLimit(options: {
+ provider: string;
+ model: string | null;
+ comboTargetLimits: number[];
+}): { limit: number; source: "target" | "combo-min" | "fallback" } {
+ const own = resolveTokenLimit(options.provider, options.model ?? null);
+ if (own.specific) {
+ return { limit: own.limit, source: "target" };
+ }
+ const knownTargets = (options.comboTargetLimits || []).filter(
+ (value) => Number.isFinite(value) && value > 0
+ );
+ if (knownTargets.length > 0) {
+ return { limit: Math.min(...knownTargets), source: "combo-min" };
+ }
+ return { limit: own.limit, source: "fallback" };
}
/**
diff --git a/open-sse/services/model.ts b/open-sse/services/model.ts
index ec0f0844ff..5d306d6fa7 100644
--- a/open-sse/services/model.ts
+++ b/open-sse/services/model.ts
@@ -272,6 +272,40 @@ async function getActiveProviderSet() {
}
}
+function isTruthyEnv(value: string | undefined) {
+ return typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim());
+}
+
+async function getPreferClaudeCodeForUnprefixedClaudeModels() {
+ try {
+ const { getCachedSettings } = await import("@/lib/localDb");
+ const settings = (await getCachedSettings()) as Record<string, unknown>;
+ if (typeof settings.preferClaudeCodeForUnprefixedClaudeModels === "boolean") {
+ return settings.preferClaudeCodeForUnprefixedClaudeModels;
+ }
+ } catch {
+ // Standalone open-sse usage may not have the app DB layer available.
+ }
+
+ return isTruthyEnv(process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS);
+}
+
+function shouldPreferClaudeCodeForUnprefixedClaudeModel(
+ modelId: string,
+ activeProviders: Set<string> | null,
+ preferClaudeCode: boolean
+) {
+ if (!preferClaudeCode || !/^claude-/i.test(modelId)) {
+ return false;
+ }
+
+ // If DB/provider state is unavailable in a lightweight runtime, honor the
+ // explicit operator flag and let the normal credential path report any missing
+ // Claude Code account. When state is available, avoid stealing traffic from
+ // other Claude-family providers unless Claude Code is actually active.
+ return activeProviders === null || activeProviders.size === 0 || activeProviders.has("claude");
+}
+
function shouldTreatAsExactModelId(modelStr: string | null) {
if (!modelStr || typeof modelStr !== "string" || !modelStr.includes("/")) return false;
if (!KNOWN_MODEL_IDS.has(modelStr)) return false;
@@ -448,7 +482,10 @@ async function resolveModelByProviderInference(modelId: string, extendedContext:
};
}
- const activeProviders = await getActiveProviderSet();
+ const [activeProviders, preferClaudeCodeForUnprefixedClaudeModels] = await Promise.all([
+ getActiveProviderSet(),
+ getPreferClaudeCodeForUnprefixedClaudeModels(),
+ ]);
// Preserve historical behavior: OpenAI stays default when model exists there.
// Connection availability must not make unprefixed OpenAI models resolve to a
@@ -485,6 +522,21 @@ async function resolveModelByProviderInference(modelId: string, extendedContext:
const candidatesToUse = nonOpenAIProviders;
+ if (
+ candidatesToUse.includes("claude") &&
+ shouldPreferClaudeCodeForUnprefixedClaudeModel(
+ modelId,
+ activeProviders,
+ preferClaudeCodeForUnprefixedClaudeModels
+ )
+ ) {
+ return {
+ provider: "claude",
+ model: resolveInferredProviderModel("claude", modelId),
+ extendedContext,
+ };
+ }
+
if (candidatesToUse.length === 1) {
const provider = candidatesToUse[0];
const canonicalModel = resolveInferredProviderModel(provider, modelId);
@@ -510,6 +562,15 @@ async function resolveModelByProviderInference(modelId: string, extendedContext:
// FIX #73: Models like claude-haiku-4-5-20251001 sent without provider prefix
// would incorrectly route to OpenAI. Use heuristic prefix detection first.
if (/^claude-/i.test(modelId)) {
+ if (
+ shouldPreferClaudeCodeForUnprefixedClaudeModel(
+ modelId,
+ activeProviders,
+ preferClaudeCodeForUnprefixedClaudeModels
+ )
+ ) {
+ return { provider: "claude", model: modelId, extendedContext };
+ }
// Claude models → Anthropic provider (canonical source for Claude models)
return { provider: "anthropic", model: modelId, extendedContext };
}
diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts
index 38336b2947..d33cbcea4a 100644
--- a/open-sse/services/usage.ts
+++ b/open-sse/services/usage.ts
@@ -3005,6 +3005,22 @@ async function getKiroUsage(accessToken?: string, providerSpecificData?: JsonRec
return { message: "Kiro connected. Profile ARN not available for quota tracking." };
}
+ // Enterprise IAM Identity Center accounts are region-bound: the profileArn, token and
+ // endpoint must all match the region. Derive the region from the stored region (preferred)
+ // or the profileArn, then route to the regional Amazon Q endpoint (us-east-1 keeps the
+ // legacy codewhisperer host; codewhisperer.{region} does not resolve for other regions).
+ const regionFromArn =
+ typeof profileArn === "string"
+ ? profileArn.toLowerCase().match(/^arn:aws:codewhisperer:([a-z0-9-]+):/)?.[1]
+ : undefined;
+ const region =
+ (typeof providerSpecificData?.region === "string" &&
+ providerSpecificData.region.trim().toLowerCase()) ||
+ regionFromArn ||
+ "us-east-1";
+ const usageBaseUrl =
+ region === "us-east-1" ? CODEWHISPERER_BASE_URL : `https://q.${region}.amazonaws.com`;
+
// Kiro uses AWS CodeWhisperer GetUsageLimits API
const payload = {
origin: "AI_EDITOR",
@@ -3012,7 +3028,7 @@ async function getKiroUsage(accessToken?: string, providerSpecificData?: JsonRec
resourceType: "AGENTIC_REQUEST",
};
- const response = await fetch(CODEWHISPERER_BASE_URL, {
+ const response = await fetch(usageBaseUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
diff --git a/open-sse/translator/index.ts b/open-sse/translator/index.ts
index 4bb82b6c1c..fc73ef656f 100644
--- a/open-sse/translator/index.ts
+++ b/open-sse/translator/index.ts
@@ -103,10 +103,6 @@ function hasNonEmptyReasoningContent(message: Record<string, unknown>): boolean
return typeof message.reasoning_content === "string" && message.reasoning_content.length > 0;
}
-function hasReasoningContentField(message: Record<string, unknown>): boolean {
- return Object.prototype.hasOwnProperty.call(message, "reasoning_content");
-}
-
function isDeepSeekReplayTarget(provider: unknown, model: unknown): boolean {
const normalizedProvider = String(provider ?? "")
.trim()
@@ -179,7 +175,10 @@ export function translateRequest(
// quirks (e.g. Vertex rejects function_call.id — #3440).
const directCredentials =
provider != null
- ? { ...(credentials && typeof credentials === "object" ? credentials : {}), _provider: provider }
+ ? {
+ ...(credentials && typeof credentials === "object" ? credentials : {}),
+ _provider: provider,
+ }
: credentials;
result = directTranslator(model, result, stream, directCredentials);
} else {
@@ -319,15 +318,23 @@ export function translateRequest(
Array.isArray(msg.content) &&
msg.content.some((b) => b?.type === "tool_use");
+ // For DeepSeek replay targets, a plain (non-tool-call) assistant turn must
+ // ALSO carry reasoning_content in thinking mode, or DeepSeek V4+ returns 400:
+ // "The reasoning_content in the thinking mode must be passed back to the API."
+ // Enter the replay path when the field is MISSING or empty (#1682) — not only
+ // when it is already present (the previous gate only matched messages that
+ // already had the field, so stripped-history turns from clients like Cursor
+ // were skipped and forwarded without reasoning_content).
const shouldReplayReasoningOnly =
!hasToolCalls &&
!hasToolUseBlocks &&
canReplayReasoningOnly &&
- hasReasoningContentField(msg);
+ !hasNonEmptyReasoningContent(msg);
if (!hasToolCalls && !hasToolUseBlocks && !shouldReplayReasoningOnly) {
- // Strip empty reasoning_content on non-tool-call messages; an empty
- // string has no meaningful value to send and may confuse some upstreams.
+ // Strip empty reasoning_content on non-tool-call messages we are NOT
+ // replaying (e.g. non-DeepSeek targets); an empty string has no meaningful
+ // value to send and may confuse some upstreams.
if (msg.reasoning_content === "") {
delete msg.reasoning_content;
}
@@ -392,7 +399,12 @@ export function translateRequest(
// Note: injectEmptyReasoningContentForToolCalls may have pre-set
// reasoning_content="" before the cache lookup, so we check for
// both undefined AND empty string here.
- if (hasToolCalls && !msg.reasoning_content) {
+ //
+ // Applies to tool-call messages AND to plain (non-tool-call) assistant turns
+ // on DeepSeek replay targets (#1682). Without the placeholder on plain turns,
+ // a multi-turn text conversation whose reasoning_content the client stripped
+ // is forwarded to DeepSeek without the field and rejected with 400.
+ if ((hasToolCalls || shouldReplayReasoningOnly) && !msg.reasoning_content) {
msg.reasoning_content = NON_ANTHROPIC_THINKING_PLACEHOLDER;
}
}
diff --git a/open-sse/utils/streamReadiness.ts b/open-sse/utils/streamReadiness.ts
index b61d5a6f3b..22cae4ce35 100644
--- a/open-sse/utils/streamReadiness.ts
+++ b/open-sse/utils/streamReadiness.ts
@@ -104,9 +104,13 @@ function hasOpenAIResponseLifecyclePayload(
}
function hasChatCompletionToolCallStart(value: unknown): boolean {
- const hasToolCallId = (item: unknown) => isRecord(item) && hasNonEmptyString(item.id);
- if (Array.isArray(value)) return value.some(hasToolCallId);
- return hasToolCallId(value);
+ // Accept a tool_call item if it has a non-empty id (fully-formed chunk) OR if it
+ // carries a numeric index (first OpenAI streaming chunk — id/name arrive in later
+ // chunks). Either form signals that a tool call has started. (#3612)
+ const hasToolCallStart = (item: unknown) =>
+ isRecord(item) && (hasNonEmptyString(item.id) || typeof item.index === "number");
+ if (Array.isArray(value)) return value.some(hasToolCallStart);
+ return hasToolCallStart(value);
}
function hasChatCompletionFunctionCallStart(value: unknown): boolean {
@@ -114,9 +118,15 @@ function hasChatCompletionFunctionCallStart(value: unknown): boolean {
}
function hasChatCompletionChunkStartPayload(payload: Record<string, unknown>): boolean {
- if (payload.object !== "chat.completion.chunk" && payload.type !== "chat.completion.chunk") {
- return false;
- }
+ // If object or type is PRESENT and is clearly a non-chat-chunk type, reject early.
+ // If both are absent (many OA-compatible backends omit object), we fall through and
+ // let the choices structure decide. (#3612)
+ const obj = payload.object;
+ const typ = payload.type;
+ const hasForeignObject =
+ (typeof obj === "string" && obj !== "chat.completion.chunk") ||
+ (typeof typ === "string" && typ !== "chat.completion.chunk");
+ if (hasForeignObject) return false;
const choices = payload.choices;
if (!Array.isArray(choices) || choices.length === 0) return false;
diff --git a/package-lock.json b/package-lock.json
index fa09e1edb8..78cbbecb02 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "omniroute",
- "version": "3.8.21",
+ "version": "3.8.22",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "omniroute",
- "version": "3.8.21",
+ "version": "3.8.22",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
@@ -21587,7 +21587,7 @@
},
"open-sse": {
"name": "@omniroute/open-sse",
- "version": "3.8.21"
+ "version": "3.8.22"
}
}
}
diff --git a/package.json b/package.json
index 8f20558fba..07985c5800 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "omniroute",
- "version": "3.8.21",
+ "version": "3.8.22",
"description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.",
"type": "module",
"bin": {
diff --git a/scripts/check/check-db-rules.mjs b/scripts/check/check-db-rules.mjs
index 8c76b2f737..b5c83990ca 100644
--- a/scripts/check/check-db-rules.mjs
+++ b/scripts/check/check-db-rules.mjs
@@ -21,62 +21,69 @@ const LOCAL_DB = path.join(cwd, "src/lib/localDb.ts");
const API_DIR = path.join(cwd, "src/app/api");
const HANDLERS_DIR = path.join(cwd, "open-sse/handlers");
-// (a) Módulos db/ que NÃO são re-exportados por localDb.ts hoje. Congelados
-// para a catraca ficar verde e bloquear QUALQUER módulo novo não re-exportado.
-// CADA UM é dívida: ou é consumido por import direto de "@/lib/db/X" (legítimo,
-// não precisa de re-export) ou deveria ser re-exportado. NÃO adicione novos aqui
-// sem justificativa — esse é o ponto do gate (Hard Rule #2).
-const KNOWN_UNEXPORTED = new Set([
- "_rowTypes", // só tipos de linha (sem runtime API), consumido localmente pelos CRUDs F2
- "cleanup", // rotina de manutenção, chamada por jobs/rotas via import direto
- "cliToolState", // estado de CLI tools, import direto pelos consumidores
- "comboForecast", // previsão de combo, import direto
- "commandCodeAuth", // auth de command-code, import direto
- "compression", // núcleo de compressão, import direto
- "compressionScheduler", // scheduler, import direto
- "detailedLogs", // logs detalhados, import direto
- "discovery", // discovery de modelos, import direto
- "domainState", // estado de domínio/circuit breaker, import direto
- "encryption", // util de cripto at-rest, import direto
- "healthCheck", // health check de DB, import direto
- "jsonMigration", // migração JSON→SQLite (one-shot), import direto
- "migrationRunner", // runner de migrations, import direto
- "notion", // integração Notion, import direto
- "obsidian", // integração Obsidian, import direto
- "pluginMetrics", // métricas de plugin, import direto
- "prompts", // prompts salvos, import direto
- "providerStats", // stats de provider, import direto
- "recovery", // recuperação de DB, import direto
- "secrets", // secrets store, import direto
- "serviceModels", // modelos de serviços embutidos, import direto
- "stateReset", // reset de estado de resiliência, import direto
- "stats", // agregações de stats, import direto
- "tierConfig", // config de tier, import direto
+// (a) Módulos db/ que NÃO são re-exportados por localDb.ts por DESIGN (Hard Rule #2:
+// "Never barrel-import from localDb.ts — import specific db/ modules instead").
+// Cada entrada aqui foi auditada e é consumida via import direto de "@/lib/db/X"
+// (estático ou dinâmico) pelos seus consumidores — exatamente o padrão correto.
+// Re-exportar esses módulos via localDb.ts INCENTIVARIA o anti-padrão proibido.
+// O gate ainda bloqueia QUALQUER módulo db/ NOVO que não seja re-exportado E não
+// esteja nessa lista — mantendo a decisão consciente obrigatória (Hard Rule #2).
+// Legenda de classificação:
+// type-only = exporta apenas tipos (sem runtime API), não há o que re-exportar
+// db-internal = importado apenas dentro de src/lib/db/ (coordenação interna)
+// intentionally-internal = consumido por import direto fora de db/ (correto per Rule #2)
+// DEAD? = zero importers encontrados na auditoria de 2026-06-11; não deletar
+// sem investigação — pode ser reserva de schema ou F2 pendente
+export const INTENTIONALLY_INTERNAL = new Set([
+ "_rowTypes", // type-only: 5 importers internos em db/ (AgentBridge/Inspector row types)
+ "cleanup", // intentionally-internal: 3 API routes (purge-quota-snapshots, purge-call-logs, purge-detailed-logs)
+ "cliToolState", // intentionally-internal: 14+ API routes em /api/cli-tools/*-settings
+ "comboForecast", // intentionally-internal: src/lib/usage/comboForecast.ts
+ "commandCodeAuth", // intentionally-internal: 5 API routes em /api/providers/command-code/auth/*
+ "compression", // intentionally-internal: 2 API routes (settings/compression, context/rtk/config)
+ "compressionScheduler", // DEAD?: 0 importers na auditoria de 2026-06-11; mantido para schema reservation
+ "detailedLogs", // intentionally-internal: 3 callers (callLogs.ts, logs/detail route, embeddings handler)
+ "discovery", // DEAD?: 0 importers na auditoria de 2026-06-11; lib/discovery/index.ts não usa db/discovery
+ "domainState", // intentionally-internal: 5 callers (batchWriter, circuitBreaker, costRules, fallbackPolicy, lockoutPolicy)
+ "encryption", // intentionally-internal: 8+ callers (container, webhookDispatcher, cloudAgent/credentials, services/apiKey, 4+ routes, open-sse)
+ "healthCheck", // db-internal: importado por db/core.ts (runDbHealthCheck)
+ "jsonMigration", // intentionally-internal: src/app/api/settings/import-json/route.ts
+ "migrationRunner", // db-internal: importado por db/core.ts (runMigrations ao inicializar o DB)
+ "notion", // intentionally-internal: settings/notion API route + open-sse/mcp-server/tools/notionTools.ts
+ "obsidian", // intentionally-internal: src/lib/obsidianSync.ts + settings/obsidian route + MCP obsidianTools.ts
+ "pluginMetrics", // DEAD? (production): write path não foi conectado ainda (documentado no cabeçalho do módulo); testado por tests/unit/plugins-metrics.test.ts
+ "prompts", // DEAD? (production): zero callers de produção encontrados; domínio domain/prompts.ts é independente; testado por tests/integration/proxy-pipeline.test.ts
+ "providerStats", // intentionally-internal: src/app/api/provider-stats/route.ts
+ "recovery", // intentionally-internal: bin/cli/runtime.mjs (import() dinâmico) + tests
+ "secrets", // intentionally-internal: src/instrumentation-node.ts (import() dinâmico na inicialização)
+ "serviceModels", // intentionally-internal: 3 callers (services/modelSync, services/bootstrap, /api/services/9router/models)
+ "stateReset", // db-internal: 3 callers dentro de src/lib/db/ (core, backup, apiKeys) para coordenação de reset
+ "stats", // intentionally-internal: src/app/api/settings/database/refresh-stats/route.ts
+ "tierConfig", // intentionally-internal: open-sse/services/tierResolver.ts (require() dinâmico)
]);
-// (c) Ofensores de SQL cru PRÉ-EXISTENTES em rotas/handlers. Congelados para a
-// catraca ficar verde e bloquear QUALQUER nova rota/handler com SQL inline.
-// CADA UM é dívida da Hard Rule #5: mover para um módulo src/lib/db/. NÃO
-// adicione novos aqui sem justificativa — crie/estenda um módulo db/ em vez disso.
-// (Chaves = caminho relativo POSIX a partir da raiz do repo.)
-const KNOWN_RAW_SQL = new Set([
- "src/app/api/analytics/auto-routing/route.ts", // SELECT … FROM usage_logs
- "src/app/api/cache/entries/route.ts", // semantic_cache COUNT/DELETE inline
- "src/app/api/db-backups/exportAll/route.ts", // SELECT key_value/combos/connections/keys
- "src/app/api/db-backups/import/route.ts", // SELECT sqlite_master + COUNTs
- "src/app/api/gamification/federation/leaderboard/route.ts", // SELECT community_servers
- "src/app/api/gamification/federation/score/route.ts", // SELECT community_servers
- "src/app/api/logs/export/route.ts", // SELECT de proxy_logs
- "src/app/api/oauth/cursor/auto-import/route.ts", // SELECT no itemTable do Cursor (DB externo)
- "src/app/api/oauth/kiro/auto-import/route.ts", // SELECT no SQLite do Kiro (DB externo)
- "src/app/api/provider-metrics/route.ts", // SELECT … FROM call_logs (agregação)
- "src/app/api/search/stats/route.ts", // SELECT … FROM call_logs
- "src/app/api/settings/export-json/route.ts", // SELECT * de usage_history/domain_*
- "src/app/api/skills/[id]/route.ts", // UPDATE skills SET dinâmico
- "src/app/api/usage/analytics/route.ts", // SELECT … FROM usage_history/daily_usage_summary
- "src/app/api/v1/search/analytics/route.ts", // SELECT … FROM call_logs (request_type=search)
+// Alias para retrocompatibilidade com os testes existentes que importam KNOWN_UNEXPORTED.
+// O comportamento do gate é idêntico — só o nome e os comentários mudaram (#3499).
+export const KNOWN_UNEXPORTED = INTENTIONALLY_INTERNAL;
+
+// (c) Leituras de SQL contra bancos EXTERNOS, permitidas por design (#3500).
+// Estas rotas NÃO consultam o DB do OmniRoute (getDbInstance) — elas abrem o
+// SQLite de OUTRO aplicativo (Cursor / Kiro) para auto-importar credenciais.
+// Por isso NÃO podem viver em src/lib/db/ (que é o domínio do DB do OmniRoute):
+// são leituras read-only de um arquivo externo, com caminho/escopo próprios.
+// Continuam no allowlist como exceção DOCUMENTADA — o gate ainda bloqueia
+// QUALQUER novo SQL cru contra o DB do OmniRoute em rotas/handlers.
+// Toda a dívida real da Hard Rule #5 (15 rotas internas) foi migrada para
+// módulos src/lib/db/ nas slices do #3500; este set ficou só com as exceções.
+const EXTERNAL_DB_ALLOWED = new Set([
+ "src/app/api/oauth/cursor/auto-import/route.ts", // read-only no itemTable do SQLite do Cursor (DB externo)
+ "src/app/api/oauth/kiro/auto-import/route.ts", // read-only no SQLite do Kiro (DB externo)
]);
+// Alias de retrocompatibilidade (testes/consumidores que importam KNOWN_RAW_SQL).
+// Comportamento do gate idêntico — só o nome e o enquadramento mudaram (#3500).
+const KNOWN_RAW_SQL = EXTERNAL_DB_ALLOWED;
+
// Módulos sempre excluídos da checagem (a): não são domínio re-exportável.
const DB_MODULE_EXCLUDE = new Set(["core", "localDb", "index"]);
@@ -112,8 +119,10 @@ export function extractReexportedModules(localDbSource) {
return out;
}
-// (a) Módulos db/ que não são re-exportados e não estão congelados.
-export function findMissingReexports(dbModules, reexported, allowlist = KNOWN_UNEXPORTED) {
+// (a) Módulos db/ que não são re-exportados e não estão na lista de
+// intencionalmente-internos (INTENTIONALLY_INTERNAL). O gate falha para
+// qualquer módulo NOVO que não seja re-exportado nem justificado.
+export function findMissingReexports(dbModules, reexported, allowlist = INTENTIONALLY_INTERNAL) {
return dbModules.filter((mod) => !reexported.has(mod) && !allowlist.has(mod));
}
@@ -216,7 +225,7 @@ function main() {
`[#2 re-export] ${missing.length} módulo(s) db/ não re-exportado(s) por src/lib/localDb.ts:\n` +
missing.map((m) => ` ✗ src/lib/db/${m}.ts`).join("\n") +
`\n → re-exporte de src/lib/localDb.ts (apenas a lista de re-export, nada de lógica)` +
- ` ou adicione a KNOWN_UNEXPORTED com justificativa (import direto de "@/lib/db/${missing[0]}").`
+ ` ou adicione a INTENTIONALLY_INTERNAL com justificativa (import direto de "@/lib/db/${missing[0]}").`
);
}
@@ -245,7 +254,7 @@ function main() {
}
console.log(
`[check-db-rules] OK (${dbModules.length} módulos db/, ${reexported.size} re-exportados, ` +
- `${KNOWN_UNEXPORTED.size} congelados; ${KNOWN_RAW_SQL.size} ofensores de SQL congelados)`
+ `${INTENTIONALLY_INTERNAL.size} intencionalmente-internos (Rule #2); ${EXTERNAL_DB_ALLOWED.size} leituras de DB externo permitidas (#3500))`
);
}
diff --git a/scripts/check/check-fetch-targets.mjs b/scripts/check/check-fetch-targets.mjs
index 6c504376ac..b51517e208 100644
--- a/scripts/check/check-fetch-targets.mjs
+++ b/scripts/check/check-fetch-targets.mjs
@@ -24,7 +24,7 @@ const IGNORE = [
// inventada. CADA UM precisa de triagem: criar a rota, corrigir o path, ou remover a
// chamada morta. NÃO adicione novos aqui sem justificativa — esse é o ponto do gate.
const KNOWN_MISSING = new Set([
- "/api/settings/obsidian/webdav", // ObsidianSourceCard.tsx — só existe /api/settings/obsidian
+ // All previously known-missing routes have been resolved.
]);
function walk(dir, acc = []) {
diff --git a/scripts/dev/responses-ws-proxy.mjs b/scripts/dev/responses-ws-proxy.mjs
index 0a8201dc7a..abbb435e8f 100644
--- a/scripts/dev/responses-ws-proxy.mjs
+++ b/scripts/dev/responses-ws-proxy.mjs
@@ -50,6 +50,10 @@ function isText(value) {
return typeof value === "string" && value.length > 0;
}
+function isRecord(value) {
+ return value && typeof value === "object" && !Array.isArray(value);
+}
+
function jsonStringifySafe(value) {
try {
return JSON.stringify(value);
@@ -67,6 +71,92 @@ function jsonStringifySafe(value) {
}
}
+function parseJsonRecord(value) {
+ try {
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
+ return isRecord(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+function toFiniteNumber(value) {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : 0;
+}
+
+function toStringOrNull(value) {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+}
+
+function buildFailurePayload(code, message) {
+ return {
+ type: "response.failed",
+ response: {
+ id: null,
+ status: "failed",
+ error: {
+ code,
+ message,
+ },
+ },
+ };
+}
+
+function getResponseErrorStatus(error) {
+ if (!isRecord(error)) return null;
+ const candidates = [
+ error.status,
+ error.status_code,
+ error.statusCode,
+ error.code === "usage_limit_reached" ? 429 : null,
+ ];
+ for (const candidate of candidates) {
+ const status = Number(candidate);
+ if (Number.isInteger(status) && status >= 400 && status <= 599) return status;
+ }
+ return null;
+}
+
+function getTerminalResponseEvent(rawData) {
+ const message = parseJsonRecord(rawData);
+ if (!message) return null;
+
+ const type = toStringOrNull(message.type) || "";
+ const response = isRecord(message.response) ? message.response : {};
+ const statusText = toStringOrNull(response.status) || "";
+
+ if (type === "response.completed" || type === "response.done" || statusText === "completed") {
+ return {
+ status: 200,
+ success: true,
+ terminalMessage: message,
+ responseBody: response,
+ };
+ }
+
+ if (type === "response.failed" || type === "response.error" || statusText === "failed") {
+ const error = isRecord(response.error)
+ ? response.error
+ : isRecord(message.error)
+ ? message.error
+ : null;
+ return {
+ status: getResponseErrorStatus(error) || 500,
+ success: false,
+ errorCode: toStringOrNull(error?.code) || "upstream_response_failed",
+ errorMessage:
+ toStringOrNull(error?.message) ||
+ toStringOrNull(response.error) ||
+ "Codex upstream response failed",
+ terminalMessage: message,
+ responseBody: response,
+ };
+ }
+
+ return null;
+}
+
export function isResponsesWsPath(pathname) {
return RESPONSES_WS_PUBLIC_PATHS.has(pathname);
}
@@ -314,6 +404,7 @@ class ResponsesWsSession {
this.maxBufferBytes = normalizePositiveInteger(maxBufferBytes, DEFAULT_MAX_WS_BUFFER_BYTES);
this.maxMessageBytes = normalizePositiveInteger(maxMessageBytes, DEFAULT_MAX_WS_MESSAGE_BYTES);
this.sessionId = randomUUID();
+ this.startedAt = Date.now();
this.closed = false;
this.buffer = Buffer.alloc(0);
this.fragmentOpcode = null;
@@ -322,6 +413,9 @@ class ResponsesWsSession {
this.processing = Promise.resolve();
this.upstream = null;
this.upstreamReady = null;
+ this.firstResponseBody = null;
+ this.preparedContext = null;
+ this.historyLogged = false;
this.lastSeenAt = Date.now();
this.pingTimer = setInterval(() => {
@@ -376,17 +470,9 @@ class ResponsesWsSession {
}
sendFailure(code, message) {
- this.sendJson({
- type: "response.failed",
- response: {
- id: null,
- status: "failed",
- error: {
- code,
- message,
- },
- },
- });
+ const payload = buildFailurePayload(code, message);
+ this.sendJson(payload);
+ return payload;
}
async onData(chunk) {
@@ -490,6 +576,7 @@ class ResponsesWsSession {
if (responseBody === null) {
throw new Error("First Responses WebSocket message must be response.create");
}
+ this.firstResponseBody ||= responseBody;
const prepared = await callInternal(
this.fetchImpl,
@@ -513,9 +600,21 @@ class ResponsesWsSession {
const code = prepared.json?.error?.code || "codex_ws_prepare_failed";
const error = new Error(message);
error.code = code;
+ error.status = prepared.status;
throw error;
}
+ this.preparedContext = {
+ upstreamUrl: toStringOrNull(prepared.json?.upstreamUrl),
+ connectionId: toStringOrNull(prepared.json?.connectionId),
+ account: toStringOrNull(prepared.json?.account),
+ provider: toStringOrNull(prepared.json?.provider) || "codex",
+ model: toStringOrNull(prepared.json?.model) || toStringOrNull(responseBody.model),
+ requestedModel: toStringOrNull(responseBody.model),
+ serviceTier:
+ toStringOrNull(responseBody.service_tier) || toStringOrNull(responseBody.serviceTier),
+ };
+
const upstream = await this.wsFactory(prepared.json.upstreamUrl, {
browser: prepared.json.browser || "chrome_142",
os: prepared.json.os || "windows",
@@ -526,17 +625,36 @@ class ResponsesWsSession {
if (this.closed) return;
const data =
typeof event.data === "string" ? event.data : Buffer.from(event.data).toString("utf8");
+ const terminalEvent = getTerminalResponseEvent(data);
+ if (terminalEvent) {
+ void this.persistHistory(terminalEvent);
+ }
this.sendFrame(0x1, Buffer.from(data, "utf8"));
};
upstream.onerror = (event) => {
if (this.closed) return;
- this.sendFailure(
- "upstream_websocket_error",
- event.message || "Codex upstream WebSocket error"
- );
+ const errorMessage = event.message || "Codex upstream WebSocket error";
+ const failurePayload = this.sendFailure("upstream_websocket_error", errorMessage);
+ void this.persistHistory({
+ status: 502,
+ success: false,
+ errorCode: "upstream_websocket_error",
+ errorMessage,
+ terminalMessage: failurePayload,
+ });
};
upstream.onclose = (event) => {
if (this.closed) return;
+ void this.persistHistory({
+ status: event.code === 1000 ? 499 : 502,
+ success: false,
+ errorCode: "upstream_websocket_closed",
+ errorMessage: event.reason || "Codex upstream WebSocket closed before completion",
+ terminalMessage: buildFailurePayload(
+ "upstream_websocket_closed",
+ event.reason || "Codex upstream WebSocket closed before completion"
+ ),
+ });
this.close(event.code || 1000, event.reason || "upstream_closed");
};
@@ -561,11 +679,56 @@ class ResponsesWsSession {
} catch (error) {
const code = error?.code || "upstream_websocket_connect_failed";
const messageText = error instanceof Error ? error.message : String(error);
- this.sendFailure(code, messageText);
+ const failurePayload = this.sendFailure(code, messageText);
+ void this.persistHistory({
+ status: Number.isInteger(error?.status) ? error.status : 502,
+ success: false,
+ errorCode: code,
+ errorMessage: messageText,
+ terminalMessage: failurePayload,
+ });
this.close(1011, "upstream_connect_failed");
}
}
+ async persistHistory({
+ status = 200,
+ success = true,
+ errorCode = null,
+ errorMessage = null,
+ terminalMessage = null,
+ responseBody = null,
+ } = {}) {
+ if (this.historyLogged || !this.firstResponseBody) return;
+ this.historyLogged = true;
+
+ const finishedAt = Date.now();
+ try {
+ await callInternal(this.fetchImpl, this.baseUrl, this.bridgeSecret, "log", {
+ sessionId: this.sessionId,
+ transport: "responses_websocket",
+ requestUrl: this.requestUrl,
+ headers: getAuthHeaders(this.requestUrl, this.requestHeaders),
+ path: new URL(this.requestUrl || "/v1/responses", "http://omniroute.local").pathname,
+ startedAt: new Date(this.startedAt).toISOString(),
+ completedAt: new Date(finishedAt).toISOString(),
+ durationMs: Math.max(0, finishedAt - this.startedAt),
+ status: toFiniteNumber(status),
+ success,
+ errorCode,
+ errorMessage,
+ clientRequest: this.firstResponseBody,
+ terminalMessage,
+ responseBody,
+ sourceFormat: "openai-responses",
+ targetFormat: "openai-responses",
+ ...this.preparedContext,
+ });
+ } catch {
+ // History logging must never break an already-established WebSocket session.
+ }
+ }
+
close(code = 1000, reason = "normal_closure") {
if (this.closed) return;
this.closed = true;
diff --git a/scripts/dev/standalone-server-ws.mjs b/scripts/dev/standalone-server-ws.mjs
index e7d4fb7672..b12f2093cf 100644
--- a/scripts/dev/standalone-server-ws.mjs
+++ b/scripts/dev/standalone-server-ws.mjs
@@ -2,6 +2,7 @@ import http from "node:http";
import { randomUUID } from "node:crypto";
import { createResponsesWsProxy } from "./responses-ws-proxy.mjs";
import { ensurePeerStampToken, wrapRequestListenerWithPeerStamp } from "./peer-stamp.mjs";
+import { maybeHandleWebdav } from "./webdav-handler.mjs";
const originalCreateServer = http.createServer.bind(http);
const proxiesByPort = new Map();
@@ -48,12 +49,32 @@ function wrapUpgradeListener(server, listener) {
};
}
+/**
+ * Wrap a request listener so WebDAV requests at /api/v1/webdav are handled
+ * before the peer-stamp/Next.js layer sees them.
+ * Returns true if the request was handled; the wrapped listener is never called.
+ */
+function wrapRequestListenerWithWebdav(listener) {
+ return async function webdavAwareRequestHandler(req, res) {
+ try {
+ const handled = await maybeHandleWebdav(req, res);
+ if (handled) return;
+ } catch {
+ // Never block a request on WebDAV errors — fall through to Next
+ }
+ return listener.call(this, req, res);
+ };
+}
+
http.createServer = function createServerWithResponsesWs(...args) {
// Next's standalone server.js may pass its request listener directly to
// createServer; wrap it so the real TCP peer IP is stamped before Next runs.
const lastFnIdx = args.map((a) => typeof a === "function").lastIndexOf(true);
if (lastFnIdx >= 0) {
- args[lastFnIdx] = wrapRequestListenerWithPeerStamp(args[lastFnIdx]);
+ // WebDAV intercept wraps outermost (first to run), then peer-stamp, then Next.
+ args[lastFnIdx] = wrapRequestListenerWithWebdav(
+ wrapRequestListenerWithPeerStamp(args[lastFnIdx])
+ );
}
const server = originalCreateServer(...args);
@@ -66,7 +87,10 @@ http.createServer = function createServerWithResponsesWs(...args) {
}
// …or it may attach the handler via server.on("request"): wrap that too.
if (eventName === "request" && typeof listener === "function") {
- return originalOn(eventName, wrapRequestListenerWithPeerStamp(listener));
+ return originalOn(
+ eventName,
+ wrapRequestListenerWithWebdav(wrapRequestListenerWithPeerStamp(listener))
+ );
}
return originalOn(eventName, listener);
};
@@ -76,7 +100,10 @@ http.createServer = function createServerWithResponsesWs(...args) {
return originalAddListener(eventName, wrapUpgradeListener(server, listener));
}
if (eventName === "request" && typeof listener === "function") {
- return originalAddListener(eventName, wrapRequestListenerWithPeerStamp(listener));
+ return originalAddListener(
+ eventName,
+ wrapRequestListenerWithWebdav(wrapRequestListenerWithPeerStamp(listener))
+ );
}
return originalAddListener(eventName, listener);
};
diff --git a/scripts/dev/webdav-handler.mjs b/scripts/dev/webdav-handler.mjs
new file mode 100644
index 0000000000..0113cc1b65
--- /dev/null
+++ b/scripts/dev/webdav-handler.mjs
@@ -0,0 +1,1002 @@
+/**
+ * WebDAV file server handler for OmniRoute.
+ *
+ * Serves the Obsidian vault directory at /api/v1/webdav, enabling
+ * Obsidian mobile (Remotely-Save plugin) to sync over Tailscale.
+ *
+ * Architecture:
+ * - Pure logic functions (resolveVaultPath, verifyBasicAuth, buildPropfindXml,
+ * decryptStored) are exported and unit-tested independently.
+ * - maybeHandleWebdav(req, res) is the thin HTTP+fs binding layer.
+ * - Credentials, enabled flag, and vault path are loaded from the same
+ * SQLite DB the app uses (DATA_DIR/storage.sqlite, key_value table).
+ *
+ * Security:
+ * - Path traversal guard on every request + Destination header.
+ * - Basic Auth with crypto.timingSafeEqual (constant-time).
+ * - No raw fs paths or stack traces in error response bodies.
+ * - NOT local-only — reachable over Tailscale; auth is the gate.
+ * - PUT body capped at MAX_PUT_BYTES.
+ */
+
+import fs from "node:fs";
+import path from "node:path";
+import { createDecipheriv, scryptSync, createHash, timingSafeEqual } from "node:crypto";
+import { createRequire } from "node:module";
+import os from "node:os";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Constants
+// ─────────────────────────────────────────────────────────────────────────────
+
+export const WEBDAV_PREFIX = "/api/v1/webdav";
+
+/** Cap PUT body to 512 MiB — Obsidian vaults are unlikely to need larger. */
+export const MAX_PUT_BYTES = 512 * 1024 * 1024;
+
+const WEBDAV_METHODS = new Set([
+ "PROPFIND",
+ "GET",
+ "HEAD",
+ "PUT",
+ "DELETE",
+ "MKCOL",
+ "MOVE",
+ "COPY",
+ "OPTIONS",
+ "LOCK",
+ "UNLOCK",
+]);
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Encryption: minimal port of src/lib/db/encryption.ts
+// Must reproduce the EXACT format: enc:v1:<iv_hex>:<ciphertext_hex>:<authTag_hex>
+// Key derivation: scryptSync(secret, "omniroute-field-encryption-v1", 32)
+// ─────────────────────────────────────────────────────────────────────────────
+
+const ENC_PREFIX = "enc:v1:";
+const STATIC_SALT = "omniroute-field-encryption-v1";
+const KEY_LENGTH = 32;
+const AUTH_TAG_LENGTH = 16;
+const ALGORITHM = "aes-256-gcm";
+
+let _cachedStaticKey = null;
+
+/**
+ * Derive the static-salt encryption key from STORAGE_ENCRYPTION_KEY.
+ * Returns null if the env var is not set (passthrough mode).
+ */
+function getStaticKey() {
+ if (_cachedStaticKey !== null) return _cachedStaticKey;
+ const secret = process.env.STORAGE_ENCRYPTION_KEY;
+ if (!secret || typeof secret !== "string" || secret.trim().length === 0) return null;
+ try {
+ _cachedStaticKey = scryptSync(secret, STATIC_SALT, KEY_LENGTH);
+ } catch {
+ return null;
+ }
+ return _cachedStaticKey;
+}
+
+/**
+ * Decrypt a value that may be encrypted with the OmniRoute enc:v1: format.
+ * If the value does not have the enc:v1: prefix, treat as plaintext (backward compat).
+ * Returns null if decryption fails.
+ *
+ * @param {string | null | undefined} stored
+ * @returns {string | null}
+ */
+export function decryptStored(stored) {
+ if (!stored || typeof stored !== "string") return null;
+
+ // Plaintext passthrough (no encryption key configured, or legacy plaintext)
+ if (!stored.startsWith(ENC_PREFIX)) return stored;
+
+ const key = getStaticKey();
+ if (!key) {
+ // Encrypted value but no key — cannot decrypt
+ return null;
+ }
+
+ const body = stored.slice(ENC_PREFIX.length);
+ const parts = body.split(":");
+ if (parts.length !== 3) return null;
+
+ const [ivHex, encryptedHex, authTagHex] = parts;
+ try {
+ const iv = Buffer.from(ivHex, "hex");
+ const authTag = Buffer.from(authTagHex, "hex");
+ const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
+ decipher.setAuthTag(authTag);
+ let decrypted = decipher.update(encryptedHex, "hex", "utf8");
+ decrypted += decipher.final("utf8");
+ return decrypted;
+ } catch {
+ return null;
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Pure logic
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Resolve a WebDAV request URL path to an absolute filesystem path within vaultRoot.
+ * Strips the /api/v1/webdav prefix and decodes percent-encoding.
+ *
+ * MANDATORY path-traversal guard:
+ * const abs = path.resolve(vaultRoot, rel);
+ * if (abs !== vaultRoot && !abs.startsWith(vaultRoot + path.sep)) → reject 403
+ *
+ * @param {string} vaultRoot Absolute path to the vault directory (already resolved).
+ * @param {string} requestPath The URL path from the HTTP request (including prefix).
+ * @returns {{ absPath: string, rel: string }} absPath is safe absolute path.
+ * @throws {{ status: 403, message: string }} On path traversal attempt.
+ */
+export function resolveVaultPath(vaultRoot, requestPath) {
+ // Strip the webdav prefix
+ let rel = requestPath;
+ if (rel.startsWith(WEBDAV_PREFIX)) {
+ rel = rel.slice(WEBDAV_PREFIX.length);
+ }
+ // Remove query string if present
+ const qmark = rel.indexOf("?");
+ if (qmark !== -1) rel = rel.slice(0, qmark);
+
+ // Decode percent-encoding — do this BEFORE path.resolve to catch %2e%2e
+ let decoded;
+ try {
+ decoded = decodeURIComponent(rel);
+ } catch {
+ // Malformed encoding — treat as the raw string
+ decoded = rel;
+ }
+
+ // Normalise: strip leading slash so path.resolve(root, "foo") works
+ const stripped = decoded.replace(/^\/+/, "");
+
+ // Resolve absolute path
+ const abs = path.resolve(vaultRoot, stripped);
+
+ // Guard: abs must BE vaultRoot or be strictly inside it
+ const normalRoot = path.resolve(vaultRoot);
+ if (abs !== normalRoot && !abs.startsWith(normalRoot + path.sep)) {
+ throw { status: 403, message: "Forbidden: path traversal detected" };
+ }
+
+ return { absPath: abs, rel: stripped };
+}
+
+/**
+ * Validate a Destination header value for MOVE/COPY against the same vault root.
+ *
+ * @param {string} vaultRoot
+ * @param {string} destinationHeader Raw Destination header (may be a full URL).
+ * @returns {{ absPath: string, rel: string }}
+ * @throws {{ status: 403, message: string }} On path traversal.
+ */
+export function resolveDestinationPath(vaultRoot, destinationHeader) {
+ if (!destinationHeader || typeof destinationHeader !== "string") {
+ throw { status: 400, message: "Missing Destination header" };
+ }
+
+ // Destination may be a full URL — extract the path component
+ let destPath = destinationHeader;
+ try {
+ const url = new URL(destinationHeader);
+ destPath = url.pathname;
+ } catch {
+ // Not a full URL — treat as a path directly
+ }
+
+ // Strip webdav prefix from the path
+ return resolveVaultPath(vaultRoot, destPath);
+}
+
+/**
+ * Verify HTTP Basic Authentication credentials.
+ * Uses crypto.timingSafeEqual for constant-time comparison (prevents timing attacks).
+ *
+ * @param {string | undefined} authHeader The Authorization header value.
+ * @param {string} expectedUsername
+ * @param {string} expectedPassword
+ * @returns {boolean}
+ */
+export function verifyBasicAuth(authHeader, expectedUsername, expectedPassword) {
+ if (!authHeader || typeof authHeader !== "string") return false;
+
+ const match = /^Basic\s+(.+)$/i.exec(authHeader.trim());
+ if (!match) return false;
+
+ let decoded;
+ try {
+ decoded = Buffer.from(match[1], "base64").toString("utf8");
+ } catch {
+ return false;
+ }
+
+ const colonIdx = decoded.indexOf(":");
+ if (colonIdx === -1) return false;
+
+ const suppliedUser = decoded.slice(0, colonIdx);
+ const suppliedPass = decoded.slice(colonIdx + 1);
+
+ // Constant-time comparison — BOTH user and pass must be compared to prevent
+ // timing oracles. We pad to the same length to avoid short-circuit length leaks.
+ const expectedUserBuf = Buffer.from(expectedUsername, "utf8");
+ const expectedPassBuf = Buffer.from(expectedPassword, "utf8");
+ const suppliedUserBuf = Buffer.from(suppliedUser, "utf8");
+ const suppliedPassBuf = Buffer.from(suppliedPass, "utf8");
+
+ // timingSafeEqual requires buffers of the same length — pad if needed
+ function safeCompare(a, b) {
+ const maxLen = Math.max(a.length, b.length);
+ const aPadded = Buffer.concat([a, Buffer.alloc(maxLen - a.length)]);
+ const bPadded = Buffer.concat([b, Buffer.alloc(maxLen - b.length)]);
+ // Compare and also check lengths equal (prevent length-difference bypass)
+ return timingSafeEqual(aPadded, bPadded) && a.length === b.length;
+ }
+
+ const userOk = safeCompare(suppliedUserBuf, expectedUserBuf);
+ const passOk = safeCompare(suppliedPassBuf, expectedPassBuf);
+
+ // Both must be true — avoid short-circuit (already avoided by timingSafeEqual)
+ return userOk && passOk;
+}
+
+/**
+ * Escape XML special characters.
+ *
+ * @param {string} str
+ * @returns {string}
+ */
+export function escapeXml(str) {
+ return String(str)
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&apos;");
+}
+
+/**
+ * Format a Date to RFC 1123 / HTTP-date format (required by WebDAV getlastmodified).
+ *
+ * @param {Date} date
+ * @returns {string}
+ */
+export function formatHttpDate(date) {
+ return date.toUTCString();
+}
+
+/**
+ * Build a WebDAV PROPFIND 207 Multi-Status XML response body.
+ *
+ * @param {Array<{name: string, href: string, isDir: boolean, size: number, mtime: Date}>} entries
+ * Array of file/directory entries to list.
+ * @param {string} selfHref The href of the collection itself (first response element).
+ * @returns {string} XML string for the 207 response body.
+ */
+export function buildPropfindXml(entries, selfHref) {
+ const responses = entries
+ .map((entry) => {
+ const resourceType = entry.isDir
+ ? "<D:resourcetype><D:collection/></D:resourcetype>"
+ : "<D:resourcetype/>";
+ const contentLength = entry.isDir
+ ? ""
+ : `<D:getcontentlength>${entry.size}</D:getcontentlength>`;
+ const contentType = entry.isDir
+ ? "<D:getcontenttype>httpd/unix-directory</D:getcontenttype>"
+ : `<D:getcontenttype>application/octet-stream</D:getcontenttype>`;
+
+ return (
+ `<D:response>` +
+ `<D:href>${escapeXml(entry.href)}</D:href>` +
+ `<D:propstat>` +
+ `<D:prop>` +
+ `<D:displayname>${escapeXml(entry.name)}</D:displayname>` +
+ resourceType +
+ contentLength +
+ contentType +
+ `<D:getlastmodified>${escapeXml(formatHttpDate(entry.mtime))}</D:getlastmodified>` +
+ `</D:prop>` +
+ `<D:status>HTTP/1.1 200 OK</D:status>` +
+ `</D:propstat>` +
+ `</D:response>`
+ );
+ })
+ .join("");
+
+ return (
+ `<?xml version="1.0" encoding="utf-8"?>` +
+ `<D:multistatus xmlns:D="DAV:">` +
+ responses +
+ `</D:multistatus>`
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// DB credential loading
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Resolve the SQLite database path.
+ * Mirrors the logic in src/lib/db/core.ts: DATA_DIR/storage.sqlite
+ *
+ * @returns {string | null}
+ */
+function resolveSqlitePath() {
+ return path.join(resolveDataDir(), "storage.sqlite");
+}
+
+/**
+ * Resolve the data directory. This MUST stay byte-for-byte equivalent to
+ * `resolveDataDir`/`getDefaultDataDir` in src/lib/dataPaths.ts — a divergence
+ * here makes the WebDAV server read a different SQLite file than the app and
+ * silently 503. (A parity test in tests/unit/webdav-server-3485.test.ts pins this.)
+ */
+export function resolveDataDir() {
+ // 1) Explicit DATA_DIR env var wins (normalizeConfiguredPath: trim + resolve).
+ const configured = process.env.DATA_DIR;
+ if (typeof configured === "string" && configured.trim().length > 0) {
+ return path.resolve(configured.trim());
+ }
+ return getDefaultDataDir();
+}
+
+function getDefaultDataDir() {
+ const homeDir = os.homedir();
+ const legacyDir = path.join(homeDir, ".omniroute"); // getLegacyDotDataDir()
+
+ // 2) Preserve the legacy ~/.omniroute path if it already exists (avoid data loss).
+ try {
+ if (fs.existsSync(legacyDir) && fs.statSync(legacyDir).isDirectory()) {
+ return legacyDir;
+ }
+ } catch {
+ // ignore stat errors
+ }
+
+ // 3) Windows → %APPDATA%/omniroute.
+ if (process.platform === "win32") {
+ const appData = process.env.APPDATA || path.join(homeDir, "AppData", "Roaming");
+ return path.join(appData, "omniroute");
+ }
+
+ // 4) XDG on Linux/macOS only when XDG_CONFIG_HOME is explicitly configured.
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME;
+ if (typeof xdgConfigHome === "string" && xdgConfigHome.trim().length > 0) {
+ return path.join(path.resolve(xdgConfigHome.trim()), "omniroute");
+ }
+
+ // 5) Default → legacy ~/.omniroute (even if it does not exist yet).
+ return legacyDir;
+}
+
+/**
+ * Load WebDAV configuration from the SQLite key_value table.
+ * Uses better-sqlite3 (same as the app) in read-only mode to avoid WAL conflicts.
+ *
+ * Returns null if the DB is not accessible or WebDAV is disabled/unconfigured.
+ *
+ * @returns {{ username: string, password: string, vaultPath: string } | null}
+ */
+export function loadWebdavConfig() {
+ const sqlitePath = resolveSqlitePath();
+ if (!sqlitePath || !fs.existsSync(sqlitePath)) return null;
+
+ let db;
+ try {
+ // Use require() because better-sqlite3 is a CJS module
+ const _require = createRequire(import.meta.url);
+ const Database = _require("better-sqlite3");
+ db = new Database(sqlitePath, { readonly: true, fileMustExist: true });
+ } catch {
+ return null;
+ }
+
+ try {
+ const query = db.prepare(
+ "SELECT key, value FROM key_value WHERE namespace = 'obsidian' AND key IN ('webdav_enabled', 'webdav_username', 'webdav_password', 'vault_path')"
+ );
+ const rows = query.all();
+
+ const kv = {};
+ for (const row of rows) {
+ try {
+ kv[row.key] = JSON.parse(row.value);
+ } catch {
+ kv[row.key] = row.value;
+ }
+ }
+
+ const enabled = kv["webdav_enabled"] === true;
+ if (!enabled) return null;
+
+ const username = typeof kv["webdav_username"] === "string" ? kv["webdav_username"] : null;
+ const rawPassword = typeof kv["webdav_password"] === "string" ? kv["webdav_password"] : null;
+ const vaultPath = typeof kv["vault_path"] === "string" ? kv["vault_path"] : null;
+
+ if (!username || !rawPassword || !vaultPath) return null;
+
+ const password = decryptStored(rawPassword);
+ if (!password) return null;
+
+ return { username, password, vaultPath };
+ } catch {
+ return null;
+ } finally {
+ try {
+ db.close();
+ } catch {
+ /* ignore */
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// HTTP helpers (thin binding layer)
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Send a plain-text error response — no raw paths or stack traces in the body.
+ *
+ * @param {import("node:http").ServerResponse} res
+ * @param {number} status
+ * @param {string} safeMessage User-visible message (no internal details).
+ * @param {Record<string, string>} [extraHeaders]
+ */
+function sendError(res, status, safeMessage, extraHeaders = {}) {
+ const body = safeMessage;
+ res.writeHead(status, {
+ "Content-Type": "text/plain; charset=utf-8",
+ "Content-Length": Buffer.byteLength(body),
+ ...extraHeaders,
+ });
+ res.end(body);
+}
+
+/**
+ * Send a 401 Unauthorized with WWW-Authenticate.
+ *
+ * @param {import("node:http").ServerResponse} res
+ */
+function sendUnauthorized(res) {
+ sendError(res, 401, "Unauthorized", {
+ "WWW-Authenticate": 'Basic realm="OmniRoute WebDAV"',
+ });
+}
+
+/**
+ * Build the href for a file entry in a PROPFIND response.
+ *
+ * @param {string} baseHref The base WebDAV path (e.g. /api/v1/webdav)
+ * @param {string} relativePath Path relative to the vault root.
+ * @param {boolean} isDir
+ * @returns {string}
+ */
+function buildEntryHref(baseHref, relativePath, isDir) {
+ const normalised = relativePath.replace(/\\/g, "/");
+ const encoded = normalised
+ .split("/")
+ .map((seg) => encodeURIComponent(seg))
+ .join("/");
+ const full = encoded ? `${baseHref}/${encoded}` : baseHref;
+ return isDir && !full.endsWith("/") ? `${full}/` : full;
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Method handlers
+// ─────────────────────────────────────────────────────────────────────────────
+
+/** Handle OPTIONS — return DAV capabilities. */
+function handleOptions(req, res) {
+ res.writeHead(200, {
+ DAV: "1, 2",
+ Allow:
+ "OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND, LOCK, UNLOCK",
+ "MS-Author-Via": "DAV",
+ "Content-Length": "0",
+ });
+ res.end();
+}
+
+/**
+ * Handle PROPFIND — list directory or file properties (Depth: 0 or 1).
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ * @param {string} requestPath
+ */
+function handlePropfind(req, res, absPath, requestPath) {
+ const depth = req.headers["depth"] || "1";
+
+ let stat;
+ try {
+ stat = fs.statSync(absPath);
+ } catch {
+ sendError(res, 404, "Not found");
+ return;
+ }
+
+ // Build href for the requested resource
+ let href = requestPath;
+ if (!href.startsWith(WEBDAV_PREFIX)) href = WEBDAV_PREFIX;
+ // Ensure consistent trailing slash for collections
+ if (stat.isDirectory() && !href.endsWith("/")) href += "/";
+
+ const entries = [];
+
+ // Self entry
+ entries.push({
+ name: path.basename(absPath) || "",
+ href,
+ isDir: stat.isDirectory(),
+ size: stat.isDirectory() ? 0 : stat.size,
+ mtime: stat.mtime,
+ });
+
+ // Children (Depth: 1 and it's a directory)
+ if (stat.isDirectory() && depth !== "0") {
+ let children;
+ try {
+ children = fs.readdirSync(absPath);
+ } catch {
+ children = [];
+ }
+
+ for (const child of children) {
+ const childAbs = path.join(absPath, child);
+ let childStat;
+ try {
+ childStat = fs.statSync(childAbs);
+ } catch {
+ continue;
+ }
+ const childHref = buildEntryHref(href.replace(/\/$/, ""), child, childStat.isDirectory());
+ entries.push({
+ name: child,
+ href: childHref,
+ isDir: childStat.isDirectory(),
+ size: childStat.isDirectory() ? 0 : childStat.size,
+ mtime: childStat.mtime,
+ });
+ }
+ }
+
+ const xml = buildPropfindXml(entries, href);
+ const body = Buffer.from(xml, "utf8");
+
+ res.writeHead(207, {
+ "Content-Type": "application/xml; charset=utf-8",
+ "Content-Length": body.length,
+ });
+ res.end(body);
+}
+
+/**
+ * Handle GET / HEAD — stream a file.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ * @param {boolean} headOnly
+ */
+function handleGet(req, res, absPath, headOnly) {
+ let stat;
+ try {
+ stat = fs.statSync(absPath);
+ } catch {
+ sendError(res, 404, "Not found");
+ return;
+ }
+
+ if (stat.isDirectory()) {
+ sendError(res, 405, "Method not allowed on a directory");
+ return;
+ }
+
+ res.writeHead(200, {
+ "Content-Type": "application/octet-stream",
+ "Content-Length": stat.size,
+ "Last-Modified": formatHttpDate(stat.mtime),
+ });
+
+ if (headOnly) {
+ res.end();
+ return;
+ }
+
+ const stream = fs.createReadStream(absPath);
+ stream.on("error", () => {
+ if (!res.headersSent) {
+ sendError(res, 500, "Read error");
+ } else {
+ res.destroy();
+ }
+ });
+ stream.pipe(res);
+}
+
+/**
+ * Handle PUT — write a file.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ */
+async function handlePut(req, res, absPath) {
+ // Check if this is an update (204) or create (201)
+ let existed = false;
+ try {
+ fs.statSync(absPath);
+ existed = true;
+ } catch {
+ /* new file */
+ }
+
+ // Ensure parent directory exists
+ try {
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
+ } catch {
+ sendError(res, 500, "Could not create parent directory");
+ return;
+ }
+
+ let written = 0;
+ let limitExceeded = false;
+ const tmpPath = absPath + ".omniroute-webdav-tmp-" + Date.now();
+ let writeStream;
+ try {
+ writeStream = fs.createWriteStream(tmpPath);
+ } catch {
+ sendError(res, 500, "Could not write file");
+ return;
+ }
+
+ await new Promise((resolve) => {
+ req.on("data", (chunk) => {
+ written += chunk.length;
+ if (written > MAX_PUT_BYTES) {
+ limitExceeded = true;
+ req.destroy();
+ writeStream.destroy();
+ } else {
+ writeStream.write(chunk);
+ }
+ });
+
+ req.on("end", () => {
+ writeStream.end();
+ resolve();
+ });
+
+ req.on("error", () => {
+ writeStream.destroy();
+ resolve();
+ });
+
+ writeStream.on("error", () => {
+ resolve();
+ });
+ });
+
+ if (limitExceeded) {
+ try {
+ fs.unlinkSync(tmpPath);
+ } catch {
+ /* ignore */
+ }
+ sendError(res, 413, "Payload too large");
+ return;
+ }
+
+ // Atomic rename
+ try {
+ fs.renameSync(tmpPath, absPath);
+ } catch {
+ try {
+ fs.unlinkSync(tmpPath);
+ } catch {
+ /* ignore */
+ }
+ sendError(res, 500, "Could not finalise file write");
+ return;
+ }
+
+ res.writeHead(existed ? 204 : 201, { "Content-Length": "0" });
+ res.end();
+}
+
+/**
+ * Handle DELETE — remove a file or empty directory.
+ *
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ */
+function handleDelete(res, absPath) {
+ let stat;
+ try {
+ stat = fs.statSync(absPath);
+ } catch {
+ sendError(res, 404, "Not found");
+ return;
+ }
+
+ try {
+ if (stat.isDirectory()) {
+ fs.rmdirSync(absPath, { recursive: true });
+ } else {
+ fs.unlinkSync(absPath);
+ }
+ res.writeHead(204, { "Content-Length": "0" });
+ res.end();
+ } catch {
+ sendError(res, 500, "Could not delete");
+ }
+}
+
+/**
+ * Handle MKCOL — create a directory.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ */
+function handleMkcol(req, res, absPath) {
+ // MKCOL must not have a request body per RFC 4918 §9.3
+ let bodyReceived = false;
+ req.on("data", () => {
+ bodyReceived = true;
+ });
+ req.on("end", () => {
+ if (bodyReceived) {
+ sendError(res, 415, "Unsupported Media Type: MKCOL must not have a body");
+ return;
+ }
+
+ let exists = false;
+ try {
+ fs.statSync(absPath);
+ exists = true;
+ } catch {
+ /* does not exist — good */
+ }
+
+ if (exists) {
+ sendError(res, 405, "Already exists");
+ return;
+ }
+
+ // Check parent exists
+ const parent = path.dirname(absPath);
+ let parentExists = false;
+ try {
+ fs.statSync(parent);
+ parentExists = true;
+ } catch {
+ /* parent missing */
+ }
+
+ if (!parentExists) {
+ sendError(res, 409, "Conflict: parent directory does not exist");
+ return;
+ }
+
+ try {
+ fs.mkdirSync(absPath);
+ res.writeHead(201, { "Content-Length": "0" });
+ res.end();
+ } catch {
+ sendError(res, 500, "Could not create directory");
+ }
+ });
+}
+
+/**
+ * Handle MOVE — rename/move a resource.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} absPath
+ * @param {string} vaultRoot
+ */
+function handleMove(req, res, absPath, vaultRoot) {
+ const destinationHeader = req.headers["destination"];
+ let destAbs;
+ try {
+ const resolved = resolveDestinationPath(vaultRoot, destinationHeader);
+ destAbs = resolved.absPath;
+ } catch (err) {
+ if (err && err.status) {
+ sendError(res, err.status, err.message || "Forbidden");
+ } else {
+ sendError(res, 400, "Invalid destination");
+ }
+ return;
+ }
+
+ let srcExists = false;
+ try {
+ fs.statSync(absPath);
+ srcExists = true;
+ } catch {
+ /* nope */
+ }
+
+ if (!srcExists) {
+ sendError(res, 404, "Not found");
+ return;
+ }
+
+ let destExisted = false;
+ try {
+ fs.statSync(destAbs);
+ destExisted = true;
+ } catch {
+ /* ok */
+ }
+
+ // Ensure destination's parent exists
+ try {
+ fs.mkdirSync(path.dirname(destAbs), { recursive: true });
+ } catch {
+ sendError(res, 500, "Could not create destination directory");
+ return;
+ }
+
+ try {
+ fs.renameSync(absPath, destAbs);
+ res.writeHead(destExisted ? 204 : 201, { "Content-Length": "0" });
+ res.end();
+ } catch {
+ sendError(res, 500, "Could not move resource");
+ }
+}
+
+/**
+ * Handle LOCK — stub that satisfies DAV: 2 clients.
+ * Returns a fake lock token so clients don't fail; we don't persist locks.
+ */
+function handleLock(req, res, absPath) {
+ const token = `urn:uuid:${Date.now().toString(16)}`;
+ const body =
+ `<?xml version="1.0" encoding="utf-8"?>` +
+ `<D:prop xmlns:D="DAV:">` +
+ `<D:lockdiscovery>` +
+ `<D:activelock>` +
+ `<D:locktoken><D:href>${escapeXml(token)}</D:href></D:locktoken>` +
+ `<D:lockscope><D:exclusive/></D:lockscope>` +
+ `<D:locktype><D:write/></D:locktype>` +
+ `<D:depth>0</D:depth>` +
+ `<D:timeout>Second-3600</D:timeout>` +
+ `</D:activelock>` +
+ `</D:lockdiscovery>` +
+ `</D:prop>`;
+ const buf = Buffer.from(body, "utf8");
+ res.writeHead(200, {
+ "Content-Type": "application/xml; charset=utf-8",
+ "Content-Length": buf.length,
+ "Lock-Token": `<${token}>`,
+ });
+ res.end(buf);
+}
+
+/** Handle UNLOCK — stub that acknowledges without persisting. */
+function handleUnlock(req, res) {
+ res.writeHead(204, { "Content-Length": "0" });
+ res.end();
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Main export: maybeHandleWebdav
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Entry point called from standalone-server-ws.mjs before forwarding to Next.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @returns {boolean} true if the request was handled (stop); false to forward to Next.
+ */
+export async function maybeHandleWebdav(req, res) {
+ const url = req.url || "";
+ const method = (req.method || "GET").toUpperCase();
+
+ // Only intercept /api/v1/webdav paths
+ if (!url.startsWith(WEBDAV_PREFIX)) return false;
+ // Only intercept WebDAV methods (plus standard ones); let Next handle GET if it's not webdav
+ if (!WEBDAV_METHODS.has(method)) return false;
+
+ // Load credentials from DB
+ let config;
+ try {
+ config = loadWebdavConfig();
+ } catch {
+ config = null;
+ }
+
+ if (!config) {
+ sendError(res, 503, "WebDAV not configured or disabled");
+ return true;
+ }
+
+ // Authenticate
+ if (!verifyBasicAuth(req.headers["authorization"], config.username, config.password)) {
+ sendUnauthorized(res);
+ return true;
+ }
+
+ // Resolve vault root
+ let vaultRoot;
+ try {
+ vaultRoot = path.resolve(config.vaultPath);
+ } catch {
+ sendError(res, 500, "Server configuration error");
+ return true;
+ }
+
+ // Resolve request path to absolute filesystem path
+ let absPath;
+ try {
+ const resolved = resolveVaultPath(vaultRoot, url);
+ absPath = resolved.absPath;
+ } catch (err) {
+ if (err && err.status) {
+ sendError(res, err.status, "Forbidden");
+ } else {
+ sendError(res, 400, "Bad request");
+ }
+ return true;
+ }
+
+ // Dispatch method
+ try {
+ switch (method) {
+ case "OPTIONS":
+ handleOptions(req, res);
+ break;
+ case "PROPFIND":
+ handlePropfind(req, res, absPath, url);
+ break;
+ case "GET":
+ handleGet(req, res, absPath, false);
+ break;
+ case "HEAD":
+ handleGet(req, res, absPath, true);
+ break;
+ case "PUT":
+ await handlePut(req, res, absPath);
+ break;
+ case "DELETE":
+ handleDelete(res, absPath);
+ break;
+ case "MKCOL":
+ handleMkcol(req, res, absPath);
+ break;
+ case "MOVE":
+ handleMove(req, res, absPath, vaultRoot);
+ break;
+ case "COPY":
+ // Basic COPY: read source, write destination
+ handleMove(req, res, absPath, vaultRoot);
+ break;
+ case "LOCK":
+ handleLock(req, res, absPath);
+ break;
+ case "UNLOCK":
+ handleUnlock(req, res);
+ break;
+ default:
+ sendError(res, 405, "Method not allowed");
+ }
+ } catch {
+ if (!res.headersSent) {
+ sendError(res, 500, "Internal server error");
+ }
+ }
+
+ return true;
+}
diff --git a/src/app/(dashboard)/dashboard/HomePageClient.tsx b/src/app/(dashboard)/dashboard/HomePageClient.tsx
index 5e40a2d73c..f6d3fa56bb 100644
--- a/src/app/(dashboard)/dashboard/HomePageClient.tsx
+++ b/src/app/(dashboard)/dashboard/HomePageClient.tsx
@@ -13,6 +13,8 @@ import { useNotificationStore } from "@/store/notificationStore";
import { copyToClipboard } from "@/shared/utils/clipboard";
import { getProviderDisplayLabel } from "@/shared/utils/providerDisplayLabel";
import { useIsElectron, useOpenExternal } from "@/shared/hooks/useElectron";
+import { useLiveRequests } from "@/hooks/useLiveDashboard";
+import { selectActiveRequests } from "../home/topologyUtils";
const ProviderTopology = dynamic(() => import("../home/ProviderTopology"), { ssr: false });
const ProviderQuotaWidget = dynamic(() => import("../home/ProviderQuotaWidget"), { ssr: false });
@@ -114,6 +116,9 @@ export default function HomePageClient({ machineId }: HomePageClientProps) {
Array<{ id?: string; prefix?: string; name?: string }>
>([]);
+ // Live in-flight requests for Provider Topology pulse animation (#3507)
+ const { activeRequests: liveActiveRequests } = useLiveRequests();
+
const [versionInfo, setVersionInfo] = useState<VersionInfo | null>(null);
const [updating, setUpdating] = useState(false);
@@ -1178,7 +1183,7 @@ export default function HomePageClient({ machineId }: HomePageClientProps) {
</div>
<ProviderTopology
providers={topologyProviders}
- activeRequests={[]}
+ activeRequests={selectActiveRequests(liveActiveRequests)}
lastProvider={lastProvider}
errorProvider={errorProvider}
/>
diff --git a/src/app/(dashboard)/dashboard/endpoint/components/ObsidianSourceCard.tsx b/src/app/(dashboard)/dashboard/endpoint/components/ObsidianSourceCard.tsx
index 35c29e502c..18370cec98 100644
--- a/src/app/(dashboard)/dashboard/endpoint/components/ObsidianSourceCard.tsx
+++ b/src/app/(dashboard)/dashboard/endpoint/components/ObsidianSourceCard.tsx
@@ -393,111 +393,6 @@ export default function ObsidianSourceCard() {
</div>
)}
- <div className="border-t border-border/50 pt-3 flex flex-col gap-2">
- <div className="flex items-center gap-2">
- <span className="text-xs text-text-muted font-medium">Vault Sync (WebDAV)</span>
- </div>
- <p className="text-[10px] text-text-muted">
- Sync your vault to Obsidian mobile using WebDAV over Tailscale.
- Install the &quot;WebDAV Sync&quot; plugin on Obsidian mobile.
- </p>
-
- {!webdavEnabled ? (
- <div className="flex flex-col gap-2">
- <label className="text-xs text-text-muted font-medium">
- Vault Directory Path
- </label>
- <div className="flex gap-2">
- <Input
- type="text"
- value={vaultPath}
- onChange={(e) => setVaultPath(e.target.value)}
- placeholder="/Users/you/Documents/Obsidian"
- disabled={webdavBusy}
- className="font-mono text-sm flex-1"
- />
- <Button
- onClick={handleEnableWebdav}
- loading={webdavBusy}
- variant="primary"
- size="sm"
- >
- Enable
- </Button>
- </div>
- </div>
- ) : (
- <div className="flex flex-col gap-3">
- <div className="flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2">
- <span className="material-symbols-outlined text-[18px] text-blue-400">cloud_sync</span>
- <div className="flex-1 min-w-0">
- <p className="text-xs text-blue-300 font-medium">WebDAV sync enabled</p>
- <p className="text-[10px] text-blue-400/70 font-mono truncate">{getWebdavUrl()}</p>
- </div>
- <Button
- onClick={handleDisableWebdav}
- loading={webdavBusy}
- variant="secondary"
- size="sm"
- className="border-red-500/30! text-red-400! hover:bg-red-500/10! shrink-0"
- >
- Disable
- </Button>
- </div>
-
- <div className="flex flex-col gap-2 rounded-lg border border-border/50 bg-black/10 p-3">
- <p className="text-[11px] text-text-muted font-medium">Configure Obsidian Mobile</p>
- <p className="text-[10px] text-text-muted">
- Install the &quot;WebDAV Sync&quot; plugin, then enter the following:
- </p>
-
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] text-text-muted font-medium">WebDAV URL</label>
- <div className="flex items-center gap-1.5 rounded border border-border/30 bg-black/20 px-2.5 py-1.5">
- <code className="text-[10px] text-text-muted font-mono flex-1 break-all select-all">
- {getWebdavUrl()}
- </code>
- </div>
- </div>
-
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] text-text-muted font-medium">Username</label>
- <div className="flex items-center gap-1.5 rounded border border-border/30 bg-black/20 px-2.5 py-1.5">
- <code className="text-[10px] text-text-muted font-mono flex-1 select-all">
- {webdavUsername ?? "—"}
- </code>
- </div>
- </div>
-
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] text-text-muted font-medium">Password</label>
- <div className="flex items-center gap-1.5">
- <div className="flex items-center gap-1.5 rounded border border-border/30 bg-black/20 px-2.5 py-1.5 flex-1">
- <code className="text-[10px] text-text-muted font-mono flex-1 select-all">
- {showPassword ? (webdavPassword ?? "—") : "••••••••••••"}
- </code>
- </div>
- <Button
- onClick={() => setShowPassword(!showPassword)}
- variant="secondary"
- size="sm"
- className="shrink-0"
- >
- <span className="material-symbols-outlined text-[16px]">
- {showPassword ? "visibility_off" : "visibility"}
- </span>
- </Button>
- </div>
- </div>
-
- <p className="text-[10px] text-text-muted">
- Use your Tailscale IP instead of localhost when configuring on mobile.
- {" "}Both devices must be on the same Tailscale network.
- </p>
- </div>
- </div>
- )}
- </div>
</div>
)}
</div>
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/ProviderDetailPageClient.tsx b/src/app/(dashboard)/dashboard/providers/[id]/ProviderDetailPageClient.tsx
new file mode 100644
index 0000000000..47aa3ffe05
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/ProviderDetailPageClient.tsx
@@ -0,0 +1,4062 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef, useMemo } from "react";
+// Phase 1f extractions — Issue #3501
+import { useProviderConnections } from "./hooks/useProviderConnections";
+import { useProviderSettings } from "./hooks/useProviderSettings";
+import { useProviderModels } from "./hooks/useProviderModels";
+import { LlmChatCard } from "@/app/(dashboard)/dashboard/media-providers/components/LlmChatCard";
+import { ServiceKindTabs } from "@/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs";
+import { EmbeddingExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/EmbeddingExampleCard";
+import { ImageExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard";
+import { TtsExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/TtsExampleCard";
+import { SttExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/SttExampleCard";
+import { WebSearchExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/WebSearchExampleCard";
+import { WebFetchExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/WebFetchExampleCard";
+import { VideoExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/VideoExampleCard";
+import { MusicExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/MusicExampleCard";
+import type { ServiceKind } from "@/shared/constants/providers";
+import { useNotificationStore } from "@/store/notificationStore";
+import { useParams, useRouter } from "next/navigation";
+import Link from "next/link";
+import { useTranslations } from "next-intl";
+import {
+ Card,
+ Button,
+ Badge,
+ Modal,
+ ConfirmModal,
+ CardSkeleton,
+ OAuthModal,
+ KiroOAuthWrapper,
+ CursorAuthModal,
+ TraeAuthModal,
+ Toggle,
+ Select,
+ ProxyConfigModal,
+ NoAuthProviderCard,
+ NoAuthAccountCard,
+} from "@/shared/components";
+import {
+ LOCAL_PROVIDERS,
+ NOAUTH_PROVIDERS,
+ AI_PROVIDERS,
+ getProviderAlias,
+ isOpenAICompatibleProvider,
+ isAnthropicCompatibleProvider,
+ isClaudeCodeCompatibleProvider,
+ isSelfHostedChatProvider,
+ supportsApiKeyOnFreeProvider,
+ // providerAllowsOptionalApiKey + supportsBulkApiKey used by extracted AddApiKeyModal
+} from "@/shared/constants/providers";
+// antigravityClientProfile + parseBulkApiKeys used by extracted modals (AddApiKeyModal, EditConnectionModal)
+import { getModelsByProviderId } from "@/shared/constants/models";
+import {
+ compatibleProviderSupportsModelImport,
+ getCompatibleFallbackModels,
+} from "@/lib/providers/managedAvailableModels";
+import {
+ matchesModelCatalogQuery,
+ normalizeModelCatalogSource,
+} from "@/shared/utils/modelCatalogSearch";
+import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
+import { pickDisplayValue } from "@/shared/utils/maskEmail";
+import useEmailPrivacyStore from "@/store/emailPrivacyStore";
+import EmailPrivacyToggle from "@/shared/components/EmailPrivacyToggle";
+import ProviderIcon from "@/shared/components/ProviderIcon";
+import { type CodexServiceTier } from "@/lib/providers/requestDefaults";
+import { type CodexGlobalServiceMode } from "@/lib/providers/codexFastTier";
+// parseExtraApiKeys used by extracted EditConnectionModal
+import { compareTr } from "@/shared/utils/turkishText";
+import RiskNoticeModal from "../components/RiskNoticeModal";
+import CodexCliGuideModal from "../components/CodexCliGuideModal";
+import { isRiskAcknowledged, useRiskAcknowledged } from "../hooks/useRiskAcknowledged";
+import { resolveDashboardProviderInfo } from "../providerPageUtils";
+// webSessionCredentials used by extracted modals (AddApiKeyModal, EditConnectionModal)
+import {
+ ImportCodexAuthModal,
+ ApplyCodexAuthModal,
+} from "./components/modals/ImportCodexAuthModal";
+import {
+ ImportClaudeAuthModal,
+ ApplyClaudeAuthModal,
+} from "./components/modals/ImportClaudeAuthModal";
+import {
+ ImportGeminiAuthModal,
+ ApplyGeminiAuthModal,
+} from "./components/modals/ImportGeminiAuthModal";
+
+import EditCompatibleNodeModal from "./components/modals/EditCompatibleNodeModal";
+import AddApiKeyModal from "./components/modals/AddApiKeyModal";
+import EditConnectionModal from "./components/modals/EditConnectionModal";
+import WebSessionCredentialGuide from "./components/WebSessionCredentialGuide";
+// Phase 1d extractions — Issue #3501
+import ConnectionRow, {
+ type ConnectionRowConnection,
+} from "./components/ConnectionRow";
+import ModelCompatPopover from "./components/ModelCompatPopover";
+import SiliconFlowEndpointModal from "./components/SiliconFlowEndpointModal";
+import { CC_COMPATIBLE_DEFAULT_CHAT_PATH } from "./providerDetailConstants";
+import {
+ // CONFIGURABLE_BASE_URL_PROVIDERS, DEFAULT_PROVIDER_BASE_URLS, getLocalProviderMetadata,
+ // isBaseUrlConfigurableProvider, getProviderBaseUrlDefault, getProviderBaseUrlHint,
+ // getProviderBaseUrlPlaceholder, isGlmProvider, parseRoutingTagsInput, parseExcludedModelsInput,
+ // formatRoutingTagsInput, formatExcludedModelsInput, getWebSessionCredentialLabel,
+ // getWebSessionCredentialHint, getWebSessionCredentialCheckLabel, getAddCredentialModalTitle,
+ // CODEX_REASONING_STRENGTH_OPTIONS, CODEX_ACCOUNT_SERVICE_TIER_VALUES, getCodexRequestDefaults,
+ // getClaudeCodeCompatibleRequestDefaults, extractCommandCodeCredentialInput,
+ // normalizeAndValidateHttpBaseUrl, formatTimeAgo
+ // — all moved to extracted modals (AddApiKeyModal, EditConnectionModal, WebSessionCredentialGuide)
+ providerText,
+ providerCountText,
+ readBooleanToggle,
+ formatProviderModelsErrorResponse,
+ type ProviderMessageTranslator,
+ type LocalProviderMetadata,
+ type CommandCodeAuthFlowState,
+ type CompatByProtocolMap,
+ type CompatModelRow,
+ type CompatModelMap,
+} from "./providerPageHelpers";
+// CODEX_GLOBAL_SERVICE_MODE_VALUES, getCodexServiceTierLabel, normalizeCodexLimitPolicy
+// moved to hooks/useProviderSettings.ts + hooks/useProviderConnections.ts (Phase 1f)
+// Phase 1e extractions — Issue #3501
+import { useModelCompatState } from "./hooks/useModelCompatState";
+import ModelRow, { ModelVisibilityToolbar } from "./components/ModelRow";
+import PassthroughModelsSection from "./components/PassthroughModelsSection";
+import CustomModelsSection from "./components/CustomModelsSection";
+import CompatibleModelsSection from "./components/CompatibleModelsSection";
+// recordToHeaderRows moved to components/ModelCompatPopover.tsx (Phase 1d)
+// buildCompatMap, isModelHidden*, effectiveNormalize/Preserve*, anyNormalize/NoPreserveCompatBadge
+// moved to providerPageHelpers.ts + hook useModelCompatState (Phase 1e)
+// formatProviderModelsErrorResponse moved to providerPageHelpers.ts (Phase 1e)
+
+/** PATCH fields for provider model compat (matches API + `ModelCompatPerProtocol` shape). */
+type ModelCompatSavePatch = {
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ compatByProtocol?: CompatByProtocolMap;
+ isHidden?: boolean;
+};
+
+// MAX_BULK_IDS moved to hooks/useProviderConnections.ts (Phase 1f)
+// ModelRowProps, PassthroughModelRowProps → components/ModelRow.tsx, PassthroughModelRow.tsx (Phase 1e)
+// PassthroughModelsSectionProps → components/PassthroughModelsSection.tsx (Phase 1e)
+// CustomModelsSectionProps → components/CustomModelsSection.tsx (Phase 1e)
+// CompatibleModelsSectionProps → components/CompatibleModelsSection.tsx (Phase 1e)
+// CooldownTimerProps moved to components/ConnectionRow.tsx (Phase 1d)
+
+// getModelSourceBadgeClass + ModelSourceBadge → components/ModelRow.tsx (Phase 1e)
+// ConnectionRowConnection, ConnectionRowProps moved to components/ConnectionRow.tsx (Phase 1d)
+
+// ModelCompatPopover extracted to components/ModelCompatPopover.tsx (Phase 1d)
+
+// ──── ProviderPlaygroundPanel ────────────────────────────────────────────────
+// Renders a playground section on the individual provider page.
+// Shows ServiceKindTabs if the provider declares multiple kinds; falls back to
+// a single-kind panel or the LlmChatCard for standard LLM providers.
+
+const MEDIA_SERVICE_KINDS: ServiceKind[] = [
+ "embedding",
+ "image",
+ "tts",
+ "stt",
+ "webSearch",
+ "webFetch",
+ "video",
+ "music",
+];
+
+function renderKindPanel(kind: ServiceKind, providerId: string): JSX.Element | null {
+ switch (kind) {
+ case "llm":
+ return <LlmChatCard providerId={providerId} />;
+ case "embedding":
+ return <EmbeddingExampleCard providerId={providerId} />;
+ case "image":
+ return <ImageExampleCard providerId={providerId} />;
+ case "tts":
+ return <TtsExampleCard providerId={providerId} />;
+ case "stt":
+ return <SttExampleCard providerId={providerId} />;
+ case "webSearch":
+ return <WebSearchExampleCard providerId={providerId} />;
+ case "webFetch":
+ return <WebFetchExampleCard providerId={providerId} />;
+ case "video":
+ return <VideoExampleCard providerId={providerId} />;
+ case "music":
+ return <MusicExampleCard providerId={providerId} />;
+ default:
+ return null;
+ }
+}
+
+function ProviderPlaygroundPanel({ providerId }: { providerId: string }) {
+ // Resolve serviceKinds from AI_PROVIDERS.
+ // For providers without explicit serviceKinds (most LLM providers), we infer
+ // "llm" as the default.
+ const providerEntry = AI_PROVIDERS[providerId as keyof typeof AI_PROVIDERS] as
+ | (Record<string, unknown> & { serviceKinds?: string[] })
+ | undefined;
+
+ const rawKinds: string[] = providerEntry?.serviceKinds ?? [];
+
+ const ALL_VALID_KINDS = [
+ "llm",
+ "embedding",
+ "image",
+ "imageToText",
+ "tts",
+ "stt",
+ "webSearch",
+ "webFetch",
+ "video",
+ "music",
+ ] as const;
+
+ const kinds: ServiceKind[] =
+ rawKinds.length > 0
+ ? rawKinds.filter((k): k is ServiceKind => (ALL_VALID_KINDS as readonly string[]).includes(k))
+ : ["llm"];
+
+ // Filter out kinds that have no playground implementation yet
+ const playgroundableKinds = kinds.filter((k) => k !== "imageToText");
+
+ // useState must be called unconditionally (Rules of Hooks)
+ const [activeKind, setActiveKind] = useState<ServiceKind>(playgroundableKinds[0] ?? "llm");
+
+ if (playgroundableKinds.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-3">
+ <h2 className="text-lg font-semibold">Playground</h2>
+ <ServiceKindTabs
+ kinds={playgroundableKinds}
+ activeKind={activeKind}
+ onSelect={setActiveKind}
+ />
+ {renderKindPanel(activeKind, providerId)}
+ </div>
+ );
+}
+
+export default function ProviderDetailPageClient() {
+ const params = useParams();
+ const router = useRouter();
+ const providerId = params.id as string;
+
+ // ── UI-only modal state (not owned by hooks) ─────────────────────────────
+ const [showOAuthModal, _setShowOAuthModal] = useState(false);
+ const [reauthConnection, setReauthConnection] = useState<ConnectionRowConnection | null>(null);
+ const [showAddApiKeyModal, setShowAddApiKeyModal] = useState(false);
+ const [showSiliconFlowEndpointModal, setShowSiliconFlowEndpointModal] = useState(false);
+ const [siliconFlowInitialBaseUrl, setSiliconFlowInitialBaseUrl] = useState<string | undefined>();
+ const [showRiskNoticeModal, setShowRiskNoticeModal] = useState(false);
+ const [commandCodeAuthState, setCommandCodeAuthState] = useState<CommandCodeAuthFlowState>({
+ phase: "idle",
+ state: "",
+ authUrl: "",
+ callbackUrl: "",
+ expiresAt: null,
+ message: "",
+ });
+ const [showEditModal, setShowEditModal] = useState(false);
+ const [showEditNodeModal, setShowEditNodeModal] = useState(false);
+ const [showTutorialModal, setShowTutorialModal] = useState(false);
+ const [selectedConnection, setSelectedConnection] = useState(null);
+ const [proxyTarget, setProxyTarget] = useState(null);
+ const [importingModels, setImportingModels] = useState(false);
+ const [importingZed, setImportingZed] = useState(false);
+ const [showZedManual, setShowZedManual] = useState(false);
+ const [zedManualProvider, setZedManualProvider] = useState("openai");
+ const [zedManualToken, setZedManualToken] = useState("");
+ const [importingZedManual, setImportingZedManual] = useState(false);
+ const [showImportModal, setShowImportModal] = useState(false);
+ const [importProgress, setImportProgress] = useState({
+ current: 0,
+ total: 0,
+ phase: "idle" as "idle" | "fetching" | "importing" | "done" | "error",
+ status: "",
+ logs: [] as string[],
+ error: "",
+ importedCount: 0,
+ });
+ const [compatSavingModelId, setCompatSavingModelId] = useState<string | null>(null);
+ const [modelFilter, setModelFilter] = useState("");
+ const [togglingModelId, setTogglingModelId] = useState<string | null>(null);
+ const [testingModelId, setTestingModelId] = useState<string | null>(null);
+ const [modelTestStatus, setModelTestStatus] = useState<Record<string, "ok" | "error">>({});
+ const [testingAll, setTestingAll] = useState(false);
+ const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);
+ const [autoHideFailed, setAutoHideFailed] = useState(true);
+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
+ const [bulkVisibilityAction, setBulkVisibilityAction] = useState<"select" | "deselect" | null>(
+ null
+ );
+ const [applyingCodexAuthId, setApplyingCodexAuthId] = useState<string | null>(null);
+ const [applyCodexModalConnectionId, setApplyCodexModalConnectionId] = useState<string | null>(
+ null
+ );
+ const [exportingCodexAuthId, setExportingCodexAuthId] = useState<string | null>(null);
+ const [importCodexModalOpen, setImportCodexModalOpen] = useState(false);
+ const [codexCliGuideOpen, setCodexCliGuideOpen] = useState(false);
+ // "Adicionar Externo": public shareable device-flow link state.
+ const [externalLinkModalOpen, setExternalLinkModalOpen] = useState(false);
+ const [externalLinkUrl, setExternalLinkUrl] = useState("");
+ const [externalLinkToken, setExternalLinkToken] = useState<string | null>(null);
+ const [externalLinkLoading, setExternalLinkLoading] = useState(false);
+ const [externalLinkError, setExternalLinkError] = useState<string | null>(null);
+ const { copied: externalLinkCopied, copy: externalLinkCopy } = useCopyToClipboard();
+ const [applyingClaudeAuthId, setApplyingClaudeAuthId] = useState<string | null>(null);
+ const [applyClaudeModalConnectionId, setApplyClaudeModalConnectionId] = useState<string | null>(
+ null
+ );
+ const [exportingClaudeAuthId, setExportingClaudeAuthId] = useState<string | null>(null);
+ const [importClaudeModalOpen, setImportClaudeModalOpen] = useState(false);
+ const [applyingGeminiAuthId, setApplyingGeminiAuthId] = useState<string | null>(null);
+ const [applyGeminiModalConnectionId, setApplyGeminiModalConnectionId] = useState<string | null>(
+ null
+ );
+ const [exportingGeminiAuthId, setExportingGeminiAuthId] = useState<string | null>(null);
+ const [importGeminiModalOpen, setImportGeminiModalOpen] = useState(false);
+ const commandCodeAuthWindowRef = useRef<Window | null>(null);
+ const commandCodeAuthTimerRef = useRef<number | null>(null);
+ const pendingRiskActionRef = useRef<(() => void) | null>(null);
+ const { acknowledged: riskAcknowledged, acknowledge: acknowledgeRisk } =
+ useRiskAcknowledged(providerId);
+ const isOpenAICompatible = isOpenAICompatibleProvider(providerId);
+ const isCcCompatible = isClaudeCodeCompatibleProvider(providerId);
+ const isCommandCode = providerId === "command-code";
+ const isAnthropicCompatible =
+ isAnthropicCompatibleProvider(providerId) && !isClaudeCodeCompatibleProvider(providerId);
+ const isCompatible = isOpenAICompatible || isAnthropicCompatible || isCcCompatible;
+ const isAnthropicProtocolCompatible = isAnthropicCompatible || isCcCompatible;
+ const isSearchProvider = providerId.endsWith("-search");
+
+ // ── Phase 1f hooks ────────────────────────────────────────────────────────
+ const {
+ connections,
+ providerNode,
+ loading,
+ retestingId,
+ batchTesting,
+ batchTestResults,
+ selectedIds,
+ batchDeleting,
+ batchUpdating,
+ batchRetesting,
+ batchDeleteConfirmOpen,
+ healthFilter,
+ page,
+ distributingProxies,
+ proxyConfig,
+ connProxyMap,
+ cpaProviderEnabled,
+ refreshingId,
+ setPage,
+ setHealthFilter,
+ setSelectedIds,
+ setBatchDeleteConfirmOpen,
+ setBatchTestResults,
+ setConnections,
+ setProviderNode,
+ fetchConnections,
+ fetchProxyConfig,
+ handleDelete,
+ handleUpdateConnectionStatus,
+ handleToggleRateLimit,
+ handleToggleClaudeExtraUsage,
+ handleToggleCodexLimit,
+ handleToggleCliproxyapiMode,
+ handleToggleProxyEnabled,
+ handleTogglePerKeyProxyEnabled,
+ handleRetestConnection,
+ handleRefreshToken,
+ handleSwapPriority,
+ handleBatchSetActive,
+ handleBatchDeleteOpenModal,
+ handleBatchDeleteConfirm,
+ handleBatchRetest,
+ handleBatchTestAll,
+ handleToggleSelectOne,
+ handleToggleSelectAll,
+ handleDistributeProxies,
+ parseApiErrorMessage,
+ getAttachmentFilename,
+ PAGE_SIZE,
+ } = useProviderConnections(providerId, isCompatible, isSearchProvider);
+
+ const {
+ codexGlobalServiceMode,
+ codexSettingsLoaded,
+ codexSettingsLoadError,
+ savingCodexGlobalServiceMode,
+ codexGlobalServiceModeOptions,
+ loadCodexSettings,
+ handleChangeCodexGlobalServiceMode,
+ preferClaudeCodeForUnprefixedClaudeModels,
+ claudeRoutingSettingsLoaded,
+ claudeRoutingSettingsLoadError,
+ savingClaudeRoutingPreference,
+ loadClaudeRoutingSettings,
+ handleToggleClaudeRoutingPreference,
+ } = useProviderSettings(providerId);
+
+ const {
+ modelMeta,
+ syncedAvailableModels,
+ modelAliases,
+ fetchProviderModelMeta,
+ fetchAliases,
+ handleSetAlias,
+ handleDeleteAlias,
+ } = useProviderModels(providerId, isSearchProvider);
+
+ // ── shared hook/store ─────────────────────────────────────────────────────
+ const { copied, copy } = useCopyToClipboard();
+ const t = useTranslations("providers");
+ const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);
+ const notify = useNotificationStore();
+
+ const setShowOAuthModal = (show: boolean, connectionRow?: ConnectionRowConnection) => {
+ _setShowOAuthModal(show);
+ setReauthConnection(show && connectionRow ? connectionRow : null);
+ };
+
+ const providerInfo = resolveDashboardProviderInfo(providerId, {
+ providerNode,
+ compatibleLabels: {
+ ccCompatibleName: t("ccCompatibleLabel"),
+ anthropicCompatibleName: t("anthropicCompatibleName"),
+ openAiCompatibleName: t("openaiCompatibleName"),
+ },
+ });
+ const providerSupportsOAuth =
+ providerInfo?.toggleAuthType === "oauth" || providerInfo?.toggleAuthType === "free";
+ const subscriptionRisk = providerInfo?.subscriptionRisk === true;
+ const providerSupportsPat = supportsApiKeyOnFreeProvider(providerId);
+ const isOAuth = providerSupportsOAuth && !providerSupportsPat;
+ const isFreeNoAuth = NOAUTH_PROVIDERS[providerId]?.noAuth === true;
+ const registryModels = getModelsByProviderId(providerId);
+ // Prefer synced API-discovered models when available, then merge built-ins
+ // and user-managed custom models without duplicating IDs.
+ const models = useMemo(() => {
+ // Universal: merge built-in registry models with API-synced models and
+ // user-managed custom models for ALL providers (was previously Gemini-only).
+ // Synced models keep their full property spread so provider-specific fields
+ // (e.g. Gemini's `supportedGenerationMethods`) survive into the table.
+ const builtInModels = registryModels.map((model) => ({
+ ...model,
+ source: "system",
+ }));
+
+ const registryIds = new Set(builtInModels.map((m) => m.id));
+ const syncedExtras = syncedAvailableModels
+ .filter((model: any) => model?.id && !registryIds.has(model.id))
+ .map((model: any) => ({
+ ...model,
+ id: model.id,
+ name: model.name || model.id,
+ source: "imported",
+ }));
+ const knownIds = new Set([...registryIds, ...syncedExtras.map((model: any) => model.id)]);
+ const customExtras = modelMeta.customModels
+ .filter((cm: any) => cm.id && !knownIds.has(cm.id))
+ .map((cm: any) => ({
+ id: cm.id,
+ name: cm.name || cm.id,
+ source: normalizeModelCatalogSource(cm.source) === "imported" ? "imported" : "custom",
+ }));
+ const allModels = [...builtInModels, ...syncedExtras, ...customExtras];
+ const deduped = new Map<string, (typeof allModels)[0]>();
+ for (const m of allModels) {
+ if (m.id && !deduped.has(m.id)) deduped.set(m.id, m);
+ }
+ return Array.from(deduped.values());
+ }, [providerId, registryModels, syncedAvailableModels, modelMeta.customModels]);
+ const providerAlias = getProviderAlias(providerId);
+ const isManagedAvailableModelsProvider = isCompatible || providerId === "openrouter";
+ // isSearchProvider declared earlier (before hooks)
+ const isUpstreamProxyProvider = providerInfo?.category === "upstream-proxy";
+ const compatibleSupportsModelImport = compatibleProviderSupportsModelImport(providerId);
+
+ const providerStorageAlias = isCompatible ? providerId : providerAlias;
+ const providerDisplayAlias = isCompatible ? providerNode?.prefix || providerId : providerAlias;
+
+ const getApiLabel = () => {
+ if (isAnthropicProtocolCompatible) return t("messagesApi");
+ const type = providerNode?.apiType;
+ switch (type) {
+ case "responses":
+ return t("responsesApi");
+ case "embeddings":
+ return t("embeddings");
+ case "audio-transcriptions":
+ return t("audioTranscriptions");
+ case "audio-speech":
+ return t("audioSpeech");
+ case "images-generations":
+ return t("imagesGenerations");
+ default:
+ return t("chatCompletions");
+ }
+ };
+
+ const getApiDefaultPath = () => {
+ if (isCcCompatible) return CC_COMPATIBLE_DEFAULT_CHAT_PATH;
+ if (isAnthropicCompatible) return "/messages";
+ const type = providerNode?.apiType;
+ switch (type) {
+ case "responses":
+ return "/responses";
+ case "embeddings":
+ return "/embeddings";
+ case "audio-transcriptions":
+ return "/audio/transcriptions";
+ case "audio-speech":
+ return "/audio/speech";
+ case "images-generations":
+ return "/images/generations";
+ default:
+ return "/chat/completions";
+ }
+ };
+
+ const getApiPath = () => {
+ const defaultPath = getApiDefaultPath();
+ return (providerNode?.chatPath || defaultPath).replace(/^\//, "");
+ };
+
+ // fetchAliases, handleSetAlias, handleDeleteAlias → hooks/useProviderModels.ts (Phase 1f)
+ // fetchProviderModelMeta, fetchProxyConfig, fetchConnections → hooks/useProviderConnections.ts + useProviderModels.ts (Phase 1f)
+ // loadCodexSettings, loadClaudeRoutingSettings → hooks/useProviderSettings.ts (Phase 1f)
+ // loadConnProxies, handleRetestConnection, handleBatchTestAll, handleBatchRetest → hooks/useProviderConnections.ts (Phase 1f)
+ // handleDelete, handleBatchDeleteConfirm, handleBatchSetActive → hooks/useProviderConnections.ts (Phase 1f)
+ // handleUpdateConnectionStatus, handleToggleProxyEnabled, handleTogglePerKeyProxyEnabled → hooks/useProviderConnections.ts (Phase 1f)
+ // handleDistributeProxies, handleToggleRateLimit, handleToggleClaudeExtraUsage → hooks/useProviderConnections.ts (Phase 1f)
+ // handleToggleCliproxyapiMode, handleToggleCodexLimit, handleSwapPriority → hooks/useProviderConnections.ts (Phase 1f)
+ // handleToggleClaudeRoutingPreference, handleChangeCodexGlobalServiceMode → hooks/useProviderSettings.ts (Phase 1f)
+ // handleRefreshToken → hooks/useProviderConnections.ts (Phase 1f)
+
+ // ── model-related effects (loading gate) ────────────────────────────────
+ useEffect(() => {
+ if (loading || isSearchProvider) return;
+ fetchProviderModelMeta();
+ fetchAliases();
+ }, [loading, isSearchProvider, fetchProviderModelMeta, fetchAliases]);
+
+ const handleUpdateNode = async (formData: any) => {
+ try {
+ const res = await fetch(`/api/provider-nodes/${providerId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(formData),
+ });
+ const data = await res.json();
+ if (res.ok) {
+ setProviderNode(data.node);
+ await fetchConnections();
+ setShowEditNodeModal(false);
+ }
+ } catch (error) {
+ console.log("Error updating provider node:", error);
+ }
+ };
+
+ const handleZedImport = useCallback(async () => {
+ if (importingZed) return;
+ setImportingZed(true);
+ try {
+ const res = await fetch("/api/providers/zed/import", { method: "POST" });
+ const data = await res.json();
+ if (!res.ok || !data.success) {
+ if (data.zedDockerEnvironment) {
+ setShowZedManual(true);
+ }
+ notify.error(data.error || "Zed import failed");
+ } else if (!data.count) {
+ const found = data.credentials?.length ?? 0;
+ if (found === 0) {
+ notify.info("No Zed credentials found in keychain");
+ } else {
+ notify.info(
+ `Found ${found} keychain credential(s), but none matched supported providers`
+ );
+ }
+ } else {
+ notify.success(
+ `Imported ${data.count} credential(s) from Zed for ${data.providers?.length ?? 0} provider(s)`
+ );
+ await fetchConnections();
+ }
+ } catch (e: any) {
+ notify.error(e?.message || "Zed import failed");
+ } finally {
+ setImportingZed(false);
+ }
+ }, [importingZed, notify, fetchConnections]);
+
+ const handleZedManualImport = useCallback(async () => {
+ if (importingZedManual || !zedManualToken.trim()) return;
+ setImportingZedManual(true);
+ try {
+ const res = await fetch("/api/providers/zed/manual-import", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider: zedManualProvider, token: zedManualToken.trim() }),
+ });
+ const data = await res.json();
+ if (!res.ok || !data.success) {
+ notify.error(data.error?.message ?? data.error ?? "Manual import failed");
+ } else {
+ notify.success(`Imported ${zedManualProvider} token from Zed`);
+ setZedManualToken("");
+ await fetchConnections();
+ }
+ } catch (e: any) {
+ notify.error(e?.message || "Manual import failed");
+ } finally {
+ setImportingZedManual(false);
+ }
+ }, [importingZedManual, zedManualProvider, zedManualToken, notify, fetchConnections]);
+
+ // loadCodexSettings, loadClaudeRoutingSettings → hooks/useProviderSettings.ts (Phase 1f)
+ // loadConnProxies → hooks/useProviderConnections.ts (Phase 1f)
+
+ const onTestModel = async (modelId: string, fullModel: string) => {
+ setTestingModelId(modelId);
+ setModelTestStatus((prev) => ({ ...prev, [modelId]: undefined }));
+ try {
+ const res = await fetch("/api/models/test", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerId: selectedConnection?.provider || providerNode?.id || providerId,
+ modelId: fullModel,
+ connectionId: selectedConnection?.id,
+ }),
+ });
+ const data = await res.json();
+ if (res.ok && data.status === "ok") {
+ notify.success(
+ providerText(
+ t,
+ "testModelSuccess",
+ `Model ${modelId} is working. Latency: ${data.latencyMs}ms`,
+ { modelId, latencyMs: data.latencyMs }
+ )
+ );
+ setModelTestStatus((prev) => ({ ...prev, [modelId]: "ok" }));
+ } else {
+ notify.error(data.error || "Model test failed");
+ setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));
+ if (handleToggleModelHidden) {
+ await handleToggleModelHidden(providerStorageAlias, modelId, true);
+ }
+ }
+ } catch (err) {
+ notify.error("Network error testing model");
+ setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));
+ if (handleToggleModelHidden) {
+ await handleToggleModelHidden(providerStorageAlias, modelId, true);
+ }
+ } finally {
+ setTestingModelId(null);
+ }
+ };
+
+ const handleTestAll = async (
+ targets: Array<{ modelId: string; fullModel: string }>
+ ): Promise<void> => {
+ if (testingAll) return;
+ if (targets.length === 0) {
+ notify.error(providerText(t, "noModelsToTest", "No models to test"));
+ return;
+ }
+ setTestingAll(true);
+ setTestProgress({ done: 0, total: targets.length });
+
+ let ok = 0;
+ let error = 0;
+ let hiddenCount = 0;
+
+ const CHUNK_SIZE = 3;
+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
+ const chunk = targets.slice(i, i + CHUNK_SIZE);
+ await Promise.all(
+ chunk.map(async ({ modelId, fullModel }) => {
+ try {
+ const result: {
+ results?: Record<
+ string,
+ {
+ status?: "ok" | "error";
+ rateLimited?: boolean;
+ isTimeout?: boolean;
+ error?: string;
+ }
+ >;
+ } = await fetch("/api/models/test-all", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerId: providerId,
+ connectionId: selectedConnection?.id,
+ modelIds: [fullModel],
+ }),
+ }).then((r) => r.json());
+
+ const entry = result.results?.[fullModel];
+ if (entry?.status === "ok") {
+ ok++;
+ } else {
+ error++;
+ if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {
+ await handleToggleModelHidden(providerStorageAlias, modelId, true);
+ hiddenCount++;
+ }
+ }
+ } catch (e) {
+ error++;
+ }
+ setTestProgress((prev) => (prev ? { done: prev.done + 1, total: prev.total } : null));
+ })
+ );
+ }
+
+ notify.info(providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error }));
+ if (hiddenCount > 0) {
+ notify.info(providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount }));
+ }
+ setTestingAll(false);
+ setTestProgress(null);
+ };
+
+ // handleToggleSelectOne/All, handleBatchDeleteOpenModal/Confirm, handleDelete,
+ // handleBatchSetActive → hooks/useProviderConnections.ts (Phase 1f)
+
+ const handleOAuthSuccess = useCallback(() => {
+ fetchConnections();
+ setShowOAuthModal(false);
+ }, [fetchConnections]);
+
+ const openApiKeyAddFlow = useCallback(() => {
+ if (providerId === "siliconflow") {
+ setShowSiliconFlowEndpointModal(true);
+ return;
+ }
+ setShowAddApiKeyModal(true);
+ }, [providerId]);
+
+ const openPrimaryAddFlow = useCallback(() => {
+ if (isOAuth) {
+ setShowOAuthModal(true);
+ return;
+ }
+ openApiKeyAddFlow();
+ }, [isOAuth, openApiKeyAddFlow]);
+
+ // "Adicionar Externo": generate a single-use public link so a third party can
+ // complete the Codex device flow in their own browser.
+ const openExternalLinkFlow = useCallback(async () => {
+ setExternalLinkModalOpen(true);
+ setExternalLinkUrl("");
+ setExternalLinkToken(null);
+ setExternalLinkError(null);
+ setExternalLinkLoading(true);
+ try {
+ const res = await fetch(`/api/oauth/${providerId}/public-link`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.ok && data?.url) {
+ setExternalLinkUrl(data.url);
+ setExternalLinkToken(data.token || null);
+ } else {
+ setExternalLinkError(data?.error || "Falha ao gerar o link.");
+ }
+ } catch {
+ setExternalLinkError("Não foi possível contatar o servidor.");
+ } finally {
+ setExternalLinkLoading(false);
+ }
+ }, [providerId]);
+
+ // While the share popup is open, poll the ticket status so the dashboard can
+ // notify + refresh the connections the moment the external visitor finishes.
+ useEffect(() => {
+ if (!externalLinkModalOpen || !externalLinkToken) return;
+ let active = true;
+ const interval = setInterval(async () => {
+ if (!active) return;
+ try {
+ const res = await fetch(
+ `/api/oauth/${providerId}/public-link-status?token=${encodeURIComponent(externalLinkToken)}`
+ );
+ const data = await res.json().catch(() => ({}));
+ if (!active) return;
+ if (data?.status === "completed") {
+ active = false;
+ clearInterval(interval);
+ notify.success("Conta Codex conectada pelo link externo.");
+ fetchConnections();
+ setExternalLinkModalOpen(false);
+ setExternalLinkToken(null);
+ } else if (data?.status === "expired") {
+ active = false;
+ clearInterval(interval);
+ setExternalLinkError("O link expirou sem ser concluído.");
+ }
+ } catch {
+ /* transient network error — keep polling */
+ }
+ }, 3000);
+ return () => {
+ active = false;
+ clearInterval(interval);
+ };
+ }, [externalLinkModalOpen, externalLinkToken, providerId, notify, fetchConnections]);
+
+ const gateConnectionFlow = useCallback(
+ (callback: () => void) => {
+ if (subscriptionRisk && !riskAcknowledged && !isRiskAcknowledged(providerId)) {
+ pendingRiskActionRef.current = callback;
+ setShowRiskNoticeModal(true);
+ return;
+ }
+ callback();
+ },
+ [providerId, riskAcknowledged, subscriptionRisk]
+ );
+
+ const handleConfirmRiskNotice = useCallback(() => {
+ acknowledgeRisk();
+ setShowRiskNoticeModal(false);
+ const pendingAction = pendingRiskActionRef.current;
+ pendingRiskActionRef.current = null;
+ pendingAction?.();
+ }, [acknowledgeRisk]);
+
+ const handleCancelRiskNotice = useCallback(() => {
+ pendingRiskActionRef.current = null;
+ setShowRiskNoticeModal(false);
+ }, []);
+
+ const clearCommandCodeAuthTimer = useCallback(() => {
+ if (commandCodeAuthTimerRef.current !== null) {
+ window.clearTimeout(commandCodeAuthTimerRef.current);
+ commandCodeAuthTimerRef.current = null;
+ }
+ }, []);
+
+ useEffect(() => {
+ return () => {
+ clearCommandCodeAuthTimer();
+ commandCodeAuthWindowRef.current?.close?.();
+ };
+ }, [clearCommandCodeAuthTimer]);
+
+ const handleCloseAddApiKeyModal = useCallback(() => {
+ clearCommandCodeAuthTimer();
+ setSiliconFlowInitialBaseUrl(undefined);
+ commandCodeAuthWindowRef.current?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ setCommandCodeAuthState({
+ phase: "idle",
+ state: "",
+ authUrl: "",
+ callbackUrl: "",
+ expiresAt: null,
+ message: "",
+ });
+ setShowAddApiKeyModal(false);
+ }, [clearCommandCodeAuthTimer]);
+
+ const handleCommandCodeAuthApply = useCallback(
+ async (state: string, connectionId?: string, name?: string, setDefault?: boolean) => {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "applying",
+ message: "Applying browser-approved key…",
+ }));
+
+ try {
+ const res = await fetch("/api/providers/command-code/auth/apply", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ state, connectionId, name, setDefault }),
+ });
+ const data = await res.json().catch(() => ({}));
+
+ if (!res.ok) {
+ const errorMessage = data.error || "Failed to apply Command Code auth";
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "error",
+ message: errorMessage,
+ }));
+ notify.error(errorMessage);
+ return false;
+ }
+
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "applied",
+ message: "Command Code connected",
+ }));
+ commandCodeAuthWindowRef.current?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ await fetchConnections();
+ handleCloseAddApiKeyModal();
+ notify.success("Command Code connection added");
+ return true;
+ } catch (error) {
+ console.error("Error applying Command Code auth:", error);
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "error",
+ message: "Failed to apply Command Code auth",
+ }));
+ notify.error("Failed to apply Command Code auth");
+ return false;
+ }
+ },
+ [fetchConnections, handleCloseAddApiKeyModal, notify]
+ );
+
+ const handleStartCommandCodeAuth = useCallback(async () => {
+ if (commandCodeAuthState.phase === "starting" || commandCodeAuthState.phase === "polling") {
+ return;
+ }
+
+ clearCommandCodeAuthTimer();
+ commandCodeAuthWindowRef.current?.close?.();
+
+ const popup = window.open("about:blank", "_blank");
+ setCommandCodeAuthState({
+ phase: "starting",
+ state: "",
+ authUrl: "",
+ callbackUrl: "",
+ expiresAt: null,
+ message: "Opening Command Code Studio…",
+ });
+
+ try {
+ const res = await fetch("/api/providers/command-code/auth/start", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ });
+ const data = await res.json().catch(() => ({}));
+
+ if (!res.ok || !data.state || !data.authUrl) {
+ const errorMessage = data.error || "Failed to start Command Code auth";
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "error",
+ message: errorMessage,
+ }));
+ notify.error(errorMessage);
+ popup?.close?.();
+ return;
+ }
+
+ setCommandCodeAuthState({
+ phase: "polling",
+ state: data.state,
+ authUrl: data.authUrl,
+ callbackUrl: data.callbackUrl || "",
+ expiresAt: data.expiresAt || null,
+ message: "Open the auth URL, approve access, then paste the returned key/JSON/URL below…",
+ });
+
+ if (popup) {
+ try {
+ popup.opener = null;
+ } catch {
+ // Ignore opener cleanup failures.
+ }
+ popup.location.href = data.authUrl;
+ commandCodeAuthWindowRef.current = popup;
+ } else {
+ const fallbackPopup = window.open(data.authUrl, "_blank", "noopener,noreferrer");
+ if (!fallbackPopup) {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "error",
+ message: "Popup blocked. Please allow popups and try Command Code Connect again.",
+ }));
+ notify.error("Popup blocked. Please allow popups and try Command Code Connect again.");
+ return;
+ }
+ commandCodeAuthWindowRef.current = fallbackPopup;
+ }
+
+ const deadline = data.expiresAt ? new Date(data.expiresAt).getTime() : Date.now() + 180000;
+ const poll = async () => {
+ if (Date.now() >= deadline) {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "expired",
+ message: "Command Code link expired",
+ }));
+ commandCodeAuthWindowRef.current?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ notify.error("Command Code auth expired");
+ clearCommandCodeAuthTimer();
+ return;
+ }
+
+ try {
+ const statusRes = await fetch(
+ `/api/providers/command-code/auth/status?state=${encodeURIComponent(data.state)}`,
+ { method: "GET", cache: "no-store" }
+ );
+ const statusData = await statusRes.json().catch(() => ({}));
+ const status = String(statusData.status || statusData.state || statusData.phase || "")
+ .toLowerCase()
+ .trim();
+
+ if (status === "expired") {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "expired",
+ message: "Command Code link expired",
+ }));
+ commandCodeAuthWindowRef.current?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ notify.error("Command Code auth expired");
+ clearCommandCodeAuthTimer();
+ return;
+ }
+
+ if (status === "applied") {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "applied",
+ message: "Command Code connected",
+ }));
+ commandCodeAuthWindowRef.current?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ await fetchConnections();
+ handleCloseAddApiKeyModal();
+ notify.success("Command Code connection added");
+ clearCommandCodeAuthTimer();
+ return;
+ }
+
+ if (status === "received") {
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "received",
+ message: "Browser approved, applying…",
+ }));
+ clearCommandCodeAuthTimer();
+ await handleCommandCodeAuthApply(
+ data.state,
+ statusData.connectionId,
+ statusData.name,
+ statusData.setDefault
+ );
+ return;
+ }
+ } catch {
+ // Keep polling until the contract reports a terminal state or timeout.
+ }
+
+ commandCodeAuthTimerRef.current = window.setTimeout(poll, 2000);
+ };
+
+ commandCodeAuthTimerRef.current = window.setTimeout(poll, 1000);
+ } catch (error) {
+ console.error("Error starting Command Code auth:", error);
+ setCommandCodeAuthState((current) => ({
+ ...current,
+ phase: "error",
+ message: "Failed to start Command Code auth",
+ }));
+ notify.error("Failed to start Command Code auth");
+ popup?.close?.();
+ commandCodeAuthWindowRef.current = null;
+ clearCommandCodeAuthTimer();
+ }
+ }, [
+ clearCommandCodeAuthTimer,
+ handleCloseAddApiKeyModal,
+ commandCodeAuthState.phase,
+ fetchConnections,
+ handleCommandCodeAuthApply,
+ notify,
+ ]);
+
+ const handleOpenCommandCodeConnect = useCallback(() => {
+ setShowAddApiKeyModal(true);
+ void handleStartCommandCodeAuth();
+ }, [handleStartCommandCodeAuth]);
+
+ const handleSaveApiKey = async (formData) => {
+ try {
+ const res = await fetch("/api/providers", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider: providerId, ...formData }),
+ });
+ if (res.ok) {
+ const connectionData = await res.json();
+ const newConnection = connectionData?.connection;
+ await fetchConnections();
+ setShowAddApiKeyModal(false);
+ setSiliconFlowInitialBaseUrl(undefined);
+
+ // Universal: sync models from the provider endpoint on every new connection
+ // (was previously Gemini-only). Do NOT re-introduce a providerId guard here.
+ if (newConnection?.id) {
+ setShowImportModal(true);
+ setImportProgress({
+ current: 0,
+ total: 0,
+ phase: "fetching",
+ status: t("fetchingModels"),
+ logs: [],
+ error: "",
+ importedCount: 0,
+ });
+
+ try {
+ const syncRes = await fetch(`/api/providers/${newConnection.id}/sync-models`, {
+ method: "POST",
+ signal: AbortSignal.timeout(30_000), // 30s timeout — model sync shouldn't hang
+ });
+ const syncData = await syncRes.json();
+
+ if (!syncRes.ok || syncData.error) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "error",
+ status: t("failedFetchModels"),
+ error: syncData.error?.message || syncData.error || t("failedImportModels"),
+ }));
+ return null;
+ }
+
+ const syncedCount = syncData.syncedModels || 0;
+ const availableCount =
+ typeof syncData.availableModelsCount === "number"
+ ? syncData.availableModelsCount
+ : Array.isArray(syncData.models)
+ ? syncData.models.length
+ : syncedCount;
+ const syncedModelList: Array<{ id: string; name?: string }> = syncData.models || [];
+ const logs: string[] = [];
+ if (syncedModelList.length > 0) {
+ logs.push(`✓ ${availableCount} models available`);
+ logs.push("");
+ for (const m of syncedModelList) {
+ logs.push(` ${m.name || m.id}`);
+ }
+ }
+
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ status: t("modelsImported", { count: availableCount }),
+ total: availableCount,
+ current: availableCount,
+ importedCount: availableCount,
+ logs,
+ }));
+
+ await fetchProviderModelMeta();
+ } catch (syncError) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "error",
+ status: t("failedFetchModels"),
+ error: String(syncError),
+ }));
+ }
+ }
+ return null;
+ }
+ const data = await res.json().catch(() => ({}));
+ const errorMsg = data.error?.message || data.error || t("failedSaveConnection");
+ return errorMsg;
+ } catch (error) {
+ console.log("Error saving connection:", error);
+ return t("failedSaveConnectionRetry");
+ }
+ };
+
+ const handleUpdateConnection = async (formData) => {
+ try {
+ const res = await fetch(`/api/providers/${selectedConnection.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(formData),
+ });
+ if (res.ok) {
+ await fetchConnections();
+ setShowEditModal(false);
+ return null;
+ }
+ const data = await res.json().catch(() => ({}));
+ return data.error?.message || data.error || t("failedSaveConnection");
+ } catch (error) {
+ console.log("Error updating connection:", error);
+ return t("failedSaveConnectionRetry");
+ }
+ };
+
+ // handleUpdateConnectionStatus, handleToggleProxyEnabled, handleTogglePerKeyProxyEnabled,
+ // handleDistributeProxies, handleToggleRateLimit, handleToggleClaudeExtraUsage,
+ // handleToggleCliproxyapiMode, handleToggleCodexLimit, handleToggleClaudeRoutingPreference,
+ // handleChangeCodexGlobalServiceMode, handleRetestConnection, runBatchTest,
+ // handleBatchTestAll, handleBatchRetest, parseApiErrorMessage, getAttachmentFilename,
+ // handleRefreshToken → hooks/useProviderConnections.ts + useProviderSettings.ts (Phase 1f)
+
+ // handleToggleProxyEnabled → useProviderConnections (Phase 1f)
+
+ // handleTogglePerKeyProxyEnabled → useProviderConnections (Phase 1f)
+
+ // handleDistributeProxies → useProviderConnections (Phase 1f)
+
+ // handleToggleRateLimit → useProviderConnections (Phase 1f)
+
+ // handleToggleClaudeExtraUsage → useProviderConnections (Phase 1f)
+
+ // [cpaProviderEnabled] state + useEffect + handleToggleCliproxyapiMode → useProviderConnections (Phase 1f)
+
+ // handleToggleCodexLimit → useProviderConnections (Phase 1f)
+
+ // handleToggleClaudeRoutingPreference + handleChangeCodexGlobalServiceMode → useProviderSettings (Phase 1f)
+
+ // handleRetestConnection, runBatchTest, handleBatchTestAll, handleBatchRetest,
+ // [refreshingId], parseApiErrorMessage, getAttachmentFilename, handleRefreshToken
+ // → useProviderConnections (Phase 1f)
+
+ const handleApplyCodexAuthLocal = async (connectionId: string) => {
+ if (applyingCodexAuthId) return;
+ setApplyingCodexAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("codexAuthAppliedLocal")
+ ? t("codexAuthAppliedLocal")
+ : "Codex auth.json applied locally";
+ const defaultError =
+ typeof t.has === "function" && t.has("codexAuthApplyFailed")
+ ? t("codexAuthApplyFailed")
+ : "Failed to apply Codex auth.json locally";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/codex-auth/apply-local`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ notify.success(defaultSuccess);
+ setApplyCodexModalConnectionId(null);
+ } catch (error) {
+ console.error("Error applying Codex auth locally:", error);
+ notify.error(defaultError);
+ } finally {
+ setApplyingCodexAuthId(null);
+ }
+ };
+
+ const handleExportCodexAuthFile = async (connectionId: string) => {
+ if (exportingCodexAuthId) return;
+ setExportingCodexAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("codexAuthExported")
+ ? t("codexAuthExported")
+ : "Codex auth.json exported";
+ const defaultError =
+ typeof t.has === "function" && t.has("codexAuthExportFailed")
+ ? t("codexAuthExportFailed")
+ : "Failed to export Codex auth.json";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/codex-auth/export`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ const blob = await res.blob();
+ const filename = getAttachmentFilename(res, "codex-auth.json");
+ const objectUrl = window.URL.createObjectURL(blob);
+ const link = document.createElement("a");
+
+ link.href = objectUrl;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
+
+ notify.success(defaultSuccess);
+ } catch (error) {
+ console.error("Error exporting Codex auth file:", error);
+ notify.error(defaultError);
+ } finally {
+ setExportingCodexAuthId(null);
+ }
+ };
+
+ const handleApplyClaudeAuthLocal = async (connectionId: string) => {
+ if (applyingClaudeAuthId) return;
+ setApplyingClaudeAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("claudeAuthAppliedLocal")
+ ? t("claudeAuthAppliedLocal")
+ : "Claude auth applied locally";
+ const defaultError =
+ typeof t.has === "function" && t.has("claudeAuthApplyFailed")
+ ? t("claudeAuthApplyFailed")
+ : "Failed to apply Claude auth locally";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/claude-auth/apply-local`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ notify.success(defaultSuccess);
+ setApplyClaudeModalConnectionId(null);
+ } catch (error) {
+ console.error("Error applying Claude auth locally:", error);
+ notify.error(defaultError);
+ } finally {
+ setApplyingClaudeAuthId(null);
+ }
+ };
+
+ const handleExportClaudeAuthFile = async (connectionId: string) => {
+ if (exportingClaudeAuthId) return;
+ setExportingClaudeAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("claudeAuthExported")
+ ? t("claudeAuthExported")
+ : "Claude auth file exported";
+ const defaultError =
+ typeof t.has === "function" && t.has("claudeAuthExportFailed")
+ ? t("claudeAuthExportFailed")
+ : "Failed to export Claude auth file";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/claude-auth/export`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ const blob = await res.blob();
+ const filename = getAttachmentFilename(res, "claude-auth.json");
+ const objectUrl = window.URL.createObjectURL(blob);
+ const link = document.createElement("a");
+
+ link.href = objectUrl;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
+
+ notify.success(defaultSuccess);
+ } catch (error) {
+ console.error("Error exporting Claude auth file:", error);
+ notify.error(defaultError);
+ } finally {
+ setExportingClaudeAuthId(null);
+ }
+ };
+
+ const handleApplyGeminiAuthLocal = async (connectionId: string) => {
+ if (applyingGeminiAuthId) return;
+ setApplyingGeminiAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("geminiAuthAppliedLocal")
+ ? t("geminiAuthAppliedLocal")
+ : "Gemini auth applied locally";
+ const defaultError =
+ typeof t.has === "function" && t.has("geminiAuthApplyFailed")
+ ? t("geminiAuthApplyFailed")
+ : "Failed to apply Gemini auth locally";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/gemini-cli-auth/apply-local`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ notify.success(defaultSuccess);
+ setApplyGeminiModalConnectionId(null);
+ } catch (error) {
+ console.error("Error applying Gemini auth locally:", error);
+ notify.error(defaultError);
+ } finally {
+ setApplyingGeminiAuthId(null);
+ }
+ };
+
+ const handleExportGeminiAuthFile = async (connectionId: string) => {
+ if (exportingGeminiAuthId) return;
+ setExportingGeminiAuthId(connectionId);
+
+ const defaultSuccess =
+ typeof t.has === "function" && t.has("geminiAuthExported")
+ ? t("geminiAuthExported")
+ : "Gemini auth file exported";
+ const defaultError =
+ typeof t.has === "function" && t.has("geminiAuthExportFailed")
+ ? t("geminiAuthExportFailed")
+ : "Failed to export Gemini auth file";
+
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/gemini-cli-auth/export`, {
+ method: "POST",
+ });
+
+ if (!res.ok) {
+ notify.error(await parseApiErrorMessage(res, defaultError));
+ return;
+ }
+
+ const blob = await res.blob();
+ const filename = getAttachmentFilename(res, "gemini-auth.json");
+ const objectUrl = window.URL.createObjectURL(blob);
+ const link = document.createElement("a");
+
+ link.href = objectUrl;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
+
+ notify.success(defaultSuccess);
+ } catch (error) {
+ console.error("Error exporting Gemini auth file:", error);
+ notify.error(defaultError);
+ } finally {
+ setExportingGeminiAuthId(null);
+ }
+ };
+
+ // handleSwapPriority → useProviderConnections (Phase 1f)
+
+ const handleImportModels = async () => {
+ if (importingModels) return;
+ const activeConnection = connections.find((conn) => conn.isActive !== false);
+ // #3047 — no-auth providers (e.g. OpenCode Free) have no connection rows;
+ // fall back to the provider id so the models route can serve the public
+ // catalog instead of the button silently doing nothing.
+ if (!activeConnection && !isFreeNoAuth) return;
+ const importTargetId = activeConnection?.id ?? providerId;
+
+ setImportingModels(true);
+ setShowImportModal(true);
+ setImportProgress({
+ current: 0,
+ total: 0,
+ phase: "fetching",
+ status: t("fetchingModels"),
+ logs: [],
+ error: "",
+ importedCount: 0,
+ });
+
+ try {
+ const res = await fetch(`/api/providers/${importTargetId}/models?refresh=true`);
+ const data = await res.json();
+ if (!res.ok) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "error",
+ status: t("failedFetchModels"),
+ error: data.error || t("failedImportModels"),
+ }));
+ return;
+ }
+ const fetchedModels = data.models || [];
+ if (fetchedModels.length === 0) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ status: t("noModelsFound"),
+ logs: [t("noModelsReturnedFromEndpoint")],
+ }));
+ return;
+ }
+
+ const existingIds = new Set([
+ ...(modelMeta.customModels || []).map((m: any) => m.id),
+ ...models.map((m: any) => m.id),
+ ]);
+ const newModels = fetchedModels.filter(
+ (model: any) => !existingIds.has(model.id || model.name || model.model)
+ );
+
+ if (newModels.length === 0) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ status: t("allModelsAlreadyImported") || "All models already imported",
+ logs: [t("noNewModelsToImport") || "No new models to import"],
+ importedCount: 0,
+ total: 0,
+ current: 0,
+ }));
+ return;
+ }
+
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "importing",
+ total: newModels.length,
+ current: 0,
+ status: t("importingModelsProgress", { current: 0, total: newModels.length }),
+ logs: [
+ t("foundModelsStartingImport", { count: newModels.length }),
+ ...(newModels.length < fetchedModels.length
+ ? [
+ t("skippingExistingModels", { count: fetchedModels.length - newModels.length }) ||
+ `Skipping ${fetchedModels.length - newModels.length} existing models`,
+ ]
+ : []),
+ ],
+ }));
+
+ let importedCount = 0;
+ for (let i = 0; i < newModels.length; i++) {
+ const model = newModels[i];
+ const modelId = model.id || model.name || model.model;
+ if (!modelId) continue;
+ const parts = modelId.split("/");
+ const baseAlias = parts[parts.length - 1];
+
+ setImportProgress((prev) => ({
+ ...prev,
+ current: i + 1,
+ status: t("importingModelsProgress", { current: i + 1, total: newModels.length }),
+ logs: [...prev.logs, t("importingModelById", { modelId })],
+ }));
+
+ // Save as imported (default) model in the DB
+ await fetch("/api/provider-models", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: providerId,
+ modelId,
+ modelName: model.name || modelId,
+ source: "imported",
+ ...(typeof model.apiFormat === "string" ? { apiFormat: model.apiFormat } : {}),
+ ...(Array.isArray(model.supportedEndpoints)
+ ? { supportedEndpoints: model.supportedEndpoints }
+ : {}),
+ }),
+ });
+ // Also create an alias for routing
+ if (!modelAliases[baseAlias]) {
+ await handleSetAlias(modelId, baseAlias, providerStorageAlias);
+ }
+ importedCount += 1;
+ }
+
+ await fetchAliases();
+
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ current: newModels.length,
+ status:
+ importedCount > 0
+ ? t("importSuccessCount", { count: importedCount })
+ : t("noNewModelsAddedExisting"),
+ logs: [
+ ...prev.logs,
+ importedCount > 0
+ ? t("importDoneCount", { count: importedCount })
+ : t("noNewModelsAdded"),
+ ],
+ importedCount,
+ }));
+
+ // Auto-reload after success
+ if (importedCount > 0) {
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ }
+ } catch (error) {
+ console.log("Error importing models:", error);
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "error",
+ status: t("importFailed"),
+ error: error instanceof Error ? error.message : t("unexpectedErrorOccurred"),
+ }));
+ } finally {
+ setImportingModels(false);
+ }
+ };
+
+ // Shared import handler for CompatibleModelsSection
+ const handleCompatibleImportWithProgress = async (connectionId: string) => {
+ setShowImportModal(true);
+ setImportProgress({
+ current: 0,
+ total: 0,
+ phase: "fetching",
+ status: t("fetchingModels"),
+ logs: [],
+ error: "",
+ importedCount: 0,
+ });
+
+ try {
+ const response = await fetch(`/api/providers/${connectionId}/sync-models?mode=import`, {
+ method: "POST",
+ signal: AbortSignal.timeout(60_000),
+ });
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || t("failedImportModels"));
+ }
+
+ const importedModels = Array.isArray(data.importedModels) ? data.importedModels : [];
+ const importedCount =
+ typeof data.importedCount === "number" ? data.importedCount : importedModels.length;
+ const changedCount =
+ typeof data.importedChanges?.total === "number"
+ ? data.importedChanges.total
+ : importedCount;
+ const totalChangedCount =
+ changedCount +
+ (typeof data.customModelChanges?.total === "number" ? data.customModelChanges.total : 0);
+
+ if (importedModels.length === 0) {
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ status:
+ importedCount > 0
+ ? t("importSuccessCount", { count: importedCount })
+ : t("noNewModelsAdded"),
+ logs: [
+ importedCount > 0
+ ? t("importDoneCount", { count: importedCount })
+ : t("noNewModelsAdded"),
+ ],
+ importedCount,
+ }));
+ if (totalChangedCount > 0) {
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ }
+ return;
+ }
+
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "done",
+ total: importedModels.length,
+ current: importedModels.length,
+ status:
+ importedCount > 0
+ ? t("importSuccessCount", { count: importedCount })
+ : t("noNewModelsAdded"),
+ logs: [
+ t("foundModelsStartingImport", { count: importedModels.length }),
+ ...importedModels.map((model: any) =>
+ t("importingModelById", { modelId: model.id || model.name || model.model })
+ ),
+ importedCount > 0
+ ? t("importDoneCount", { count: importedCount })
+ : t("noNewModelsAdded"),
+ ],
+ importedCount,
+ }));
+
+ if (totalChangedCount > 0) {
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ }
+ } catch (error) {
+ console.log("Error importing models:", error);
+ setImportProgress((prev) => ({
+ ...prev,
+ phase: "error",
+ status: t("importFailed"),
+ error: error instanceof Error ? error.message : t("unexpectedErrorOccurred"),
+ }));
+ }
+ };
+
+ const canImportModels = isFreeNoAuth || connections.some((conn) => conn.isActive !== false);
+
+ // Auto-sync toggle state: read from first active connection's providerSpecificData
+ const autoSyncConnection = connections.find((conn: any) => conn.isActive !== false);
+ const isAutoSyncEnabled = !!(autoSyncConnection as any)?.providerSpecificData?.autoSync;
+ const [togglingAutoSync, setTogglingAutoSync] = useState(false);
+
+ const handleToggleAutoSync = async () => {
+ if (!autoSyncConnection || togglingAutoSync) return;
+ setTogglingAutoSync(true);
+ try {
+ const newValue = !isAutoSyncEnabled;
+ await fetch(`/api/providers/${(autoSyncConnection as any).id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerSpecificData: { autoSync: newValue },
+ }),
+ });
+ await fetchConnections();
+ notify[newValue ? "success" : "info"](
+ newValue ? t("autoSyncEnabled") : t("autoSyncDisabled")
+ );
+ } catch (error) {
+ console.log("Error toggling auto-sync:", error);
+ notify.error(t("autoSyncToggleFailed"));
+ } finally {
+ setTogglingAutoSync(false);
+ }
+ };
+
+ const [clearingModels, setClearingModels] = useState(false);
+ const providerAliasEntries = useMemo(
+ () =>
+ Object.entries(modelAliases).filter(
+ ([, model]) => typeof model === "string" && model.startsWith(`${providerStorageAlias}/`)
+ ),
+ [modelAliases, providerStorageAlias]
+ );
+
+ const handleClearAllModels = async () => {
+ if (clearingModels) return;
+ if (!confirm(t("clearAllModelsConfirm"))) return;
+ setClearingModels(true);
+ try {
+ const res = await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerStorageAlias)}&all=true`,
+ { method: "DELETE" }
+ );
+ if (res.ok) {
+ // Also delete all aliases that belong to this provider
+ await Promise.all(
+ providerAliasEntries.map(([alias]) =>
+ fetch(`/api/models/alias?alias=${encodeURIComponent(alias)}`, {
+ method: "DELETE",
+ }).catch(() => {})
+ )
+ );
+ await fetchProviderModelMeta();
+ await fetchAliases();
+ notify.success(t("clearAllModelsSuccess"));
+ } else {
+ notify.error(t("clearAllModelsFailed"));
+ }
+ } catch {
+ notify.error(t("clearAllModelsFailed"));
+ } finally {
+ setClearingModels(false);
+ }
+ };
+
+ // Phase 1e: compat-state derivations moved to useModelCompatState hook.
+ const compat = useModelCompatState(
+ modelMeta.customModels,
+ modelMeta.modelCompatOverrides
+ );
+ const { customMap, overrideMap } = compat;
+ const effectiveModelNormalize = compat.effectiveModelNormalize;
+ const effectiveModelPreserveDeveloper = compat.effectiveModelPreserveDeveloper;
+ const effectiveModelHidden = compat.isModelHidden;
+ const getUpstreamHeadersRecordForModel = compat.getUpstreamHeadersRecord;
+
+ const compatibleFallbackModels = useMemo(
+ () => getCompatibleFallbackModels(providerId, modelMeta.customModels),
+ [providerId, modelMeta.customModels]
+ );
+
+ const saveModelCompatFlags = async (modelId: string, patch: ModelCompatSavePatch) => {
+ setCompatSavingModelId(modelId);
+ try {
+ const c = customMap.get(modelId) as Record<string, unknown> | undefined;
+ let body: Record<string, unknown>;
+ const onlyCompatByProtocol =
+ patch.compatByProtocol &&
+ patch.normalizeToolCallId === undefined &&
+ patch.preserveOpenAIDeveloperRole === undefined &&
+ !("upstreamHeaders" in patch);
+
+ if (c) {
+ if (onlyCompatByProtocol) {
+ body = {
+ provider: providerId,
+ modelId,
+ compatByProtocol: patch.compatByProtocol,
+ };
+ } else {
+ body = {
+ provider: providerId,
+ modelId,
+ modelName: (c.name as string) || modelId,
+ source: (c.source as string) || "manual",
+ apiFormat: (c.apiFormat as string) || "chat-completions",
+ supportedEndpoints:
+ Array.isArray(c.supportedEndpoints) && (c.supportedEndpoints as unknown[]).length
+ ? c.supportedEndpoints
+ : ["chat"],
+ normalizeToolCallId:
+ patch.normalizeToolCallId !== undefined
+ ? patch.normalizeToolCallId
+ : Boolean(c.normalizeToolCallId),
+ preserveOpenAIDeveloperRole:
+ patch.preserveOpenAIDeveloperRole !== undefined
+ ? patch.preserveOpenAIDeveloperRole
+ : Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole")
+ ? Boolean(c.preserveOpenAIDeveloperRole)
+ : true,
+ };
+ if (patch.compatByProtocol) body.compatByProtocol = patch.compatByProtocol;
+ }
+ } else {
+ body = { provider: providerId, modelId, ...patch };
+ }
+ const res = await fetch("/api/provider-models", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const detail = await formatProviderModelsErrorResponse(res);
+ notify.error(
+ detail ? `${t("failedSaveCustomModel")} — ${detail}` : t("failedSaveCustomModel")
+ );
+ return;
+ }
+ } catch {
+ notify.error(t("failedSaveCustomModel"));
+ return;
+ } finally {
+ setCompatSavingModelId(null);
+ }
+ try {
+ await fetchProviderModelMeta();
+ } catch {
+ /* refresh failure is non-critical — data was already saved */
+ }
+ };
+
+ const handleToggleModelHidden = async (
+ providerKey: string,
+ modelId: string,
+ hidden: boolean
+ ): Promise<void> => {
+ setTogglingModelId(modelId);
+ try {
+ const res = await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerKey)}&modelId=${encodeURIComponent(modelId)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ isHidden: hidden }),
+ }
+ );
+ if (!res.ok) {
+ const detail = await res.text().catch(() => "");
+ notify.error(detail || t("failedSaveCustomModel"));
+ return;
+ }
+ await Promise.all([fetchProviderModelMeta().catch(() => {}), fetchAliases().catch(() => {})]);
+ } catch {
+ notify.error(t("failedSaveCustomModel"));
+ } finally {
+ setTogglingModelId(null);
+ }
+ };
+
+ const handleBulkToggleModelHidden = async (
+ providerKey: string,
+ modelIds: string[],
+ hidden: boolean
+ ): Promise<void> => {
+ if (modelIds.length === 0) return;
+ setBulkVisibilityAction(hidden ? "deselect" : "select");
+ try {
+ const res = await fetch(`/api/provider-models?provider=${encodeURIComponent(providerKey)}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ isHidden: hidden, modelIds }),
+ });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => "");
+ notify.error(detail || t("failedSaveCustomModel"));
+ return;
+ }
+ await Promise.all([fetchProviderModelMeta().catch(() => {}), fetchAliases().catch(() => {})]);
+ } catch {
+ notify.error(t("failedSaveCustomModel"));
+ } finally {
+ setBulkVisibilityAction(null);
+ }
+ };
+
+ const renderModelsSection = () => {
+ const autoSyncToggle = compatibleSupportsModelImport && canImportModels && (
+ <button
+ onClick={handleToggleAutoSync}
+ disabled={togglingAutoSync}
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border bg-transparent cursor-pointer text-[12px] disabled:opacity-50 disabled:cursor-not-allowed"
+ title={t("autoSyncTooltip")}
+ >
+ <span
+ className="material-symbols-outlined text-[16px]"
+ style={{ color: isAutoSyncEnabled ? "#22c55e" : "var(--color-text-muted)" }}
+ >
+ {isAutoSyncEnabled ? "toggle_on" : "toggle_off"}
+ </span>
+ <span className="text-text-main">{t("autoSync")}</span>
+ </button>
+ );
+
+ const clearAllButton = (modelMeta.customModels.length > 0 ||
+ providerAliasEntries.length > 0) && (
+ <button
+ onClick={handleClearAllModels}
+ disabled={clearingModels}
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-red-300 dark:border-red-800 bg-transparent cursor-pointer text-[12px] text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 disabled:cursor-not-allowed"
+ title={t("clearAllModels")}
+ >
+ <span className="material-symbols-outlined text-[16px]">delete_sweep</span>
+ <span>{t("clearAllModels")}</span>
+ </button>
+ );
+
+ if (isManagedAvailableModelsProvider) {
+ const description =
+ providerId === "openrouter"
+ ? t("openRouterAnyModelHint")
+ : isCcCompatible
+ ? t("ccCompatibleModelsDescription")
+ : t("compatibleModelsDescription", {
+ type: isAnthropicCompatible ? t("anthropic") : t("openai"),
+ });
+ const inputLabel = providerId === "openrouter" ? t("modelIdFromOpenRouter") : t("modelId");
+ const inputPlaceholder =
+ providerId === "openrouter"
+ ? t("openRouterModelPlaceholder")
+ : isCcCompatible
+ ? "claude-sonnet-4-6"
+ : isAnthropicCompatible
+ ? t("anthropicCompatibleModelPlaceholder")
+ : t("openaiCompatibleModelPlaceholder");
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-4">
+ {autoSyncToggle}
+ {clearAllButton}
+ </div>
+ <CompatibleModelsSection
+ providerStorageAlias={providerStorageAlias}
+ providerDisplayAlias={providerDisplayAlias}
+ modelAliases={modelAliases}
+ availableModels={syncedAvailableModels}
+ customModels={modelMeta.customModels}
+ fallbackModels={compatibleFallbackModels}
+ description={description}
+ inputLabel={inputLabel}
+ inputPlaceholder={inputPlaceholder}
+ copied={copied}
+ onCopy={copy}
+ onSetAlias={handleSetAlias}
+ onDeleteAlias={handleDeleteAlias}
+ connections={connections}
+ isAnthropic={isAnthropicProtocolCompatible}
+ onImportWithProgress={handleCompatibleImportWithProgress}
+ t={t}
+ effectiveModelNormalize={effectiveModelNormalize}
+ effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
+ getUpstreamHeadersRecord={getUpstreamHeadersRecordForModel}
+ saveModelCompatFlags={saveModelCompatFlags}
+ compatSavingModelId={compatSavingModelId}
+ onModelsChanged={fetchProviderModelMeta}
+ allowImport={compatibleSupportsModelImport}
+ isModelHidden={effectiveModelHidden}
+ onToggleHidden={(modelId, hidden) =>
+ handleToggleModelHidden(providerStorageAlias, modelId, hidden)
+ }
+ onBulkToggleHidden={(modelIds, hidden) =>
+ handleBulkToggleModelHidden(providerStorageAlias, modelIds, hidden)
+ }
+ bulkTogglePending={bulkVisibilityAction !== null}
+ togglingModelId={togglingModelId}
+ onTestModel={onTestModel}
+ modelTestStatus={modelTestStatus}
+ testingModelId={testingModelId}
+ onTestAll={handleTestAll}
+ testingAll={testingAll}
+ testProgress={testProgress}
+ autoHideFailed={autoHideFailed}
+ onAutoHideFailedChange={setAutoHideFailed}
+ />
+ </div>
+ );
+ }
+
+ if (providerInfo.passthroughModels) {
+ const passthroughDescription =
+ providerId === "openrouter"
+ ? t("openRouterAnyModelHint")
+ : providerId === "bedrock"
+ ? t("bedrockModelsDescription")
+ : t("passthroughModelsDescription", { provider: providerInfo?.name || providerId });
+ const passthroughInputLabel =
+ providerId === "openrouter" ? t("modelIdFromOpenRouter") : t("modelId");
+ const passthroughInputPlaceholder =
+ providerId === "openrouter"
+ ? t("openRouterModelPlaceholder")
+ : providerId === "bedrock"
+ ? t("bedrockModelPlaceholder")
+ : t("openaiCompatibleModelPlaceholder");
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-4">
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="download"
+ onClick={handleImportModels}
+ disabled={!canImportModels || importingModels}
+ >
+ {importingModels ? t("importingModels") : t("importFromModels")}
+ </Button>
+ {autoSyncToggle}
+ {clearAllButton}
+ {!canImportModels && (
+ <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>
+ )}
+ </div>
+ <PassthroughModelsSection
+ providerAlias={providerAlias}
+ modelAliases={modelAliases}
+ availableModels={syncedAvailableModels}
+ customModels={modelMeta.customModels}
+ description={passthroughDescription}
+ inputLabel={passthroughInputLabel}
+ inputPlaceholder={passthroughInputPlaceholder}
+ copied={copied}
+ onCopy={copy}
+ onSetAlias={handleSetAlias}
+ onDeleteAlias={handleDeleteAlias}
+ t={t}
+ effectiveModelNormalize={effectiveModelNormalize}
+ effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
+ getUpstreamHeadersRecord={getUpstreamHeadersRecordForModel}
+ saveModelCompatFlags={saveModelCompatFlags}
+ compatSavingModelId={compatSavingModelId}
+ isModelHidden={effectiveModelHidden}
+ onToggleHidden={(modelId, hidden) =>
+ handleToggleModelHidden(providerStorageAlias, modelId, hidden)
+ }
+ onBulkToggleHidden={(modelIds, hidden) =>
+ handleBulkToggleModelHidden(providerStorageAlias, modelIds, hidden)
+ }
+ bulkTogglePending={bulkVisibilityAction !== null}
+ togglingModelId={togglingModelId}
+ onTestModel={onTestModel}
+ modelTestStatus={modelTestStatus}
+ testingModelId={testingModelId}
+ providerId={providerId}
+ connectionId={selectedConnection?.id ?? ""}
+ autoHideFailed={autoHideFailed}
+ onAutoHideFailedChange={setAutoHideFailed}
+ />
+ </div>
+ );
+ }
+
+ const importButton = (
+ <div className="flex items-center gap-2 mb-4">
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="download"
+ onClick={handleImportModels}
+ disabled={!canImportModels || importingModels}
+ >
+ {importingModels ? t("importingModels") : t("importFromModels")}
+ </Button>
+ {autoSyncToggle}
+ {!canImportModels && (
+ <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>
+ )}
+ </div>
+ );
+
+ if (models.length === 0) {
+ return (
+ <div>
+ {importButton}
+ <p className="text-sm text-text-muted">{t("noModelsConfigured")}</p>
+ </div>
+ );
+ }
+ const modelsWithVisibility = models.map((model) => ({
+ ...model,
+ isHidden: effectiveModelHidden(model.id),
+ }));
+ const filteredModels = modelsWithVisibility.filter((model) => {
+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {
+ modelId: model.id,
+ modelName: model.name,
+ source: model.source,
+ });
+ const matchesVisibility =
+ visibilityFilter === "all"
+ ? true
+ : visibilityFilter === "visible"
+ ? !model.isHidden
+ : model.isHidden;
+ return matchesQuery && matchesVisibility;
+ });
+ const activeCount = modelsWithVisibility.filter((m) => !m.isHidden).length;
+ const hiddenFilteredCount = filteredModels.filter((m) => m.isHidden).length;
+ const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;
+ const testAllTargets = filteredModels
+ .filter((m) => !m.isHidden)
+ .map((m) => ({ modelId: m.id, fullModel: `${providerDisplayAlias}/${m.id}` }));
+ return (
+ <div>
+ {importButton}
+ {modelsWithVisibility.length > 0 && (
+ <ModelVisibilityToolbar
+ t={t}
+ filterValue={modelFilter}
+ onFilterChange={setModelFilter}
+ activeCount={activeCount}
+ totalCount={modelsWithVisibility.length}
+ onSelectAll={() =>
+ handleBulkToggleModelHidden(
+ providerId,
+ filteredModels.map((model) => model.id),
+ false
+ )
+ }
+ onDeselectAll={() =>
+ handleBulkToggleModelHidden(
+ providerId,
+ filteredModels.map((model) => model.id),
+ true
+ )
+ }
+ selectAllDisabled={hiddenFilteredCount === 0 || bulkVisibilityAction !== null}
+ deselectAllDisabled={visibleFilteredCount === 0 || bulkVisibilityAction !== null}
+ onTestAll={() => handleTestAll(testAllTargets)}
+ testingAll={testingAll}
+ testProgress={testProgress}
+ visibilityFilter={visibilityFilter}
+ onVisibilityFilterChange={setVisibilityFilter}
+ autoHideFailed={autoHideFailed}
+ onAutoHideFailedChange={setAutoHideFailed}
+ />
+ )}
+ <div className="flex flex-wrap gap-3">
+ {filteredModels.map((model) => {
+ return (
+ <ModelRow
+ key={model.id}
+ model={model}
+ fullModel={`${providerDisplayAlias}/${model.id}`}
+ provider={providerId}
+ copied={copied}
+ onCopy={copy}
+ t={t}
+ showDeveloperToggle
+ effectiveModelNormalize={effectiveModelNormalize}
+ effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
+ getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecordForModel(model.id, p)}
+ saveModelCompatFlags={saveModelCompatFlags}
+ compatDisabled={compatSavingModelId === model.id}
+ onToggleHidden={(modelId, hidden) =>
+ handleToggleModelHidden(providerId, modelId, hidden)
+ }
+ togglingHidden={togglingModelId === model.id}
+ onTestModel={onTestModel}
+ testStatus={modelTestStatus[model.id] || null}
+ testingModel={testingModelId === model.id}
+ />
+ );
+ })}
+ {filteredModels.length === 0 && modelFilter && (
+ <p className="text-sm text-text-muted py-2">
+ {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
+ filter: modelFilter,
+ })}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ if (loading) {
+ return (
+ <div className="flex flex-col gap-8">
+ <CardSkeleton />
+ <CardSkeleton />
+ </div>
+ );
+ }
+
+ if (!providerInfo) {
+ return (
+ <div className="text-center py-20">
+ <p className="text-text-muted">{t("providerNotFound")}</p>
+ <Link href="/dashboard/providers" className="text-primary mt-4 inline-block">
+ {t("backToProviders")}
+ </Link>
+ </div>
+ );
+ }
+
+ // OpenAI/Anthropic compatible providers use their specialized pseudo-provider icons.
+ const getHeaderIconProviderId = () => {
+ if (isOpenAICompatible && providerInfo.apiType) {
+ return providerInfo.apiType === "responses" ? "oai-r" : "oai-cc";
+ }
+ if (isAnthropicProtocolCompatible) {
+ return "anthropic-m";
+ }
+ return providerInfo.id;
+ };
+
+ return (
+ <div className="flex flex-col gap-8">
+ {/* Header */}
+ <div>
+ <Link
+ href="/dashboard/providers"
+ className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4"
+ >
+ <span className="material-symbols-outlined text-lg">arrow_back</span>
+ {t("backToProviders")}
+ </Link>
+ <div className="flex items-center gap-4">
+ <div
+ className="rounded-lg flex items-center justify-center"
+ style={{ backgroundColor: `${providerInfo.color}15` }}
+ >
+ <ProviderIcon providerId={getHeaderIconProviderId()} size={48} type="color" />
+ </div>
+ <div>
+ {providerInfo.website ? (
+ <a
+ href={providerInfo.website}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-3xl font-semibold tracking-tight hover:underline inline-flex items-center gap-2"
+ style={{ color: providerInfo.color }}
+ >
+ {providerInfo.name}
+ <span className="material-symbols-outlined text-lg opacity-60">open_in_new</span>
+ </a>
+ ) : (
+ <h1 className="text-3xl font-semibold tracking-tight">{providerInfo.name}</h1>
+ )}
+ <div className="flex items-center gap-2">
+ <p className="text-text-muted">
+ {t("connectionCountLabel", { count: connections.length })}
+ </p>
+ <EmailPrivacyToggle size="md" />
+ {providerId === "adapta-web" && (
+ <button
+ onClick={() => setShowTutorialModal(true)}
+ className="text-sm font-medium underline underline-offset-2 opacity-70 hover:opacity-100 transition-opacity"
+ style={{ color: providerInfo.color }}
+ >
+ Tutorial
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {providerId === "zed" && (
+ <>
+ <Card>
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex-1 min-w-0">
+ <h2 className="text-lg font-semibold flex items-center gap-2">
+ <span className="material-symbols-outlined text-[20px]">download</span>
+ Import from Zed Keychain
+ </h2>
+ <p className="text-sm text-text-muted mt-1">
+ Discover AI provider credentials (OpenAI, Anthropic, Google, Mistral, xAI) that
+ Zed IDE stored in the OS keychain and import them as connections. Requires Zed IDE
+ installed on this machine.
+ </p>
+ </div>
+ <Button
+ size="sm"
+ variant="secondary"
+ icon={importingZed ? "sync" : "download"}
+ onClick={handleZedImport}
+ disabled={importingZed}
+ >
+ {importingZed ? "Importing…" : "Import from Zed"}
+ </Button>
+ </div>
+ </Card>
+ <Card>
+ <div className="flex flex-col gap-3">
+ <button
+ className="flex items-center justify-between w-full text-left"
+ onClick={() => setShowZedManual((v) => !v)}
+ >
+ <h2 className="text-lg font-semibold flex items-center gap-2">
+ <span className="material-symbols-outlined text-[20px]">edit</span>
+ Manual Token Import
+ </h2>
+ <span className="material-symbols-outlined text-[18px] text-text-muted">
+ {showZedManual ? "expand_less" : "expand_more"}
+ </span>
+ </button>
+ {showZedManual && (
+ <div className="flex flex-col gap-3 mt-1">
+ <p className="text-sm text-text-muted">
+ Use this when OmniRoute runs in Docker or the keychain is unavailable. Paste the
+ API key that Zed stored under{" "}
+ <code className="font-mono text-xs">~/.config/zed/settings.json</code> or copy
+ it from the Zed AI settings panel.
+ </p>
+ <div className="flex gap-2 flex-col sm:flex-row">
+ <select
+ className="input input-sm"
+ value={zedManualProvider}
+ onChange={(e) => setZedManualProvider(e.target.value)}
+ >
+ <option value="openai">OpenAI</option>
+ <option value="anthropic">Anthropic</option>
+ <option value="google">Google</option>
+ <option value="mistral">Mistral</option>
+ <option value="xai">xAI</option>
+ <option value="openrouter">OpenRouter</option>
+ <option value="deepseek">DeepSeek</option>
+ </select>
+ <input
+ type="password"
+ className="input input-sm flex-1"
+ placeholder="Paste API key…"
+ value={zedManualToken}
+ onChange={(e) => setZedManualToken(e.target.value)}
+ />
+ <Button
+ size="sm"
+ variant="secondary"
+ icon={importingZedManual ? "sync" : "upload"}
+ onClick={handleZedManualImport}
+ disabled={importingZedManual || !zedManualToken.trim()}
+ >
+ {importingZedManual ? "Saving…" : "Import"}
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </Card>
+ </>
+ )}
+
+ {isCompatible && providerNode && (
+ <Card>
+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div>
+ <h2 className="text-lg font-semibold">
+ {isCcCompatible
+ ? t("ccCompatibleDetailsTitle")
+ : isAnthropicCompatible
+ ? t("anthropicCompatibleDetails")
+ : t("openaiCompatibleDetails")}
+ </h2>
+ <p className="text-sm text-text-muted">
+ {getApiLabel()} · {(providerNode.baseUrl || "").replace(/\/$/, "")}/{getApiPath()}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button size="sm" icon="add" onClick={() => gateConnectionFlow(openApiKeyAddFlow)}>
+ {t("add")}
+ </Button>
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="edit"
+ onClick={() => setShowEditNodeModal(true)}
+ >
+ {t("edit")}
+ </Button>
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="delete"
+ onClick={async () => {
+ if (
+ !confirm(
+ t("deleteCompatibleNodeConfirm", {
+ type: isCcCompatible
+ ? t("ccCompatibleLabel")
+ : isAnthropicCompatible
+ ? t("anthropic")
+ : t("openai"),
+ })
+ )
+ )
+ return;
+ try {
+ const res = await fetch(`/api/provider-nodes/${providerId}`, {
+ method: "DELETE",
+ });
+ if (res.ok) {
+ router.push("/dashboard/providers");
+ }
+ } catch (error) {
+ console.error("Error deleting provider node:", error);
+ }
+ }}
+ >
+ {t("delete")}
+ </Button>
+ </div>
+ </div>
+ {isCcCompatible && (
+ <div className="mb-4 rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
+ warning
+ </span>
+ <p>{t("ccCompatibleValidationHint")}</p>
+ </div>
+ </div>
+ )}
+ </Card>
+ )}
+
+ {/* Connections */}
+ {!isUpstreamProxyProvider && isFreeNoAuth && providerId === "mimocode" && (
+ <NoAuthAccountCard
+ providerId={providerId}
+ providerName="MiMoCode"
+ generateAccountId={() => crypto.randomUUID().replace(/-/g, "")}
+ />
+ )}
+ {!isUpstreamProxyProvider && isFreeNoAuth && providerId === "opencode" && (
+ <NoAuthAccountCard
+ providerId={providerId}
+ providerName="OpenCode"
+ generateAccountId={() => crypto.randomUUID().replace(/-/g, "")}
+ />
+ )}
+ {!isUpstreamProxyProvider &&
+ isFreeNoAuth &&
+ providerId !== "mimocode" &&
+ providerId !== "opencode" && <NoAuthProviderCard />}
+ {!isUpstreamProxyProvider && !isFreeNoAuth && (
+ <Card>
+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <h2 className="text-lg font-semibold">{t("connections")}</h2>
+ {providerId === "claude" && (
+ <div
+ className="inline-flex items-center gap-2 rounded-lg border border-orange-500/20 bg-orange-500/5 px-2 py-1 text-xs font-medium text-text-muted"
+ title={providerText(
+ t,
+ "preferClaudeCodeForUnprefixedClaudeModelsTooltip",
+ "Route bare claude-* model IDs from Claude Code clients through the Claude Code account instead of asking for a provider prefix."
+ )}
+ >
+ <span className="material-symbols-outlined text-[14px] text-orange-500">
+ alt_route
+ </span>
+ <span>
+ {providerText(
+ t,
+ "preferClaudeCodeForUnprefixedClaudeModelsLabel",
+ "Claude Code default"
+ )}
+ </span>
+ <Toggle
+ size="sm"
+ checked={preferClaudeCodeForUnprefixedClaudeModels}
+ onChange={handleToggleClaudeRoutingPreference}
+ disabled={savingClaudeRoutingPreference || !claudeRoutingSettingsLoaded}
+ ariaLabel={providerText(
+ t,
+ "preferClaudeCodeForUnprefixedClaudeModelsAria",
+ "Prefer Claude Code for unprefixed Claude models"
+ )}
+ title={
+ preferClaudeCodeForUnprefixedClaudeModels
+ ? providerText(
+ t,
+ "preferClaudeCodeForUnprefixedClaudeModelsDisable",
+ "Disable Claude Code preference for bare claude-* model IDs"
+ )
+ : providerText(
+ t,
+ "preferClaudeCodeForUnprefixedClaudeModelsEnable",
+ "Enable Claude Code preference for bare claude-* model IDs"
+ )
+ }
+ />
+ <span className="text-[11px] text-text-muted/70">
+ {preferClaudeCodeForUnprefixedClaudeModels
+ ? providerText(t, "toggleOnShort", "On")
+ : providerText(t, "toggleOffShort", "Off")}
+ </span>
+ {claudeRoutingSettingsLoadError ? (
+ <button
+ type="button"
+ onClick={() => void loadClaudeRoutingSettings()}
+ className="rounded border border-orange-500/30 px-2 py-0.5 text-[11px] font-medium text-orange-600 hover:bg-orange-500/10 dark:text-orange-300"
+ title={claudeRoutingSettingsLoadError}
+ >
+ {providerText(t, "retry", "Retry")}
+ </button>
+ ) : null}
+ </div>
+ )}
+ {providerId === "codex" && (
+ <div
+ className="inline-flex items-center gap-2 rounded-lg border border-sky-500/20 bg-sky-500/5 px-2 py-1 text-xs font-medium text-text-muted"
+ title={providerText(
+ t,
+ "providerDetailServiceModeTooltip",
+ "Set a global Codex service mode, or leave accounts on their individual service-tier setting."
+ )}
+ >
+ <span>
+ {providerText(t, "providerDetailServiceModeLabel", "Global service mode:")}
+ </span>
+ <select
+ value={codexGlobalServiceMode}
+ onChange={(event) =>
+ handleChangeCodexGlobalServiceMode(
+ event.target.value as CodexGlobalServiceMode
+ )
+ }
+ disabled={savingCodexGlobalServiceMode || !codexSettingsLoaded}
+ aria-label="Global Codex service mode"
+ className="rounded-md border border-border bg-bg px-2 py-1 text-xs text-text-main outline-none transition-colors focus:border-primary disabled:opacity-60"
+ >
+ {codexGlobalServiceModeOptions.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ {codexSettingsLoadError ? (
+ <button
+ type="button"
+ onClick={() => void loadCodexSettings()}
+ className="rounded border border-sky-500/30 px-2 py-0.5 text-[11px] font-medium text-sky-600 hover:bg-sky-500/10 dark:text-sky-300"
+ title={codexSettingsLoadError}
+ >
+ {providerText(t, "retry", "Retry")}
+ </button>
+ ) : null}
+ </div>
+ )}
+ {/* Provider-level proxy indicator/button */}
+ <button
+ onClick={() =>
+ setProxyTarget({
+ level: "provider",
+ id: providerId,
+ label: providerInfo?.name || providerId,
+ })
+ }
+ className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${
+ proxyConfig?.providers?.[providerId]
+ ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={
+ proxyConfig?.providers?.[providerId]
+ ? t("providerProxyTitleConfigured", {
+ host: proxyConfig.providers[providerId].host || t("configured"),
+ })
+ : t("providerProxyConfigureHint")
+ }
+ >
+ <span className="material-symbols-outlined text-[14px]">vpn_lock</span>
+ {proxyConfig?.providers?.[providerId]
+ ? proxyConfig.providers[providerId].host || t("providerProxy")
+ : t("providerProxy")}
+ </button>
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
+ {connections.length > 0 && (
+ <button
+ onClick={() => handleDistributeProxies()}
+ disabled={distributingProxies || batchTesting || !!retestingId}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
+ distributingProxies
+ ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
+ : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
+ }`}
+ title={t("distributeProxies")}
+ aria-label={t("distributeProxies")}
+ >
+ <span className="material-symbols-outlined text-[14px]">
+ {distributingProxies ? "sync" : "swap_horiz"}
+ </span>
+ {distributingProxies ? t("distributing") : t("distributeProxies")}
+ </button>
+ )}
+ {connections.length > 1 && (
+ <button
+ onClick={handleBatchTestAll}
+ disabled={batchTesting || batchRetesting || !!retestingId}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
+ batchTesting
+ ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
+ : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
+ }`}
+ title={t("testAll")}
+ aria-label={t("testAll")}
+ >
+ <span className="material-symbols-outlined text-[14px]">
+ {batchTesting ? "sync" : "play_arrow"}
+ </span>
+ {batchTesting ? t("testing") : t("testAll")}
+ </button>
+ )}
+ {!isCompatible ? (
+ <>
+ {isCommandCode ? (
+ <>
+ <Button
+ size="sm"
+ icon="open_in_new"
+ loading={
+ commandCodeAuthState.phase === "starting" ||
+ commandCodeAuthState.phase === "polling" ||
+ commandCodeAuthState.phase === "applying"
+ }
+ onClick={() => gateConnectionFlow(handleOpenCommandCodeConnect)}
+ >
+ Connect
+ </Button>
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="add"
+ onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
+ >
+ Manual API key
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button
+ size="sm"
+ icon="add"
+ onClick={() => gateConnectionFlow(openPrimaryAddFlow)}
+ >
+ {providerSupportsPat ? "Add PAT" : t("add")}
+ </Button>
+ {providerId === "qoder" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => gateConnectionFlow(() => setShowOAuthModal(true))}
+ >
+ Experimental OAuth
+ </Button>
+ )}
+ {providerId === "codex" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="menu_book"
+ onClick={() => setCodexCliGuideOpen(true)}
+ >
+ Codex CLI Guide
+ </Button>
+ )}
+ {providerId === "codex" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="share"
+ onClick={() => gateConnectionFlow(openExternalLinkFlow)}
+ >
+ Adicionar Externo
+ </Button>
+ )}
+ {providerId === "codex" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportCodexModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importCodexAuth")
+ ? t("importCodexAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ {providerId === "claude" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportClaudeModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importClaudeAuth")
+ ? t("importClaudeAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ {providerId === "gemini-cli" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportGeminiModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importGeminiAuth")
+ ? t("importGeminiAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ </>
+ )}
+ </>
+ ) : (
+ connections.length === 0 && (
+ <Button
+ size="sm"
+ icon="add"
+ onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
+ >
+ {t("add")}
+ </Button>
+ )
+ )}
+ </div>
+ </div>
+
+ {connections.length === 0 ? (
+ <div className="text-center py-12">
+ <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
+ <span className="material-symbols-outlined text-[32px]">
+ {isOAuth ? "lock" : "key"}
+ </span>
+ </div>
+ <p className="text-text-main font-medium mb-1">{t("noConnectionsYet")}</p>
+ <p className="text-sm text-text-muted mb-4">{t("addFirstConnectionHint")}</p>
+ {!isCompatible && (
+ <div className="flex items-center justify-center gap-2">
+ {isCommandCode ? (
+ <>
+ <Button
+ icon="open_in_new"
+ loading={
+ commandCodeAuthState.phase === "starting" ||
+ commandCodeAuthState.phase === "polling" ||
+ commandCodeAuthState.phase === "applying"
+ }
+ onClick={() => gateConnectionFlow(handleOpenCommandCodeConnect)}
+ >
+ Connect
+ </Button>
+ <Button
+ variant="secondary"
+ icon="add"
+ onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
+ >
+ Manual API key
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button icon="add" onClick={() => gateConnectionFlow(openPrimaryAddFlow)}>
+ {providerSupportsPat ? "Add PAT" : t("addConnection")}
+ </Button>
+ {providerId === "qoder" && (
+ <Button
+ variant="secondary"
+ onClick={() => gateConnectionFlow(() => setShowOAuthModal(true))}
+ >
+ Experimental OAuth
+ </Button>
+ )}
+ {providerId === "codex" && (
+ <Button
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportCodexModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importCodexAuth")
+ ? t("importCodexAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ {providerId === "claude" && (
+ <Button
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportClaudeModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importClaudeAuth")
+ ? t("importClaudeAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ {providerId === "gemini-cli" && (
+ <Button
+ variant="secondary"
+ icon="upload_file"
+ onClick={() => gateConnectionFlow(() => setImportGeminiModalOpen(true))}
+ >
+ {typeof t.has === "function" && t.has("importGeminiAuth")
+ ? t("importGeminiAuth")
+ : "Import auth"}
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ ) : (
+ (() => {
+ const sorted = [...connections].sort((a, b) => (a.priority || 0) - (b.priority || 0));
+ const hasAnyTag = sorted.some(
+ (c) => c.providerSpecificData?.tag as string | undefined
+ );
+ const allSelected = selectedIds.size === connections.length && connections.length > 0;
+ const someSelected = selectedIds.size > 0 && selectedIds.size < connections.length;
+ const bulkBusy =
+ batchUpdating !== null || batchRetesting || batchDeleting || batchTesting;
+ const bulkActions = selectedIds.size > 0 && (
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <Button
+ variant="secondary"
+ size="sm"
+ icon="toggle_on"
+ loading={batchUpdating === "activate"}
+ disabled={bulkBusy && batchUpdating !== "activate"}
+ onClick={() => handleBatchSetActive(true)}
+ >
+ {t("batchActivateSelected")}
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ icon="toggle_off"
+ loading={batchUpdating === "deactivate"}
+ disabled={bulkBusy && batchUpdating !== "deactivate"}
+ onClick={() => handleBatchSetActive(false)}
+ >
+ {t("batchDeactivateSelected")}
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ icon="play_arrow"
+ loading={batchRetesting}
+ disabled={(bulkBusy && !batchRetesting) || !!retestingId}
+ onClick={handleBatchRetest}
+ >
+ {t("batchRetestSelected")}
+ </Button>
+ <Button
+ variant="danger"
+ size="sm"
+ icon="delete"
+ loading={batchDeleting}
+ disabled={bulkBusy && !batchDeleting}
+ onClick={handleBatchDeleteOpenModal}
+ >
+ {t("batchDeleteSelected", { count: selectedIds.size })}
+ </Button>
+ </div>
+ );
+
+ const isHealthy = (c: ConnectionRowConnection): boolean => {
+ const s = c.testStatus;
+ return c.isActive !== false && (!s || s === "active" || s === "success");
+ };
+ const STATUS_FILTER_OPTIONS = [
+ { value: "all", label: t("filterAll", "All") },
+ { value: "active", label: t("filterActive", "Active") },
+ { value: "error", label: t("filterError", "Error") },
+ { value: "banned", label: t("filterBanned", "Banned") },
+ {
+ value: "credits_exhausted",
+ label: t("filterCreditsExhausted", "Credits Exhausted"),
+ },
+ ];
+ const filtered =
+ healthFilter === "all"
+ ? sorted
+ : sorted.filter((c) => {
+ if (healthFilter === "active") return isHealthy(c);
+ if (healthFilter === "error")
+ return (
+ !isHealthy(c) &&
+ c.testStatus !== "banned" &&
+ c.testStatus !== "credits_exhausted"
+ );
+ return c.testStatus === healthFilter;
+ });
+
+ const totalFilteredPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
+ const clampedPage = Math.min(page, totalFilteredPages - 1);
+ const pageStart = clampedPage * PAGE_SIZE;
+ const pageEnd = pageStart + PAGE_SIZE;
+
+ const filterPills = (
+ <div className="flex items-center gap-1.5 flex-wrap">
+ {STATUS_FILTER_OPTIONS.map((opt) => (
+ <button
+ key={opt.value}
+ onClick={() => {
+ setHealthFilter(opt.value);
+ setPage(0);
+ setSelectedIds(new Set());
+ }}
+ className={`px-2.5 py-1 text-xs rounded-full font-medium transition-colors ${
+ healthFilter === opt.value
+ ? "bg-primary text-white"
+ : "bg-muted/60 text-text-muted hover:bg-muted"
+ }`}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ );
+
+ const paginationBar =
+ totalFilteredPages > 1 ? (
+ <div className="flex items-center justify-between px-3 py-2 border-t border-border">
+ <span className="text-xs text-text-muted">
+ {pageStart + 1}–{Math.min(pageEnd, filtered.length)} / {filtered.length}
+ </span>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="chevron_left"
+ disabled={clampedPage === 0}
+ onClick={() => setPage((p) => Math.max(0, p - 1))}
+ />
+ <span className="text-xs text-text-muted min-w-[4rem] text-center">
+ {clampedPage + 1} / {totalFilteredPages}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="chevron_right"
+ disabled={clampedPage >= totalFilteredPages - 1}
+ onClick={() => setPage((p) => Math.min(totalFilteredPages - 1, p + 1))}
+ />
+ </div>
+ </div>
+ ) : null;
+
+ if (!hasAnyTag) {
+ const pageConnections = filtered.slice(pageStart, pageEnd);
+ const allSelected =
+ pageConnections.length > 0 && pageConnections.every((c) => selectedIds.has(c.id));
+ const someSelected = pageConnections.some((c) => selectedIds.has(c.id));
+ return (
+ <>
+ <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
+ <div className="flex items-center gap-2 flex-wrap">
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ type="checkbox"
+ checked={allSelected}
+ ref={(el) => {
+ if (el) el.indeterminate = someSelected;
+ }}
+ onChange={() => {
+ if (allSelected) {
+ const toRemove = new Set(pageConnections.map((c) => c.id));
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ for (const id of toRemove) next.delete(id);
+ return next;
+ });
+ } else {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ for (const c of pageConnections) next.add(c.id);
+ return next;
+ });
+ }
+ }}
+ className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
+ />
+ <span className="text-sm font-medium text-text-muted">
+ {selectedIds.size > 0
+ ? providerCountText(
+ t,
+ "selectedCount",
+ selectedIds.size,
+ "{count} selected",
+ "{count} selected"
+ )
+ : providerCountText(
+ t,
+ "accountsCount",
+ filtered.length,
+ "{count} account",
+ "{count} accounts"
+ )}
+ </span>
+ </label>
+ {filterPills}
+ </div>
+
+ {bulkActions}
+ </div>
+ <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03] border border-t-0 border-border rounded-b-lg overflow-hidden">
+ {pageConnections.length === 0 ? (
+ <div className="px-3 py-6 text-center text-sm text-text-muted">
+ {t("noFilteredConnections", "No connections match the current filter.")}
+ </div>
+ ) : (
+ pageConnections.map((conn, index) => (
+ <ConnectionRow
+ key={conn.id}
+ connection={conn}
+ isOAuth={conn.authType === "oauth"}
+ isClaude={providerId === "claude"}
+ codexGlobalServiceMode={codexGlobalServiceMode}
+ isFirst={index === 0}
+ isLast={index === pageConnections.length - 1}
+ isSelected={selectedIds.has(conn.id)}
+ onToggleSelect={() => handleToggleSelectOne(conn.id)}
+ onMoveUp={() => handleSwapPriority(conn, sorted[index - 1])}
+ onMoveDown={() => handleSwapPriority(conn, sorted[index + 1])}
+ onToggleActive={(isActive) =>
+ handleUpdateConnectionStatus(conn.id, isActive)
+ }
+ onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
+ onToggleClaudeExtraUsage={(enabled) =>
+ handleToggleClaudeExtraUsage(conn.id, enabled)
+ }
+ isCodex={providerId === "codex"}
+ isGeminiCli={providerId === "gemini-cli"}
+ isCcCompatible={isCcCompatible}
+ cliproxyapiEnabled={cpaProviderEnabled}
+ onToggleCliproxyapiMode={(enabled) =>
+ handleToggleCliproxyapiMode(conn.id, enabled)
+ }
+ onToggleCodex5h={(enabled) =>
+ handleToggleCodexLimit(conn.id, "use5h", enabled)
+ }
+ onToggleCodexWeekly={(enabled) =>
+ handleToggleCodexLimit(conn.id, "useWeekly", enabled)
+ }
+ onRetest={() => handleRetestConnection(conn.id)}
+ isRetesting={retestingId === conn.id}
+ onEdit={() => {
+ setSelectedConnection(conn);
+ setShowEditModal(true);
+ }}
+ onDelete={() => handleDelete(conn.id)}
+ onReauth={
+ conn.authType === "oauth"
+ ? () => gateConnectionFlow(() => setShowOAuthModal(true, conn))
+ : undefined
+ }
+ onRefreshToken={
+ conn.authType === "oauth"
+ ? () => handleRefreshToken(conn.id)
+ : undefined
+ }
+ isRefreshing={refreshingId === conn.id}
+ onApplyCodexAuthLocal={
+ providerId === "codex"
+ ? () => setApplyCodexModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
+ onExportCodexAuthFile={
+ providerId === "codex"
+ ? () => handleExportCodexAuthFile(conn.id)
+ : undefined
+ }
+ isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
+ onApplyClaudeAuthLocal={
+ providerId === "claude"
+ ? () => setApplyClaudeModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
+ onExportClaudeAuthFile={
+ providerId === "claude"
+ ? () => handleExportClaudeAuthFile(conn.id)
+ : undefined
+ }
+ isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
+ onApplyGeminiAuthLocal={
+ providerId === "gemini-cli"
+ ? () => setApplyGeminiModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
+ onExportGeminiAuthFile={
+ providerId === "gemini-cli"
+ ? () => handleExportGeminiAuthFile(conn.id)
+ : undefined
+ }
+ isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
+ onProxy={() =>
+ setProxyTarget({
+ level: "key",
+ id: conn.id,
+ label: pickDisplayValue(
+ [conn.name, conn.email],
+ emailsVisible,
+ conn.id
+ ),
+ })
+ }
+ hasProxy={!!connProxyMap[conn.id]?.proxy}
+ proxySource={connProxyMap[conn.id]?.level || null}
+ proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
+ proxyEnabled={readBooleanToggle(conn.proxyEnabled, true)}
+ onToggleProxyEnabled={(enabled) =>
+ handleToggleProxyEnabled(conn.id, enabled)
+ }
+ perKeyProxyEnabled={readBooleanToggle(conn.perKeyProxyEnabled, false)}
+ onTogglePerKeyProxyEnabled={(enabled) =>
+ handleTogglePerKeyProxyEnabled(conn.id, enabled)
+ }
+ />
+ ))
+ )}
+ </div>
+ {paginationBar}
+ </>
+ );
+ }
+
+ // Build ordered tag groups: untagged first, then alphabetically
+ const groupMap = new Map<string, ConnectionRowConnection[]>();
+ for (const conn of filtered) {
+ const tag = (conn.providerSpecificData?.tag as string | undefined)?.trim() || "";
+ if (!groupMap.has(tag)) groupMap.set(tag, []);
+ groupMap.get(tag)!.push(conn);
+ }
+ const groupKeys = Array.from(groupMap.keys()).sort((a, b) => {
+ if (a === "") return -1;
+ if (b === "") return 1;
+ return compareTr(a, b);
+ });
+
+ return (
+ <>
+ {selectedIds.size > 0 || connections.length > 0 ? (
+ <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
+ <div className="flex items-center gap-2 flex-wrap">
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ type="checkbox"
+ checked={allSelected}
+ ref={(el) => {
+ if (el) el.indeterminate = someSelected;
+ }}
+ onChange={handleToggleSelectAll}
+ className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
+ />
+ <span className="text-sm font-medium text-text-muted">
+ {selectedIds.size > 0
+ ? providerCountText(
+ t,
+ "selectedCount",
+ selectedIds.size,
+ "{count} selected",
+ "{count} selected"
+ )
+ : providerCountText(
+ t,
+ "accountsCount",
+ filtered.length,
+ "{count} account",
+ "{count} accounts"
+ )}
+ </span>
+ </label>
+ {filterPills}
+ </div>
+
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {/* Distribute Proxies lives in the provider toolbar (top action bar);
+ removed the duplicate here that rendered simultaneously when nothing
+ was selected. Per-tag groups keep their own scoped button. */}
+ {bulkActions}
+ </div>
+ </div>
+ ) : null}
+ <div className="flex flex-col gap-0 border border-t-0 border-border rounded-b-lg overflow-hidden">
+ {groupKeys.map((tag, gi) => {
+ const groupConns = groupMap.get(tag)!;
+ return (
+ <div
+ key={tag || "__untagged__"}
+ className={
+ gi > 0
+ ? "border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1"
+ : ""
+ }
+ >
+ {tag && (
+ <div className="flex items-center gap-2 px-3 pt-2 pb-1">
+ <span className="material-symbols-outlined text-[13px] text-text-muted/50">
+ label
+ </span>
+ <span className="text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none">
+ {tag}
+ </span>
+ <div className="flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]" />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon="shield"
+ loading={distributingProxies}
+ onClick={() => handleDistributeProxies(tag)}
+ >
+ Distribute Proxies
+ </Button>
+ <span className="text-[10px] text-text-muted/40">
+ {groupConns.length}
+ </span>
+ </div>
+ )}
+ <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
+ {groupConns.map((conn, index) => (
+ <ConnectionRow
+ key={conn.id}
+ connection={conn}
+ isOAuth={conn.authType === "oauth"}
+ isClaude={providerId === "claude"}
+ codexGlobalServiceMode={codexGlobalServiceMode}
+ isFirst={gi === 0 && index === 0}
+ isLast={
+ gi === groupKeys.length - 1 && index === groupConns.length - 1
+ }
+ isSelected={selectedIds.has(conn.id)}
+ onToggleSelect={() => handleToggleSelectOne(conn.id)}
+ onMoveUp={() =>
+ handleSwapPriority(conn, sorted[sorted.indexOf(conn) - 1])
+ }
+ onMoveDown={() =>
+ handleSwapPriority(conn, sorted[sorted.indexOf(conn) + 1])
+ }
+ onToggleActive={(isActive) =>
+ handleUpdateConnectionStatus(conn.id, isActive)
+ }
+ onToggleRateLimit={(enabled) =>
+ handleToggleRateLimit(conn.id, enabled)
+ }
+ onToggleClaudeExtraUsage={(enabled) =>
+ handleToggleClaudeExtraUsage(conn.id, enabled)
+ }
+ isCodex={providerId === "codex"}
+ isGeminiCli={providerId === "gemini-cli"}
+ isCcCompatible={isCcCompatible}
+ cliproxyapiEnabled={cpaProviderEnabled}
+ onToggleCodex5h={(enabled) =>
+ handleToggleCodexLimit(conn.id, "use5h", enabled)
+ }
+ onToggleCodexWeekly={(enabled) =>
+ handleToggleCodexLimit(conn.id, "useWeekly", enabled)
+ }
+ onRetest={() => handleRetestConnection(conn.id)}
+ isRetesting={retestingId === conn.id}
+ onEdit={() => {
+ setSelectedConnection(conn);
+ setShowEditModal(true);
+ }}
+ onDelete={() => handleDelete(conn.id)}
+ onReauth={
+ conn.authType === "oauth"
+ ? () => gateConnectionFlow(() => setShowOAuthModal(true, conn))
+ : undefined
+ }
+ onRefreshToken={
+ conn.authType === "oauth"
+ ? () => handleRefreshToken(conn.id)
+ : undefined
+ }
+ isRefreshing={refreshingId === conn.id}
+ onApplyCodexAuthLocal={
+ providerId === "codex"
+ ? () => setApplyCodexModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
+ onExportCodexAuthFile={
+ providerId === "codex"
+ ? () => handleExportCodexAuthFile(conn.id)
+ : undefined
+ }
+ isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
+ onApplyClaudeAuthLocal={
+ providerId === "claude"
+ ? () => setApplyClaudeModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
+ onExportClaudeAuthFile={
+ providerId === "claude"
+ ? () => handleExportClaudeAuthFile(conn.id)
+ : undefined
+ }
+ isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
+ onApplyGeminiAuthLocal={
+ providerId === "gemini-cli"
+ ? () => setApplyGeminiModalConnectionId(conn.id)
+ : undefined
+ }
+ isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
+ onExportGeminiAuthFile={
+ providerId === "gemini-cli"
+ ? () => handleExportGeminiAuthFile(conn.id)
+ : undefined
+ }
+ isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
+ onProxy={() =>
+ setProxyTarget({
+ level: "key",
+ id: conn.id,
+ label: pickDisplayValue(
+ [conn.name, conn.email],
+ emailsVisible,
+ conn.id
+ ),
+ })
+ }
+ hasProxy={!!connProxyMap[conn.id]?.proxy}
+ proxySource={connProxyMap[conn.id]?.level || null}
+ proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
+ proxyEnabled={readBooleanToggle(conn.proxyEnabled, true)}
+ onToggleProxyEnabled={(enabled) =>
+ handleToggleProxyEnabled(conn.id, enabled)
+ }
+ perKeyProxyEnabled={readBooleanToggle(
+ conn.perKeyProxyEnabled,
+ false
+ )}
+ onTogglePerKeyProxyEnabled={(enabled) =>
+ handleTogglePerKeyProxyEnabled(conn.id, enabled)
+ }
+ />
+ ))}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </>
+ );
+ })()
+ )}
+ </Card>
+ )}
+
+ {isUpstreamProxyProvider && (
+ <Card>
+ <div className="flex flex-col gap-3">
+ <div>
+ <h2 className="text-lg font-semibold">
+ {providerText(
+ t,
+ "upstreamProxyManagedTitle",
+ "Managed via Upstream Proxy Settings"
+ )}
+ </h2>
+ <p className="text-sm text-text-muted mt-1">
+ {providerText(
+ t,
+ "upstreamProxyManagedDescription",
+ "CLIProxyAPI is configured as an upstream proxy layer, not as a direct provider connection. Manage the binary/runtime in CLI Tools and enable proxy routing on each provider via the provider proxy controls."
+ )}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Link
+ href="/dashboard/cli-code"
+ className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
+ >
+ <span className="material-symbols-outlined text-base">terminal</span>
+ {t("openCliTools")}
+ </Link>
+ <Link
+ href="/dashboard/settings"
+ className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
+ >
+ <span className="material-symbols-outlined text-base">settings</span>
+ {t("openSettings")}
+ </Link>
+ </div>
+ </div>
+ </Card>
+ )}
+
+ {/* Models — hidden for search providers (they don't have models) */}
+ {!isSearchProvider && !isUpstreamProxyProvider && (
+ <Card>
+ <h2 className="text-lg font-semibold mb-4">{t("availableModels")}</h2>
+ {renderModelsSection()}
+
+ {/* Custom Models — available for all providers */}
+ <CustomModelsSection
+ providerId={providerId}
+ providerAlias={providerDisplayAlias}
+ copied={copied}
+ onCopy={copy}
+ onModelsChanged={fetchProviderModelMeta}
+ />
+ </Card>
+ )}
+
+ {/* Search provider info */}
+ {isSearchProvider && (
+ <Card>
+ <h2 className="text-lg font-semibold mb-4">{t("searchProvider")}</h2>
+ <p className="text-sm text-text-muted">{t("searchProviderDesc")}</p>
+ {providerId === "perplexity-search" && (
+ <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20">
+ <span className="material-symbols-outlined text-sm text-blue-400">link</span>
+ <p className="text-xs text-blue-300">{t("perplexitySearchSharedKeyInfo")}</p>
+ </div>
+ )}
+ {providerId === "google-pse-search" && (
+ <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
+ <span className="material-symbols-outlined text-sm text-amber-300">tune</span>
+ <p className="text-xs text-amber-200">{t("googlePseInfo")}</p>
+ </div>
+ )}
+ {providerId === "searxng-search" && (
+ <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-emerald-500/10 border border-emerald-500/20">
+ <span className="material-symbols-outlined text-sm text-emerald-300">dns</span>
+ <p className="text-xs text-emerald-200">{t("searxngInfo")}</p>
+ </div>
+ )}
+ </Card>
+ )}
+
+ {/* Playground panel — rendered for providers that declare serviceKinds */}
+ <ProviderPlaygroundPanel providerId={providerId} />
+
+ {/* Modals */}
+ {showRiskNoticeModal && subscriptionRisk && (
+ <RiskNoticeModal
+ variant={providerInfo.riskNoticeVariant ?? "oauth"}
+ providerId={providerId}
+ providerName={providerInfo.name}
+ onConfirm={handleConfirmRiskNotice}
+ onCancel={handleCancelRiskNotice}
+ />
+ )}
+ {!isUpstreamProxyProvider &&
+ (providerId === "kiro" || providerId === "amazon-q" ? (
+ <KiroOAuthWrapper
+ isOpen={showOAuthModal}
+ reauthConnection={reauthConnection}
+ providerInfo={{ ...providerInfo, id: providerId }}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ) : providerId === "cursor" ? (
+ <CursorAuthModal
+ isOpen={showOAuthModal}
+ reauthConnection={reauthConnection}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ) : providerId === "trae" ? (
+ <TraeAuthModal
+ isOpen={showOAuthModal}
+ reauthConnection={reauthConnection}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ) : (
+ <OAuthModal
+ isOpen={showOAuthModal}
+ reauthConnection={reauthConnection}
+ provider={providerId}
+ providerInfo={providerInfo}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ))}
+ {providerId === "siliconflow" && (
+ <SiliconFlowEndpointModal
+ isOpen={showSiliconFlowEndpointModal}
+ onSelect={(baseUrl) => {
+ setSiliconFlowInitialBaseUrl(baseUrl);
+ setShowSiliconFlowEndpointModal(false);
+ setShowAddApiKeyModal(true);
+ }}
+ onClose={() => {
+ setShowSiliconFlowEndpointModal(false);
+ setSiliconFlowInitialBaseUrl(undefined);
+ }}
+ />
+ )}
+ {!isUpstreamProxyProvider && (
+ <AddApiKeyModal
+ isOpen={showAddApiKeyModal}
+ provider={providerId}
+ providerName={providerInfo.name}
+ initialBaseUrl={siliconFlowInitialBaseUrl}
+ isCompatible={isCompatible}
+ isAnthropic={isAnthropicProtocolCompatible}
+ isCcCompatible={isCcCompatible}
+ isCommandCode={isCommandCode}
+ commandCodeAuthState={commandCodeAuthState}
+ onStartCommandCodeAuth={handleStartCommandCodeAuth}
+ onSave={handleSaveApiKey}
+ onClose={handleCloseAddApiKeyModal}
+ />
+ )}
+ <ConfirmModal
+ isOpen={batchDeleteConfirmOpen}
+ onClose={() => setBatchDeleteConfirmOpen(false)}
+ onConfirm={handleBatchDeleteConfirm}
+ title={t("batchDeleteConfirmTitle", "Delete connections")}
+ message={t("batchDeleteConfirm", { count: selectedIds.size })}
+ confirmText={t("batchDeleteConfirmButton", "Delete")}
+ cancelText={t("cancel", "Cancel")}
+ loading={batchDeleting}
+ />
+ {providerId === "codex" && applyCodexModalConnectionId && (
+ <ApplyCodexAuthModal
+ key={applyCodexModalConnectionId}
+ connectionId={applyCodexModalConnectionId}
+ inProgress={!!applyingCodexAuthId}
+ onConfirm={handleApplyCodexAuthLocal}
+ onClose={() => setApplyCodexModalConnectionId(null)}
+ />
+ )}
+ {!isUpstreamProxyProvider && (
+ <EditConnectionModal
+ isOpen={showEditModal}
+ connection={selectedConnection}
+ onSave={handleUpdateConnection}
+ onClose={() => setShowEditModal(false)}
+ />
+ )}
+ {!isUpstreamProxyProvider && isCompatible && (
+ <EditCompatibleNodeModal
+ isOpen={showEditNodeModal}
+ node={providerNode}
+ onSave={handleUpdateNode}
+ onClose={() => setShowEditNodeModal(false)}
+ isAnthropic={isAnthropicProtocolCompatible}
+ isCcCompatible={isCcCompatible}
+ />
+ )}
+ {/* Codex CLI Guide Modal */}
+ <CodexCliGuideModal isOpen={codexCliGuideOpen} onClose={() => setCodexCliGuideOpen(false)} />
+ {/* Codex Import Auth Modal */}
+ {providerId === "codex" && importCodexModalOpen && (
+ <ImportCodexAuthModal
+ key="import-codex-modal"
+ onClose={() => setImportCodexModalOpen(false)}
+ onSuccess={() => {
+ setImportCodexModalOpen(false);
+ void fetchConnections();
+ }}
+ />
+ )}
+ {providerId === "codex" && externalLinkModalOpen && (
+ <Modal
+ isOpen={externalLinkModalOpen}
+ onClose={() => setExternalLinkModalOpen(false)}
+ title="Adicionar Externo — link do Codex"
+ >
+ <div className="space-y-4">
+ <p className="text-sm text-text-muted">
+ Compartilhe este link com quem vai autenticar a conta do Codex. A pessoa abre a
+ página, faz o login da OpenAI no próprio navegador e a conexão é cadastrada aqui. Uso
+ único, expira em 15 minutos.
+ </p>
+ {externalLinkLoading ? (
+ <p className="text-sm text-text-muted">Gerando link…</p>
+ ) : externalLinkError ? (
+ <p className="text-sm text-red-500">{externalLinkError}</p>
+ ) : externalLinkUrl ? (
+ <>
+ <div className="rounded-lg border border-border bg-bg-base p-3 break-all text-sm text-text-main">
+ {externalLinkUrl}
+ </div>
+ <div className="flex gap-2">
+ <Button
+ className="flex-1"
+ icon="open_in_new"
+ onClick={() => window.open(externalLinkUrl, "_blank", "noopener")}
+ >
+ Abrir
+ </Button>
+ <Button
+ variant="secondary"
+ icon="content_copy"
+ onClick={() => externalLinkCopy(externalLinkUrl, "extlink")}
+ >
+ {externalLinkCopied === "extlink" ? "Copiado" : "Copiar"}
+ </Button>
+ </div>
+ <p className="flex items-center gap-2 text-xs text-text-muted">
+ <span className="material-symbols-outlined animate-spin text-[16px]">sync</span>
+ Aguardando a autenticação no navegador da pessoa… esta janela atualiza sozinha.
+ </p>
+ </>
+ ) : null}
+ </div>
+ </Modal>
+ )}
+ {/* Claude Apply Auth Modal */}
+ {providerId === "claude" && applyClaudeModalConnectionId && (
+ <ApplyClaudeAuthModal
+ key={applyClaudeModalConnectionId}
+ connectionId={applyClaudeModalConnectionId}
+ inProgress={!!applyingClaudeAuthId}
+ onConfirm={handleApplyClaudeAuthLocal}
+ onClose={() => setApplyClaudeModalConnectionId(null)}
+ />
+ )}
+ {/* Claude Import Auth Modal */}
+ {providerId === "claude" && importClaudeModalOpen && (
+ <ImportClaudeAuthModal
+ key="import-claude-modal"
+ onClose={() => setImportClaudeModalOpen(false)}
+ onSuccess={() => {
+ setImportClaudeModalOpen(false);
+ void fetchConnections();
+ }}
+ />
+ )}
+ {/* Gemini Apply Auth Modal */}
+ {providerId === "gemini-cli" && applyGeminiModalConnectionId && (
+ <ApplyGeminiAuthModal
+ key={applyGeminiModalConnectionId}
+ connectionId={applyGeminiModalConnectionId}
+ inProgress={!!applyingGeminiAuthId}
+ onConfirm={handleApplyGeminiAuthLocal}
+ onClose={() => setApplyGeminiModalConnectionId(null)}
+ />
+ )}
+ {/* Gemini Import Auth Modal */}
+ {providerId === "gemini-cli" && importGeminiModalOpen && (
+ <ImportGeminiAuthModal
+ key="import-gemini-modal"
+ onClose={() => setImportGeminiModalOpen(false)}
+ onSuccess={() => {
+ setImportGeminiModalOpen(false);
+ void fetchConnections();
+ }}
+ />
+ )}
+ {/* Batch Test Results Modal */}
+ {batchTestResults && (
+ <div
+ className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh]"
+ onClick={() => setBatchTestResults(null)}
+ >
+ <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
+ <div
+ className="relative bg-bg-primary border border-border rounded-xl w-full max-w-[600px] max-h-[80vh] overflow-y-auto shadow-2xl"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-bg-primary/95 backdrop-blur-sm rounded-t-xl">
+ <h3 className="font-semibold">{t("testResults")}</h3>
+ <button
+ onClick={() => setBatchTestResults(null)}
+ className="p-1 rounded-lg hover:bg-bg-subtle text-text-muted hover:text-text-primary transition-colors"
+ aria-label={t("close")}
+ >
+ <span className="material-symbols-outlined text-lg">close</span>
+ </button>
+ </div>
+ <div className="p-5">
+ {batchTestResults.error &&
+ (!batchTestResults.results || batchTestResults.results.length === 0) ? (
+ <div className="text-center py-6">
+ <span className="material-symbols-outlined text-red-500 text-[32px] mb-2 block">
+ error
+ </span>
+ <p className="text-sm text-red-400">{String(batchTestResults.error)}</p>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3">
+ {batchTestResults.summary && (
+ <div className="flex items-center gap-3 text-xs mb-1">
+ <span className="text-text-muted">{providerInfo?.name || providerId}</span>
+ <span className="px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium">
+ {t("passedCount", { count: batchTestResults.summary.passed })}
+ </span>
+ {batchTestResults.summary.failed > 0 && (
+ <span className="px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium">
+ {t("failedCount", { count: batchTestResults.summary.failed })}
+ </span>
+ )}
+ <span className="text-text-muted ml-auto">
+ {t("testedCount", { count: batchTestResults.summary.total })}
+ </span>
+ </div>
+ )}
+ {(batchTestResults.results || []).map((r: any, i: number) => (
+ <div
+ key={r.connectionId || i}
+ className="flex items-center gap-2 text-xs px-3 py-2 rounded-lg bg-black/[0.03] dark:bg-white/[0.03]"
+ >
+ <span
+ className={`material-symbols-outlined text-[16px] ${
+ r.valid ? "text-emerald-500" : "text-red-500"
+ }`}
+ >
+ {r.valid ? "check_circle" : "error"}
+ </span>
+ <div className="flex-1 min-w-0">
+ <span className="font-medium">
+ {pickDisplayValue([r.connectionName], emailsVisible, r.connectionName)}
+ </span>
+ </div>
+ {r.latencyMs !== undefined && (
+ <span className="text-text-muted font-mono tabular-nums">
+ {t("millisecondsAbbr", { value: r.latencyMs })}
+ </span>
+ )}
+ <span
+ className={`text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${
+ r.valid
+ ? "bg-emerald-500/15 text-emerald-400"
+ : "bg-red-500/15 text-red-400"
+ }`}
+ >
+ {r.valid ? t("okShort") : r.diagnosis?.type || t("errorShort")}
+ </span>
+ </div>
+ ))}
+ {(!batchTestResults.results || batchTestResults.results.length === 0) && (
+ <div className="text-center py-4 text-text-muted text-sm">
+ {t("noActiveConnectionsInGroup")}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ {/* Proxy Config Modal */}
+ {proxyTarget && (
+ <ProxyConfigModal
+ isOpen={!!proxyTarget}
+ onClose={() => setProxyTarget(null)}
+ level={proxyTarget.level}
+ levelId={proxyTarget.id}
+ levelLabel={proxyTarget.label}
+ onSaved={() => {
+ void fetchProxyConfig();
+ void loadConnProxies(connections);
+ }}
+ />
+ )}
+ {/* Import Progress Modal */}
+ <Modal
+ isOpen={showImportModal}
+ onClose={() => {
+ if (importProgress.phase === "done" || importProgress.phase === "error") {
+ setShowImportModal(false);
+ }
+ }}
+ title={t("importingModelsTitle")}
+ size="md"
+ closeOnOverlay={false}
+ showCloseButton={importProgress.phase === "done" || importProgress.phase === "error"}
+ >
+ <div className="flex flex-col gap-4">
+ {/* Status text */}
+ <div className="flex items-center gap-3">
+ {importProgress.phase === "fetching" && (
+ <span className="material-symbols-outlined text-primary animate-spin">
+ progress_activity
+ </span>
+ )}
+ {importProgress.phase === "importing" && (
+ <span className="material-symbols-outlined text-primary animate-spin">
+ progress_activity
+ </span>
+ )}
+ {importProgress.phase === "done" && (
+ <span className="material-symbols-outlined text-green-500">check_circle</span>
+ )}
+ {importProgress.phase === "error" && (
+ <span className="material-symbols-outlined text-red-500">error</span>
+ )}
+ <span className="text-sm font-medium text-text-main">{importProgress.status}</span>
+ </div>
+
+ {/* Progress bar */}
+ {(importProgress.phase === "importing" || importProgress.phase === "done") &&
+ importProgress.total > 0 && (
+ <div className="w-full">
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-xs text-text-muted">
+ {importProgress.current} / {importProgress.total}
+ </span>
+ <span className="text-xs text-text-muted">
+ {Math.round((importProgress.current / importProgress.total) * 100)}%
+ </span>
+ </div>
+ <div className="w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden">
+ <div
+ className="h-full rounded-full transition-all duration-300 ease-out"
+ style={{
+ width: `${(importProgress.current / importProgress.total) * 100}%`,
+ background:
+ importProgress.phase === "done"
+ ? "linear-gradient(90deg, #22c55e, #16a34a)"
+ : "linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))",
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Fetching indeterminate bar */}
+ {importProgress.phase === "fetching" && (
+ <div className="w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden">
+ <div
+ className="h-full rounded-full animate-pulse"
+ style={{
+ width: "60%",
+ background:
+ "linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))",
+ }}
+ />
+ </div>
+ )}
+
+ {/* Error message */}
+ {importProgress.phase === "error" && importProgress.error && (
+ <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
+ <p className="text-sm text-red-400">{importProgress.error}</p>
+ </div>
+ )}
+
+ {/* Log list */}
+ {importProgress.logs.length > 0 && (
+ <div className="max-h-48 overflow-y-auto rounded-lg bg-black/5 dark:bg-white/5 p-3 border border-black/5 dark:border-white/5">
+ <div className="flex flex-col gap-1">
+ {importProgress.logs.map((log, i) => (
+ <p
+ key={i}
+ className={`text-xs font-mono ${
+ typeof log === "string" && log.startsWith("✓")
+ ? "text-green-500 font-semibold"
+ : "text-text-muted"
+ }`}
+ >
+ {log}
+ </p>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Close button */}
+ {importProgress.phase === "done" && (
+ <div className="flex justify-center">
+ <button
+ onClick={() => setShowImportModal(false)}
+ className="px-4 py-2 text-sm font-medium rounded-lg bg-primary text-white hover:opacity-90 transition-opacity"
+ >
+ {t("close")}
+ </button>
+ </div>
+ )}
+ </div>
+ </Modal>
+
+ {/* Adapta Web — Tutorial Modal */}
+ {providerId === "adapta-web" && (
+ <Modal
+ isOpen={showTutorialModal}
+ onClose={() => setShowTutorialModal(false)}
+ title="Como conectar o Adapta Web"
+ size="md"
+ >
+ <div className="flex flex-col gap-5 text-sm">
+ <p className="text-text-muted">
+ O Adapta usa autenticação via Clerk. O token{" "}
+ <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> é um JWT
+ de longa duração que permite renovar sessões automaticamente.
+ </p>
+
+ <ol className="flex flex-col gap-4 list-none">
+ <li className="flex gap-3">
+ <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
+ 1
+ </span>
+ <div>
+ <p className="font-medium">Acesse o chat do Adapta</p>
+ <p className="text-text-muted mt-0.5">
+ Abra{" "}
+ <a
+ href="https://agent.adapta.one/agentic-chat"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline text-primary"
+ >
+ agent.adapta.one/agentic-chat
+ </a>{" "}
+ e faça login com sua conta Gold ou Business.
+ </p>
+ </div>
+ </li>
+
+ <li className="flex gap-3">
+ <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
+ 2
+ </span>
+ <div>
+ <p className="font-medium">Abra o DevTools</p>
+ <p className="text-text-muted mt-0.5">
+ Pressione{" "}
+ <kbd className="bg-surface-2 px-1.5 py-0.5 rounded text-xs font-mono">F12</kbd>{" "}
+ ou{" "}
+ <kbd className="bg-surface-2 px-1.5 py-0.5 rounded text-xs font-mono">
+ Cmd+Option+I
+ </kbd>{" "}
+ para abrir as Ferramentas do Desenvolvedor.
+ </p>
+ </div>
+ </li>
+
+ <li className="flex gap-3">
+ <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
+ 3
+ </span>
+ <div>
+ <p className="font-medium">Vá em Application → Cookies</p>
+ <p className="text-text-muted mt-0.5">
+ Na aba <strong>Application</strong> (Chrome/Edge) ou <strong>Storage</strong>{" "}
+ (Firefox), expanda <strong>Cookies</strong> e clique em{" "}
+ <code className="bg-surface-2 px-1 rounded font-mono text-xs">
+ .clerk.agent.adapta.one
+ </code>
+ .
+ </p>
+ </div>
+ </li>
+
+ <li className="flex gap-3">
+ <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
+ 4
+ </span>
+ <div>
+ <p className="font-medium">
+ Copie o valor do cookie{" "}
+ <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code>
+ </p>
+ <p className="text-text-muted mt-0.5">
+ Localize o cookie chamado{" "}
+ <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> na
+ lista. Clique nele e copie o conteúdo da coluna <strong>Value</strong> — começa
+ com <code className="bg-surface-2 px-1 rounded font-mono text-xs">eyJ…</code>.
+ </p>
+ </div>
+ </li>
+
+ <li className="flex gap-3">
+ <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
+ 5
+ </span>
+ <div>
+ <p className="font-medium">Cole aqui e salve</p>
+ <p className="text-text-muted mt-0.5">
+ Clique em <strong>Add Connection</strong>, cole o valor do{" "}
+ <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> no
+ campo de API Key e salve. O OmniRoute renovará a sessão automaticamente.
+ </p>
+ </div>
+ </li>
+ </ol>
+
+ <div
+ className="rounded-lg p-3 text-xs text-text-muted"
+ style={{ backgroundColor: "rgba(110,58,211,0.08)", borderLeft: "3px solid #6E3AD3" }}
+ >
+ <strong>Dica:</strong> O cookie <code className="font-mono">__client</code> tem
+ validade longa (meses). Só será necessário renová-lo se você sair da conta ou o Adapta
+ invalidar a sessão.
+ </div>
+ </div>
+ </Modal>
+ )}
+ </div>
+ );
+}
+
+// ModelRow, ModelVisibilityToolbar, PassthroughModelsSection, PassthroughModelRow,
+// CustomModelsSection, CompatibleModelsSection → components/ (Phase 1e — Issue #3501)
+
+// Phase 1d: CooldownTimer, inferErrorType, getStatusPresentation, ConnectionRow → components/ConnectionRow.tsx
+// Phase 1d: ModelCompatPopover, recordToHeaderRows → components/ModelCompatPopover.tsx
+// Phase 1d: SiliconFlowEndpointModal → components/SiliconFlowEndpointModal.tsx
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/__tests__/ProviderDetailPageClient.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/ProviderDetailPageClient.test.tsx
new file mode 100644
index 0000000000..2a8f59ac03
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/ProviderDetailPageClient.test.tsx
@@ -0,0 +1,136 @@
+// @vitest-environment jsdom
+//
+// Phase 0 smoke test for Issue #3501 (strangler-fig decomposition of the
+// 12.8K-LOC providers/[id] god-component). Before any code is moved out of the
+// component, this proves the freshly-extracted ProviderDetailPageClient still
+// mounts and renders its loading shell without throwing — the safety net that
+// every later extraction phase (1..6) is diffed against. Hard Rule #8: the page
+// had ZERO tests before this; this is the first.
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import ProviderDetailPageClient from "../ProviderDetailPageClient";
+
+function getRequestPath(input: RequestInfo | URL) {
+ return typeof input === "string" ? input : input instanceof URL ? input.pathname : input.url;
+}
+
+function emptyJsonResponse() {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({}),
+ text: async () => "",
+ headers: { get: () => null },
+ } as unknown as Response;
+}
+
+const cleanupCallbacks: Array<() => void> = [];
+
+function installLocalStorageStub() {
+ const store = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ clear: () => store.clear(),
+ });
+}
+
+// next/navigation — the client reads the route id via useParams() and never
+// receives props from the thin page.tsx wrapper, so this mock is what supplies it.
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "openai" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn(), refresh: vi.fn() }),
+ usePathname: () => "/dashboard/providers/openai",
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
+ <a href={String(href)} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+vi.mock("next-intl", () => ({
+ // Echo the key back so assertions don't depend on a full message catalog.
+ useTranslations: (namespace?: string) => (key: string) => (namespace ? `${namespace}.${key}` : key),
+}));
+
+function renderProviderPage() {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ let mounted = true;
+
+ act(() => {
+ root.render(<ProviderDetailPageClient />);
+ });
+
+ const unmount = () => {
+ if (!mounted) return;
+ act(() => root.unmount());
+ container.remove();
+ mounted = false;
+ };
+ cleanupCallbacks.push(unmount);
+ return { container, unmount };
+}
+
+describe("ProviderDetailPageClient (Phase 0 smoke)", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockImplementation(() => Promise.resolve(emptyJsonResponse()));
+ (
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal("fetch", fetchMock);
+ vi.stubGlobal(
+ "matchMedia",
+ vi.fn(() => ({
+ matches: false,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ }))
+ );
+ installLocalStorageStub();
+ });
+
+ afterEach(() => {
+ while (cleanupCallbacks.length > 0) cleanupCallbacks.pop()?.();
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it("mounts and renders the loading shell without throwing", () => {
+ const { container } = renderProviderPage();
+ // Mount succeeded (no throw) and produced DOM — the loading skeleton renders
+ // synchronously while the on-mount fetches are still pending.
+ expect(container.childNodes.length).toBeGreaterThan(0);
+ expect(container.querySelector("*")).not.toBeNull();
+ });
+
+ it("kicks off provider data loading on mount", async () => {
+ renderProviderPage();
+ // Let the mount effects schedule their fetches.
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(fetchMock).toHaveBeenCalled();
+ const paths = fetchMock.mock.calls.map(([input]) => getRequestPath(input as RequestInfo | URL));
+ // The provider id from useParams() drives the connection/provider lookups.
+ expect(paths.some((p) => p.includes("openai") || p.includes("/api/"))).toBe(true);
+ });
+
+ it("unmounts cleanly during the initial load", () => {
+ const { unmount } = renderProviderPage();
+ expect(() => unmount()).not.toThrow();
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/__tests__/passthroughTestHelpers.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/passthroughTestHelpers.test.tsx
new file mode 100644
index 0000000000..3d1c188c49
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/passthroughTestHelpers.test.tsx
@@ -0,0 +1,79 @@
+// Unit tests for passthrough test-all helpers (Issue #3610).
+//
+// These helpers capture the three-bug fix:
+// 1. `autoHideFailed` must be threaded into the request body so the server
+// persists the hide (was missing → server never hid models).
+// 2. `shouldSwitchToVisibleFilter` must return true when ≥1 model was hidden
+// so the component switches to "visible" filter and the user sees the
+// models disappear (was missing → models stayed on-screen even after hide).
+//
+// Pure-function tests — no DOM, no component rendering.
+import { describe, expect, it } from "vitest";
+import {
+ buildPassthroughTestBody,
+ shouldSwitchToVisibleFilter,
+} from "../providerPageHelpers";
+
+// ---------------------------------------------------------------------------
+// buildPassthroughTestBody
+// ---------------------------------------------------------------------------
+describe("buildPassthroughTestBody", () => {
+ it("includes autoHideFailed=true when the flag is enabled", () => {
+ const body = buildPassthroughTestBody({
+ providerId: "opencode",
+ connectionId: "conn-1",
+ modelId: "gpt-4o",
+ autoHideFailed: true,
+ });
+
+ expect(body.autoHideFailed).toBe(true);
+ expect(body.modelIds).toEqual(["gpt-4o"]);
+ expect(body.providerId).toBe("opencode");
+ expect(body.connectionId).toBe("conn-1");
+ });
+
+ it("includes autoHideFailed=false when the flag is disabled", () => {
+ const body = buildPassthroughTestBody({
+ providerId: "opencode",
+ connectionId: "conn-1",
+ modelId: "gpt-4o",
+ autoHideFailed: false,
+ });
+
+ expect(body.autoHideFailed).toBe(false);
+ });
+
+ it("wraps modelId in a single-element array", () => {
+ const body = buildPassthroughTestBody({
+ providerId: "p",
+ connectionId: "c",
+ modelId: "some-model",
+ autoHideFailed: true,
+ });
+
+ expect(body.modelIds).toHaveLength(1);
+ expect(body.modelIds[0]).toBe("some-model");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// shouldSwitchToVisibleFilter
+// ---------------------------------------------------------------------------
+describe("shouldSwitchToVisibleFilter", () => {
+ it("returns true when autoHideFailed is enabled and at least one model was hidden", () => {
+ expect(shouldSwitchToVisibleFilter({ autoHideFailed: true, hiddenCount: 1 })).toBe(true);
+ expect(shouldSwitchToVisibleFilter({ autoHideFailed: true, hiddenCount: 5 })).toBe(true);
+ });
+
+ it("returns false when autoHideFailed is enabled but no model was hidden", () => {
+ expect(shouldSwitchToVisibleFilter({ autoHideFailed: true, hiddenCount: 0 })).toBe(false);
+ });
+
+ it("returns false when autoHideFailed is disabled even if models were hidden", () => {
+ expect(shouldSwitchToVisibleFilter({ autoHideFailed: false, hiddenCount: 3 })).toBe(false);
+ });
+
+ it("returns false when both flag and count are falsy", () => {
+ expect(shouldSwitchToVisibleFilter({ autoHideFailed: false, hiddenCount: 0 })).toBe(false);
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1e.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1e.test.tsx
new file mode 100644
index 0000000000..fb0562c8a8
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1e.test.tsx
@@ -0,0 +1,304 @@
+// @vitest-environment jsdom
+//
+// Phase 1e smoke tests for Issue #3501 (strangler-fig decomposition).
+// Validates:
+// 1. useModelCompatState hook computes correct values from raw arrays.
+// 2. ModelRow, PassthroughModelRow, ModelVisibilityToolbar render without throwing.
+// 3. PassthroughModelsSection, CustomModelsSection, CompatibleModelsSection render without throwing.
+// 4. No cycle: providerPageHelpers imports DO NOT import from ProviderDetailPageClient.
+//
+// We use shallow rendering (no Next.js server context needed) because these are
+// presentational components that receive all data via props.
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ buildCompatMap,
+ isModelHiddenFn,
+ effectiveNormalizeForProtocol,
+ effectivePreserveForProtocol,
+ anyNormalizeCompatBadge,
+ anyNoPreserveCompatBadge,
+ formatProviderModelsErrorResponse,
+} from "../providerPageHelpers";
+
+// ---------------------------------------------------------------------------
+// Global mocks required by the extracted components
+// ---------------------------------------------------------------------------
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "test-provider" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ usePathname: () => "/providers/test-provider",
+}));
+
+vi.mock("next-intl", () => ({
+ useTranslations: () => (key: string, values?: Record<string, unknown>) => {
+ if (values) {
+ return Object.entries(values).reduce(
+ (acc, [k, v]) => acc.replace(`{${k}}`, String(v)),
+ key
+ );
+ }
+ return key;
+ },
+}));
+
+vi.mock("@/store/notificationStore", () => ({
+ useNotificationStore: () => ({
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ }),
+}));
+
+vi.mock("@/shared/components", () => ({
+ Badge: ({ children }: any) => <span>{children}</span>,
+ Button: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
+}));
+
+// ---------------------------------------------------------------------------
+// Pure-function tests for model-compat helpers (moved to providerPageHelpers)
+// ---------------------------------------------------------------------------
+
+describe("providerPageHelpers — model-compat pure functions", () => {
+ const customRow = {
+ id: "gpt-4o",
+ normalizeToolCallId: true,
+ preserveOpenAIDeveloperRole: false,
+ isHidden: true,
+ };
+ const customModels = [customRow];
+ const overrideModels: any[] = [];
+
+ it("buildCompatMap produces a Map keyed by id", () => {
+ const map = buildCompatMap(customModels);
+ expect(map.size).toBe(1);
+ expect(map.get("gpt-4o")).toEqual(customRow);
+ });
+
+ it("isModelHiddenFn reads from customMap first", () => {
+ const customMap = buildCompatMap(customModels);
+ const overrideMap = buildCompatMap(overrideModels);
+ expect(isModelHiddenFn("gpt-4o", customMap, overrideMap)).toBe(true);
+ expect(isModelHiddenFn("unknown-model", customMap, overrideMap)).toBe(false);
+ });
+
+ it("effectiveNormalizeForProtocol returns correct flag", () => {
+ const customMap = buildCompatMap(customModels);
+ const overrideMap = buildCompatMap(overrideModels);
+ expect(effectiveNormalizeForProtocol("gpt-4o", "openai", customMap, overrideMap)).toBe(true);
+ expect(effectiveNormalizeForProtocol("unknown", "openai", customMap, overrideMap)).toBe(false);
+ });
+
+ it("effectivePreserveForProtocol returns correct flag", () => {
+ const customMap = buildCompatMap(customModels);
+ const overrideMap = buildCompatMap(overrideModels);
+ expect(effectivePreserveForProtocol("gpt-4o", "openai", customMap, overrideMap)).toBe(false);
+ // Unknown model defaults to true
+ expect(effectivePreserveForProtocol("unknown", "openai", customMap, overrideMap)).toBe(true);
+ });
+
+ it("anyNormalizeCompatBadge returns true when flag is set", () => {
+ const customMap = buildCompatMap(customModels);
+ const overrideMap = buildCompatMap(overrideModels);
+ expect(anyNormalizeCompatBadge("gpt-4o", customMap, overrideMap)).toBe(true);
+ expect(anyNormalizeCompatBadge("unknown", customMap, overrideMap)).toBe(false);
+ });
+
+ it("anyNoPreserveCompatBadge returns true when preserve=false", () => {
+ const customMap = buildCompatMap(customModels);
+ const overrideMap = buildCompatMap(overrideModels);
+ expect(anyNoPreserveCompatBadge("gpt-4o", customMap, overrideMap)).toBe(true);
+ expect(anyNoPreserveCompatBadge("unknown", customMap, overrideMap)).toBe(false);
+ });
+
+ it("formatProviderModelsErrorResponse extracts error.message", async () => {
+ const mockRes = new Response(
+ JSON.stringify({ error: { message: "Model not found" } }),
+ { status: 422, statusText: "Unprocessable Entity" }
+ );
+ const detail = await formatProviderModelsErrorResponse(mockRes);
+ expect(detail).toBe("Model not found");
+ });
+
+ it("formatProviderModelsErrorResponse falls back to statusText", async () => {
+ const mockRes = new Response("{}", { status: 500, statusText: "Internal Server Error" });
+ const detail = await formatProviderModelsErrorResponse(mockRes);
+ expect(detail).toBe("Internal Server Error");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Component render smoke tests
+// ---------------------------------------------------------------------------
+
+describe("ModelRow — render smoke test", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("renders without throwing", async () => {
+ // Dynamic import to keep top-level mock resolution clean
+ const { default: ModelRow } = await import("../components/ModelRow");
+
+ await act(async () => {
+ root.render(
+ <ModelRow
+ model={{ id: "gpt-4o", name: "GPT-4o", source: "system", isHidden: false }}
+ fullModel="openai/gpt-4o"
+ provider="openai"
+ t={(k) => k}
+ effectiveModelNormalize={() => false}
+ effectiveModelPreserveDeveloper={() => true}
+ saveModelCompatFlags={vi.fn()}
+ getUpstreamHeadersRecord={() => ({})}
+ />
+ );
+ });
+
+ expect(container.textContent).toContain("openai/gpt-4o");
+ });
+});
+
+describe("PassthroughModelRow — render smoke test", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => { root.unmount(); });
+ container.remove();
+ });
+
+ it("renders without throwing", async () => {
+ const { default: PassthroughModelRow } = await import("../components/PassthroughModelRow");
+
+ await act(async () => {
+ root.render(
+ <PassthroughModelRow
+ modelId="some-model"
+ fullModel="openrouter/some-model"
+ t={(k) => k}
+ onCopy={vi.fn()}
+ effectiveModelNormalize={() => false}
+ effectiveModelPreserveDeveloper={() => true}
+ saveModelCompatFlags={vi.fn()}
+ getUpstreamHeadersRecord={() => ({})}
+ />
+ );
+ });
+
+ expect(container.textContent).toContain("openrouter/some-model");
+ });
+});
+
+describe("ModelVisibilityToolbar — render smoke test", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => { root.unmount(); });
+ container.remove();
+ });
+
+ it("renders without throwing", async () => {
+ const { ModelVisibilityToolbar } = await import("../components/ModelRow");
+
+ await act(async () => {
+ root.render(
+ <ModelVisibilityToolbar
+ t={(k) => k}
+ filterValue=""
+ onFilterChange={vi.fn()}
+ activeCount={5}
+ totalCount={10}
+ onSelectAll={vi.fn()}
+ onDeselectAll={vi.fn()}
+ />
+ );
+ });
+
+ // toolbar renders filter input
+ expect(container.querySelector("input")).not.toBeNull();
+ });
+});
+
+describe("useModelCompatState — hook unit test via component wrapper", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => { root.unmount(); });
+ container.remove();
+ });
+
+ it("exposes isModelHidden, effectiveModelNormalize, anyNormalizeCompatBadge correctly", async () => {
+ const { useModelCompatState } = await import("../hooks/useModelCompatState");
+
+ const customModels = [
+ { id: "gpt-4o", normalizeToolCallId: true, preserveOpenAIDeveloperRole: false, isHidden: true },
+ ];
+ const modelCompatOverrides: any[] = [];
+
+ // Capture results via a data-testid attribute on a span to avoid hook-mutation rules
+ function TestWrapper() {
+ const compat = useModelCompatState(customModels, modelCompatOverrides);
+ const results = [
+ compat.isModelHidden("gpt-4o"),
+ compat.isModelHidden("unknown"),
+ compat.effectiveModelNormalize("gpt-4o"),
+ compat.effectiveModelPreserveDeveloper("gpt-4o"),
+ compat.anyNormalizeCompatBadge("gpt-4o"),
+ compat.anyNoPreserveCompatBadge("gpt-4o"),
+ ].map(String).join(",");
+ return <span data-testid="results">{results}</span>;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ const span = container.querySelector("[data-testid='results']");
+ expect(span).not.toBeNull();
+ const [hidden, notHidden, normalize, preserve, anyNorm, anyNoPreserve] =
+ (span!.textContent ?? "").split(",");
+
+ expect(hidden).toBe("true");
+ expect(notHidden).toBe("false");
+ expect(normalize).toBe("true");
+ expect(preserve).toBe("false");
+ expect(anyNorm).toBe("true");
+ expect(anyNoPreserve).toBe("true");
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1f.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1f.test.tsx
new file mode 100644
index 0000000000..9ee6137d20
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/__tests__/phase1f.test.tsx
@@ -0,0 +1,345 @@
+// @vitest-environment jsdom
+//
+// Phase 1f smoke tests for Issue #3501 (strangler-fig decomposition).
+// Validates:
+// 1. useProviderConnections initialises with expected defaults.
+// 2. useProviderSettings initialises with expected defaults.
+// 3. useProviderModels initialises with expected defaults.
+// 4. No cycle: none of the three hooks import from ProviderDetailPageClient.
+//
+// Uses createRoot + act to mount each hook inside a minimal wrapper component
+// so we test real React hook semantics without a full Next.js server context.
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+// ---------------------------------------------------------------------------
+// Global mocks required by the extracted hooks
+// ---------------------------------------------------------------------------
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "test-provider" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ usePathname: () => "/providers/test-provider",
+}));
+
+vi.mock("next-intl", () => ({
+ useTranslations: () => (key: string, values?: Record<string, unknown>) => {
+ if (values) {
+ return Object.entries(values).reduce(
+ (acc, [k, v]) => acc.replace(`{${k}}`, String(v)),
+ key
+ );
+ }
+ return key;
+ },
+}));
+
+vi.mock("@/store/notificationStore", () => ({
+ useNotificationStore: () => ({
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ }),
+}));
+
+// Stub fetch so the hooks don't fire real network calls during mount
+const fetchStub = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({}),
+ text: async () => "",
+ headers: { get: () => null },
+} as any);
+vi.stubGlobal("fetch", fetchStub);
+
+// ---------------------------------------------------------------------------
+// useProviderConnections
+// ---------------------------------------------------------------------------
+
+describe("useProviderConnections — initial state", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ fetchStub.mockClear();
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("exposes connections=[], loading=true, batchTesting=false on first render", async () => {
+ const { useProviderConnections } = await import("../hooks/useProviderConnections");
+
+ type HookResult = ReturnType<typeof useProviderConnections>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderConnections("openai", true, false);
+ return (
+ <span data-testid="loaded">
+ {String(result.connections.length)}|{String(result.batchTesting)}
+ </span>
+ );
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ expect(result).not.toBeNull();
+ expect(result!.connections).toEqual([]);
+ expect(result!.batchTesting).toBe(false);
+ expect(result!.batchDeleting).toBe(false);
+ expect(result!.selectedIds.size).toBe(0);
+ expect(result!.batchDeleteConfirmOpen).toBe(false);
+ expect(result!.healthFilter).toBe("all");
+ expect(result!.page).toBe(0);
+ });
+
+ it("exposes all expected handler functions", async () => {
+ const { useProviderConnections } = await import("../hooks/useProviderConnections");
+
+ type HookResult = ReturnType<typeof useProviderConnections>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderConnections("openai", true, false);
+ return <span />;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ const expected = [
+ "fetchConnections",
+ "fetchProxyConfig",
+ "handleDelete",
+ "handleUpdateConnectionStatus",
+ "handleToggleRateLimit",
+ "handleToggleClaudeExtraUsage",
+ "handleToggleCodexLimit",
+ "handleToggleCliproxyapiMode",
+ "handleToggleProxyEnabled",
+ "handleTogglePerKeyProxyEnabled",
+ "handleRetestConnection",
+ "handleRefreshToken",
+ "handleSwapPriority",
+ "handleBatchSetActive",
+ "handleBatchDeleteOpenModal",
+ "handleBatchDeleteConfirm",
+ "handleBatchRetest",
+ "handleBatchTestAll",
+ "handleToggleSelectOne",
+ "handleToggleSelectAll",
+ "handleDistributeProxies",
+ "parseApiErrorMessage",
+ "getAttachmentFilename",
+ ] as const;
+
+ for (const fn of expected) {
+ expect(typeof (result as any)[fn]).toBe("function");
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// useProviderSettings
+// ---------------------------------------------------------------------------
+
+describe("useProviderSettings — initial state", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ fetchStub.mockClear();
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("exposes codex defaults for a non-codex provider", async () => {
+ const { useProviderSettings } = await import("../hooks/useProviderSettings");
+
+ type HookResult = ReturnType<typeof useProviderSettings>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderSettings("openai");
+ return <span />;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ expect(result).not.toBeNull();
+ // Non-codex provider: settings stay at defaults
+ expect(result!.codexGlobalServiceMode).toBe("none");
+ expect(result!.codexSettingsLoaded).toBe(false);
+ expect(result!.savingCodexGlobalServiceMode).toBe(false);
+ // Claude routing starts unloaded
+ expect(result!.preferClaudeCodeForUnprefixedClaudeModels).toBe(false);
+ expect(result!.claudeRoutingSettingsLoaded).toBe(false);
+ expect(result!.savingClaudeRoutingPreference).toBe(false);
+ });
+
+ it("exposes handler functions", async () => {
+ const { useProviderSettings } = await import("../hooks/useProviderSettings");
+
+ type HookResult = ReturnType<typeof useProviderSettings>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderSettings("codex");
+ return <span />;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ expect(typeof result!.loadCodexSettings).toBe("function");
+ expect(typeof result!.handleChangeCodexGlobalServiceMode).toBe("function");
+ expect(typeof result!.loadClaudeRoutingSettings).toBe("function");
+ expect(typeof result!.handleToggleClaudeRoutingPreference).toBe("function");
+ expect(Array.isArray(result!.codexGlobalServiceModeOptions)).toBe(true);
+ expect(result!.codexGlobalServiceModeOptions.length).toBeGreaterThan(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// useProviderModels
+// ---------------------------------------------------------------------------
+
+describe("useProviderModels — initial state", () => {
+ let container: HTMLElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ fetchStub.mockClear();
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it("initialises with empty arrays and empty alias map", async () => {
+ const { useProviderModels } = await import("../hooks/useProviderModels");
+
+ type HookResult = ReturnType<typeof useProviderModels>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderModels("openai", false);
+ return <span />;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ expect(result).not.toBeNull();
+ expect(result!.modelMeta.customModels).toEqual([]);
+ expect(result!.modelMeta.modelCompatOverrides).toEqual([]);
+ expect(result!.syncedAvailableModels).toEqual([]);
+ expect(result!.modelAliases).toEqual({});
+ });
+
+ it("exposes handler functions", async () => {
+ const { useProviderModels } = await import("../hooks/useProviderModels");
+
+ type HookResult = ReturnType<typeof useProviderModels>;
+ let result: HookResult | null = null;
+
+ function TestWrapper() {
+ result = useProviderModels("openai", false);
+ return <span />;
+ }
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ expect(typeof result!.fetchProviderModelMeta).toBe("function");
+ expect(typeof result!.fetchAliases).toBe("function");
+ expect(typeof result!.handleSetAlias).toBe("function");
+ expect(typeof result!.handleDeleteAlias).toBe("function");
+ });
+
+ it("does not auto-fetch on isSearchProvider=true", async () => {
+ const { useProviderModels } = await import("../hooks/useProviderModels");
+
+ function TestWrapper() {
+ useProviderModels("perplexity-search", true);
+ return <span />;
+ }
+
+ const callCountBefore = fetchStub.mock.calls.length;
+
+ await act(async () => {
+ root.render(<TestWrapper />);
+ });
+
+ // No fetch should have been triggered by the hook itself (the client
+ // gates the effect on !isSearchProvider).
+ const callsForModelMeta = fetchStub.mock.calls.filter((c: any[]) =>
+ String(c[0]).includes("provider-models")
+ );
+ expect(callsForModelMeta.length).toBe(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Cycle-safety: hooks must NOT import from ProviderDetailPageClient
+// ---------------------------------------------------------------------------
+
+const HOOKS_DIR =
+ "/home/diegosouzapw/dev/proxys/OmniRoute/.worktrees/fix-3501-phase1f/src/app/(dashboard)/dashboard/providers/[id]/hooks";
+
+describe("Cycle-safety — hooks do not import ProviderDetailPageClient", () => {
+ // We allow the name in JSDoc comments; what we forbid is an actual ES import statement.
+ function hasImport(source: string): boolean {
+ return /^import[^;]*ProviderDetailPageClient/m.test(source);
+ }
+
+ it("useProviderConnections has no ES import of ProviderDetailPageClient", async () => {
+ const fs = await import("fs/promises");
+ const source = await fs.readFile(`${HOOKS_DIR}/useProviderConnections.ts`, "utf-8");
+ expect(hasImport(source)).toBe(false);
+ });
+
+ it("useProviderSettings has no ES import of ProviderDetailPageClient", async () => {
+ const fs = await import("fs/promises");
+ const source = await fs.readFile(`${HOOKS_DIR}/useProviderSettings.ts`, "utf-8");
+ expect(hasImport(source)).toBe(false);
+ });
+
+ it("useProviderModels has no ES import of ProviderDetailPageClient", async () => {
+ const fs = await import("fs/promises");
+ const source = await fs.readFile(`${HOOKS_DIR}/useProviderModels.ts`, "utf-8");
+ expect(hasImport(source)).toBe(false);
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleModelsSection.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleModelsSection.tsx
new file mode 100644
index 0000000000..1979ee7ce3
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleModelsSection.tsx
@@ -0,0 +1,463 @@
+"use client";
+/**
+ * CompatibleModelsSection — Issue #3501 Phase 1e
+ *
+ * Extracted from ProviderDetailPageClient.tsx. Renders the models panel for
+ * compatible providers (OpenAI-compat, Anthropic-compat, CC-compat, OpenRouter).
+ *
+ * Never imports from ProviderDetailPageClient.
+ */
+import React, { useState, useCallback, useMemo } from "react";
+import { Button } from "@/shared/components";
+import {
+ matchesModelCatalogQuery,
+ normalizeModelCatalogSource,
+} from "@/shared/utils/modelCatalogSearch";
+import { resolveManagedModelAlias } from "@/shared/utils/providerModelAliases";
+import { useNotificationStore } from "@/store/notificationStore";
+import {
+ buildCompatMap,
+ providerText,
+ type CompatModelRow,
+} from "../providerPageHelpers";
+import { ModelVisibilityToolbar } from "./ModelRow";
+import PassthroughModelRow, { type PassthroughModelRowProps } from "./PassthroughModelRow";
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export type CompatibleModelsSaveFlags = {
+ normalizeToolCallId?: boolean;
+ preserveDeveloperRole?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ isHidden?: boolean;
+};
+
+export interface CompatibleModelsSectionProps {
+ providerStorageAlias: string;
+ providerDisplayAlias: string;
+ modelAliases: Record<string, string>;
+ availableModels?: CompatModelRow[];
+ customModels?: CompatModelRow[];
+ fallbackModels?: CompatModelRow[];
+ allowImport: boolean;
+ description: string;
+ inputLabel: string;
+ inputPlaceholder: string;
+ copied?: string;
+ onCopy: (text: string, key: string) => void;
+ onSetAlias: (modelId: string, alias: string, providerStorageAlias?: string) => Promise<void>;
+ onDeleteAlias: (alias: string) => void;
+ connections: { id?: string; isActive?: boolean }[];
+ isAnthropic?: boolean;
+ onImportWithProgress: (connectionId: string) => Promise<void>;
+ t: (key: string, values?: Record<string, unknown>) => string;
+ effectiveModelNormalize: (alias: string) => boolean;
+ effectiveModelPreserveDeveloper: (alias: string) => boolean;
+ getUpstreamHeadersRecord: (modelId: string, protocol: string) => Record<string, string>;
+ saveModelCompatFlags: (
+ modelId: string,
+ flags: CompatibleModelsSaveFlags
+ ) => Promise<void>;
+ compatSavingModelId?: string;
+ onModelsChanged?: () => void;
+ isModelHidden: (modelId: string) => boolean;
+ onToggleHidden: (modelId: string, hidden: boolean) => Promise<void>;
+ onBulkToggleHidden: (modelIds: string[], hidden: boolean) => Promise<void>;
+ bulkTogglePending?: boolean;
+ togglingModelId?: string | null;
+ onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
+ modelTestStatus?: Record<string, "ok" | "error" | null>;
+ testingModelId?: string | null;
+ onTestAll?: (targets: Array<{ modelId: string; fullModel: string }>) => Promise<void>;
+ testingAll?: boolean;
+ testProgress?: { done: number; total: number } | null;
+ autoHideFailed?: boolean;
+ onAutoHideFailedChange?: (v: boolean) => void;
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export default function CompatibleModelsSection({
+ providerStorageAlias,
+ providerDisplayAlias,
+ modelAliases,
+ availableModels = [],
+ customModels = [],
+ fallbackModels = [],
+ description,
+ inputLabel,
+ inputPlaceholder,
+ copied,
+ onCopy,
+ onSetAlias,
+ onDeleteAlias,
+ connections,
+ isAnthropic,
+ onImportWithProgress,
+ t,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ saveModelCompatFlags,
+ compatSavingModelId,
+ onModelsChanged,
+ allowImport,
+ isModelHidden,
+ onToggleHidden,
+ onBulkToggleHidden,
+ bulkTogglePending,
+ togglingModelId,
+ onTestModel,
+ modelTestStatus,
+ testingModelId,
+ onTestAll,
+ testingAll,
+ testProgress,
+ autoHideFailed,
+ onAutoHideFailedChange,
+}: CompatibleModelsSectionProps) {
+ const [newModel, setNewModel] = useState("");
+ const [adding, setAdding] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const [modelFilter, setModelFilter] = useState("");
+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
+ const notify = useNotificationStore();
+ const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);
+
+ const providerAliases = useMemo(
+ () =>
+ Object.entries(modelAliases).filter(([, model]: [string, any]) =>
+ (model as string).startsWith(`${providerStorageAlias}/`)
+ ),
+ [modelAliases, providerStorageAlias]
+ );
+
+ const allModels = useMemo(() => {
+ const prefix = `${providerStorageAlias}/`;
+ const aliasByModelId = new Map<string, string>();
+ const rows: Array<{
+ modelId: string;
+ alias: string | null;
+ displayName: string;
+ source: string;
+ isFree: boolean;
+ isHidden: boolean;
+ }> = [];
+ const seenModelIds = new Set<string>();
+
+ for (const [alias, fullModel] of providerAliases) {
+ const fmStr = fullModel as string;
+ const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
+ aliasByModelId.set(modelId, alias as string);
+ }
+
+ const addModel = (model: CompatModelRow, source: string) => {
+ if (!model?.id || seenModelIds.has(model.id)) return;
+ rows.push({
+ modelId: model.id,
+ alias: aliasByModelId.get(model.id) || null,
+ displayName: model.name || model.id,
+ source,
+ isFree:
+ Boolean((model as any).free) ||
+ model.id.endsWith(":free") ||
+ /\bgr[aá]tis\b|\bfree\b/i.test(model.name || ""),
+ isHidden: isModelHidden(model.id),
+ });
+ seenModelIds.add(model.id);
+ };
+
+ for (const model of availableModels) {
+ addModel(model, "imported");
+ }
+
+ for (const model of customModels) {
+ addModel(
+ model,
+ normalizeModelCatalogSource(model.source) === "imported" ? "imported" : "custom"
+ );
+ }
+
+ for (const model of fallbackModels) {
+ addModel(model, "fallback");
+ }
+
+ for (const [alias, fullModel] of providerAliases) {
+ const fmStr = fullModel as string;
+ const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
+ if (!modelId || seenModelIds.has(modelId)) continue;
+ const customModel = customModelMap.get(modelId);
+ rows.push({
+ modelId,
+ alias: alias as string,
+ displayName: alias as string,
+ source: customModel ? customModel.source || "custom" : "alias",
+ isFree:
+ modelId.endsWith(":free") ||
+ Boolean((customModel as any)?.free) ||
+ /\bgr[aá]tis\b|\bfree\b/i.test(customModel?.name || alias || ""),
+ isHidden: isModelHidden(modelId),
+ });
+ seenModelIds.add(modelId);
+ }
+
+ return rows;
+ }, [
+ availableModels,
+ customModelMap,
+ customModels,
+ fallbackModels,
+ isModelHidden,
+ providerAliases,
+ providerStorageAlias,
+ ]);
+
+ const filteredModels = allModels.filter((model) => {
+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {
+ modelId: model.modelId,
+ modelName: model.displayName,
+ alias: model.alias,
+ source: model.source,
+ });
+ const matchesVisibility =
+ visibilityFilter === "all"
+ ? true
+ : visibilityFilter === "visible"
+ ? !model.isHidden
+ : model.isHidden;
+ return matchesQuery && matchesVisibility;
+ });
+ const activeCount = allModels.filter((model) => !model.isHidden).length;
+ const hiddenFilteredCount = filteredModels.filter((model) => model.isHidden).length;
+ const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;
+
+ const resolveAlias = useCallback(
+ (modelId: string, workingAliases: Record<string, string>) =>
+ resolveManagedModelAlias({
+ modelId,
+ fullModel: `${providerStorageAlias}/${modelId}`,
+ providerDisplayAlias,
+ existingAliases: workingAliases,
+ }),
+ [providerDisplayAlias, providerStorageAlias]
+ );
+
+ const handleAdd = async () => {
+ if (!newModel.trim() || adding) return;
+ const modelId = newModel.trim();
+ const resolvedAlias = resolveAlias(modelId, modelAliases);
+ if (!resolvedAlias) {
+ notify.error(t("allSuggestedAliasesExist"));
+ return;
+ }
+
+ setAdding(true);
+ try {
+ // Save to customModels DB FIRST - only create alias if this succeeds
+ const customModelRes = await fetch("/api/provider-models", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: providerStorageAlias,
+ modelId,
+ modelName: modelId,
+ source: "manual",
+ }),
+ });
+
+ if (!customModelRes.ok) {
+ let errorData: { error?: { message?: string } } = {};
+ try {
+ errorData = await customModelRes.json();
+ } catch (jsonError) {
+ console.error("Failed to parse error response from custom model API:", jsonError);
+ }
+ throw new Error(errorData.error?.message || t("failedSaveCustomModel"));
+ }
+
+ // Only create alias after customModel is saved successfully
+ await onSetAlias(modelId, resolvedAlias, providerStorageAlias);
+ setNewModel("");
+ notify.success(t("modelAddedSuccess", { modelId }));
+ onModelsChanged?.();
+ } catch (error) {
+ console.error("Error adding model:", error);
+ notify.error(error instanceof Error ? error.message : t("failedAddModelTryAgain"));
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ const handleImport = async () => {
+ if (!allowImport || importing) return;
+ const activeConnection = connections.find((conn) => conn.isActive !== false);
+ if (!activeConnection?.id) return;
+
+ setImporting(true);
+ try {
+ await onImportWithProgress(activeConnection.id);
+ } catch (error) {
+ console.error("Error importing models:", error);
+ notify.error(t("failedImportModelsTryAgain"));
+ } finally {
+ setImporting(false);
+ }
+ };
+
+ const canImport = connections.some((conn) => conn.isActive !== false);
+
+ // Handle delete: remove from both alias and customModels DB
+ const handleDeleteModel = async (modelId: string, alias?: string | null) => {
+ try {
+ // Remove from customModels DB
+ const res = await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerStorageAlias)}&model=${encodeURIComponent(modelId)}`,
+ { method: "DELETE" }
+ );
+ if (!res.ok) {
+ throw new Error(t("failedRemoveModelFromDatabase"));
+ }
+ // Also delete the alias
+ if (alias) {
+ await onDeleteAlias(alias);
+ }
+ notify.success(t("modelRemovedSuccess"));
+ onModelsChanged?.();
+ } catch (error) {
+ console.error("Error deleting model:", error);
+ notify.error(error instanceof Error ? error.message : t("failedDeleteModelTryAgain"));
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-text-muted">{description}</p>
+
+ <div className="flex items-end gap-2 flex-wrap">
+ <div className="flex-1 min-w-[240px]">
+ <label
+ htmlFor="new-compatible-model-input"
+ className="text-xs text-text-muted mb-1 block"
+ >
+ {inputLabel}
+ </label>
+ <input
+ id="new-compatible-model-input"
+ type="text"
+ value={newModel}
+ onChange={(e) => setNewModel(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleAdd()}
+ placeholder={inputPlaceholder}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ />
+ </div>
+ <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModel.trim() || adding}>
+ {adding ? t("adding") : t("add")}
+ </Button>
+ {allowImport && (
+ <Button
+ size="sm"
+ variant="secondary"
+ icon="download"
+ onClick={handleImport}
+ disabled={!canImport || importing}
+ >
+ {importing ? t("importingModels") : t("importFromModels")}
+ </Button>
+ )}
+ </div>
+
+ {allowImport && !canImport && (
+ <p className="text-xs text-text-muted">{t("addConnectionToImport")}</p>
+ )}
+
+ {allModels.length > 0 && (
+ <div className="flex flex-col gap-3">
+ <ModelVisibilityToolbar
+ t={t}
+ filterValue={modelFilter}
+ onFilterChange={setModelFilter}
+ activeCount={activeCount}
+ totalCount={allModels.length}
+ onSelectAll={() =>
+ onBulkToggleHidden(
+ filteredModels.map((model) => model.modelId),
+ false
+ )
+ }
+ onDeselectAll={() =>
+ onBulkToggleHidden(
+ filteredModels.map((model) => model.modelId),
+ true
+ )
+ }
+ selectAllDisabled={hiddenFilteredCount === 0 || bulkTogglePending}
+ deselectAllDisabled={visibleFilteredCount === 0 || bulkTogglePending}
+ visibilityFilter={visibilityFilter}
+ onVisibilityFilterChange={setVisibilityFilter}
+ onTestAll={() => {
+ const targets = filteredModels
+ .filter((m) => !m.isHidden)
+ .map((m) => ({
+ modelId: m.modelId,
+ fullModel: `${providerDisplayAlias}/${m.modelId}`,
+ }));
+ return onTestAll?.(targets);
+ }}
+ testingAll={testingAll}
+ testProgress={testProgress}
+ autoHideFailed={autoHideFailed}
+ onAutoHideFailedChange={onAutoHideFailedChange}
+ />
+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ {filteredModels.map(({ modelId, alias, isHidden, source, isFree }) => {
+ const fullModel = `${providerDisplayAlias}/${modelId}`;
+ return (
+ <PassthroughModelRow
+ key={`${providerStorageAlias}:${modelId}`}
+ modelId={modelId}
+ fullModel={fullModel}
+ source={source}
+ isFree={isFree}
+ isHidden={isHidden}
+ copied={copied}
+ onCopy={onCopy}
+ onDeleteAlias={
+ source === "custom" || source === "manual"
+ ? () => handleDeleteModel(modelId, alias)
+ : source === "alias" && alias
+ ? () => onDeleteAlias(alias)
+ : undefined
+ }
+ t={t}
+ showDeveloperToggle={!isAnthropic}
+ effectiveModelNormalize={effectiveModelNormalize}
+ effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
+ getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecord(modelId, p)}
+ saveModelCompatFlags={saveModelCompatFlags}
+ compatDisabled={compatSavingModelId === modelId}
+ onToggleHidden={onToggleHidden}
+ togglingHidden={togglingModelId === modelId}
+ onTestModel={onTestModel}
+ testStatus={modelTestStatus?.[modelId] || null}
+ testingModel={testingModelId === modelId}
+ />
+ );
+ })}
+ </div>
+ {filteredModels.length === 0 && modelFilter && (
+ <p className="py-2 text-sm text-text-muted">
+ {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
+ filter: modelFilter,
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/ConnectionRow.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/ConnectionRow.tsx
new file mode 100644
index 0000000000..36fedfe74c
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/ConnectionRow.tsx
@@ -0,0 +1,940 @@
+"use client";
+
+// Phase 1d extraction — Issue #3501
+// ConnectionRow (and its local helpers CooldownTimer, inferErrorType,
+// getStatusPresentation) moved out of ProviderDetailPageClient.tsx.
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { Badge, Button, Toggle } from "@/shared/components";
+import { pickDisplayValue } from "@/shared/utils/maskEmail";
+import useEmailPrivacyStore from "@/store/emailPrivacyStore";
+import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";
+import {
+ getCodexEffectiveServiceTier,
+ type CodexGlobalServiceMode,
+} from "@/lib/providers/codexFastTier";
+import {
+ normalizeCodexLimitPolicy,
+ providerText,
+ ERROR_TYPE_LABELS,
+} from "../providerPageHelpers";
+
+// ---------------------------------------------------------------------------
+// Types (exported so the client can reference them without re-importing)
+// ---------------------------------------------------------------------------
+
+export interface ConnectionRowConnection {
+ id?: string;
+ name?: string;
+ email?: string;
+ displayName?: string;
+ rateLimitedUntil?: string;
+ rateLimitProtection?: boolean;
+ testStatus?: string;
+ isActive?: boolean;
+ priority?: number;
+ lastError?: string;
+ lastErrorType?: string;
+ lastErrorSource?: string;
+ errorCode?: string | number;
+ globalPriority?: number;
+ providerSpecificData?: Record<string, unknown>;
+ expiresAt?: string;
+ tokenExpiresAt?: string;
+ maxConcurrent?: number | null;
+ authType?: string;
+ proxyEnabled?: boolean;
+ perKeyProxyEnabled?: boolean;
+}
+
+export interface ConnectionRowProps {
+ connection: ConnectionRowConnection;
+ isOAuth: boolean;
+ isClaude?: boolean;
+ isCodex?: boolean;
+ isGeminiCli?: boolean;
+ codexGlobalServiceMode?: CodexGlobalServiceMode;
+ isFirst: boolean;
+ isLast: boolean;
+ isSelected?: boolean;
+ onToggleSelect?: () => void;
+ onMoveUp: () => void;
+ onMoveDown: () => void;
+ onToggleActive: (isActive?: boolean) => void | Promise<void>;
+ onToggleRateLimit: (enabled?: boolean) => void;
+ onToggleClaudeExtraUsage?: (enabled?: boolean) => void;
+ onToggleCodex5h?: (enabled?: boolean) => void;
+ onToggleCodexWeekly?: (enabled?: boolean) => void;
+ isCcCompatible?: boolean;
+ cliproxyapiEnabled?: boolean;
+ onToggleCliproxyapiMode?: (enabled?: boolean) => void;
+ onRetest: () => void;
+ isRetesting?: boolean;
+ onEdit: () => void;
+ onDelete: () => void;
+ onReauth?: () => void;
+ onProxy?: () => void;
+ hasProxy?: boolean;
+ proxySource?: string;
+ proxyHost?: string;
+ proxyEnabled?: boolean;
+ perKeyProxyEnabled?: boolean;
+ onToggleProxyEnabled?: (enabled: boolean) => void;
+ onTogglePerKeyProxyEnabled?: (enabled: boolean) => void;
+ onRefreshToken?: () => void;
+ isRefreshing?: boolean;
+ onApplyCodexAuthLocal?: () => void;
+ isApplyingCodexAuthLocal?: boolean;
+ onExportCodexAuthFile?: () => void;
+ isExportingCodexAuthFile?: boolean;
+ onApplyClaudeAuthLocal?: () => void;
+ isApplyingClaudeAuthLocal?: boolean;
+ onExportClaudeAuthFile?: () => void;
+ isExportingClaudeAuthFile?: boolean;
+ onApplyGeminiAuthLocal?: () => void;
+ isApplyingGeminiAuthLocal?: boolean;
+ onExportGeminiAuthFile?: () => void;
+ isExportingGeminiAuthFile?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// CooldownTimerProps (local — only used below)
+// ---------------------------------------------------------------------------
+
+interface CooldownTimerProps {
+ until: string | number | Date;
+}
+
+// ---------------------------------------------------------------------------
+// CooldownTimer
+// ---------------------------------------------------------------------------
+
+function CooldownTimer({ until }: CooldownTimerProps) {
+ const [remaining, setRemaining] = useState("");
+
+ useEffect(() => {
+ const updateRemaining = () => {
+ const diff = new Date(until).getTime() - Date.now();
+ if (diff <= 0) {
+ setRemaining("");
+ return;
+ }
+ const secs = Math.floor(diff / 1000);
+ if (secs < 60) {
+ setRemaining(`${secs}s`);
+ } else if (secs < 3600) {
+ setRemaining(`${Math.floor(secs / 60)}m ${secs % 60}s`);
+ } else {
+ const hrs = Math.floor(secs / 3600);
+ const mins = Math.floor((secs % 3600) / 60);
+ setRemaining(`${hrs}h ${mins}m`);
+ }
+ };
+
+ updateRemaining();
+ const interval = setInterval(updateRemaining, 1000);
+ return () => clearInterval(interval);
+ }, [until]);
+
+ if (!remaining) return null;
+
+ return <span className="text-xs text-orange-500 font-mono">⏱ {remaining}</span>;
+}
+
+// ---------------------------------------------------------------------------
+// inferErrorType
+// ---------------------------------------------------------------------------
+
+function inferErrorType(connection: ConnectionRowConnection, isCooldown: boolean): string | null {
+ if (isCooldown) return "upstream_rate_limited";
+ if (connection.testStatus === "banned") return "banned";
+ if (connection.testStatus === "credits_exhausted") return "credits_exhausted";
+ if (connection.lastErrorType) return connection.lastErrorType;
+
+ const code = Number(connection.errorCode);
+ if (code === 401 || code === 403) return "upstream_auth_error";
+ if (code === 429) return "upstream_rate_limited";
+ if (code >= 500) return "upstream_unavailable";
+
+ const msg = (connection.lastError || "").toLowerCase();
+ if (!msg) return null;
+ if (
+ msg.includes("runtime") ||
+ msg.includes("not runnable") ||
+ msg.includes("not installed") ||
+ msg.includes("healthcheck")
+ )
+ return "runtime_error";
+ if (msg.includes("refresh failed")) return "token_refresh_failed";
+ if (msg.includes("token expired") || msg.includes("expired")) return "token_expired";
+ if (
+ msg.includes("invalid api key") ||
+ msg.includes("token invalid") ||
+ msg.includes("revoked") ||
+ msg.includes("access denied") ||
+ msg.includes("unauthorized")
+ )
+ return "upstream_auth_error";
+ if (
+ msg.includes("rate limit") ||
+ msg.includes("quota") ||
+ msg.includes("too many requests") ||
+ msg.includes("429")
+ )
+ return "upstream_rate_limited";
+ if (
+ msg.includes("fetch failed") ||
+ msg.includes("network") ||
+ msg.includes("timeout") ||
+ msg.includes("econn") ||
+ msg.includes("enotfound")
+ )
+ return "network_error";
+ if (msg.includes("not supported")) return "unsupported";
+ return "upstream_error";
+}
+
+// ---------------------------------------------------------------------------
+// getStatusPresentation
+// ---------------------------------------------------------------------------
+
+type TFn = (key: string, values?: Record<string, unknown>) => string;
+
+function getStatusPresentation(
+ connection: ConnectionRowConnection,
+ effectiveStatus: string | undefined,
+ isCooldown: boolean,
+ t: TFn
+) {
+ if (connection.isActive === false) {
+ return {
+ statusVariant: "default",
+ statusLabel: t("statusDisabled"),
+ errorType: null,
+ errorBadge: null,
+ errorTextClass: "text-text-muted",
+ };
+ }
+
+ if (effectiveStatus === "active" || effectiveStatus === "success") {
+ return {
+ statusVariant: "success",
+ statusLabel: t("statusConnected"),
+ errorType: null,
+ errorBadge: null,
+ errorTextClass: "text-text-muted",
+ };
+ }
+
+ const errorType = inferErrorType(connection, isCooldown);
+ const errorBadge = errorType ? ERROR_TYPE_LABELS[errorType] || null : null;
+
+ if (errorType === "runtime_error") {
+ return {
+ statusVariant: "warning",
+ statusLabel: t("statusRuntimeIssue"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-yellow-600 dark:text-yellow-400",
+ };
+ }
+
+ if (errorType === "account_deactivated") {
+ return {
+ statusVariant: "error",
+ statusLabel: t("statusDeactivated", "Deactivated"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-red-600 font-bold",
+ };
+ }
+
+ if (
+ errorType === "upstream_auth_error" ||
+ errorType === "auth_missing" ||
+ errorType === "token_refresh_failed" ||
+ errorType === "token_expired"
+ ) {
+ return {
+ statusVariant: "error",
+ statusLabel: t("statusAuthFailed"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-red-500",
+ };
+ }
+
+ if (errorType === "upstream_rate_limited") {
+ return {
+ statusVariant: "warning",
+ statusLabel: t("statusRateLimited"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-yellow-600 dark:text-yellow-400",
+ };
+ }
+
+ if (errorType === "network_error") {
+ return {
+ statusVariant: "warning",
+ statusLabel: t("statusNetworkIssue"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-yellow-600 dark:text-yellow-400",
+ };
+ }
+
+ if (errorType === "unsupported") {
+ return {
+ statusVariant: "default",
+ statusLabel: t("statusTestUnsupported"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-text-muted",
+ };
+ }
+
+ if (errorType === "banned") {
+ return {
+ statusVariant: "error",
+ statusLabel: t("statusBanned", "Banned (403)"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-red-600 font-bold",
+ };
+ }
+
+ if (errorType === "credits_exhausted") {
+ return {
+ statusVariant: "warning",
+ statusLabel: t("statusCreditsExhausted", "Out of Credits"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-amber-500",
+ };
+ }
+
+ const fallbackStatusMap: Record<string, string> = {
+ unavailable: t("statusUnavailable"),
+ failed: t("statusFailed"),
+ error: t("statusError"),
+ };
+
+ return {
+ statusVariant: "error",
+ statusLabel: fallbackStatusMap[effectiveStatus ?? ""] || effectiveStatus || t("statusError"),
+ errorType,
+ errorBadge,
+ errorTextClass: "text-red-500",
+ };
+}
+
+// ---------------------------------------------------------------------------
+// ConnectionRow
+// ---------------------------------------------------------------------------
+
+export default function ConnectionRow({
+ connection,
+ isOAuth,
+ isClaude,
+ isCodex,
+ isGeminiCli,
+ codexGlobalServiceMode,
+ isCcCompatible,
+ cliproxyapiEnabled,
+ isFirst,
+ isLast,
+ isSelected,
+ onToggleSelect,
+ onMoveUp,
+ onMoveDown,
+ onToggleActive,
+ onToggleRateLimit,
+ onToggleClaudeExtraUsage,
+ onToggleCodex5h,
+ onToggleCodexWeekly,
+ onToggleCliproxyapiMode,
+ onRetest,
+ isRetesting,
+ onEdit,
+ onDelete,
+ onReauth,
+ onProxy,
+ hasProxy,
+ proxySource,
+ proxyHost,
+ onRefreshToken,
+ isRefreshing,
+ onApplyCodexAuthLocal,
+ isApplyingCodexAuthLocal,
+ onExportCodexAuthFile,
+ isExportingCodexAuthFile,
+ onApplyClaudeAuthLocal,
+ isApplyingClaudeAuthLocal,
+ onExportClaudeAuthFile,
+ isExportingClaudeAuthFile,
+ onApplyGeminiAuthLocal,
+ isApplyingGeminiAuthLocal,
+ onExportGeminiAuthFile,
+ isExportingGeminiAuthFile,
+ perKeyProxyEnabled,
+ onTogglePerKeyProxyEnabled,
+ proxyEnabled,
+ onToggleProxyEnabled,
+}: ConnectionRowProps) {
+ const t = useTranslations("providers");
+ const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);
+ const displayName = isOAuth
+ ? pickDisplayValue(
+ [connection.name, connection.email, connection.displayName],
+ emailsVisible,
+ t("oauthAccount")
+ )
+ : connection.name;
+ const applyCodexAuthLabel =
+ typeof t.has === "function" && t.has("applyCodexAuthLocal")
+ ? t("applyCodexAuthLocal")
+ : "Apply auth";
+ const exportCodexAuthLabel =
+ typeof t.has === "function" && t.has("exportCodexAuthFile")
+ ? t("exportCodexAuthFile")
+ : "Export auth";
+ const applyClaudeAuthLabel =
+ typeof t.has === "function" && t.has("applyClaudeAuthLocal")
+ ? t("applyClaudeAuthLocal")
+ : "Apply auth";
+ const exportClaudeAuthLabel =
+ typeof t.has === "function" && t.has("exportClaudeAuthFile")
+ ? t("exportClaudeAuthFile")
+ : "Export auth";
+ const applyGeminiAuthLabel =
+ typeof t.has === "function" && t.has("applyGeminiAuthLocal")
+ ? t("applyGeminiAuthLocal")
+ : "Apply auth";
+ const exportGeminiAuthLabel =
+ typeof t.has === "function" && t.has("exportGeminiAuthFile")
+ ? t("exportGeminiAuthFile")
+ : "Export auth";
+
+ // Use useState + useEffect for impure Date.now() to avoid calling during render
+ const [isCooldown, setIsCooldown] = useState(false);
+ // T12: token expiry status — lazy init avoids calling Date.now() during render;
+ // updates every 30s via interval only (no sync setState in effect body).
+ // Prefer tokenExpiresAt (updated on each refresh) over expiresAt (original grant date).
+ const effectiveExpiresAt = connection.tokenExpiresAt || connection.expiresAt;
+ const getTokenMinsLeft = () => {
+ if (!isOAuth || !effectiveExpiresAt) return null;
+ const expiresMs = new Date(effectiveExpiresAt).getTime();
+ return Math.floor((expiresMs - Date.now()) / 60000);
+ };
+ const [tokenMinsLeft, setTokenMinsLeft] = useState<number | null>(getTokenMinsLeft);
+
+ useEffect(() => {
+ if (!isOAuth || !effectiveExpiresAt) return;
+ const update = () => {
+ const expiresMs = new Date(effectiveExpiresAt).getTime();
+ setTokenMinsLeft(Math.floor((expiresMs - Date.now()) / 60000));
+ };
+ update();
+ const iv = setInterval(update, 30000);
+ return () => clearInterval(iv);
+ }, [isOAuth, effectiveExpiresAt]);
+
+ useEffect(() => {
+ const checkCooldown = () => {
+ const cooldown =
+ connection.rateLimitedUntil && new Date(connection.rateLimitedUntil).getTime() > Date.now();
+ setIsCooldown(!!cooldown);
+ };
+
+ checkCooldown();
+ // Update every second while in cooldown
+ const interval = connection.rateLimitedUntil ? setInterval(checkCooldown, 1000) : null;
+ return () => {
+ if (interval) clearInterval(interval);
+ };
+ }, [connection.rateLimitedUntil]);
+
+ // Determine effective status (override unavailable if cooldown expired)
+ const effectiveStatus =
+ connection.testStatus === "unavailable" && !isCooldown
+ ? "active" // Cooldown expired → treat as active
+ : connection.testStatus;
+
+ const statusPresentation = getStatusPresentation(connection, effectiveStatus, isCooldown, t);
+ const rateLimitEnabled = !!connection.rateLimitProtection;
+ const codexPolicy =
+ connection.providerSpecificData &&
+ typeof connection.providerSpecificData === "object" &&
+ connection.providerSpecificData.codexLimitPolicy &&
+ typeof connection.providerSpecificData.codexLimitPolicy === "object"
+ ? connection.providerSpecificData.codexLimitPolicy
+ : {};
+ const normalizedCodexPolicy = normalizeCodexLimitPolicy(codexPolicy);
+ const codex5hEnabled = normalizedCodexPolicy.use5h;
+ const codexWeeklyEnabled = normalizedCodexPolicy.useWeekly;
+ const codexServiceTier = isCodex
+ ? getCodexEffectiveServiceTier(
+ connection.providerSpecificData,
+ codexGlobalServiceMode ?? "none"
+ )
+ : "default";
+ const codexServiceTierIsGlobal =
+ isCodex && codexGlobalServiceMode !== undefined && codexGlobalServiceMode !== "none";
+ const codexServiceTierBadge =
+ codexServiceTier === "priority"
+ ? {
+ label: providerText(t, "codexTierFastLabel", "Fast"),
+ icon: "bolt",
+ className: "bg-sky-500/15 text-sky-500",
+ title: codexServiceTierIsGlobal
+ ? providerText(
+ t,
+ "providerDetailGlobalPriorityActive",
+ "Global Codex priority service tier is active"
+ )
+ : providerText(
+ t,
+ "providerDetailConnectionPriorityActive",
+ "Codex priority service tier is active for this connection"
+ ),
+ }
+ : codexServiceTier === "flex"
+ ? {
+ label: providerText(t, "codexTierFlexLabel", "Flex"),
+ icon: "speed",
+ className: "bg-cyan-500/15 text-cyan-500",
+ title: codexServiceTierIsGlobal
+ ? providerText(
+ t,
+ "providerDetailGlobalFlexActive",
+ "Global Codex flex service tier is active"
+ )
+ : providerText(
+ t,
+ "providerDetailConnectionFlexActive",
+ "Codex flex service tier is active for this connection"
+ ),
+ }
+ : null;
+ const claudeBlockExtraUsageEnabled = isClaude
+ ? isClaudeExtraUsageBlockEnabled("claude", connection.providerSpecificData)
+ : false;
+ const cliproxyapiDeepMode = !!cliproxyapiEnabled;
+
+ return (
+ <div
+ className={`group flex items-center justify-between p-3 rounded-lg hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${connection.isActive === false ? "opacity-60" : ""}`}
+ >
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ {onToggleSelect && (
+ <input
+ type="checkbox"
+ checked={isSelected}
+ onChange={onToggleSelect}
+ className="w-4 h-4 shrink-0 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
+ />
+ )}
+ {/* Priority arrows */}
+ <div className="flex flex-col">
+ <button
+ onClick={onMoveUp}
+ disabled={isFirst}
+ className={`p-0.5 rounded ${isFirst ? "text-text-muted/30 cursor-not-allowed" : "hover:bg-sidebar text-text-muted hover:text-primary"}`}
+ >
+ <span className="material-symbols-outlined text-sm">keyboard_arrow_up</span>
+ </button>
+ <button
+ onClick={onMoveDown}
+ disabled={isLast}
+ className={`p-0.5 rounded ${isLast ? "text-text-muted/30 cursor-not-allowed" : "hover:bg-sidebar text-text-muted hover:text-primary"}`}
+ >
+ <span className="material-symbols-outlined text-sm">keyboard_arrow_down</span>
+ </button>
+ </div>
+ <span className="material-symbols-outlined text-base text-text-muted">
+ {isOAuth ? "lock" : "key"}
+ </span>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{displayName}</p>
+ <div className="flex items-center gap-2 mt-1 flex-wrap">
+ <Badge variant={statusPresentation.statusVariant as any} size="sm" dot>
+ {statusPresentation.statusLabel}
+ </Badge>
+ {/* T12: Token expiry status indicator (state-driven, no Date.now in render) */}
+ {tokenMinsLeft !== null &&
+ (tokenMinsLeft < 0 ? (
+ <span
+ className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-500"
+ title={t("tokenExpiredTitle", { date: effectiveExpiresAt })}
+ >
+ <span className="material-symbols-outlined text-[11px]">error</span>
+ {t("tokenExpiredBadge")}
+ </span>
+ ) : tokenMinsLeft < 30 ? (
+ <span
+ className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-500"
+ title={t("tokenExpiresSoonTitle", { minutes: tokenMinsLeft })}
+ >
+ <span className="material-symbols-outlined text-[11px]">warning</span>
+ {`~${tokenMinsLeft}m`}
+ </span>
+ ) : null)}
+ {isCooldown && connection.isActive !== false && (
+ <CooldownTimer until={connection.rateLimitedUntil!} />
+ )}
+ {statusPresentation.errorBadge && connection.isActive !== false && (
+ <Badge variant={statusPresentation.errorBadge.variant} size="sm">
+ {t(statusPresentation.errorBadge.labelKey)}
+ </Badge>
+ )}
+ {connection.lastError && connection.isActive !== false && (
+ <span
+ className={`text-xs truncate max-w-[300px] ${statusPresentation.errorTextClass}`}
+ title={connection.lastError}
+ >
+ {connection.lastError}
+ </span>
+ )}
+ <span className="text-xs text-text-muted">#{connection.priority}</span>
+ {connection.globalPriority && (
+ <span className="text-xs text-text-muted">
+ {t("autoPriority", { priority: connection.globalPriority })}
+ </span>
+ )}
+ {connection.maxConcurrent != null && connection.maxConcurrent > 0 && (
+ <span
+ className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-zinc-500/15 text-zinc-500 dark:bg-zinc-400/15 dark:text-zinc-400"
+ title={t("accountConcurrencyCapLabel")}
+ >
+ <span className="material-symbols-outlined text-[11px]">dynamic_feed</span>
+ {connection.maxConcurrent}
+ </span>
+ )}
+ {/* Rate Limit Protection — inline toggle with label */}
+ <span className="text-text-muted/30 select-none">|</span>
+ <button
+ onClick={() => onToggleRateLimit(!rateLimitEnabled)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ rateLimitEnabled
+ ? "bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={
+ rateLimitEnabled ? t("disableRateLimitProtection") : t("enableRateLimitProtection")
+ }
+ >
+ <span className="material-symbols-outlined text-[13px]">shield</span>
+ {rateLimitEnabled ? t("rateLimitProtected") : t("rateLimitUnprotected")}
+ </button>
+ {isClaude && (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ <button
+ onClick={() => onToggleClaudeExtraUsage?.(!claudeBlockExtraUsageEnabled)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ !claudeBlockExtraUsageEnabled
+ ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={t("claudeExtraUsageToggleTitle")}
+ >
+ <span className="material-symbols-outlined text-[13px]">payments</span>
+ {t("claudeExtraUsageShort")}{" "}
+ {!claudeBlockExtraUsageEnabled ? t("toggleOnShort") : t("toggleOffShort")}
+ </button>
+ </>
+ )}
+ {isCcCompatible && (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ <button
+ onClick={() => onToggleCliproxyapiMode?.(!cliproxyapiDeepMode)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ cliproxyapiDeepMode
+ ? "bg-indigo-500/15 text-indigo-500 hover:bg-indigo-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={cliproxyapiDeepMode ? t("cpaModeEnabledTitle") : t("cpaModeDisabledTitle")}
+ >
+ <span className="material-symbols-outlined text-[13px]">swap_horiz</span>
+ CPA {cliproxyapiDeepMode ? t("toggleOnShort") : t("toggleOffShort")}
+ </button>
+ </>
+ )}
+ {isCodex && (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ {codexServiceTierBadge && (
+ <span
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium ${codexServiceTierBadge.className}`}
+ title={codexServiceTierBadge.title}
+ >
+ <span className="material-symbols-outlined text-[13px]">
+ {codexServiceTierBadge.icon}
+ </span>
+ {codexServiceTierBadge.label}
+ </span>
+ )}
+ <button
+ onClick={() => onToggleCodex5h?.(!codex5hEnabled)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ codex5hEnabled
+ ? "bg-blue-500/15 text-blue-500 hover:bg-blue-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={t("codex5hToggleTitle")}
+ >
+ <span className="material-symbols-outlined text-[13px]">timer</span>
+ 5h {codex5hEnabled ? t("toggleOnShort") : t("toggleOffShort")}
+ </button>
+ <button
+ onClick={() => onToggleCodexWeekly?.(!codexWeeklyEnabled)}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ codexWeeklyEnabled
+ ? "bg-violet-500/15 text-violet-500 hover:bg-violet-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={t("codexWeeklyToggleTitle")}
+ >
+ <span className="material-symbols-outlined text-[13px]">date_range</span>
+ {t("weeklyShort")} {codexWeeklyEnabled ? t("toggleOnShort") : t("toggleOffShort")}
+ </button>
+ </>
+ )}
+ {onToggleProxyEnabled && (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ <button
+ onClick={() => onToggleProxyEnabled(!proxyEnabled)}
+ aria-label={proxyEnabled ? t("proxyEnabledTitle") : t("proxyDisabledTitle")}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ proxyEnabled
+ ? "bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={proxyEnabled ? t("proxyEnabledTitle") : t("proxyDisabledTitle")}
+ >
+ <span className="material-symbols-outlined text-[13px]">vpn_lock</span>
+ {proxyEnabled ? <span className="sr-only">{t("proxyOn")}</span> : t("proxyOff")}
+ </button>
+ </>
+ )}
+ {onTogglePerKeyProxyEnabled && (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ <button
+ onClick={() => onTogglePerKeyProxyEnabled(!perKeyProxyEnabled)}
+ aria-label={
+ perKeyProxyEnabled
+ ? t("perKeyProxyEnabledTitle")
+ : t("perKeyProxyDisabledTitle")
+ }
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
+ perKeyProxyEnabled
+ ? "bg-violet-500/15 text-violet-500 hover:bg-violet-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={
+ perKeyProxyEnabled
+ ? t("perKeyProxyEnabledTitle")
+ : t("perKeyProxyDisabledTitle")
+ }
+ >
+ <span className="material-symbols-outlined text-[13px]">key</span>
+ {perKeyProxyEnabled ? (
+ t("perKeyProxyOn")
+ ) : (
+ <span className="sr-only">{t("perKeyProxyOff")}</span>
+ )}
+ </button>
+ </>
+ )}
+ {hasProxy &&
+ (() => {
+ const colorClass =
+ proxySource === "global"
+ ? "bg-emerald-500/15 text-emerald-500"
+ : proxySource === "provider"
+ ? "bg-amber-500/15 text-amber-500"
+ : "bg-blue-500/15 text-blue-500";
+ const label =
+ proxySource === "global"
+ ? t("proxySourceGlobal")
+ : proxySource === "provider"
+ ? t("proxySourceProvider")
+ : t("proxySourceKey");
+ return (
+ <>
+ <span className="text-text-muted/30 select-none">|</span>
+ <span
+ className={`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${colorClass}`}
+ title={t("proxyConfiguredBySource", {
+ source: label,
+ host: proxyHost || t("configured"),
+ })}
+ >
+ <span className="material-symbols-outlined text-[13px]">vpn_lock</span>
+ {proxyHost || t("proxy")}
+ </span>
+ </>
+ );
+ })()}
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="refresh"
+ loading={isRetesting}
+ disabled={connection.isActive === false}
+ onClick={onRetest}
+ className="!h-7 !px-2 text-xs"
+ title={t("retestAuthentication")}
+ >
+ {t("retest")}
+ </Button>
+ {/* T12: Manual token refresh for OAuth accounts */}
+ {onRefreshToken && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="token"
+ loading={isRefreshing}
+ disabled={connection.isActive === false || isRefreshing}
+ onClick={onRefreshToken}
+ className="!h-7 !px-2 text-xs text-amber-500 hover:text-amber-400"
+ title={t("refreshOauthTokenTitle")}
+ >
+ {t("tokenShort")}
+ </Button>
+ )}
+ {isCodex && onApplyCodexAuthLocal && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="download_done"
+ loading={isApplyingCodexAuthLocal}
+ disabled={isApplyingCodexAuthLocal}
+ onClick={onApplyCodexAuthLocal}
+ className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
+ title={applyCodexAuthLabel}
+ >
+ {applyCodexAuthLabel}
+ </Button>
+ )}
+ {isCodex && onExportCodexAuthFile && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="download"
+ loading={isExportingCodexAuthFile}
+ disabled={isExportingCodexAuthFile}
+ onClick={onExportCodexAuthFile}
+ className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
+ title={exportCodexAuthLabel}
+ >
+ {exportCodexAuthLabel}
+ </Button>
+ )}
+ {isClaude && onApplyClaudeAuthLocal && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="install_desktop"
+ loading={isApplyingClaudeAuthLocal}
+ disabled={isApplyingClaudeAuthLocal}
+ onClick={onApplyClaudeAuthLocal}
+ className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
+ title={applyClaudeAuthLabel}
+ >
+ {applyClaudeAuthLabel}
+ </Button>
+ )}
+ {isClaude && onExportClaudeAuthFile && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="download"
+ loading={isExportingClaudeAuthFile}
+ disabled={isExportingClaudeAuthFile}
+ onClick={onExportClaudeAuthFile}
+ className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
+ title={exportClaudeAuthLabel}
+ >
+ {exportClaudeAuthLabel}
+ </Button>
+ )}
+ {isGeminiCli && onApplyGeminiAuthLocal && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="install_desktop"
+ loading={isApplyingGeminiAuthLocal}
+ disabled={isApplyingGeminiAuthLocal}
+ onClick={onApplyGeminiAuthLocal}
+ className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
+ title={applyGeminiAuthLabel}
+ >
+ {applyGeminiAuthLabel}
+ </Button>
+ )}
+ {isGeminiCli && onExportGeminiAuthFile && (
+ <Button
+ size="sm"
+ variant="ghost"
+ icon="download"
+ loading={isExportingGeminiAuthFile}
+ disabled={isExportingGeminiAuthFile}
+ onClick={onExportGeminiAuthFile}
+ className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
+ title={exportGeminiAuthLabel}
+ >
+ {exportGeminiAuthLabel}
+ </Button>
+ )}
+ <Toggle
+ size="sm"
+ checked={connection.isActive ?? true}
+ onChange={onToggleActive}
+ title={(connection.isActive ?? true) ? t("disableConnection") : t("enableConnection")}
+ />
+ <div className="flex gap-1 ml-1 transition-opacity">
+ {onReauth && (
+ <button
+ onClick={onReauth}
+ className="p-2 hover:bg-amber-500/10 rounded text-amber-600 hover:text-amber-500"
+ title={t("reauthenticateConnection")}
+ >
+ <span className="material-symbols-outlined text-[18px]">passkey</span>
+ </button>
+ )}
+ <button
+ onClick={onEdit}
+ className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary"
+ title={t("edit")}
+ >
+ <span className="material-symbols-outlined text-[18px]">edit</span>
+ </button>
+ <button
+ onClick={onProxy}
+ className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary"
+ title={t("proxyConfig")}
+ >
+ <span className="material-symbols-outlined text-[18px]">vpn_lock</span>
+ </button>
+ <button
+ onClick={onDelete}
+ className="p-2 hover:bg-red-500/10 rounded text-red-500"
+ title={t("delete")}
+ >
+ <span className="material-symbols-outlined text-[18px]">delete</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/CustomModelsSection.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/CustomModelsSection.tsx
new file mode 100644
index 0000000000..7b9a342e80
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/CustomModelsSection.tsx
@@ -0,0 +1,562 @@
+"use client";
+/**
+ * CustomModelsSection — Issue #3501 Phase 1e
+ *
+ * Extracted from ProviderDetailPageClient.tsx. Renders the "custom models"
+ * panel for ALL providers. This section is self-contained: it fetches its
+ * own model state from the API and manages local loading/saving state.
+ *
+ * Never imports from ProviderDetailPageClient.
+ */
+import React, { useState, useEffect, useCallback, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { Button } from "@/shared/components";
+import { useNotificationStore } from "@/store/notificationStore";
+import {
+ buildCompatMap,
+ anyNormalizeCompatBadge,
+ anyNoPreserveCompatBadge,
+ anyUpstreamHeadersBadge,
+ effectiveNormalizeForProtocol,
+ effectivePreserveForProtocol,
+ effectiveUpstreamHeadersForProtocol,
+ formatProviderModelsErrorResponse,
+ type CompatModelRow,
+ type CompatByProtocolMap,
+} from "../providerPageHelpers";
+import ModelCompatPopover from "./ModelCompatPopover";
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export interface CustomModelsSectionProps {
+ providerId: string;
+ providerAlias: string;
+ copied?: string;
+ onCopy: (text: string, key: string) => void;
+ onModelsChanged?: () => void;
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export default function CustomModelsSection({
+ providerId,
+ providerAlias,
+ copied,
+ onCopy,
+ onModelsChanged,
+}: CustomModelsSectionProps) {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+ const [customModels, setCustomModels] = useState<CompatModelRow[]>([]);
+ const [modelCompatOverrides, setModelCompatOverrides] = useState<
+ Array<CompatModelRow & { id: string }>
+ >([]);
+ const [newModelId, setNewModelId] = useState("");
+ const [newModelName, setNewModelName] = useState("");
+ const [newApiFormat, setNewApiFormat] = useState("chat-completions");
+ const [newEndpoints, setNewEndpoints] = useState(["chat"]);
+ const [adding, setAdding] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const [editingModelId, setEditingModelId] = useState<string | null>(null);
+ const [editingApiFormat, setEditingApiFormat] = useState("chat-completions");
+ const [editingEndpoints, setEditingEndpoints] = useState<string[]>(["chat"]);
+ const [savingModelId, setSavingModelId] = useState<string | null>(null);
+ const [togglingModelId, setTogglingModelId] = useState<string | null>(null);
+
+ const customMap = useMemo(() => buildCompatMap(customModels), [customModels]);
+ const overrideMap = useMemo(() => buildCompatMap(modelCompatOverrides), [modelCompatOverrides]);
+
+ const fetchCustomModels = useCallback(async () => {
+ try {
+ const res = await fetch(`/api/provider-models?provider=${encodeURIComponent(providerId)}`);
+ if (res.ok) {
+ const data = await res.json();
+ setCustomModels(data.models || []);
+ setModelCompatOverrides(data.modelCompatOverrides || []);
+ }
+ } catch (e) {
+ console.error("Failed to fetch custom models:", e);
+ } finally {
+ setLoading(false);
+ }
+ }, [providerId]);
+
+ useEffect(() => {
+ fetchCustomModels();
+ }, [fetchCustomModels]);
+
+ const handleAdd = async () => {
+ if (!newModelId.trim() || adding) return;
+ setAdding(true);
+ try {
+ const res = await fetch("/api/provider-models", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: providerId,
+ modelId: newModelId.trim(),
+ modelName: newModelName.trim() || undefined,
+ apiFormat: newApiFormat,
+ supportedEndpoints: newEndpoints,
+ }),
+ });
+ if (res.ok) {
+ setNewModelId("");
+ setNewModelName("");
+ setNewApiFormat("chat-completions");
+ setNewEndpoints(["chat"]);
+ await fetchCustomModels();
+ onModelsChanged?.();
+ }
+ } catch (e) {
+ console.error("Failed to add custom model:", e);
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ const handleRemove = async (modelId: string) => {
+ try {
+ await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerId)}&model=${encodeURIComponent(modelId)}`,
+ {
+ method: "DELETE",
+ }
+ );
+ await fetchCustomModels();
+ onModelsChanged?.();
+ } catch (e) {
+ console.error("Failed to remove custom model:", e);
+ }
+ };
+
+ const handleToggleHidden = async (modelId: string, hidden: boolean) => {
+ setTogglingModelId(modelId);
+ try {
+ const res = await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerId)}&modelId=${encodeURIComponent(modelId)}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ isHidden: hidden }),
+ }
+ );
+ if (res.ok) {
+ await fetchCustomModels();
+ onModelsChanged?.();
+ }
+ } catch (e) {
+ console.error("Failed to toggle model visibility:", e);
+ } finally {
+ setTogglingModelId(null);
+ }
+ };
+
+ const beginEdit = (model: CompatModelRow) => {
+ setEditingModelId(model.id ?? null);
+ setEditingApiFormat(model.apiFormat || "chat-completions");
+ setEditingEndpoints(
+ Array.isArray(model.supportedEndpoints) && model.supportedEndpoints.length
+ ? model.supportedEndpoints
+ : ["chat"]
+ );
+ };
+
+ const cancelEdit = () => {
+ setEditingModelId(null);
+ setEditingApiFormat("chat-completions");
+ setEditingEndpoints(["chat"]);
+ setSavingModelId(null);
+ };
+
+ const saveCustomCompat = async (
+ modelId: string,
+ patch: { compatByProtocol?: CompatByProtocolMap }
+ ) => {
+ setSavingModelId(modelId);
+ try {
+ const res = await fetch("/api/provider-models", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider: providerId, modelId, ...patch }),
+ });
+ if (!res.ok) {
+ const detail = await formatProviderModelsErrorResponse(res);
+ notify.error(
+ detail ? `${t("failedSaveCustomModel")} — ${detail}` : t("failedSaveCustomModel")
+ );
+ return;
+ }
+ } catch {
+ notify.error(t("failedSaveCustomModel"));
+ return;
+ } finally {
+ setSavingModelId(null);
+ }
+ try {
+ await fetchCustomModels();
+ onModelsChanged?.();
+ } catch {
+ /* refresh failure is non-critical — data was already saved */
+ }
+ };
+
+ const saveEdit = async (modelId: string) => {
+ if (!editingModelId || editingModelId !== modelId) return;
+ if (!editingEndpoints.length) {
+ notify.error("Select at least one supported endpoint");
+ return;
+ }
+
+ setSavingModelId(modelId);
+ try {
+ const model = customModels.find((m) => m.id === modelId);
+ const res = await fetch("/api/provider-models", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: providerId,
+ modelId,
+ modelName: model?.name || modelId,
+ source: model?.source || "manual",
+ apiFormat: editingApiFormat,
+ supportedEndpoints: editingEndpoints,
+ }),
+ });
+
+ if (!res.ok) {
+ const detail = await formatProviderModelsErrorResponse(res);
+ throw new Error(detail || "Failed to save model endpoint settings");
+ }
+
+ await fetchCustomModels();
+ onModelsChanged?.();
+ notify.success("Saved model endpoint settings");
+ cancelEdit();
+ } catch (e) {
+ console.error("Failed to save custom model:", e);
+ notify.error(
+ e instanceof Error && e.message ? e.message : "Failed to save model endpoint settings"
+ );
+ } finally {
+ setSavingModelId(null);
+ }
+ };
+
+ return (
+ <div className="mt-6 pt-6 border-t border-border">
+ <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
+ <span className="material-symbols-outlined text-base text-primary">tune</span>
+ {t("customModels")}
+ </h3>
+ <p className="text-xs text-text-muted mb-3">{t("customModelsHint")}</p>
+
+ {/* Add form */}
+ <div className="flex flex-col gap-3 mb-3">
+ <div className="flex items-end gap-2">
+ <div className="flex-1">
+ <label htmlFor="custom-model-id" className="text-xs text-text-muted mb-1 block">
+ {t("modelId")}
+ </label>
+ <input
+ id="custom-model-id"
+ type="text"
+ value={newModelId}
+ onChange={(e) => setNewModelId(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleAdd()}
+ placeholder={t("customModelPlaceholder")}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ />
+ </div>
+ <div className="w-40">
+ <label htmlFor="custom-model-name" className="text-xs text-text-muted mb-1 block">
+ {t("displayName")}
+ </label>
+ <input
+ id="custom-model-name"
+ type="text"
+ value={newModelName}
+ onChange={(e) => setNewModelName(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleAdd()}
+ placeholder={t("optional")}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ />
+ </div>
+ <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModelId.trim() || adding}>
+ {adding ? t("adding") : t("add")}
+ </Button>
+ </div>
+
+ {/* API Format + Supported Endpoints */}
+ <div className="flex items-end gap-4 flex-wrap">
+ <div className="w-48">
+ <label htmlFor="custom-api-format" className="text-xs text-text-muted mb-1 block">
+ API Format
+ </label>
+ <select
+ id="custom-api-format"
+ value={newApiFormat}
+ onChange={(e) => setNewApiFormat(e.target.value)}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ >
+ <option value="chat-completions">{t("chatCompletions")}</option>
+ <option value="responses">{t("responsesApi")}</option>
+ <option value="embeddings">{t("embeddings")}</option>
+ <option value="rerank">Rerank</option>
+ <option value="audio-transcriptions">{t("audioTranscriptions")}</option>
+ <option value="audio-speech">{t("audioSpeech")}</option>
+ <option value="images-generations">{t("imagesGenerations")}</option>
+ </select>
+ </div>
+ <div className="flex-1">
+ <span className="text-xs text-text-muted mb-1 block">
+ {t("supportedEndpointsLabel")}
+ </span>
+ <div className="flex items-center gap-3">
+ {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (
+ <label
+ key={ep}
+ className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer"
+ >
+ <input
+ type="checkbox"
+ checked={newEndpoints.includes(ep)}
+ onChange={(e) => {
+ if (e.target.checked) {
+ setNewEndpoints((prev) => [...prev, ep]);
+ } else {
+ setNewEndpoints((prev) => prev.filter((x) => x !== ep));
+ }
+ }}
+ className="rounded border-border"
+ />
+ {ep === "chat"
+ ? `💬 ${t("supportedEndpointChat")}`
+ : ep === "embeddings"
+ ? `📐 ${t("supportedEndpointEmbeddings")}`
+ : ep === "rerank"
+ ? "Rerank"
+ : ep === "images"
+ ? `🖼️ ${t("supportedEndpointImages")}`
+ : `🔊 ${t("supportedEndpointAudio")}`}
+ </label>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* List */}
+ {loading ? (
+ <p className="text-xs text-text-muted">{t("loading")}</p>
+ ) : customModels.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ {customModels.map((model) => {
+ const fullModel = `${providerAlias}/${model.id}`;
+ const copyKey = `custom-${model.id}`;
+ return (
+ <div
+ key={model.id}
+ className="flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-sidebar/50"
+ >
+ {editingModelId !== model.id && (
+ <span className="material-symbols-outlined text-base text-primary shrink-0">
+ tune
+ </span>
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium truncate">{model.name || model.id}</p>
+ <div className="flex items-center gap-1 mt-1 flex-wrap">
+ <code className="text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded">
+ {fullModel}
+ </code>
+ <button
+ onClick={() => onCopy(fullModel, copyKey)}
+ className="p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary"
+ title={t("copyModel")}
+ >
+ <span className="material-symbols-outlined text-sm">
+ {copied === copyKey ? "check" : "content_copy"}
+ </span>
+ </button>
+ {model.apiFormat === "responses" && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 font-medium">
+ {t("responses")}
+ </span>
+ )}
+ {model.supportedEndpoints?.includes("embeddings") && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-purple-500/15 text-purple-400 font-medium">
+ {`📐 ${t("supportedEndpointEmbeddings")}`}
+ </span>
+ )}
+ {model.supportedEndpoints?.includes("images") && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-400 font-medium">
+ {`🖼️ ${t("imagesShortLabel")}`}
+ </span>
+ )}
+ {model.supportedEndpoints?.includes("audio") && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 font-medium">
+ {`🔊 ${t("audioShortLabel")}`}
+ </span>
+ )}
+ {anyNormalizeCompatBadge(model.id!, customMap, overrideMap) && (
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded-full bg-slate-500/15 text-slate-400 font-medium"
+ title={t("normalizeToolCallIdLabel")}
+ >
+ ID×9
+ </span>
+ )}
+ {anyNoPreserveCompatBadge(model.id!, customMap, overrideMap) && (
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded-full bg-cyan-500/15 text-cyan-400 font-medium"
+ title={t("compatDoNotPreserveDeveloper")}
+ >
+ {t("compatBadgeNoPreserve")}
+ </span>
+ )}
+ {anyUpstreamHeadersBadge(model.id!, customMap, overrideMap) && (
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded-full bg-violet-500/15 text-violet-400 font-medium"
+ title={t("compatUpstreamHeadersLabel")}
+ >
+ {t("compatBadgeUpstreamHeaders")}
+ </span>
+ )}
+ </div>
+
+ {editingModelId === model.id && (
+ <div className="mt-3 min-w-0 max-w-full rounded-lg border border-border bg-muted p-3 dark:bg-zinc-900">
+ <div className="flex min-w-0 flex-wrap items-end gap-x-3 gap-y-2">
+ <div className="w-[11rem] shrink-0 min-w-0">
+ <label className="text-xs text-text-muted mb-1 block">
+ {t("apiFormatLabel")}
+ </label>
+ <select
+ value={editingApiFormat}
+ onChange={(e) => setEditingApiFormat(e.target.value)}
+ className="w-full px-2.5 py-2 text-xs border border-border rounded-lg bg-background text-text-main focus:outline-none focus:border-primary"
+ >
+ <option value="chat-completions">{t("chatCompletions")}</option>
+ <option value="responses">{t("responsesApi")}</option>
+ <option value="embeddings">{t("embeddings")}</option>
+ <option value="rerank">Rerank</option>
+ <option value="audio-transcriptions">
+ {t("audioTranscriptions")}
+ </option>
+ <option value="audio-speech">{t("audioSpeech")}</option>
+ <option value="images-generations">{t("imagesGenerations")}</option>
+ </select>
+ </div>
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1 overflow-x-auto overflow-y-visible [scrollbar-width:thin]">
+ <span className="text-xs text-text-muted shrink-0">
+ {t("supportedEndpointsLabel")}
+ </span>
+ <div className="flex flex-wrap items-center gap-x-2 sm:gap-x-3 gap-y-1 min-w-0">
+ {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (
+ <label
+ key={ep}
+ className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer whitespace-nowrap"
+ >
+ <input
+ type="checkbox"
+ checked={editingEndpoints.includes(ep)}
+ onChange={(e) => {
+ if (e.target.checked) {
+ setEditingEndpoints((prev) =>
+ prev.includes(ep) ? prev : [...prev, ep]
+ );
+ } else {
+ setEditingEndpoints((prev) => prev.filter((x) => x !== ep));
+ }
+ }}
+ className="rounded border-border"
+ />
+ {ep === "chat"
+ ? `💬 ${t("supportedEndpointChat")}`
+ : ep === "embeddings"
+ ? `📐 ${t("supportedEndpointEmbeddings")}`
+ : ep === "rerank"
+ ? "Rerank"
+ : ep === "images"
+ ? `🖼️ ${t("supportedEndpointImages")}`
+ : `🔊 ${t("supportedEndpointAudio")}`}
+ </label>
+ ))}
+ </div>
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-2 pb-0.5">
+ <Button
+ size="sm"
+ onClick={() => saveEdit(model.id!)}
+ disabled={savingModelId === model.id}
+ >
+ {savingModelId === model.id ? t("saving") : t("save")}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={cancelEdit}>
+ {t("cancel")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ onClick={() => beginEdit(model)}
+ className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary"
+ title={t("edit")}
+ >
+ <span className="material-symbols-outlined text-sm">edit</span>
+ </button>
+ <ModelCompatPopover
+ t={t}
+ effectiveModelNormalize={(p) =>
+ effectiveNormalizeForProtocol(model.id!, p, customMap, overrideMap)
+ }
+ effectiveModelPreserveDeveloper={(p) =>
+ effectivePreserveForProtocol(model.id!, p, customMap, overrideMap)
+ }
+ getUpstreamHeadersRecord={(p) =>
+ effectiveUpstreamHeadersForProtocol(model.id!, p, customMap, overrideMap)
+ }
+ onCompatPatch={(protocol, payload) =>
+ saveCustomCompat(model.id!, {
+ compatByProtocol: { [protocol]: payload },
+ })
+ }
+ showDeveloperToggle
+ disabled={savingModelId === model.id}
+ />
+ <button
+ onClick={() => handleToggleHidden(model.id!, !model.isHidden)}
+ disabled={togglingModelId === model.id}
+ className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary disabled:opacity-50"
+ title={model.isHidden ? t("unhideModel") : t("hideModel")}
+ >
+ <span className="material-symbols-outlined text-sm">
+ {model.isHidden ? "visibility_off" : "visibility"}
+ </span>
+ </button>
+ <button
+ onClick={() => handleRemove(model.id!)}
+ className="rounded p-1 text-red-500 hover:bg-red-50"
+ title={t("removeCustomModel")}
+ >
+ <span className="material-symbols-outlined text-sm">delete</span>
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-xs text-text-muted">{t("noCustomModels")}</p>
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/ModelCompatPopover.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/ModelCompatPopover.tsx
new file mode 100644
index 0000000000..0943cb63a0
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/ModelCompatPopover.tsx
@@ -0,0 +1,355 @@
+"use client";
+
+// Phase 1d extraction — Issue #3501
+// ModelCompatPopover and its local helper (recordToHeaderRows) moved out of
+// ProviderDetailPageClient.tsx. Leaf deps: @/shared + providerPageHelpers.
+
+import { useState, useEffect, useLayoutEffect, useCallback, useRef } from "react";
+import { createPortal } from "react-dom";
+import { Input, Toggle } from "@/shared/components";
+import { MODEL_COMPAT_PROTOCOL_KEYS } from "@/shared/constants/modelCompat";
+import {
+ upstreamHeadersRecordsEqual,
+ UPSTREAM_HEADERS_UI_MAX,
+ headerRowsToRecord,
+ compatProtocolLabelKey,
+ type HeaderDraftRow,
+} from "../providerPageHelpers";
+
+// ---------------------------------------------------------------------------
+// Local helper — only used by this component
+// ---------------------------------------------------------------------------
+
+function recordToHeaderRows(rec: Record<string, string>, genId: () => string): HeaderDraftRow[] {
+ const entries = Object.entries(rec).filter(([k]) => k.trim());
+ if (entries.length === 0) return [{ id: genId(), name: "", value: "" }];
+ return entries.map(([name, value]) => ({ id: genId(), name, value }));
+}
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export interface ModelCompatPopoverProps {
+ t: (key: string) => string;
+ effectiveModelNormalize: (protocol: string) => boolean;
+ effectiveModelPreserveDeveloper: (protocol: string) => boolean;
+ getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
+ onCompatPatch: (
+ protocol: string,
+ payload: {
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ }
+ ) => void;
+ showDeveloperToggle?: boolean;
+ compact?: boolean;
+ disabled?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export default function ModelCompatPopover({
+ t,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ onCompatPatch,
+ showDeveloperToggle = true,
+ compact = false,
+ disabled,
+}: ModelCompatPopoverProps) {
+ const [open, setOpen] = useState(false);
+ const [protocol, setProtocol] = useState<string>(MODEL_COMPAT_PROTOCOL_KEYS[0]);
+ const [headerRows, setHeaderRows] = useState<HeaderDraftRow[]>([]);
+ const [valuePeekRowId, setValuePeekRowId] = useState<string | null>(null);
+ const [valueFocusRowId, setValueFocusRowId] = useState<string | null>(null);
+ const ref = useRef<HTMLDivElement>(null);
+ const panelRef = useRef<HTMLDivElement | null>(null);
+ const [portalPanelRect, setPortalPanelRect] = useState<{
+ top?: number;
+ bottom?: number;
+ left: number;
+ width: number;
+ } | null>(null);
+ const headerRowIdRef = useRef(0);
+ const headerRowsRef = useRef<HeaderDraftRow[]>([]);
+ headerRowsRef.current = headerRows;
+
+ const genHeaderRowId = () => {
+ headerRowIdRef.current += 1;
+ return `uh-${headerRowIdRef.current}`;
+ };
+
+ const normalizeToolCallId = effectiveModelNormalize(protocol);
+ const preserveDeveloperRole = effectiveModelPreserveDeveloper(protocol);
+ const devToggle = showDeveloperToggle && protocol !== "claude";
+
+ const tryCommitHeaderRows = useCallback(
+ (rows: HeaderDraftRow[]) => {
+ const parsed = headerRowsToRecord(rows);
+ const current = getUpstreamHeadersRecord(protocol);
+ if (upstreamHeadersRecordsEqual(parsed, current)) return;
+ onCompatPatch(protocol, { upstreamHeaders: parsed });
+ },
+ [getUpstreamHeadersRecord, onCompatPatch, protocol]
+ );
+
+ const onHeaderFieldBlur = useCallback(() => {
+ queueMicrotask(() => tryCommitHeaderRows(headerRowsRef.current));
+ }, [tryCommitHeaderRows]);
+
+ useEffect(() => {
+ if (!open) return;
+ return () => {
+ tryCommitHeaderRows(headerRowsRef.current);
+ };
+ }, [open, tryCommitHeaderRows]);
+
+ useEffect(() => {
+ if (!open) return;
+ const rec = getUpstreamHeadersRecord(protocol);
+ setHeaderRows(recordToHeaderRows(rec, genHeaderRowId));
+ // Only re-load rows when opening or switching protocol — not when the parent passes a new
+ // inline callback every render (would wipe in-progress edits).
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- see above
+ }, [open, protocol]);
+
+ useEffect(() => {
+ setValuePeekRowId(null);
+ setValueFocusRowId(null);
+ }, [open, protocol]);
+
+ const namedHeaderCount = headerRows.filter((r) => r.name.trim()).length;
+ const canAddHeaderRow = namedHeaderCount < UPSTREAM_HEADERS_UI_MAX;
+
+ const updateHeaderRow = (id: string, patch: Partial<Pick<HeaderDraftRow, "name" | "value">>) => {
+ setHeaderRows((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
+ };
+
+ const addHeaderRow = () => {
+ if (!canAddHeaderRow) return;
+ setHeaderRows((prev) => [...prev, { id: genHeaderRowId(), name: "", value: "" }]);
+ };
+
+ const removeHeaderRow = (id: string) => {
+ setHeaderRows((prev) => {
+ const next = prev.filter((r) => r.id !== id);
+ const normalized = next.length === 0 ? [{ id: genHeaderRowId(), name: "", value: "" }] : next;
+ queueMicrotask(() => tryCommitHeaderRows(normalized));
+ return normalized;
+ });
+ };
+
+ useEffect(() => {
+ if (!open) return;
+ const onDocClick = (e: MouseEvent) => {
+ const target = e.target as Node;
+ const insideTrigger = ref.current?.contains(target);
+ const insidePanel = panelRef.current?.contains(target);
+ if (!insideTrigger && !insidePanel) setOpen(false);
+ };
+ document.addEventListener("mousedown", onDocClick);
+ return () => document.removeEventListener("mousedown", onDocClick);
+ }, [open]);
+
+ const updatePortalPanelRect = useCallback(() => {
+ if (!open || !ref.current) return;
+ const rect = ref.current.getBoundingClientRect();
+ const margin = 10;
+ const width = Math.min(window.innerWidth - 2 * margin, 24 * 16);
+ let left = rect.right - width;
+ left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
+ // Estimated panel height: capped at min(82vh, 42rem=672px)
+ const estimatedPanelHeight = Math.min(window.innerHeight * 0.82, 672);
+ const spaceBelow = window.innerHeight - rect.bottom - margin;
+ const spaceAbove = rect.top - margin;
+ if (spaceBelow < estimatedPanelHeight && spaceAbove > spaceBelow) {
+ // Not enough space below — open upward
+ setPortalPanelRect({ bottom: window.innerHeight - rect.top + 8, left, width });
+ } else {
+ setPortalPanelRect({ top: rect.bottom + 8, left, width });
+ }
+ }, [open]);
+
+ useLayoutEffect(() => {
+ if (!open) {
+ setPortalPanelRect(null);
+ return;
+ }
+ updatePortalPanelRect();
+ window.addEventListener("resize", updatePortalPanelRect);
+ window.addEventListener("scroll", updatePortalPanelRect, true);
+ return () => {
+ window.removeEventListener("resize", updatePortalPanelRect);
+ window.removeEventListener("scroll", updatePortalPanelRect, true);
+ };
+ }, [open, updatePortalPanelRect]);
+
+ const panelChromeClass =
+ "flex max-h-[min(82vh,42rem)] flex-col overflow-hidden rounded-xl border-2 border-zinc-200 bg-white shadow-2xl dark:border-zinc-600 dark:bg-zinc-950";
+
+ return (
+ <div className="relative inline-flex" ref={ref}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ disabled={disabled}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg border border-border bg-background text-text-muted hover:bg-muted hover:text-text-main disabled:opacity-50 transition-colors"
+ title={t("compatAdjustmentsTitle")}
+ >
+ <span className="material-symbols-outlined text-base leading-none">tune</span>
+ {!compact && t("compatButtonLabel")}
+ </button>
+ {open &&
+ typeof document !== "undefined" &&
+ portalPanelRect &&
+ createPortal(
+ <div
+ ref={panelRef}
+ className={panelChromeClass}
+ style={{
+ position: "fixed",
+ ...(portalPanelRect.top !== undefined
+ ? { top: portalPanelRect.top }
+ : { bottom: portalPanelRect.bottom }),
+ left: portalPanelRect.left,
+ width: portalPanelRect.width,
+ zIndex: 10040,
+ }}
+ >
+ <div className="shrink-0 border-b-2 border-zinc-200 bg-zinc-100 px-3 py-2.5 dark:border-zinc-600 dark:bg-zinc-900">
+ <p className="text-xs font-semibold text-text-main">{t("compatAdjustmentsTitle")}</p>
+ <p className="text-[11px] text-text-muted mt-1 leading-relaxed">
+ {t("compatProtocolHint")}
+ </p>
+ </div>
+ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto bg-white p-3 [scrollbar-gutter:stable] [scrollbar-width:thin] dark:bg-zinc-950">
+ <label className="block text-[11px] font-medium text-text-muted mb-1.5">
+ {t("compatProtocolLabel")}
+ </label>
+ <select
+ value={protocol}
+ onChange={(e) => setProtocol(e.target.value)}
+ disabled={disabled}
+ className="mb-4 w-full rounded-lg border border-zinc-200 bg-white px-2.5 py-2 text-xs text-text-main focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30 dark:border-zinc-600 dark:bg-zinc-900"
+ >
+ {MODEL_COMPAT_PROTOCOL_KEYS.map((p) => (
+ <option key={p} value={p}>
+ {t(compatProtocolLabelKey(p))}
+ </option>
+ ))}
+ </select>
+ <div className="flex flex-col gap-3.5">
+ <Toggle
+ size="sm"
+ label={t("compatToolIdShort")}
+ title={t("normalizeToolCallIdLabel")}
+ checked={normalizeToolCallId}
+ onChange={(v) => onCompatPatch(protocol, { normalizeToolCallId: v })}
+ disabled={disabled}
+ />
+ {devToggle && (
+ <Toggle
+ size="sm"
+ label={t("compatDoNotPreserveDeveloper")}
+ title={t("preserveDeveloperRoleLabel")}
+ checked={preserveDeveloperRole === false}
+ onChange={(checked) =>
+ onCompatPatch(protocol, { preserveOpenAIDeveloperRole: !checked })
+ }
+ disabled={disabled}
+ />
+ )}
+ </div>
+
+ <div className="mt-4 rounded-lg border-2 border-zinc-200 bg-zinc-100 p-3 dark:border-zinc-600 dark:bg-zinc-900">
+ <label className="block text-[11px] font-semibold text-text-main mb-1">
+ {t("compatUpstreamHeadersLabel")}
+ </label>
+ <p className="text-[11px] text-text-muted mb-3 leading-relaxed">
+ {t("compatUpstreamHeadersHint")}
+ </p>
+ <div className="space-y-2">
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-end text-[10px] font-medium uppercase tracking-wide text-text-muted px-0.5">
+ <span>{t("compatUpstreamHeaderName")}</span>
+ <span className="col-span-1">{t("compatUpstreamHeaderValue")}</span>
+ <span className="w-8 shrink-0" aria-hidden />
+ </div>
+ {headerRows.map((row) => (
+ <div
+ key={row.id}
+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-center"
+ >
+ <Input
+ value={row.name}
+ onChange={(e) => updateHeaderRow(row.id, { name: e.target.value })}
+ onBlur={onHeaderFieldBlur}
+ disabled={disabled}
+ placeholder={t("compatUpstreamHeaderNamePlaceholder")}
+ className="gap-0 min-w-0"
+ inputClassName="h-9 bg-white py-1.5 px-2 text-xs font-mono dark:bg-zinc-900"
+ autoComplete="off"
+ />
+ <div
+ className="min-w-0"
+ onMouseEnter={() => setValuePeekRowId(row.id)}
+ onMouseLeave={() =>
+ setValuePeekRowId((cur) => (cur === row.id ? null : cur))
+ }
+ >
+ <Input
+ type={
+ valuePeekRowId === row.id || valueFocusRowId === row.id
+ ? "text"
+ : "password"
+ }
+ value={row.value}
+ onChange={(e) => updateHeaderRow(row.id, { value: e.target.value })}
+ onFocus={() => setValueFocusRowId(row.id)}
+ onBlur={() => {
+ setValueFocusRowId((cur) => (cur === row.id ? null : cur));
+ onHeaderFieldBlur();
+ }}
+ disabled={disabled}
+ placeholder={t("compatUpstreamHeaderValuePlaceholder")}
+ className="gap-0 min-w-0"
+ inputClassName="h-9 bg-white py-1.5 px-2 text-xs dark:bg-zinc-900"
+ autoComplete="off"
+ spellCheck={false}
+ />
+ </div>
+ <button
+ type="button"
+ disabled={disabled || headerRows.length <= 1}
+ onClick={() => removeHeaderRow(row.id)}
+ title={t("compatUpstreamRemoveRow")}
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/80 text-text-muted hover:bg-red-500/10 hover:text-red-600 dark:hover:text-red-400 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-text-muted transition-colors"
+ >
+ <span className="material-symbols-outlined text-lg leading-none">
+ close
+ </span>
+ </button>
+ </div>
+ ))}
+ </div>
+ <button
+ type="button"
+ disabled={disabled || !canAddHeaderRow}
+ onClick={addHeaderRow}
+ className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-border py-2 text-xs font-medium text-primary hover:bg-primary/5 disabled:opacity-40 disabled:hover:bg-transparent transition-colors"
+ >
+ <span className="material-symbols-outlined text-base leading-none">add</span>
+ {t("compatUpstreamAddRow")}
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/ModelRow.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/ModelRow.tsx
new file mode 100644
index 0000000000..1b51365760
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/ModelRow.tsx
@@ -0,0 +1,330 @@
+"use client";
+/**
+ * ModelRow — Issue #3501 Phase 1e
+ *
+ * Extracted from ProviderDetailPageClient.tsx. Contains:
+ * - ModelSourceBadge (tiny utility)
+ * - ModelVisibilityToolbar (filter/test toolbar)
+ * - ModelRow (catalog model row with compat controls)
+ *
+ * Leaf component: imports from shared, leaf helpers, and sibling components.
+ * Never imports from ProviderDetailPageClient.
+ */
+import React from "react";
+import {
+ getModelCatalogSourceLabel,
+ normalizeModelCatalogSource,
+} from "@/shared/utils/modelCatalogSearch";
+import { providerText } from "../providerPageHelpers";
+import ModelCompatPopover from "./ModelCompatPopover";
+
+// ---------------------------------------------------------------------------
+// Shared prop types
+// ---------------------------------------------------------------------------
+
+/** PATCH fields for provider model compat (matches API + `ModelCompatPerProtocol` shape). */
+export type ModelCompatSavePatch = {
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ compatByProtocol?: Record<
+ string,
+ {
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ }
+ >;
+ isHidden?: boolean;
+};
+
+// ---------------------------------------------------------------------------
+// ModelSourceBadge
+// ---------------------------------------------------------------------------
+
+function getModelSourceBadgeClass(source?: string): string {
+ switch (normalizeModelCatalogSource(source)) {
+ case "imported":
+ return "border-sky-500/30 bg-sky-500/10 text-sky-300";
+ case "custom":
+ return "border-emerald-500/30 bg-emerald-500/10 text-emerald-300";
+ case "fallback":
+ return "border-amber-500/30 bg-amber-500/10 text-amber-300";
+ case "alias":
+ return "border-violet-500/30 bg-violet-500/10 text-violet-300";
+ case "system":
+ default:
+ return "border-border bg-sidebar/70 text-text-muted";
+ }
+}
+
+export function ModelSourceBadge({ source }: { source?: string }) {
+ return (
+ <span
+ className={`rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide ${getModelSourceBadgeClass(
+ source
+ )}`}
+ >
+ {getModelCatalogSourceLabel(source)}
+ </span>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// ModelVisibilityToolbar
+// ---------------------------------------------------------------------------
+
+export interface ModelVisibilityToolbarProps {
+ t: ((key: string, values?: Record<string, unknown>) => string) & {
+ has?: (key: string) => boolean;
+ };
+ filterValue: string;
+ onFilterChange: (value: string) => void;
+ activeCount: number;
+ totalCount: number;
+ onSelectAll: () => void;
+ onDeselectAll: () => void;
+ selectAllDisabled?: boolean;
+ deselectAllDisabled?: boolean;
+ onTestAll?: () => void;
+ testingAll?: boolean;
+ testProgress?: { done: number; total: number } | null;
+ visibilityFilter?: "all" | "visible" | "hidden";
+ onVisibilityFilterChange?: (filter: "all" | "visible" | "hidden") => void;
+ autoHideFailed?: boolean;
+ onAutoHideFailedChange?: (v: boolean) => void;
+}
+
+export function ModelVisibilityToolbar({
+ t,
+ filterValue,
+ onFilterChange,
+ activeCount: _activeCount,
+ totalCount: _totalCount,
+ onSelectAll,
+ onDeselectAll,
+ selectAllDisabled,
+ deselectAllDisabled,
+ onTestAll,
+ testingAll,
+ testProgress,
+ visibilityFilter,
+ onVisibilityFilterChange,
+ autoHideFailed,
+ onAutoHideFailedChange,
+}: ModelVisibilityToolbarProps) {
+ return (
+ <div className="mb-3 flex flex-wrap items-center gap-2">
+ <div className="relative min-w-[220px] flex-1">
+ <span className="material-symbols-outlined pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[15px] text-text-muted">
+ search
+ </span>
+ <input
+ type="text"
+ value={filterValue}
+ onChange={(e) => onFilterChange(e.target.value)}
+ placeholder={providerText(t, "filterModels", "Filter models…")}
+ className="w-full rounded-lg border border-border bg-sidebar/50 py-1.5 pl-7 pr-3 text-xs text-text-main placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ {visibilityFilter !== undefined && onVisibilityFilterChange && (
+ <div className="flex items-center gap-1 rounded-lg border border-border bg-sidebar/50 p-0.5">
+ {(["all", "visible", "hidden"] as const).map((f) => (
+ <button
+ key={f}
+ onClick={() => onVisibilityFilterChange(f)}
+ className={`rounded px-2 py-1 text-xs ${
+ visibilityFilter === f
+ ? "bg-primary text-primary-foreground"
+ : "text-text-muted hover:text-text-main"
+ }`}
+ >
+ {f === "all"
+ ? providerText(t, "showAllModels", "All")
+ : f === "visible"
+ ? providerText(t, "showVisibleOnly", "Visible")
+ : providerText(t, "showHiddenOnly", "Hidden")}
+ </button>
+ ))}
+ </div>
+ )}
+ {onAutoHideFailedChange && (
+ <label className="flex items-center gap-1.5 text-xs text-text-muted">
+ <input
+ type="checkbox"
+ checked={autoHideFailed ?? false}
+ onChange={(e) => onAutoHideFailedChange(e.target.checked)}
+ className="rounded border-border bg-sidebar"
+ />
+ {providerText(t, "hideFailedAuto", "Auto-hide failed")}
+ </label>
+ )}
+ {onTestAll && (
+ <button
+ onClick={onTestAll}
+ disabled={testingAll}
+ className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
+ title={providerText(t, "testAllModels", "Test all")}
+ >
+ <span className="material-symbols-outlined text-[16px]">
+ {testingAll ? "progress_activity" : "science"}
+ </span>
+ <span>
+ {testingAll && testProgress
+ ? providerText(t, "testingAllModels", "Testing {done}/{total}", testProgress)
+ : providerText(t, "testAllModels", "Test all")}
+ </span>
+ </button>
+ )}
+ <button
+ onClick={onSelectAll}
+ disabled={selectAllDisabled}
+ className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
+ title={providerText(t, "showAllModels", "Show all")}
+ >
+ <span className="material-symbols-outlined text-[16px]">visibility</span>
+ <span>{providerText(t, "showAllModels", "Show all")}</span>
+ </button>
+ <button
+ onClick={onDeselectAll}
+ disabled={deselectAllDisabled}
+ className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
+ title={providerText(t, "hideAllModels", "Hide all")}
+ >
+ <span className="material-symbols-outlined text-[16px]">visibility_off</span>
+ <span>{providerText(t, "hideAllModels", "Hide all")}</span>
+ </button>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// ModelRow
+// ---------------------------------------------------------------------------
+
+export interface ModelRowProps {
+ model: { id: string; name?: string; source?: string; isHidden?: boolean };
+ fullModel: string;
+ provider: string;
+ copied?: string;
+ onCopy: (text: string, key: string) => void;
+ t: (key: string, values?: Record<string, unknown>) => string;
+ showDeveloperToggle?: boolean;
+ effectiveModelNormalize: (modelId: string, protocol?: string) => boolean;
+ effectiveModelPreserveDeveloper: (modelId: string, protocol?: string) => boolean;
+ saveModelCompatFlags: (modelId: string, patch: ModelCompatSavePatch) => void;
+ getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
+ compatDisabled?: boolean;
+ onToggleHidden?: (modelId: string, hidden: boolean) => Promise<void>;
+ togglingHidden?: boolean;
+ onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
+ testStatus?: "ok" | "error" | null;
+ testingModel?: boolean;
+}
+
+export default function ModelRow({
+ model,
+ fullModel,
+ copied,
+ onCopy,
+ t,
+ showDeveloperToggle = true,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ saveModelCompatFlags,
+ compatDisabled,
+ onToggleHidden,
+ togglingHidden,
+ onTestModel,
+ testStatus,
+ testingModel,
+}: ModelRowProps) {
+ const isHidden = Boolean(model.isHidden);
+ return (
+ <div
+ className={`flex min-w-[220px] max-w-md items-center gap-2 rounded-lg border border-border px-3 py-2 hover:bg-sidebar/50 transition-opacity ${
+ isHidden ? "opacity-50" : ""
+ }`}
+ >
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
+ <span
+ className="material-symbols-outlined shrink-0 text-base"
+ style={{ color: isHidden ? "var(--color-text-muted)" : undefined }}
+ >
+ smart_toy
+ </span>
+ <code className="rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted">
+ {fullModel}
+ </code>
+ <ModelSourceBadge source={model.source} />
+ <button
+ onClick={() => onCopy(fullModel, `model-${model.id}`)}
+ className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary"
+ title={t("copyModel")}
+ >
+ <span className="material-symbols-outlined text-sm">
+ {copied === `model-${model.id}` ? "check" : "content_copy"}
+ </span>
+ </button>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {onTestModel && (
+ <button
+ onClick={() => onTestModel(model.id, fullModel)}
+ disabled={testingModel}
+ className={`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}`}
+ title={
+ testingModel
+ ? t("testingModel")
+ : testStatus === "ok"
+ ? "OK"
+ : testStatus === "error"
+ ? "Error"
+ : t("testModel")
+ }
+ >
+ {testingModel ? (
+ <span className="material-symbols-outlined text-sm animate-spin">
+ progress_activity
+ </span>
+ ) : testStatus === "ok" ? (
+ <span className="material-symbols-outlined text-sm">check_circle</span>
+ ) : testStatus === "error" ? (
+ <span className="material-symbols-outlined text-sm">error</span>
+ ) : (
+ <span className="material-symbols-outlined text-sm">play_circle</span>
+ )}
+ </button>
+ )}
+ {onToggleHidden && (
+ <button
+ onClick={() => onToggleHidden(model.id, !isHidden)}
+ disabled={togglingHidden}
+ className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary disabled:opacity-40 disabled:cursor-not-allowed"
+ title={
+ isHidden
+ ? providerText(t, "showModel", "Show model")
+ : providerText(t, "hideModel", "Hide model")
+ }
+ >
+ <span className="material-symbols-outlined text-sm">
+ {isHidden ? "visibility_off" : "visibility"}
+ </span>
+ </button>
+ )}
+ <ModelCompatPopover
+ t={t}
+ effectiveModelNormalize={(p) => effectiveModelNormalize(model.id, p)}
+ effectiveModelPreserveDeveloper={(p) => effectiveModelPreserveDeveloper(model.id, p)}
+ getUpstreamHeadersRecord={getUpstreamHeadersRecord}
+ onCompatPatch={(protocol, payload) =>
+ saveModelCompatFlags(model.id, { compatByProtocol: { [protocol]: payload } })
+ }
+ showDeveloperToggle={showDeveloperToggle}
+ disabled={compatDisabled}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelRow.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelRow.tsx
new file mode 100644
index 0000000000..27de2c6c9e
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelRow.tsx
@@ -0,0 +1,178 @@
+"use client";
+/**
+ * PassthroughModelRow — Issue #3501 Phase 1e
+ *
+ * Extracted from ProviderDetailPageClient.tsx. Renders one row in the
+ * passthrough / compatible models list.
+ *
+ * Leaf component: imports from shared, leaf helpers, and sibling components.
+ * Never imports from ProviderDetailPageClient.
+ */
+import React from "react";
+import { Badge } from "@/shared/components";
+import { providerText } from "../providerPageHelpers";
+import ModelCompatPopover from "./ModelCompatPopover";
+import { ModelSourceBadge, type ModelCompatSavePatch } from "./ModelRow";
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export interface PassthroughModelRowProps {
+ modelId: string;
+ fullModel: string;
+ source?: string;
+ isFree?: boolean;
+ isHidden?: boolean;
+ copied?: string;
+ onCopy: (text: string, key: string) => void;
+ onDeleteAlias?: () => void;
+ t: (key: string, values?: Record<string, unknown>) => string;
+ showDeveloperToggle?: boolean;
+ effectiveModelNormalize: (modelId: string, protocol?: string) => boolean;
+ effectiveModelPreserveDeveloper: (modelId: string, protocol?: string) => boolean;
+ saveModelCompatFlags: (modelId: string, patch: ModelCompatSavePatch) => void;
+ getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
+ compatDisabled?: boolean;
+ onToggleHidden?: (modelId: string, hidden: boolean) => Promise<void>;
+ togglingHidden?: boolean;
+ onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
+ testStatus?: "ok" | "error" | null;
+ testingModel?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export default function PassthroughModelRow({
+ modelId,
+ fullModel,
+ source,
+ isFree,
+ isHidden,
+ copied,
+ onCopy,
+ onDeleteAlias,
+ t,
+ showDeveloperToggle = true,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ saveModelCompatFlags,
+ compatDisabled,
+ onToggleHidden,
+ togglingHidden,
+ onTestModel,
+ testStatus,
+ testingModel,
+}: PassthroughModelRowProps) {
+ return (
+ <div
+ className={`flex min-w-0 flex-col gap-2 rounded-lg border border-border px-3.5 py-3 transition-opacity hover:bg-sidebar/50 ${
+ isHidden ? "opacity-50" : ""
+ }`}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="material-symbols-outlined shrink-0 text-base text-text-muted"
+ style={{ color: isHidden ? "var(--color-text-muted)" : undefined }}
+ >
+ smart_toy
+ </span>
+ <code
+ className="min-w-0 truncate rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted"
+ title={fullModel}
+ >
+ {fullModel}
+ </code>
+ </div>
+ <div className="flex min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">
+ <ModelSourceBadge source={source} />
+ {isFree && (
+ <Badge variant="success" className="shrink-0 px-1.5 py-0 text-[10px]">
+ {providerText(t, "freeBadge", "Free")}
+ </Badge>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ onClick={() => onCopy(fullModel, `model-${modelId}`)}
+ className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary"
+ title={t("copyModel")}
+ >
+ <span className="material-symbols-outlined text-sm">
+ {copied === `model-${modelId}` ? "check" : "content_copy"}
+ </span>
+ </button>
+ {onTestModel && (
+ <button
+ onClick={() => onTestModel(modelId, fullModel)}
+ disabled={testingModel}
+ className={`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}`}
+ title={
+ testingModel
+ ? t("testingModel")
+ : testStatus === "ok"
+ ? "OK"
+ : testStatus === "error"
+ ? "Error"
+ : t("testModel")
+ }
+ >
+ {testingModel ? (
+ <span className="material-symbols-outlined text-sm animate-spin">
+ progress_activity
+ </span>
+ ) : testStatus === "ok" ? (
+ <span className="material-symbols-outlined text-sm">check_circle</span>
+ ) : testStatus === "error" ? (
+ <span className="material-symbols-outlined text-sm">error</span>
+ ) : (
+ <span className="material-symbols-outlined text-sm">play_circle</span>
+ )}
+ </button>
+ )}
+ {onToggleHidden && (
+ <button
+ onClick={() => onToggleHidden(modelId, !isHidden)}
+ disabled={togglingHidden}
+ className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary disabled:cursor-not-allowed disabled:opacity-40"
+ title={
+ isHidden
+ ? providerText(t, "showModel", "Show model")
+ : providerText(t, "hideModel", "Hide model")
+ }
+ >
+ <span className="material-symbols-outlined text-sm">
+ {isHidden ? "visibility_off" : "visibility"}
+ </span>
+ </button>
+ )}
+ <ModelCompatPopover
+ t={t}
+ effectiveModelNormalize={(p) => effectiveModelNormalize(modelId, p)}
+ effectiveModelPreserveDeveloper={(p) => effectiveModelPreserveDeveloper(modelId, p)}
+ getUpstreamHeadersRecord={getUpstreamHeadersRecord}
+ onCompatPatch={(protocol, payload) =>
+ saveModelCompatFlags(modelId, { compatByProtocol: { [protocol]: payload } })
+ }
+ showDeveloperToggle={showDeveloperToggle}
+ compact
+ disabled={compatDisabled}
+ />
+ {onDeleteAlias && (
+ <button
+ onClick={onDeleteAlias}
+ className="rounded p-1 text-red-500 hover:bg-red-50"
+ title={t("removeModel")}
+ >
+ <span className="material-symbols-outlined text-sm">delete</span>
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelsSection.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelsSection.tsx
new file mode 100644
index 0000000000..222016da5d
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/PassthroughModelsSection.tsx
@@ -0,0 +1,421 @@
+"use client";
+/**
+ * PassthroughModelsSection — Issue #3501 Phase 1e
+ *
+ * Extracted from ProviderDetailPageClient.tsx. Renders the full "passthrough
+ * models" panel for non-compatible providers (OpenRouter, etc.).
+ *
+ * Preserves the Bug #3610 fix intact:
+ * - autoHideFailed is threaded from the outer component (shared checkbox).
+ * - buildPassthroughTestBody / shouldSwitchToVisibleFilter come from the
+ * leaf helper providerPageHelpers.ts.
+ *
+ * Never imports from ProviderDetailPageClient.
+ */
+import React, { useState, useMemo } from "react";
+import { Button } from "@/shared/components";
+import { matchesModelCatalogQuery, normalizeModelCatalogSource } from "@/shared/utils/modelCatalogSearch";
+import { useNotificationStore } from "@/store/notificationStore";
+import {
+ buildCompatMap,
+ providerText,
+ buildPassthroughTestBody,
+ shouldSwitchToVisibleFilter,
+ type CompatModelRow,
+ type CompatByProtocolMap,
+} from "../providerPageHelpers";
+import { ModelVisibilityToolbar } from "./ModelRow";
+import PassthroughModelRow from "./PassthroughModelRow";
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export type ModelCompatSavePatchPassthrough = {
+ normalizeToolCallId?: boolean;
+ preserveDeveloperRole?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+};
+
+export interface PassthroughModelsSectionProps {
+ providerAlias: string;
+ modelAliases: Record<string, string>;
+ availableModels?: CompatModelRow[];
+ customModels?: CompatModelRow[];
+ description: string;
+ inputLabel: string;
+ inputPlaceholder: string;
+ copied?: string;
+ onCopy: (text: string, key: string) => void;
+ onSetAlias: (modelId: string, alias: string) => Promise<void>;
+ onDeleteAlias: (alias: string) => void;
+ t: (key: string, values?: Record<string, unknown>) => string;
+ effectiveModelNormalize: (alias: string) => boolean;
+ effectiveModelPreserveDeveloper: (alias: string) => boolean;
+ getUpstreamHeadersRecord: (modelId: string, protocol: string) => Record<string, string>;
+ saveModelCompatFlags: (
+ modelId: string,
+ flags: ModelCompatSavePatchPassthrough
+ ) => Promise<void>;
+ compatSavingModelId?: string;
+ isModelHidden: (modelId: string) => boolean;
+ onToggleHidden: (modelId: string, hidden: boolean) => Promise<void>;
+ onBulkToggleHidden: (modelIds: string[], hidden: boolean) => Promise<void>;
+ bulkTogglePending?: boolean;
+ togglingModelId?: string | null;
+ onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
+ modelTestStatus?: Record<string, "ok" | "error" | null>;
+ testingModelId?: string | null;
+ providerId: string;
+ connectionId: string;
+ /** Controlled from the outer component so both sections share one checkbox (#3610). */
+ autoHideFailed?: boolean;
+ onAutoHideFailedChange?: (v: boolean) => void;
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export default function PassthroughModelsSection({
+ providerAlias,
+ modelAliases,
+ availableModels = [],
+ customModels = [],
+ description,
+ inputLabel,
+ inputPlaceholder,
+ copied,
+ onCopy,
+ onSetAlias,
+ onDeleteAlias,
+ t,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ saveModelCompatFlags,
+ compatSavingModelId,
+ isModelHidden,
+ onToggleHidden,
+ onBulkToggleHidden,
+ bulkTogglePending,
+ togglingModelId,
+ onTestModel,
+ modelTestStatus,
+ testingModelId,
+ providerId,
+ connectionId,
+ // Bug #3610 fix 1: use the prop value when provided; fall back to local state only
+ // when the outer component does not pass the prop (backward-compat / standalone use).
+ autoHideFailed: autoHideFailedProp,
+ onAutoHideFailedChange,
+}: PassthroughModelsSectionProps) {
+ const [newModel, setNewModel] = useState("");
+ const [adding, setAdding] = useState(false);
+ const [modelFilter, setModelFilter] = useState("");
+ const [testingAll, setTestingAll] = useState(false);
+ const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);
+ const [localAutoHideFailed, setLocalAutoHideFailed] = useState(true);
+ const autoHideFailed = autoHideFailedProp !== undefined ? autoHideFailedProp : localAutoHideFailed;
+ const setAutoHideFailed = onAutoHideFailedChange ?? setLocalAutoHideFailed;
+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
+ const notify = useNotificationStore();
+ const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);
+
+ const handleTestAll = async () => {
+ const modelsToTest = filteredModels.filter((m) => !m.isHidden);
+ if (modelsToTest.length === 0) {
+ notify.error(providerText(t, "noModelsToTest", "No models to test"));
+ return;
+ }
+ setTestingAll(true);
+ setTestProgress({ done: 0, total: modelsToTest.length });
+
+ let ok = 0;
+ let error = 0;
+ let hiddenCount = 0;
+
+ for (const model of modelsToTest) {
+ try {
+ const result: {
+ results?: Record<
+ string,
+ {
+ status?: "ok" | "error";
+ rateLimited?: boolean;
+ isTimeout?: boolean;
+ error?: string;
+ }
+ >;
+ } = await fetch("/api/models/test-all", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ // Bug #3610 fix 2: pass autoHideFailed so the server persists the hide
+ body: JSON.stringify(
+ buildPassthroughTestBody({
+ providerId,
+ connectionId,
+ modelId: model.modelId,
+ autoHideFailed,
+ })
+ ),
+ }).then((r) => r.json());
+
+ const entry = result.results?.[model.modelId];
+ if (entry?.status === "ok") {
+ ok++;
+ } else {
+ error++;
+ if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {
+ await onToggleHidden(model.modelId, true);
+ hiddenCount++;
+ }
+ }
+ } catch (e) {
+ error++;
+ }
+ setTestProgress((prev) => (prev ? { done: prev.done + 1, total: prev.total } : null));
+ }
+
+ notify.info(providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error }));
+ if (hiddenCount > 0) {
+ notify.info(providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount }));
+ // Bug #3610 fix 3: switch to "visible" filter so hidden models disappear on-screen
+ if (shouldSwitchToVisibleFilter({ autoHideFailed, hiddenCount })) {
+ setVisibilityFilter("visible");
+ }
+ }
+ setTestingAll(false);
+ setTestProgress(null);
+ };
+
+ const providerAliases = useMemo(
+ () =>
+ Object.entries(modelAliases).filter(([, model]: [string, any]) =>
+ (model as string).startsWith(`${providerAlias}/`)
+ ),
+ [modelAliases, providerAlias]
+ );
+
+ const allModels = useMemo(() => {
+ const prefix = `${providerAlias}/`;
+ const aliasByModelId = new Map<string, string>();
+ const fullModelByModelId = new Map<string, string>();
+ const rows: Array<{
+ modelId: string;
+ fullModel: string;
+ alias: string | null;
+ displayName: string;
+ source: string;
+ isFree: boolean;
+ isHidden: boolean;
+ }> = [];
+ const seenModelIds = new Set<string>();
+
+ for (const [alias, fullModel] of providerAliases) {
+ const fmStr = fullModel as string;
+ const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
+ aliasByModelId.set(modelId, alias as string);
+ fullModelByModelId.set(modelId, fmStr);
+ }
+
+ const addModel = (model: CompatModelRow, source: string) => {
+ if (!model?.id || seenModelIds.has(model.id)) return;
+ const fullModel = fullModelByModelId.get(model.id) || `${providerAlias}/${model.id}`;
+ rows.push({
+ modelId: model.id,
+ fullModel,
+ alias: aliasByModelId.get(model.id) || null,
+ displayName: model.name || model.id,
+ source,
+ isFree:
+ Boolean((model as any).free) ||
+ model.id.endsWith(":free") ||
+ /\bgr[aá]tis\b|\bfree\b/i.test(model.name || ""),
+ isHidden: isModelHidden(model.id),
+ });
+ seenModelIds.add(model.id);
+ };
+
+ for (const model of availableModels) {
+ addModel(model, "imported");
+ }
+
+ for (const model of customModels) {
+ addModel(
+ model,
+ normalizeModelCatalogSource(model.source) === "imported" ? "imported" : "custom"
+ );
+ }
+
+ for (const [alias, fullModel] of providerAliases) {
+ const fmStr = fullModel as string;
+ const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
+ if (!modelId || seenModelIds.has(modelId)) continue;
+ const customModel = customModelMap.get(modelId);
+ rows.push({
+ modelId,
+ fullModel: fmStr,
+ alias: alias as string,
+ displayName: alias as string,
+ source: customModel ? customModel.source || "custom" : "alias",
+ isFree:
+ modelId.endsWith(":free") ||
+ Boolean((customModel as any)?.free) ||
+ /\bgr[aá]tis\b|\bfree\b/i.test(customModel?.name || alias || ""),
+ isHidden: isModelHidden(modelId),
+ });
+ seenModelIds.add(modelId);
+ }
+
+ return rows;
+ }, [
+ availableModels,
+ customModelMap,
+ customModels,
+ isModelHidden,
+ providerAlias,
+ providerAliases,
+ ]);
+
+ const filteredModels = allModels.filter((model) => {
+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {
+ modelId: model.modelId,
+ modelName: model.displayName,
+ alias: model.alias,
+ source: model.source,
+ });
+
+ const matchesVisibility =
+ visibilityFilter === "all"
+ ? true
+ : visibilityFilter === "visible"
+ ? !model.isHidden
+ : model.isHidden;
+
+ return matchesQuery && matchesVisibility;
+ });
+ const activeCount = allModels.filter((model) => !model.isHidden).length;
+
+ // Generate default alias from modelId (last part after /)
+ const generateDefaultAlias = (modelId: string) => {
+ const parts = modelId.split("/");
+ return parts[parts.length - 1];
+ };
+
+ const handleAdd = async () => {
+ if (!newModel.trim() || adding) return;
+ const modelId = newModel.trim();
+ const defaultAlias = generateDefaultAlias(modelId);
+
+ // Check if alias already exists
+ if (modelAliases[defaultAlias]) {
+ alert(t("aliasExistsAlert", { alias: defaultAlias }));
+ return;
+ }
+
+ setAdding(true);
+ try {
+ await onSetAlias(modelId, defaultAlias);
+ setNewModel("");
+ } catch (error) {
+ console.error("Error adding model:", error);
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-text-muted">{description}</p>
+
+ {/* Add new model */}
+ <div className="flex items-end gap-2">
+ <div className="flex-1">
+ <label htmlFor="new-model-input" className="text-xs text-text-muted mb-1 block">
+ {inputLabel}
+ </label>
+ <input
+ id="new-model-input"
+ type="text"
+ value={newModel}
+ onChange={(e) => setNewModel(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleAdd()}
+ placeholder={inputPlaceholder}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ />
+ </div>
+ <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModel.trim() || adding}>
+ {adding ? t("adding") : t("add")}
+ </Button>
+ </div>
+
+ {/* Models list */}
+ {allModels.length > 0 && (
+ <div className="flex flex-col gap-3">
+ <ModelVisibilityToolbar
+ t={t}
+ filterValue={modelFilter}
+ onFilterChange={setModelFilter}
+ activeCount={activeCount}
+ totalCount={allModels.length}
+ onSelectAll={() =>
+ onBulkToggleHidden(
+ filteredModels.map((m) => m.modelId),
+ false
+ )
+ }
+ onDeselectAll={() =>
+ onBulkToggleHidden(
+ filteredModels.map((m) => m.modelId),
+ true
+ )
+ }
+ selectAllDisabled={bulkTogglePending || filteredModels.length === 0}
+ deselectAllDisabled={bulkTogglePending || filteredModels.length === 0}
+ onTestAll={handleTestAll}
+ testingAll={testingAll}
+ visibilityFilter={visibilityFilter}
+ onVisibilityFilterChange={setVisibilityFilter}
+ autoHideFailed={autoHideFailed}
+ onAutoHideFailedChange={setAutoHideFailed}
+ />
+ <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ {filteredModels.map(({ modelId, fullModel, alias, isHidden, source, isFree }) => (
+ <PassthroughModelRow
+ key={fullModel as string}
+ modelId={modelId}
+ fullModel={fullModel}
+ source={source}
+ isFree={isFree}
+ isHidden={isHidden}
+ copied={copied}
+ onCopy={onCopy}
+ onDeleteAlias={source === "alias" && alias ? () => onDeleteAlias(alias) : undefined}
+ t={t}
+ showDeveloperToggle
+ effectiveModelNormalize={effectiveModelNormalize}
+ effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
+ getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecord(modelId, p)}
+ saveModelCompatFlags={saveModelCompatFlags}
+ compatDisabled={compatSavingModelId === modelId}
+ onToggleHidden={onToggleHidden}
+ togglingHidden={togglingModelId === modelId}
+ onTestModel={onTestModel}
+ testStatus={modelTestStatus?.[modelId] || null}
+ testingModel={testingModelId === modelId}
+ />
+ ))}
+ </div>
+ {filteredModels.length === 0 && modelFilter && (
+ <p className="py-2 text-sm text-text-muted">
+ {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
+ filter: modelFilter,
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/SiliconFlowEndpointModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/SiliconFlowEndpointModal.tsx
new file mode 100644
index 0000000000..bf04e500fb
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/SiliconFlowEndpointModal.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+// Phase 1d extraction — Issue #3501
+// SiliconFlowEndpointModal moved out of ProviderDetailPageClient.tsx.
+
+import { useTranslations } from "next-intl";
+import { Modal } from "@/shared/components";
+import { providerText, SILICONFLOW_ENDPOINTS } from "../providerPageHelpers";
+
+interface SiliconFlowEndpointModalProps {
+ isOpen: boolean;
+ onSelect: (baseUrl: string) => void;
+ onClose: () => void;
+}
+
+export default function SiliconFlowEndpointModal({
+ isOpen,
+ onSelect,
+ onClose,
+}: SiliconFlowEndpointModalProps) {
+ const t = useTranslations("providers");
+
+ return (
+ <Modal
+ isOpen={isOpen}
+ title={providerText(t, "connectSiliconFlow", "Connect SiliconFlow")}
+ onClose={onClose}
+ size="lg"
+ >
+ <div className="space-y-3">
+ <p className="text-sm text-text-muted mb-4">
+ {providerText(t, "chooseSiliconFlowEndpoint", "Choose your SiliconFlow endpoint:")}
+ </p>
+ {SILICONFLOW_ENDPOINTS.map((endpoint) => (
+ <button
+ key={endpoint.id}
+ type="button"
+ onClick={() => onSelect(endpoint.baseUrl)}
+ className="w-full p-4 text-left border border-border rounded-lg hover:bg-sidebar transition-colors"
+ >
+ <div className="flex items-start gap-3">
+ <span className="material-symbols-outlined text-primary mt-0.5">public</span>
+ <div className="flex-1">
+ <h3 className="font-semibold mb-1">
+ {providerText(
+ t,
+ endpoint.id === "siliconflow" ? "endpointGlobal" : "endpointChina",
+ endpoint.label
+ )}
+ </h3>
+ <p className="text-sm text-text-muted font-mono">{endpoint.baseUrl}</p>
+ </div>
+ </div>
+ </button>
+ ))}
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/WebSessionCredentialGuide.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/WebSessionCredentialGuide.tsx
new file mode 100644
index 0000000000..f4f30ddce9
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/WebSessionCredentialGuide.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+// Issue #3501 Phase 1c — extracted from the god-component.
+// Shared by AddApiKeyModal and EditConnectionModal; imports only leaf modules
+// (no cycle risk).
+
+import type { WebSessionCredentialRequirement } from "../webSessionCredentials";
+import { providerText, type ProviderMessageTranslator } from "../providerPageHelpers";
+
+export interface WebSessionCredentialGuideProps {
+ requirement: WebSessionCredentialRequirement;
+ providerName: string;
+ t: ProviderMessageTranslator;
+}
+
+export default function WebSessionCredentialGuide({
+ requirement,
+ providerName,
+ t,
+}: WebSessionCredentialGuideProps) {
+ if (requirement.kind === "none") {
+ return (
+ <div className="rounded-lg border border-emerald-500/25 bg-emerald-500/10 px-3 py-3 text-sm text-text-muted">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-emerald-500">
+ check_circle
+ </span>
+ <div>
+ <p className="font-medium text-text-main">
+ {providerText(t, "webNoAuthGuideTitle", "No credential required")}
+ </p>
+ <p className="mt-1">
+ {providerText(
+ t,
+ "webNoAuthGuideBody",
+ "{provider} does not need an API key or cookie. Save the connection to use its free web endpoint.",
+ { provider: providerName }
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const requiredCredentialKey =
+ requirement.kind === "token" ? "webTokenRequiredCredential" : "webCookieRequiredCredential";
+ const requiredCredentialFallback =
+ requirement.kind === "token" ? "Required token: {credential}" : "Required cookie: {credential}";
+
+ return (
+ <div className="rounded-lg border border-purple-500/25 bg-purple-500/10 px-3 py-3 text-sm text-text-muted">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-purple-500">cookie</span>
+ <div className="space-y-2">
+ <div>
+ <p className="font-medium text-text-main">
+ {providerText(t, "webSessionGuideTitle", "How to get the session credential")}
+ </p>
+ <p className="mt-1">
+ {providerText(
+ t,
+ "webSessionGuideIntro",
+ "{provider} uses a browser web session instead of an API key.",
+ { provider: providerName }
+ )}
+ </p>
+ </div>
+ <p className="font-medium text-text-main">
+ {providerText(t, requiredCredentialKey, requiredCredentialFallback, {
+ credential: requirement.credentialName,
+ })}
+ </p>
+ <ol className="list-decimal space-y-1 pl-5">
+ <li>
+ {providerText(t, "webSessionGuideStep1", "Sign in to {provider} in your browser.", {
+ provider: providerName,
+ })}
+ </li>
+ <li>
+ {providerText(
+ t,
+ "webSessionGuideStep2",
+ "Open the browser developer tools and inspect a request made by the web app."
+ )}
+ </li>
+ <li>
+ {providerText(
+ t,
+ "webSessionGuideStep3",
+ "Copy the required credential from the provider's own domain. For cookies, copy only the Cookie header value and omit Cookie:.",
+ { credential: requirement.credentialName }
+ )}
+ </li>
+ <li>
+ {providerText(
+ t,
+ "webSessionGuideStep4",
+ "Paste it here and check the connection. If it stops working, sign in again and replace it with a fresh value."
+ )}
+ </li>
+ </ol>
+ <p className="text-xs text-amber-700 dark:text-amber-300">
+ {providerText(
+ t,
+ "webSessionSecurityHint",
+ "Treat this like a password: it may access your signed-in web account until it expires or is revoked."
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/__tests__/phase1d.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/__tests__/phase1d.test.tsx
new file mode 100644
index 0000000000..ae3cdacb47
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/__tests__/phase1d.test.tsx
@@ -0,0 +1,202 @@
+// @vitest-environment jsdom
+//
+// Phase 1d regression tests for Issue #3501.
+// ConnectionRow, ModelCompatPopover, and SiliconFlowEndpointModal were extracted
+// from the god-component. This proves each mounts in isolation with its clean
+// Props interface (Hard Rule #8, Rule #18 TDD gate).
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import ConnectionRow from "../ConnectionRow";
+import ModelCompatPopover from "../ModelCompatPopover";
+import SiliconFlowEndpointModal from "../SiliconFlowEndpointModal";
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "openai" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+}));
+vi.mock("next-intl", () => ({
+ useTranslations: () => (k: string) => k,
+}));
+
+// Minimal store stubs
+vi.mock("@/store/emailPrivacyStore", () => ({
+ default: () => true,
+}));
+vi.mock("@/store/notificationStore", () => ({
+ useNotificationStore: () => ({ add: vi.fn() }),
+}));
+
+const cleanups: Array<() => void> = [];
+
+function renderComponent(node: React.ReactElement) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(node));
+ cleanups.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+ return container;
+}
+
+describe("phase-1d extractions (#3501)", () => {
+ beforeEach(() => {
+ (
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve({ ok: true, json: async () => ({}), text: async () => "" } as Response)
+ )
+ );
+ vi.stubGlobal("localStorage", {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ clear: () => undefined,
+ });
+ });
+
+ afterEach(() => {
+ while (cleanups.length) cleanups.pop()?.();
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ });
+
+ // ── ConnectionRow ──────────────────────────────────────────────────────────
+
+ it("ConnectionRow mounts with minimal required props (API-key connection)", () => {
+ const conn = {
+ id: "conn-1",
+ name: "My Key",
+ isActive: true,
+ priority: 1,
+ };
+ const c = renderComponent(
+ <ConnectionRow
+ connection={conn}
+ isOAuth={false}
+ isFirst={true}
+ isLast={false}
+ onMoveUp={vi.fn()}
+ onMoveDown={vi.fn()}
+ onToggleActive={vi.fn()}
+ onToggleRateLimit={vi.fn()}
+ onRetest={vi.fn()}
+ onEdit={vi.fn()}
+ onDelete={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ it("ConnectionRow mounts as OAuth connection (isClaude=true)", () => {
+ const conn = {
+ id: "conn-2",
+ email: "[email protected]",
+ isActive: true,
+ priority: 2,
+ };
+ const c = renderComponent(
+ <ConnectionRow
+ connection={conn}
+ isOAuth={true}
+ isClaude={true}
+ isFirst={false}
+ isLast={true}
+ onMoveUp={vi.fn()}
+ onMoveDown={vi.fn()}
+ onToggleActive={vi.fn()}
+ onToggleRateLimit={vi.fn()}
+ onRetest={vi.fn()}
+ onEdit={vi.fn()}
+ onDelete={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ it("ConnectionRow renders cooldown badge when rateLimitedUntil is in the future", () => {
+ const conn = {
+ id: "conn-3",
+ name: "Rate-limited Key",
+ isActive: true,
+ priority: 1,
+ rateLimitedUntil: new Date(Date.now() + 60000).toISOString(),
+ testStatus: "unavailable",
+ };
+ const c = renderComponent(
+ <ConnectionRow
+ connection={conn}
+ isOAuth={false}
+ isFirst={true}
+ isLast={true}
+ onMoveUp={vi.fn()}
+ onMoveDown={vi.fn()}
+ onToggleActive={vi.fn()}
+ onToggleRateLimit={vi.fn()}
+ onRetest={vi.fn()}
+ onEdit={vi.fn()}
+ onDelete={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ // ── ModelCompatPopover ─────────────────────────────────────────────────────
+
+ it("ModelCompatPopover mounts in closed state without throwing", () => {
+ const c = renderComponent(
+ <ModelCompatPopover
+ t={(k: string) => k}
+ effectiveModelNormalize={() => false}
+ effectiveModelPreserveDeveloper={() => true}
+ getUpstreamHeadersRecord={() => ({})}
+ onCompatPatch={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ it("ModelCompatPopover mounts with compact=true and disabled=true", () => {
+ const c = renderComponent(
+ <ModelCompatPopover
+ t={(k: string) => k}
+ effectiveModelNormalize={() => true}
+ effectiveModelPreserveDeveloper={() => false}
+ getUpstreamHeadersRecord={() => ({ "X-Custom": "value" })}
+ onCompatPatch={vi.fn()}
+ compact={true}
+ disabled={true}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ // ── SiliconFlowEndpointModal ───────────────────────────────────────────────
+
+ it("SiliconFlowEndpointModal mounts when isOpen=false (renders nothing visible)", () => {
+ const c = renderComponent(
+ <SiliconFlowEndpointModal
+ isOpen={false}
+ onSelect={vi.fn()}
+ onClose={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+
+ it("SiliconFlowEndpointModal mounts when isOpen=true without throwing", () => {
+ const c = renderComponent(
+ <SiliconFlowEndpointModal
+ isOpen={true}
+ onSelect={vi.fn()}
+ onClose={vi.fn()}
+ />
+ );
+ expect(c).toBeDefined();
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal.tsx
new file mode 100644
index 0000000000..df432143dc
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal.tsx
@@ -0,0 +1,842 @@
+"use client";
+
+// Issue #3501 Phase 1c — extracted from the god-component.
+// ~787-LOC modal for adding a new API key / credential to a provider.
+
+import { useState, useEffect, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { Button, Badge, Input, Modal, Toggle } from "@/shared/components";
+import {
+ providerAllowsOptionalApiKey,
+ supportsBulkApiKey,
+} from "@/shared/constants/providers";
+import { parseBulkApiKeys } from "@/shared/utils/bulkApiKeyParser";
+import {
+ isBaseUrlConfigurableProvider,
+ getProviderBaseUrlDefault,
+ getProviderBaseUrlHint,
+ getProviderBaseUrlPlaceholder,
+ isGlmProvider,
+ parseRoutingTagsInput,
+ parseExcludedModelsInput,
+ getWebSessionCredentialLabel,
+ getWebSessionCredentialHint,
+ getWebSessionCredentialCheckLabel,
+ getAddCredentialModalTitle,
+ getLocalProviderMetadata,
+ normalizeAndValidateHttpBaseUrl,
+ extractCommandCodeCredentialInput,
+ providerText,
+ type CommandCodeAuthFlowState,
+} from "../../providerPageHelpers";
+import { getWebSessionCredentialRequirement } from "../../webSessionCredentials";
+import WebSessionCredentialGuide from "../WebSessionCredentialGuide";
+
+export interface AddApiKeyModalProps {
+ isOpen: boolean;
+ provider?: string;
+ providerName?: string;
+ initialBaseUrl?: string;
+ isCompatible?: boolean;
+ isAnthropic?: boolean;
+ isCcCompatible?: boolean;
+ isCommandCode?: boolean;
+ commandCodeAuthState?: CommandCodeAuthFlowState;
+ onStartCommandCodeAuth?: () => void;
+ onSave: (data: {
+ name: string;
+ apiKey?: string;
+ priority: number;
+ baseUrl?: string;
+ providerSpecificData?: Record<string, unknown>;
+ }) => Promise<void | unknown>;
+ onClose: () => void;
+}
+
+export default function AddApiKeyModal({
+ isOpen,
+ provider,
+ providerName,
+ initialBaseUrl,
+ isCompatible,
+ isAnthropic,
+ isCcCompatible,
+ isCommandCode,
+ commandCodeAuthState,
+ onStartCommandCodeAuth,
+ onSave,
+ onClose,
+}: AddApiKeyModalProps) {
+ const t = useTranslations("providers");
+ const usesBaseUrl = isBaseUrlConfigurableProvider(provider);
+ const defaultBaseUrl = getProviderBaseUrlDefault(provider);
+ const isVertex = provider === "vertex" || provider === "vertex-partner";
+ const isBedrock = provider === "bedrock";
+ const showsRegion = isVertex || isBedrock;
+ const defaultRegion = isBedrock ? "eu-west-2" : "us-central1";
+ const isGlm = isGlmProvider(provider);
+ const isQoder = provider === "qoder";
+ const isCloudflare = provider === "cloudflare-ai";
+ const localProviderMetadata = getLocalProviderMetadata(provider);
+ const isLocalSelfHostedProvider = !!localProviderMetadata;
+ const isGooglePse = provider === "google-pse-search";
+ const webSessionCredential = getWebSessionCredentialRequirement(provider);
+ const isNoAuthWebSessionCredential = webSessionCredential?.kind === "none";
+ const isWebSessionCredential = !!webSessionCredential && webSessionCredential.kind !== "none";
+ const providerDisplayName = providerName || provider || "";
+ const apiKeyOptional =
+ providerAllowsOptionalApiKey(provider) || Boolean(isNoAuthWebSessionCredential);
+ const commandCodeAuthPhaseLabel = commandCodeAuthState
+ ? {
+ idle: "Ready",
+ starting: "Starting…",
+ polling: "Waiting for browser…",
+ received: "Browser approved",
+ applying: "Applying key…",
+ applied: "Connected",
+ expired: "Link expired",
+ error: "Connection failed",
+ }[commandCodeAuthState.phase]
+ : null;
+
+ const [formData, setFormData] = useState({
+ name: "",
+ apiKey: "",
+ priority: 1,
+ baseUrl: initialBaseUrl || defaultBaseUrl,
+ cx: "",
+ region: showsRegion ? defaultRegion : "",
+ apiRegion: "international",
+ validationModelId: "",
+ routingTags: "",
+ excludedModels: "",
+ customUserAgent: "",
+ accountId: "",
+ consoleApiKey: "",
+ ccCompatibleContext1m: false,
+ passthroughModels: false,
+ });
+ const [validating, setValidating] = useState(false);
+ const [validationResult, setValidationResult] = useState(null);
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+ const [showAdvanced, setShowAdvanced] = useState(false);
+ const [copiedCommandCodeField, setCopiedCommandCodeField] = useState<string | null>(null);
+ const wasOpenRef = useRef(false);
+
+ useEffect(() => {
+ const wasOpen = wasOpenRef.current;
+ wasOpenRef.current = isOpen;
+ if (!isOpen || wasOpen) return;
+ setFormData((current) => ({
+ ...current,
+ baseUrl: initialBaseUrl || defaultBaseUrl,
+ }));
+ }, [defaultBaseUrl, initialBaseUrl, isOpen]);
+
+ const bulkSupported = supportsBulkApiKey(provider);
+ const [mode, setMode] = useState<"single" | "bulk">("single");
+ const [bulkText, setBulkText] = useState("");
+ const [bulkValidateKeys, setBulkValidateKeys] = useState(false);
+ const [bulkResult, setBulkResult] = useState<{
+ success: number;
+ failed: number;
+ total: number;
+ errors: Array<{ index: number; name: string; message: string }>;
+ } | null>(null);
+ const [bulkWarnings, setBulkWarnings] = useState<string[]>([]);
+ const apiCredentialLabel = isQoder
+ ? t("personalAccessTokenLabel")
+ : webSessionCredential
+ ? getWebSessionCredentialLabel(t, webSessionCredential, apiKeyOptional)
+ : apiKeyOptional
+ ? `${t("apiKeyLabel")} (${t("optional").toLowerCase()})`
+ : t("apiKeyLabel");
+ const apiCredentialPlaceholder = isVertex
+ ? t("vertexServiceAccountPlaceholder")
+ : isWebSessionCredential
+ ? webSessionCredential.placeholder
+ : isQoder
+ ? t("qoderPatPlaceholder")
+ : apiKeyOptional
+ ? t("optional")
+ : undefined;
+ const apiCredentialHint = isQoder
+ ? t("qoderPatHint")
+ : isWebSessionCredential
+ ? getWebSessionCredentialHint(t, webSessionCredential, providerDisplayName, false)
+ : isLocalSelfHostedProvider
+ ? t("localProviderApiKeyOptionalHint", {
+ provider: localProviderMetadata?.name || providerName || provider || "",
+ })
+ : apiKeyOptional
+ ? t("apiKeyOptionalHint")
+ : undefined;
+ const credentialValidationFailedMessage = isWebSessionCredential
+ ? providerText(
+ t,
+ "webSessionCredentialValidationFailed",
+ "Session credential validation failed. Sign in again, copy a fresh credential, and try again."
+ )
+ : t("apiKeyValidationFailed");
+
+ const handleValidate = async () => {
+ setValidating(true);
+ setSaveError(null);
+ try {
+ const credentialInput = isCommandCode
+ ? extractCommandCodeCredentialInput(formData.apiKey)
+ : formData.apiKey;
+ const res = await fetch("/api/providers/validate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider,
+ apiKey: credentialInput,
+ validationModelId: formData.validationModelId || undefined,
+ customUserAgent: formData.customUserAgent.trim() || undefined,
+ baseUrl: formData.baseUrl.trim() || undefined,
+ region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
+ cx: formData.cx.trim() || undefined,
+ }),
+ });
+ const data = await res.json();
+ setValidationResult(data.valid ? "success" : "failed");
+ } catch {
+ setValidationResult("failed");
+ } finally {
+ setValidating(false);
+ }
+ };
+
+ const copyCommandCodeValue = async (value: string | undefined, key: string) => {
+ if (!value) return;
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopiedCommandCodeField(key);
+ window.setTimeout(() => setCopiedCommandCodeField(null), 1500);
+ } catch {
+ setSaveError("Copy failed. Select the text and copy it manually.");
+ }
+ };
+
+ const handleSubmit = async () => {
+ const credentialInput = isCommandCode
+ ? extractCommandCodeCredentialInput(formData.apiKey)
+ : formData.apiKey;
+ if (!provider || (!isCompatible && !apiKeyOptional && !credentialInput)) return;
+
+ setSaving(true);
+ setSaveError(null);
+ try {
+ if (isGooglePse && !formData.cx.trim()) {
+ setSaveError(t("searchEngineIdRequired"));
+ return;
+ }
+
+ let validatedBaseUrl = null;
+ if (usesBaseUrl) {
+ const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
+ if (checked.error) {
+ setSaveError(checked.error);
+ return;
+ }
+ validatedBaseUrl = checked.value;
+ }
+
+ let isValid = Boolean(isNoAuthWebSessionCredential && !credentialInput);
+ let validationError: string | null = null;
+ if (!isValid) {
+ try {
+ setValidating(true);
+ setValidationResult(null);
+ const res = await fetch("/api/providers/validate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider,
+ apiKey: credentialInput,
+ validationModelId: formData.validationModelId || undefined,
+ customUserAgent: formData.customUserAgent.trim() || undefined,
+ baseUrl: formData.baseUrl.trim() || undefined,
+ region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
+ cx: formData.cx.trim() || undefined,
+ }),
+ });
+ const data = await res.json();
+ isValid = !!data.valid;
+ if (!isValid && data.error) {
+ validationError = data.error;
+ }
+ setValidationResult(isValid ? "success" : "failed");
+ } catch {
+ setValidationResult("failed");
+ } finally {
+ setValidating(false);
+ }
+ }
+
+ if (!isValid) {
+ if (apiKeyOptional && !credentialInput) {
+ // Bypass validation block for local/optional providers when no key is provided
+ console.debug("Validation failed but apiKey is optional; proceeding to save.");
+ } else {
+ setSaveError(validationError || credentialValidationFailedMessage);
+ return;
+ }
+ }
+
+ const providerSpecificData: Record<string, unknown> = {};
+ if (formData.customUserAgent.trim()) {
+ providerSpecificData.customUserAgent = formData.customUserAgent.trim();
+ }
+ if (formData.routingTags.trim()) {
+ providerSpecificData.tags = parseRoutingTagsInput(formData.routingTags);
+ }
+ if (formData.excludedModels.trim()) {
+ providerSpecificData.excludedModels = parseExcludedModelsInput(formData.excludedModels);
+ }
+ if (formData.passthroughModels) {
+ providerSpecificData.passthroughModels = true;
+ }
+ if (provider === "bailian-coding-plan" && formData.consoleApiKey.trim()) {
+ providerSpecificData.consoleApiKey = formData.consoleApiKey.trim();
+ }
+ if (isGooglePse && formData.cx.trim()) {
+ providerSpecificData.cx = formData.cx.trim();
+ }
+ if (usesBaseUrl) {
+ providerSpecificData.baseUrl = validatedBaseUrl;
+ } else if (showsRegion) {
+ providerSpecificData.region = formData.region.trim() || defaultRegion;
+ } else if (isGlm) {
+ providerSpecificData.apiRegion = formData.apiRegion;
+ } else if (isCloudflare && formData.accountId.trim()) {
+ providerSpecificData.accountId = formData.accountId.trim();
+ }
+ if (isCcCompatible && formData.ccCompatibleContext1m) {
+ providerSpecificData.requestDefaults = { context1m: true };
+ }
+
+ const payload = {
+ name: formData.name,
+ apiKey: credentialInput.trim() || undefined,
+ priority: formData.priority,
+ testStatus: "active",
+ providerSpecificData:
+ Object.keys(providerSpecificData).length > 0 ? providerSpecificData : undefined,
+ };
+
+ const error = await onSave(payload);
+ if (error) {
+ setSaveError(typeof error === "string" ? error : t("failedSaveConnection"));
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleBulkSubmit = async () => {
+ if (!provider) return;
+ const parsed = parseBulkApiKeys(bulkText);
+ setBulkWarnings(parsed.warnings);
+ if (parsed.entries.length === 0) return;
+
+ setSaving(true);
+ setBulkResult(null);
+ setSaveError(null);
+
+ try {
+ let providerSpecificData: Record<string, unknown> | undefined;
+ if (usesBaseUrl) {
+ const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
+ if (checked.error) {
+ setSaveError(checked.error);
+ return;
+ }
+ providerSpecificData = { baseUrl: checked.value };
+ }
+
+ const res = await fetch("/api/providers/bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider,
+ entries: parsed.entries.map((e) => ({ name: e.name, apiKey: e.apiKey })),
+ priority: formData.priority || 1,
+ providerSpecificData,
+ validateKeys: bulkValidateKeys,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) {
+ setSaveError(typeof data?.error === "string" ? data.error : t("failedSaveConnection"));
+ return;
+ }
+ setBulkResult({
+ success: data.success || 0,
+ failed: data.failed || 0,
+ total: data.total || 0,
+ errors: Array.isArray(data.errors) ? data.errors : [],
+ });
+ } catch (err) {
+ setSaveError(err instanceof Error ? err.message : t("failedSaveConnection"));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (!provider) return null;
+
+ return (
+ <Modal
+ isOpen={isOpen}
+ title={getAddCredentialModalTitle(t, providerDisplayName, webSessionCredential)}
+ onClose={onClose}
+ >
+ <div className="flex flex-col gap-4">
+ {bulkSupported && (
+ <div className="flex gap-1 border-b border-border">
+ <button
+ type="button"
+ onClick={() => {
+ setMode("single");
+ setBulkResult(null);
+ setBulkWarnings([]);
+ }}
+ className={`px-3 py-1.5 text-sm font-medium transition-colors ${
+ mode === "single"
+ ? "border-b-2 border-primary text-text-main"
+ : "text-text-muted hover:text-text-main"
+ }`}
+ >
+ {t("bulkTabSingle")}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setMode("bulk");
+ setSaveError(null);
+ }}
+ className={`px-3 py-1.5 text-sm font-medium transition-colors ${
+ mode === "bulk"
+ ? "border-b-2 border-primary text-text-main"
+ : "text-text-muted hover:text-text-main"
+ }`}
+ >
+ {t("bulkTabBulkAdd")}
+ </button>
+ </div>
+ )}
+
+ {bulkSupported && mode === "bulk" && (
+ <div className="flex flex-col gap-3">
+ <p className="text-xs text-text-muted">{t("bulkAddFormatHint")}</p>
+ <textarea
+ className="w-full rounded border border-border bg-background p-2 text-sm font-mono resize-y min-h-[140px] focus:outline-none focus:ring-1 focus:ring-primary"
+ placeholder={"name1|sk-key1\nname2|sk-key2\nsk-key-only-auto-named"}
+ value={bulkText}
+ onChange={(e) => setBulkText(e.target.value)}
+ />
+ <div className="flex items-center gap-4 flex-wrap">
+ <div className="flex items-center gap-2">
+ <label className="text-sm text-text-muted">{t("priorityLabel")}</label>
+ <input
+ type="number"
+ min={1}
+ max={100}
+ value={formData.priority}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ priority: Number.parseInt(e.target.value) || 1,
+ })
+ }
+ className="w-20 px-2 py-1 text-sm border border-border rounded bg-background"
+ />
+ </div>
+ <label className="flex items-center gap-2 text-sm text-text-muted cursor-pointer">
+ <input
+ type="checkbox"
+ checked={bulkValidateKeys}
+ onChange={(e) => setBulkValidateKeys(e.target.checked)}
+ className="rounded border-border"
+ />
+ {t("bulkValidateKeys")}
+ </label>
+ </div>
+ {bulkWarnings.length > 0 && (
+ <div className="rounded border border-amber-500/25 bg-amber-500/10 p-2 text-xs text-amber-200 space-y-1">
+ {bulkWarnings.map((w, i) => (
+ <div key={i}>{w}</div>
+ ))}
+ </div>
+ )}
+ {bulkResult && (
+ <div
+ className={`text-sm font-medium ${
+ bulkResult.failed > 0 ? "text-amber-300" : "text-emerald-400"
+ }`}
+ >
+ {t("bulkAddedCount", { count: bulkResult.success })}
+ {bulkResult.failed > 0 && (
+ <>, {t("bulkFailedCount", { count: bulkResult.failed })}</>
+ )}
+ {bulkResult.errors.length > 0 && (
+ <ul className="mt-2 list-disc pl-5 text-xs text-text-muted font-normal space-y-0.5">
+ {bulkResult.errors.slice(0, 10).map((err, i) => (
+ <li key={i}>
+ {err.name}: {err.message}
+ </li>
+ ))}
+ {bulkResult.errors.length > 10 && (
+ <li>… {bulkResult.errors.length - 10} more</li>
+ )}
+ </ul>
+ )}
+ </div>
+ )}
+ {saveError && <div className="text-sm text-rose-400">{saveError}</div>}
+ <div className="flex gap-2">
+ <Button onClick={handleBulkSubmit} fullWidth disabled={saving || !bulkText.trim()}>
+ {saving ? t("adding") : t("bulkAddAllKeys")}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {(!bulkSupported || mode === "single") && (
+ <>
+ {isCcCompatible && (
+ <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
+ warning
+ </span>
+ <p>{t("ccCompatibleValidationHint")}</p>
+ </div>
+ </div>
+ )}
+ {isCommandCode && onStartCommandCodeAuth && (
+ <div className="rounded-lg border border-sky-500/20 bg-sky-500/10 px-3 py-3 text-sm">
+ <div className="flex items-start gap-3">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-sky-500">
+ open_in_new
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="font-medium text-text-main">
+ {t("providerDetailBrowserManualConnect")}
+ </p>
+ <p className="mt-1 text-xs text-text-muted">
+ Open Command Code Studio, then paste the returned key/JSON/URL into the API
+ key field below.
+ </p>
+ {commandCodeAuthState?.message && (
+ <p className="mt-2 text-xs text-text-muted">
+ {commandCodeAuthPhaseLabel}: {commandCodeAuthState.message}
+ </p>
+ )}
+ {commandCodeAuthState?.authUrl && (
+ <div className="mt-3 space-y-2">
+ <div>
+ <p className="mb-1 text-xs font-medium text-text-main">
+ {t("providerDetailAuthUrl")}
+ </p>
+ <div className="flex gap-2">
+ <Input
+ value={commandCodeAuthState.authUrl}
+ readOnly
+ className="flex-1 font-mono text-xs"
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon={copiedCommandCodeField === "authUrl" ? "check" : "content_copy"}
+ onClick={() =>
+ copyCommandCodeValue(commandCodeAuthState.authUrl, "authUrl")
+ }
+ />
+ </div>
+ </div>
+ {commandCodeAuthState.callbackUrl && (
+ <div>
+ <p className="mb-1 text-xs font-medium text-text-main">
+ {t("providerDetailCallbackUrl")}
+ </p>
+ <div className="flex gap-2">
+ <Input
+ value={commandCodeAuthState.callbackUrl}
+ readOnly
+ className="flex-1 font-mono text-xs"
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ icon={
+ copiedCommandCodeField === "callbackUrl"
+ ? "check"
+ : "content_copy"
+ }
+ onClick={() =>
+ copyCommandCodeValue(
+ commandCodeAuthState.callbackUrl,
+ "callbackUrl"
+ )
+ }
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ <Button
+ variant="secondary"
+ size="sm"
+ icon="open_in_new"
+ loading={
+ commandCodeAuthState?.phase === "starting" ||
+ commandCodeAuthState?.phase === "polling" ||
+ commandCodeAuthState?.phase === "applying"
+ }
+ onClick={onStartCommandCodeAuth}
+ >
+ Connect in browser
+ </Button>
+ </div>
+ </div>
+ )}
+ <Input
+ label={t("nameLabel")}
+ value={formData.name}
+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ placeholder={isQoder ? t("personalAccessTokenLabel") : t("productionKey")}
+ />
+ {webSessionCredential && (
+ <WebSessionCredentialGuide
+ requirement={webSessionCredential}
+ providerName={providerDisplayName}
+ t={t}
+ />
+ )}
+ {!isNoAuthWebSessionCredential && (
+ <div className="flex gap-2">
+ <Input
+ label={apiCredentialLabel}
+ type="password"
+ value={formData.apiKey}
+ onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
+ className="flex-1"
+ placeholder={apiCredentialPlaceholder}
+ hint={apiCredentialHint}
+ autoComplete="off"
+ spellCheck={false}
+ autoCapitalize="off"
+ />
+ <div className="pt-6">
+ <Button
+ onClick={handleValidate}
+ disabled={
+ (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
+ (isGooglePse && !formData.cx.trim()) ||
+ validating ||
+ saving
+ }
+ variant="secondary"
+ >
+ {validating
+ ? t("checking")
+ : webSessionCredential
+ ? getWebSessionCredentialCheckLabel(t, webSessionCredential)
+ : t("check")}
+ </Button>
+ </div>
+ </div>
+ )}
+ {isGooglePse && (
+ <Input
+ label={t("searchEngineIdLabel")}
+ value={formData.cx}
+ onChange={(e) => setFormData({ ...formData, cx: e.target.value })}
+ placeholder="012345678901234567890:abc123xyz"
+ hint={t("searchEngineIdHint")}
+ />
+ )}
+ {validationResult && (
+ <Badge variant={validationResult === "success" ? "success" : "error"}>
+ {validationResult === "success" ? t("valid") : t("invalid")}
+ </Badge>
+ )}
+ {saveError && (
+ <div className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">
+ {saveError}
+ </div>
+ )}
+ {isCcCompatible && (
+ <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
+ <Toggle
+ checked={formData.ccCompatibleContext1m}
+ onChange={(checked) =>
+ setFormData({ ...formData, ccCompatibleContext1m: checked })
+ }
+ label={t("ccCompatibleContext1mLabel")}
+ description={t("ccCompatibleContext1mDescription")}
+ />
+ </div>
+ )}
+ {isCompatible && !isCcCompatible && (
+ <p className="text-xs text-text-muted">
+ {isAnthropic
+ ? t("validationChecksAnthropicCompatible", {
+ provider: providerName || t("anthropicCompatibleName"),
+ })
+ : t("validationChecksOpenAiCompatible", {
+ provider: providerName || t("openaiCompatibleName"),
+ })}
+ </p>
+ )}
+ <button
+ type="button"
+ className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ aria-expanded={showAdvanced}
+ aria-controls="add-api-key-advanced-settings"
+ >
+ <span
+ className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
+ aria-hidden="true"
+ >
+ ▶
+ </span>
+ {t("advancedSettings")}
+ </button>
+ {showAdvanced && (
+ <div
+ id="add-api-key-advanced-settings"
+ className="flex flex-col gap-3 pl-2 border-l-2 border-border"
+ >
+ <Input
+ label={t("customUserAgentLabel")}
+ value={formData.customUserAgent}
+ onChange={(e) => setFormData({ ...formData, customUserAgent: e.target.value })}
+ placeholder="my-app/1.0"
+ hint={t("customUserAgentHint")}
+ />
+ <Input
+ label={t("routingTagsLabel")}
+ value={formData.routingTags}
+ onChange={(e) => setFormData({ ...formData, routingTags: e.target.value })}
+ placeholder={t("routingTagsPlaceholder")}
+ hint={t("routingTagsHint")}
+ />
+ <Input
+ label={t("excludedModelsLabel")}
+ value={formData.excludedModels}
+ onChange={(e) => setFormData({ ...formData, excludedModels: e.target.value })}
+ placeholder={t("excludedModelsPlaceholder")}
+ hint={t("excludedModelsHint")}
+ />
+ <Toggle
+ size="sm"
+ checked={formData.passthroughModels}
+ onChange={(checked) => setFormData({ ...formData, passthroughModels: checked })}
+ label={t("perModelQuotaLabel")}
+ description={t("perModelQuotaDescription")}
+ />
+ {provider === "bailian-coding-plan" && (
+ <Input
+ label={t("consoleApiKeyOracleLabel")}
+ value={formData.consoleApiKey}
+ onChange={(e) => setFormData({ ...formData, consoleApiKey: e.target.value })}
+ placeholder={t("consoleApiKeyOraclePlaceholder")}
+ hint={t("consoleApiKeyOracleHint")}
+ type="password"
+ />
+ )}
+ </div>
+ )}
+ <Input
+ label={t("validationModelIdLabel")}
+ placeholder={t("validationModelIdPlaceholder")}
+ value={formData.validationModelId}
+ onChange={(e) => setFormData({ ...formData, validationModelId: e.target.value })}
+ hint={t("validationModelIdHint")}
+ />
+ <Input
+ label={t("priorityLabel")}
+ type="number"
+ value={formData.priority}
+ onChange={(e) =>
+ setFormData({ ...formData, priority: Number.parseInt(e.target.value) || 1 })
+ }
+ />
+ {usesBaseUrl && (
+ <Input
+ label={t("baseUrlLabel")}
+ value={formData.baseUrl}
+ onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
+ placeholder={getProviderBaseUrlPlaceholder(provider)}
+ hint={getProviderBaseUrlHint(provider, t)}
+ />
+ )}
+ {showsRegion && (
+ <Input
+ label={t("regionLabel")}
+ value={formData.region}
+ onChange={(e) => setFormData({ ...formData, region: e.target.value })}
+ placeholder={defaultRegion}
+ hint={t("regionHint")}
+ />
+ )}
+ {isCloudflare && (
+ <Input
+ label={t("accountIdLabel")}
+ value={formData.accountId}
+ onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
+ placeholder={t("accountIdPlaceholder")}
+ hint={t("accountIdHint")}
+ />
+ )}
+ {isGlm && (
+ <div>
+ <label className="text-sm font-medium text-text-main mb-1 block">
+ {t("apiRegionLabel")}
+ </label>
+ <select
+ value={formData.apiRegion}
+ onChange={(e) => setFormData({ ...formData, apiRegion: e.target.value })}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ >
+ <option value="international">{t("apiRegionInternational")}</option>
+ <option value="china">{t("apiRegionChina")}</option>
+ </select>
+ <p className="text-xs text-text-muted mt-1">{t("apiRegionHint")}</p>
+ </div>
+ )}
+ <div className="flex gap-2">
+ <Button
+ onClick={handleSubmit}
+ fullWidth
+ disabled={
+ !formData.name ||
+ (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
+ (isGooglePse && !formData.cx.trim()) ||
+ saving ||
+ (usesBaseUrl && !formData.baseUrl.trim() && !defaultBaseUrl)
+ }
+ >
+ {saving ? t("saving") : t("save")}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx
new file mode 100644
index 0000000000..306a0caccd
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx
@@ -0,0 +1,284 @@
+"use client";
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { Button, Badge, Input, Modal, Select } from "@/shared/components";
+import { CC_COMPATIBLE_DEFAULT_CHAT_PATH } from "../../providerDetailConstants";
+interface EditCompatibleNodeModalNode {
+ id?: string;
+ name?: string;
+ prefix?: string;
+ apiType?: string;
+ baseUrl?: string;
+ chatPath?: string;
+ modelsPath?: string;
+}
+
+interface EditCompatibleNodeModalProps {
+ isOpen: boolean;
+ node: EditCompatibleNodeModalNode | null;
+ onSave: (data: unknown) => Promise<void>;
+ onClose: () => void;
+ isAnthropic?: boolean;
+ isCcCompatible?: boolean;
+}
+
+export default function EditCompatibleNodeModal({
+ isOpen,
+ node,
+ onSave,
+ onClose,
+ isAnthropic,
+ isCcCompatible,
+}: EditCompatibleNodeModalProps) {
+ const t = useTranslations("providers");
+ const [formData, setFormData] = useState({
+ name: "",
+ prefix: "",
+ apiType: "chat",
+ baseUrl: "https://api.openai.com/v1",
+ chatPath: "",
+ modelsPath: "",
+ });
+ const [saving, setSaving] = useState(false);
+ const [checkKey, setCheckKey] = useState("");
+ const [validating, setValidating] = useState(false);
+ const [validationResult, setValidationResult] = useState(null);
+ const [showAdvanced, setShowAdvanced] = useState(false);
+
+ useEffect(() => {
+ if (node) {
+ setFormData({
+ name: node.name || "",
+ prefix: node.prefix || "",
+ apiType: node.apiType || "chat",
+ baseUrl:
+ node.baseUrl ||
+ (isCcCompatible
+ ? "https://api.anthropic.com"
+ : isAnthropic
+ ? "https://api.anthropic.com/v1"
+ : "https://api.openai.com/v1"),
+ chatPath: node.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
+ modelsPath: isCcCompatible ? "" : node.modelsPath || "",
+ });
+ setShowAdvanced(
+ !!(
+ node.chatPath ||
+ (!isCcCompatible && node.modelsPath) ||
+ (isCcCompatible && !node.chatPath)
+ )
+ );
+ }
+ }, [node, isAnthropic, isCcCompatible]);
+
+ const apiTypeOptions = [
+ { value: "chat", label: t("chatCompletions") },
+ { value: "responses", label: t("responsesApi") },
+ { value: "embeddings", label: t("embeddings") },
+ { value: "audio-transcriptions", label: t("audioTranscriptions") },
+ { value: "audio-speech", label: t("audioSpeech") },
+ { value: "images-generations", label: t("imagesGenerations") },
+ ];
+
+ const handleSubmit = async () => {
+ if (!formData.name.trim() || !formData.prefix.trim() || !formData.baseUrl.trim()) return;
+ setSaving(true);
+ try {
+ const payload: any = {
+ name: formData.name,
+ prefix: formData.prefix,
+ baseUrl: formData.baseUrl,
+ chatPath: formData.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
+ modelsPath: isCcCompatible ? "" : formData.modelsPath,
+ };
+ if (!isAnthropic) {
+ payload.apiType = formData.apiType;
+ }
+ await onSave(payload);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleValidate = async () => {
+ setValidating(true);
+ try {
+ const res = await fetch("/api/provider-nodes/validate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ baseUrl: formData.baseUrl,
+ apiKey: checkKey,
+ type: isAnthropic ? "anthropic-compatible" : "openai-compatible",
+ compatMode: isCcCompatible ? "cc" : undefined,
+ chatPath: formData.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
+ modelsPath: isCcCompatible ? "" : formData.modelsPath,
+ }),
+ });
+ const data = await res.json();
+ setValidationResult(data.valid ? "success" : "failed");
+ } catch {
+ setValidationResult("failed");
+ } finally {
+ setValidating(false);
+ }
+ };
+
+ if (!node) return null;
+
+ return (
+ <Modal
+ isOpen={isOpen}
+ title={
+ isCcCompatible
+ ? t("ccCompatibleDetailsTitle")
+ : t("editCompatibleTitle", { type: isAnthropic ? t("anthropic") : t("openai") })
+ }
+ onClose={onClose}
+ >
+ <div className="flex flex-col gap-4">
+ {isCcCompatible && (
+ <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
+ warning
+ </span>
+ <p>{t("ccCompatibleValidationHint")}</p>
+ </div>
+ </div>
+ )}
+ <Input
+ label={t("nameLabel")}
+ value={formData.name}
+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ placeholder={
+ isCcCompatible
+ ? t("ccCompatibleNamePlaceholder")
+ : t("compatibleProdPlaceholder", {
+ type: isAnthropic ? t("anthropic") : t("openai"),
+ })
+ }
+ hint={isCcCompatible ? t("ccCompatibleNameHint") : t("nameHint")}
+ />
+ <Input
+ label={t("prefixLabel")}
+ value={formData.prefix}
+ onChange={(e) => setFormData({ ...formData, prefix: e.target.value })}
+ placeholder={
+ isCcCompatible
+ ? t("ccCompatiblePrefixPlaceholder")
+ : isAnthropic
+ ? t("anthropicPrefixPlaceholder")
+ : t("openaiPrefixPlaceholder")
+ }
+ hint={isCcCompatible ? t("ccCompatiblePrefixHint") : t("prefixHint")}
+ />
+ {!isAnthropic && (
+ <Select
+ label={t("apiTypeLabel")}
+ options={apiTypeOptions}
+ value={formData.apiType}
+ onChange={(e) => setFormData({ ...formData, apiType: e.target.value })}
+ />
+ )}
+ <Input
+ label={t("baseUrlLabel")}
+ value={formData.baseUrl}
+ onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
+ placeholder={
+ isCcCompatible
+ ? t("ccCompatibleBaseUrlPlaceholder")
+ : isAnthropic
+ ? t("anthropicBaseUrlPlaceholder")
+ : t("openaiBaseUrlPlaceholder")
+ }
+ hint={
+ isCcCompatible
+ ? t("ccCompatibleBaseUrlHint")
+ : t("compatibleBaseUrlHint", {
+ type: isAnthropic ? t("anthropic") : t("openai"),
+ })
+ }
+ />
+ <button
+ type="button"
+ className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ aria-expanded={showAdvanced}
+ aria-controls="advanced-settings"
+ >
+ <span
+ className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
+ aria-hidden="true"
+ >
+ ▶
+ </span>
+ {t("advancedSettings")}
+ </button>
+ {showAdvanced && (
+ <div id="advanced-settings" className="flex flex-col gap-3 pl-2 border-l-2 border-border">
+ <Input
+ label={t("chatPathLabel")}
+ value={formData.chatPath}
+ onChange={(e) => setFormData({ ...formData, chatPath: e.target.value })}
+ placeholder={
+ isCcCompatible
+ ? CC_COMPATIBLE_DEFAULT_CHAT_PATH
+ : isAnthropic
+ ? "/messages"
+ : t("chatPathPlaceholder")
+ }
+ hint={isCcCompatible ? t("ccCompatibleChatPathHint") : t("chatPathHint")}
+ />
+ {!isCcCompatible && (
+ <Input
+ label={t("modelsPathLabel")}
+ value={formData.modelsPath}
+ onChange={(e) => setFormData({ ...formData, modelsPath: e.target.value })}
+ placeholder={t("modelsPathPlaceholder")}
+ hint={t("modelsPathHint")}
+ />
+ )}
+ </div>
+ )}
+ <div className="flex gap-2">
+ <Input
+ label={t("apiKeyForCheck")}
+ type="password"
+ value={checkKey}
+ onChange={(e) => setCheckKey(e.target.value)}
+ className="flex-1"
+ />
+ <div className="pt-6">
+ <Button
+ onClick={handleValidate}
+ disabled={!checkKey || validating || !formData.baseUrl.trim()}
+ variant="secondary"
+ >
+ {validating ? t("checking") : t("check")}
+ </Button>
+ </div>
+ </div>
+ {validationResult && (
+ <Badge variant={validationResult === "success" ? "success" : "error"}>
+ {validationResult === "success" ? t("valid") : t("invalid")}
+ </Badge>
+ )}
+ <div className="flex gap-2">
+ <Button
+ onClick={handleSubmit}
+ fullWidth
+ disabled={
+ !formData.name.trim() || !formData.prefix.trim() || !formData.baseUrl.trim() || saving
+ }
+ >
+ {saving ? t("saving") : t("save")}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx
new file mode 100644
index 0000000000..1cdf280c77
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx
@@ -0,0 +1,1170 @@
+"use client";
+
+// Issue #3501 Phase 1c — extracted from the god-component.
+// ~1091-LOC modal for editing an existing provider connection.
+
+import { useState, useEffect, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { Button, Badge, Input, Modal, Toggle, Select } from "@/shared/components";
+import {
+ isOpenAICompatibleProvider,
+ isAnthropicCompatibleProvider,
+ isClaudeCodeCompatibleProvider,
+ providerAllowsOptionalApiKey,
+} from "@/shared/constants/providers";
+import {
+ ANTIGRAVITY_CLIENT_PROFILE_OPTIONS,
+ normalizeAntigravityClientProfileSetting,
+} from "@/shared/constants/antigravityClientProfile";
+import { parseExtraApiKeys } from "@/shared/utils/parseApiKeys";
+import { maskEmail } from "@/shared/utils/maskEmail";
+import useEmailPrivacyStore from "@/store/emailPrivacyStore";
+import { useNotificationStore } from "@/store/notificationStore";
+import { type CodexServiceTier } from "@/lib/providers/requestDefaults";
+import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";
+import { resolveDashboardProviderInfo } from "../../../providerPageUtils";
+import {
+ isBaseUrlConfigurableProvider,
+ getProviderBaseUrlDefault,
+ getProviderBaseUrlHint,
+ getProviderBaseUrlPlaceholder,
+ isGlmProvider,
+ parseRoutingTagsInput,
+ parseExcludedModelsInput,
+ formatRoutingTagsInput,
+ formatExcludedModelsInput,
+ getWebSessionCredentialLabel,
+ getWebSessionCredentialHint,
+ getWebSessionCredentialCheckLabel,
+ getLocalProviderMetadata,
+ normalizeAndValidateHttpBaseUrl,
+ CODEX_REASONING_STRENGTH_OPTIONS,
+ CODEX_ACCOUNT_SERVICE_TIER_VALUES,
+ getCodexServiceTierLabel,
+ getCodexRequestDefaults,
+ getClaudeCodeCompatibleRequestDefaults,
+ providerText,
+ ERROR_TYPE_LABELS,
+ formatTimeAgo,
+} from "../../providerPageHelpers";
+import { getWebSessionCredentialRequirement } from "../../webSessionCredentials";
+import WebSessionCredentialGuide from "../WebSessionCredentialGuide";
+
+export interface EditConnectionModalConnection {
+ id?: string;
+ name?: string;
+ email?: string;
+ priority?: number;
+ maxConcurrent?: number | null;
+ rateLimitOverrides?: Record<string, number> | null;
+ authType?: string;
+ provider?: string;
+ apiKey?: string;
+ providerSpecificData?: Record<string, unknown>;
+ healthCheckInterval?: number;
+ projectId?: string | null;
+}
+
+export interface EditConnectionModalProps {
+ isOpen: boolean;
+ connection: EditConnectionModalConnection | null;
+ onSave: (data: unknown) => Promise<void | unknown>;
+ onClose: () => void;
+}
+
+export default function EditConnectionModal({
+ isOpen,
+ connection,
+ onSave,
+ onClose,
+}: EditConnectionModalProps) {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+ const [formData, setFormData] = useState({
+ name: "",
+ priority: 1,
+ maxConcurrent: "",
+ rpm: "",
+ tpm: "",
+ tpd: "",
+ minTime: "",
+ rateLimitMaxConcurrent: "",
+ apiKey: "",
+ healthCheckInterval: 60,
+ baseUrl: "",
+ cx: "",
+ region: "",
+ apiRegion: "international",
+ validationModelId: "",
+ tag: "",
+ routingTags: "",
+ excludedModels: "",
+ customUserAgent: "",
+ accountId: "",
+ codexReasoningEffort: "medium",
+ codexServiceTier: "default" as CodexServiceTier,
+ codexOpenaiStoreEnabled: false,
+ consoleApiKey: "",
+ ccCompatibleContext1m: false,
+ cloudCodeProjectId: "",
+ antigravityClientProfile: "ide",
+ blockExtraUsage:
+ connection?.provider === "claude"
+ ? isClaudeExtraUsageBlockEnabled(connection?.provider, connection?.providerSpecificData)
+ : false,
+ passthroughModels: connection?.providerSpecificData?.passthroughModels === true,
+ });
+ const [testing, setTesting] = useState(false);
+ const [testResult, setTestResult] = useState(null);
+ const [validating, setValidating] = useState(false);
+ const [validationResult, setValidationResult] = useState(null);
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+ const [extraApiKeys, setExtraApiKeys] = useState<string[]>([]);
+ const [newExtraKey, setNewExtraKey] = useState("");
+ const [apiKeyHealth, setApiKeyHealth] = useState<
+ Record<
+ string,
+ {
+ status: "active" | "warning" | "invalid";
+ failures: number;
+ lastFailure: string | null;
+ totalRequests?: number;
+ totalFailures?: number;
+ }
+ >
+ >({});
+ const [showAdvanced, setShowAdvanced] = useState(false);
+ const { emailsVisible: showEmail, toggleEmailVisibility: toggleShowEmail } =
+ useEmailPrivacyStore();
+
+ const usesBaseUrl = isBaseUrlConfigurableProvider(connection?.provider);
+ const defaultBaseUrl = getProviderBaseUrlDefault(connection?.provider);
+ const isVertex = connection?.provider === "vertex" || connection?.provider === "vertex-partner";
+ const isBedrock = connection?.provider === "bedrock";
+ const showsRegion = isVertex || isBedrock;
+ const isGlm = isGlmProvider(connection?.provider);
+ const isCloudflare = connection?.provider === "cloudflare-ai";
+ const isCodex = connection?.provider === "codex";
+ const isClaude = connection?.provider === "claude";
+ const isGeminiCli = connection?.provider === "gemini-cli";
+ const isAntigravity = connection?.provider === "antigravity";
+ const supportsGoogleProjectId = isGeminiCli || isAntigravity;
+ const localProviderMetadata = getLocalProviderMetadata(connection?.provider);
+ const isLocalSelfHostedProvider = !!localProviderMetadata;
+ const isGooglePse = connection?.provider === "google-pse-search";
+ const webSessionCredential = getWebSessionCredentialRequirement(connection?.provider);
+ const isNoAuthWebSessionCredential = webSessionCredential?.kind === "none";
+ const isWebSessionCredential = !!webSessionCredential && webSessionCredential.kind !== "none";
+ const providerDisplayName =
+ (connection?.provider ? resolveDashboardProviderInfo(connection.provider)?.name : null) ||
+ connection?.provider ||
+ "";
+ const apiKeyOptional =
+ providerAllowsOptionalApiKey(connection?.provider) || Boolean(isNoAuthWebSessionCredential);
+ const isCcCompatible = isClaudeCodeCompatibleProvider(connection?.provider);
+ const defaultRegion = isBedrock ? "eu-west-2" : "us-central1";
+ const apiCredentialLabel = webSessionCredential
+ ? getWebSessionCredentialLabel(t, webSessionCredential, apiKeyOptional)
+ : apiKeyOptional
+ ? t("apiKeyOptionalLabel")
+ : t("apiKeyLabel");
+ const apiCredentialPlaceholder = isWebSessionCredential
+ ? webSessionCredential.placeholder
+ : isVertex
+ ? t("vertexServiceAccountPlaceholder")
+ : t("enterNewApiKey");
+ const apiCredentialHint = isWebSessionCredential
+ ? getWebSessionCredentialHint(t, webSessionCredential, providerDisplayName, true)
+ : isLocalSelfHostedProvider
+ ? t("localProviderApiKeyOptionalHint", {
+ provider: localProviderMetadata?.name || connection?.provider || "",
+ })
+ : apiKeyOptional
+ ? t("apiKeyOptionalHint")
+ : t("leaveBlankKeepCurrentApiKey");
+ const codexAccountServiceTierOptions = useMemo(
+ () =>
+ CODEX_ACCOUNT_SERVICE_TIER_VALUES.map((value) => ({
+ value,
+ label: getCodexServiceTierLabel(t, value),
+ })),
+ [t]
+ );
+
+ useEffect(() => {
+ if (isOpen && connection) {
+ const rawBaseUrl = connection.providerSpecificData?.baseUrl;
+ const existingBaseUrl = typeof rawBaseUrl === "string" ? rawBaseUrl : "";
+ const rawRegion = connection.providerSpecificData?.region;
+ const existingRegion = typeof rawRegion === "string" ? rawRegion : "";
+ const rawCustomUserAgent = connection.providerSpecificData?.customUserAgent;
+ const existingCustomUserAgent =
+ typeof rawCustomUserAgent === "string" ? rawCustomUserAgent : "";
+ const rawCx = connection.providerSpecificData?.cx;
+ const existingCx = typeof rawCx === "string" ? rawCx : "";
+ const rawAccountId = connection.providerSpecificData?.accountId;
+ const existingAccountId = typeof rawAccountId === "string" ? rawAccountId : "";
+ const codexRequestDefaults = getCodexRequestDefaults(connection.providerSpecificData);
+ const ccRequestDefaults = getClaudeCodeCompatibleRequestDefaults(
+ connection.providerSpecificData
+ );
+ const rawConsoleApiKey = connection.providerSpecificData?.consoleApiKey;
+ const existingConsoleApiKey = typeof rawConsoleApiKey === "string" ? rawConsoleApiKey : "";
+ setFormData({
+ name: connection.name || "",
+ priority: connection.priority || 1,
+ maxConcurrent:
+ connection.maxConcurrent !== null && connection.maxConcurrent !== undefined
+ ? String(connection.maxConcurrent)
+ : "",
+ rpm:
+ connection.rateLimitOverrides?.rpm != null
+ ? String(connection.rateLimitOverrides.rpm)
+ : "",
+ tpm:
+ connection.rateLimitOverrides?.tpm != null
+ ? String(connection.rateLimitOverrides.tpm)
+ : "",
+ tpd:
+ connection.rateLimitOverrides?.tpd != null
+ ? String(connection.rateLimitOverrides.tpd)
+ : "",
+ minTime:
+ connection.rateLimitOverrides?.minTime != null
+ ? String(connection.rateLimitOverrides.minTime)
+ : "",
+ rateLimitMaxConcurrent:
+ connection.rateLimitOverrides?.maxConcurrent != null
+ ? String(connection.rateLimitOverrides.maxConcurrent)
+ : "",
+ apiKey: "",
+ healthCheckInterval: connection.healthCheckInterval ?? 60,
+ baseUrl: existingBaseUrl || defaultBaseUrl,
+ cx: existingCx,
+ region: existingRegion || (showsRegion ? defaultRegion : ""),
+ apiRegion: (connection.providerSpecificData?.apiRegion as string) || "international",
+ validationModelId: (connection.providerSpecificData?.validationModelId as string) || "",
+ tag: (connection.providerSpecificData?.tag as string) || "",
+ routingTags: formatRoutingTagsInput(connection.providerSpecificData?.tags),
+ excludedModels: formatExcludedModelsInput(
+ connection.providerSpecificData?.excludedModels ??
+ connection.providerSpecificData?.excluded_models
+ ),
+ customUserAgent: existingCustomUserAgent,
+ accountId: existingAccountId,
+ codexReasoningEffort: codexRequestDefaults.reasoningEffort,
+ codexServiceTier: codexRequestDefaults.serviceTier ?? "default",
+ codexOpenaiStoreEnabled: connection.providerSpecificData?.openaiStoreEnabled === true,
+ consoleApiKey: existingConsoleApiKey,
+ ccCompatibleContext1m: ccRequestDefaults.context1m,
+ cloudCodeProjectId:
+ (connection.providerSpecificData?.projectId as string) || connection.projectId || "",
+ antigravityClientProfile: normalizeAntigravityClientProfileSetting(
+ connection.providerSpecificData?.clientProfile
+ ),
+ blockExtraUsage: isClaudeExtraUsageBlockEnabled(
+ connection.provider,
+ connection.providerSpecificData
+ ),
+ passthroughModels: connection?.providerSpecificData?.passthroughModels === true,
+ });
+ // Load existing extra keys from providerSpecificData
+ const existing = connection.providerSpecificData?.extraApiKeys;
+ setExtraApiKeys(Array.isArray(existing) ? existing : []);
+ // Load API key health status
+ const health = connection.providerSpecificData?.apiKeyHealth as
+ | Record<
+ string,
+ {
+ status: "active" | "warning" | "invalid";
+ failures: number;
+ lastFailure: string | null;
+ totalRequests?: number;
+ totalFailures?: number;
+ }
+ >
+ | undefined;
+ setApiKeyHealth(health || {});
+ setNewExtraKey("");
+ setShowAdvanced(!!existingCustomUserAgent);
+ // email visibility controlled by global store
+ setTestResult(null);
+ setValidationResult(null);
+ setSaveError(null);
+ }
+ }, [isOpen, connection, defaultBaseUrl, showsRegion, defaultRegion]);
+
+ const handleTest = async () => {
+ if (!connection?.provider) return;
+ setTesting(true);
+ setTestResult(null);
+ try {
+ const res = await fetch(`/api/providers/${connection.id}/test`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ validationModelId: formData.validationModelId || undefined,
+ }),
+ });
+ const data = await res.json();
+ setTestResult({
+ valid: !!data.valid,
+ diagnosis: data.diagnosis || null,
+ message: data.error || null,
+ });
+ } catch {
+ setTestResult({
+ valid: false,
+ diagnosis: { type: "network_error" },
+ message: t("failedTestConnection"),
+ });
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const handleValidate = async () => {
+ if (
+ !connection?.provider ||
+ isNoAuthWebSessionCredential ||
+ (!isCompatible && !apiKeyOptional && !formData.apiKey)
+ ) {
+ return;
+ }
+ setValidating(true);
+ setValidationResult(null);
+ try {
+ const res = await fetch("/api/providers/validate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: connection.provider,
+ apiKey: formData.apiKey,
+ validationModelId: formData.validationModelId || undefined,
+ customUserAgent: formData.customUserAgent.trim() || undefined,
+ baseUrl: formData.baseUrl.trim() || undefined,
+ region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
+ cx: formData.cx.trim() || undefined,
+ }),
+ });
+ const data = await res.json();
+ setValidationResult(data.valid ? "success" : "failed");
+ } catch {
+ setValidationResult("failed");
+ } finally {
+ setValidating(false);
+ }
+ };
+
+ const handleAddParsedExtraKeys = (raw: string) => {
+ const { added, duplicates } = parseExtraApiKeys(raw, extraApiKeys);
+ if (added.length > 0) {
+ setExtraApiKeys((prev) => [...prev, ...added]);
+ notify.success(t("bulkPasteAdded", { count: added.length }));
+ }
+ if (duplicates > 0) {
+ notify.warning(t("bulkPasteDuplicatesIgnored", { count: duplicates }));
+ }
+ };
+
+ const handleSubmit = async () => {
+ setSaving(true);
+ setSaveError(null);
+ try {
+ const trimmedMaxConcurrent = formData.maxConcurrent.trim();
+ const trimmedCloudCodeProjectId = formData.cloudCodeProjectId.trim();
+ let parsedMaxConcurrent: number | null = null;
+ if (trimmedMaxConcurrent) {
+ const numericMaxConcurrent = Number(trimmedMaxConcurrent);
+ if (!Number.isInteger(numericMaxConcurrent) || numericMaxConcurrent < 0) {
+ setSaveError(t("maxConcurrentWholeNumberError"));
+ return;
+ }
+ parsedMaxConcurrent = numericMaxConcurrent;
+ }
+
+ const updates: any = {
+ name: formData.name,
+ priority: formData.priority,
+ maxConcurrent: parsedMaxConcurrent,
+ healthCheckInterval: formData.healthCheckInterval,
+ };
+
+ // Build rateLimitOverrides from non-empty fields
+ const overrides: Record<string, number> = {};
+ if (formData.rpm.trim()) overrides.rpm = Number(formData.rpm);
+ if (formData.tpm.trim()) overrides.tpm = Number(formData.tpm);
+ if (formData.tpd.trim()) overrides.tpd = Number(formData.tpd);
+ if (formData.minTime.trim()) overrides.minTime = Number(formData.minTime);
+ if (formData.rateLimitMaxConcurrent.trim())
+ overrides.maxConcurrent = Number(formData.rateLimitMaxConcurrent);
+ updates.rateLimitOverrides = Object.keys(overrides).length > 0 ? overrides : null;
+
+ if (supportsGoogleProjectId) {
+ updates.projectId = trimmedCloudCodeProjectId || null;
+ }
+
+ if (isGooglePse && !formData.cx.trim()) {
+ setSaveError(t("searchEngineIdRequired"));
+ return;
+ }
+
+ let validatedBaseUrl = null;
+ if (usesBaseUrl) {
+ const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
+ if (checked.error) {
+ setSaveError(checked.error);
+ return;
+ }
+ validatedBaseUrl = checked.value;
+ }
+
+ if (!isOAuth && formData.apiKey) {
+ updates.apiKey = formData.apiKey;
+ let isValid = validationResult === "success";
+ if (!isValid) {
+ try {
+ setValidating(true);
+ setValidationResult(null);
+ const res = await fetch("/api/providers/validate", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: connection.provider,
+ apiKey: formData.apiKey,
+ validationModelId: formData.validationModelId || undefined,
+ customUserAgent: formData.customUserAgent.trim() || undefined,
+ baseUrl: formData.baseUrl.trim() || undefined,
+ region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
+ cx: formData.cx.trim() || undefined,
+ }),
+ });
+ const data = await res.json();
+ isValid = !!data.valid;
+ setValidationResult(isValid ? "success" : "failed");
+ } catch {
+ setValidationResult("failed");
+ } finally {
+ setValidating(false);
+ }
+ }
+ if (isValid) {
+ updates.testStatus = "active";
+ updates.lastError = null;
+ updates.lastErrorAt = null;
+ updates.lastErrorType = null;
+ updates.lastErrorSource = null;
+ updates.errorCode = null;
+ updates.rateLimitedUntil = null;
+ }
+ }
+ // Persist extra API keys and baseUrl in providerSpecificData
+ if (!isOAuth) {
+ updates.providerSpecificData = {
+ ...(connection.providerSpecificData || {}),
+ extraApiKeys: extraApiKeys.filter((k) => k.trim().length > 0),
+ tag: formData.tag.trim() || undefined,
+ tags: parseRoutingTagsInput(formData.routingTags),
+ excludedModels: parseExcludedModelsInput(formData.excludedModels),
+ customUserAgent: formData.customUserAgent.trim(),
+ // Only write when explicitly enabled; omit to let registry default take effect
+ ...(formData.passthroughModels ? { passthroughModels: true } : {}),
+ };
+ if (connection.provider === "bailian-coding-plan") {
+ if (formData.consoleApiKey.trim()) {
+ updates.providerSpecificData.consoleApiKey = formData.consoleApiKey.trim();
+ } else {
+ updates.providerSpecificData.consoleApiKey = undefined;
+ }
+ }
+ if (formData.validationModelId) {
+ updates.providerSpecificData.validationModelId = formData.validationModelId;
+ }
+ if (isGooglePse) {
+ updates.providerSpecificData.cx = formData.cx.trim() || undefined;
+ }
+ if (usesBaseUrl) {
+ updates.providerSpecificData.baseUrl = validatedBaseUrl;
+ } else if (showsRegion) {
+ updates.providerSpecificData.region = formData.region.trim() || defaultRegion;
+ } else if (isGlm) {
+ updates.providerSpecificData.apiRegion = formData.apiRegion;
+ } else if (isCloudflare && formData.accountId.trim()) {
+ updates.providerSpecificData.accountId = formData.accountId.trim();
+ }
+ if (supportsGoogleProjectId) {
+ updates.providerSpecificData.projectId = trimmedCloudCodeProjectId || null;
+ }
+ if (isCcCompatible) {
+ const currentRequestDefaults =
+ updates.providerSpecificData.requestDefaults &&
+ typeof updates.providerSpecificData.requestDefaults === "object" &&
+ !Array.isArray(updates.providerSpecificData.requestDefaults)
+ ? { ...(updates.providerSpecificData.requestDefaults as Record<string, unknown>) }
+ : {};
+ if (formData.ccCompatibleContext1m) {
+ currentRequestDefaults.context1m = true;
+ } else {
+ delete currentRequestDefaults.context1m;
+ }
+ updates.providerSpecificData.requestDefaults =
+ Object.keys(currentRequestDefaults).length > 0 ? currentRequestDefaults : undefined;
+ }
+ } else {
+ // Also persist tag for OAuth accounts
+ updates.providerSpecificData = {
+ ...(connection.providerSpecificData || {}),
+ tag: formData.tag.trim() || undefined,
+ tags: parseRoutingTagsInput(formData.routingTags),
+ excludedModels: parseExcludedModelsInput(formData.excludedModels),
+ };
+ if (isClaude) {
+ updates.providerSpecificData.blockExtraUsage = formData.blockExtraUsage;
+ }
+ if (isCodex) {
+ updates.providerSpecificData.requestDefaults = {
+ reasoningEffort: formData.codexReasoningEffort,
+ ...(formData.codexServiceTier !== "default"
+ ? { serviceTier: formData.codexServiceTier }
+ : {}),
+ };
+ updates.providerSpecificData.openaiStoreEnabled =
+ formData.codexOpenaiStoreEnabled === true;
+ }
+ if (supportsGoogleProjectId) {
+ updates.providerSpecificData.projectId = trimmedCloudCodeProjectId || null;
+ }
+ }
+ if (isAntigravity) {
+ updates.providerSpecificData = {
+ ...(connection.providerSpecificData || {}),
+ ...(updates.providerSpecificData || {}),
+ clientProfile: normalizeAntigravityClientProfileSetting(
+ formData.antigravityClientProfile
+ ),
+ };
+ }
+ const error = (await onSave(updates)) as void | unknown;
+ if (error) {
+ setSaveError(typeof error === "string" ? error : t("failedSaveConnection"));
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (!connection) return null;
+
+ const isOAuth = connection.authType === "oauth";
+ const isCompatible =
+ isOpenAICompatibleProvider(connection.provider) ||
+ isAnthropicCompatibleProvider(connection.provider);
+ const testErrorMeta =
+ !testResult?.valid && testResult?.diagnosis?.type
+ ? ERROR_TYPE_LABELS[testResult.diagnosis.type] || null
+ : null;
+
+ return (
+ <Modal isOpen={isOpen} title={t("editConnection")} onClose={onClose}>
+ <div className="flex flex-col gap-4">
+ <Input
+ label={t("nameLabel")}
+ value={formData.name}
+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}
+ placeholder={isOAuth ? t("accountName") : t("productionKey")}
+ />
+ <Input
+ label={t("tagGroupLabel")}
+ value={formData.tag}
+ onChange={(e) => setFormData({ ...formData, tag: e.target.value })}
+ placeholder={t("tagGroupPlaceholder")}
+ hint={t("tagGroupHint")}
+ />
+ <Input
+ label={t("routingTagsLabel")}
+ value={formData.routingTags}
+ onChange={(e) => setFormData({ ...formData, routingTags: e.target.value })}
+ placeholder={t("routingTagsPlaceholder")}
+ hint={t("routingTagsHint")}
+ />
+ <Input
+ label={t("excludedModelsLabel")}
+ value={formData.excludedModels}
+ onChange={(e) => setFormData({ ...formData, excludedModels: e.target.value })}
+ placeholder={t("excludedModelsPlaceholder")}
+ hint={t("excludedModelsHint")}
+ />
+ {isCodex && (
+ <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
+ <Select
+ label={t("defaultThinkingStrengthLabel")}
+ value={formData.codexReasoningEffort}
+ options={CODEX_REASONING_STRENGTH_OPTIONS}
+ onChange={(e) => setFormData({ ...formData, codexReasoningEffort: e.target.value })}
+ hint={t("defaultThinkingStrengthHint")}
+ />
+ <Select
+ label={providerText(t, "codexServiceTierLabel", "Codex service tier")}
+ value={formData.codexServiceTier}
+ options={codexAccountServiceTierOptions}
+ onChange={(event) =>
+ setFormData({
+ ...formData,
+ codexServiceTier: event.target.value as CodexServiceTier,
+ })
+ }
+ hint={providerText(
+ t,
+ "codexServiceTierDescription",
+ "Default uses the normal Codex tier. Priority shows as Fast; Flex uses the flex service tier when available."
+ )}
+ />
+ <Toggle
+ checked={formData.codexOpenaiStoreEnabled}
+ onChange={(checked) => setFormData({ ...formData, codexOpenaiStoreEnabled: checked })}
+ label={t("openaiResponsesStoreLabel")}
+ description={t("openaiResponsesStoreDescription")}
+ />
+ </div>
+ )}
+ {isClaude && (
+ <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
+ <Toggle
+ checked={formData.blockExtraUsage}
+ onChange={(checked) => setFormData({ ...formData, blockExtraUsage: checked })}
+ label={t("blockClaudeExtraUsageLabel")}
+ description={t("blockClaudeExtraUsageDescription")}
+ />
+ </div>
+ )}
+ {isCcCompatible && (
+ <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
+ <Toggle
+ checked={formData.ccCompatibleContext1m}
+ onChange={(checked) => setFormData({ ...formData, ccCompatibleContext1m: checked })}
+ label={t("ccCompatibleContext1mLabel")}
+ description={t("ccCompatibleContext1mDescription")}
+ />
+ </div>
+ )}
+ {supportsGoogleProjectId && (
+ <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
+ {isAntigravity && (
+ <Select
+ label={t("antigravityClientProfileLabel")}
+ value={formData.antigravityClientProfile}
+ options={ANTIGRAVITY_CLIENT_PROFILE_OPTIONS.map((option) => ({
+ value: option.value,
+ label: t(option.labelKey),
+ }))}
+ onChange={(e) =>
+ setFormData({ ...formData, antigravityClientProfile: e.target.value })
+ }
+ hint={t("antigravityClientProfileHint")}
+ />
+ )}
+ <Input
+ label={isAntigravity ? t("antigravityProjectIdLabel") : t("geminiCliProjectIdLabel")}
+ value={formData.cloudCodeProjectId}
+ onChange={(e) => setFormData({ ...formData, cloudCodeProjectId: e.target.value })}
+ placeholder={
+ isAntigravity
+ ? t("antigravityProjectIdPlaceholder")
+ : t("geminiCliProjectIdPlaceholder")
+ }
+ hint={isAntigravity ? t("antigravityProjectIdHint") : t("geminiCliProjectIdHint")}
+ className="font-mono text-xs"
+ />
+ </div>
+ )}
+ {isOAuth && connection.email && (
+ <div className="bg-sidebar/50 p-3 rounded-lg">
+ <p className="text-sm text-text-muted mb-1">{t("email")}</p>
+ <div className="flex items-center gap-2">
+ <p className="font-medium" title={showEmail ? connection.email : undefined}>
+ {showEmail ? connection.email : maskEmail(connection.email)}
+ </p>
+ <button
+ type="button"
+ onClick={toggleShowEmail}
+ className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary"
+ title={showEmail ? t("hideEmail") : t("showEmail")}
+ >
+ <span className="material-symbols-outlined text-sm">
+ {showEmail ? "visibility_off" : "visibility"}
+ </span>
+ </button>
+ </div>
+ </div>
+ )}
+ {isOAuth && (
+ <Input
+ label={t("healthCheckMinutes")}
+ type="number"
+ value={formData.healthCheckInterval}
+ onChange={(e) =>
+ setFormData({
+ ...formData,
+ healthCheckInterval: Math.max(0, Number.parseInt(e.target.value) || 0),
+ })
+ }
+ hint={t("healthCheckHint")}
+ />
+ )}
+ <Input
+ label={t("priorityLabel")}
+ type="number"
+ value={formData.priority}
+ onChange={(e) =>
+ setFormData({ ...formData, priority: Number.parseInt(e.target.value) || 1 })
+ }
+ />
+ <Input
+ label={t("accountConcurrencyCapLabel")}
+ type="number"
+ min={0}
+ step={1}
+ value={formData.maxConcurrent}
+ onChange={(e) => {
+ const nextValue = e.target.value;
+ setFormData({ ...formData, maxConcurrent: nextValue });
+ if (saveError && nextValue.trim()) {
+ const numericValue = Number(nextValue);
+ if (Number.isInteger(numericValue) && numericValue >= 0) {
+ setSaveError(null);
+ }
+ }
+ }}
+ placeholder="0"
+ hint={t("accountConcurrencyCapHint")}
+ />
+ {saveError && (
+ <div className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">
+ {saveError}
+ </div>
+ )}
+ {!isOAuth && (
+ <>
+ {webSessionCredential && (
+ <WebSessionCredentialGuide
+ requirement={webSessionCredential}
+ providerName={providerDisplayName}
+ t={t}
+ />
+ )}
+ {!isNoAuthWebSessionCredential && (
+ <div className="flex gap-2">
+ <Input
+ label={apiCredentialLabel}
+ type="password"
+ value={formData.apiKey}
+ onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
+ placeholder={apiCredentialPlaceholder}
+ hint={apiCredentialHint}
+ className="flex-1"
+ autoComplete="off"
+ spellCheck={false}
+ autoCapitalize="off"
+ />
+ <div className="pt-6">
+ <Button
+ onClick={handleValidate}
+ disabled={
+ (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
+ (isGooglePse && !formData.cx.trim()) ||
+ validating ||
+ saving
+ }
+ variant="secondary"
+ >
+ {validating
+ ? t("checking")
+ : webSessionCredential
+ ? getWebSessionCredentialCheckLabel(t, webSessionCredential)
+ : t("check")}
+ </Button>
+ </div>
+ </div>
+ )}
+ {isGooglePse && (
+ <Input
+ label={t("searchEngineIdLabel")}
+ value={formData.cx}
+ onChange={(e) => setFormData({ ...formData, cx: e.target.value })}
+ placeholder="012345678901234567890:abc123xyz"
+ hint={t("searchEngineIdHint")}
+ />
+ )}
+ {validationResult && (
+ <Badge variant={validationResult === "success" ? "success" : "error"}>
+ {validationResult === "success" ? t("valid") : t("invalid")}
+ </Badge>
+ )}
+ <button
+ type="button"
+ className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ aria-expanded={showAdvanced}
+ aria-controls="edit-connection-advanced-settings"
+ >
+ <span
+ className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
+ aria-hidden="true"
+ >
+ ▶
+ </span>
+ {t("advancedSettings")}
+ </button>
+ {showAdvanced && (
+ <div
+ id="edit-connection-advanced-settings"
+ className="flex flex-col gap-3 pl-2 border-l-2 border-border"
+ >
+ <Input
+ label={t("customUserAgentLabel")}
+ value={formData.customUserAgent}
+ onChange={(e) => setFormData({ ...formData, customUserAgent: e.target.value })}
+ placeholder="my-app/1.0"
+ hint={t("customUserAgentHint")}
+ />
+ <Toggle
+ size="sm"
+ checked={formData.passthroughModels}
+ onChange={(checked) => setFormData({ ...formData, passthroughModels: checked })}
+ label={t("perModelQuotaLabel")}
+ description={t("perModelQuotaDescription")}
+ />
+ {connection.provider === "bailian-coding-plan" && (
+ <Input
+ label={t("consoleApiKeyOracleLabel")}
+ value={formData.consoleApiKey}
+ onChange={(e) => setFormData({ ...formData, consoleApiKey: e.target.value })}
+ placeholder={t("consoleApiKeyOraclePlaceholder")}
+ hint={t("consoleApiKeyOracleHint")}
+ type="password"
+ />
+ )}
+ <div className="border-t border-border/30 pt-3 mt-1">
+ <p className="text-xs font-medium text-text-muted mb-2">
+ {t("rateLimitOverridesSection")}
+ </p>
+ <div className="grid grid-cols-2 gap-3">
+ <Input
+ label={t("rateLimitOverridesRpmLabel")}
+ type="number"
+ min={0}
+ value={formData.rpm}
+ onChange={(e) => setFormData({ ...formData, rpm: e.target.value })}
+ placeholder="Inherit"
+ hint={t("rateLimitOverridesRpmHint")}
+ />
+ <Input
+ label={t("rateLimitOverridesTpmLabel")}
+ type="number"
+ min={0}
+ value={formData.tpm}
+ onChange={(e) => setFormData({ ...formData, tpm: e.target.value })}
+ placeholder="Inherit"
+ hint={t("rateLimitOverridesTpmHint")}
+ />
+ <Input
+ label={t("rateLimitOverridesTpdLabel")}
+ type="number"
+ min={0}
+ value={formData.tpd}
+ onChange={(e) => setFormData({ ...formData, tpd: e.target.value })}
+ placeholder="Inherit"
+ hint={t("rateLimitOverridesTpdHint")}
+ />
+ <Input
+ label={t("rateLimitOverridesMinTimeLabel")}
+ type="number"
+ min={0}
+ value={formData.minTime}
+ onChange={(e) => setFormData({ ...formData, minTime: e.target.value })}
+ placeholder="Inherit"
+ hint={t("rateLimitOverridesMinTimeHint")}
+ />
+ <Input
+ label={t("rateLimitOverridesMaxConcurrentLabel")}
+ type="number"
+ min={0}
+ value={formData.rateLimitMaxConcurrent}
+ onChange={(e) =>
+ setFormData({ ...formData, rateLimitMaxConcurrent: e.target.value })
+ }
+ placeholder="Inherit"
+ hint={t("rateLimitOverridesMaxConcurrentHint")}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ <Input
+ label={t("validationModelIdLabel")}
+ placeholder={t("validationModelIdPlaceholder")}
+ value={formData.validationModelId}
+ onChange={(e) => setFormData({ ...formData, validationModelId: e.target.value })}
+ hint={t("validationModelIdHint")}
+ />
+ </>
+ )}
+
+ {usesBaseUrl && (
+ <Input
+ label={t("baseUrlLabel")}
+ value={formData.baseUrl}
+ onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
+ placeholder={getProviderBaseUrlPlaceholder(connection.provider)}
+ hint={getProviderBaseUrlHint(connection.provider, t)}
+ />
+ )}
+
+ {showsRegion && (
+ <Input
+ label={t("regionLabel")}
+ value={formData.region}
+ onChange={(e) => setFormData({ ...formData, region: e.target.value })}
+ placeholder={defaultRegion}
+ hint={t("regionHint")}
+ />
+ )}
+
+ {isCloudflare && (
+ <Input
+ label={t("accountIdLabel")}
+ value={formData.accountId}
+ onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
+ placeholder={t("accountIdPlaceholder")}
+ hint={t("accountIdHint")}
+ />
+ )}
+
+ {isGlm && (
+ <div>
+ <label className="text-sm font-medium text-text-main mb-1 block">
+ {t("apiRegionLabel")}
+ </label>
+ <select
+ value={formData.apiRegion}
+ onChange={(e) => setFormData({ ...formData, apiRegion: e.target.value })}
+ className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
+ >
+ <option value="international">{t("apiRegionInternational")}</option>
+ <option value="china">{t("apiRegionChina")}</option>
+ </select>
+ <p className="text-xs text-text-muted mt-1">{t("apiRegionHint")}</p>
+ </div>
+ )}
+
+ {/* T07: API Key Health Status */}
+ {!isOAuth && connection?.apiKey && (
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium text-text-main">{t("apiKeyHealthLabel")}</label>
+ <div className="flex flex-col gap-1.5">
+ {/* Primary Key Health */}
+ {(() => {
+ const keyId = "primary";
+ const health = apiKeyHealth[keyId];
+ const statusColor =
+ health?.status === "invalid"
+ ? "text-red-400"
+ : health?.status === "warning"
+ ? "text-yellow-400"
+ : "text-text-muted";
+ const statusIcon =
+ health?.status === "invalid" ? "🔴" : health?.status === "warning" ? "🟡" : "🟢";
+ const statusLabel =
+ health?.status === "invalid"
+ ? t("apiKeyStatusInvalid")
+ : health?.status === "warning"
+ ? t("apiKeyStatusWarning", { count: health.failures })
+ : t("apiKeyStatusActive");
+
+ return (
+ <div className="flex items-center gap-2">
+ <span
+ className={`flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border truncate ${statusColor}`}
+ >
+ {statusIcon} {t("primaryKey")}: {connection.apiKey.slice(0, 6)}...
+ {connection.apiKey.slice(-4)}
+ </span>
+ {health && (
+ <span
+ className="text-[10px] text-text-muted whitespace-nowrap"
+ title={statusLabel}
+ >
+ {health.failures}x
+ {health.lastFailure ? ` · ${formatTimeAgo(health.lastFailure)}` : ""}
+ {health.totalRequests != null
+ ? ` · (${health.totalRequests} req${health.totalFailures != null ? `, ${health.totalFailures} fail` : ""})`
+ : ""}
+ </span>
+ )}
+ </div>
+ );
+ })()}
+ </div>
+ </div>
+ )}
+
+ {/* T07: Extra API Keys for round-robin rotation */}
+ {!isOAuth && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2">
+ <label className="text-sm font-medium text-text-main">
+ {t("extraApiKeysLabel")}
+ <span className="ml-2 text-[11px] font-normal text-text-muted">
+ ({t("extraApiKeysHint")})
+ </span>
+ </label>
+ {extraApiKeys.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setExtraApiKeys([])}
+ className="px-2.5 py-1.5 rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20 hover:text-red-300 text-xs font-medium transition-colors"
+ >
+ {t("deleteAllExtraApiKeys")}
+ </button>
+ )}
+ </div>
+ {extraApiKeys.length > 0 && (
+ <div className="flex flex-col gap-1.5">
+ {extraApiKeys.map((key, idx) => {
+ const keyId = `extra_${idx}`;
+ const health = apiKeyHealth[keyId];
+ const statusColor =
+ health?.status === "invalid"
+ ? "text-red-400"
+ : health?.status === "warning"
+ ? "text-yellow-400"
+ : "text-text-muted";
+ const statusIcon =
+ health?.status === "invalid"
+ ? "🔴"
+ : health?.status === "warning"
+ ? "🟡"
+ : "🟢";
+ const statusLabel =
+ health?.status === "invalid"
+ ? t("apiKeyStatusInvalid")
+ : health?.status === "warning"
+ ? t("apiKeyStatusWarning", { count: health.failures })
+ : t("apiKeyStatusActive");
+
+ return (
+ <div key={idx} className="flex items-center gap-2">
+ <span
+ className={`flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border truncate ${statusColor}`}
+ >
+ {statusIcon}{" "}
+ {t("extraApiKeyMasked", {
+ index: idx + 2,
+ prefix: key.slice(0, 6),
+ suffix: key.slice(-4),
+ })}
+ </span>
+ <div className="flex items-center gap-1">
+ {health && (
+ <span
+ className="text-[10px] text-text-muted whitespace-nowrap"
+ title={statusLabel}
+ >
+ {health.failures}x
+ {health.lastFailure ? ` · ${formatTimeAgo(health.lastFailure)}` : ""}
+ {health.totalRequests != null
+ ? ` · (${health.totalRequests} req${health.totalFailures != null ? `, ${health.totalFailures} fail` : ""})`
+ : ""}
+ </span>
+ )}
+ <button
+ onClick={() => setExtraApiKeys(extraApiKeys.filter((_, i) => i !== idx))}
+ className="p-1.5 rounded hover:bg-red-500/10 text-red-400 hover:text-red-500"
+ title={t("removeThisKey")}
+ >
+ <span className="material-symbols-outlined text-[16px]">close</span>
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ <div className="flex gap-2">
+ <input
+ type="password"
+ value={newExtraKey}
+ onChange={(e) => setNewExtraKey(e.target.value)}
+ placeholder={t("addAnotherApiKey")}
+ className="flex-1 text-sm bg-sidebar/50 border border-border rounded px-3 py-2 text-text-main placeholder:text-text-muted focus:ring-1 focus:ring-primary outline-none"
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && newExtraKey.trim()) {
+ setExtraApiKeys([...extraApiKeys, newExtraKey.trim()]);
+ setNewExtraKey("");
+ }
+ }}
+ onPaste={(e) => {
+ const text = e.clipboardData.getData("text");
+ if (!/\r?\n/.test(text)) return;
+ e.preventDefault();
+ handleAddParsedExtraKeys(text);
+ }}
+ />
+ <button
+ onClick={() => {
+ if (newExtraKey.trim()) {
+ setExtraApiKeys([...extraApiKeys, newExtraKey.trim()]);
+ setNewExtraKey("");
+ }
+ }}
+ disabled={!newExtraKey.trim()}
+ className="px-3 py-2 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-40 text-sm font-medium"
+ >
+ {t("add")}
+ </button>
+ </div>
+ <p className="text-[11px] text-text-muted">{t("bulkPasteHint")}</p>
+ {extraApiKeys.length > 0 && (
+ <p className="text-[11px] text-text-muted">
+ {t("totalKeysRotating", { count: extraApiKeys.length + 1 })}
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Test Connection */}
+ {!isCompatible && (
+ <div className="flex items-center gap-3">
+ <Button onClick={handleTest} variant="secondary" disabled={testing}>
+ {testing ? t("testing") : t("testConnection")}
+ </Button>
+ {testResult && (
+ <>
+ <Badge variant={testResult.valid ? "success" : "error"}>
+ {testResult.valid ? t("valid") : t("failed")}
+ </Badge>
+ {testErrorMeta && (
+ <Badge variant={testErrorMeta.variant}>{t(testErrorMeta.labelKey)}</Badge>
+ )}
+ </>
+ )}
+ </div>
+ )}
+
+ <div className="flex gap-2">
+ <Button
+ onClick={handleSubmit}
+ fullWidth
+ disabled={saving || (isGooglePse && !formData.cx.trim())}
+ >
+ {saving ? t("saving") : t("save")}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportClaudeAuthModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportClaudeAuthModal.tsx
new file mode 100644
index 0000000000..e10ad6e98f
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportClaudeAuthModal.tsx
@@ -0,0 +1,730 @@
+"use client";
+import { useState } from "react";
+import { useNotificationStore } from "@/store/notificationStore";
+import { useTranslations } from "next-intl";
+import { Button, Modal } from "@/shared/components";
+interface ImportClaudeAuthModalProps {
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+type ClaudeImportTopTab = "single" | "bulk";
+type ClaudeBulkSubMode = "upload" | "paste" | "zip";
+
+interface ClaudeBulkEntry {
+ name: string;
+ json: unknown;
+ parseError: string | null;
+ email: string | null;
+}
+
+function extractEmailFromClaudeJson(json: unknown): string | null {
+ try {
+ const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
+ if (!doc) return null;
+ const oauth =
+ doc.claudeAiOauth && typeof doc.claudeAiOauth === "object"
+ ? (doc.claudeAiOauth as Record<string, unknown>)
+ : null;
+ if (!oauth) return null;
+ return null; // email comes from bootstrap, not the file
+ } catch {
+ return null;
+ }
+}
+
+function previewClaudeJson(json: unknown): { valid: boolean; email: string | null } {
+ try {
+ const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
+ if (!doc) return { valid: false, email: null };
+ const oauth =
+ doc.claudeAiOauth && typeof doc.claudeAiOauth === "object"
+ ? (doc.claudeAiOauth as Record<string, unknown>)
+ : null;
+ if (!oauth || !oauth.accessToken || !oauth.refreshToken) return { valid: false, email: null };
+ return { valid: true, email: null };
+ } catch {
+ return { valid: false, email: null };
+ }
+}
+
+export function ImportClaudeAuthModal({ onClose, onSuccess }: ImportClaudeAuthModalProps) {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ const [topTab, setTopTab] = useState<ClaudeImportTopTab>("single");
+ const [singleSubTab, setSingleSubTab] = useState<"upload" | "paste">("upload");
+ const [bulkSubMode, setBulkSubMode] = useState<ClaudeBulkSubMode>("upload");
+
+ // Single
+ const [singleJson, setSingleJson] = useState<unknown>(null);
+ const [singlePasteText, setSinglePasteText] = useState("");
+ const [singleName, setSingleName] = useState("");
+ const [singleEmail, setSingleEmail] = useState("");
+ const [overwriteExisting, setOverwriteExisting] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+
+ // Bulk
+ const [bulkEntries, setBulkEntries] = useState<ClaudeBulkEntry[]>([]);
+ const [bulkPasteText, setBulkPasteText] = useState("");
+ const [bulkSubmitting, setBulkSubmitting] = useState(false);
+ const [bulkErrors, setBulkErrors] = useState<{ index: number; name: string; message: string }[]>(
+ []
+ );
+ const [bulkResult, setBulkResult] = useState<{
+ success: number;
+ failed: number;
+ total: number;
+ } | null>(null);
+ const [zipExtracting, setZipExtracting] = useState(false);
+
+ const handleSingleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ const json = JSON.parse(ev.target?.result as string);
+ setSingleJson(json);
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportInvalidJson")
+ ? t("claudeImportInvalidJson")
+ : "Could not parse the file as JSON"
+ );
+ }
+ };
+ reader.readAsText(file);
+ };
+
+ const handleSingleSubmit = async () => {
+ if (submitting) return;
+ setSubmitting(true);
+ try {
+ let rawJson: unknown;
+ if (singleSubTab === "upload") {
+ rawJson = singleJson;
+ } else {
+ try {
+ rawJson = JSON.parse(singlePasteText);
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportInvalidJson")
+ ? t("claudeImportInvalidJson")
+ : "Could not parse the pasted content as JSON"
+ );
+ return;
+ }
+ }
+
+ const body =
+ singleSubTab === "paste"
+ ? {
+ source: { kind: "text", text: singlePasteText },
+ name: singleName || undefined,
+ email: singleEmail || undefined,
+ overwriteExisting,
+ }
+ : {
+ source: { kind: "json", json: rawJson },
+ name: singleName || undefined,
+ email: singleEmail || undefined,
+ overwriteExisting,
+ };
+
+ const res = await fetch("/api/providers/claude-auth/import", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ const data = await res.json().catch(() => ({}));
+
+ if (!res.ok) {
+ if (data.code === "duplicate_account") {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportDuplicate")
+ ? t("claudeImportDuplicate")
+ : 'Account already exists — enable "Replace existing" to overwrite'
+ );
+ } else if (data.code === "identity_unverified") {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportIdentityUnverified")
+ ? t("claudeImportIdentityUnverified")
+ : 'Bootstrap could not verify the account. Enable "Replace existing" or provide an email.'
+ );
+ } else {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("claudeImportFailed")
+ ? t("claudeImportFailed")
+ : "Failed to import Claude auth")
+ );
+ }
+ return;
+ }
+
+ notify.success(
+ typeof t.has === "function" && t.has("claudeImportSuccess")
+ ? t("claudeImportSuccess")
+ : "Claude connection imported successfully"
+ );
+ onSuccess();
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportFailed")
+ ? t("claudeImportFailed")
+ : "Failed to import Claude auth"
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const handleBulkFilesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files || []);
+ const newEntries: ClaudeBulkEntry[] = [];
+ let pending = files.length;
+ if (!pending) return;
+ files.forEach((file) => {
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ const json = JSON.parse(ev.target?.result as string);
+ const email = extractEmailFromClaudeJson(json);
+ newEntries.push({
+ name: file.name.replace(/\.json$/, ""),
+ json,
+ parseError: null,
+ email,
+ });
+ } catch {
+ newEntries.push({
+ name: file.name,
+ json: null,
+ parseError: "Not valid JSON",
+ email: null,
+ });
+ }
+ pending--;
+ if (pending === 0) setBulkEntries((prev) => [...prev, ...newEntries]);
+ };
+ reader.readAsText(file);
+ });
+ };
+
+ const handleBulkPasteChange = (text: string) => {
+ setBulkPasteText(text);
+ const trimmed = text.trim();
+ if (!trimmed) {
+ setBulkEntries([]);
+ return;
+ }
+ try {
+ const arr = JSON.parse(trimmed);
+ if (Array.isArray(arr)) {
+ setBulkEntries(
+ arr.map((item, i) => ({
+ name: `entry ${i + 1}`,
+ json: item,
+ parseError: null,
+ email: null,
+ }))
+ );
+ } else {
+ setBulkEntries([{ name: "entry 1", json: arr, parseError: null, email: null }]);
+ }
+ } catch {
+ setBulkEntries([
+ { name: "parse error", json: null, parseError: "Invalid JSON", email: null },
+ ]);
+ }
+ };
+
+ const handleZipUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ setZipExtracting(true);
+ try {
+ const res = await fetch("/api/providers/claude-auth/zip-extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/zip" },
+ body: file,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("claudeImportBulkZipError")
+ ? t("claudeImportBulkZipError")
+ : "Failed to extract ZIP")
+ );
+ return;
+ }
+ const entries: ClaudeBulkEntry[] = (data.entries || []).map(
+ (e: { name: string; json: unknown; parseError: string | null }) => ({
+ name: e.name,
+ json: e.json,
+ parseError: e.parseError,
+ email: null,
+ })
+ );
+ setBulkEntries(entries);
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportBulkZipError")
+ ? t("claudeImportBulkZipError")
+ : "Failed to extract ZIP"
+ );
+ } finally {
+ setZipExtracting(false);
+ }
+ };
+
+ const handleBulkSubmit = async () => {
+ if (bulkSubmitting) return;
+ setBulkSubmitting(true);
+ setBulkErrors([]);
+ setBulkResult(null);
+ try {
+ const validEntries = bulkEntries.filter((e) => e.json !== null);
+ if (validEntries.length === 0) {
+ notify.error("No valid entries to import");
+ return;
+ }
+ const res = await fetch("/api/providers/claude-auth/import-bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ entries: validEntries.map((e) => ({
+ json: e.json,
+ name: e.name,
+ email: e.email || undefined,
+ })),
+ overwriteExisting,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("claudeImportBulkFailed")
+ ? t("claudeImportBulkFailed")
+ : "Some entries failed to import")
+ );
+ return;
+ }
+ setBulkResult({ success: data.success, failed: data.failed, total: data.total });
+ if (data.errors?.length > 0) setBulkErrors(data.errors);
+ if (data.success > 0) {
+ notify.success(
+ typeof t.has === "function" && t.has("claudeImportBulkSuccess")
+ ? t("claudeImportBulkSuccess", { count: data.success })
+ : `Imported ${data.success} Claude connections`
+ );
+ if (data.failed === 0) onSuccess();
+ }
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("claudeImportBulkFailed")
+ ? t("claudeImportBulkFailed")
+ : "Some entries failed to import"
+ );
+ } finally {
+ setBulkSubmitting(false);
+ }
+ };
+
+ const tabLabels: Record<ClaudeImportTopTab, string> = {
+ single:
+ typeof t.has === "function" && t.has("claudeImportTabSingle")
+ ? t("claudeImportTabSingle")
+ : "Single",
+ bulk:
+ typeof t.has === "function" && t.has("claudeImportTabBulk")
+ ? t("claudeImportTabBulk")
+ : "Bulk",
+ };
+
+ const modalTitle =
+ typeof t.has === "function" && t.has("claudeImportModalTitle")
+ ? t("claudeImportModalTitle")
+ : "Import Claude Auth";
+
+ return (
+ <Modal isOpen onClose={onClose} title={modalTitle}>
+ <div className="flex flex-col gap-4">
+ {/* Top tabs */}
+ <div className="flex gap-1 border-b border-border pb-0">
+ {(["single", "bulk"] as ClaudeImportTopTab[]).map((tab) => (
+ <button
+ key={tab}
+ onClick={() => setTopTab(tab)}
+ className={`px-3 py-1.5 text-sm rounded-t-md transition-colors ${
+ topTab === tab
+ ? "bg-primary/10 text-primary border-b-2 border-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {tabLabels[tab]}
+ </button>
+ ))}
+ </div>
+
+ {topTab === "single" && (
+ <div className="flex flex-col gap-3">
+ {/* Sub-tabs */}
+ <div className="flex gap-1">
+ {(["upload", "paste"] as const).map((sub) => (
+ <button
+ key={sub}
+ onClick={() => setSingleSubTab(sub)}
+ className={`px-2 py-1 text-xs rounded transition-colors ${
+ singleSubTab === sub
+ ? "bg-bg-subtle text-text-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {sub === "upload"
+ ? typeof t.has === "function" && t.has("claudeImportTabUpload")
+ ? t("claudeImportTabUpload")
+ : "Upload file"
+ : typeof t.has === "function" && t.has("claudeImportTabPaste")
+ ? t("claudeImportTabPaste")
+ : "Paste JSON"}
+ </button>
+ ))}
+ </div>
+ {singleSubTab === "upload" ? (
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportFileLabel")
+ ? t("claudeImportFileLabel")
+ : "Choose .credentials.json"}
+ </label>
+ <input
+ type="file"
+ accept=".json"
+ onChange={handleSingleFileChange}
+ className="block w-full text-sm"
+ />
+ {singleJson && previewClaudeJson(singleJson).valid && (
+ <p className="mt-1 text-xs text-emerald-500">
+ {t("providerDetailValidClaudeCredentialsFile")}
+ </p>
+ )}
+ {singleJson && !previewClaudeJson(singleJson).valid && (
+ <p className="mt-1 text-xs text-red-500">
+ {typeof t.has === "function" && t.has("claudeImportInvalidShape")
+ ? t("claudeImportInvalidShape")
+ : "The file is not a valid .credentials.json"}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportPasteLabel")
+ ? t("claudeImportPasteLabel")
+ : "Paste the JSON content"}
+ </label>
+ <textarea
+ value={singlePasteText}
+ onChange={(e) => setSinglePasteText(e.target.value)}
+ rows={6}
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
+ placeholder='{ "claudeAiOauth": { ... } }'
+ />
+ </div>
+ )}
+ <div className="grid grid-cols-2 gap-2">
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportEmailLabel")
+ ? t("claudeImportEmailLabel")
+ : "Account email"}
+ </label>
+ <input
+ type="email"
+ value={singleEmail}
+ onChange={(e) => setSingleEmail(e.target.value)}
+ placeholder="auto-detected"
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportNameLabel")
+ ? t("claudeImportNameLabel")
+ : "Connection name (optional)"}
+ </label>
+ <input
+ type="text"
+ value={singleName}
+ onChange={(e) => setSingleName(e.target.value)}
+ placeholder="My Claude account"
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
+ />
+ </div>
+ </div>
+ <label className="flex items-center gap-2 text-xs text-text-muted">
+ <input
+ type="checkbox"
+ checked={overwriteExisting}
+ onChange={(e) => setOverwriteExisting(e.target.checked)}
+ />
+ {typeof t.has === "function" && t.has("claudeImportOverwriteLabel")
+ ? t("claudeImportOverwriteLabel")
+ : "Replace existing connection if account already exists"}
+ </label>
+ <Button
+ loading={submitting}
+ onClick={handleSingleSubmit}
+ disabled={singleSubTab === "upload" ? !singleJson : !singlePasteText.trim()}
+ >
+ {typeof t.has === "function" && t.has("claudeImportSubmit")
+ ? t("claudeImportSubmit")
+ : "Import"}
+ </Button>
+ </div>
+ )}
+
+ {topTab === "bulk" && (
+ <div className="flex flex-col gap-3">
+ {/* Sub-mode tabs */}
+ <div className="flex gap-1">
+ {(["upload", "paste", "zip"] as ClaudeBulkSubMode[]).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => {
+ setBulkSubMode(mode);
+ setBulkEntries([]);
+ }}
+ className={`px-2 py-1 text-xs rounded transition-colors ${
+ bulkSubMode === mode
+ ? "bg-bg-subtle text-text-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {mode === "upload"
+ ? typeof t.has === "function" && t.has("claudeImportBulkModeUpload")
+ ? t("claudeImportBulkModeUpload")
+ : "Upload files"
+ : mode === "paste"
+ ? typeof t.has === "function" && t.has("claudeImportBulkModePaste")
+ ? t("claudeImportBulkModePaste")
+ : "Paste JSON array"
+ : typeof t.has === "function" && t.has("claudeImportBulkModeZip")
+ ? t("claudeImportBulkModeZip")
+ : "Upload ZIP"}
+ </button>
+ ))}
+ </div>
+
+ {bulkSubMode === "upload" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportBulkUploadHint")
+ ? t("claudeImportBulkUploadHint")
+ : "Drop or pick up to 50 .credentials.json files (256KB each, 10MB total)."}
+ </p>
+ <input
+ type="file"
+ accept=".json"
+ multiple
+ onChange={handleBulkFilesChange}
+ className="block w-full text-sm"
+ />
+ </div>
+ )}
+ {bulkSubMode === "paste" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportBulkPasteHint")
+ ? t("claudeImportBulkPasteHint")
+ : "Paste an array of objects: [{ json, name?, email? }, ...]"}
+ </p>
+ <textarea
+ value={bulkPasteText}
+ onChange={(e) => handleBulkPasteChange(e.target.value)}
+ rows={6}
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
+ placeholder="[{ ... }, { ... }]"
+ />
+ </div>
+ )}
+ {bulkSubMode === "zip" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("claudeImportBulkZipHint")
+ ? t("claudeImportBulkZipHint")
+ : "ZIP containing .json entries. Max 50 entries, 10MB unpacked."}
+ </p>
+ {zipExtracting ? (
+ <p className="text-xs text-primary animate-pulse">
+ {typeof t.has === "function" && t.has("claudeImportBulkZipExtracting")
+ ? t("claudeImportBulkZipExtracting")
+ : "Extracting ZIP…"}
+ </p>
+ ) : (
+ <input
+ type="file"
+ accept=".zip"
+ onChange={handleZipUpload}
+ className="block w-full text-sm"
+ />
+ )}
+ </div>
+ )}
+
+ {bulkEntries.length > 0 && (
+ <div className="rounded border border-border bg-bg-subtle px-2 py-1.5 max-h-36 overflow-y-auto">
+ {bulkEntries.map((e, i) => (
+ <div
+ key={i}
+ className={`text-xs py-0.5 flex items-center gap-1 ${e.parseError ? "text-red-500" : "text-text-main"}`}
+ >
+ <span className="material-symbols-outlined text-[12px]">
+ {e.parseError ? "error" : "check_circle"}
+ </span>
+ {e.name}
+ {e.email ? ` (${e.email})` : ""}
+ {e.parseError ? ` — ${e.parseError}` : ""}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <label className="flex items-center gap-2 text-xs text-text-muted">
+ <input
+ type="checkbox"
+ checked={overwriteExisting}
+ onChange={(e) => setOverwriteExisting(e.target.checked)}
+ />
+ {typeof t.has === "function" && t.has("claudeImportOverwriteLabel")
+ ? t("claudeImportOverwriteLabel")
+ : "Replace existing connection if account already exists"}
+ </label>
+
+ {bulkResult && (
+ <div className="rounded bg-bg-subtle px-2 py-1.5 text-xs">
+ {bulkResult.success}/{bulkResult.total} imported
+ {bulkResult.failed > 0 ? `, ${bulkResult.failed} failed` : ""}
+ </div>
+ )}
+ {bulkErrors.length > 0 && (
+ <div className="rounded border border-red-500/30 bg-red-500/5 px-2 py-1.5 max-h-28 overflow-y-auto">
+ {bulkErrors.map((e) => (
+ <div key={e.index} className="text-xs text-red-500 py-0.5">
+ {e.name}: {e.message}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <Button
+ loading={bulkSubmitting}
+ onClick={handleBulkSubmit}
+ disabled={bulkEntries.filter((e) => e.json !== null).length === 0}
+ >
+ {typeof t.has === "function" && t.has("claudeImportBulkSubmit")
+ ? t("claudeImportBulkSubmit")
+ : "Import all"}
+ </Button>
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+// ──── ApplyClaudeAuthModal ────────────────────────────────────────────────────
+
+export function ApplyClaudeAuthModal({
+ connectionId,
+ inProgress,
+ onConfirm,
+ onClose,
+}: {
+ connectionId: string | null;
+ inProgress: boolean;
+ onConfirm: (id: string) => Promise<void>;
+ onClose: () => void;
+}) {
+ const t = useTranslations("providers");
+ const [confirmed, setConfirmed] = useState(false);
+ const isOpen = !!connectionId;
+
+ if (!connectionId) return null;
+
+ const title =
+ typeof t.has === "function" && t.has("claudeApplyModalTitle")
+ ? t("claudeApplyModalTitle")
+ : "Apply to Local Claude Code";
+ const targetLabel =
+ typeof t.has === "function" && t.has("claudeApplyTargetLabel")
+ ? t("claudeApplyTargetLabel")
+ : "Target path";
+ const backupLabel =
+ typeof t.has === "function" && t.has("claudeApplyBackupLabel")
+ ? t("claudeApplyBackupLabel")
+ : "Backups";
+ const warning =
+ typeof t.has === "function" && t.has("claudeApplyWarning")
+ ? t("claudeApplyWarning")
+ : "This will replace the existing claudeAiOauth section. Continue?";
+ const confirmText =
+ typeof t.has === "function" && t.has("claudeApplyConfirmCheckbox")
+ ? t("claudeApplyConfirmCheckbox")
+ : "I confirm I want to replace the existing claudeAiOauth section";
+ const applyText =
+ typeof t.has === "function" && t.has("claudeApply") ? t("claudeApply") : "Apply";
+ const mcpHint =
+ typeof t.has === "function" && t.has("claudeApplyMcpHint")
+ ? t("claudeApplyMcpHint")
+ : "Existing MCP OAuth state will be preserved.";
+
+ return (
+ <Modal isOpen={isOpen} title={title} onClose={onClose}>
+ <div className="flex flex-col gap-4">
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
+ <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
+ ~/.claude/.credentials.json
+ </code>
+ <p className="mt-1 text-xs text-text-muted">Path is auto-detected per OS (Linux/Mac).</p>
+ </div>
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
+ <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
+ {"~/.claude/credentials-{timestamp}.bak"}
+ </code>
+ </div>
+ <div className="rounded bg-sky-500/10 border border-sky-500/20 px-3 py-2 text-xs text-sky-400">
+ {mcpHint}
+ </div>
+ <p className="text-sm text-text-muted">{warning}</p>
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ checked={confirmed}
+ onChange={(e) => setConfirmed(e.target.checked)}
+ />
+ {confirmText}
+ </label>
+ <div className="flex justify-end gap-2">
+ <Button variant="secondary" onClick={onClose} disabled={inProgress}>
+ Cancel
+ </Button>
+ <Button
+ loading={inProgress}
+ disabled={!confirmed || inProgress}
+ onClick={() => void onConfirm(connectionId)}
+ >
+ {applyText}
+ </Button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportCodexAuthModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportCodexAuthModal.tsx
new file mode 100644
index 0000000000..449962e526
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportCodexAuthModal.tsx
@@ -0,0 +1,743 @@
+"use client";
+import { useState } from "react";
+import { useNotificationStore } from "@/store/notificationStore";
+import { useTranslations } from "next-intl";
+import { Button, Modal, Select } from "@/shared/components";
+interface ImportCodexAuthModalProps {
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+type ImportTopTab = "single" | "bulk";
+type BulkSubMode = "upload" | "paste" | "zip";
+
+interface BulkEntry {
+ name: string;
+ json: unknown;
+ parseError: string | null;
+ email: string | null;
+}
+
+function extractEmailFromJwtLocal(idToken: string): string | null {
+ try {
+ const parts = idToken.split(".");
+ if (parts.length !== 3) return null;
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
+ return typeof payload.email === "string" ? payload.email : null;
+ } catch {
+ return null;
+ }
+}
+
+function previewCodexJson(json: unknown): { valid: boolean; email: string | null } {
+ try {
+ const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
+ // Codex CLI no longer writes auth_mode — accept both with and without it.
+ // Only reject when auth_mode is explicitly set to something other than "chatgpt".
+ if (
+ !doc ||
+ (doc.auth_mode !== undefined && doc.auth_mode !== null && doc.auth_mode !== "chatgpt")
+ )
+ return { valid: false, email: null };
+ const tokens =
+ doc.tokens && typeof doc.tokens === "object" ? (doc.tokens as Record<string, unknown>) : null;
+ if (!tokens?.id_token || typeof tokens.id_token !== "string")
+ return { valid: false, email: null };
+ return { valid: true, email: extractEmailFromJwtLocal(tokens.id_token as string) };
+ } catch {
+ return { valid: false, email: null };
+ }
+}
+
+function parseBulkPasteText(text: string): BulkEntry[] {
+ const trimmed = text.trim();
+ if (!trimmed) return [];
+
+ const tryParse = (s: string): BulkEntry => {
+ try {
+ const json = JSON.parse(s);
+ const { email } = previewCodexJson(json);
+ return { name: email || "unknown", json, parseError: null, email };
+ } catch {
+ return { name: "parse error", json: null, parseError: "Invalid JSON", email: null };
+ }
+ };
+
+ try {
+ const arr = JSON.parse(trimmed);
+ if (Array.isArray(arr))
+ return arr.map((item) => {
+ const { email } = previewCodexJson(item);
+ return { name: email || "unknown", json: item, parseError: null, email };
+ });
+ const { email } = previewCodexJson(arr);
+ return [{ name: email || "unknown", json: arr, parseError: null, email }];
+ } catch {
+ return trimmed
+ .split(/^---$/m)
+ .map((s) => tryParse(s.trim()))
+ .filter((e) => e.json !== null || e.parseError !== null);
+ }
+}
+
+export function ImportCodexAuthModal({ onClose, onSuccess }: ImportCodexAuthModalProps) {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ // Top-level tab: Single / Bulk
+ const [topTab, setTopTab] = useState<ImportTopTab>("single");
+
+ // ── Single mode state ──
+ const [singleTab, setSingleTab] = useState<"upload" | "paste">("upload");
+ const [singleParsedJson, setSingleParsedJson] = useState<unknown>(null);
+ const [singleParseError, setSingleParseError] = useState<string | null>(null);
+ const [singleDetectedEmail, setSingleDetectedEmail] = useState<string | null>(null);
+ const [singlePasteText, setSinglePasteText] = useState("");
+ const [singleName, setSingleName] = useState("");
+ const [singleEmail, setSingleEmail] = useState("");
+ const [singleOverwrite, setSingleOverwrite] = useState(false);
+ const [singleLoading, setSingleLoading] = useState(false);
+ const [singleError, setSingleError] = useState<string | null>(null);
+
+ // ── Bulk mode state ──
+ const [bulkMode, setBulkMode] = useState<BulkSubMode>("upload");
+ const [bulkEntries, setBulkEntries] = useState<BulkEntry[]>([]);
+ const [bulkPasteText, setBulkPasteText] = useState("");
+ const [bulkZipExtracting, setBulkZipExtracting] = useState(false);
+ const [bulkZipError, setBulkZipError] = useState<string | null>(null);
+ const [bulkOverwrite, setBulkOverwrite] = useState(false);
+ const [bulkLoading, setBulkLoading] = useState(false);
+ const [bulkResult, setBulkResult] = useState<{
+ success: number;
+ failed: number;
+ errors: { index: number; name: string; message: string }[];
+ } | null>(null);
+
+ // ── Single helpers ──
+
+ function handleSinglePreview(json: unknown) {
+ setSingleParseError(null);
+ setSingleDetectedEmail(null);
+ setSingleParsedJson(null);
+ const { valid, email } = previewCodexJson(json);
+ if (!valid) {
+ setSingleParseError(t("codexImportInvalidShape") || "Not a valid Codex auth.json");
+ return;
+ }
+ setSingleDetectedEmail(email);
+ if (email && !singleEmail) setSingleEmail(email);
+ setSingleParsedJson(json);
+ }
+
+ function handleSingleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ handleSinglePreview(JSON.parse(ev.target?.result as string));
+ } catch {
+ setSingleParseError(t("codexImportInvalidJson") || "Could not parse JSON");
+ }
+ };
+ reader.readAsText(file);
+ }
+
+ function handleSinglePasteChange(text: string) {
+ setSinglePasteText(text);
+ if (!text.trim()) {
+ setSingleParsedJson(null);
+ setSingleParseError(null);
+ setSingleDetectedEmail(null);
+ return;
+ }
+ try {
+ handleSinglePreview(JSON.parse(text));
+ } catch {
+ setSingleParseError(t("codexImportInvalidJson") || "Could not parse JSON");
+ setSingleParsedJson(null);
+ }
+ }
+
+ async function handleSingleSubmit() {
+ if (!singleParsedJson) return;
+ setSingleLoading(true);
+ setSingleError(null);
+ try {
+ const res = await fetch("/api/providers/codex-auth/import", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ source: { kind: "json", json: singleParsedJson },
+ name: singleName.trim() || undefined,
+ email: singleEmail.trim() || undefined,
+ overwriteExisting: singleOverwrite,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ setSingleError(
+ data.code === "duplicate_account"
+ ? t("codexImportDuplicate") ||
+ "Account already exists — enable Replace existing to overwrite"
+ : data.error || t("codexImportFailed") || "Failed to import"
+ );
+ return;
+ }
+ notify.success(t("codexImportSuccess") || "Codex connection imported successfully");
+ onSuccess();
+ } catch {
+ setSingleError(t("codexImportFailed") || "Failed to import Codex auth");
+ } finally {
+ setSingleLoading(false);
+ }
+ }
+
+ // ── Bulk helpers ──
+
+ function handleBulkFilesChange(e: React.ChangeEvent<HTMLInputElement>) {
+ const files = Array.from(e.target.files || []);
+ const entries: BulkEntry[] = [];
+ let pending = files.length;
+ if (pending === 0) return;
+ files.forEach((file) => {
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ const json = JSON.parse(ev.target?.result as string);
+ const { email } = previewCodexJson(json);
+ entries.push({
+ name: email || file.name.replace(".json", ""),
+ json,
+ parseError: null,
+ email,
+ });
+ } catch {
+ entries.push({ name: file.name, json: null, parseError: "Invalid JSON", email: null });
+ }
+ if (--pending === 0) setBulkEntries([...entries]);
+ };
+ reader.readAsText(file);
+ });
+ }
+
+ function handleBulkPasteChange(text: string) {
+ setBulkPasteText(text);
+ if (!text.trim()) {
+ setBulkEntries([]);
+ return;
+ }
+ setBulkEntries(parseBulkPasteText(text));
+ }
+
+ async function handleZipUpload(e: React.ChangeEvent<HTMLInputElement>) {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ setBulkZipExtracting(true);
+ setBulkZipError(null);
+ setBulkEntries([]);
+ try {
+ const res = await fetch("/api/providers/codex-auth/zip-extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/octet-stream" },
+ body: file,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ setBulkZipError(data.error || t("codexImportBulkZipError") || "Failed to extract ZIP");
+ return;
+ }
+ const extracted: BulkEntry[] = (data.entries || []).map(
+ (entry: { name: string; json: unknown; parseError: string | null }) => {
+ if (entry.parseError)
+ return { name: entry.name, json: null, parseError: entry.parseError, email: null };
+ const { email } = previewCodexJson(entry.json);
+ return {
+ name: email || entry.name.replace(".json", ""),
+ json: entry.json,
+ parseError: null,
+ email,
+ };
+ }
+ );
+ setBulkEntries(extracted);
+ } catch {
+ setBulkZipError(t("codexImportBulkZipError") || "Failed to extract ZIP");
+ } finally {
+ setBulkZipExtracting(false);
+ }
+ }
+
+ async function handleBulkSubmit() {
+ const validEntries = bulkEntries.filter((e) => !e.parseError && e.json !== null);
+ if (validEntries.length === 0) return;
+ setBulkLoading(true);
+ setBulkResult(null);
+ try {
+ const res = await fetch("/api/providers/codex-auth/import-bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ entries: validEntries.map((e) => ({
+ json: e.json,
+ name: e.name || undefined,
+ email: e.email || undefined,
+ })),
+ overwriteExisting: bulkOverwrite,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ notify.error(data.error || t("codexImportFailed") || "Failed to import");
+ return;
+ }
+ setBulkResult({ success: data.success, failed: data.failed, errors: data.errors || [] });
+ if (data.success > 0) onSuccess();
+ } catch {
+ notify.error(t("codexImportFailed") || "Failed to import Codex auth");
+ } finally {
+ setBulkLoading(false);
+ }
+ }
+
+ const singleCanSubmit = !!singleParsedJson && !singleParseError && !singleLoading;
+ const validBulkCount = bulkEntries.filter((e) => !e.parseError && e.json !== null).length;
+ const bulkCanSubmit = validBulkCount > 0 && !bulkLoading && !bulkZipExtracting;
+
+ const TOP_TABS: { id: ImportTopTab; label: string }[] = [
+ { id: "single", label: t("codexImportTabSingle") || "Single" },
+ { id: "bulk", label: t("codexImportTabBulk") || "Bulk" },
+ ];
+
+ const BULK_MODES: { id: BulkSubMode; label: string }[] = [
+ { id: "upload", label: t("codexImportBulkModeUpload") || "Upload files" },
+ { id: "paste", label: t("codexImportBulkModePaste") || "Paste list" },
+ { id: "zip", label: t("codexImportBulkModeZip") || "ZIP archive" },
+ ];
+
+ return (
+ <Modal
+ isOpen
+ onClose={onClose}
+ title={t("codexImportModalTitle") || "Import Codex Auth"}
+ maxWidth="max-w-lg"
+ >
+ <div className="flex flex-col gap-4">
+ {/* Top-level Single / Bulk tabs */}
+ <div className="flex border-b border-border">
+ {TOP_TABS.map(({ id, label }) => (
+ <button
+ key={id}
+ onClick={() => {
+ setTopTab(id);
+ setBulkResult(null);
+ setSingleError(null);
+ }}
+ className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
+ topTab === id
+ ? "border-primary text-primary"
+ : "border-transparent text-text-muted hover:text-text-main"
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* ── Single tab ── */}
+ {topTab === "single" && (
+ <>
+ {/* Source sub-tabs */}
+ <div className="flex border-b border-border">
+ {(["upload", "paste"] as const).map((id) => (
+ <button
+ key={id}
+ onClick={() => {
+ setSingleTab(id);
+ setSingleParsedJson(null);
+ setSingleParseError(null);
+ setSingleDetectedEmail(null);
+ }}
+ className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
+ singleTab === id
+ ? "border-primary text-primary"
+ : "border-transparent text-text-muted hover:text-text-main"
+ }`}
+ >
+ {id === "upload"
+ ? t("codexImportTabUpload") || "Upload file"
+ : t("codexImportTabPaste") || "Paste JSON"}
+ </button>
+ ))}
+ </div>
+
+ {singleTab === "upload" && (
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium text-text-main">
+ {t("codexImportFileLabel") || "Choose auth.json"}
+ </label>
+ <input
+ type="file"
+ accept=".json"
+ onChange={handleSingleFileChange}
+ className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer"
+ />
+ <p className="text-xs text-text-muted">
+ {t("codexImportFileHint") ||
+ "Select the auth.json file exported from Codex or OmniRoute."}
+ </p>
+ </div>
+ )}
+
+ {singleTab === "paste" && (
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium text-text-main">
+ {t("codexImportPasteLabel") || "Paste the JSON content"}
+ </label>
+ <textarea
+ value={singlePasteText}
+ onChange={(e) => handleSinglePasteChange(e.target.value)}
+ rows={7}
+ placeholder='{ "auth_mode": "chatgpt", ... }'
+ className="w-full rounded-lg border border-border bg-bg-subtle px-3 py-2 text-xs font-mono text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40 resize-none"
+ />
+ </div>
+ )}
+
+ {singleParseError && <p className="text-sm text-red-500">{singleParseError}</p>}
+ {singleDetectedEmail && !singleParseError && (
+ <p className="text-xs text-text-muted">
+ {t("codexImportDetectedEmail", { email: singleDetectedEmail }) ||
+ `Detected: ${singleDetectedEmail}`}
+ </p>
+ )}
+
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <label className="text-sm font-medium text-text-main">
+ {t("codexImportEmailLabel") || "Account email"}
+ </label>
+ <input
+ type="email"
+ value={singleEmail}
+ onChange={(e) => setSingleEmail(e.target.value)}
+ placeholder="[email protected]"
+ className="rounded-lg border border-border bg-bg-subtle px-3 py-2 text-sm text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40"
+ />
+ <p className="text-xs text-text-muted">
+ {t("codexImportEmailHint") || "Auto-detected from the file; edit if needed."}
+ </p>
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-sm font-medium text-text-main">
+ {t("codexImportNameLabel") || "Connection name (optional)"}
+ </label>
+ <input
+ type="text"
+ value={singleName}
+ onChange={(e) => setSingleName(e.target.value)}
+ placeholder={singleEmail || "Codex (imported)"}
+ className="rounded-lg border border-border bg-bg-subtle px-3 py-2 text-sm text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40"
+ />
+ </div>
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={singleOverwrite}
+ onChange={(e) => setSingleOverwrite(e.target.checked)}
+ className="rounded border-border"
+ />
+ <span className="text-sm text-text-main">
+ {t("codexImportOverwriteLabel") ||
+ "Replace existing connection if account already exists"}
+ </span>
+ </label>
+ </div>
+
+ {singleError && (
+ <div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3 text-sm text-red-400">
+ {singleError}
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-1">
+ <Button
+ onClick={handleSingleSubmit}
+ disabled={!singleCanSubmit}
+ loading={singleLoading}
+ fullWidth
+ >
+ {t("codexImportSubmit") || "Import"}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </>
+ )}
+
+ {/* ── Bulk tab ── */}
+ {topTab === "bulk" && (
+ <>
+ {/* Sub-mode selector */}
+ <div className="flex gap-1 p-1 bg-bg-subtle rounded-lg">
+ {BULK_MODES.map(({ id, label }) => (
+ <button
+ key={id}
+ onClick={() => {
+ setBulkMode(id);
+ setBulkEntries([]);
+ setBulkZipError(null);
+ setBulkPasteText("");
+ setBulkResult(null);
+ }}
+ className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
+ bulkMode === id
+ ? "bg-bg-primary text-text-main shadow-sm"
+ : "text-text-muted hover:text-text-main"
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* Upload mode */}
+ {bulkMode === "upload" && (
+ <div className="flex flex-col gap-2">
+ <input
+ type="file"
+ accept=".json"
+ multiple
+ onChange={handleBulkFilesChange}
+ className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer"
+ />
+ <p className="text-xs text-text-muted">
+ {t("codexImportBulkUploadHint") || "Select multiple .json files"}
+ </p>
+ </div>
+ )}
+
+ {/* Paste mode */}
+ {bulkMode === "paste" && (
+ <div className="flex flex-col gap-2">
+ <textarea
+ value={bulkPasteText}
+ onChange={(e) => handleBulkPasteChange(e.target.value)}
+ rows={7}
+ placeholder={'[{ "auth_mode": "chatgpt", ... }, ...]'}
+ className="w-full rounded-lg border border-border bg-bg-subtle px-3 py-2 text-xs font-mono text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40 resize-none"
+ />
+ <p className="text-xs text-text-muted">
+ {t("codexImportBulkPasteHint") || "JSON array or multiple JSONs separated by ---"}
+ </p>
+ </div>
+ )}
+
+ {/* ZIP mode */}
+ {bulkMode === "zip" && (
+ <div className="flex flex-col gap-2">
+ <input
+ type="file"
+ accept=".zip"
+ onChange={handleZipUpload}
+ disabled={bulkZipExtracting}
+ className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer disabled:opacity-50"
+ />
+ {bulkZipExtracting && (
+ <p className="text-xs text-text-muted animate-pulse">
+ {t("codexImportBulkZipExtracting") || "Extracting ZIP…"}
+ </p>
+ )}
+ {bulkZipError && <p className="text-sm text-red-500">{bulkZipError}</p>}
+ <p className="text-xs text-text-muted">
+ {t("codexImportBulkZipHint") ||
+ "Upload a .zip containing auth.json files (max 50 files, 10 MB)"}
+ </p>
+ </div>
+ )}
+
+ {/* Entry preview list */}
+ {bulkEntries.length > 0 && !bulkResult && (
+ <div className="flex flex-col gap-1 max-h-40 overflow-y-auto rounded-lg border border-border bg-bg-subtle p-2">
+ <p className="text-xs font-medium text-text-muted px-1">
+ {validBulkCount} / {bulkEntries.length} valid
+ </p>
+ {bulkEntries.map((entry, i) => (
+ <div key={i} className="flex items-center gap-2 px-2 py-1 rounded">
+ <span
+ className={`material-symbols-outlined text-[14px] ${entry.parseError ? "text-red-500" : "text-emerald-500"}`}
+ >
+ {entry.parseError ? "error" : "check_circle"}
+ </span>
+ <span className="text-xs text-text-main flex-1 truncate">{entry.name}</span>
+ {entry.parseError && (
+ <span className="text-xs text-red-400">{entry.parseError}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Overwrite checkbox */}
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={bulkOverwrite}
+ onChange={(e) => setBulkOverwrite(e.target.checked)}
+ className="rounded border-border"
+ />
+ <span className="text-sm text-text-main">
+ {t("codexImportOverwriteLabel") ||
+ "Replace existing connections if accounts already exist"}
+ </span>
+ </label>
+
+ {/* Result panel */}
+ {bulkResult && (
+ <div
+ className={`rounded-lg border px-4 py-3 text-sm ${
+ bulkResult.failed === 0
+ ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400"
+ : "bg-amber-500/10 border-amber-500/20 text-amber-400"
+ }`}
+ >
+ <p className="font-medium">
+ {bulkResult.success}{" "}
+ {t("codexImportBulkSuccess", { count: bulkResult.success }) || "imported"} ·{" "}
+ {bulkResult.failed}{" "}
+ {t("codexImportBulkFailed", { count: bulkResult.failed }) || "failed"}
+ </p>
+ {bulkResult.errors.length > 0 && (
+ <ul className="mt-2 space-y-0.5 text-xs">
+ {bulkResult.errors.map((e, i) => (
+ <li key={i}>
+ <span className="font-medium">{e.name}:</span> {e.message}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-1">
+ <Button
+ onClick={handleBulkSubmit}
+ disabled={!bulkCanSubmit}
+ loading={bulkLoading}
+ fullWidth
+ >
+ {bulkLoading
+ ? t("saving") || "Importing…"
+ : typeof t.has === "function" && t.has("codexImportBulkSubmit")
+ ? t("codexImportBulkSubmit", { count: validBulkCount })
+ : `Import ${validBulkCount} accounts`}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth>
+ {t("cancel")}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+export function ApplyCodexAuthModal({
+ connectionId,
+ inProgress,
+ onConfirm,
+ onClose,
+}: {
+ connectionId: string | null;
+ inProgress: boolean;
+ onConfirm: (id: string) => Promise<void>;
+ onClose: () => void;
+}) {
+ const t = useTranslations("providers");
+ // `key`-reset pattern: caller re-mounts the modal each open (different
+ // connectionId triggers a new instance), so local confirmation state is
+ // naturally fresh without any post-render bookkeeping.
+ const [confirmed, setConfirmed] = useState(false);
+ const isOpen = !!connectionId;
+
+ if (!connectionId) return null;
+
+ const title =
+ typeof t.has === "function" && t.has("codexApplyModalTitle")
+ ? t("codexApplyModalTitle")
+ : "Apply to Local Codex";
+ const targetLabel =
+ typeof t.has === "function" && t.has("codexApplyTargetLabel")
+ ? t("codexApplyTargetLabel")
+ : "Target path";
+ const backupLabel =
+ typeof t.has === "function" && t.has("codexApplyBackupLabel")
+ ? t("codexApplyBackupLabel")
+ : "Backups";
+ const warning =
+ typeof t.has === "function" && t.has("codexApplyWarning")
+ ? t("codexApplyWarning")
+ : "This will replace the existing auth.json. Continue?";
+ const confirmText =
+ typeof t.has === "function" && t.has("codexApplyConfirmCheckbox")
+ ? t("codexApplyConfirmCheckbox")
+ : "I confirm I want to replace the existing auth.json";
+ const applyText = typeof t.has === "function" && t.has("codexApply") ? t("codexApply") : "Apply";
+
+ return (
+ <Modal isOpen={isOpen} title={title} onClose={onClose}>
+ <div className="flex flex-col gap-4">
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
+ <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
+ ~/.codex/auth.json
+ </code>
+ <p className="mt-1 text-xs text-text-muted">{t("providerDetailPathAutoDetectedAllOs")}</p>
+ </div>
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
+ <ul className="text-xs text-text-muted space-y-0.5 list-disc pl-4">
+ <li>
+ <code className="text-text-main">~/.codex/auth-&lt;timestamp&gt;.bak</code> — quick
+ local rollback
+ </li>
+ <li>Centralized backup history (audit trail)</li>
+ </ul>
+ </div>
+ <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-amber-200">
+ <div className="flex items-start gap-2">
+ <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
+ warning
+ </span>
+ <span>{warning}</span>
+ </div>
+ </div>
+ <label className="flex items-center gap-2 text-sm text-text-muted cursor-pointer">
+ <input
+ type="checkbox"
+ checked={confirmed}
+ onChange={(e) => setConfirmed(e.target.checked)}
+ className="rounded border-border"
+ />
+ {confirmText}
+ </label>
+ <div className="flex gap-2">
+ <Button
+ onClick={() => void onConfirm(connectionId)}
+ fullWidth
+ disabled={!confirmed || inProgress}
+ >
+ {inProgress ? t("saving") : applyText}
+ </Button>
+ <Button onClick={onClose} variant="ghost" fullWidth disabled={inProgress}>
+ {t("cancel")}
+ </Button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+// ──── ImportClaudeAuthModal ────────────────────────────────────────────────────
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportGeminiAuthModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportGeminiAuthModal.tsx
new file mode 100644
index 0000000000..af00548f8d
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/ImportGeminiAuthModal.tsx
@@ -0,0 +1,706 @@
+"use client";
+import { useState } from "react";
+import { useNotificationStore } from "@/store/notificationStore";
+import { useTranslations } from "next-intl";
+import { Button, Modal } from "@/shared/components";
+interface ImportGeminiAuthModalProps {
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+type GeminiImportTopTab = "single" | "bulk";
+type GeminiBulkSubMode = "upload" | "paste" | "zip";
+
+interface GeminiBulkEntry {
+ name: string;
+ json: unknown;
+ parseError: string | null;
+ email: string | null;
+}
+
+function extractEmailFromGeminiJwt(idToken: string): string | null {
+ try {
+ const parts = idToken.split(".");
+ if (parts.length !== 3) return null;
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
+ return typeof payload.email === "string" ? payload.email : null;
+ } catch {
+ return null;
+ }
+}
+
+function previewGeminiJson(json: unknown): { valid: boolean; email: string | null } {
+ try {
+ const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
+ if (!doc) return { valid: false, email: null };
+ if (!doc.access_token || !doc.refresh_token || !doc.id_token)
+ return { valid: false, email: null };
+ const email = typeof doc.id_token === "string" ? extractEmailFromGeminiJwt(doc.id_token) : null;
+ return { valid: true, email };
+ } catch {
+ return { valid: false, email: null };
+ }
+}
+
+export function ImportGeminiAuthModal({ onClose, onSuccess }: ImportGeminiAuthModalProps) {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ const [topTab, setTopTab] = useState<GeminiImportTopTab>("single");
+ const [singleSubTab, setSingleSubTab] = useState<"upload" | "paste">("upload");
+ const [bulkSubMode, setBulkSubMode] = useState<GeminiBulkSubMode>("upload");
+
+ // Single
+ const [singleJson, setSingleJson] = useState<unknown>(null);
+ const [singlePasteText, setSinglePasteText] = useState("");
+ const [singleName, setSingleName] = useState("");
+ const [singleEmail, setSingleEmail] = useState("");
+ const [overwriteExisting, setOverwriteExisting] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+
+ // Bulk
+ const [bulkEntries, setBulkEntries] = useState<GeminiBulkEntry[]>([]);
+ const [bulkPasteText, setBulkPasteText] = useState("");
+ const [bulkSubmitting, setBulkSubmitting] = useState(false);
+ const [bulkErrors, setBulkErrors] = useState<{ index: number; name: string; message: string }[]>(
+ []
+ );
+ const [bulkResult, setBulkResult] = useState<{
+ success: number;
+ failed: number;
+ total: number;
+ } | null>(null);
+ const [zipExtracting, setZipExtracting] = useState(false);
+
+ const handleSingleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ const json = JSON.parse(ev.target?.result as string);
+ setSingleJson(json);
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportInvalidJson")
+ ? t("geminiImportInvalidJson")
+ : "Could not parse the file as JSON"
+ );
+ }
+ };
+ reader.readAsText(file);
+ };
+
+ const handleSingleSubmit = async () => {
+ if (submitting) return;
+ setSubmitting(true);
+ try {
+ const body =
+ singleSubTab === "paste"
+ ? {
+ source: { kind: "text", text: singlePasteText },
+ name: singleName || undefined,
+ email: singleEmail || undefined,
+ overwriteExisting,
+ }
+ : {
+ source: { kind: "json", json: singleJson },
+ name: singleName || undefined,
+ email: singleEmail || undefined,
+ overwriteExisting,
+ };
+
+ const res = await fetch("/api/providers/gemini-cli-auth/import", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ const data = await res.json().catch(() => ({}));
+
+ if (!res.ok) {
+ if (data.code === "duplicate_account") {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportDuplicate")
+ ? t("geminiImportDuplicate")
+ : 'Account already exists — enable "Replace existing" to overwrite'
+ );
+ } else if (data.code === "identity_unverified") {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportIdentityUnverified")
+ ? t("geminiImportIdentityUnverified")
+ : 'Could not verify identity from id_token. Enable "Replace existing" or provide an email.'
+ );
+ } else {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("geminiImportFailed")
+ ? t("geminiImportFailed")
+ : "Failed to import Gemini auth")
+ );
+ }
+ return;
+ }
+
+ const preview = previewGeminiJson(singleJson);
+ notify.success(
+ typeof t.has === "function" && t.has("geminiImportSuccess")
+ ? t("geminiImportSuccess")
+ : `Gemini connection imported successfully${preview.email ? ` (${preview.email})` : ""}`
+ );
+ onSuccess();
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportFailed")
+ ? t("geminiImportFailed")
+ : "Failed to import Gemini auth"
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const handleBulkFilesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files || []);
+ const newEntries: GeminiBulkEntry[] = [];
+ let pending = files.length;
+ if (!pending) return;
+ files.forEach((file) => {
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ try {
+ const json = JSON.parse(ev.target?.result as string);
+ const { email } = previewGeminiJson(json);
+ newEntries.push({
+ name: file.name.replace(/\.json$/, ""),
+ json,
+ parseError: null,
+ email,
+ });
+ } catch {
+ newEntries.push({
+ name: file.name,
+ json: null,
+ parseError: "Not valid JSON",
+ email: null,
+ });
+ }
+ pending--;
+ if (pending === 0) setBulkEntries((prev) => [...prev, ...newEntries]);
+ };
+ reader.readAsText(file);
+ });
+ };
+
+ const handleBulkPasteChange = (text: string) => {
+ setBulkPasteText(text);
+ const trimmed = text.trim();
+ if (!trimmed) {
+ setBulkEntries([]);
+ return;
+ }
+ try {
+ const arr = JSON.parse(trimmed);
+ if (Array.isArray(arr)) {
+ setBulkEntries(
+ arr.map((item, i) => {
+ const { email } = previewGeminiJson(item);
+ return { name: email || `entry ${i + 1}`, json: item, parseError: null, email };
+ })
+ );
+ } else {
+ const { email } = previewGeminiJson(arr);
+ setBulkEntries([{ name: email || "entry 1", json: arr, parseError: null, email }]);
+ }
+ } catch {
+ setBulkEntries([
+ { name: "parse error", json: null, parseError: "Invalid JSON", email: null },
+ ]);
+ }
+ };
+
+ const handleZipUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ setZipExtracting(true);
+ try {
+ const res = await fetch("/api/providers/gemini-cli-auth/zip-extract", {
+ method: "POST",
+ headers: { "Content-Type": "application/zip" },
+ body: file,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("geminiImportBulkZipError")
+ ? t("geminiImportBulkZipError")
+ : "Failed to extract ZIP")
+ );
+ return;
+ }
+ const entries: GeminiBulkEntry[] = (data.entries || []).map(
+ (e: { name: string; json: unknown; parseError: string | null }) => {
+ const { email } = previewGeminiJson(e.json);
+ return { name: e.name, json: e.json, parseError: e.parseError, email };
+ }
+ );
+ setBulkEntries(entries);
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportBulkZipError")
+ ? t("geminiImportBulkZipError")
+ : "Failed to extract ZIP"
+ );
+ } finally {
+ setZipExtracting(false);
+ }
+ };
+
+ const handleBulkSubmit = async () => {
+ if (bulkSubmitting) return;
+ setBulkSubmitting(true);
+ setBulkErrors([]);
+ setBulkResult(null);
+ try {
+ const validEntries = bulkEntries.filter((e) => e.json !== null);
+ if (validEntries.length === 0) {
+ notify.error("No valid entries to import");
+ return;
+ }
+ const res = await fetch("/api/providers/gemini-cli-auth/import-bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ entries: validEntries.map((e) => ({
+ json: e.json,
+ name: e.name,
+ email: e.email || undefined,
+ })),
+ overwriteExisting,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ notify.error(
+ data.error ||
+ (typeof t.has === "function" && t.has("geminiImportBulkFailed")
+ ? t("geminiImportBulkFailed")
+ : "Some entries failed to import")
+ );
+ return;
+ }
+ setBulkResult({ success: data.success, failed: data.failed, total: data.total });
+ if (data.errors?.length > 0) setBulkErrors(data.errors);
+ if (data.success > 0) {
+ notify.success(
+ typeof t.has === "function" && t.has("geminiImportBulkSuccess")
+ ? t("geminiImportBulkSuccess", { count: data.success })
+ : `Imported ${data.success} Gemini connections`
+ );
+ if (data.failed === 0) onSuccess();
+ }
+ } catch {
+ notify.error(
+ typeof t.has === "function" && t.has("geminiImportBulkFailed")
+ ? t("geminiImportBulkFailed")
+ : "Some entries failed to import"
+ );
+ } finally {
+ setBulkSubmitting(false);
+ }
+ };
+
+ const tabLabels: Record<GeminiImportTopTab, string> = {
+ single:
+ typeof t.has === "function" && t.has("geminiImportTabSingle")
+ ? t("geminiImportTabSingle")
+ : "Single",
+ bulk:
+ typeof t.has === "function" && t.has("geminiImportTabBulk")
+ ? t("geminiImportTabBulk")
+ : "Bulk",
+ };
+
+ const modalTitle =
+ typeof t.has === "function" && t.has("geminiImportModalTitle")
+ ? t("geminiImportModalTitle")
+ : "Import Gemini Auth";
+
+ return (
+ <Modal isOpen onClose={onClose} title={modalTitle}>
+ <div className="flex flex-col gap-4">
+ <div className="flex gap-1 border-b border-border pb-0">
+ {(["single", "bulk"] as GeminiImportTopTab[]).map((tab) => (
+ <button
+ key={tab}
+ onClick={() => setTopTab(tab)}
+ className={`px-3 py-1.5 text-sm rounded-t-md transition-colors ${
+ topTab === tab
+ ? "bg-primary/10 text-primary border-b-2 border-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {tabLabels[tab]}
+ </button>
+ ))}
+ </div>
+
+ {topTab === "single" && (
+ <div className="flex flex-col gap-3">
+ <div className="flex gap-1">
+ {(["upload", "paste"] as const).map((sub) => (
+ <button
+ key={sub}
+ onClick={() => setSingleSubTab(sub)}
+ className={`px-2 py-1 text-xs rounded transition-colors ${
+ singleSubTab === sub
+ ? "bg-bg-subtle text-text-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {sub === "upload"
+ ? typeof t.has === "function" && t.has("geminiImportTabUpload")
+ ? t("geminiImportTabUpload")
+ : "Upload file"
+ : typeof t.has === "function" && t.has("geminiImportTabPaste")
+ ? t("geminiImportTabPaste")
+ : "Paste JSON"}
+ </button>
+ ))}
+ </div>
+ {singleSubTab === "upload" ? (
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportFileLabel")
+ ? t("geminiImportFileLabel")
+ : "Choose oauth_creds.json"}
+ </label>
+ <input
+ type="file"
+ accept=".json"
+ onChange={handleSingleFileChange}
+ className="block w-full text-sm"
+ />
+ {singleJson && previewGeminiJson(singleJson).valid && (
+ <p className="mt-1 text-xs text-emerald-500">
+ Valid Gemini OAuth credentials
+ {previewGeminiJson(singleJson).email
+ ? ` (${previewGeminiJson(singleJson).email})`
+ : ""}
+ </p>
+ )}
+ {singleJson && !previewGeminiJson(singleJson).valid && (
+ <p className="mt-1 text-xs text-red-500">
+ {typeof t.has === "function" && t.has("geminiImportInvalidShape")
+ ? t("geminiImportInvalidShape")
+ : "The file is not a valid oauth_creds.json"}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportPasteLabel")
+ ? t("geminiImportPasteLabel")
+ : "Paste the JSON content"}
+ </label>
+ <textarea
+ value={singlePasteText}
+ onChange={(e) => setSinglePasteText(e.target.value)}
+ rows={6}
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
+ placeholder='{ "access_token": "...", "refresh_token": "...", "id_token": "..." }'
+ />
+ </div>
+ )}
+ <div className="grid grid-cols-2 gap-2">
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportEmailLabel")
+ ? t("geminiImportEmailLabel")
+ : "Account email"}
+ </label>
+ <input
+ type="email"
+ value={singleEmail}
+ onChange={(e) => setSingleEmail(e.target.value)}
+ placeholder="auto-detected from id_token"
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportNameLabel")
+ ? t("geminiImportNameLabel")
+ : "Connection name (optional)"}
+ </label>
+ <input
+ type="text"
+ value={singleName}
+ onChange={(e) => setSingleName(e.target.value)}
+ placeholder="My Gemini account"
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
+ />
+ </div>
+ </div>
+ <label className="flex items-center gap-2 text-xs text-text-muted">
+ <input
+ type="checkbox"
+ checked={overwriteExisting}
+ onChange={(e) => setOverwriteExisting(e.target.checked)}
+ />
+ {typeof t.has === "function" && t.has("geminiImportOverwriteLabel")
+ ? t("geminiImportOverwriteLabel")
+ : "Replace existing connection if account already exists"}
+ </label>
+ <Button
+ loading={submitting}
+ onClick={handleSingleSubmit}
+ disabled={singleSubTab === "upload" ? !singleJson : !singlePasteText.trim()}
+ >
+ {typeof t.has === "function" && t.has("geminiImportSubmit")
+ ? t("geminiImportSubmit")
+ : "Import"}
+ </Button>
+ </div>
+ )}
+
+ {topTab === "bulk" && (
+ <div className="flex flex-col gap-3">
+ <div className="flex gap-1">
+ {(["upload", "paste", "zip"] as GeminiBulkSubMode[]).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => {
+ setBulkSubMode(mode);
+ setBulkEntries([]);
+ }}
+ className={`px-2 py-1 text-xs rounded transition-colors ${
+ bulkSubMode === mode
+ ? "bg-bg-subtle text-text-primary"
+ : "text-text-muted hover:text-text-primary"
+ }`}
+ >
+ {mode === "upload"
+ ? typeof t.has === "function" && t.has("geminiImportBulkModeUpload")
+ ? t("geminiImportBulkModeUpload")
+ : "Upload files"
+ : mode === "paste"
+ ? typeof t.has === "function" && t.has("geminiImportBulkModePaste")
+ ? t("geminiImportBulkModePaste")
+ : "Paste JSON array"
+ : typeof t.has === "function" && t.has("geminiImportBulkModeZip")
+ ? t("geminiImportBulkModeZip")
+ : "Upload ZIP"}
+ </button>
+ ))}
+ </div>
+
+ {bulkSubMode === "upload" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportBulkUploadHint")
+ ? t("geminiImportBulkUploadHint")
+ : "Drop or pick up to 50 oauth_creds.json files (256KB each, 10MB total)."}
+ </p>
+ <input
+ type="file"
+ accept=".json"
+ multiple
+ onChange={handleBulkFilesChange}
+ className="block w-full text-sm"
+ />
+ </div>
+ )}
+ {bulkSubMode === "paste" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportBulkPasteHint")
+ ? t("geminiImportBulkPasteHint")
+ : "Paste an array of objects: [{ json, name?, email? }, ...]"}
+ </p>
+ <textarea
+ value={bulkPasteText}
+ onChange={(e) => handleBulkPasteChange(e.target.value)}
+ rows={6}
+ className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
+ placeholder="[{ ... }, { ... }]"
+ />
+ </div>
+ )}
+ {bulkSubMode === "zip" && (
+ <div>
+ <p className="text-xs text-text-muted mb-1">
+ {typeof t.has === "function" && t.has("geminiImportBulkZipHint")
+ ? t("geminiImportBulkZipHint")
+ : "ZIP containing oauth_creds.json entries. Max 50 entries, 10MB unpacked."}
+ </p>
+ {zipExtracting ? (
+ <p className="text-xs text-primary animate-pulse">
+ {typeof t.has === "function" && t.has("geminiImportBulkZipExtracting")
+ ? t("geminiImportBulkZipExtracting")
+ : "Extracting ZIP…"}
+ </p>
+ ) : (
+ <input
+ type="file"
+ accept=".zip"
+ onChange={handleZipUpload}
+ className="block w-full text-sm"
+ />
+ )}
+ </div>
+ )}
+
+ {bulkEntries.length > 0 && (
+ <div className="rounded border border-border bg-bg-subtle px-2 py-1.5 max-h-36 overflow-y-auto">
+ {bulkEntries.map((e, i) => (
+ <div
+ key={i}
+ className={`text-xs py-0.5 flex items-center gap-1 ${e.parseError ? "text-red-500" : "text-text-main"}`}
+ >
+ <span className="material-symbols-outlined text-[12px]">
+ {e.parseError ? "error" : "check_circle"}
+ </span>
+ {e.name}
+ {e.email ? ` (${e.email})` : ""}
+ {e.parseError ? ` — ${e.parseError}` : ""}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <label className="flex items-center gap-2 text-xs text-text-muted">
+ <input
+ type="checkbox"
+ checked={overwriteExisting}
+ onChange={(e) => setOverwriteExisting(e.target.checked)}
+ />
+ {typeof t.has === "function" && t.has("geminiImportOverwriteLabel")
+ ? t("geminiImportOverwriteLabel")
+ : "Replace existing connection if account already exists"}
+ </label>
+
+ {bulkResult && (
+ <div className="rounded bg-bg-subtle px-2 py-1.5 text-xs">
+ {bulkResult.success}/{bulkResult.total} imported
+ {bulkResult.failed > 0 ? `, ${bulkResult.failed} failed` : ""}
+ </div>
+ )}
+ {bulkErrors.length > 0 && (
+ <div className="rounded border border-red-500/30 bg-red-500/5 px-2 py-1.5 max-h-28 overflow-y-auto">
+ {bulkErrors.map((e) => (
+ <div key={e.index} className="text-xs text-red-500 py-0.5">
+ {e.name}: {e.message}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <Button
+ loading={bulkSubmitting}
+ onClick={handleBulkSubmit}
+ disabled={bulkEntries.filter((e) => e.json !== null).length === 0}
+ >
+ {typeof t.has === "function" && t.has("geminiImportBulkSubmit")
+ ? t("geminiImportBulkSubmit")
+ : "Import all"}
+ </Button>
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+// ──── ApplyGeminiAuthModal ────────────────────────────────────────────────────
+
+export function ApplyGeminiAuthModal({
+ connectionId,
+ inProgress,
+ onConfirm,
+ onClose,
+}: {
+ connectionId: string | null;
+ inProgress: boolean;
+ onConfirm: (id: string) => Promise<void>;
+ onClose: () => void;
+}) {
+ const t = useTranslations("providers");
+ const [confirmed, setConfirmed] = useState(false);
+ const isOpen = !!connectionId;
+
+ if (!connectionId) return null;
+
+ const title =
+ typeof t.has === "function" && t.has("geminiApplyModalTitle")
+ ? t("geminiApplyModalTitle")
+ : "Apply to Local Gemini CLI";
+ const targetLabel =
+ typeof t.has === "function" && t.has("geminiApplyTargetLabel")
+ ? t("geminiApplyTargetLabel")
+ : "Target path";
+ const backupLabel =
+ typeof t.has === "function" && t.has("geminiApplyBackupLabel")
+ ? t("geminiApplyBackupLabel")
+ : "Backups";
+ const warning =
+ typeof t.has === "function" && t.has("geminiApplyWarning")
+ ? t("geminiApplyWarning")
+ : "This will replace the existing oauth_creds.json and update google_accounts.json. Continue?";
+ const confirmText =
+ typeof t.has === "function" && t.has("geminiApplyConfirmCheckbox")
+ ? t("geminiApplyConfirmCheckbox")
+ : "I confirm I want to replace the existing oauth_creds.json";
+ const applyText =
+ typeof t.has === "function" && t.has("geminiApply") ? t("geminiApply") : "Apply";
+ const accountsHint =
+ typeof t.has === "function" && t.has("geminiApplyAccountsHint")
+ ? t("geminiApplyAccountsHint")
+ : "The google_accounts.json active account will be updated to match this connection.";
+
+ return (
+ <Modal isOpen={isOpen} title={title} onClose={onClose}>
+ <div className="flex flex-col gap-4">
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
+ <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
+ ~/.gemini/oauth_creds.json
+ </code>
+ <p className="mt-1 text-xs text-text-muted">Path is auto-detected per OS (Linux/Mac).</p>
+ </div>
+ <div>
+ <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
+ <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
+ ~/.gemini/oauth_creds-&#123;timestamp&#125;.bak
+ </code>
+ </div>
+ <div className="rounded bg-amber-500/10 border border-amber-500/20 px-3 py-2 text-xs text-amber-400">
+ {accountsHint}
+ </div>
+ <p className="text-sm text-text-muted">{warning}</p>
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ checked={confirmed}
+ onChange={(e) => setConfirmed(e.target.checked)}
+ />
+ {confirmText}
+ </label>
+ <div className="flex justify-end gap-2">
+ <Button variant="secondary" onClick={onClose} disabled={inProgress}>
+ Cancel
+ </Button>
+ <Button
+ loading={inProgress}
+ disabled={!confirmed || inProgress}
+ onClick={() => void onConfirm(connectionId)}
+ >
+ {applyText}
+ </Button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/authImportModals.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/authImportModals.test.tsx
new file mode 100644
index 0000000000..3365c2c6d4
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/authImportModals.test.tsx
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+//
+// Phase 1a regression test for Issue #3501. The three auth-import modal clusters
+// (Codex/Claude/Gemini) were extracted out of the 12.8K-LOC god-component into
+// standalone files. This proves each now mounts in isolation with its clean
+// { onClose, onSuccess } interface — the payoff of the extraction (Hard Rule #8).
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ImportCodexAuthModal } from "../ImportCodexAuthModal";
+import { ImportClaudeAuthModal } from "../ImportClaudeAuthModal";
+import { ImportGeminiAuthModal } from "../ImportGeminiAuthModal";
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "openai" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+}));
+vi.mock("next-intl", () => ({
+ useTranslations: (ns?: string) => (k: string) => (ns ? `${ns}.${k}` : k),
+}));
+
+const cleanups: Array<() => void> = [];
+
+function renderModal(node: React.ReactElement) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(node));
+ cleanups.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+ return container;
+}
+
+describe("auth-import modals (Phase 1a extraction)", () => {
+ beforeEach(() => {
+ (
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve({ ok: true, json: async () => ({}), text: async () => "" } as Response)
+ )
+ );
+ });
+
+ afterEach(() => {
+ while (cleanups.length) cleanups.pop()?.();
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ });
+
+ it("ImportCodexAuthModal mounts standalone", () => {
+ const onClose = vi.fn();
+ const onSuccess = vi.fn();
+ const c = renderModal(<ImportCodexAuthModal onClose={onClose} onSuccess={onSuccess} />);
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+
+ it("ImportClaudeAuthModal mounts standalone", () => {
+ const c = renderModal(<ImportClaudeAuthModal onClose={vi.fn()} onSuccess={vi.fn()} />);
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+
+ it("ImportGeminiAuthModal mounts standalone", () => {
+ const c = renderModal(<ImportGeminiAuthModal onClose={vi.fn()} onSuccess={vi.fn()} />);
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/connModals.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/connModals.test.tsx
new file mode 100644
index 0000000000..ce4e2ac998
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/connModals.test.tsx
@@ -0,0 +1,155 @@
+// @vitest-environment jsdom
+//
+// Phase 1c regression tests for Issue #3501. AddApiKeyModal and EditConnectionModal
+// were extracted from the god-component. This proves each mounts in isolation with
+// its clean Props interface (Hard Rule #8, Rule #18 TDD gate).
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import AddApiKeyModal from "../AddApiKeyModal";
+import EditConnectionModal from "../EditConnectionModal";
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ id: "openai" }),
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+}));
+vi.mock("next-intl", () => ({
+ useTranslations: (ns?: string) => (k: string) => (ns ? `${ns}.${k}` : k),
+}));
+
+const cleanups: Array<() => void> = [];
+
+function renderModal(node: React.ReactElement) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(node));
+ cleanups.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+ return container;
+}
+
+describe("conn-modals (Phase 1c extraction)", () => {
+ beforeEach(() => {
+ (
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve({ ok: true, json: async () => ({}), text: async () => "" } as Response)
+ )
+ );
+ vi.stubGlobal("localStorage", {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ clear: () => undefined,
+ });
+ });
+
+ afterEach(() => {
+ while (cleanups.length) cleanups.pop()?.();
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ });
+
+ it("AddApiKeyModal mounts standalone when isOpen=false", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const c = renderModal(
+ <AddApiKeyModal
+ isOpen={false}
+ provider="openai"
+ providerName="OpenAI"
+ isCompatible={false}
+ onSave={onSave}
+ onClose={vi.fn()}
+ />
+ );
+ // When isOpen=false the modal renders nothing (null body) — no throw is the assertion.
+ expect(c).toBeDefined();
+ });
+
+ it("AddApiKeyModal mounts standalone when isOpen=true", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const c = renderModal(
+ <AddApiKeyModal
+ isOpen={true}
+ provider="openai"
+ providerName="OpenAI"
+ isCompatible={false}
+ onSave={onSave}
+ onClose={vi.fn()}
+ />
+ );
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+
+ it("AddApiKeyModal returns null when provider is falsy", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const c = renderModal(
+ <AddApiKeyModal isOpen={true} onSave={onSave} onClose={vi.fn()} />
+ );
+ // No provider → renders null
+ expect(c.textContent).toBe("");
+ });
+
+ it("EditConnectionModal mounts standalone when connection=null", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const c = renderModal(
+ <EditConnectionModal
+ isOpen={false}
+ connection={null}
+ onSave={onSave}
+ onClose={vi.fn()}
+ />
+ );
+ // connection=null → renders null — no throw is the assertion
+ expect(c).toBeDefined();
+ });
+
+ it("EditConnectionModal mounts standalone with a connection", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const connection = {
+ id: "conn-1",
+ name: "Test Connection",
+ provider: "openai",
+ authType: "apikey",
+ priority: 1,
+ };
+ const c = renderModal(
+ <EditConnectionModal
+ isOpen={true}
+ connection={connection}
+ onSave={onSave}
+ onClose={vi.fn()}
+ />
+ );
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+
+ it("EditConnectionModal renders without ReferenceError for oauth connection", () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const connection = {
+ id: "conn-oauth",
+ name: "OAuth Account",
+ email: "[email protected]",
+ provider: "claude",
+ authType: "oauth",
+ priority: 1,
+ };
+ // Must not throw; tests that ERROR_TYPE_LABELS and formatTimeAgo are properly imported
+ expect(() =>
+ renderModal(
+ <EditConnectionModal
+ isOpen={true}
+ connection={connection}
+ onSave={onSave}
+ onClose={vi.fn()}
+ />
+ )
+ ).not.toThrow();
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/editCompatibleNodeModal.test.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/editCompatibleNodeModal.test.tsx
new file mode 100644
index 0000000000..678820ddff
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/__tests__/editCompatibleNodeModal.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+//
+// Phase 1b regression test for Issue #3501. EditCompatibleNodeModal was extracted
+// out of the god-component into a standalone file (its node/props types co-moved,
+// the shared CC_COMPATIBLE_DEFAULT_CHAT_PATH constant pulled into a leaf module to
+// keep the import graph acyclic). Proves it mounts in isolation (Hard Rule #8).
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import EditCompatibleNodeModal from "../EditCompatibleNodeModal";
+
+vi.mock("next-intl", () => ({
+ useTranslations: (ns?: string) => (k: string) => (ns ? `${ns}.${k}` : k),
+}));
+
+const cleanups: Array<() => void> = [];
+
+function renderModal(node: React.ReactElement) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(node));
+ cleanups.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+ return container;
+}
+
+describe("EditCompatibleNodeModal (Phase 1b extraction)", () => {
+ beforeEach(() => {
+ (
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+ });
+
+ afterEach(() => {
+ while (cleanups.length) cleanups.pop()?.();
+ document.body.innerHTML = "";
+ });
+
+ it("mounts standalone when open", () => {
+ const c = renderModal(
+ <EditCompatibleNodeModal
+ isOpen
+ node={{ id: "n1", name: "Node", baseUrl: "https://x" }}
+ onSave={async () => {}}
+ onClose={() => {}}
+ isCcCompatible
+ />
+ );
+ expect(c.querySelector("*")).not.toBeNull();
+ });
+
+ it("renders nothing harmful when closed", () => {
+ expect(() =>
+ renderModal(
+ <EditCompatibleNodeModal isOpen={false} node={null} onSave={async () => {}} onClose={() => {}} />
+ )
+ ).not.toThrow();
+ });
+});
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/hooks/useModelCompatState.ts b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useModelCompatState.ts
new file mode 100644
index 0000000000..c91e41b896
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useModelCompatState.ts
@@ -0,0 +1,101 @@
+/**
+ * useModelCompatState — Issue #3501 Phase 1e
+ *
+ * Owns all model-compat derivations (buildCompatMap, isModelHidden,
+ * effectiveNormalizeForProtocol, effectivePreserveForProtocol,
+ * anyNormalizeCompatBadge, anyNoPreserveCompatBadge) that used to be
+ * inlined in the god-component.
+ *
+ * Leaf module: imports ONLY from providerPageHelpers and React.
+ * No import from ProviderDetailPageClient → zero cycle risk.
+ */
+import { useMemo, useCallback } from "react";
+import { MODEL_COMPAT_PROTOCOL_KEYS } from "@/shared/constants/modelCompat";
+import {
+ buildCompatMap,
+ isModelHiddenFn,
+ effectiveNormalizeForProtocol,
+ effectivePreserveForProtocol,
+ anyNormalizeCompatBadge,
+ anyNoPreserveCompatBadge,
+ effectiveUpstreamHeadersForProtocol,
+ type CompatModelRow,
+ type CompatModelMap,
+} from "../providerPageHelpers";
+
+export interface ModelCompatState {
+ /** The computed custom-model map (memoised). */
+ customMap: CompatModelMap;
+ /** The computed override map (memoised). */
+ overrideMap: CompatModelMap;
+ /** Stable callback: is the given model hidden? */
+ isModelHidden: (modelId: string) => boolean;
+ /** Stable callback: effective normalize flag for (modelId, protocol). */
+ effectiveModelNormalize: (modelId: string, protocol?: string) => boolean;
+ /** Stable callback: effective preserve-developer flag for (modelId, protocol). */
+ effectiveModelPreserveDeveloper: (modelId: string, protocol?: string) => boolean;
+ /** Stable callback: upstream-headers record for (modelId, protocol). */
+ getUpstreamHeadersRecord: (modelId: string, protocol: string) => Record<string, string>;
+ /** Stable callback: should the normalize compat badge be shown? */
+ anyNormalizeCompatBadge: (modelId: string) => boolean;
+ /** Stable callback: should the no-preserve compat badge be shown? */
+ anyNoPreserveCompatBadge: (modelId: string) => boolean;
+}
+
+/**
+ * Hook that derives stable compat callbacks from raw model-meta arrays.
+ *
+ * @param customModels The `modelMeta.customModels` array from page state.
+ * @param modelCompatOverrides The `modelMeta.modelCompatOverrides` array from page state.
+ */
+export function useModelCompatState(
+ customModels: CompatModelRow[],
+ modelCompatOverrides: Array<CompatModelRow & { id: string }>
+): ModelCompatState {
+ const customMap = useMemo(() => buildCompatMap(customModels), [customModels]);
+ const overrideMap = useMemo(() => buildCompatMap(modelCompatOverrides), [modelCompatOverrides]);
+
+ const isModelHidden = useCallback(
+ (modelId: string) => isModelHiddenFn(modelId, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ const effectiveModelNormalize = useCallback(
+ (modelId: string, protocol = MODEL_COMPAT_PROTOCOL_KEYS[0]) =>
+ effectiveNormalizeForProtocol(modelId, protocol, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ const effectiveModelPreserveDeveloper = useCallback(
+ (modelId: string, protocol = MODEL_COMPAT_PROTOCOL_KEYS[0]) =>
+ effectivePreserveForProtocol(modelId, protocol, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ const getUpstreamHeadersRecord = useCallback(
+ (modelId: string, protocol: string) =>
+ effectiveUpstreamHeadersForProtocol(modelId, protocol, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ const anyNormalizeCompatBadgeFn = useCallback(
+ (modelId: string) => anyNormalizeCompatBadge(modelId, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ const anyNoPreserveCompatBadgeFn = useCallback(
+ (modelId: string) => anyNoPreserveCompatBadge(modelId, customMap, overrideMap),
+ [customMap, overrideMap]
+ );
+
+ return {
+ customMap,
+ overrideMap,
+ isModelHidden,
+ effectiveModelNormalize,
+ effectiveModelPreserveDeveloper,
+ getUpstreamHeadersRecord,
+ anyNormalizeCompatBadge: anyNormalizeCompatBadgeFn,
+ anyNoPreserveCompatBadge: anyNoPreserveCompatBadgeFn,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderConnections.ts b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderConnections.ts
new file mode 100644
index 0000000000..7799ccf68e
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderConnections.ts
@@ -0,0 +1,953 @@
+"use client";
+
+/**
+ * useProviderConnections — Phase 1f extraction for Issue #3501.
+ *
+ * Owns ALL connection-management state and handlers that were previously
+ * inline in ProviderDetailPageClient:
+ * - connections / providerNode / loading state
+ * - fetchConnections (with compatible-node retry logic)
+ * - batch activate / deactivate / retest / delete (with MAX_BULK_IDS chunking)
+ * - single-connection handlers: delete, update status, proxy toggles,
+ * rate-limit, claude extra-usage, codex limit, cpa mode,
+ * retest, token refresh, swap priority
+ * - selection state: selectedIds, handleToggleSelectOne/All, batchDeleteConfirmOpen
+ * - batch-test runner (runBatchTest / handleBatchTestAll / handleBatchRetest)
+ * - health/pagination filters (healthFilter, page)
+ * - proxy/distribution helpers (loadConnProxies, handleDistributeProxies,
+ * toggleProxyEnabled, togglePerKeyProxyEnabled)
+ *
+ * The hook is cycle-safe: it imports only from leaf modules (@/store, @/shared,
+ * providers constants) — never from ProviderDetailPageClient.
+ */
+
+import { useState, useEffect, useCallback } from "react";
+import { useTranslations } from "next-intl";
+import { useNotificationStore } from "@/store/notificationStore";
+import { isClaudeCodeCompatibleProvider } from "@/shared/constants/providers";
+import type { ConnectionRowConnection } from "../components/ConnectionRow";
+import { normalizeCodexLimitPolicy } from "../providerPageHelpers";
+
+// Max connection ids accepted per bulk request — mirrors API-side cap.
+const MAX_BULK_IDS = 100;
+const PAGE_SIZE = 50;
+
+// ──── types ─────────────────────────────────────────────────────────────────
+
+export type BatchTestResults = {
+ error: string | null;
+ results: any[];
+ summary: { passed: number; failed: number; total: number } | null;
+} | null;
+
+export interface UseProviderConnectionsReturn {
+ // State
+ connections: ConnectionRowConnection[];
+ providerNode: any;
+ loading: boolean;
+ retestingId: string | null;
+ batchTesting: boolean;
+ batchTestResults: BatchTestResults;
+ selectedIds: Set<string>;
+ batchDeleting: boolean;
+ batchUpdating: "activate" | "deactivate" | null;
+ batchRetesting: boolean;
+ batchDeleteConfirmOpen: boolean;
+ healthFilter: string;
+ page: number;
+ distributingProxies: boolean;
+ proxyConfig: any;
+ connProxyMap: Record<string, { proxy: any; level: string } | null>;
+ cpaProviderEnabled: boolean;
+ refreshingId: string | null;
+
+ // Setters (minimal surface for UI)
+ setPage: (p: number) => void;
+ setHealthFilter: (f: string) => void;
+ setSelectedIds: (updater: Set<string> | ((prev: Set<string>) => Set<string>)) => void;
+ setBatchDeleteConfirmOpen: (open: boolean) => void;
+ setBatchTestResults: (r: BatchTestResults) => void;
+ setConnections: (
+ updater:
+ | ConnectionRowConnection[]
+ | ((prev: ConnectionRowConnection[]) => ConnectionRowConnection[])
+ ) => void;
+ setProviderNode: (node: any) => void;
+
+ // Connection fetch
+ fetchConnections: () => Promise<void>;
+ fetchProxyConfig: () => Promise<void>;
+
+ // Single-connection handlers
+ handleDelete: (connectionId: string) => Promise<void>;
+ handleUpdateConnectionStatus: (id: string, isActive: boolean) => Promise<void>;
+ handleToggleRateLimit: (connectionId: string, enabled: boolean) => Promise<void>;
+ handleToggleClaudeExtraUsage: (connectionId: string, enabled: boolean) => Promise<void>;
+ handleToggleCodexLimit: (
+ connectionId: string,
+ field: string,
+ enabled: boolean
+ ) => Promise<void>;
+ handleToggleCliproxyapiMode: (connectionId: string, enabled: boolean) => Promise<void>;
+ handleToggleProxyEnabled: (connectionId: string, proxyEnabled: boolean) => Promise<void>;
+ handleTogglePerKeyProxyEnabled: (
+ connectionId: string,
+ perKeyProxyEnabled: boolean
+ ) => Promise<void>;
+ handleRetestConnection: (connectionId: string) => Promise<void>;
+ handleRefreshToken: (connectionId: string) => Promise<void>;
+ handleSwapPriority: (conn1: any, conn2: any) => Promise<void>;
+
+ // Batch handlers
+ handleBatchSetActive: (isActive: boolean) => Promise<void>;
+ handleBatchDeleteOpenModal: () => void;
+ handleBatchDeleteConfirm: (
+ onAfter?: () => Promise<void>
+ ) => Promise<void>;
+ handleBatchRetest: () => Promise<void>;
+ handleBatchTestAll: () => Promise<void>;
+
+ // Selection helpers
+ handleToggleSelectOne: (id: string) => void;
+ handleToggleSelectAll: () => void;
+
+ // Proxy distribution
+ handleDistributeProxies: (tagFilter?: string) => Promise<void>;
+
+ // Helpers for parsing API responses
+ parseApiErrorMessage: (res: Response, fallback: string) => Promise<string>;
+ getAttachmentFilename: (res: Response, fallback: string) => string;
+
+ // Constants exposed for render
+ PAGE_SIZE: number;
+}
+
+export function useProviderConnections(
+ providerId: string,
+ isCompatible: boolean,
+ isSearchProvider: boolean
+): UseProviderConnectionsReturn {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ const isCcCompatible = isClaudeCodeCompatibleProvider(providerId);
+
+ // ── core state ──────────────────────────────────────────────────────────
+ const [connections, setConnections] = useState<ConnectionRowConnection[]>([]);
+ const [providerNode, setProviderNode] = useState<any>(null);
+ const [loading, setLoading] = useState(true);
+
+ // ── test state ──────────────────────────────────────────────────────────
+ const [retestingId, setRetestingId] = useState<string | null>(null);
+ const [batchTesting, setBatchTesting] = useState(false);
+ const [batchTestResults, setBatchTestResults] = useState<BatchTestResults>(null);
+
+ // ── selection + batch state ─────────────────────────────────────────────
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
+ const [batchDeleting, setBatchDeleting] = useState(false);
+ const [batchUpdating, setBatchUpdating] = useState<"activate" | "deactivate" | null>(null);
+ const [batchRetesting, setBatchRetesting] = useState(false);
+ const [batchDeleteConfirmOpen, setBatchDeleteConfirmOpen] = useState(false);
+
+ // ── filter / pagination state ───────────────────────────────────────────
+ const [healthFilter, setHealthFilter] = useState<string>("all");
+ const [page, setPage] = useState(0);
+
+ // ── proxy state ─────────────────────────────────────────────────────────
+ const [distributingProxies, setDistributingProxies] = useState(false);
+ const [proxyConfig, setProxyConfig] = useState<any>(null);
+ const [connProxyMap, setConnProxyMap] = useState<
+ Record<string, { proxy: any; level: string } | null>
+ >({});
+
+ // ── CLIProxyAPI state ───────────────────────────────────────────────────
+ const [cpaProviderEnabled, setCpaProviderEnabled] = useState(false);
+
+ // ── token refresh state ─────────────────────────────────────────────────
+ const [refreshingId, setRefreshingId] = useState<string | null>(null);
+
+ // ────────────────────────────────────────────────────────────────────────
+ // Fetch helpers
+ // ────────────────────────────────────────────────────────────────────────
+
+ const fetchProxyConfig = useCallback(async () => {
+ try {
+ const res = await fetch("/api/settings/proxy", { cache: "no-store" });
+ if (res.ok) {
+ setProxyConfig(await res.json());
+ } else {
+ setProxyConfig(null);
+ }
+ } catch {
+ // Proxy indicators are best-effort.
+ }
+ }, []);
+
+ const fetchConnections = useCallback(async () => {
+ try {
+ const [connectionsRes, nodesRes] = await Promise.all([
+ fetch("/api/providers", { cache: "no-store" }),
+ fetch("/api/provider-nodes", { cache: "no-store" }),
+ ]);
+ const connectionsData = await connectionsRes.json();
+ const nodesData = await nodesRes.json();
+ if (connectionsRes.ok) {
+ const filtered = (connectionsData.connections || []).filter(
+ (c: any) => c.provider === providerId
+ );
+ setConnections(filtered);
+ }
+ if (nodesRes.ok) {
+ let node =
+ (nodesData.nodes || []).find((entry: any) => entry.id === providerId) || null;
+
+ // Newly created compatible nodes can be briefly unavailable on one worker.
+ if (!node && isCompatible) {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ const retryRes = await fetch("/api/provider-nodes", { cache: "no-store" });
+ if (!retryRes.ok) continue;
+ const retryData = await retryRes.json();
+ node =
+ (retryData.nodes || []).find((entry: any) => entry.id === providerId) || null;
+ if (node) break;
+ }
+ }
+
+ setProviderNode(node);
+ }
+ } catch (error) {
+ console.log("Error fetching connections:", error);
+ } finally {
+ setLoading(false);
+ }
+ }, [providerId, isCompatible]);
+
+ const loadConnProxies = useCallback(async (conns: { id?: string }[]) => {
+ if (!conns.length) return;
+ try {
+ const results = await Promise.all(
+ conns
+ .filter((c) => c.id)
+ .map((c) =>
+ fetch(
+ `/api/settings/proxy?resolve=${encodeURIComponent(c.id!)}`,
+ { cache: "no-store" }
+ )
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => [c.id!, data] as [string, any])
+ .catch(() => [c.id!, null] as [string, any])
+ )
+ );
+ const map: Record<string, { proxy: any; level: string } | null> = {};
+ for (const [id, data] of results) {
+ map[id] = data?.proxy ? data : null;
+ }
+ setConnProxyMap(map);
+ } catch {
+ // ignore
+ }
+ }, []);
+
+ // ── effects ──────────────────────────────────────────────────────────────
+
+ useEffect(() => {
+ fetchConnections();
+ void fetchProxyConfig();
+ }, [fetchConnections, fetchProxyConfig]);
+
+ // Per-connection proxy (handles registry assignments)
+ useEffect(() => {
+ if (!loading && connections.length > 0) {
+ void loadConnProxies(connections);
+ }
+ }, [loading, connections, loadConnProxies]);
+
+ // CLIProxyAPI upstream proxy config
+ useEffect(() => {
+ if (!isCcCompatible) return;
+
+ fetch(`/api/settings`)
+ .then((r) => r.json())
+ .then(() => {
+ // Check if this provider has CLIProxyAPI routing enabled
+ })
+ .catch(() => {});
+
+ fetch(`/api/upstream-proxy/${providerId}`)
+ .then((r) => {
+ if (!r.ok) return null;
+ return r.json();
+ })
+ .then((data) => {
+ if (data?.enabled && (data.mode === "cliproxyapi" || data.mode === "fallback")) {
+ setCpaProviderEnabled(true);
+ }
+ })
+ .catch(() => {});
+ }, [isCcCompatible, providerId]);
+
+ // ────────────────────────────────────────────────────────────────────────
+ // API error helpers
+ // ────────────────────────────────────────────────────────────────────────
+
+ const parseApiErrorMessage = async (res: Response, fallback: string): Promise<string> => {
+ const contentType = res.headers.get("content-type") || "";
+ if (contentType.includes("application/json")) {
+ const data = await res.json().catch(() => ({}));
+ if (typeof data?.error === "string" && data.error.trim()) return data.error;
+ if (data?.error?.message) return data.error.message;
+ }
+ const text = await res.text().catch(() => "");
+ return text.trim() || fallback;
+ };
+
+ const getAttachmentFilename = (res: Response, fallback: string): string => {
+ const disposition = res.headers.get("content-disposition") || "";
+ const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
+ if (utf8Match?.[1]) return decodeURIComponent(utf8Match[1]);
+ const plainMatch = disposition.match(/filename="([^"]+)"/i);
+ if (plainMatch?.[1]) return plainMatch[1];
+ return fallback;
+ };
+
+ // ────────────────────────────────────────────────────────────────────────
+ // Single-connection handlers
+ // ────────────────────────────────────────────────────────────────────────
+
+ const handleDelete = useCallback(
+ async (connectionId: string) => {
+ if (!connectionId) return;
+ try {
+ const res = await fetch(`/api/providers/${connectionId}`, { method: "DELETE" });
+ if (res.ok) {
+ notify.success("Connection deleted");
+ await fetchConnections();
+ } else {
+ const data = await res.json().catch(() => ({}));
+ const message =
+ (typeof data?.error === "string" && data.error) ||
+ data?.error?.message ||
+ "Failed to delete connection";
+ notify.error(message);
+ }
+ } catch (error) {
+ console.error("Error deleting connection:", error);
+ notify.error("Failed to delete connection");
+ }
+ },
+ [fetchConnections, notify]
+ );
+
+ const handleUpdateConnectionStatus = async (id: string, isActive: boolean) => {
+ try {
+ const res = await fetch(`/api/providers/${id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ isActive }),
+ });
+ if (res.ok) {
+ setConnections((prev: any[]) =>
+ prev.map((c) => (c.id === id ? { ...c, isActive } : c))
+ );
+ }
+ } catch (error) {
+ console.log("Error updating connection status:", error);
+ }
+ };
+
+ const handleToggleRateLimit = async (connectionId: string, enabled: boolean) => {
+ try {
+ const res = await fetch("/api/rate-limits", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ connectionId, enabled }),
+ });
+ if (res.ok) {
+ setConnections((prev: any[]) =>
+ prev.map((c) =>
+ c.id === connectionId ? { ...c, rateLimitProtection: enabled } : c
+ )
+ );
+ }
+ } catch (error) {
+ console.error("Error toggling rate limit:", error);
+ }
+ };
+
+ const handleToggleClaudeExtraUsage = async (connectionId: string, enabled: boolean) => {
+ try {
+ const target = (connections as any[]).find((connection) => connection.id === connectionId);
+ if (!target) return;
+
+ const providerSpecificData =
+ target.providerSpecificData && typeof target.providerSpecificData === "object"
+ ? target.providerSpecificData
+ : {};
+
+ const res = await fetch(`/api/providers/${connectionId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerSpecificData: { ...providerSpecificData, blockExtraUsage: enabled },
+ }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ notify.error(data.error || "Failed to update Claude extra-usage policy");
+ return;
+ }
+
+ setConnections((prev: any[]) =>
+ prev.map((connection) =>
+ connection.id === connectionId
+ ? {
+ ...connection,
+ providerSpecificData: {
+ ...(connection.providerSpecificData || {}),
+ blockExtraUsage: enabled,
+ },
+ ...(!enabled && connection.lastErrorSource === "extra_usage"
+ ? {
+ testStatus: "active",
+ lastError: null,
+ lastErrorAt: null,
+ lastErrorType: null,
+ lastErrorSource: null,
+ errorCode: null,
+ rateLimitedUntil: null,
+ }
+ : {}),
+ }
+ : connection
+ )
+ );
+ notify.success(
+ enabled
+ ? "Claude extra-usage blocking enabled (extra usage will be blocked)"
+ : "Claude extra-usage blocking disabled (extra usage is allowed)"
+ );
+ } catch (error) {
+ console.error("Error toggling Claude extra-usage policy:", error);
+ notify.error("Failed to update Claude extra-usage policy");
+ }
+ };
+
+ const handleToggleCodexLimit = async (
+ connectionId: string,
+ field: string,
+ enabled: boolean
+ ) => {
+ try {
+ const target = (connections as any[]).find((connection) => connection.id === connectionId);
+ if (!target) return;
+
+ const providerSpecificData =
+ target.providerSpecificData && typeof target.providerSpecificData === "object"
+ ? target.providerSpecificData
+ : {};
+ const existingPolicy =
+ providerSpecificData.codexLimitPolicy &&
+ typeof providerSpecificData.codexLimitPolicy === "object"
+ ? providerSpecificData.codexLimitPolicy
+ : {};
+
+ const nextPolicy = {
+ ...normalizeCodexLimitPolicy(existingPolicy),
+ [field]: enabled,
+ };
+
+ const res = await fetch(`/api/providers/${connectionId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerSpecificData: { ...providerSpecificData, codexLimitPolicy: nextPolicy },
+ }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ notify.error(data.error || "Failed to update Codex limit policy");
+ return;
+ }
+
+ setConnections((prev: any[]) =>
+ prev.map((connection) =>
+ connection.id === connectionId
+ ? {
+ ...connection,
+ providerSpecificData: {
+ ...(connection.providerSpecificData || {}),
+ codexLimitPolicy: nextPolicy,
+ },
+ }
+ : connection
+ )
+ );
+ notify.success("Codex limit policy updated");
+ } catch (error) {
+ console.error("Error toggling Codex quota policy:", error);
+ notify.error("Failed to update Codex limit policy");
+ }
+ };
+
+ const handleToggleCliproxyapiMode = async (_connectionId: string, enabled: boolean) => {
+ try {
+ const res = await fetch(`/api/upstream-proxy/${providerId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mode: enabled ? "cliproxyapi" : "native", enabled }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ notify.error(data.error || "Failed to update CLIProxyAPI routing");
+ return;
+ }
+
+ setCpaProviderEnabled(enabled);
+ notify.success(
+ enabled
+ ? "Requests now route through CLIProxyAPI (deeper emulation)"
+ : "Requests now use native OmniRoute (direct)"
+ );
+ } catch {
+ notify.error("Failed to update CLIProxyAPI routing");
+ }
+ };
+
+ const handleToggleProxyEnabled = async (connectionId: string, proxyEnabled: boolean) => {
+ try {
+ const res = await fetch(`/api/providers/${connectionId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ proxyEnabled }),
+ });
+ if (res.ok) {
+ setConnections((prev: any[]) =>
+ prev.map((c) => (c.id === connectionId ? { ...c, proxyEnabled } : c))
+ );
+ }
+ } catch (error) {
+ console.error("Error toggling proxy enabled:", error);
+ }
+ };
+
+ const handleTogglePerKeyProxyEnabled = async (
+ connectionId: string,
+ perKeyProxyEnabled: boolean
+ ) => {
+ try {
+ const res = await fetch(`/api/providers/${connectionId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ perKeyProxyEnabled }),
+ });
+ if (res.ok) {
+ setConnections((prev: any[]) =>
+ prev.map((c) => (c.id === connectionId ? { ...c, perKeyProxyEnabled } : c))
+ );
+ }
+ } catch (error) {
+ console.error("Error toggling per-key proxy enabled:", error);
+ }
+ };
+
+ const handleRetestConnection = async (connectionId: string) => {
+ if (!connectionId || retestingId) return;
+ setRetestingId(connectionId);
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/test`, { method: "POST" });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ alert(data.error || t("failedRetestConnection"));
+ return;
+ }
+ await fetchConnections();
+ } catch (error) {
+ console.error("Error retesting connection:", error);
+ } finally {
+ setRetestingId(null);
+ }
+ };
+
+ const handleRefreshToken = async (connectionId: string) => {
+ if (refreshingId) return;
+ setRefreshingId(connectionId);
+ try {
+ const res = await fetch(`/api/providers/${connectionId}/refresh`, { method: "POST" });
+ const data = await res.json().catch(() => ({}));
+ if (res.ok && data.success) {
+ notify.success(t("tokenRefreshed"));
+ await fetchConnections();
+ } else {
+ notify.error(data.error || t("tokenRefreshFailed"));
+ }
+ } catch (error) {
+ console.error("Error refreshing token:", error);
+ notify.error(t("tokenRefreshFailed"));
+ } finally {
+ setRefreshingId(null);
+ }
+ };
+
+ const handleSwapPriority = async (conn1: any, conn2: any) => {
+ if (!conn1 || !conn2) return;
+ try {
+ let p1 = conn2.priority;
+ let p2 = conn1.priority;
+
+ if (p1 === p2) {
+ const isConn1MovingUp =
+ (connections as any[]).indexOf(conn1) > (connections as any[]).indexOf(conn2);
+ if (isConn1MovingUp) {
+ p1 = conn2.priority - 0.5;
+ } else {
+ p1 = conn2.priority + 0.5;
+ }
+ }
+
+ await Promise.all([
+ fetch(`/api/providers/${conn1.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ priority: p1 }),
+ }),
+ fetch(`/api/providers/${conn2.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ priority: p2 }),
+ }),
+ ]);
+ await fetchConnections();
+ } catch (error) {
+ console.log("Error swapping priority:", error);
+ }
+ };
+
+ // ────────────────────────────────────────────────────────────────────────
+ // Selection handlers
+ // ────────────────────────────────────────────────────────────────────────
+
+ const handleToggleSelectOne = useCallback((id: string) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ }, []);
+
+ const handleToggleSelectAll = useCallback(() => {
+ setSelectedIds((prev) => {
+ if (
+ prev.size === (connections as any[]).length &&
+ (connections as any[]).length > 0
+ ) {
+ return new Set();
+ }
+ return new Set((connections as any[]).map((c: { id: string }) => c.id));
+ });
+ }, [connections]);
+
+ // ────────────────────────────────────────────────────────────────────────
+ // Batch handlers
+ // ────────────────────────────────────────────────────────────────────────
+
+ const handleBatchDeleteOpenModal = () => {
+ if (selectedIds.size === 0) return;
+ setBatchDeleteConfirmOpen(true);
+ };
+
+ const handleBatchDeleteConfirm = async (onAfter?: () => Promise<void>) => {
+ setBatchDeleteConfirmOpen(false);
+ setBatchDeleting(true);
+ try {
+ const res = await fetch("/api/providers", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: Array.from(selectedIds) }),
+ });
+
+ if (res.ok) {
+ const count = selectedIds.size;
+ setSelectedIds(new Set());
+ await fetchConnections();
+ notify.success(t("batchDeleteSuccess", { count }));
+ if (onAfter) await onAfter();
+ } else {
+ const data = await res.json();
+ notify.error(data.error || "Batch delete failed");
+ }
+ } catch {
+ notify.error("Network error during batch delete");
+ } finally {
+ setBatchDeleting(false);
+ }
+ };
+
+ const handleBatchSetActive = async (isActive: boolean) => {
+ if (selectedIds.size === 0 || batchUpdating) return;
+ setBatchUpdating(isActive ? "activate" : "deactivate");
+ try {
+ const ids = Array.from(selectedIds);
+ let updated = 0;
+ let notFound = 0;
+ for (let i = 0; i < ids.length; i += MAX_BULK_IDS) {
+ const chunk = ids.slice(i, i + MAX_BULK_IDS);
+ const res = await fetch("/api/providers", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: chunk, isActive }),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error?.message || data.error || "Batch update failed");
+ }
+ const data = await res.json();
+ updated += data.updated ?? 0;
+ notFound += Array.isArray(data.notFound) ? data.notFound.length : 0;
+ }
+
+ await fetchConnections();
+
+ if (updated === 0) {
+ notify.warning(t("batchUpdateNone"));
+ } else if (notFound > 0) {
+ notify.warning(t("batchUpdatePartial", { count: updated, skipped: notFound }));
+ } else {
+ notify.success(
+ isActive
+ ? t("batchActivateSuccess", { count: updated })
+ : t("batchDeactivateSuccess", { count: updated })
+ );
+ }
+ } catch (error: any) {
+ notify.error(error?.message || "Network error during batch update");
+ } finally {
+ setBatchUpdating(null);
+ }
+ };
+
+ // Shared runner for batch connection tests (all-for-provider or selected IDs)
+ const runBatchTest = async (payload: Record<string, unknown>) => {
+ setBatchTestResults(null);
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 120_000); // 2min max
+ try {
+ const res = await fetch("/api/providers/test-batch", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ signal: controller.signal,
+ });
+ let data: any;
+ try {
+ data = await res.json();
+ } catch {
+ data = { error: t("providerTestFailed"), results: [], summary: null };
+ }
+ setBatchTestResults({
+ ...data,
+ error: data.error
+ ? typeof data.error === "object"
+ ? data.error.message || data.error.error || JSON.stringify(data.error)
+ : String(data.error)
+ : null,
+ });
+ if (data?.summary) {
+ const { passed, failed, total } = data.summary;
+ if (total === 0) notify.warning(t("noConnectionsToTest"));
+ else if (failed === 0) notify.success(t("allTestsPassed", { total }));
+ else notify.warning(t("testSummary", { passed, failed, total }));
+ }
+ await fetchConnections();
+ } catch (error: any) {
+ const isAbort = error?.name === "AbortError";
+ const msg = isAbort ? t("providerTestTimeout") : t("providerTestFailed");
+ setBatchTestResults({ error: msg, results: [], summary: null });
+ notify.error(msg);
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ };
+
+ // Batch test all connections for this provider
+ const handleBatchTestAll = async () => {
+ if (batchTesting || (connections as any[]).length === 0) return;
+ setBatchTesting(true);
+ try {
+ await runBatchTest({ mode: "provider", providerId });
+ } finally {
+ setBatchTesting(false);
+ }
+ };
+
+ // Batch retest only the selected connections
+ const handleBatchRetest = async () => {
+ if (batchRetesting || selectedIds.size === 0) return;
+ // Live-testing a huge selection risks the 120s client abort; bound it to
+ // the same cap the API enforces and tell the user to narrow the selection.
+ if (selectedIds.size > MAX_BULK_IDS) {
+ notify.warning(t("batchRetestLimit", { max: MAX_BULK_IDS }));
+ return;
+ }
+ setBatchRetesting(true);
+ try {
+ await runBatchTest({ mode: "selected", connectionIds: Array.from(selectedIds) });
+ } finally {
+ setBatchRetesting(false);
+ }
+ };
+
+ // ────────────────────────────────────────────────────────────────────────
+ // Proxy distribution
+ // ────────────────────────────────────────────────────────────────────────
+
+ const handleDistributeProxies = async (tagFilter?: string) => {
+ const targetConnections = tagFilter
+ ? (connections as any[]).filter(
+ (c: any) => (c.providerSpecificData?.tag as string | undefined)?.trim() === tagFilter
+ )
+ : connections;
+ if ((targetConnections as any[]).length === 0) return;
+ setDistributingProxies(true);
+ try {
+ const proxiesRes = await fetch("/api/settings/proxies");
+ if (!proxiesRes.ok) throw new Error("Failed to fetch proxies");
+ const proxiesData = await proxiesRes.json();
+ const savedProxies = (proxiesData?.items || []).filter((p: any) => p.status === "active");
+ if (savedProxies.length === 0) {
+ notify.error("No saved proxies found. Add proxies in Settings → Proxy first.");
+ return;
+ }
+
+ let assigned = 0;
+ const sorted = [...(targetConnections as any[])].sort(
+ (a: any, b: any) => (a.priority || 0) - (b.priority || 0)
+ );
+
+ for (let i = 0; i < sorted.length; i++) {
+ const conn = sorted[i] as any;
+ const proxy = savedProxies[i % savedProxies.length];
+
+ try {
+ await fetch("/api/settings/proxies/assignments", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ scope: "account", scopeId: conn.id, proxyId: null }),
+ });
+ } catch {
+ /* clear old assignment */
+ }
+
+ const patchRes = await fetch(`/api/providers/${conn.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ proxyEnabled: true, perKeyProxyEnabled: true }),
+ });
+
+ if (!patchRes.ok) {
+ console.error(`Failed to update connection ${conn.id}`);
+ continue;
+ }
+
+ const assignRes = await fetch("/api/settings/proxies/assignments", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ scope: "account", scopeId: conn.id, proxyId: proxy.id }),
+ });
+
+ if (!assignRes.ok) {
+ console.error(`Failed to assign proxy to ${conn.id}`);
+ continue;
+ }
+
+ assigned++;
+ }
+
+ await fetchConnections();
+ const tagLabel = tagFilter ? `"${tagFilter}" ` : "";
+ notify.success(
+ `Distributed ${assigned} proxy assignment(s) across ${tagLabel}${sorted.length} connection(s).`
+ );
+ } catch (err) {
+ console.error("Error distributing proxies:", err);
+ notify.error("Failed to distribute proxies.");
+ } finally {
+ setDistributingProxies(false);
+ }
+ };
+
+ // ────────────────────────────────────────────────────────────────────────
+
+ return {
+ // State
+ connections,
+ providerNode,
+ loading,
+ retestingId,
+ batchTesting,
+ batchTestResults,
+ selectedIds,
+ batchDeleting,
+ batchUpdating,
+ batchRetesting,
+ batchDeleteConfirmOpen,
+ healthFilter,
+ page,
+ distributingProxies,
+ proxyConfig,
+ connProxyMap,
+ cpaProviderEnabled,
+ refreshingId,
+
+ // Setters
+ setPage,
+ setHealthFilter,
+ setSelectedIds,
+ setBatchDeleteConfirmOpen,
+ setBatchTestResults,
+ setConnections,
+ setProviderNode,
+
+ // Fetch
+ fetchConnections,
+ fetchProxyConfig,
+
+ // Single-connection handlers
+ handleDelete,
+ handleUpdateConnectionStatus,
+ handleToggleRateLimit,
+ handleToggleClaudeExtraUsage,
+ handleToggleCodexLimit,
+ handleToggleCliproxyapiMode,
+ handleToggleProxyEnabled,
+ handleTogglePerKeyProxyEnabled,
+ handleRetestConnection,
+ handleRefreshToken,
+ handleSwapPriority,
+
+ // Batch handlers
+ handleBatchSetActive,
+ handleBatchDeleteOpenModal,
+ handleBatchDeleteConfirm,
+ handleBatchRetest,
+ handleBatchTestAll,
+
+ // Selection
+ handleToggleSelectOne,
+ handleToggleSelectAll,
+
+ // Proxy distribution
+ handleDistributeProxies,
+
+ // Helpers
+ parseApiErrorMessage,
+ getAttachmentFilename,
+
+ // Constants
+ PAGE_SIZE,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderModels.ts b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderModels.ts
new file mode 100644
index 0000000000..0128a2ee9f
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderModels.ts
@@ -0,0 +1,154 @@
+"use client";
+
+/**
+ * useProviderModels — Phase 1f extraction for Issue #3501.
+ *
+ * Owns model-metadata state and handlers that were previously inline in
+ * ProviderDetailPageClient:
+ * - modelMeta (customModels + modelCompatOverrides)
+ * - syncedAvailableModels
+ * - modelAliases
+ * - fetchProviderModelMeta, fetchAliases, handleSetAlias, handleDeleteAlias
+ *
+ * Cycle-safe: imports only from leaf modules.
+ */
+
+import { useState, useCallback } from "react";
+import { useTranslations } from "next-intl";
+import { useNotificationStore } from "@/store/notificationStore";
+import type { CompatModelRow } from "../providerPageHelpers";
+
+// ──── types ─────────────────────────────────────────────────────────────────
+
+export interface ModelMeta {
+ customModels: CompatModelRow[];
+ modelCompatOverrides: Array<CompatModelRow & { id: string }>;
+}
+
+export interface UseProviderModelsReturn {
+ modelMeta: ModelMeta;
+ syncedAvailableModels: any[];
+ modelAliases: Record<string, string>;
+ fetchProviderModelMeta: () => Promise<void>;
+ fetchAliases: () => Promise<void>;
+ handleSetAlias: (modelId: string, alias: string, providerAlias?: string) => Promise<void>;
+ handleDeleteAlias: (alias: string) => Promise<void>;
+}
+
+export function useProviderModels(
+ providerId: string,
+ isSearchProvider: boolean
+): UseProviderModelsReturn {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ const [modelMeta, setModelMeta] = useState<ModelMeta>({
+ customModels: [],
+ modelCompatOverrides: [],
+ });
+ const [syncedAvailableModels, setSyncedAvailableModels] = useState<any[]>([]);
+ const [modelAliases, setModelAliases] = useState<Record<string, string>>({});
+
+ const fetchAliases = useCallback(async () => {
+ try {
+ const res = await fetch("/api/models/alias");
+ const data = await res.json();
+ if (res.ok) {
+ setModelAliases(data.aliases || {});
+ }
+ } catch (error) {
+ console.log("Error fetching aliases:", error);
+ }
+ }, []);
+
+ const handleSetAlias = useCallback(
+ async (modelId: string, alias: string, providerAlias?: string) => {
+ const qualifiedModel = providerAlias
+ ? modelId.includes("/")
+ ? `${providerAlias}/${modelId.split("/").slice(1).join("/")}`
+ : `${providerAlias}/${modelId}`
+ : modelId;
+ try {
+ const res = await fetch("/api/models/alias", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model: qualifiedModel, alias }),
+ });
+ if (res.ok) {
+ await fetchAliases();
+ notify.success(t("setAliasSuccess", { alias }));
+ } else {
+ const data = await res.json().catch(() => ({}));
+ notify.error(data?.error?.message || "Failed to set alias");
+ }
+ } catch (error) {
+ console.log("Error setting alias:", error);
+ notify.error("Network error setting alias");
+ }
+ },
+ [fetchAliases, t, notify]
+ );
+
+ const handleDeleteAlias = useCallback(
+ async (alias: string) => {
+ try {
+ const res = await fetch(`/api/models/alias?alias=${encodeURIComponent(alias)}`, {
+ method: "DELETE",
+ });
+ if (res.ok) {
+ await fetchAliases();
+ notify.success(t("deleteAliasSuccess", { alias }));
+ } else {
+ const data = await res.json().catch(() => ({}));
+ notify.error(data?.error?.message || "Failed to delete alias");
+ }
+ } catch (error) {
+ console.log("Error deleting alias:", error);
+ notify.error("Network error deleting alias");
+ }
+ },
+ [fetchAliases, t, notify]
+ );
+
+ const fetchProviderModelMeta = useCallback(async () => {
+ if (isSearchProvider) return;
+ try {
+ const res = await fetch(
+ `/api/provider-models?provider=${encodeURIComponent(providerId)}`,
+ { cache: "no-store" }
+ );
+ if (!res.ok) return;
+ const data = await res.json();
+ setModelMeta({
+ customModels: data.models || [],
+ modelCompatOverrides: data.modelCompatOverrides || [],
+ });
+ try {
+ const syncRes = await fetch(
+ `/api/synced-available-models?provider=${encodeURIComponent(providerId)}`,
+ { cache: "no-store" }
+ );
+ if (syncRes.ok) {
+ const syncData = await syncRes.json();
+ setSyncedAvailableModels(syncData.models || []);
+ } else {
+ setSyncedAvailableModels([]);
+ }
+ } catch {
+ setSyncedAvailableModels([]);
+ }
+ } catch (e) {
+ console.error("fetchProviderModelMeta", e);
+ }
+ }, [providerId, isSearchProvider]);
+
+ return {
+ modelMeta,
+ syncedAvailableModels,
+ modelAliases,
+ fetchProviderModelMeta,
+ fetchAliases,
+ handleSetAlias,
+ handleDeleteAlias,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderSettings.ts b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderSettings.ts
new file mode 100644
index 0000000000..6a9248b64d
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/hooks/useProviderSettings.ts
@@ -0,0 +1,263 @@
+"use client";
+
+/**
+ * useProviderSettings — Phase 1f extraction for Issue #3501.
+ *
+ * Owns provider-specific global settings state that were previously inline in
+ * ProviderDetailPageClient:
+ * - Codex: global service mode, supported models, load/save/error state
+ * - Claude: preferClaudeCodeForUnprefixedClaudeModels toggle, load/save/error state
+ *
+ * Cycle-safe: imports only from leaf modules (no client imports).
+ */
+
+import { useState, useEffect, useCallback, useRef, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { useNotificationStore } from "@/store/notificationStore";
+import {
+ CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS,
+ getCodexGlobalServiceMode,
+ resolveCodexGlobalFastServiceTier,
+ type CodexGlobalServiceMode,
+} from "@/lib/providers/codexFastTier";
+import {
+ CODEX_GLOBAL_SERVICE_MODE_VALUES,
+ getCodexServiceTierLabel,
+ providerText,
+} from "../providerPageHelpers";
+
+// ──── types ─────────────────────────────────────────────────────────────────
+
+export interface UseProviderSettingsReturn {
+ // Codex
+ codexGlobalServiceMode: CodexGlobalServiceMode;
+ codexGlobalSupportedModels: string[];
+ codexSettingsLoaded: boolean;
+ codexSettingsLoadError: string | null;
+ savingCodexGlobalServiceMode: boolean;
+ codexGlobalServiceModeOptions: Array<{ value: string; label: string }>;
+ loadCodexSettings: () => Promise<void>;
+ handleChangeCodexGlobalServiceMode: (mode: CodexGlobalServiceMode) => Promise<void>;
+
+ // Claude routing
+ preferClaudeCodeForUnprefixedClaudeModels: boolean;
+ claudeRoutingSettingsLoaded: boolean;
+ claudeRoutingSettingsLoadError: string | null;
+ savingClaudeRoutingPreference: boolean;
+ loadClaudeRoutingSettings: () => Promise<void>;
+ handleToggleClaudeRoutingPreference: (enabled: boolean) => Promise<void>;
+}
+
+export function useProviderSettings(providerId: string): UseProviderSettingsReturn {
+ const t = useTranslations("providers");
+ const notify = useNotificationStore();
+
+ // ── Codex state ──────────────────────────────────────────────────────────
+ const codexSettingsRequestSeqRef = useRef(0);
+
+ const [codexGlobalServiceMode, setCodexGlobalServiceMode] =
+ useState<CodexGlobalServiceMode>("none");
+ const [codexGlobalSupportedModels, setCodexGlobalSupportedModels] = useState<string[]>([
+ ...CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS,
+ ]);
+ const [codexSettingsLoaded, setCodexSettingsLoaded] = useState(false);
+ const [codexSettingsLoadError, setCodexSettingsLoadError] = useState<string | null>(null);
+ const [savingCodexGlobalServiceMode, setSavingCodexGlobalServiceMode] = useState(false);
+
+ // ── Claude routing state ─────────────────────────────────────────────────
+ const [preferClaudeCodeForUnprefixedClaudeModels, setPreferClaudeCodeForUnprefixedClaudeModels] =
+ useState(false);
+ const [claudeRoutingSettingsLoaded, setClaudeRoutingSettingsLoaded] = useState(false);
+ const [claudeRoutingSettingsLoadError, setClaudeRoutingSettingsLoadError] = useState<
+ string | null
+ >(null);
+ const [savingClaudeRoutingPreference, setSavingClaudeRoutingPreference] = useState(false);
+
+ // ── derived ──────────────────────────────────────────────────────────────
+ const codexGlobalServiceModeOptions = useMemo(
+ () =>
+ CODEX_GLOBAL_SERVICE_MODE_VALUES.map((value) => ({
+ value,
+ label: getCodexServiceTierLabel(t, value),
+ })),
+ [t]
+ );
+
+ // ── Codex settings loader ────────────────────────────────────────────────
+ const loadCodexSettings = useCallback(async () => {
+ const requestSeq = codexSettingsRequestSeqRef.current + 1;
+ codexSettingsRequestSeqRef.current = requestSeq;
+ const isCurrentRequest = () => codexSettingsRequestSeqRef.current === requestSeq;
+
+ if (providerId !== "codex") {
+ setCodexSettingsLoaded(false);
+ setCodexSettingsLoadError(null);
+ return;
+ }
+
+ setCodexSettingsLoaded(false);
+ setCodexSettingsLoadError(null);
+
+ try {
+ const response = await fetch("/api/settings", { cache: "no-store" });
+ if (!response.ok) {
+ throw new Error(`Settings request failed with HTTP ${response.status}`);
+ }
+ const data = await response.json();
+ if (!data || typeof data !== "object") {
+ throw new Error("Settings response was empty");
+ }
+ if (!isCurrentRequest()) return;
+ const resolvedCodexServiceTier = resolveCodexGlobalFastServiceTier(data);
+ setCodexGlobalServiceMode(getCodexGlobalServiceMode(data));
+ setCodexGlobalSupportedModels([...resolvedCodexServiceTier.supportedModels]);
+ setCodexSettingsLoaded(true);
+ } catch (error) {
+ if (!isCurrentRequest()) return;
+ setCodexSettingsLoaded(false);
+ setCodexSettingsLoadError(
+ error instanceof Error ? error.message : "Failed to load settings"
+ );
+ }
+ }, [providerId]);
+
+ useEffect(() => {
+ void loadCodexSettings();
+ }, [loadCodexSettings]);
+
+ // ── Claude routing settings loader ───────────────────────────────────────
+ const loadClaudeRoutingSettings = useCallback(async () => {
+ if (providerId !== "claude") {
+ setClaudeRoutingSettingsLoaded(false);
+ setClaudeRoutingSettingsLoadError(null);
+ return;
+ }
+
+ setClaudeRoutingSettingsLoaded(false);
+ setClaudeRoutingSettingsLoadError(null);
+
+ try {
+ const response = await fetch("/api/settings", { cache: "no-store" });
+ if (!response.ok) {
+ throw new Error(`Settings request failed with HTTP ${response.status}`);
+ }
+ const data = await response.json();
+ if (!data || typeof data !== "object") {
+ throw new Error("Settings response was empty");
+ }
+ setPreferClaudeCodeForUnprefixedClaudeModels(
+ data.preferClaudeCodeForUnprefixedClaudeModels === true
+ );
+ setClaudeRoutingSettingsLoaded(true);
+ } catch (error) {
+ setClaudeRoutingSettingsLoaded(false);
+ setClaudeRoutingSettingsLoadError(
+ error instanceof Error ? error.message : "Failed to load settings"
+ );
+ }
+ }, [providerId]);
+
+ useEffect(() => {
+ void loadClaudeRoutingSettings();
+ }, [loadClaudeRoutingSettings]);
+
+ // ── Codex service mode handler ───────────────────────────────────────────
+ const handleChangeCodexGlobalServiceMode = async (mode: CodexGlobalServiceMode) => {
+ if (savingCodexGlobalServiceMode || !codexSettingsLoaded) return;
+ setSavingCodexGlobalServiceMode(true);
+ const previousMode = codexGlobalServiceMode;
+ setCodexGlobalServiceMode(mode);
+ try {
+ const tier = mode === "none" ? (previousMode !== "none" ? previousMode : undefined) : mode;
+ const res = await fetch("/api/settings", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ codexServiceTier: {
+ enabled: mode !== "none",
+ ...(tier ? { tier } : {}),
+ supportedModels: codexGlobalSupportedModels,
+ },
+ }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ setCodexGlobalServiceMode(previousMode);
+ notify.error(data.error || "Failed to update Codex service mode");
+ return;
+ }
+
+ notify.success("Codex service mode updated");
+ } catch (error) {
+ setCodexGlobalServiceMode(previousMode);
+ console.error("Error updating Codex service mode:", error);
+ notify.error("Failed to update Codex service mode");
+ } finally {
+ setSavingCodexGlobalServiceMode(false);
+ }
+ };
+
+ // ── Claude routing preference handler ───────────────────────────────────
+ const handleToggleClaudeRoutingPreference = async (enabled: boolean) => {
+ if (savingClaudeRoutingPreference || !claudeRoutingSettingsLoaded) return;
+ setSavingClaudeRoutingPreference(true);
+ const previous = preferClaudeCodeForUnprefixedClaudeModels;
+ setPreferClaudeCodeForUnprefixedClaudeModels(enabled);
+
+ try {
+ const res = await fetch("/api/settings", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ preferClaudeCodeForUnprefixedClaudeModels: enabled }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ setPreferClaudeCodeForUnprefixedClaudeModels(previous);
+ notify.error(data.error || "Failed to update Claude Code routing preference");
+ return;
+ }
+
+ const data = await res.json().catch(() => null);
+ if (data && typeof data === "object") {
+ setPreferClaudeCodeForUnprefixedClaudeModels(
+ data.preferClaudeCodeForUnprefixedClaudeModels === true
+ );
+ }
+ notify.success(
+ enabled
+ ? "Unprefixed Claude models now prefer Claude Code"
+ : "Unprefixed Claude models no longer prefer Claude Code"
+ );
+ } catch (error) {
+ setPreferClaudeCodeForUnprefixedClaudeModels(previous);
+ console.error("Error updating Claude Code routing preference:", error);
+ notify.error(
+ providerText(t, "failedUpdateClaudeRoutingPreference", "Failed to update Claude Code routing preference")
+ );
+ } finally {
+ setSavingClaudeRoutingPreference(false);
+ }
+ };
+
+ return {
+ // Codex
+ codexGlobalServiceMode,
+ codexGlobalSupportedModels,
+ codexSettingsLoaded,
+ codexSettingsLoadError,
+ savingCodexGlobalServiceMode,
+ codexGlobalServiceModeOptions,
+ loadCodexSettings,
+ handleChangeCodexGlobalServiceMode,
+
+ // Claude routing
+ preferClaudeCodeForUnprefixedClaudeModels,
+ claudeRoutingSettingsLoaded,
+ claudeRoutingSettingsLoadError,
+ savingClaudeRoutingPreference,
+ loadClaudeRoutingSettings,
+ handleToggleClaudeRoutingPreference,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
index 511fe49861..781164db03 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
@@ -1,12882 +1,8 @@
-"use client";
-
-import { useState, useEffect, useLayoutEffect, useCallback, useRef, useMemo } from "react";
-import { createPortal } from "react-dom";
-import { LlmChatCard } from "@/app/(dashboard)/dashboard/media-providers/components/LlmChatCard";
-import { ServiceKindTabs } from "@/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs";
-import { EmbeddingExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/EmbeddingExampleCard";
-import { ImageExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard";
-import { TtsExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/TtsExampleCard";
-import { SttExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/SttExampleCard";
-import { WebSearchExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/WebSearchExampleCard";
-import { WebFetchExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/WebFetchExampleCard";
-import { VideoExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/VideoExampleCard";
-import { MusicExampleCard } from "@/app/(dashboard)/dashboard/media-providers/components/MusicExampleCard";
-import type { ServiceKind } from "@/shared/constants/providers";
-import { useNotificationStore } from "@/store/notificationStore";
-import { useParams, useRouter } from "next/navigation";
-import Link from "next/link";
-import { useTranslations } from "next-intl";
-import {
- Card,
- Button,
- Badge,
- Input,
- Modal,
- ConfirmModal,
- CardSkeleton,
- OAuthModal,
- KiroOAuthWrapper,
- CursorAuthModal,
- TraeAuthModal,
- Toggle,
- Select,
- ProxyConfigModal,
- NoAuthProviderCard,
-} from "@/shared/components";
-import {
- LOCAL_PROVIDERS,
- NOAUTH_PROVIDERS,
- AI_PROVIDERS,
- getProviderAlias,
- isOpenAICompatibleProvider,
- isAnthropicCompatibleProvider,
- isClaudeCodeCompatibleProvider,
- isSelfHostedChatProvider,
- providerAllowsOptionalApiKey,
- supportsApiKeyOnFreeProvider,
- supportsBulkApiKey,
-} from "@/shared/constants/providers";
-import {
- ANTIGRAVITY_CLIENT_PROFILE_OPTIONS,
- normalizeAntigravityClientProfileSetting,
-} from "@/shared/constants/antigravityClientProfile";
-import { parseBulkApiKeys } from "@/shared/utils/bulkApiKeyParser";
-import { getModelsByProviderId } from "@/shared/constants/models";
-import {
- compatibleProviderSupportsModelImport,
- getCompatibleFallbackModels,
-} from "@/lib/providers/managedAvailableModels";
-import {
- getModelCatalogSourceLabel,
- matchesModelCatalogQuery,
- normalizeModelCatalogSource,
-} from "@/shared/utils/modelCatalogSearch";
-import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
-import {
- MODEL_COMPAT_PROTOCOL_KEYS,
- type ModelCompatProtocolKey,
-} from "@/shared/constants/modelCompat";
-import { resolveManagedModelAlias } from "@/shared/utils/providerModelAliases";
-import { maskEmail, pickMaskedDisplayValue, pickDisplayValue } from "@/shared/utils/maskEmail";
-import useEmailPrivacyStore from "@/store/emailPrivacyStore";
-import EmailPrivacyToggle from "@/shared/components/EmailPrivacyToggle";
-import ProviderIcon from "@/shared/components/ProviderIcon";
-import {
- getClaudeCodeCompatibleRequestDefaults as _getClaudeCodeCompatibleRequestDefaults,
- getCodexRequestDefaults as _getCodexRequestDefaults,
- type CodexServiceTier,
-} from "@/lib/providers/requestDefaults";
-import {
- CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS,
- getCodexEffectiveServiceTier,
- getCodexGlobalServiceMode,
- resolveCodexGlobalFastServiceTier,
- type CodexGlobalServiceMode,
-} from "@/lib/providers/codexFastTier";
-import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";
-import { parseExtraApiKeys } from "@/shared/utils/parseApiKeys";
-import { compareTr } from "@/shared/utils/turkishText";
-import RiskNoticeModal from "../components/RiskNoticeModal";
-import CodexCliGuideModal from "../components/CodexCliGuideModal";
-import { isRiskAcknowledged, useRiskAcknowledged } from "../hooks/useRiskAcknowledged";
-import { resolveDashboardProviderInfo } from "../providerPageUtils";
-import {
- getWebSessionCredentialRequirement,
- type WebSessionCredentialRequirement,
-} from "./webSessionCredentials";
-
-type CompatByProtocolMap = Partial<
- Record<
- ModelCompatProtocolKey,
- {
- normalizeToolCallId?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- upstreamHeaders?: Record<string, string>;
- }
- >
->;
-
-/** PATCH fields for provider model compat (matches API + `ModelCompatPerProtocol` shape). */
-type ModelCompatSavePatch = {
- normalizeToolCallId?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- upstreamHeaders?: Record<string, string>;
- compatByProtocol?: CompatByProtocolMap;
- isHidden?: boolean;
-};
-
-type CompatModelRow = {
- id?: string;
- name?: string;
- source?: string;
- apiFormat?: string;
- supportedEndpoints?: string[];
- normalizeToolCallId?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- isHidden?: boolean;
- upstreamHeaders?: Record<string, string>;
- compatByProtocol?: CompatByProtocolMap;
-};
-
-type CompatModelMap = Map<string, CompatModelRow>;
-type LocalProviderMetadata = {
- name?: string;
- localDefault?: string;
- [key: string]: unknown;
-};
-
-function buildCompatMap(rows: CompatModelRow[]): CompatModelMap {
- const m = new Map<string, CompatModelRow>();
- for (const r of rows) if (r.id) m.set(r.id, r);
- return m;
-}
-
-function getProtoSlice(
- c: CompatModelRow | undefined,
- o: CompatModelRow | undefined,
- protocol: string
-) {
- return c?.compatByProtocol?.[protocol] ?? o?.compatByProtocol?.[protocol];
-}
-
-function isModelHidden(
- modelId: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- if (c && Object.prototype.hasOwnProperty.call(c, "isHidden")) {
- return Boolean(c.isHidden);
- }
- const o = overrideMap.get(modelId);
- if (o && Object.prototype.hasOwnProperty.call(o, "isHidden")) {
- return Boolean(o.isHidden);
- }
- return false;
-}
-
-type ProviderMessageTranslator = ((key: string, values?: Record<string, unknown>) => string) & {
- has?: (key: string) => boolean;
-};
-
-function providerText(
- t: ProviderMessageTranslator,
- key: string,
- fallback: string,
- values?: Record<string, unknown>
-): string {
- if (typeof t.has === "function" && t.has(key)) {
- return t(key, values);
- }
- if (values) {
- return Object.entries(values).reduce(
- (acc, [name, value]) => acc.replaceAll(`{${name}}`, String(value)),
- fallback
- );
- }
- return fallback;
-}
-
-function providerCountText(
- t: ProviderMessageTranslator,
- key: string,
- count: number,
- singularFallback: string,
- pluralFallback: string
-): string {
- return providerText(t, key, count === 1 ? singularFallback : pluralFallback, { count });
-}
-
-function readBooleanToggle(value: unknown, fallback: boolean): boolean {
- if (typeof value === "boolean") return value;
- if (typeof value === "number") return value === 1;
- if (typeof value === "string") {
- const normalized = value.trim().toLowerCase();
- if (normalized === "1" || normalized === "true") return true;
- if (normalized === "0" || normalized === "false") return false;
- }
- return fallback;
-}
-
-function getWebSessionCredentialLabel(
- t: ProviderMessageTranslator,
- requirement: WebSessionCredentialRequirement,
- optional: boolean
-): string {
- if (requirement.kind === "none") {
- return providerText(t, "webNoAuthCredentialLabel", "No credential required");
- }
- const baseLabel =
- requirement.kind === "token"
- ? providerText(t, "webTokenCredentialLabel", "Web session token")
- : t("sessionCookieLabel");
- return optional ? `${baseLabel} (${t("optional").toLowerCase()})` : baseLabel;
-}
-
-function getWebSessionCredentialHint(
- t: ProviderMessageTranslator,
- requirement: WebSessionCredentialRequirement,
- providerName: string,
- editing: boolean
-): string | undefined {
- if (requirement.kind === "none") return undefined;
-
- const values = { provider: providerName, credential: requirement.credentialName };
- if (editing) {
- return requirement.kind === "token"
- ? providerText(
- t,
- "webTokenEditHint",
- "Leave blank to keep the current web session token. Credential: {credential}.",
- values
- )
- : providerText(
- t,
- "webCookieEditHint",
- "Leave blank to keep the current session cookie. Required cookie: {credential}.",
- values
- );
- }
-
- return requirement.kind === "token"
- ? providerText(
- t,
- "webTokenCredentialHint",
- "Credential: {credential}. Paste the token value from your own signed-in {provider} web session, or a DevTools HAR export if the provider supports it.",
- values
- )
- : providerText(
- t,
- "webCookieCredentialHint",
- "Required cookie: {credential}. Paste the Cookie header value from your own signed-in {provider} web session. Do not include the Cookie: prefix.",
- values
- );
-}
-
-function getWebSessionCredentialCheckLabel(
- t: ProviderMessageTranslator,
- requirement: WebSessionCredentialRequirement
-): string {
- if (requirement.kind === "token") return providerText(t, "checkWebToken", "Check token");
- return providerText(t, "checkCookie", "Check cookie");
-}
-
-function getAddCredentialModalTitle(
- t: ProviderMessageTranslator,
- providerName: string,
- requirement: WebSessionCredentialRequirement | null
-): string {
- if (!requirement) return t("addProviderApiKeyTitle", { provider: providerName });
- if (requirement.kind === "none") {
- return providerText(t, "addProviderConnectionTitle", "Add {provider} connection", {
- provider: providerName,
- });
- }
- if (requirement.kind === "token") {
- return providerText(t, "addProviderWebTokenTitle", "Add {provider} web token", {
- provider: providerName,
- });
- }
- return providerText(t, "addProviderSessionCookieTitle", "Add {provider} session cookie", {
- provider: providerName,
- });
-}
-
-function WebSessionCredentialGuide({
- requirement,
- providerName,
- t,
-}: {
- requirement: WebSessionCredentialRequirement;
- providerName: string;
- t: ProviderMessageTranslator;
-}) {
- if (requirement.kind === "none") {
- return (
- <div className="rounded-lg border border-emerald-500/25 bg-emerald-500/10 px-3 py-3 text-sm text-text-muted">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-emerald-500">
- check_circle
- </span>
- <div>
- <p className="font-medium text-text-main">
- {providerText(t, "webNoAuthGuideTitle", "No credential required")}
- </p>
- <p className="mt-1">
- {providerText(
- t,
- "webNoAuthGuideBody",
- "{provider} does not need an API key or cookie. Save the connection to use its free web endpoint.",
- { provider: providerName }
- )}
- </p>
- </div>
- </div>
- </div>
- );
- }
-
- const requiredCredentialKey =
- requirement.kind === "token" ? "webTokenRequiredCredential" : "webCookieRequiredCredential";
- const requiredCredentialFallback =
- requirement.kind === "token" ? "Required token: {credential}" : "Required cookie: {credential}";
-
- return (
- <div className="rounded-lg border border-purple-500/25 bg-purple-500/10 px-3 py-3 text-sm text-text-muted">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-purple-500">cookie</span>
- <div className="space-y-2">
- <div>
- <p className="font-medium text-text-main">
- {providerText(t, "webSessionGuideTitle", "How to get the session credential")}
- </p>
- <p className="mt-1">
- {providerText(
- t,
- "webSessionGuideIntro",
- "{provider} uses a browser web session instead of an API key.",
- { provider: providerName }
- )}
- </p>
- </div>
- <p className="font-medium text-text-main">
- {providerText(t, requiredCredentialKey, requiredCredentialFallback, {
- credential: requirement.credentialName,
- })}
- </p>
- <ol className="list-decimal space-y-1 pl-5">
- <li>
- {providerText(t, "webSessionGuideStep1", "Sign in to {provider} in your browser.", {
- provider: providerName,
- })}
- </li>
- <li>
- {providerText(
- t,
- "webSessionGuideStep2",
- "Open the browser developer tools and inspect a request made by the web app."
- )}
- </li>
- <li>
- {providerText(
- t,
- "webSessionGuideStep3",
- "Copy the required credential from the provider's own domain. For cookies, copy only the Cookie header value and omit Cookie:.",
- { credential: requirement.credentialName }
- )}
- </li>
- <li>
- {providerText(
- t,
- "webSessionGuideStep4",
- "Paste it here and check the connection. If it stops working, sign in again and replace it with a fresh value."
- )}
- </li>
- </ol>
- <p className="text-xs text-amber-700 dark:text-amber-300">
- {providerText(
- t,
- "webSessionSecurityHint",
- "Treat this like a password: it may access your signed-in web account until it expires or is revoked."
- )}
- </p>
- </div>
- </div>
- </div>
- );
-}
-
-function effectiveNormalizeForProtocol(
- modelId: string,
- protocol: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- const pc = getProtoSlice(c, o, protocol);
- if (pc && Object.prototype.hasOwnProperty.call(pc, "normalizeToolCallId")) {
- return Boolean(pc.normalizeToolCallId);
- }
- if (c?.normalizeToolCallId) return true;
- return Boolean(o?.normalizeToolCallId);
-}
-
-function effectivePreserveForProtocol(
- modelId: string,
- protocol: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- const pc = getProtoSlice(c, o, protocol);
- if (pc && Object.prototype.hasOwnProperty.call(pc, "preserveOpenAIDeveloperRole")) {
- return Boolean(pc.preserveOpenAIDeveloperRole);
- }
- if (c && Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole")) {
- return Boolean(c.preserveOpenAIDeveloperRole);
- }
- if (o && Object.prototype.hasOwnProperty.call(o, "preserveOpenAIDeveloperRole")) {
- return Boolean(o.preserveOpenAIDeveloperRole);
- }
- return true;
-}
-
-function anyNormalizeCompatBadge(
- modelId: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- if (c?.normalizeToolCallId || o?.normalizeToolCallId) return true;
- for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
- const pc = getProtoSlice(c, o, p);
- if (pc?.normalizeToolCallId) return true;
- }
- return false;
-}
-
-function anyNoPreserveCompatBadge(
- modelId: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- if (
- c &&
- Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole") &&
- c.preserveOpenAIDeveloperRole === false
- ) {
- return true;
- }
- if (
- o &&
- Object.prototype.hasOwnProperty.call(o, "preserveOpenAIDeveloperRole") &&
- o.preserveOpenAIDeveloperRole === false
- ) {
- return true;
- }
- for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
- const pc = getProtoSlice(c, o, p);
- if (
- pc &&
- Object.prototype.hasOwnProperty.call(pc, "preserveOpenAIDeveloperRole") &&
- pc.preserveOpenAIDeveloperRole === false
- ) {
- return true;
- }
- }
- return false;
-}
-
-function upstreamHeadersRecordsEqual(
- a: Record<string, string>,
- b: Record<string, string>
-): boolean {
- const ka = Object.keys(a).sort();
- const kb = Object.keys(b).sort();
- if (ka.length !== kb.length) return false;
- return ka.every((k, i) => k === kb[i] && a[k] === b[k]);
-}
-
-type HeaderDraftRow = { id: string; name: string; value: string };
-
-const UPSTREAM_HEADERS_UI_MAX = 16;
-
-function recordToHeaderRows(rec: Record<string, string>, genId: () => string): HeaderDraftRow[] {
- const entries = Object.entries(rec).filter(([k]) => k.trim());
- if (entries.length === 0) return [{ id: genId(), name: "", value: "" }];
- return entries.map(([name, value]) => ({ id: genId(), name, value }));
-}
-
-function headerRowsToRecord(rows: HeaderDraftRow[]): Record<string, string> {
- const out: Record<string, string> = {};
- for (const r of rows) {
- const k = r.name.trim();
- if (!k) continue;
- out[k] = r.value;
- }
- return out;
-}
-
-type ProviderModelsApiErrorBody = {
- error?: {
- message?: string;
- details?: Array<{ field?: string; message?: string }>;
- };
-};
-
-async function formatProviderModelsErrorResponse(res: Response): Promise<string> {
- try {
- const data = (await res.json()) as ProviderModelsApiErrorBody;
- const err = data?.error;
- if (Array.isArray(err?.details) && err.details.length > 0) {
- return err.details
- .map((d) => {
- const f = typeof d.field === "string" && d.field ? d.field : "?";
- const m = typeof d.message === "string" ? d.message : "";
- return m ? `${f}: ${m}` : f;
- })
- .join("; ");
- }
- if (typeof err?.message === "string" && err.message.trim()) {
- return err.message.trim();
- }
- } catch {
- /* ignore */
- }
- const st = res.statusText?.trim();
- return st || `HTTP ${res.status}`;
-}
-
-function effectiveUpstreamHeadersForProtocol(
- modelId: string,
- protocol: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): Record<string, string> {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- const base: Record<string, string> = {};
- if (c?.upstreamHeaders && typeof c.upstreamHeaders === "object") {
- Object.assign(base, c.upstreamHeaders);
- } else if (o?.upstreamHeaders && typeof o.upstreamHeaders === "object") {
- Object.assign(base, o.upstreamHeaders);
- }
- const pc = getProtoSlice(c, o, protocol);
- if (pc?.upstreamHeaders && typeof pc.upstreamHeaders === "object") {
- Object.assign(base, pc.upstreamHeaders);
- }
- return base;
-}
-
-function anyUpstreamHeadersBadge(
- modelId: string,
- customMap: CompatModelMap,
- overrideMap: CompatModelMap
-): boolean {
- const c = customMap.get(modelId);
- const o = overrideMap.get(modelId);
- const nonempty = (u: unknown) =>
- u && typeof u === "object" && !Array.isArray(u) && Object.keys(u as object).length > 0;
- if (nonempty(c?.upstreamHeaders) || nonempty(o?.upstreamHeaders)) return true;
- for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
- const pc = getProtoSlice(c, o, p);
- if (nonempty(pc?.upstreamHeaders)) return true;
- }
- return false;
-}
-
-interface ModelRowProps {
- model: { id: string; name?: string; source?: string; isHidden?: boolean };
- fullModel: string;
- provider: string;
- copied?: string;
- onCopy: (text: string, key: string) => void;
- t: (key: string, values?: Record<string, unknown>) => string;
- showDeveloperToggle?: boolean;
- effectiveModelNormalize: (modelId: string, protocol?: string) => boolean;
- effectiveModelPreserveDeveloper: (modelId: string, protocol?: string) => boolean;
- saveModelCompatFlags: (modelId: string, patch: ModelCompatSavePatch) => void;
- getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
- compatDisabled?: boolean;
- onToggleHidden?: (modelId: string, hidden: boolean) => Promise<void>;
- togglingHidden?: boolean;
- onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
- testStatus?: "ok" | "error" | null;
- testingModel?: boolean;
-}
-
-interface PassthroughModelRowProps {
- modelId: string;
- fullModel: string;
- source?: string;
- isFree?: boolean;
- isHidden?: boolean;
- copied?: string;
- onCopy: (text: string, key: string) => void;
- onDeleteAlias?: () => void;
- t: (key: string, values?: Record<string, unknown>) => string;
- showDeveloperToggle?: boolean;
- effectiveModelNormalize: (modelId: string, protocol?: string) => boolean;
- effectiveModelPreserveDeveloper: (modelId: string, protocol?: string) => boolean;
- saveModelCompatFlags: (modelId: string, patch: ModelCompatSavePatch) => void;
- getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
- compatDisabled?: boolean;
- onToggleHidden?: (modelId: string, hidden: boolean) => Promise<void>;
- togglingHidden?: boolean;
- onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
- testStatus?: "ok" | "error" | null;
- testingModel?: boolean;
-}
-
-interface PassthroughModelsSectionProps {
- providerAlias: string;
- modelAliases: Record<string, string>;
- availableModels?: CompatModelRow[];
- customModels?: CompatModelRow[];
- description: string;
- inputLabel: string;
- inputPlaceholder: string;
- copied?: string;
- onCopy: (text: string, key: string) => void;
- onSetAlias: (modelId: string, alias: string) => Promise<void>;
- onDeleteAlias: (alias: string) => void;
- t: (key: string, values?: Record<string, unknown>) => string;
- effectiveModelNormalize: (alias: string) => boolean;
- effectiveModelPreserveDeveloper: (alias: string) => boolean;
- getUpstreamHeadersRecord: (modelId: string, protocol: string) => Record<string, string>;
- saveModelCompatFlags: (
- modelId: string,
- flags: {
- normalizeToolCallId?: boolean;
- preserveDeveloperRole?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- }
- ) => Promise<void>;
- compatSavingModelId?: string;
- isModelHidden: (modelId: string) => boolean;
- onToggleHidden: (modelId: string, hidden: boolean) => Promise<void>;
- onBulkToggleHidden: (modelIds: string[], hidden: boolean) => Promise<void>;
- bulkTogglePending?: boolean;
- togglingModelId?: string | null;
- onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
- modelTestStatus?: Record<string, "ok" | "error" | null>;
- testingModelId?: string | null;
- providerId: string;
- connectionId: string;
-}
-
-interface CustomModelsSectionProps {
- providerId: string;
- providerAlias: string;
- copied?: string;
- onCopy: (text: string, key: string) => void;
- onModelsChanged?: () => void;
-}
-
-interface CompatibleModelsSectionProps {
- providerStorageAlias: string;
- providerDisplayAlias: string;
- modelAliases: Record<string, string>;
- availableModels?: CompatModelRow[];
- customModels?: CompatModelRow[];
- fallbackModels?: CompatModelRow[];
- allowImport: boolean;
- description: string;
- inputLabel: string;
- inputPlaceholder: string;
- copied?: string;
- onCopy: (text: string, key: string) => void;
- onSetAlias: (modelId: string, alias: string, providerStorageAlias?: string) => Promise<void>;
- onDeleteAlias: (alias: string) => void;
- connections: { id?: string; isActive?: boolean }[];
- isAnthropic?: boolean;
- onImportWithProgress: (connectionId: string) => Promise<void>;
- t: (key: string, values?: Record<string, unknown>) => string;
- effectiveModelNormalize: (alias: string) => boolean;
- effectiveModelPreserveDeveloper: (alias: string) => boolean;
- getUpstreamHeadersRecord: (modelId: string, protocol: string) => Record<string, string>;
- saveModelCompatFlags: (
- modelId: string,
- flags: {
- normalizeToolCallId?: boolean;
- preserveDeveloperRole?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- isHidden?: boolean;
- }
- ) => Promise<void>;
- compatSavingModelId?: string;
- onModelsChanged?: () => void;
- isModelHidden: (modelId: string) => boolean;
- onToggleHidden: (modelId: string, hidden: boolean) => Promise<void>;
- onBulkToggleHidden: (modelIds: string[], hidden: boolean) => Promise<void>;
- bulkTogglePending?: boolean;
- togglingModelId?: string | null;
- onTestModel?: (modelId: string, fullModel: string) => Promise<void>;
- modelTestStatus?: Record<string, "ok" | "error" | null>;
- testingModelId?: string | null;
- onTestAll?: (targets: Array<{ modelId: string; fullModel: string }>) => Promise<void>;
- testingAll?: boolean;
- testProgress?: { done: number; total: number } | null;
- autoHideFailed?: boolean;
- onAutoHideFailedChange?: (v: boolean) => void;
-}
-
-interface CooldownTimerProps {
- until: string | number | Date;
-}
-
-function getModelSourceBadgeClass(source?: string): string {
- switch (normalizeModelCatalogSource(source)) {
- case "imported":
- return "border-sky-500/30 bg-sky-500/10 text-sky-300";
- case "custom":
- return "border-emerald-500/30 bg-emerald-500/10 text-emerald-300";
- case "fallback":
- return "border-amber-500/30 bg-amber-500/10 text-amber-300";
- case "alias":
- return "border-violet-500/30 bg-violet-500/10 text-violet-300";
- case "system":
- default:
- return "border-border bg-sidebar/70 text-text-muted";
- }
-}
-
-function ModelSourceBadge({ source }: { source?: string }) {
- return (
- <span
- className={`rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide ${getModelSourceBadgeClass(
- source
- )}`}
- >
- {getModelCatalogSourceLabel(source)}
- </span>
- );
-}
-
-interface ConnectionRowConnection {
- id?: string;
- name?: string;
- email?: string;
- displayName?: string;
- rateLimitedUntil?: string;
- rateLimitProtection?: boolean;
- testStatus?: string;
- isActive?: boolean;
- priority?: number;
- lastError?: string;
- lastErrorType?: string;
- lastErrorSource?: string;
- errorCode?: string | number;
- globalPriority?: number;
- providerSpecificData?: Record<string, unknown>;
- expiresAt?: string;
- tokenExpiresAt?: string;
- maxConcurrent?: number | null;
- authType?: string;
- proxyEnabled?: boolean;
- perKeyProxyEnabled?: boolean;
-}
-
-interface ConnectionRowProps {
- connection: ConnectionRowConnection;
- isOAuth: boolean;
- isClaude?: boolean;
- isCodex?: boolean;
- isGeminiCli?: boolean;
- codexGlobalServiceMode?: CodexGlobalServiceMode;
- isFirst: boolean;
- isLast: boolean;
- isSelected?: boolean;
- onToggleSelect?: () => void;
- onMoveUp: () => void;
- onMoveDown: () => void;
- onToggleActive: (isActive?: boolean) => void | Promise<void>;
- onToggleRateLimit: (enabled?: boolean) => void;
- onToggleClaudeExtraUsage?: (enabled?: boolean) => void;
- onToggleCodex5h?: (enabled?: boolean) => void;
- onToggleCodexWeekly?: (enabled?: boolean) => void;
- isCcCompatible?: boolean;
- cliproxyapiEnabled?: boolean;
- onToggleCliproxyapiMode?: (enabled?: boolean) => void;
- onRetest: () => void;
- isRetesting?: boolean;
- onEdit: () => void;
- onDelete: () => void;
- onReauth?: () => void;
- onProxy?: () => void;
- hasProxy?: boolean;
- proxySource?: string;
- proxyHost?: string;
- proxyEnabled?: boolean;
- perKeyProxyEnabled?: boolean;
- onToggleProxyEnabled?: (enabled: boolean) => void;
- onTogglePerKeyProxyEnabled?: (enabled: boolean) => void;
- onRefreshToken?: () => void;
- isRefreshing?: boolean;
- onApplyCodexAuthLocal?: () => void;
- isApplyingCodexAuthLocal?: boolean;
- onExportCodexAuthFile?: () => void;
- isExportingCodexAuthFile?: boolean;
- onApplyClaudeAuthLocal?: () => void;
- isApplyingClaudeAuthLocal?: boolean;
- onExportClaudeAuthFile?: () => void;
- isExportingClaudeAuthFile?: boolean;
- onApplyGeminiAuthLocal?: () => void;
- isApplyingGeminiAuthLocal?: boolean;
- onExportGeminiAuthFile?: () => void;
- isExportingGeminiAuthFile?: boolean;
-}
-
-interface AddApiKeyModalProps {
- isOpen: boolean;
- provider?: string;
- providerName?: string;
- initialBaseUrl?: string;
- isCompatible?: boolean;
- isAnthropic?: boolean;
- isCcCompatible?: boolean;
- isCommandCode?: boolean;
- commandCodeAuthState?: CommandCodeAuthFlowState;
- onStartCommandCodeAuth?: () => void;
- onSave: (data: {
- name: string;
- apiKey?: string;
- priority: number;
- baseUrl?: string;
- providerSpecificData?: Record<string, unknown>;
- }) => Promise<void | unknown>;
- onClose: () => void;
-}
-
-type CommandCodeAuthFlowState = {
- phase:
- | "idle"
- | "starting"
- | "polling"
- | "received"
- | "applying"
- | "applied"
- | "expired"
- | "error";
- state: string;
- authUrl: string;
- callbackUrl: string;
- expiresAt: string | null;
- message?: string;
-};
-
-const SILICONFLOW_ENDPOINTS = [
- { id: "siliconflow", label: "Global", baseUrl: "https://api.siliconflow.com/v1" },
- { id: "siliconflow-cn", label: "China", baseUrl: "https://api.siliconflow.cn/v1" },
-] as const;
-
-interface EditConnectionModalConnection {
- id?: string;
- name?: string;
- email?: string;
- priority?: number;
- maxConcurrent?: number | null;
- rateLimitOverrides?: Record<string, number> | null;
- authType?: string;
- provider?: string;
- apiKey?: string;
- providerSpecificData?: Record<string, unknown>;
- healthCheckInterval?: number;
- projectId?: string | null;
-}
-
-const formatTimeAgo = (dateStr: string): string => {
- const now = Date.now();
- const date = new Date(dateStr).getTime();
- const diff = now - date;
- if (diff < 0) return "just now";
- const minutes = Math.floor(diff / 60000);
- if (minutes < 1) return "just now";
- if (minutes < 60) return `${minutes}m ago`;
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
- const days = Math.floor(hours / 24);
- if (days < 30) return `${days}d ago`;
- return new Date(dateStr).toLocaleDateString();
-};
-
-interface EditConnectionModalProps {
- isOpen: boolean;
- connection: EditConnectionModalConnection | null;
- onSave: (data: unknown) => Promise<void | unknown>;
- onClose: () => void;
-}
-
-interface EditCompatibleNodeModalNode {
- id?: string;
- name?: string;
- prefix?: string;
- apiType?: string;
- baseUrl?: string;
- chatPath?: string;
- modelsPath?: string;
-}
-
-interface EditCompatibleNodeModalProps {
- isOpen: boolean;
- node: EditCompatibleNodeModalNode | null;
- onSave: (data: unknown) => Promise<void>;
- onClose: () => void;
- isAnthropic?: boolean;
- isCcCompatible?: boolean;
-}
-
-const CC_COMPATIBLE_DEFAULT_CHAT_PATH = "/v1/messages?beta=true";
-const CODEX_REASONING_STRENGTH_OPTIONS = [
- { value: "none", label: "None" },
- { value: "low", label: "Low" },
- { value: "medium", label: "Medium" },
- { value: "high", label: "High" },
- { value: "xhigh", label: "XHigh" },
-];
-
-const CODEX_ACCOUNT_SERVICE_TIER_VALUES: CodexServiceTier[] = ["default", "priority", "flex"];
-const CODEX_GLOBAL_SERVICE_MODE_VALUES: CodexGlobalServiceMode[] = [
- "none",
- ...CODEX_ACCOUNT_SERVICE_TIER_VALUES,
-];
-
-function getCodexServiceTierLabel(
- t: ProviderMessageTranslator,
- value: CodexGlobalServiceMode
-): string {
- if (value === "none") {
- return providerText(t, "codexServiceModeNone", "No global setting");
- }
- if (value === "default") return providerText(t, "codexServiceTierDefault", "Default");
- if (value === "priority") return providerText(t, "codexServiceTierPriority", "Priority");
- return providerText(t, "codexServiceTierFlex", "Flex");
-}
-
-function normalizeCodexLimitPolicy(policy: unknown): { use5h: boolean; useWeekly: boolean } {
- const record =
- policy && typeof policy === "object" && !Array.isArray(policy)
- ? (policy as Record<string, unknown>)
- : {};
- return {
- use5h: typeof record.use5h === "boolean" ? record.use5h : true,
- useWeekly: typeof record.useWeekly === "boolean" ? record.useWeekly : true,
- };
-}
-
-/**
- * UI adapter around the canonical getCodexRequestDefaults from requestDefaults.ts.
- * Adds the "medium" fallback for reasoningEffort required by the connection form.
- */
-function getCodexRequestDefaults(providerSpecificData: unknown): {
- reasoningEffort: string;
- serviceTier?: CodexServiceTier;
-} {
- const defaults = _getCodexRequestDefaults(providerSpecificData);
- return {
- reasoningEffort: defaults.reasoningEffort ?? "medium",
- ...(defaults.serviceTier ? { serviceTier: defaults.serviceTier } : {}),
- };
-}
-
-function getClaudeCodeCompatibleRequestDefaults(providerSpecificData: unknown): {
- context1m: boolean;
-} {
- const defaults = _getClaudeCodeCompatibleRequestDefaults(providerSpecificData);
- return {
- context1m: defaults.context1m === true,
- };
-}
-
-function compatProtocolLabelKey(protocol: string): string {
- if (protocol === "openai") return "compatProtocolOpenAI";
- if (protocol === "openai-responses") return "compatProtocolOpenAIResponses";
- if (protocol === "claude") return "compatProtocolClaude";
- return "compatProtocolOpenAI";
-}
-
-function ModelCompatPopover({
- t,
- effectiveModelNormalize,
- effectiveModelPreserveDeveloper,
- getUpstreamHeadersRecord,
- onCompatPatch,
- showDeveloperToggle = true,
- compact = false,
- disabled,
-}: {
- t: (key: string) => string;
- effectiveModelNormalize: (protocol: string) => boolean;
- effectiveModelPreserveDeveloper: (protocol: string) => boolean;
- getUpstreamHeadersRecord: (protocol: string) => Record<string, string>;
- onCompatPatch: (
- protocol: string,
- payload: {
- normalizeToolCallId?: boolean;
- preserveOpenAIDeveloperRole?: boolean;
- upstreamHeaders?: Record<string, string>;
- }
- ) => void;
- showDeveloperToggle?: boolean;
- compact?: boolean;
- disabled?: boolean;
-}) {
- const [open, setOpen] = useState(false);
- const [protocol, setProtocol] = useState<string>(MODEL_COMPAT_PROTOCOL_KEYS[0]);
- const [headerRows, setHeaderRows] = useState<HeaderDraftRow[]>([]);
- const [valuePeekRowId, setValuePeekRowId] = useState<string | null>(null);
- const [valueFocusRowId, setValueFocusRowId] = useState<string | null>(null);
- const ref = useRef<HTMLDivElement>(null);
- const panelRef = useRef<HTMLDivElement | null>(null);
- const [portalPanelRect, setPortalPanelRect] = useState<{
- top?: number;
- bottom?: number;
- left: number;
- width: number;
- } | null>(null);
- const headerRowIdRef = useRef(0);
- const headerRowsRef = useRef<HeaderDraftRow[]>([]);
- headerRowsRef.current = headerRows;
-
- const genHeaderRowId = () => {
- headerRowIdRef.current += 1;
- return `uh-${headerRowIdRef.current}`;
- };
-
- const normalizeToolCallId = effectiveModelNormalize(protocol);
- const preserveDeveloperRole = effectiveModelPreserveDeveloper(protocol);
- const devToggle = showDeveloperToggle && protocol !== "claude";
-
- const tryCommitHeaderRows = useCallback(
- (rows: HeaderDraftRow[]) => {
- const parsed = headerRowsToRecord(rows);
- const current = getUpstreamHeadersRecord(protocol);
- if (upstreamHeadersRecordsEqual(parsed, current)) return;
- onCompatPatch(protocol, { upstreamHeaders: parsed });
- },
- [getUpstreamHeadersRecord, onCompatPatch, protocol]
- );
-
- const onHeaderFieldBlur = useCallback(() => {
- queueMicrotask(() => tryCommitHeaderRows(headerRowsRef.current));
- }, [tryCommitHeaderRows]);
-
- useEffect(() => {
- if (!open) return;
- return () => {
- tryCommitHeaderRows(headerRowsRef.current);
- };
- }, [open, tryCommitHeaderRows]);
-
- useEffect(() => {
- if (!open) return;
- const rec = getUpstreamHeadersRecord(protocol);
- setHeaderRows(recordToHeaderRows(rec, genHeaderRowId));
- // Only re-load rows when opening or switching protocol — not when the parent passes a new
- // inline callback every render (would wipe in-progress edits).
- // eslint-disable-next-line react-hooks/exhaustive-deps -- see above
- }, [open, protocol]);
-
- useEffect(() => {
- setValuePeekRowId(null);
- setValueFocusRowId(null);
- }, [open, protocol]);
-
- const namedHeaderCount = headerRows.filter((r) => r.name.trim()).length;
- const canAddHeaderRow = namedHeaderCount < UPSTREAM_HEADERS_UI_MAX;
-
- const updateHeaderRow = (id: string, patch: Partial<Pick<HeaderDraftRow, "name" | "value">>) => {
- setHeaderRows((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
- };
-
- const addHeaderRow = () => {
- if (!canAddHeaderRow) return;
- setHeaderRows((prev) => [...prev, { id: genHeaderRowId(), name: "", value: "" }]);
- };
-
- const removeHeaderRow = (id: string) => {
- setHeaderRows((prev) => {
- const next = prev.filter((r) => r.id !== id);
- const normalized = next.length === 0 ? [{ id: genHeaderRowId(), name: "", value: "" }] : next;
- queueMicrotask(() => tryCommitHeaderRows(normalized));
- return normalized;
- });
- };
-
- useEffect(() => {
- if (!open) return;
- const onDocClick = (e: MouseEvent) => {
- const target = e.target as Node;
- const insideTrigger = ref.current?.contains(target);
- const insidePanel = panelRef.current?.contains(target);
- if (!insideTrigger && !insidePanel) setOpen(false);
- };
- document.addEventListener("mousedown", onDocClick);
- return () => document.removeEventListener("mousedown", onDocClick);
- }, [open]);
-
- const updatePortalPanelRect = useCallback(() => {
- if (!open || !ref.current) return;
- const rect = ref.current.getBoundingClientRect();
- const margin = 10;
- const width = Math.min(window.innerWidth - 2 * margin, 24 * 16);
- let left = rect.right - width;
- left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
- // Estimated panel height: capped at min(82vh, 42rem=672px)
- const estimatedPanelHeight = Math.min(window.innerHeight * 0.82, 672);
- const spaceBelow = window.innerHeight - rect.bottom - margin;
- const spaceAbove = rect.top - margin;
- if (spaceBelow < estimatedPanelHeight && spaceAbove > spaceBelow) {
- // Not enough space below — open upward
- setPortalPanelRect({ bottom: window.innerHeight - rect.top + 8, left, width });
- } else {
- setPortalPanelRect({ top: rect.bottom + 8, left, width });
- }
- }, [open]);
-
- useLayoutEffect(() => {
- if (!open) {
- setPortalPanelRect(null);
- return;
- }
- updatePortalPanelRect();
- window.addEventListener("resize", updatePortalPanelRect);
- window.addEventListener("scroll", updatePortalPanelRect, true);
- return () => {
- window.removeEventListener("resize", updatePortalPanelRect);
- window.removeEventListener("scroll", updatePortalPanelRect, true);
- };
- }, [open, updatePortalPanelRect]);
-
- const panelChromeClass =
- "flex max-h-[min(82vh,42rem)] flex-col overflow-hidden rounded-xl border-2 border-zinc-200 bg-white shadow-2xl dark:border-zinc-600 dark:bg-zinc-950";
-
- return (
- <div className="relative inline-flex" ref={ref}>
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- disabled={disabled}
- className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg border border-border bg-background text-text-muted hover:bg-muted hover:text-text-main disabled:opacity-50 transition-colors"
- title={t("compatAdjustmentsTitle")}
- >
- <span className="material-symbols-outlined text-base leading-none">tune</span>
- {!compact && t("compatButtonLabel")}
- </button>
- {open &&
- typeof document !== "undefined" &&
- portalPanelRect &&
- createPortal(
- <div
- ref={panelRef}
- className={panelChromeClass}
- style={{
- position: "fixed",
- ...(portalPanelRect.top !== undefined
- ? { top: portalPanelRect.top }
- : { bottom: portalPanelRect.bottom }),
- left: portalPanelRect.left,
- width: portalPanelRect.width,
- zIndex: 10040,
- }}
- >
- <div className="shrink-0 border-b-2 border-zinc-200 bg-zinc-100 px-3 py-2.5 dark:border-zinc-600 dark:bg-zinc-900">
- <p className="text-xs font-semibold text-text-main">{t("compatAdjustmentsTitle")}</p>
- <p className="text-[11px] text-text-muted mt-1 leading-relaxed">
- {t("compatProtocolHint")}
- </p>
- </div>
- <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto bg-white p-3 [scrollbar-gutter:stable] [scrollbar-width:thin] dark:bg-zinc-950">
- <label className="block text-[11px] font-medium text-text-muted mb-1.5">
- {t("compatProtocolLabel")}
- </label>
- <select
- value={protocol}
- onChange={(e) => setProtocol(e.target.value)}
- disabled={disabled}
- className="mb-4 w-full rounded-lg border border-zinc-200 bg-white px-2.5 py-2 text-xs text-text-main focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30 dark:border-zinc-600 dark:bg-zinc-900"
- >
- {MODEL_COMPAT_PROTOCOL_KEYS.map((p) => (
- <option key={p} value={p}>
- {t(compatProtocolLabelKey(p))}
- </option>
- ))}
- </select>
- <div className="flex flex-col gap-3.5">
- <Toggle
- size="sm"
- label={t("compatToolIdShort")}
- title={t("normalizeToolCallIdLabel")}
- checked={normalizeToolCallId}
- onChange={(v) => onCompatPatch(protocol, { normalizeToolCallId: v })}
- disabled={disabled}
- />
- {devToggle && (
- <Toggle
- size="sm"
- label={t("compatDoNotPreserveDeveloper")}
- title={t("preserveDeveloperRoleLabel")}
- checked={preserveDeveloperRole === false}
- onChange={(checked) =>
- onCompatPatch(protocol, { preserveOpenAIDeveloperRole: !checked })
- }
- disabled={disabled}
- />
- )}
- </div>
-
- <div className="mt-4 rounded-lg border-2 border-zinc-200 bg-zinc-100 p-3 dark:border-zinc-600 dark:bg-zinc-900">
- <label className="block text-[11px] font-semibold text-text-main mb-1">
- {t("compatUpstreamHeadersLabel")}
- </label>
- <p className="text-[11px] text-text-muted mb-3 leading-relaxed">
- {t("compatUpstreamHeadersHint")}
- </p>
- <div className="space-y-2">
- <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-end text-[10px] font-medium uppercase tracking-wide text-text-muted px-0.5">
- <span>{t("compatUpstreamHeaderName")}</span>
- <span className="col-span-1">{t("compatUpstreamHeaderValue")}</span>
- <span className="w-8 shrink-0" aria-hidden />
- </div>
- {headerRows.map((row) => (
- <div
- key={row.id}
- className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-center"
- >
- <Input
- value={row.name}
- onChange={(e) => updateHeaderRow(row.id, { name: e.target.value })}
- onBlur={onHeaderFieldBlur}
- disabled={disabled}
- placeholder={t("compatUpstreamHeaderNamePlaceholder")}
- className="gap-0 min-w-0"
- inputClassName="h-9 bg-white py-1.5 px-2 text-xs font-mono dark:bg-zinc-900"
- autoComplete="off"
- />
- <div
- className="min-w-0"
- onMouseEnter={() => setValuePeekRowId(row.id)}
- onMouseLeave={() =>
- setValuePeekRowId((cur) => (cur === row.id ? null : cur))
- }
- >
- <Input
- type={
- valuePeekRowId === row.id || valueFocusRowId === row.id
- ? "text"
- : "password"
- }
- value={row.value}
- onChange={(e) => updateHeaderRow(row.id, { value: e.target.value })}
- onFocus={() => setValueFocusRowId(row.id)}
- onBlur={() => {
- setValueFocusRowId((cur) => (cur === row.id ? null : cur));
- onHeaderFieldBlur();
- }}
- disabled={disabled}
- placeholder={t("compatUpstreamHeaderValuePlaceholder")}
- className="gap-0 min-w-0"
- inputClassName="h-9 bg-white py-1.5 px-2 text-xs dark:bg-zinc-900"
- autoComplete="off"
- spellCheck={false}
- />
- </div>
- <button
- type="button"
- disabled={disabled || headerRows.length <= 1}
- onClick={() => removeHeaderRow(row.id)}
- title={t("compatUpstreamRemoveRow")}
- className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/80 text-text-muted hover:bg-red-500/10 hover:text-red-600 dark:hover:text-red-400 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-text-muted transition-colors"
- >
- <span className="material-symbols-outlined text-lg leading-none">
- close
- </span>
- </button>
- </div>
- ))}
- </div>
- <button
- type="button"
- disabled={disabled || !canAddHeaderRow}
- onClick={addHeaderRow}
- className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-border py-2 text-xs font-medium text-primary hover:bg-primary/5 disabled:opacity-40 disabled:hover:bg-transparent transition-colors"
- >
- <span className="material-symbols-outlined text-base leading-none">add</span>
- {t("compatUpstreamAddRow")}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
- </div>
- );
-}
-
-// ──── ProviderPlaygroundPanel ────────────────────────────────────────────────
-// Renders a playground section on the individual provider page.
-// Shows ServiceKindTabs if the provider declares multiple kinds; falls back to
-// a single-kind panel or the LlmChatCard for standard LLM providers.
-
-const MEDIA_SERVICE_KINDS: ServiceKind[] = [
- "embedding",
- "image",
- "tts",
- "stt",
- "webSearch",
- "webFetch",
- "video",
- "music",
-];
-
-function renderKindPanel(kind: ServiceKind, providerId: string): JSX.Element | null {
- switch (kind) {
- case "llm":
- return <LlmChatCard providerId={providerId} />;
- case "embedding":
- return <EmbeddingExampleCard providerId={providerId} />;
- case "image":
- return <ImageExampleCard providerId={providerId} />;
- case "tts":
- return <TtsExampleCard providerId={providerId} />;
- case "stt":
- return <SttExampleCard providerId={providerId} />;
- case "webSearch":
- return <WebSearchExampleCard providerId={providerId} />;
- case "webFetch":
- return <WebFetchExampleCard providerId={providerId} />;
- case "video":
- return <VideoExampleCard providerId={providerId} />;
- case "music":
- return <MusicExampleCard providerId={providerId} />;
- default:
- return null;
- }
-}
-
-function ProviderPlaygroundPanel({ providerId }: { providerId: string }) {
- // Resolve serviceKinds from AI_PROVIDERS.
- // For providers without explicit serviceKinds (most LLM providers), we infer
- // "llm" as the default.
- const providerEntry = AI_PROVIDERS[providerId as keyof typeof AI_PROVIDERS] as
- | (Record<string, unknown> & { serviceKinds?: string[] })
- | undefined;
-
- const rawKinds: string[] = providerEntry?.serviceKinds ?? [];
-
- const ALL_VALID_KINDS = [
- "llm",
- "embedding",
- "image",
- "imageToText",
- "tts",
- "stt",
- "webSearch",
- "webFetch",
- "video",
- "music",
- ] as const;
-
- const kinds: ServiceKind[] =
- rawKinds.length > 0
- ? rawKinds.filter((k): k is ServiceKind => (ALL_VALID_KINDS as readonly string[]).includes(k))
- : ["llm"];
-
- // Filter out kinds that have no playground implementation yet
- const playgroundableKinds = kinds.filter((k) => k !== "imageToText");
-
- // useState must be called unconditionally (Rules of Hooks)
- const [activeKind, setActiveKind] = useState<ServiceKind>(playgroundableKinds[0] ?? "llm");
-
- if (playgroundableKinds.length === 0) return null;
-
- return (
- <div className="flex flex-col gap-3">
- <h2 className="text-lg font-semibold">Playground</h2>
- <ServiceKindTabs
- kinds={playgroundableKinds}
- activeKind={activeKind}
- onSelect={setActiveKind}
- />
- {renderKindPanel(activeKind, providerId)}
- </div>
- );
-}
+import ProviderDetailPageClient from "./ProviderDetailPageClient";
+// Thin route wrapper — all logic lives in ProviderDetailPageClient (Issue #3501,
+// Phase 0 of the strangler-fig decomposition of this 12.8K-LOC god-component).
+// The client reads the route id itself via useParams(), so no props are threaded.
export default function ProviderDetailPage() {
- const params = useParams();
- const router = useRouter();
- const providerId = params.id as string;
- const [connections, setConnections] = useState([]);
- const [loading, setLoading] = useState(true);
- const [providerNode, setProviderNode] = useState(null);
- const [showOAuthModal, _setShowOAuthModal] = useState(false);
- const [reauthConnection, setReauthConnection] = useState<ConnectionRowConnection | null>(null);
- const [showAddApiKeyModal, setShowAddApiKeyModal] = useState(false);
- const [showSiliconFlowEndpointModal, setShowSiliconFlowEndpointModal] = useState(false);
- const [siliconFlowInitialBaseUrl, setSiliconFlowInitialBaseUrl] = useState<string | undefined>();
- const [showRiskNoticeModal, setShowRiskNoticeModal] = useState(false);
- const [commandCodeAuthState, setCommandCodeAuthState] = useState<CommandCodeAuthFlowState>({
- phase: "idle",
- state: "",
- authUrl: "",
- callbackUrl: "",
- expiresAt: null,
- message: "",
- });
- const [showEditModal, setShowEditModal] = useState(false);
- const [showEditNodeModal, setShowEditNodeModal] = useState(false);
- const [showTutorialModal, setShowTutorialModal] = useState(false);
- const [selectedConnection, setSelectedConnection] = useState(null);
- const [retestingId, setRetestingId] = useState(null);
- const [batchTesting, setBatchTesting] = useState(false);
- const [batchTestResults, setBatchTestResults] = useState<any>(null);
- const [modelAliases, setModelAliases] = useState({});
- const { copied, copy } = useCopyToClipboard();
- const t = useTranslations("providers");
- const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);
- const notify = useNotificationStore();
- const [proxyTarget, setProxyTarget] = useState(null);
- const [distributingProxies, setDistributingProxies] = useState(false);
- const [proxyConfig, setProxyConfig] = useState(null);
- const [connProxyMap, setConnProxyMap] = useState<
- Record<string, { proxy: any; level: string } | null>
- >({});
- const [importingModels, setImportingModels] = useState(false);
- const [importingZed, setImportingZed] = useState(false);
- const [showZedManual, setShowZedManual] = useState(false);
- const [zedManualProvider, setZedManualProvider] = useState("openai");
- const [zedManualToken, setZedManualToken] = useState("");
- const [importingZedManual, setImportingZedManual] = useState(false);
- const [showImportModal, setShowImportModal] = useState(false);
- const [importProgress, setImportProgress] = useState({
- current: 0,
- total: 0,
- phase: "idle" as "idle" | "fetching" | "importing" | "done" | "error",
- status: "",
- logs: [] as string[],
- error: "",
- importedCount: 0,
- });
- const [modelMeta, setModelMeta] = useState<{
- customModels: CompatModelRow[];
- modelCompatOverrides: Array<CompatModelRow & { id: string }>;
- }>({ customModels: [], modelCompatOverrides: [] });
- const [syncedAvailableModels, setSyncedAvailableModels] = useState<any[]>([]);
- const [compatSavingModelId, setCompatSavingModelId] = useState<string | null>(null);
- const [modelFilter, setModelFilter] = useState("");
- const [togglingModelId, setTogglingModelId] = useState<string | null>(null);
- const [testingModelId, setTestingModelId] = useState<string | null>(null);
- const [modelTestStatus, setModelTestStatus] = useState<Record<string, "ok" | "error">>({});
- const [testingAll, setTestingAll] = useState(false);
- const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);
- const [autoHideFailed, setAutoHideFailed] = useState(true);
- const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
- const [bulkVisibilityAction, setBulkVisibilityAction] = useState<"select" | "deselect" | null>(
- null
- );
- const [applyingCodexAuthId, setApplyingCodexAuthId] = useState<string | null>(null);
- const [applyCodexModalConnectionId, setApplyCodexModalConnectionId] = useState<string | null>(
- null
- );
- const [exportingCodexAuthId, setExportingCodexAuthId] = useState<string | null>(null);
- const [importCodexModalOpen, setImportCodexModalOpen] = useState(false);
- const [codexCliGuideOpen, setCodexCliGuideOpen] = useState(false);
- // "Adicionar Externo": public shareable device-flow link state.
- const [externalLinkModalOpen, setExternalLinkModalOpen] = useState(false);
- const [externalLinkUrl, setExternalLinkUrl] = useState("");
- const [externalLinkToken, setExternalLinkToken] = useState<string | null>(null);
- const [externalLinkLoading, setExternalLinkLoading] = useState(false);
- const [externalLinkError, setExternalLinkError] = useState<string | null>(null);
- const { copied: externalLinkCopied, copy: externalLinkCopy } = useCopyToClipboard();
- const [applyingClaudeAuthId, setApplyingClaudeAuthId] = useState<string | null>(null);
- const [applyClaudeModalConnectionId, setApplyClaudeModalConnectionId] = useState<string | null>(
- null
- );
- const [exportingClaudeAuthId, setExportingClaudeAuthId] = useState<string | null>(null);
- const [importClaudeModalOpen, setImportClaudeModalOpen] = useState(false);
- const [applyingGeminiAuthId, setApplyingGeminiAuthId] = useState<string | null>(null);
- const [applyGeminiModalConnectionId, setApplyGeminiModalConnectionId] = useState<string | null>(
- null
- );
- const [exportingGeminiAuthId, setExportingGeminiAuthId] = useState<string | null>(null);
- const [importGeminiModalOpen, setImportGeminiModalOpen] = useState(false);
- const [codexGlobalServiceMode, setCodexGlobalServiceMode] =
- useState<CodexGlobalServiceMode>("none");
- const [codexGlobalSupportedModels, setCodexGlobalSupportedModels] = useState<string[]>([
- ...CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS,
- ]);
- const [codexSettingsLoaded, setCodexSettingsLoaded] = useState(false);
- const [codexSettingsLoadError, setCodexSettingsLoadError] = useState<string | null>(null);
- const [savingCodexGlobalServiceMode, setSavingCodexGlobalServiceMode] = useState(false);
- const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
- const [batchDeleting, setBatchDeleting] = useState(false);
- const [batchUpdating, setBatchUpdating] = useState<"activate" | "deactivate" | null>(null);
- const [batchRetesting, setBatchRetesting] = useState(false);
- const [healthFilter, setHealthFilter] = useState<string>("all");
- const [page, setPage] = useState(0);
- const PAGE_SIZE = 50;
- const [batchDeleteConfirmOpen, setBatchDeleteConfirmOpen] = useState(false);
- const commandCodeAuthWindowRef = useRef<Window | null>(null);
- const commandCodeAuthTimerRef = useRef<number | null>(null);
- const pendingRiskActionRef = useRef<(() => void) | null>(null);
- const { acknowledged: riskAcknowledged, acknowledge: acknowledgeRisk } =
- useRiskAcknowledged(providerId);
- const codexSettingsRequestSeqRef = useRef(0);
- const isOpenAICompatible = isOpenAICompatibleProvider(providerId);
- const isCcCompatible = isClaudeCodeCompatibleProvider(providerId);
- const isCommandCode = providerId === "command-code";
- const isAnthropicCompatible =
- isAnthropicCompatibleProvider(providerId) && !isClaudeCodeCompatibleProvider(providerId);
- const isCompatible = isOpenAICompatible || isAnthropicCompatible || isCcCompatible;
- const isAnthropicProtocolCompatible = isAnthropicCompatible || isCcCompatible;
-
- const setShowOAuthModal = (show: boolean, connectionRow?: ConnectionRowConnection) => {
- _setShowOAuthModal(show);
- setReauthConnection(show && connectionRow ? connectionRow : null);
- };
-
- const codexGlobalServiceModeOptions = useMemo(
- () =>
- CODEX_GLOBAL_SERVICE_MODE_VALUES.map((value) => ({
- value,
- label: getCodexServiceTierLabel(t, value),
- })),
- [t]
- );
-
- const providerInfo = resolveDashboardProviderInfo(providerId, {
- providerNode,
- compatibleLabels: {
- ccCompatibleName: t("ccCompatibleLabel"),
- anthropicCompatibleName: t("anthropicCompatibleName"),
- openAiCompatibleName: t("openaiCompatibleName"),
- },
- });
- const providerSupportsOAuth =
- providerInfo?.toggleAuthType === "oauth" || providerInfo?.toggleAuthType === "free";
- const subscriptionRisk = providerInfo?.subscriptionRisk === true;
- const providerSupportsPat = supportsApiKeyOnFreeProvider(providerId);
- const isOAuth = providerSupportsOAuth && !providerSupportsPat;
- const isFreeNoAuth = NOAUTH_PROVIDERS[providerId]?.noAuth === true;
- const registryModels = getModelsByProviderId(providerId);
- // Prefer synced API-discovered models when available, then merge built-ins
- // and user-managed custom models without duplicating IDs.
- const models = useMemo(() => {
- // Universal: merge built-in registry models with API-synced models and
- // user-managed custom models for ALL providers (was previously Gemini-only).
- // Synced models keep their full property spread so provider-specific fields
- // (e.g. Gemini's `supportedGenerationMethods`) survive into the table.
- const builtInModels = registryModels.map((model) => ({
- ...model,
- source: "system",
- }));
-
- const registryIds = new Set(builtInModels.map((m) => m.id));
- const syncedExtras = syncedAvailableModels
- .filter((model: any) => model?.id && !registryIds.has(model.id))
- .map((model: any) => ({
- ...model,
- id: model.id,
- name: model.name || model.id,
- source: "imported",
- }));
- const knownIds = new Set([...registryIds, ...syncedExtras.map((model: any) => model.id)]);
- const customExtras = modelMeta.customModels
- .filter((cm: any) => cm.id && !knownIds.has(cm.id))
- .map((cm: any) => ({
- id: cm.id,
- name: cm.name || cm.id,
- source: normalizeModelCatalogSource(cm.source) === "imported" ? "imported" : "custom",
- }));
- const allModels = [...builtInModels, ...syncedExtras, ...customExtras];
- const deduped = new Map<string, typeof allModels[0]>();
- for (const m of allModels) {
- if (m.id && !deduped.has(m.id)) deduped.set(m.id, m);
- }
- return Array.from(deduped.values());
- }, [providerId, registryModels, syncedAvailableModels, modelMeta.customModels]);
- const providerAlias = getProviderAlias(providerId);
- const isManagedAvailableModelsProvider = isCompatible || providerId === "openrouter";
- const isSearchProvider = providerId.endsWith("-search");
- const isUpstreamProxyProvider = providerInfo?.category === "upstream-proxy";
- const compatibleSupportsModelImport = compatibleProviderSupportsModelImport(providerId);
-
- const providerStorageAlias = isCompatible ? providerId : providerAlias;
- const providerDisplayAlias = isCompatible ? providerNode?.prefix || providerId : providerAlias;
-
- const getApiLabel = () => {
- if (isAnthropicProtocolCompatible) return t("messagesApi");
- const type = providerNode?.apiType;
- switch (type) {
- case "responses":
- return t("responsesApi");
- case "embeddings":
- return t("embeddings");
- case "audio-transcriptions":
- return t("audioTranscriptions");
- case "audio-speech":
- return t("audioSpeech");
- case "images-generations":
- return t("imagesGenerations");
- default:
- return t("chatCompletions");
- }
- };
-
- const getApiDefaultPath = () => {
- if (isCcCompatible) return CC_COMPATIBLE_DEFAULT_CHAT_PATH;
- if (isAnthropicCompatible) return "/messages";
- const type = providerNode?.apiType;
- switch (type) {
- case "responses":
- return "/responses";
- case "embeddings":
- return "/embeddings";
- case "audio-transcriptions":
- return "/audio/transcriptions";
- case "audio-speech":
- return "/audio/speech";
- case "images-generations":
- return "/images/generations";
- default:
- return "/chat/completions";
- }
- };
-
- const getApiPath = () => {
- const defaultPath = getApiDefaultPath();
- return (providerNode?.chatPath || defaultPath).replace(/^\//, "");
- };
-
- // Define callbacks BEFORE the useEffect that uses them
- const fetchAliases = useCallback(async () => {
- try {
- const res = await fetch("/api/models/alias");
- const data = await res.json();
- if (res.ok) {
- setModelAliases(data.aliases || {});
- }
- } catch (error) {
- console.log("Error fetching aliases:", error);
- }
- }, []);
-
- const handleSetAlias = useCallback(
- async (modelId: string, alias: string, providerAlias?: string) => {
- const qualifiedModel = providerAlias
- ? modelId.includes("/")
- ? `${providerAlias}/${modelId.split("/").slice(1).join("/")}`
- : `${providerAlias}/${modelId}`
- : modelId;
- try {
- const res = await fetch("/api/models/alias", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ model: qualifiedModel, alias }),
- });
- if (res.ok) {
- await fetchAliases();
- notify.success(t("setAliasSuccess", { alias }));
- } else {
- const data = await res.json().catch(() => ({}));
- notify.error(data?.error?.message || "Failed to set alias");
- }
- } catch (error) {
- console.log("Error setting alias:", error);
- notify.error("Network error setting alias");
- }
- },
- [fetchAliases, t]
- );
-
- const handleDeleteAlias = useCallback(
- async (alias: string) => {
- try {
- const res = await fetch(
- `/api/models/alias?alias=${encodeURIComponent(alias)}`,
- { method: "DELETE" }
- );
- if (res.ok) {
- await fetchAliases();
- notify.success(t("deleteAliasSuccess", { alias }));
- } else {
- const data = await res.json().catch(() => ({}));
- notify.error(data?.error?.message || "Failed to delete alias");
- }
- } catch (error) {
- console.log("Error deleting alias:", error);
- notify.error("Network error deleting alias");
- }
- },
- [fetchAliases, t]
- );
-
- const fetchProviderModelMeta = useCallback(async () => {
- if (isSearchProvider) return;
- try {
- const res = await fetch(`/api/provider-models?provider=${encodeURIComponent(providerId)}`, {
- cache: "no-store",
- });
- if (!res.ok) return;
- const data = await res.json();
- setModelMeta({
- customModels: data.models || [],
- modelCompatOverrides: data.modelCompatOverrides || [],
- });
- try {
- const syncRes = await fetch(
- `/api/synced-available-models?provider=${encodeURIComponent(providerId)}`,
- {
- cache: "no-store",
- }
- );
- if (syncRes.ok) {
- const syncData = await syncRes.json();
- setSyncedAvailableModels(syncData.models || []);
- } else {
- setSyncedAvailableModels([]);
- }
- } catch {
- setSyncedAvailableModels([]);
- }
- } catch (e) {
- console.error("fetchProviderModelMeta", e);
- }
- }, [providerId, isSearchProvider]);
-
- const fetchProxyConfig = useCallback(async () => {
- try {
- const res = await fetch("/api/settings/proxy", { cache: "no-store" });
- if (res.ok) {
- setProxyConfig(await res.json());
- } else {
- setProxyConfig(null);
- }
- } catch {
- // Proxy indicators are best-effort.
- }
- }, []);
-
- const fetchConnections = useCallback(async () => {
- try {
- const [connectionsRes, nodesRes] = await Promise.all([
- fetch("/api/providers", { cache: "no-store" }),
- fetch("/api/provider-nodes", { cache: "no-store" }),
- ]);
- const connectionsData = await connectionsRes.json();
- const nodesData = await nodesRes.json();
- if (connectionsRes.ok) {
- const filtered = (connectionsData.connections || []).filter(
- (c) => c.provider === providerId
- );
- setConnections(filtered);
- }
- if (nodesRes.ok) {
- let node = (nodesData.nodes || []).find((entry) => entry.id === providerId) || null;
-
- // Newly created compatible nodes can be briefly unavailable on one worker.
- // Retry a few times before showing "Provider not found".
- if (!node && isCompatible) {
- for (let attempt = 0; attempt < 3; attempt += 1) {
- await new Promise((resolve) => setTimeout(resolve, 150));
- const retryRes = await fetch("/api/provider-nodes", { cache: "no-store" });
- if (!retryRes.ok) continue;
- const retryData = await retryRes.json();
- node = (retryData.nodes || []).find((entry) => entry.id === providerId) || null;
- if (node) break;
- }
- }
-
- setProviderNode(node);
- }
- } catch (error) {
- console.log("Error fetching connections:", error);
- } finally {
- setLoading(false);
- }
- }, [providerId, isCompatible]);
-
- const handleUpdateNode = async (formData) => {
- try {
- const res = await fetch(`/api/provider-nodes/${providerId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(formData),
- });
- const data = await res.json();
- if (res.ok) {
- setProviderNode(data.node);
- await fetchConnections();
- setShowEditNodeModal(false);
- }
- } catch (error) {
- console.log("Error updating provider node:", error);
- }
- };
-
- useEffect(() => {
- fetchConnections();
- fetchAliases();
- // Load proxy config for visual indicators (provider-level button)
- void fetchProxyConfig();
- }, [fetchConnections, fetchAliases, fetchProxyConfig]);
-
- const handleZedImport = useCallback(async () => {
- if (importingZed) return;
- setImportingZed(true);
- try {
- const res = await fetch("/api/providers/zed/import", { method: "POST" });
- const data = await res.json();
- if (!res.ok || !data.success) {
- if (data.zedDockerEnvironment) {
- setShowZedManual(true);
- }
- notify.error(data.error || "Zed import failed");
- } else if (!data.count) {
- const found = data.credentials?.length ?? 0;
- if (found === 0) {
- notify.info("No Zed credentials found in keychain");
- } else {
- notify.info(
- `Found ${found} keychain credential(s), but none matched supported providers`
- );
- }
- } else {
- notify.success(
- `Imported ${data.count} credential(s) from Zed for ${data.providers?.length ?? 0} provider(s)`
- );
- await fetchConnections();
- }
- } catch (e: any) {
- notify.error(e?.message || "Zed import failed");
- } finally {
- setImportingZed(false);
- }
- }, [importingZed, notify, fetchConnections]);
-
- const handleZedManualImport = useCallback(async () => {
- if (importingZedManual || !zedManualToken.trim()) return;
- setImportingZedManual(true);
- try {
- const res = await fetch("/api/providers/zed/manual-import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider: zedManualProvider, token: zedManualToken.trim() }),
- });
- const data = await res.json();
- if (!res.ok || !data.success) {
- notify.error(data.error?.message ?? data.error ?? "Manual import failed");
- } else {
- notify.success(`Imported ${zedManualProvider} token from Zed`);
- setZedManualToken("");
- await fetchConnections();
- }
- } catch (e: any) {
- notify.error(e?.message || "Manual import failed");
- } finally {
- setImportingZedManual(false);
- }
- }, [importingZedManual, zedManualProvider, zedManualToken, notify, fetchConnections]);
-
- const loadCodexSettings = useCallback(async () => {
- const requestSeq = codexSettingsRequestSeqRef.current + 1;
- codexSettingsRequestSeqRef.current = requestSeq;
- const isCurrentRequest = () => codexSettingsRequestSeqRef.current === requestSeq;
-
- if (providerId !== "codex") {
- setCodexSettingsLoaded(false);
- setCodexSettingsLoadError(null);
- return;
- }
-
- setCodexSettingsLoaded(false);
- setCodexSettingsLoadError(null);
-
- try {
- const response = await fetch("/api/settings", { cache: "no-store" });
- if (!response.ok) {
- throw new Error(`Settings request failed with HTTP ${response.status}`);
- }
- const data = await response.json();
- if (!data || typeof data !== "object") {
- throw new Error("Settings response was empty");
- }
- if (!isCurrentRequest()) return;
- const resolvedCodexServiceTier = resolveCodexGlobalFastServiceTier(data);
- setCodexGlobalServiceMode(getCodexGlobalServiceMode(data));
- setCodexGlobalSupportedModels([...resolvedCodexServiceTier.supportedModels]);
- setCodexSettingsLoaded(true);
- } catch (error) {
- if (!isCurrentRequest()) return;
- setCodexSettingsLoaded(false);
- setCodexSettingsLoadError(error instanceof Error ? error.message : "Failed to load settings");
- }
- }, [providerId]);
-
- useEffect(() => {
- void loadCodexSettings();
- }, [loadCodexSettings]);
-
- const loadConnProxies = useCallback(async (conns: { id?: string }[]) => {
- if (!conns.length) return;
- try {
- const results = await Promise.all(
- conns
- .filter((c) => c.id)
- .map((c) =>
- fetch(`/api/settings/proxy?resolve=${encodeURIComponent(c.id!)}`, { cache: "no-store" })
- .then((r) => (r.ok ? r.json() : null))
- .then((data) => [c.id!, data] as [string, any])
- .catch(() => [c.id!, null] as [string, any])
- )
- );
- const map: Record<string, { proxy: any; level: string } | null> = {};
- for (const [id, data] of results) {
- map[id] = data?.proxy ? data : null;
- }
- setConnProxyMap(map);
- } catch {
- // ignore
- }
- }, []);
-
- useEffect(() => {
- if (loading || isSearchProvider) return;
- fetchProviderModelMeta();
- }, [loading, isSearchProvider, fetchProviderModelMeta]);
-
- // Load per-connection effective proxy (handles registry assignments)
- useEffect(() => {
- if (!loading && connections.length > 0) {
- void loadConnProxies(connections);
- }
- }, [loading, connections, loadConnProxies]);
-
- const onTestModel = async (modelId: string, fullModel: string) => {
- setTestingModelId(modelId);
- setModelTestStatus((prev) => ({ ...prev, [modelId]: undefined }));
- try {
- const res = await fetch("/api/models/test", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerId: selectedConnection?.provider || providerNode?.id || providerId,
- modelId: fullModel,
- connectionId: selectedConnection?.id,
- }),
- });
- const data = await res.json();
- if (res.ok && data.status === "ok") {
- notify.success(
- providerText(
- t,
- "testModelSuccess",
- `Model ${modelId} is working. Latency: ${data.latencyMs}ms`,
- { modelId, latencyMs: data.latencyMs }
- )
- );
- setModelTestStatus((prev) => ({ ...prev, [modelId]: "ok" }));
- } else {
- notify.error(data.error || "Model test failed");
- setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));
- if (handleToggleModelHidden) {
- await handleToggleModelHidden(providerStorageAlias, modelId, true);
- }
- }
- } catch (err) {
- notify.error("Network error testing model");
- setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));
- if (handleToggleModelHidden) {
- await handleToggleModelHidden(providerStorageAlias, modelId, true);
- }
- } finally {
- setTestingModelId(null);
- }
- };
-
- const handleTestAll = async (
- targets: Array<{ modelId: string; fullModel: string }>
- ): Promise<void> => {
- if (testingAll) return;
- if (targets.length === 0) {
- notify.error(providerText(t, "noModelsToTest", "No models to test"));
- return;
- }
- setTestingAll(true);
- setTestProgress({ done: 0, total: targets.length });
-
- let ok = 0;
- let error = 0;
- let hiddenCount = 0;
-
- const CHUNK_SIZE = 3;
- for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
- const chunk = targets.slice(i, i + CHUNK_SIZE);
- await Promise.all(
- chunk.map(async ({ modelId, fullModel }) => {
- try {
- const result: {
- results?: Record<
- string,
- {
- status?: "ok" | "error";
- rateLimited?: boolean;
- isTimeout?: boolean;
- error?: string;
- }
- >;
- } = await fetch("/api/models/test-all", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerId: providerId,
- connectionId: selectedConnection?.id,
- modelIds: [fullModel],
- }),
- }).then((r) => r.json());
-
- const entry = result.results?.[fullModel];
- if (entry?.status === "ok") {
- ok++;
- } else {
- error++;
- if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {
- await handleToggleModelHidden(providerStorageAlias, modelId, true);
- hiddenCount++;
- }
- }
- } catch (e) {
- error++;
- }
- setTestProgress((prev) =>
- prev ? { done: prev.done + 1, total: prev.total } : null
- );
- })
- );
- }
-
- notify.info(
- providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error })
- );
- if (hiddenCount > 0) {
- notify.info(
- providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount })
- );
- }
- setTestingAll(false);
- setTestProgress(null);
- };
-
- const handleToggleSelectOne = useCallback((id: string) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- }, []);
-
- const handleToggleSelectAll = useCallback(() => {
- setSelectedIds((prev) => {
- if (prev.size === connections.length && connections.length > 0) {
- return new Set();
- }
- return new Set(connections.map((c) => (c as { id: string }).id));
- });
- }, [connections]);
-
- const handleBatchDeleteOpenModal = () => {
- if (selectedIds.size === 0) return;
- setBatchDeleteConfirmOpen(true);
- };
-
- const handleBatchDeleteConfirm = async () => {
- setBatchDeleteConfirmOpen(false);
- setBatchDeleting(true);
- try {
- const res = await fetch("/api/providers", {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: Array.from(selectedIds) }),
- });
-
- if (res.ok) {
- setSelectedIds(new Set());
- await fetchConnections();
- notify.success(t("batchDeleteSuccess", { count: selectedIds.size }));
- await fetchProviderModelMeta();
- } else {
- const data = await res.json();
- notify.error(data.error || "Batch delete failed");
- }
- } catch {
- notify.error("Network error during batch delete");
- } finally {
- setBatchDeleting(false);
- }
- };
-
- const handleDelete = useCallback(
- async (connectionId: string) => {
- if (!connectionId) return;
- try {
- const res = await fetch(`/api/providers/${connectionId}`, { method: "DELETE" });
- if (res.ok) {
- notify.success("Connection deleted");
- await fetchConnections();
- await fetchProviderModelMeta();
- } else {
- const data = await res.json().catch(() => ({}));
- const message =
- (typeof data?.error === "string" && data.error) ||
- data?.error?.message ||
- "Failed to delete connection";
- notify.error(message);
- }
- } catch (error) {
- console.error("Error deleting connection:", error);
- notify.error("Failed to delete connection");
- }
- },
- [fetchConnections, fetchProviderModelMeta, notify]
- );
-
- const handleBatchSetActive = async (isActive: boolean) => {
- if (selectedIds.size === 0 || batchUpdating) return;
- setBatchUpdating(isActive ? "activate" : "deactivate");
- try {
- const res = await fetch("/api/providers", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: Array.from(selectedIds), isActive }),
- });
-
- if (res.ok) {
- const data = await res.json();
- await fetchConnections();
- notify.success(
- isActive
- ? t("batchActivateSuccess", { count: data.updated })
- : t("batchDeactivateSuccess", { count: data.updated })
- );
- } else {
- const data = await res.json().catch(() => ({}));
- notify.error(data.error?.message || data.error || "Batch update failed");
- }
- } catch {
- notify.error("Network error during batch update");
- } finally {
- setBatchUpdating(null);
- }
- };
-
- const handleOAuthSuccess = useCallback(() => {
- fetchConnections();
- setShowOAuthModal(false);
- }, [fetchConnections]);
-
- const openApiKeyAddFlow = useCallback(() => {
- if (providerId === "siliconflow") {
- setShowSiliconFlowEndpointModal(true);
- return;
- }
- setShowAddApiKeyModal(true);
- }, [providerId]);
-
- const openPrimaryAddFlow = useCallback(() => {
- if (isOAuth) {
- setShowOAuthModal(true);
- return;
- }
- openApiKeyAddFlow();
- }, [isOAuth, openApiKeyAddFlow]);
-
- // "Adicionar Externo": generate a single-use public link so a third party can
- // complete the Codex device flow in their own browser.
- const openExternalLinkFlow = useCallback(async () => {
- setExternalLinkModalOpen(true);
- setExternalLinkUrl("");
- setExternalLinkToken(null);
- setExternalLinkError(null);
- setExternalLinkLoading(true);
- try {
- const res = await fetch(`/api/oauth/${providerId}/public-link`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
- const data = await res.json().catch(() => ({}));
- if (res.ok && data?.url) {
- setExternalLinkUrl(data.url);
- setExternalLinkToken(data.token || null);
- } else {
- setExternalLinkError(data?.error || "Falha ao gerar o link.");
- }
- } catch {
- setExternalLinkError("Não foi possível contatar o servidor.");
- } finally {
- setExternalLinkLoading(false);
- }
- }, [providerId]);
-
- // While the share popup is open, poll the ticket status so the dashboard can
- // notify + refresh the connections the moment the external visitor finishes.
- useEffect(() => {
- if (!externalLinkModalOpen || !externalLinkToken) return;
- let active = true;
- const interval = setInterval(async () => {
- if (!active) return;
- try {
- const res = await fetch(
- `/api/oauth/${providerId}/public-link-status?token=${encodeURIComponent(externalLinkToken)}`
- );
- const data = await res.json().catch(() => ({}));
- if (!active) return;
- if (data?.status === "completed") {
- active = false;
- clearInterval(interval);
- notify.success("Conta Codex conectada pelo link externo.");
- fetchConnections();
- setExternalLinkModalOpen(false);
- setExternalLinkToken(null);
- } else if (data?.status === "expired") {
- active = false;
- clearInterval(interval);
- setExternalLinkError("O link expirou sem ser concluído.");
- }
- } catch {
- /* transient network error — keep polling */
- }
- }, 3000);
- return () => {
- active = false;
- clearInterval(interval);
- };
- }, [externalLinkModalOpen, externalLinkToken, providerId, notify, fetchConnections]);
-
- const gateConnectionFlow = useCallback(
- (callback: () => void) => {
- if (subscriptionRisk && !riskAcknowledged && !isRiskAcknowledged(providerId)) {
- pendingRiskActionRef.current = callback;
- setShowRiskNoticeModal(true);
- return;
- }
- callback();
- },
- [providerId, riskAcknowledged, subscriptionRisk]
- );
-
- const handleConfirmRiskNotice = useCallback(() => {
- acknowledgeRisk();
- setShowRiskNoticeModal(false);
- const pendingAction = pendingRiskActionRef.current;
- pendingRiskActionRef.current = null;
- pendingAction?.();
- }, [acknowledgeRisk]);
-
- const handleCancelRiskNotice = useCallback(() => {
- pendingRiskActionRef.current = null;
- setShowRiskNoticeModal(false);
- }, []);
-
- const clearCommandCodeAuthTimer = useCallback(() => {
- if (commandCodeAuthTimerRef.current !== null) {
- window.clearTimeout(commandCodeAuthTimerRef.current);
- commandCodeAuthTimerRef.current = null;
- }
- }, []);
-
- useEffect(() => {
- return () => {
- clearCommandCodeAuthTimer();
- commandCodeAuthWindowRef.current?.close?.();
- };
- }, [clearCommandCodeAuthTimer]);
-
- const handleCloseAddApiKeyModal = useCallback(() => {
- clearCommandCodeAuthTimer();
- setSiliconFlowInitialBaseUrl(undefined);
- commandCodeAuthWindowRef.current?.close?.();
- commandCodeAuthWindowRef.current = null;
- setCommandCodeAuthState({
- phase: "idle",
- state: "",
- authUrl: "",
- callbackUrl: "",
- expiresAt: null,
- message: "",
- });
- setShowAddApiKeyModal(false);
- }, [clearCommandCodeAuthTimer]);
-
- const handleCommandCodeAuthApply = useCallback(
- async (state: string, connectionId?: string, name?: string, setDefault?: boolean) => {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "applying",
- message: "Applying browser-approved key…",
- }));
-
- try {
- const res = await fetch("/api/providers/command-code/auth/apply", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ state, connectionId, name, setDefault }),
- });
- const data = await res.json().catch(() => ({}));
-
- if (!res.ok) {
- const errorMessage = data.error || "Failed to apply Command Code auth";
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "error",
- message: errorMessage,
- }));
- notify.error(errorMessage);
- return false;
- }
-
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "applied",
- message: "Command Code connected",
- }));
- commandCodeAuthWindowRef.current?.close?.();
- commandCodeAuthWindowRef.current = null;
- await fetchConnections();
- handleCloseAddApiKeyModal();
- notify.success("Command Code connection added");
- return true;
- } catch (error) {
- console.error("Error applying Command Code auth:", error);
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "error",
- message: "Failed to apply Command Code auth",
- }));
- notify.error("Failed to apply Command Code auth");
- return false;
- }
- },
- [fetchConnections, handleCloseAddApiKeyModal, notify]
- );
-
- const handleStartCommandCodeAuth = useCallback(async () => {
- if (commandCodeAuthState.phase === "starting" || commandCodeAuthState.phase === "polling") {
- return;
- }
-
- clearCommandCodeAuthTimer();
- commandCodeAuthWindowRef.current?.close?.();
-
- const popup = window.open("about:blank", "_blank");
- setCommandCodeAuthState({
- phase: "starting",
- state: "",
- authUrl: "",
- callbackUrl: "",
- expiresAt: null,
- message: "Opening Command Code Studio…",
- });
-
- try {
- const res = await fetch("/api/providers/command-code/auth/start", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- });
- const data = await res.json().catch(() => ({}));
-
- if (!res.ok || !data.state || !data.authUrl) {
- const errorMessage = data.error || "Failed to start Command Code auth";
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "error",
- message: errorMessage,
- }));
- notify.error(errorMessage);
- popup?.close?.();
- return;
- }
-
- setCommandCodeAuthState({
- phase: "polling",
- state: data.state,
- authUrl: data.authUrl,
- callbackUrl: data.callbackUrl || "",
- expiresAt: data.expiresAt || null,
- message: "Open the auth URL, approve access, then paste the returned key/JSON/URL below…",
- });
-
- if (popup) {
- try {
- popup.opener = null;
- } catch {
- // Ignore opener cleanup failures.
- }
- popup.location.href = data.authUrl;
- commandCodeAuthWindowRef.current = popup;
- } else {
- const fallbackPopup = window.open(data.authUrl, "_blank", "noopener,noreferrer");
- if (!fallbackPopup) {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "error",
- message: "Popup blocked. Please allow popups and try Command Code Connect again.",
- }));
- notify.error("Popup blocked. Please allow popups and try Command Code Connect again.");
- return;
- }
- commandCodeAuthWindowRef.current = fallbackPopup;
- }
-
- const deadline = data.expiresAt ? new Date(data.expiresAt).getTime() : Date.now() + 180000;
- const poll = async () => {
- if (Date.now() >= deadline) {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "expired",
- message: "Command Code link expired",
- }));
- commandCodeAuthWindowRef.current?.close?.();
- commandCodeAuthWindowRef.current = null;
- notify.error("Command Code auth expired");
- clearCommandCodeAuthTimer();
- return;
- }
-
- try {
- const statusRes = await fetch(
- `/api/providers/command-code/auth/status?state=${encodeURIComponent(data.state)}`,
- { method: "GET", cache: "no-store" }
- );
- const statusData = await statusRes.json().catch(() => ({}));
- const status = String(statusData.status || statusData.state || statusData.phase || "")
- .toLowerCase()
- .trim();
-
- if (status === "expired") {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "expired",
- message: "Command Code link expired",
- }));
- commandCodeAuthWindowRef.current?.close?.();
- commandCodeAuthWindowRef.current = null;
- notify.error("Command Code auth expired");
- clearCommandCodeAuthTimer();
- return;
- }
-
- if (status === "applied") {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "applied",
- message: "Command Code connected",
- }));
- commandCodeAuthWindowRef.current?.close?.();
- commandCodeAuthWindowRef.current = null;
- await fetchConnections();
- handleCloseAddApiKeyModal();
- notify.success("Command Code connection added");
- clearCommandCodeAuthTimer();
- return;
- }
-
- if (status === "received") {
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "received",
- message: "Browser approved, applying…",
- }));
- clearCommandCodeAuthTimer();
- await handleCommandCodeAuthApply(
- data.state,
- statusData.connectionId,
- statusData.name,
- statusData.setDefault
- );
- return;
- }
- } catch {
- // Keep polling until the contract reports a terminal state or timeout.
- }
-
- commandCodeAuthTimerRef.current = window.setTimeout(poll, 2000);
- };
-
- commandCodeAuthTimerRef.current = window.setTimeout(poll, 1000);
- } catch (error) {
- console.error("Error starting Command Code auth:", error);
- setCommandCodeAuthState((current) => ({
- ...current,
- phase: "error",
- message: "Failed to start Command Code auth",
- }));
- notify.error("Failed to start Command Code auth");
- popup?.close?.();
- commandCodeAuthWindowRef.current = null;
- clearCommandCodeAuthTimer();
- }
- }, [
- clearCommandCodeAuthTimer,
- handleCloseAddApiKeyModal,
- commandCodeAuthState.phase,
- fetchConnections,
- handleCommandCodeAuthApply,
- notify,
- ]);
-
- const handleOpenCommandCodeConnect = useCallback(() => {
- setShowAddApiKeyModal(true);
- void handleStartCommandCodeAuth();
- }, [handleStartCommandCodeAuth]);
-
- const handleSaveApiKey = async (formData) => {
- try {
- const res = await fetch("/api/providers", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider: providerId, ...formData }),
- });
- if (res.ok) {
- const connectionData = await res.json();
- const newConnection = connectionData?.connection;
- await fetchConnections();
- setShowAddApiKeyModal(false);
- setSiliconFlowInitialBaseUrl(undefined);
-
- // Universal: sync models from the provider endpoint on every new connection
- // (was previously Gemini-only). Do NOT re-introduce a providerId guard here.
- if (newConnection?.id) {
- setShowImportModal(true);
- setImportProgress({
- current: 0,
- total: 0,
- phase: "fetching",
- status: t("fetchingModels"),
- logs: [],
- error: "",
- importedCount: 0,
- });
-
- try {
- const syncRes = await fetch(`/api/providers/${newConnection.id}/sync-models`, {
- method: "POST",
- signal: AbortSignal.timeout(30_000), // 30s timeout — model sync shouldn't hang
- });
- const syncData = await syncRes.json();
-
- if (!syncRes.ok || syncData.error) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "error",
- status: t("failedFetchModels"),
- error: syncData.error?.message || syncData.error || t("failedImportModels"),
- }));
- return null;
- }
-
- const syncedCount = syncData.syncedModels || 0;
- const availableCount =
- typeof syncData.availableModelsCount === "number"
- ? syncData.availableModelsCount
- : Array.isArray(syncData.models)
- ? syncData.models.length
- : syncedCount;
- const syncedModelList: Array<{ id: string; name?: string }> = syncData.models || [];
- const logs: string[] = [];
- if (syncedModelList.length > 0) {
- logs.push(`✓ ${availableCount} models available`);
- logs.push("");
- for (const m of syncedModelList) {
- logs.push(` ${m.name || m.id}`);
- }
- }
-
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- status: t("modelsImported", { count: availableCount }),
- total: availableCount,
- current: availableCount,
- importedCount: availableCount,
- logs,
- }));
-
- await fetchProviderModelMeta();
- } catch (syncError) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "error",
- status: t("failedFetchModels"),
- error: String(syncError),
- }));
- }
- }
- return null;
- }
- const data = await res.json().catch(() => ({}));
- const errorMsg = data.error?.message || data.error || t("failedSaveConnection");
- return errorMsg;
- } catch (error) {
- console.log("Error saving connection:", error);
- return t("failedSaveConnectionRetry");
- }
- };
-
- const handleUpdateConnection = async (formData) => {
- try {
- const res = await fetch(`/api/providers/${selectedConnection.id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(formData),
- });
- if (res.ok) {
- await fetchConnections();
- setShowEditModal(false);
- return null;
- }
- const data = await res.json().catch(() => ({}));
- return data.error?.message || data.error || t("failedSaveConnection");
- } catch (error) {
- console.log("Error updating connection:", error);
- return t("failedSaveConnectionRetry");
- }
- };
-
- const handleUpdateConnectionStatus = async (id, isActive) => {
- try {
- const res = await fetch(`/api/providers/${id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ isActive }),
- });
- if (res.ok) {
- setConnections((prev) => prev.map((c) => (c.id === id ? { ...c, isActive } : c)));
- }
- } catch (error) {
- console.log("Error updating connection status:", error);
- }
- };
-
- const handleToggleProxyEnabled = async (connectionId, proxyEnabled) => {
- try {
- const res = await fetch(`/api/providers/${connectionId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ proxyEnabled }),
- });
- if (res.ok) {
- setConnections((prev) =>
- prev.map((c) => (c.id === connectionId ? { ...c, proxyEnabled } : c))
- );
- }
- } catch (error) {
- console.error("Error toggling proxy enabled:", error);
- }
- };
-
- const handleTogglePerKeyProxyEnabled = async (connectionId, perKeyProxyEnabled) => {
- try {
- const res = await fetch(`/api/providers/${connectionId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ perKeyProxyEnabled }),
- });
- if (res.ok) {
- setConnections((prev) =>
- prev.map((c) => (c.id === connectionId ? { ...c, perKeyProxyEnabled } : c))
- );
- }
- } catch (error) {
- console.error("Error toggling per-key proxy enabled:", error);
- }
- };
-
- const handleDistributeProxies = async (tagFilter?: string) => {
- const targetConnections = tagFilter
- ? connections.filter(
- (c: any) =>
- (c.providerSpecificData?.tag as string | undefined)?.trim() === tagFilter
- )
- : connections;
- if (targetConnections.length === 0) return;
- setDistributingProxies(true);
- try {
- const proxiesRes = await fetch("/api/settings/proxies");
- if (!proxiesRes.ok) throw new Error("Failed to fetch proxies");
- const proxiesData = await proxiesRes.json();
- const savedProxies = (proxiesData?.items || []).filter(
- (p: any) => p.status === "active"
- );
- if (savedProxies.length === 0) {
- notify.error("No saved proxies found. Add proxies in Settings → Proxy first.");
- return;
- }
-
- let assigned = 0;
- const sorted = [...targetConnections].sort(
- (a: any, b: any) => (a.priority || 0) - (b.priority || 0)
- );
-
- for (let i = 0; i < sorted.length; i++) {
- const conn = sorted[i] as any;
- const proxy = savedProxies[i % savedProxies.length];
-
- try {
- await fetch("/api/settings/proxies/assignments", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- scope: "account",
- scopeId: conn.id,
- proxyId: null,
- }),
- });
- } catch {
- /* clear old assignment */
- }
-
- const patchRes = await fetch(`/api/providers/${conn.id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ proxyEnabled: true, perKeyProxyEnabled: true }),
- });
-
- if (!patchRes.ok) {
- console.error(`Failed to update connection ${conn.id}`);
- continue;
- }
-
- // Assign new proxy
- const assignRes = await fetch("/api/settings/proxies/assignments", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- scope: "account",
- scopeId: conn.id,
- proxyId: proxy.id,
- }),
- });
-
- if (!assignRes.ok) {
- console.error(`Failed to assign proxy to ${conn.id}`);
- continue;
- }
-
- assigned++;
- }
-
- await fetchConnections();
- const tagLabel = tagFilter ? `"${tagFilter}" ` : "";
- notify.success(
- `Distributed ${assigned} proxy assignment(s) across ${tagLabel}${sorted.length} connection(s).`
- );
- } catch (err) {
- console.error("Error distributing proxies:", err);
- notify.error("Failed to distribute proxies.");
- } finally {
- setDistributingProxies(false);
- }
- };
-
- const handleToggleRateLimit = async (connectionId, enabled) => {
- try {
- const res = await fetch("/api/rate-limits", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ connectionId, enabled }),
- });
- if (res.ok) {
- setConnections((prev) =>
- prev.map((c) => (c.id === connectionId ? { ...c, rateLimitProtection: enabled } : c))
- );
- }
- } catch (error) {
- console.error("Error toggling rate limit:", error);
- }
- };
-
- const handleToggleClaudeExtraUsage = async (connectionId, enabled) => {
- try {
- const target = connections.find((connection) => connection.id === connectionId);
- if (!target) return;
-
- const providerSpecificData =
- target.providerSpecificData && typeof target.providerSpecificData === "object"
- ? target.providerSpecificData
- : {};
-
- const res = await fetch(`/api/providers/${connectionId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerSpecificData: {
- ...providerSpecificData,
- blockExtraUsage: enabled,
- },
- }),
- });
-
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- notify.error(data.error || "Failed to update Claude extra-usage policy");
- return;
- }
-
- setConnections((prev) =>
- prev.map((connection) =>
- connection.id === connectionId
- ? {
- ...connection,
- providerSpecificData: {
- ...(connection.providerSpecificData || {}),
- blockExtraUsage: enabled,
- },
- ...(!enabled && connection.lastErrorSource === "extra_usage"
- ? {
- testStatus: "active",
- lastError: null,
- lastErrorAt: null,
- lastErrorType: null,
- lastErrorSource: null,
- errorCode: null,
- rateLimitedUntil: null,
- }
- : {}),
- }
- : connection
- )
- );
- notify.success(
- enabled
- ? "Claude extra-usage blocking enabled (extra usage will be blocked)"
- : "Claude extra-usage blocking disabled (extra usage is allowed)"
- );
- } catch (error) {
- console.error("Error toggling Claude extra-usage policy:", error);
- notify.error("Failed to update Claude extra-usage policy");
- }
- };
-
- const [cpaProviderEnabled, setCpaProviderEnabled] = useState(false);
-
- // Load upstream proxy config for this provider on mount
- useEffect(() => {
- if (!isCcCompatible) return;
- fetch(`/api/settings`)
- .then((r) => r.json())
- .then((data) => {
- // Check if this provider has CLIProxyAPI routing enabled
- // The upstream_proxy_config is synced via the settings API
- })
- .catch(() => {});
-
- // Also check via direct upstream proxy config lookup
- fetch(`/api/upstream-proxy/${providerId}`)
- .then((r) => {
- if (!r.ok) return null;
- return r.json();
- })
- .then((data) => {
- if (data?.enabled && (data.mode === "cliproxyapi" || data.mode === "fallback")) {
- setCpaProviderEnabled(true);
- }
- })
- .catch(() => {});
- }, [isCcCompatible, providerId]);
-
- const handleToggleCliproxyapiMode = async (_connectionId, enabled) => {
- try {
- // Write to upstream_proxy_config table which resolveExecutorWithProxy reads
- const res = await fetch(`/api/upstream-proxy/${providerId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- mode: enabled ? "cliproxyapi" : "native",
- enabled: enabled,
- }),
- });
-
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- notify.error(data.error || "Failed to update CLIProxyAPI routing");
- return;
- }
-
- setCpaProviderEnabled(enabled);
- notify.success(
- enabled
- ? "Requests now route through CLIProxyAPI (deeper emulation)"
- : "Requests now use native OmniRoute (direct)"
- );
- } catch {
- notify.error("Failed to update CLIProxyAPI routing");
- }
- };
-
- const handleToggleCodexLimit = async (connectionId, field, enabled) => {
- try {
- const target = connections.find((connection) => connection.id === connectionId);
- if (!target) return;
-
- const providerSpecificData =
- target.providerSpecificData && typeof target.providerSpecificData === "object"
- ? target.providerSpecificData
- : {};
- const existingPolicy =
- providerSpecificData.codexLimitPolicy &&
- typeof providerSpecificData.codexLimitPolicy === "object"
- ? providerSpecificData.codexLimitPolicy
- : {};
-
- const nextPolicy = {
- ...normalizeCodexLimitPolicy(existingPolicy),
- [field]: enabled,
- };
-
- const res = await fetch(`/api/providers/${connectionId}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerSpecificData: {
- ...providerSpecificData,
- codexLimitPolicy: nextPolicy,
- },
- }),
- });
-
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- notify.error(data.error || "Failed to update Codex limit policy");
- return;
- }
-
- setConnections((prev) =>
- prev.map((connection) =>
- connection.id === connectionId
- ? {
- ...connection,
- providerSpecificData: {
- ...(connection.providerSpecificData || {}),
- codexLimitPolicy: nextPolicy,
- },
- }
- : connection
- )
- );
- notify.success("Codex limit policy updated");
- } catch (error) {
- console.error("Error toggling Codex quota policy:", error);
- notify.error("Failed to update Codex limit policy");
- }
- };
-
- const handleChangeCodexGlobalServiceMode = async (mode: CodexGlobalServiceMode) => {
- if (savingCodexGlobalServiceMode || !codexSettingsLoaded) return;
- setSavingCodexGlobalServiceMode(true);
- const previousMode = codexGlobalServiceMode;
- setCodexGlobalServiceMode(mode);
- try {
- const tier = mode === "none" ? (previousMode !== "none" ? previousMode : undefined) : mode;
- const res = await fetch("/api/settings", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- codexServiceTier: {
- enabled: mode !== "none",
- ...(tier ? { tier } : {}),
- supportedModels: codexGlobalSupportedModels,
- },
- }),
- });
-
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- setCodexGlobalServiceMode(previousMode);
- notify.error(data.error || "Failed to update Codex service mode");
- return;
- }
-
- notify.success("Codex service mode updated");
- } catch (error) {
- setCodexGlobalServiceMode(previousMode);
- console.error("Error updating Codex service mode:", error);
- notify.error("Failed to update Codex service mode");
- } finally {
- setSavingCodexGlobalServiceMode(false);
- }
- };
-
- const handleRetestConnection = async (connectionId) => {
- if (!connectionId || retestingId) return;
- setRetestingId(connectionId);
- try {
- const res = await fetch(`/api/providers/${connectionId}/test`, { method: "POST" });
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- alert(data.error || t("failedRetestConnection"));
- return;
- }
- await fetchConnections();
- } catch (error) {
- console.error("Error retesting connection:", error);
- } finally {
- setRetestingId(null);
- }
- };
-
- // Shared runner for batch connection tests (all-for-provider or selected IDs)
- const runBatchTest = async (payload: Record<string, unknown>) => {
- setBatchTestResults(null);
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 120_000); // 2min max
- try {
- const res = await fetch("/api/providers/test-batch", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- signal: controller.signal,
- });
- let data: any;
- try {
- data = await res.json();
- } catch {
- data = { error: t("providerTestFailed"), results: [], summary: null };
- }
- setBatchTestResults({
- ...data,
- error: data.error
- ? typeof data.error === "object"
- ? data.error.message || data.error.error || JSON.stringify(data.error)
- : String(data.error)
- : null,
- });
- if (data?.summary) {
- const { passed, failed, total } = data.summary;
- if (failed === 0) notify.success(t("allTestsPassed", { total }));
- else notify.warning(t("testSummary", { passed, failed, total }));
- }
- // Refresh connections to update statuses
- await fetchConnections();
- } catch (error: any) {
- const isAbort = error?.name === "AbortError";
- const msg = isAbort ? t("providerTestTimeout") : t("providerTestFailed");
- setBatchTestResults({ error: msg, results: [], summary: null });
- notify.error(msg);
- } finally {
- clearTimeout(timeoutId);
- }
- };
-
- // Batch test all connections for this provider
- const handleBatchTestAll = async () => {
- if (batchTesting || connections.length === 0) return;
- setBatchTesting(true);
- try {
- await runBatchTest({ mode: "provider", providerId });
- } finally {
- setBatchTesting(false);
- }
- };
-
- // Batch retest only the selected connections
- const handleBatchRetest = async () => {
- if (batchRetesting || selectedIds.size === 0) return;
- setBatchRetesting(true);
- try {
- await runBatchTest({ mode: "selected", connectionIds: Array.from(selectedIds) });
- } finally {
- setBatchRetesting(false);
- }
- };
-
- // T12: Manual token refresh
- const [refreshingId, setRefreshingId] = useState<string | null>(null);
-
- const parseApiErrorMessage = async (res: Response, fallback: string) => {
- const contentType = res.headers.get("content-type") || "";
-
- if (contentType.includes("application/json")) {
- const data = await res.json().catch(() => ({}));
- if (typeof data?.error === "string" && data.error.trim()) {
- return data.error;
- }
- if (data?.error?.message) {
- return data.error.message;
- }
- }
-
- const text = await res.text().catch(() => "");
- return text.trim() || fallback;
- };
-
- const getAttachmentFilename = (res: Response, fallback: string) => {
- const disposition = res.headers.get("content-disposition") || "";
- const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
- if (utf8Match?.[1]) {
- return decodeURIComponent(utf8Match[1]);
- }
-
- const plainMatch = disposition.match(/filename="([^"]+)"/i);
- if (plainMatch?.[1]) {
- return plainMatch[1];
- }
-
- return fallback;
- };
-
- const handleRefreshToken = async (connectionId: string) => {
- if (refreshingId) return;
- setRefreshingId(connectionId);
- try {
- const res = await fetch(`/api/providers/${connectionId}/refresh`, { method: "POST" });
- const data = await res.json().catch(() => ({}));
- if (res.ok && data.success) {
- notify.success(t("tokenRefreshed"));
- await fetchConnections();
- } else {
- notify.error(data.error || t("tokenRefreshFailed"));
- }
- } catch (error) {
- console.error("Error refreshing token:", error);
- notify.error(t("tokenRefreshFailed"));
- } finally {
- setRefreshingId(null);
- }
- };
-
- const handleApplyCodexAuthLocal = async (connectionId: string) => {
- if (applyingCodexAuthId) return;
- setApplyingCodexAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("codexAuthAppliedLocal")
- ? t("codexAuthAppliedLocal")
- : "Codex auth.json applied locally";
- const defaultError =
- typeof t.has === "function" && t.has("codexAuthApplyFailed")
- ? t("codexAuthApplyFailed")
- : "Failed to apply Codex auth.json locally";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/codex-auth/apply-local`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- notify.success(defaultSuccess);
- setApplyCodexModalConnectionId(null);
- } catch (error) {
- console.error("Error applying Codex auth locally:", error);
- notify.error(defaultError);
- } finally {
- setApplyingCodexAuthId(null);
- }
- };
-
- const handleExportCodexAuthFile = async (connectionId: string) => {
- if (exportingCodexAuthId) return;
- setExportingCodexAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("codexAuthExported")
- ? t("codexAuthExported")
- : "Codex auth.json exported";
- const defaultError =
- typeof t.has === "function" && t.has("codexAuthExportFailed")
- ? t("codexAuthExportFailed")
- : "Failed to export Codex auth.json";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/codex-auth/export`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- const blob = await res.blob();
- const filename = getAttachmentFilename(res, "codex-auth.json");
- const objectUrl = window.URL.createObjectURL(blob);
- const link = document.createElement("a");
-
- link.href = objectUrl;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
-
- notify.success(defaultSuccess);
- } catch (error) {
- console.error("Error exporting Codex auth file:", error);
- notify.error(defaultError);
- } finally {
- setExportingCodexAuthId(null);
- }
- };
-
- const handleApplyClaudeAuthLocal = async (connectionId: string) => {
- if (applyingClaudeAuthId) return;
- setApplyingClaudeAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("claudeAuthAppliedLocal")
- ? t("claudeAuthAppliedLocal")
- : "Claude auth applied locally";
- const defaultError =
- typeof t.has === "function" && t.has("claudeAuthApplyFailed")
- ? t("claudeAuthApplyFailed")
- : "Failed to apply Claude auth locally";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/claude-auth/apply-local`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- notify.success(defaultSuccess);
- setApplyClaudeModalConnectionId(null);
- } catch (error) {
- console.error("Error applying Claude auth locally:", error);
- notify.error(defaultError);
- } finally {
- setApplyingClaudeAuthId(null);
- }
- };
-
- const handleExportClaudeAuthFile = async (connectionId: string) => {
- if (exportingClaudeAuthId) return;
- setExportingClaudeAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("claudeAuthExported")
- ? t("claudeAuthExported")
- : "Claude auth file exported";
- const defaultError =
- typeof t.has === "function" && t.has("claudeAuthExportFailed")
- ? t("claudeAuthExportFailed")
- : "Failed to export Claude auth file";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/claude-auth/export`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- const blob = await res.blob();
- const filename = getAttachmentFilename(res, "claude-auth.json");
- const objectUrl = window.URL.createObjectURL(blob);
- const link = document.createElement("a");
-
- link.href = objectUrl;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
-
- notify.success(defaultSuccess);
- } catch (error) {
- console.error("Error exporting Claude auth file:", error);
- notify.error(defaultError);
- } finally {
- setExportingClaudeAuthId(null);
- }
- };
-
- const handleApplyGeminiAuthLocal = async (connectionId: string) => {
- if (applyingGeminiAuthId) return;
- setApplyingGeminiAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("geminiAuthAppliedLocal")
- ? t("geminiAuthAppliedLocal")
- : "Gemini auth applied locally";
- const defaultError =
- typeof t.has === "function" && t.has("geminiAuthApplyFailed")
- ? t("geminiAuthApplyFailed")
- : "Failed to apply Gemini auth locally";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/gemini-cli-auth/apply-local`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- notify.success(defaultSuccess);
- setApplyGeminiModalConnectionId(null);
- } catch (error) {
- console.error("Error applying Gemini auth locally:", error);
- notify.error(defaultError);
- } finally {
- setApplyingGeminiAuthId(null);
- }
- };
-
- const handleExportGeminiAuthFile = async (connectionId: string) => {
- if (exportingGeminiAuthId) return;
- setExportingGeminiAuthId(connectionId);
-
- const defaultSuccess =
- typeof t.has === "function" && t.has("geminiAuthExported")
- ? t("geminiAuthExported")
- : "Gemini auth file exported";
- const defaultError =
- typeof t.has === "function" && t.has("geminiAuthExportFailed")
- ? t("geminiAuthExportFailed")
- : "Failed to export Gemini auth file";
-
- try {
- const res = await fetch(`/api/providers/${connectionId}/gemini-cli-auth/export`, {
- method: "POST",
- });
-
- if (!res.ok) {
- notify.error(await parseApiErrorMessage(res, defaultError));
- return;
- }
-
- const blob = await res.blob();
- const filename = getAttachmentFilename(res, "gemini-auth.json");
- const objectUrl = window.URL.createObjectURL(blob);
- const link = document.createElement("a");
-
- link.href = objectUrl;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 1000);
-
- notify.success(defaultSuccess);
- } catch (error) {
- console.error("Error exporting Gemini auth file:", error);
- notify.error(defaultError);
- } finally {
- setExportingGeminiAuthId(null);
- }
- };
-
- const handleSwapPriority = async (conn1, conn2) => {
- if (!conn1 || !conn2) return;
- try {
- // If they have the same priority, we need to ensure the one moving up
- // gets a lower value than the one moving down.
- // We use a small offset which the backend re-indexing will fix.
- let p1 = conn2.priority;
- let p2 = conn1.priority;
-
- if (p1 === p2) {
- // If moving conn1 "up" (index decreases)
- const isConn1MovingUp = connections.indexOf(conn1) > connections.indexOf(conn2);
- if (isConn1MovingUp) {
- p1 = conn2.priority - 0.5;
- } else {
- p1 = conn2.priority + 0.5;
- }
- }
-
- await Promise.all([
- fetch(`/api/providers/${conn1.id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ priority: p1 }),
- }),
- fetch(`/api/providers/${conn2.id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ priority: p2 }),
- }),
- ]);
- await fetchConnections();
- } catch (error) {
- console.log("Error swapping priority:", error);
- }
- };
-
- const handleImportModels = async () => {
- if (importingModels) return;
- const activeConnection = connections.find((conn) => conn.isActive !== false);
- // #3047 — no-auth providers (e.g. OpenCode Free) have no connection rows;
- // fall back to the provider id so the models route can serve the public
- // catalog instead of the button silently doing nothing.
- if (!activeConnection && !isFreeNoAuth) return;
- const importTargetId = activeConnection?.id ?? providerId;
-
- setImportingModels(true);
- setShowImportModal(true);
- setImportProgress({
- current: 0,
- total: 0,
- phase: "fetching",
- status: t("fetchingModels"),
- logs: [],
- error: "",
- importedCount: 0,
- });
-
- try {
- const res = await fetch(`/api/providers/${importTargetId}/models?refresh=true`);
- const data = await res.json();
- if (!res.ok) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "error",
- status: t("failedFetchModels"),
- error: data.error || t("failedImportModels"),
- }));
- return;
- }
- const fetchedModels = data.models || [];
- if (fetchedModels.length === 0) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- status: t("noModelsFound"),
- logs: [t("noModelsReturnedFromEndpoint")],
- }));
- return;
- }
-
- const existingIds = new Set([
- ...(modelMeta.customModels || []).map((m: any) => m.id),
- ...models.map((m: any) => m.id),
- ]);
- const newModels = fetchedModels.filter(
- (model: any) => !existingIds.has(model.id || model.name || model.model)
- );
-
- if (newModels.length === 0) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- status: t("allModelsAlreadyImported") || "All models already imported",
- logs: [t("noNewModelsToImport") || "No new models to import"],
- importedCount: 0,
- total: 0,
- current: 0,
- }));
- return;
- }
-
- setImportProgress((prev) => ({
- ...prev,
- phase: "importing",
- total: newModels.length,
- current: 0,
- status: t("importingModelsProgress", { current: 0, total: newModels.length }),
- logs: [
- t("foundModelsStartingImport", { count: newModels.length }),
- ...(newModels.length < fetchedModels.length
- ? [
- t("skippingExistingModels", { count: fetchedModels.length - newModels.length }) ||
- `Skipping ${fetchedModels.length - newModels.length} existing models`,
- ]
- : []),
- ],
- }));
-
- let importedCount = 0;
- for (let i = 0; i < newModels.length; i++) {
- const model = newModels[i];
- const modelId = model.id || model.name || model.model;
- if (!modelId) continue;
- const parts = modelId.split("/");
- const baseAlias = parts[parts.length - 1];
-
- setImportProgress((prev) => ({
- ...prev,
- current: i + 1,
- status: t("importingModelsProgress", { current: i + 1, total: newModels.length }),
- logs: [...prev.logs, t("importingModelById", { modelId })],
- }));
-
- // Save as imported (default) model in the DB
- await fetch("/api/provider-models", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: providerId,
- modelId,
- modelName: model.name || modelId,
- source: "imported",
- ...(typeof model.apiFormat === "string" ? { apiFormat: model.apiFormat } : {}),
- ...(Array.isArray(model.supportedEndpoints)
- ? { supportedEndpoints: model.supportedEndpoints }
- : {}),
- }),
- });
- // Also create an alias for routing
- if (!modelAliases[baseAlias]) {
- await handleSetAlias(modelId, baseAlias, providerStorageAlias);
- }
- importedCount += 1;
- }
-
- await fetchAliases();
-
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- current: newModels.length,
- status:
- importedCount > 0
- ? t("importSuccessCount", { count: importedCount })
- : t("noNewModelsAddedExisting"),
- logs: [
- ...prev.logs,
- importedCount > 0
- ? t("importDoneCount", { count: importedCount })
- : t("noNewModelsAdded"),
- ],
- importedCount,
- }));
-
- // Auto-reload after success
- if (importedCount > 0) {
- setTimeout(() => {
- window.location.reload();
- }, 2000);
- }
- } catch (error) {
- console.log("Error importing models:", error);
- setImportProgress((prev) => ({
- ...prev,
- phase: "error",
- status: t("importFailed"),
- error: error instanceof Error ? error.message : t("unexpectedErrorOccurred"),
- }));
- } finally {
- setImportingModels(false);
- }
- };
-
- // Shared import handler for CompatibleModelsSection
- const handleCompatibleImportWithProgress = async (connectionId: string) => {
- setShowImportModal(true);
- setImportProgress({
- current: 0,
- total: 0,
- phase: "fetching",
- status: t("fetchingModels"),
- logs: [],
- error: "",
- importedCount: 0,
- });
-
- try {
- const response = await fetch(`/api/providers/${connectionId}/sync-models?mode=import`, {
- method: "POST",
- signal: AbortSignal.timeout(60_000),
- });
- const data = await response.json();
- if (!response.ok) {
- throw new Error(data.error || t("failedImportModels"));
- }
-
- const importedModels = Array.isArray(data.importedModels) ? data.importedModels : [];
- const importedCount =
- typeof data.importedCount === "number" ? data.importedCount : importedModels.length;
- const changedCount =
- typeof data.importedChanges?.total === "number"
- ? data.importedChanges.total
- : importedCount;
- const totalChangedCount =
- changedCount +
- (typeof data.customModelChanges?.total === "number" ? data.customModelChanges.total : 0);
-
- if (importedModels.length === 0) {
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- status:
- importedCount > 0
- ? t("importSuccessCount", { count: importedCount })
- : t("noNewModelsAdded"),
- logs: [
- importedCount > 0
- ? t("importDoneCount", { count: importedCount })
- : t("noNewModelsAdded"),
- ],
- importedCount,
- }));
- if (totalChangedCount > 0) {
- setTimeout(() => {
- window.location.reload();
- }, 2000);
- }
- return;
- }
-
- setImportProgress((prev) => ({
- ...prev,
- phase: "done",
- total: importedModels.length,
- current: importedModels.length,
- status:
- importedCount > 0
- ? t("importSuccessCount", { count: importedCount })
- : t("noNewModelsAdded"),
- logs: [
- t("foundModelsStartingImport", { count: importedModels.length }),
- ...importedModels.map((model: any) =>
- t("importingModelById", { modelId: model.id || model.name || model.model })
- ),
- importedCount > 0
- ? t("importDoneCount", { count: importedCount })
- : t("noNewModelsAdded"),
- ],
- importedCount,
- }));
-
- if (totalChangedCount > 0) {
- setTimeout(() => {
- window.location.reload();
- }, 2000);
- }
- } catch (error) {
- console.log("Error importing models:", error);
- setImportProgress((prev) => ({
- ...prev,
- phase: "error",
- status: t("importFailed"),
- error: error instanceof Error ? error.message : t("unexpectedErrorOccurred"),
- }));
- }
- };
-
- const canImportModels = isFreeNoAuth || connections.some((conn) => conn.isActive !== false);
-
- // Auto-sync toggle state: read from first active connection's providerSpecificData
- const autoSyncConnection = connections.find((conn: any) => conn.isActive !== false);
- const isAutoSyncEnabled = !!(autoSyncConnection as any)?.providerSpecificData?.autoSync;
- const [togglingAutoSync, setTogglingAutoSync] = useState(false);
-
- const handleToggleAutoSync = async () => {
- if (!autoSyncConnection || togglingAutoSync) return;
- setTogglingAutoSync(true);
- try {
- const newValue = !isAutoSyncEnabled;
- await fetch(`/api/providers/${(autoSyncConnection as any).id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerSpecificData: { autoSync: newValue },
- }),
- });
- await fetchConnections();
- notify[newValue ? "success" : "info"](
- newValue ? t("autoSyncEnabled") : t("autoSyncDisabled")
- );
- } catch (error) {
- console.log("Error toggling auto-sync:", error);
- notify.error(t("autoSyncToggleFailed"));
- } finally {
- setTogglingAutoSync(false);
- }
- };
-
- const [clearingModels, setClearingModels] = useState(false);
- const providerAliasEntries = useMemo(
- () =>
- Object.entries(modelAliases).filter(
- ([, model]) =>
- typeof model === "string" && model.startsWith(`${providerStorageAlias}/`)
- ),
- [modelAliases, providerStorageAlias]
- );
-
- const handleClearAllModels = async () => {
- if (clearingModels) return;
- if (!confirm(t("clearAllModelsConfirm"))) return;
- setClearingModels(true);
- try {
- const res = await fetch(
- `/api/provider-models?provider=${encodeURIComponent(providerStorageAlias)}&all=true`,
- { method: "DELETE" }
- );
- if (res.ok) {
- // Also delete all aliases that belong to this provider
- await Promise.all(
- providerAliasEntries.map(([alias]) =>
- fetch(`/api/models/alias?alias=${encodeURIComponent(alias)}`, {
- method: "DELETE",
- }).catch(() => {})
- )
- );
- await fetchProviderModelMeta();
- await fetchAliases();
- notify.success(t("clearAllModelsSuccess"));
- } else {
- notify.error(t("clearAllModelsFailed"));
- }
- } catch {
- notify.error(t("clearAllModelsFailed"));
- } finally {
- setClearingModels(false);
- }
- };
-
- const customMap = useMemo(() => buildCompatMap(modelMeta.customModels), [modelMeta.customModels]);
- const overrideMap = useMemo(
- () => buildCompatMap(modelMeta.modelCompatOverrides),
- [modelMeta.modelCompatOverrides]
- );
- const compatibleFallbackModels = useMemo(
- () => getCompatibleFallbackModels(providerId, modelMeta.customModels),
- [providerId, modelMeta.customModels]
- );
-
- const effectiveModelNormalize = (modelId: string, protocol = MODEL_COMPAT_PROTOCOL_KEYS[0]) =>
- effectiveNormalizeForProtocol(modelId, protocol, customMap, overrideMap);
-
- const effectiveModelPreserveDeveloper = (
- modelId: string,
- protocol = MODEL_COMPAT_PROTOCOL_KEYS[0]
- ) => effectivePreserveForProtocol(modelId, protocol, customMap, overrideMap);
-
- const effectiveModelHidden = useCallback(
- (modelId: string) => isModelHidden(modelId, customMap, overrideMap),
- [customMap, overrideMap]
- );
-
- const getUpstreamHeadersRecordForModel = useCallback(
- (modelId: string, protocol: string) =>
- effectiveUpstreamHeadersForProtocol(modelId, protocol, customMap, overrideMap),
- [customMap, overrideMap]
- );
-
- const saveModelCompatFlags = async (modelId: string, patch: ModelCompatSavePatch) => {
- setCompatSavingModelId(modelId);
- try {
- const c = customMap.get(modelId) as Record<string, unknown> | undefined;
- let body: Record<string, unknown>;
- const onlyCompatByProtocol =
- patch.compatByProtocol &&
- patch.normalizeToolCallId === undefined &&
- patch.preserveOpenAIDeveloperRole === undefined &&
- !("upstreamHeaders" in patch);
-
- if (c) {
- if (onlyCompatByProtocol) {
- body = {
- provider: providerId,
- modelId,
- compatByProtocol: patch.compatByProtocol,
- };
- } else {
- body = {
- provider: providerId,
- modelId,
- modelName: (c.name as string) || modelId,
- source: (c.source as string) || "manual",
- apiFormat: (c.apiFormat as string) || "chat-completions",
- supportedEndpoints:
- Array.isArray(c.supportedEndpoints) && (c.supportedEndpoints as unknown[]).length
- ? c.supportedEndpoints
- : ["chat"],
- normalizeToolCallId:
- patch.normalizeToolCallId !== undefined
- ? patch.normalizeToolCallId
- : Boolean(c.normalizeToolCallId),
- preserveOpenAIDeveloperRole:
- patch.preserveOpenAIDeveloperRole !== undefined
- ? patch.preserveOpenAIDeveloperRole
- : Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole")
- ? Boolean(c.preserveOpenAIDeveloperRole)
- : true,
- };
- if (patch.compatByProtocol) body.compatByProtocol = patch.compatByProtocol;
- }
- } else {
- body = { provider: providerId, modelId, ...patch };
- }
- const res = await fetch("/api/provider-models", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- if (!res.ok) {
- const detail = await formatProviderModelsErrorResponse(res);
- notify.error(
- detail ? `${t("failedSaveCustomModel")} — ${detail}` : t("failedSaveCustomModel")
- );
- return;
- }
- } catch {
- notify.error(t("failedSaveCustomModel"));
- return;
- } finally {
- setCompatSavingModelId(null);
- }
- try {
- await fetchProviderModelMeta();
- } catch {
- /* refresh failure is non-critical — data was already saved */
- }
- };
-
- const handleToggleModelHidden = async (
- providerKey: string,
- modelId: string,
- hidden: boolean
- ): Promise<void> => {
- setTogglingModelId(modelId);
- try {
- const res = await fetch(
- `/api/provider-models?provider=${encodeURIComponent(providerKey)}&modelId=${encodeURIComponent(modelId)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ isHidden: hidden }),
- }
- );
- if (!res.ok) {
- const detail = await res.text().catch(() => "");
- notify.error(detail || t("failedSaveCustomModel"));
- return;
- }
- await Promise.all([fetchProviderModelMeta().catch(() => {}), fetchAliases().catch(() => {})]);
- } catch {
- notify.error(t("failedSaveCustomModel"));
- } finally {
- setTogglingModelId(null);
- }
- };
-
- const handleBulkToggleModelHidden = async (
- providerKey: string,
- modelIds: string[],
- hidden: boolean
- ): Promise<void> => {
- if (modelIds.length === 0) return;
- setBulkVisibilityAction(hidden ? "deselect" : "select");
- try {
- const res = await fetch(`/api/provider-models?provider=${encodeURIComponent(providerKey)}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ isHidden: hidden, modelIds }),
- });
- if (!res.ok) {
- const detail = await res.text().catch(() => "");
- notify.error(detail || t("failedSaveCustomModel"));
- return;
- }
- await Promise.all([fetchProviderModelMeta().catch(() => {}), fetchAliases().catch(() => {})]);
- } catch {
- notify.error(t("failedSaveCustomModel"));
- } finally {
- setBulkVisibilityAction(null);
- }
- };
-
- const renderModelsSection = () => {
- const autoSyncToggle = compatibleSupportsModelImport && canImportModels && (
- <button
- onClick={handleToggleAutoSync}
- disabled={togglingAutoSync}
- className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border bg-transparent cursor-pointer text-[12px] disabled:opacity-50 disabled:cursor-not-allowed"
- title={t("autoSyncTooltip")}
- >
- <span
- className="material-symbols-outlined text-[16px]"
- style={{ color: isAutoSyncEnabled ? "#22c55e" : "var(--color-text-muted)" }}
- >
- {isAutoSyncEnabled ? "toggle_on" : "toggle_off"}
- </span>
- <span className="text-text-main">{t("autoSync")}</span>
- </button>
- );
-
- const clearAllButton = (modelMeta.customModels.length > 0 ||
- providerAliasEntries.length > 0) && (
- <button
- onClick={handleClearAllModels}
- disabled={clearingModels}
- className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-red-300 dark:border-red-800 bg-transparent cursor-pointer text-[12px] text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 disabled:cursor-not-allowed"
- title={t("clearAllModels")}
- >
- <span className="material-symbols-outlined text-[16px]">delete_sweep</span>
- <span>{t("clearAllModels")}</span>
- </button>
- );
-
- if (isManagedAvailableModelsProvider) {
- const description =
- providerId === "openrouter"
- ? t("openRouterAnyModelHint")
- : isCcCompatible
- ? t("ccCompatibleModelsDescription")
- : t("compatibleModelsDescription", {
- type: isAnthropicCompatible ? t("anthropic") : t("openai"),
- });
- const inputLabel = providerId === "openrouter" ? t("modelIdFromOpenRouter") : t("modelId");
- const inputPlaceholder =
- providerId === "openrouter"
- ? t("openRouterModelPlaceholder")
- : isCcCompatible
- ? "claude-sonnet-4-6"
- : isAnthropicCompatible
- ? t("anthropicCompatibleModelPlaceholder")
- : t("openaiCompatibleModelPlaceholder");
-
- return (
- <div>
- <div className="flex items-center gap-2 mb-4">
- {autoSyncToggle}
- {clearAllButton}
- </div>
- <CompatibleModelsSection
- providerStorageAlias={providerStorageAlias}
- providerDisplayAlias={providerDisplayAlias}
- modelAliases={modelAliases}
- availableModels={syncedAvailableModels}
- customModels={modelMeta.customModels}
- fallbackModels={compatibleFallbackModels}
- description={description}
- inputLabel={inputLabel}
- inputPlaceholder={inputPlaceholder}
- copied={copied}
- onCopy={copy}
- onSetAlias={handleSetAlias}
- onDeleteAlias={handleDeleteAlias}
- connections={connections}
- isAnthropic={isAnthropicProtocolCompatible}
- onImportWithProgress={handleCompatibleImportWithProgress}
- t={t}
- effectiveModelNormalize={effectiveModelNormalize}
- effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
- getUpstreamHeadersRecord={getUpstreamHeadersRecordForModel}
- saveModelCompatFlags={saveModelCompatFlags}
- compatSavingModelId={compatSavingModelId}
- onModelsChanged={fetchProviderModelMeta}
- allowImport={compatibleSupportsModelImport}
- isModelHidden={effectiveModelHidden}
- onToggleHidden={(modelId, hidden) =>
- handleToggleModelHidden(providerStorageAlias, modelId, hidden)
- }
- onBulkToggleHidden={(modelIds, hidden) =>
- handleBulkToggleModelHidden(providerStorageAlias, modelIds, hidden)
- }
- bulkTogglePending={bulkVisibilityAction !== null}
- togglingModelId={togglingModelId}
- onTestModel={onTestModel}
- modelTestStatus={modelTestStatus}
- testingModelId={testingModelId}
- onTestAll={handleTestAll}
- testingAll={testingAll}
- testProgress={testProgress}
- autoHideFailed={autoHideFailed}
- onAutoHideFailedChange={setAutoHideFailed}
- />
- </div>
- );
- }
-
- if (providerInfo.passthroughModels) {
- const passthroughDescription =
- providerId === "openrouter"
- ? t("openRouterAnyModelHint")
- : providerId === "bedrock"
- ? t("bedrockModelsDescription")
- : t("passthroughModelsDescription", { provider: providerInfo?.name || providerId });
- const passthroughInputLabel =
- providerId === "openrouter" ? t("modelIdFromOpenRouter") : t("modelId");
- const passthroughInputPlaceholder =
- providerId === "openrouter"
- ? t("openRouterModelPlaceholder")
- : providerId === "bedrock"
- ? t("bedrockModelPlaceholder")
- : t("openaiCompatibleModelPlaceholder");
-
- return (
- <div>
- <div className="flex items-center gap-2 mb-4">
- <Button
- size="sm"
- variant="secondary"
- icon="download"
- onClick={handleImportModels}
- disabled={!canImportModels || importingModels}
- >
- {importingModels ? t("importingModels") : t("importFromModels")}
- </Button>
- {autoSyncToggle}
- {clearAllButton}
- {!canImportModels && (
- <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>
- )}
- </div>
- <PassthroughModelsSection
- providerAlias={providerAlias}
- modelAliases={modelAliases}
- availableModels={syncedAvailableModels}
- customModels={modelMeta.customModels}
- description={passthroughDescription}
- inputLabel={passthroughInputLabel}
- inputPlaceholder={passthroughInputPlaceholder}
- copied={copied}
- onCopy={copy}
- onSetAlias={handleSetAlias}
- onDeleteAlias={handleDeleteAlias}
- t={t}
- effectiveModelNormalize={effectiveModelNormalize}
- effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
- getUpstreamHeadersRecord={getUpstreamHeadersRecordForModel}
- saveModelCompatFlags={saveModelCompatFlags}
- compatSavingModelId={compatSavingModelId}
- isModelHidden={effectiveModelHidden}
- onToggleHidden={(modelId, hidden) =>
- handleToggleModelHidden(providerStorageAlias, modelId, hidden)
- }
- onBulkToggleHidden={(modelIds, hidden) =>
- handleBulkToggleModelHidden(providerStorageAlias, modelIds, hidden)
- }
- bulkTogglePending={bulkVisibilityAction !== null}
- togglingModelId={togglingModelId}
- onTestModel={onTestModel}
- modelTestStatus={modelTestStatus}
- testingModelId={testingModelId}
- providerId={providerId}
- connectionId={selectedConnection?.id ?? ""}
- />
- </div>
- );
- }
-
- const importButton = (
- <div className="flex items-center gap-2 mb-4">
- <Button
- size="sm"
- variant="secondary"
- icon="download"
- onClick={handleImportModels}
- disabled={!canImportModels || importingModels}
- >
- {importingModels ? t("importingModels") : t("importFromModels")}
- </Button>
- {autoSyncToggle}
- {!canImportModels && (
- <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>
- )}
- </div>
- );
-
- if (models.length === 0) {
- return (
- <div>
- {importButton}
- <p className="text-sm text-text-muted">{t("noModelsConfigured")}</p>
- </div>
- );
- }
- const modelsWithVisibility = models.map((model) => ({
- ...model,
- isHidden: effectiveModelHidden(model.id),
- }));
- const filteredModels = modelsWithVisibility.filter((model) => {
- const matchesQuery = matchesModelCatalogQuery(modelFilter, {
- modelId: model.id,
- modelName: model.name,
- source: model.source,
- });
- const matchesVisibility =
- visibilityFilter === "all"
- ? true
- : visibilityFilter === "visible"
- ? !model.isHidden
- : model.isHidden;
- return matchesQuery && matchesVisibility;
- });
- const activeCount = modelsWithVisibility.filter((m) => !m.isHidden).length;
- const hiddenFilteredCount = filteredModels.filter((m) => m.isHidden).length;
- const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;
- const testAllTargets = filteredModels
- .filter((m) => !m.isHidden)
- .map((m) => ({ modelId: m.id, fullModel: `${providerDisplayAlias}/${m.id}` }));
- return (
- <div>
- {importButton}
- {modelsWithVisibility.length > 0 && (
- <ModelVisibilityToolbar
- t={t}
- filterValue={modelFilter}
- onFilterChange={setModelFilter}
- activeCount={activeCount}
- totalCount={modelsWithVisibility.length}
- onSelectAll={() =>
- handleBulkToggleModelHidden(
- providerId,
- filteredModels.map((model) => model.id),
- false
- )
- }
- onDeselectAll={() =>
- handleBulkToggleModelHidden(
- providerId,
- filteredModels.map((model) => model.id),
- true
- )
- }
- selectAllDisabled={hiddenFilteredCount === 0 || bulkVisibilityAction !== null}
- deselectAllDisabled={visibleFilteredCount === 0 || bulkVisibilityAction !== null}
- onTestAll={() => handleTestAll(testAllTargets)}
- testingAll={testingAll}
- testProgress={testProgress}
- visibilityFilter={visibilityFilter}
- onVisibilityFilterChange={setVisibilityFilter}
- autoHideFailed={autoHideFailed}
- onAutoHideFailedChange={setAutoHideFailed}
- />
- )}
- <div className="flex flex-wrap gap-3">
- {filteredModels.map((model) => {
- return (
- <ModelRow
- key={model.id}
- model={model}
- fullModel={`${providerDisplayAlias}/${model.id}`}
- provider={providerId}
- copied={copied}
- onCopy={copy}
- t={t}
- showDeveloperToggle
- effectiveModelNormalize={effectiveModelNormalize}
- effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
- getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecordForModel(model.id, p)}
- saveModelCompatFlags={saveModelCompatFlags}
- compatDisabled={compatSavingModelId === model.id}
- onToggleHidden={(modelId, hidden) =>
- handleToggleModelHidden(providerId, modelId, hidden)
- }
- togglingHidden={togglingModelId === model.id}
- onTestModel={onTestModel}
- testStatus={modelTestStatus[model.id] || null}
- testingModel={testingModelId === model.id}
- />
- );
- })}
- {filteredModels.length === 0 && modelFilter && (
- <p className="text-sm text-text-muted py-2">
- {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
- filter: modelFilter,
- })}
- </p>
- )}
- </div>
- </div>
- );
- };
-
- if (loading) {
- return (
- <div className="flex flex-col gap-8">
- <CardSkeleton />
- <CardSkeleton />
- </div>
- );
- }
-
- if (!providerInfo) {
- return (
- <div className="text-center py-20">
- <p className="text-text-muted">{t("providerNotFound")}</p>
- <Link href="/dashboard/providers" className="text-primary mt-4 inline-block">
- {t("backToProviders")}
- </Link>
- </div>
- );
- }
-
- // OpenAI/Anthropic compatible providers use their specialized pseudo-provider icons.
- const getHeaderIconProviderId = () => {
- if (isOpenAICompatible && providerInfo.apiType) {
- return providerInfo.apiType === "responses" ? "oai-r" : "oai-cc";
- }
- if (isAnthropicProtocolCompatible) {
- return "anthropic-m";
- }
- return providerInfo.id;
- };
-
- return (
- <div className="flex flex-col gap-8">
- {/* Header */}
- <div>
- <Link
- href="/dashboard/providers"
- className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4"
- >
- <span className="material-symbols-outlined text-lg">arrow_back</span>
- {t("backToProviders")}
- </Link>
- <div className="flex items-center gap-4">
- <div
- className="rounded-lg flex items-center justify-center"
- style={{ backgroundColor: `${providerInfo.color}15` }}
- >
- <ProviderIcon providerId={getHeaderIconProviderId()} size={48} type="color" />
- </div>
- <div>
- {providerInfo.website ? (
- <a
- href={providerInfo.website}
- target="_blank"
- rel="noopener noreferrer"
- className="text-3xl font-semibold tracking-tight hover:underline inline-flex items-center gap-2"
- style={{ color: providerInfo.color }}
- >
- {providerInfo.name}
- <span className="material-symbols-outlined text-lg opacity-60">open_in_new</span>
- </a>
- ) : (
- <h1 className="text-3xl font-semibold tracking-tight">{providerInfo.name}</h1>
- )}
- <div className="flex items-center gap-2">
- <p className="text-text-muted">
- {t("connectionCountLabel", { count: connections.length })}
- </p>
- <EmailPrivacyToggle size="md" />
- {providerId === "adapta-web" && (
- <button
- onClick={() => setShowTutorialModal(true)}
- className="text-sm font-medium underline underline-offset-2 opacity-70 hover:opacity-100 transition-opacity"
- style={{ color: providerInfo.color }}
- >
- Tutorial
- </button>
- )}
- </div>
- </div>
- </div>
- </div>
-
- {providerId === "zed" && (
- <>
- <Card>
- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div className="flex-1 min-w-0">
- <h2 className="text-lg font-semibold flex items-center gap-2">
- <span className="material-symbols-outlined text-[20px]">download</span>
- Import from Zed Keychain
- </h2>
- <p className="text-sm text-text-muted mt-1">
- Discover AI provider credentials (OpenAI, Anthropic, Google, Mistral, xAI) that
- Zed IDE stored in the OS keychain and import them as connections. Requires Zed IDE
- installed on this machine.
- </p>
- </div>
- <Button
- size="sm"
- variant="secondary"
- icon={importingZed ? "sync" : "download"}
- onClick={handleZedImport}
- disabled={importingZed}
- >
- {importingZed ? "Importing…" : "Import from Zed"}
- </Button>
- </div>
- </Card>
- <Card>
- <div className="flex flex-col gap-3">
- <button
- className="flex items-center justify-between w-full text-left"
- onClick={() => setShowZedManual((v) => !v)}
- >
- <h2 className="text-lg font-semibold flex items-center gap-2">
- <span className="material-symbols-outlined text-[20px]">edit</span>
- Manual Token Import
- </h2>
- <span className="material-symbols-outlined text-[18px] text-text-muted">
- {showZedManual ? "expand_less" : "expand_more"}
- </span>
- </button>
- {showZedManual && (
- <div className="flex flex-col gap-3 mt-1">
- <p className="text-sm text-text-muted">
- Use this when OmniRoute runs in Docker or the keychain is unavailable. Paste the
- API key that Zed stored under{" "}
- <code className="font-mono text-xs">~/.config/zed/settings.json</code> or copy
- it from the Zed AI settings panel.
- </p>
- <div className="flex gap-2 flex-col sm:flex-row">
- <select
- className="input input-sm"
- value={zedManualProvider}
- onChange={(e) => setZedManualProvider(e.target.value)}
- >
- <option value="openai">OpenAI</option>
- <option value="anthropic">Anthropic</option>
- <option value="google">Google</option>
- <option value="mistral">Mistral</option>
- <option value="xai">xAI</option>
- <option value="openrouter">OpenRouter</option>
- <option value="deepseek">DeepSeek</option>
- </select>
- <input
- type="password"
- className="input input-sm flex-1"
- placeholder="Paste API key…"
- value={zedManualToken}
- onChange={(e) => setZedManualToken(e.target.value)}
- />
- <Button
- size="sm"
- variant="secondary"
- icon={importingZedManual ? "sync" : "upload"}
- onClick={handleZedManualImport}
- disabled={importingZedManual || !zedManualToken.trim()}
- >
- {importingZedManual ? "Saving…" : "Import"}
- </Button>
- </div>
- </div>
- )}
- </div>
- </Card>
- </>
- )}
-
- {isCompatible && providerNode && (
- <Card>
- <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div>
- <h2 className="text-lg font-semibold">
- {isCcCompatible
- ? t("ccCompatibleDetailsTitle")
- : isAnthropicCompatible
- ? t("anthropicCompatibleDetails")
- : t("openaiCompatibleDetails")}
- </h2>
- <p className="text-sm text-text-muted">
- {getApiLabel()} · {(providerNode.baseUrl || "").replace(/\/$/, "")}/{getApiPath()}
- </p>
- </div>
- <div className="flex flex-wrap items-center gap-2">
- <Button size="sm" icon="add" onClick={() => gateConnectionFlow(openApiKeyAddFlow)}>
- {t("add")}
- </Button>
- <Button
- size="sm"
- variant="secondary"
- icon="edit"
- onClick={() => setShowEditNodeModal(true)}
- >
- {t("edit")}
- </Button>
- <Button
- size="sm"
- variant="secondary"
- icon="delete"
- onClick={async () => {
- if (
- !confirm(
- t("deleteCompatibleNodeConfirm", {
- type: isCcCompatible
- ? t("ccCompatibleLabel")
- : isAnthropicCompatible
- ? t("anthropic")
- : t("openai"),
- })
- )
- )
- return;
- try {
- const res = await fetch(`/api/provider-nodes/${providerId}`, {
- method: "DELETE",
- });
- if (res.ok) {
- router.push("/dashboard/providers");
- }
- } catch (error) {
- console.error("Error deleting provider node:", error);
- }
- }}
- >
- {t("delete")}
- </Button>
- </div>
- </div>
- {isCcCompatible && (
- <div className="mb-4 rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
- warning
- </span>
- <p>{t("ccCompatibleValidationHint")}</p>
- </div>
- </div>
- )}
- </Card>
- )}
-
- {/* Connections */}
- {!isUpstreamProxyProvider && isFreeNoAuth && <NoAuthProviderCard />}
- {!isUpstreamProxyProvider && !isFreeNoAuth && (
- <Card>
- <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div className="flex min-w-0 flex-wrap items-center gap-2">
- <h2 className="text-lg font-semibold">{t("connections")}</h2>
- {providerId === "codex" && (
- <div
- className="inline-flex items-center gap-2 rounded-lg border border-sky-500/20 bg-sky-500/5 px-2 py-1 text-xs font-medium text-text-muted"
- title={providerText(
- t,
- "providerDetailServiceModeTooltip",
- "Set a global Codex service mode, or leave accounts on their individual service-tier setting."
- )}
- >
- <span>
- {providerText(t, "providerDetailServiceModeLabel", "Global service mode:")}
- </span>
- <select
- value={codexGlobalServiceMode}
- onChange={(event) =>
- handleChangeCodexGlobalServiceMode(
- event.target.value as CodexGlobalServiceMode
- )
- }
- disabled={savingCodexGlobalServiceMode || !codexSettingsLoaded}
- aria-label="Global Codex service mode"
- className="rounded-md border border-border bg-bg px-2 py-1 text-xs text-text-main outline-none transition-colors focus:border-primary disabled:opacity-60"
- >
- {codexGlobalServiceModeOptions.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- {codexSettingsLoadError ? (
- <button
- type="button"
- onClick={() => void loadCodexSettings()}
- className="rounded border border-sky-500/30 px-2 py-0.5 text-[11px] font-medium text-sky-600 hover:bg-sky-500/10 dark:text-sky-300"
- title={codexSettingsLoadError}
- >
- {providerText(t, "retry", "Retry")}
- </button>
- ) : null}
- </div>
- )}
- {/* Provider-level proxy indicator/button */}
- <button
- onClick={() =>
- setProxyTarget({
- level: "provider",
- id: providerId,
- label: providerInfo?.name || providerId,
- })
- }
- className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${
- proxyConfig?.providers?.[providerId]
- ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={
- proxyConfig?.providers?.[providerId]
- ? t("providerProxyTitleConfigured", {
- host: proxyConfig.providers[providerId].host || t("configured"),
- })
- : t("providerProxyConfigureHint")
- }
- >
- <span className="material-symbols-outlined text-[14px]">vpn_lock</span>
- {proxyConfig?.providers?.[providerId]
- ? proxyConfig.providers[providerId].host || t("providerProxy")
- : t("providerProxy")}
- </button>
- </div>
- <div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
- {connections.length > 0 && (
- <button
- onClick={() => handleDistributeProxies()}
- disabled={distributingProxies || batchTesting || !!retestingId}
- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
- distributingProxies
- ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
- : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
- }`}
- title={t("distributeProxies")}
- aria-label={t("distributeProxies")}
- >
- <span className="material-symbols-outlined text-[14px]">
- {distributingProxies ? "sync" : "swap_horiz"}
- </span>
- {distributingProxies ? t("distributing") : t("distributeProxies")}
- </button>
- )}
- {connections.length > 1 && (
- <button
- onClick={handleBatchTestAll}
- disabled={batchTesting || !!retestingId}
- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
- batchTesting
- ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
- : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
- }`}
- title={t("testAll")}
- aria-label={t("testAll")}
- >
- <span className="material-symbols-outlined text-[14px]">
- {batchTesting ? "sync" : "play_arrow"}
- </span>
- {batchTesting ? t("testing") : t("testAll")}
- </button>
- )}
- {!isCompatible ? (
- <>
- {isCommandCode ? (
- <>
- <Button
- size="sm"
- icon="open_in_new"
- loading={
- commandCodeAuthState.phase === "starting" ||
- commandCodeAuthState.phase === "polling" ||
- commandCodeAuthState.phase === "applying"
- }
- onClick={() => gateConnectionFlow(handleOpenCommandCodeConnect)}
- >
- Connect
- </Button>
- <Button
- size="sm"
- variant="secondary"
- icon="add"
- onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
- >
- Manual API key
- </Button>
- </>
- ) : (
- <>
- <Button
- size="sm"
- icon="add"
- onClick={() => gateConnectionFlow(openPrimaryAddFlow)}
- >
- {providerSupportsPat ? "Add PAT" : t("add")}
- </Button>
- {providerId === "qoder" && (
- <Button
- size="sm"
- variant="secondary"
- onClick={() => gateConnectionFlow(() => setShowOAuthModal(true))}
- >
- Experimental OAuth
- </Button>
- )}
- {providerId === "codex" && (
- <Button
- size="sm"
- variant="secondary"
- icon="menu_book"
- onClick={() => setCodexCliGuideOpen(true)}
- >
- Codex CLI Guide
- </Button>
- )}
- {providerId === "codex" && (
- <Button
- size="sm"
- variant="secondary"
- icon="share"
- onClick={() => gateConnectionFlow(openExternalLinkFlow)}
- >
- Adicionar Externo
- </Button>
- )}
- {providerId === "codex" && (
- <Button
- size="sm"
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportCodexModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importCodexAuth")
- ? t("importCodexAuth")
- : "Import auth"}
- </Button>
- )}
- {providerId === "claude" && (
- <Button
- size="sm"
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportClaudeModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importClaudeAuth")
- ? t("importClaudeAuth")
- : "Import auth"}
- </Button>
- )}
- {providerId === "gemini-cli" && (
- <Button
- size="sm"
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportGeminiModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importGeminiAuth")
- ? t("importGeminiAuth")
- : "Import auth"}
- </Button>
- )}
- </>
- )}
- </>
- ) : (
- connections.length === 0 && (
- <Button
- size="sm"
- icon="add"
- onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
- >
- {t("add")}
- </Button>
- )
- )}
- </div>
- </div>
-
- {connections.length === 0 ? (
- <div className="text-center py-12">
- <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
- <span className="material-symbols-outlined text-[32px]">
- {isOAuth ? "lock" : "key"}
- </span>
- </div>
- <p className="text-text-main font-medium mb-1">{t("noConnectionsYet")}</p>
- <p className="text-sm text-text-muted mb-4">{t("addFirstConnectionHint")}</p>
- {!isCompatible && (
- <div className="flex items-center justify-center gap-2">
- {isCommandCode ? (
- <>
- <Button
- icon="open_in_new"
- loading={
- commandCodeAuthState.phase === "starting" ||
- commandCodeAuthState.phase === "polling" ||
- commandCodeAuthState.phase === "applying"
- }
- onClick={() => gateConnectionFlow(handleOpenCommandCodeConnect)}
- >
- Connect
- </Button>
- <Button
- variant="secondary"
- icon="add"
- onClick={() => gateConnectionFlow(openApiKeyAddFlow)}
- >
- Manual API key
- </Button>
- </>
- ) : (
- <>
- <Button icon="add" onClick={() => gateConnectionFlow(openPrimaryAddFlow)}>
- {providerSupportsPat ? "Add PAT" : t("addConnection")}
- </Button>
- {providerId === "qoder" && (
- <Button
- variant="secondary"
- onClick={() => gateConnectionFlow(() => setShowOAuthModal(true))}
- >
- Experimental OAuth
- </Button>
- )}
- {providerId === "codex" && (
- <Button
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportCodexModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importCodexAuth")
- ? t("importCodexAuth")
- : "Import auth"}
- </Button>
- )}
- {providerId === "claude" && (
- <Button
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportClaudeModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importClaudeAuth")
- ? t("importClaudeAuth")
- : "Import auth"}
- </Button>
- )}
- {providerId === "gemini-cli" && (
- <Button
- variant="secondary"
- icon="upload_file"
- onClick={() => gateConnectionFlow(() => setImportGeminiModalOpen(true))}
- >
- {typeof t.has === "function" && t.has("importGeminiAuth")
- ? t("importGeminiAuth")
- : "Import auth"}
- </Button>
- )}
- </>
- )}
- </div>
- )}
- </div>
- ) : (
- (() => {
- const sorted = [...connections].sort((a, b) => (a.priority || 0) - (b.priority || 0));
- const hasAnyTag = sorted.some(
- (c) => c.providerSpecificData?.tag as string | undefined
- );
- const allSelected = selectedIds.size === connections.length && connections.length > 0;
- const someSelected = selectedIds.size > 0 && selectedIds.size < connections.length;
- const bulkBusy = batchUpdating !== null || batchRetesting || batchDeleting;
- const bulkActions = selectedIds.size > 0 && (
- <div className="flex flex-wrap items-center justify-end gap-2">
- <Button
- variant="secondary"
- size="sm"
- icon="toggle_on"
- loading={batchUpdating === "activate"}
- disabled={bulkBusy && batchUpdating !== "activate"}
- onClick={() => handleBatchSetActive(true)}
- >
- {t("batchActivateSelected")}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- icon="toggle_off"
- loading={batchUpdating === "deactivate"}
- disabled={bulkBusy && batchUpdating !== "deactivate"}
- onClick={() => handleBatchSetActive(false)}
- >
- {t("batchDeactivateSelected")}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- icon="play_arrow"
- loading={batchRetesting}
- disabled={(bulkBusy && !batchRetesting) || !!retestingId}
- onClick={handleBatchRetest}
- >
- {t("batchRetestSelected")}
- </Button>
- <Button
- variant="danger"
- size="sm"
- icon="delete"
- loading={batchDeleting}
- disabled={bulkBusy && !batchDeleting}
- onClick={handleBatchDeleteOpenModal}
- >
- {t("batchDeleteSelected", { count: selectedIds.size })}
- </Button>
- </div>
- );
-
- const isHealthy = (c: ConnectionRowConnection): boolean => {
- const s = c.testStatus;
- return c.isActive !== false && (!s || s === "active" || s === "success");
- };
- const STATUS_FILTER_OPTIONS = [
- { value: "all", label: t("filterAll", "All") },
- { value: "active", label: t("filterActive", "Active") },
- { value: "error", label: t("filterError", "Error") },
- { value: "banned", label: t("filterBanned", "Banned") },
- { value: "credits_exhausted", label: t("filterCreditsExhausted", "Credits Exhausted") },
- ];
- const filtered = healthFilter === "all"
- ? sorted
- : sorted.filter((c) => {
- if (healthFilter === "active") return isHealthy(c);
- if (healthFilter === "error") return !isHealthy(c) && c.testStatus !== "banned" && c.testStatus !== "credits_exhausted";
- return c.testStatus === healthFilter;
- });
-
- const totalFilteredPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
- const clampedPage = Math.min(page, totalFilteredPages - 1);
- const pageStart = clampedPage * PAGE_SIZE;
- const pageEnd = pageStart + PAGE_SIZE;
-
- const filterPills = (
- <div className="flex items-center gap-1.5 flex-wrap">
- {STATUS_FILTER_OPTIONS.map((opt) => (
- <button
- key={opt.value}
- onClick={() => {
- setHealthFilter(opt.value);
- setPage(0);
- setSelectedIds(new Set());
- }}
- className={`px-2.5 py-1 text-xs rounded-full font-medium transition-colors ${
- healthFilter === opt.value
- ? "bg-primary text-white"
- : "bg-muted/60 text-text-muted hover:bg-muted"
- }`}
- >
- {opt.label}
- </button>
- ))}
- </div>
- );
-
- const paginationBar = totalFilteredPages > 1 ? (
- <div className="flex items-center justify-between px-3 py-2 border-t border-border">
- <span className="text-xs text-text-muted">
- {pageStart + 1}–{Math.min(pageEnd, filtered.length)} / {filtered.length}
- </span>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- icon="chevron_left"
- disabled={clampedPage === 0}
- onClick={() => setPage((p) => Math.max(0, p - 1))}
- />
- <span className="text-xs text-text-muted min-w-[4rem] text-center">
- {clampedPage + 1} / {totalFilteredPages}
- </span>
- <Button
- variant="ghost"
- size="sm"
- icon="chevron_right"
- disabled={clampedPage >= totalFilteredPages - 1}
- onClick={() => setPage((p) => Math.min(totalFilteredPages - 1, p + 1))}
- />
- </div>
- </div>
- ) : null;
-
- if (!hasAnyTag) {
- const pageConnections = filtered.slice(pageStart, pageEnd);
- const allSelected = pageConnections.length > 0 && pageConnections.every((c) => selectedIds.has(c.id));
- const someSelected = pageConnections.some((c) => selectedIds.has(c.id));
- return (
- <>
- <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
- <div className="flex items-center gap-2 flex-wrap">
- <label className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="checkbox"
- checked={allSelected}
- ref={(el) => {
- if (el) el.indeterminate = someSelected;
- }}
- onChange={() => {
- if (allSelected) {
- const toRemove = new Set(pageConnections.map((c) => c.id));
- setSelectedIds((prev) => {
- const next = new Set(prev);
- for (const id of toRemove) next.delete(id);
- return next;
- });
- } else {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- for (const c of pageConnections) next.add(c.id);
- return next;
- });
- }
- }}
- className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
- />
- <span className="text-sm font-medium text-text-muted">
- {selectedIds.size > 0
- ? providerCountText(
- t,
- "selectedCount",
- selectedIds.size,
- "{count} selected",
- "{count} selected"
- )
- : providerCountText(
- t,
- "accountsCount",
- filtered.length,
- "{count} account",
- "{count} accounts"
- )}
- </span>
- </label>
- {filterPills}
- </div>
-
- {bulkActions}
- </div>
- <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03] border border-t-0 border-border rounded-b-lg overflow-hidden">
- {pageConnections.length === 0 ? (
- <div className="px-3 py-6 text-center text-sm text-text-muted">
- {t("noFilteredConnections", "No connections match the current filter.")}
- </div>
- ) : (
- pageConnections.map((conn, index) => (
- <ConnectionRow
- key={conn.id}
- connection={conn}
- isOAuth={conn.authType === "oauth"}
- isClaude={providerId === "claude"}
- codexGlobalServiceMode={codexGlobalServiceMode}
- isFirst={index === 0}
- isLast={index === pageConnections.length - 1}
- isSelected={selectedIds.has(conn.id)}
- onToggleSelect={() => handleToggleSelectOne(conn.id)}
- onMoveUp={() => handleSwapPriority(conn, sorted[index - 1])}
- onMoveDown={() => handleSwapPriority(conn, sorted[index + 1])}
- onToggleActive={(isActive) =>
- handleUpdateConnectionStatus(conn.id, isActive)
- }
- onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
- onToggleClaudeExtraUsage={(enabled) =>
- handleToggleClaudeExtraUsage(conn.id, enabled)
- }
- isCodex={providerId === "codex"}
- isGeminiCli={providerId === "gemini-cli"}
- isCcCompatible={isCcCompatible}
- cliproxyapiEnabled={cpaProviderEnabled}
- onToggleCliproxyapiMode={(enabled) =>
- handleToggleCliproxyapiMode(conn.id, enabled)
- }
- onToggleCodex5h={(enabled) =>
- handleToggleCodexLimit(conn.id, "use5h", enabled)
- }
- onToggleCodexWeekly={(enabled) =>
- handleToggleCodexLimit(conn.id, "useWeekly", enabled)
- }
- onRetest={() => handleRetestConnection(conn.id)}
- isRetesting={retestingId === conn.id}
- onEdit={() => {
- setSelectedConnection(conn);
- setShowEditModal(true);
- }}
- onDelete={() => handleDelete(conn.id)}
- onReauth={
- conn.authType === "oauth"
- ? () => gateConnectionFlow(() => setShowOAuthModal(true, conn))
- : undefined
- }
- onRefreshToken={
- conn.authType === "oauth"
- ? () => handleRefreshToken(conn.id)
- : undefined
- }
- isRefreshing={refreshingId === conn.id}
- onApplyCodexAuthLocal={
- providerId === "codex"
- ? () => setApplyCodexModalConnectionId(conn.id)
- : undefined
- }
- isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
- onExportCodexAuthFile={
- providerId === "codex"
- ? () => handleExportCodexAuthFile(conn.id)
- : undefined
- }
- isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
- onApplyClaudeAuthLocal={
- providerId === "claude"
- ? () => setApplyClaudeModalConnectionId(conn.id)
- : undefined
- }
- isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
- onExportClaudeAuthFile={
- providerId === "claude"
- ? () => handleExportClaudeAuthFile(conn.id)
- : undefined
- }
- isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
- onApplyGeminiAuthLocal={
- providerId === "gemini-cli"
- ? () => setApplyGeminiModalConnectionId(conn.id)
- : undefined
- }
- isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
- onExportGeminiAuthFile={
- providerId === "gemini-cli"
- ? () => handleExportGeminiAuthFile(conn.id)
- : undefined
- }
- isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
- onProxy={() =>
- setProxyTarget({
- level: "key",
- id: conn.id,
- label: pickDisplayValue(
- [conn.name, conn.email],
- emailsVisible,
- conn.id
- ),
- })
- }
- hasProxy={!!connProxyMap[conn.id]?.proxy}
- proxySource={connProxyMap[conn.id]?.level || null}
- proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
- proxyEnabled={readBooleanToggle(conn.proxyEnabled, true)}
- onToggleProxyEnabled={(enabled) => handleToggleProxyEnabled(conn.id, enabled)}
- perKeyProxyEnabled={readBooleanToggle(conn.perKeyProxyEnabled, false)}
- onTogglePerKeyProxyEnabled={(enabled) => handleTogglePerKeyProxyEnabled(conn.id, enabled)}
- />
- )))
- }
- </div>
- {paginationBar}
- </>
- );
- }
-
- // Build ordered tag groups: untagged first, then alphabetically
- const groupMap = new Map<string, ConnectionRowConnection[]>();
- for (const conn of filtered) {
- const tag = (conn.providerSpecificData?.tag as string | undefined)?.trim() || "";
- if (!groupMap.has(tag)) groupMap.set(tag, []);
- groupMap.get(tag)!.push(conn);
- }
- const groupKeys = Array.from(groupMap.keys()).sort((a, b) => {
- if (a === "") return -1;
- if (b === "") return 1;
- return compareTr(a, b);
- });
-
- return (
- <>
- {selectedIds.size > 0 || connections.length > 0 ? (
- <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
- <div className="flex items-center gap-2 flex-wrap">
- <label className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="checkbox"
- checked={allSelected}
- ref={(el) => {
- if (el) el.indeterminate = someSelected;
- }}
- onChange={handleToggleSelectAll}
- className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
- />
- <span className="text-sm font-medium text-text-muted">
- {selectedIds.size > 0
- ? providerCountText(
- t,
- "selectedCount",
- selectedIds.size,
- "{count} selected",
- "{count} selected"
- )
- : providerCountText(
- t,
- "accountsCount",
- filtered.length,
- "{count} account",
- "{count} accounts"
- )}
- </span>
- </label>
- {filterPills}
- </div>
-
- <div className="flex flex-wrap items-center justify-end gap-2">
- {/* Distribute Proxies lives in the provider toolbar (top action bar);
- removed the duplicate here that rendered simultaneously when nothing
- was selected. Per-tag groups keep their own scoped button. */}
- {bulkActions}
- </div>
- </div>
- ) : null}
- <div className="flex flex-col gap-0 border border-t-0 border-border rounded-b-lg overflow-hidden">
- {groupKeys.map((tag, gi) => {
- const groupConns = groupMap.get(tag)!;
- return (
- <div
- key={tag || "__untagged__"}
- className={
- gi > 0
- ? "border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1"
- : ""
- }
- >
- {tag && (
- <div className="flex items-center gap-2 px-3 pt-2 pb-1">
- <span className="material-symbols-outlined text-[13px] text-text-muted/50">
- label
- </span>
- <span className="text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none">
- {tag}
- </span>
- <div className="flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]" />
- <Button
- variant="ghost"
- size="sm"
- icon="shield"
- loading={distributingProxies}
- onClick={() => handleDistributeProxies(tag)}
- >
- Distribute Proxies
- </Button>
- <span className="text-[10px] text-text-muted/40">
- {groupConns.length}
- </span>
- </div>
- )}
- <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
- {groupConns.map((conn, index) => (
- <ConnectionRow
- key={conn.id}
- connection={conn}
- isOAuth={conn.authType === "oauth"}
- isClaude={providerId === "claude"}
- codexGlobalServiceMode={codexGlobalServiceMode}
- isFirst={gi === 0 && index === 0}
- isLast={
- gi === groupKeys.length - 1 && index === groupConns.length - 1
- }
- isSelected={selectedIds.has(conn.id)}
- onToggleSelect={() => handleToggleSelectOne(conn.id)}
- onMoveUp={() =>
- handleSwapPriority(conn, sorted[sorted.indexOf(conn) - 1])
- }
- onMoveDown={() =>
- handleSwapPriority(conn, sorted[sorted.indexOf(conn) + 1])
- }
- onToggleActive={(isActive) =>
- handleUpdateConnectionStatus(conn.id, isActive)
- }
- onToggleRateLimit={(enabled) =>
- handleToggleRateLimit(conn.id, enabled)
- }
- onToggleClaudeExtraUsage={(enabled) =>
- handleToggleClaudeExtraUsage(conn.id, enabled)
- }
- isCodex={providerId === "codex"}
- isGeminiCli={providerId === "gemini-cli"}
- isCcCompatible={isCcCompatible}
- cliproxyapiEnabled={cpaProviderEnabled}
- onToggleCodex5h={(enabled) =>
- handleToggleCodexLimit(conn.id, "use5h", enabled)
- }
- onToggleCodexWeekly={(enabled) =>
- handleToggleCodexLimit(conn.id, "useWeekly", enabled)
- }
- onRetest={() => handleRetestConnection(conn.id)}
- isRetesting={retestingId === conn.id}
- onEdit={() => {
- setSelectedConnection(conn);
- setShowEditModal(true);
- }}
- onDelete={() => handleDelete(conn.id)}
- onReauth={
- conn.authType === "oauth"
- ? () => gateConnectionFlow(() => setShowOAuthModal(true, conn))
- : undefined
- }
- onRefreshToken={
- conn.authType === "oauth"
- ? () => handleRefreshToken(conn.id)
- : undefined
- }
- isRefreshing={refreshingId === conn.id}
- onApplyCodexAuthLocal={
- providerId === "codex"
- ? () => setApplyCodexModalConnectionId(conn.id)
- : undefined
- }
- isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
- onExportCodexAuthFile={
- providerId === "codex"
- ? () => handleExportCodexAuthFile(conn.id)
- : undefined
- }
- isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
- onApplyClaudeAuthLocal={
- providerId === "claude"
- ? () => setApplyClaudeModalConnectionId(conn.id)
- : undefined
- }
- isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
- onExportClaudeAuthFile={
- providerId === "claude"
- ? () => handleExportClaudeAuthFile(conn.id)
- : undefined
- }
- isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
- onApplyGeminiAuthLocal={
- providerId === "gemini-cli"
- ? () => setApplyGeminiModalConnectionId(conn.id)
- : undefined
- }
- isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
- onExportGeminiAuthFile={
- providerId === "gemini-cli"
- ? () => handleExportGeminiAuthFile(conn.id)
- : undefined
- }
- isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
- onProxy={() =>
- setProxyTarget({
- level: "key",
- id: conn.id,
- label: pickDisplayValue(
- [conn.name, conn.email],
- emailsVisible,
- conn.id
- ),
- })
- }
- hasProxy={!!connProxyMap[conn.id]?.proxy}
- proxySource={connProxyMap[conn.id]?.level || null}
- proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
- proxyEnabled={readBooleanToggle(conn.proxyEnabled, true)}
- onToggleProxyEnabled={(enabled) => handleToggleProxyEnabled(conn.id, enabled)}
- perKeyProxyEnabled={readBooleanToggle(conn.perKeyProxyEnabled, false)}
- onTogglePerKeyProxyEnabled={(enabled) => handleTogglePerKeyProxyEnabled(conn.id, enabled)}
- />
- ))}
- </div>
- </div>
- );
- })}
- </div>
- </>
- );
- })()
- )}
- </Card>
- )}
-
- {isUpstreamProxyProvider && (
- <Card>
- <div className="flex flex-col gap-3">
- <div>
- <h2 className="text-lg font-semibold">
- {providerText(
- t,
- "upstreamProxyManagedTitle",
- "Managed via Upstream Proxy Settings"
- )}
- </h2>
- <p className="text-sm text-text-muted mt-1">
- {providerText(
- t,
- "upstreamProxyManagedDescription",
- "CLIProxyAPI is configured as an upstream proxy layer, not as a direct provider connection. Manage the binary/runtime in CLI Tools and enable proxy routing on each provider via the provider proxy controls."
- )}
- </p>
- </div>
- <div className="flex flex-wrap gap-2">
- <Link
- href="/dashboard/cli-code"
- className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
- >
- <span className="material-symbols-outlined text-base">terminal</span>
- {t("openCliTools")}
- </Link>
- <Link
- href="/dashboard/settings"
- className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
- >
- <span className="material-symbols-outlined text-base">settings</span>
- {t("openSettings")}
- </Link>
- </div>
- </div>
- </Card>
- )}
-
- {/* Models — hidden for search providers (they don't have models) */}
- {!isSearchProvider && !isUpstreamProxyProvider && (
- <Card>
- <h2 className="text-lg font-semibold mb-4">{t("availableModels")}</h2>
- {renderModelsSection()}
-
- {/* Custom Models — available for all providers */}
- <CustomModelsSection
- providerId={providerId}
- providerAlias={providerDisplayAlias}
- copied={copied}
- onCopy={copy}
- onModelsChanged={fetchProviderModelMeta}
- />
- </Card>
- )}
-
- {/* Search provider info */}
- {isSearchProvider && (
- <Card>
- <h2 className="text-lg font-semibold mb-4">{t("searchProvider")}</h2>
- <p className="text-sm text-text-muted">{t("searchProviderDesc")}</p>
- {providerId === "perplexity-search" && (
- <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20">
- <span className="material-symbols-outlined text-sm text-blue-400">link</span>
- <p className="text-xs text-blue-300">{t("perplexitySearchSharedKeyInfo")}</p>
- </div>
- )}
- {providerId === "google-pse-search" && (
- <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
- <span className="material-symbols-outlined text-sm text-amber-300">tune</span>
- <p className="text-xs text-amber-200">{t("googlePseInfo")}</p>
- </div>
- )}
- {providerId === "searxng-search" && (
- <div className="mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-emerald-500/10 border border-emerald-500/20">
- <span className="material-symbols-outlined text-sm text-emerald-300">dns</span>
- <p className="text-xs text-emerald-200">{t("searxngInfo")}</p>
- </div>
- )}
- </Card>
- )}
-
- {/* Playground panel — rendered for providers that declare serviceKinds */}
- <ProviderPlaygroundPanel providerId={providerId} />
-
- {/* Modals */}
- {showRiskNoticeModal && subscriptionRisk && (
- <RiskNoticeModal
- variant={providerInfo.riskNoticeVariant ?? "oauth"}
- providerId={providerId}
- providerName={providerInfo.name}
- onConfirm={handleConfirmRiskNotice}
- onCancel={handleCancelRiskNotice}
- />
- )}
- {!isUpstreamProxyProvider &&
- (providerId === "kiro" || providerId === "amazon-q" ? (
- <KiroOAuthWrapper
- isOpen={showOAuthModal}
- reauthConnection={reauthConnection}
- providerInfo={{ ...providerInfo, id: providerId }}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ) : providerId === "cursor" ? (
- <CursorAuthModal
- isOpen={showOAuthModal}
- reauthConnection={reauthConnection}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ) : providerId === "trae" ? (
- <TraeAuthModal
- isOpen={showOAuthModal}
- reauthConnection={reauthConnection}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ) : (
- <OAuthModal
- isOpen={showOAuthModal}
- reauthConnection={reauthConnection}
- provider={providerId}
- providerInfo={providerInfo}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ))}
- {providerId === "siliconflow" && (
- <SiliconFlowEndpointModal
- isOpen={showSiliconFlowEndpointModal}
- onSelect={(baseUrl) => {
- setSiliconFlowInitialBaseUrl(baseUrl);
- setShowSiliconFlowEndpointModal(false);
- setShowAddApiKeyModal(true);
- }}
- onClose={() => {
- setShowSiliconFlowEndpointModal(false);
- setSiliconFlowInitialBaseUrl(undefined);
- }}
- />
- )}
- {!isUpstreamProxyProvider && (
- <AddApiKeyModal
- isOpen={showAddApiKeyModal}
- provider={providerId}
- providerName={providerInfo.name}
- initialBaseUrl={siliconFlowInitialBaseUrl}
- isCompatible={isCompatible}
- isAnthropic={isAnthropicProtocolCompatible}
- isCcCompatible={isCcCompatible}
- isCommandCode={isCommandCode}
- commandCodeAuthState={commandCodeAuthState}
- onStartCommandCodeAuth={handleStartCommandCodeAuth}
- onSave={handleSaveApiKey}
- onClose={handleCloseAddApiKeyModal}
- />
- )}
- <ConfirmModal
- isOpen={batchDeleteConfirmOpen}
- onClose={() => setBatchDeleteConfirmOpen(false)}
- onConfirm={handleBatchDeleteConfirm}
- title={t("batchDeleteConfirmTitle", "Delete connections")}
- message={t("batchDeleteConfirm", { count: selectedIds.size })}
- confirmText={t("batchDeleteConfirmButton", "Delete")}
- cancelText={t("cancel", "Cancel")}
- loading={batchDeleting}
- />
- {providerId === "codex" && applyCodexModalConnectionId && (
- <ApplyCodexAuthModal
- key={applyCodexModalConnectionId}
- connectionId={applyCodexModalConnectionId}
- inProgress={!!applyingCodexAuthId}
- onConfirm={handleApplyCodexAuthLocal}
- onClose={() => setApplyCodexModalConnectionId(null)}
- />
- )}
- {!isUpstreamProxyProvider && (
- <EditConnectionModal
- isOpen={showEditModal}
- connection={selectedConnection}
- onSave={handleUpdateConnection}
- onClose={() => setShowEditModal(false)}
- />
- )}
- {!isUpstreamProxyProvider && isCompatible && (
- <EditCompatibleNodeModal
- isOpen={showEditNodeModal}
- node={providerNode}
- onSave={handleUpdateNode}
- onClose={() => setShowEditNodeModal(false)}
- isAnthropic={isAnthropicProtocolCompatible}
- isCcCompatible={isCcCompatible}
- />
- )}
- {/* Codex CLI Guide Modal */}
- <CodexCliGuideModal
- isOpen={codexCliGuideOpen}
- onClose={() => setCodexCliGuideOpen(false)}
- />
- {/* Codex Import Auth Modal */}
- {providerId === "codex" && importCodexModalOpen && (
- <ImportCodexAuthModal
- key="import-codex-modal"
- onClose={() => setImportCodexModalOpen(false)}
- onSuccess={() => {
- setImportCodexModalOpen(false);
- void fetchConnections();
- }}
- />
- )}
- {providerId === "codex" && externalLinkModalOpen && (
- <Modal
- isOpen={externalLinkModalOpen}
- onClose={() => setExternalLinkModalOpen(false)}
- title="Adicionar Externo — link do Codex"
- >
- <div className="space-y-4">
- <p className="text-sm text-text-muted">
- Compartilhe este link com quem vai autenticar a conta do Codex. A pessoa abre a
- página, faz o login da OpenAI no próprio navegador e a conexão é cadastrada aqui.
- Uso único, expira em 15 minutos.
- </p>
- {externalLinkLoading ? (
- <p className="text-sm text-text-muted">Gerando link…</p>
- ) : externalLinkError ? (
- <p className="text-sm text-red-500">{externalLinkError}</p>
- ) : externalLinkUrl ? (
- <>
- <div className="rounded-lg border border-border bg-bg-base p-3 break-all text-sm text-text-main">
- {externalLinkUrl}
- </div>
- <div className="flex gap-2">
- <Button
- className="flex-1"
- icon="open_in_new"
- onClick={() => window.open(externalLinkUrl, "_blank", "noopener")}
- >
- Abrir
- </Button>
- <Button
- variant="secondary"
- icon="content_copy"
- onClick={() => externalLinkCopy(externalLinkUrl, "extlink")}
- >
- {externalLinkCopied === "extlink" ? "Copiado" : "Copiar"}
- </Button>
- </div>
- <p className="flex items-center gap-2 text-xs text-text-muted">
- <span className="material-symbols-outlined animate-spin text-[16px]">sync</span>
- Aguardando a autenticação no navegador da pessoa… esta janela atualiza sozinha.
- </p>
- </>
- ) : null}
- </div>
- </Modal>
- )}
- {/* Claude Apply Auth Modal */}
- {providerId === "claude" && applyClaudeModalConnectionId && (
- <ApplyClaudeAuthModal
- key={applyClaudeModalConnectionId}
- connectionId={applyClaudeModalConnectionId}
- inProgress={!!applyingClaudeAuthId}
- onConfirm={handleApplyClaudeAuthLocal}
- onClose={() => setApplyClaudeModalConnectionId(null)}
- />
- )}
- {/* Claude Import Auth Modal */}
- {providerId === "claude" && importClaudeModalOpen && (
- <ImportClaudeAuthModal
- key="import-claude-modal"
- onClose={() => setImportClaudeModalOpen(false)}
- onSuccess={() => {
- setImportClaudeModalOpen(false);
- void fetchConnections();
- }}
- />
- )}
- {/* Gemini Apply Auth Modal */}
- {providerId === "gemini-cli" && applyGeminiModalConnectionId && (
- <ApplyGeminiAuthModal
- key={applyGeminiModalConnectionId}
- connectionId={applyGeminiModalConnectionId}
- inProgress={!!applyingGeminiAuthId}
- onConfirm={handleApplyGeminiAuthLocal}
- onClose={() => setApplyGeminiModalConnectionId(null)}
- />
- )}
- {/* Gemini Import Auth Modal */}
- {providerId === "gemini-cli" && importGeminiModalOpen && (
- <ImportGeminiAuthModal
- key="import-gemini-modal"
- onClose={() => setImportGeminiModalOpen(false)}
- onSuccess={() => {
- setImportGeminiModalOpen(false);
- void fetchConnections();
- }}
- />
- )}
- {/* Batch Test Results Modal */}
- {batchTestResults && (
- <div
- className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh]"
- onClick={() => setBatchTestResults(null)}
- >
- <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
- <div
- className="relative bg-bg-primary border border-border rounded-xl w-full max-w-[600px] max-h-[80vh] overflow-y-auto shadow-2xl"
- onClick={(e) => e.stopPropagation()}
- >
- <div className="sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-bg-primary/95 backdrop-blur-sm rounded-t-xl">
- <h3 className="font-semibold">{t("testResults")}</h3>
- <button
- onClick={() => setBatchTestResults(null)}
- className="p-1 rounded-lg hover:bg-bg-subtle text-text-muted hover:text-text-primary transition-colors"
- aria-label={t("close")}
- >
- <span className="material-symbols-outlined text-lg">close</span>
- </button>
- </div>
- <div className="p-5">
- {batchTestResults.error &&
- (!batchTestResults.results || batchTestResults.results.length === 0) ? (
- <div className="text-center py-6">
- <span className="material-symbols-outlined text-red-500 text-[32px] mb-2 block">
- error
- </span>
- <p className="text-sm text-red-400">{String(batchTestResults.error)}</p>
- </div>
- ) : (
- <div className="flex flex-col gap-3">
- {batchTestResults.summary && (
- <div className="flex items-center gap-3 text-xs mb-1">
- <span className="text-text-muted">{providerInfo?.name || providerId}</span>
- <span className="px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium">
- {t("passedCount", { count: batchTestResults.summary.passed })}
- </span>
- {batchTestResults.summary.failed > 0 && (
- <span className="px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium">
- {t("failedCount", { count: batchTestResults.summary.failed })}
- </span>
- )}
- <span className="text-text-muted ml-auto">
- {t("testedCount", { count: batchTestResults.summary.total })}
- </span>
- </div>
- )}
- {(batchTestResults.results || []).map((r: any, i: number) => (
- <div
- key={r.connectionId || i}
- className="flex items-center gap-2 text-xs px-3 py-2 rounded-lg bg-black/[0.03] dark:bg-white/[0.03]"
- >
- <span
- className={`material-symbols-outlined text-[16px] ${
- r.valid ? "text-emerald-500" : "text-red-500"
- }`}
- >
- {r.valid ? "check_circle" : "error"}
- </span>
- <div className="flex-1 min-w-0">
- <span className="font-medium">
- {pickDisplayValue([r.connectionName], emailsVisible, r.connectionName)}
- </span>
- </div>
- {r.latencyMs !== undefined && (
- <span className="text-text-muted font-mono tabular-nums">
- {t("millisecondsAbbr", { value: r.latencyMs })}
- </span>
- )}
- <span
- className={`text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${
- r.valid
- ? "bg-emerald-500/15 text-emerald-400"
- : "bg-red-500/15 text-red-400"
- }`}
- >
- {r.valid ? t("okShort") : r.diagnosis?.type || t("errorShort")}
- </span>
- </div>
- ))}
- {(!batchTestResults.results || batchTestResults.results.length === 0) && (
- <div className="text-center py-4 text-text-muted text-sm">
- {t("noActiveConnectionsInGroup")}
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- {/* Proxy Config Modal */}
- {proxyTarget && (
- <ProxyConfigModal
- isOpen={!!proxyTarget}
- onClose={() => setProxyTarget(null)}
- level={proxyTarget.level}
- levelId={proxyTarget.id}
- levelLabel={proxyTarget.label}
- onSaved={() => {
- void fetchProxyConfig();
- void loadConnProxies(connections);
- }}
- />
- )}
- {/* Import Progress Modal */}
- <Modal
- isOpen={showImportModal}
- onClose={() => {
- if (importProgress.phase === "done" || importProgress.phase === "error") {
- setShowImportModal(false);
- }
- }}
- title={t("importingModelsTitle")}
- size="md"
- closeOnOverlay={false}
- showCloseButton={importProgress.phase === "done" || importProgress.phase === "error"}
- >
- <div className="flex flex-col gap-4">
- {/* Status text */}
- <div className="flex items-center gap-3">
- {importProgress.phase === "fetching" && (
- <span className="material-symbols-outlined text-primary animate-spin">
- progress_activity
- </span>
- )}
- {importProgress.phase === "importing" && (
- <span className="material-symbols-outlined text-primary animate-spin">
- progress_activity
- </span>
- )}
- {importProgress.phase === "done" && (
- <span className="material-symbols-outlined text-green-500">check_circle</span>
- )}
- {importProgress.phase === "error" && (
- <span className="material-symbols-outlined text-red-500">error</span>
- )}
- <span className="text-sm font-medium text-text-main">{importProgress.status}</span>
- </div>
-
- {/* Progress bar */}
- {(importProgress.phase === "importing" || importProgress.phase === "done") &&
- importProgress.total > 0 && (
- <div className="w-full">
- <div className="flex items-center justify-between mb-1">
- <span className="text-xs text-text-muted">
- {importProgress.current} / {importProgress.total}
- </span>
- <span className="text-xs text-text-muted">
- {Math.round((importProgress.current / importProgress.total) * 100)}%
- </span>
- </div>
- <div className="w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden">
- <div
- className="h-full rounded-full transition-all duration-300 ease-out"
- style={{
- width: `${(importProgress.current / importProgress.total) * 100}%`,
- background:
- importProgress.phase === "done"
- ? "linear-gradient(90deg, #22c55e, #16a34a)"
- : "linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))",
- }}
- />
- </div>
- </div>
- )}
-
- {/* Fetching indeterminate bar */}
- {importProgress.phase === "fetching" && (
- <div className="w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden">
- <div
- className="h-full rounded-full animate-pulse"
- style={{
- width: "60%",
- background:
- "linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))",
- }}
- />
- </div>
- )}
-
- {/* Error message */}
- {importProgress.phase === "error" && importProgress.error && (
- <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
- <p className="text-sm text-red-400">{importProgress.error}</p>
- </div>
- )}
-
- {/* Log list */}
- {importProgress.logs.length > 0 && (
- <div className="max-h-48 overflow-y-auto rounded-lg bg-black/5 dark:bg-white/5 p-3 border border-black/5 dark:border-white/5">
- <div className="flex flex-col gap-1">
- {importProgress.logs.map((log, i) => (
- <p
- key={i}
- className={`text-xs font-mono ${
- typeof log === "string" && log.startsWith("✓")
- ? "text-green-500 font-semibold"
- : "text-text-muted"
- }`}
- >
- {log}
- </p>
- ))}
- </div>
- </div>
- )}
-
- {/* Close button */}
- {importProgress.phase === "done" && (
- <div className="flex justify-center">
- <button
- onClick={() => setShowImportModal(false)}
- className="px-4 py-2 text-sm font-medium rounded-lg bg-primary text-white hover:opacity-90 transition-opacity"
- >
- {t("close")}
- </button>
- </div>
- )}
- </div>
- </Modal>
-
- {/* Adapta Web — Tutorial Modal */}
- {providerId === "adapta-web" && (
- <Modal
- isOpen={showTutorialModal}
- onClose={() => setShowTutorialModal(false)}
- title="Como conectar o Adapta Web"
- size="md"
- >
- <div className="flex flex-col gap-5 text-sm">
- <p className="text-text-muted">
- O Adapta usa autenticação via Clerk. O token{" "}
- <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> é um JWT
- de longa duração que permite renovar sessões automaticamente.
- </p>
-
- <ol className="flex flex-col gap-4 list-none">
- <li className="flex gap-3">
- <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
- 1
- </span>
- <div>
- <p className="font-medium">Acesse o chat do Adapta</p>
- <p className="text-text-muted mt-0.5">
- Abra{" "}
- <a
- href="https://agent.adapta.one/agentic-chat"
- target="_blank"
- rel="noopener noreferrer"
- className="underline text-primary"
- >
- agent.adapta.one/agentic-chat
- </a>{" "}
- e faça login com sua conta Gold ou Business.
- </p>
- </div>
- </li>
-
- <li className="flex gap-3">
- <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
- 2
- </span>
- <div>
- <p className="font-medium">Abra o DevTools</p>
- <p className="text-text-muted mt-0.5">
- Pressione{" "}
- <kbd className="bg-surface-2 px-1.5 py-0.5 rounded text-xs font-mono">F12</kbd>{" "}
- ou{" "}
- <kbd className="bg-surface-2 px-1.5 py-0.5 rounded text-xs font-mono">
- Cmd+Option+I
- </kbd>{" "}
- para abrir as Ferramentas do Desenvolvedor.
- </p>
- </div>
- </li>
-
- <li className="flex gap-3">
- <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
- 3
- </span>
- <div>
- <p className="font-medium">Vá em Application → Cookies</p>
- <p className="text-text-muted mt-0.5">
- Na aba <strong>Application</strong> (Chrome/Edge) ou <strong>Storage</strong>{" "}
- (Firefox), expanda <strong>Cookies</strong> e clique em{" "}
- <code className="bg-surface-2 px-1 rounded font-mono text-xs">
- .clerk.agent.adapta.one
- </code>
- .
- </p>
- </div>
- </li>
-
- <li className="flex gap-3">
- <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
- 4
- </span>
- <div>
- <p className="font-medium">
- Copie o valor do cookie{" "}
- <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code>
- </p>
- <p className="text-text-muted mt-0.5">
- Localize o cookie chamado{" "}
- <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> na
- lista. Clique nele e copie o conteúdo da coluna <strong>Value</strong> — começa
- com <code className="bg-surface-2 px-1 rounded font-mono text-xs">eyJ…</code>.
- </p>
- </div>
- </li>
-
- <li className="flex gap-3">
- <span className="flex-none w-6 h-6 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center">
- 5
- </span>
- <div>
- <p className="font-medium">Cole aqui e salve</p>
- <p className="text-text-muted mt-0.5">
- Clique em <strong>Add Connection</strong>, cole o valor do{" "}
- <code className="bg-surface-2 px-1 rounded font-mono text-xs">__client</code> no
- campo de API Key e salve. O OmniRoute renovará a sessão automaticamente.
- </p>
- </div>
- </li>
- </ol>
-
- <div
- className="rounded-lg p-3 text-xs text-text-muted"
- style={{ backgroundColor: "rgba(110,58,211,0.08)", borderLeft: "3px solid #6E3AD3" }}
- >
- <strong>Dica:</strong> O cookie <code className="font-mono">__client</code> tem
- validade longa (meses). Só será necessário renová-lo se você sair da conta ou o Adapta
- invalidar a sessão.
- </div>
- </div>
- </Modal>
- )}
- </div>
- );
-}
-
-function ModelRow({
- model,
- fullModel,
- provider,
- copied,
- onCopy,
- t,
- showDeveloperToggle = true,
- effectiveModelNormalize,
- effectiveModelPreserveDeveloper,
- getUpstreamHeadersRecord,
- saveModelCompatFlags,
- compatDisabled,
- onToggleHidden,
- togglingHidden,
- onTestModel,
- testStatus,
- testingModel,
-}: ModelRowProps) {
- const isHidden = Boolean(model.isHidden);
- return (
- <div
- className={`flex min-w-[220px] max-w-md items-center gap-2 rounded-lg border border-border px-3 py-2 hover:bg-sidebar/50 transition-opacity ${
- isHidden ? "opacity-50" : ""
- }`}
- >
- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
- <span
- className="material-symbols-outlined shrink-0 text-base"
- style={{ color: isHidden ? "var(--color-text-muted)" : undefined }}
- >
- smart_toy
- </span>
- <code className="rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted">
- {fullModel}
- </code>
- <ModelSourceBadge source={model.source} />
- <button
- onClick={() => onCopy(fullModel, `model-${model.id}`)}
- className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary"
- title={t("copyModel")}
- >
- <span className="material-symbols-outlined text-sm">
- {copied === `model-${model.id}` ? "check" : "content_copy"}
- </span>
- </button>
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {onTestModel && (
- <button
- onClick={() => onTestModel(model.id, fullModel)}
- disabled={testingModel}
- className={`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}`}
- title={
- testingModel
- ? t("testingModel")
- : testStatus === "ok"
- ? "OK"
- : testStatus === "error"
- ? "Error"
- : t("testModel")
- }
- >
- {testingModel ? (
- <span className="material-symbols-outlined text-sm animate-spin">
- progress_activity
- </span>
- ) : testStatus === "ok" ? (
- <span className="material-symbols-outlined text-sm">check_circle</span>
- ) : testStatus === "error" ? (
- <span className="material-symbols-outlined text-sm">error</span>
- ) : (
- <span className="material-symbols-outlined text-sm">play_circle</span>
- )}
- </button>
- )}
- {onToggleHidden && (
- <button
- onClick={() => onToggleHidden(model.id, !isHidden)}
- disabled={togglingHidden}
- className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary disabled:opacity-40 disabled:cursor-not-allowed"
- title={
- isHidden
- ? providerText(t, "showModel", "Show model")
- : providerText(t, "hideModel", "Hide model")
- }
- >
- <span className="material-symbols-outlined text-sm">
- {isHidden ? "visibility_off" : "visibility"}
- </span>
- </button>
- )}
- <ModelCompatPopover
- t={t}
- effectiveModelNormalize={(p) => effectiveModelNormalize(model.id, p)}
- effectiveModelPreserveDeveloper={(p) => effectiveModelPreserveDeveloper(model.id, p)}
- getUpstreamHeadersRecord={getUpstreamHeadersRecord}
- onCompatPatch={(protocol, payload) =>
- saveModelCompatFlags(model.id, { compatByProtocol: { [protocol]: payload } })
- }
- showDeveloperToggle={showDeveloperToggle}
- disabled={compatDisabled}
- />
- </div>
- </div>
- );
-}
-
-function ModelVisibilityToolbar({
- t,
- filterValue,
- onFilterChange,
- activeCount,
- totalCount,
- onSelectAll,
- onDeselectAll,
- selectAllDisabled,
- deselectAllDisabled,
- onTestAll,
- testingAll,
- testProgress,
- visibilityFilter,
- onVisibilityFilterChange,
- autoHideFailed,
- onAutoHideFailedChange,
-}: {
- t: ((key: string, values?: Record<string, unknown>) => string) & {
- has?: (key: string) => boolean;
- };
- filterValue: string;
- onFilterChange: (value: string) => void;
- activeCount: number;
- totalCount: number;
- onSelectAll: () => void;
- onDeselectAll: () => void;
- selectAllDisabled?: boolean;
- deselectAllDisabled?: boolean;
- onTestAll?: () => void;
- testingAll?: boolean;
- testProgress?: { done: number; total: number } | null;
- visibilityFilter?: "all" | "visible" | "hidden";
- onVisibilityFilterChange?: (filter: "all" | "visible" | "hidden") => void;
- autoHideFailed?: boolean;
- onAutoHideFailedChange?: (v: boolean) => void;
-}) {
- return (
- <div className="mb-3 flex flex-wrap items-center gap-2">
- <div className="relative min-w-[220px] flex-1">
- <span className="material-symbols-outlined pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[15px] text-text-muted">
- search
- </span>
- <input
- type="text"
- value={filterValue}
- onChange={(e) => onFilterChange(e.target.value)}
- placeholder={providerText(t, "filterModels", "Filter models…")}
- className="w-full rounded-lg border border-border bg-sidebar/50 py-1.5 pl-7 pr-3 text-xs text-text-main placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
- />
- </div>
- {visibilityFilter !== undefined && onVisibilityFilterChange && (
- <div className="flex items-center gap-1 rounded-lg border border-border bg-sidebar/50 p-0.5">
- {(["all", "visible", "hidden"] as const).map((f) => (
- <button
- key={f}
- onClick={() => onVisibilityFilterChange(f)}
- className={`rounded px-2 py-1 text-xs ${
- visibilityFilter === f
- ? "bg-primary text-primary-foreground"
- : "text-text-muted hover:text-text-main"
- }`}
- >
- {f === "all"
- ? providerText(t, "showAllModels", "All")
- : f === "visible"
- ? providerText(t, "showVisibleOnly", "Visible")
- : providerText(t, "showHiddenOnly", "Hidden")}
- </button>
- ))}
- </div>
- )}
- {onAutoHideFailedChange && (
- <label className="flex items-center gap-1.5 text-xs text-text-muted">
- <input
- type="checkbox"
- checked={autoHideFailed ?? false}
- onChange={(e) => onAutoHideFailedChange(e.target.checked)}
- className="rounded border-border bg-sidebar"
- />
- {providerText(t, "hideFailedAuto", "Auto-hide failed")}
- </label>
- )}
- {onTestAll && (
- <button
- onClick={onTestAll}
- disabled={testingAll}
- className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
- title={providerText(t, "testAllModels", "Test all")}
- >
- <span className="material-symbols-outlined text-[16px]">
- {testingAll ? "progress_activity" : "science"}
- </span>
- <span>
- {testingAll && testProgress
- ? providerText(t, "testingAllModels", "Testing {done}/{total}", testProgress)
- : providerText(t, "testAllModels", "Test all")}
- </span>
- </button>
- )}
- <button
- onClick={onSelectAll}
- disabled={selectAllDisabled}
- className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
- title={providerText(t, "showAllModels", "Show all")}
- >
- <span className="material-symbols-outlined text-[16px]">visibility</span>
- <span>{providerText(t, "showAllModels", "Show all")}</span>
- </button>
- <button
- onClick={onDeselectAll}
- disabled={deselectAllDisabled}
- className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"
- title={providerText(t, "hideAllModels", "Hide all")}
- >
- <span className="material-symbols-outlined text-[16px]">visibility_off</span>
- <span>{providerText(t, "hideAllModels", "Hide all")}</span>
- </button>
- </div>
- );
-}
-
-function PassthroughModelsSection({
- providerAlias,
- modelAliases,
- availableModels = [],
- customModels = [],
- description,
- inputLabel,
- inputPlaceholder,
- copied,
- onCopy,
- onSetAlias,
- onDeleteAlias,
- t,
- effectiveModelNormalize,
- effectiveModelPreserveDeveloper,
- getUpstreamHeadersRecord,
- saveModelCompatFlags,
- compatSavingModelId,
- isModelHidden,
- onToggleHidden,
- onBulkToggleHidden,
- bulkTogglePending,
- togglingModelId,
- onTestModel,
- modelTestStatus,
- testingModelId,
- providerId,
- connectionId,
-}: PassthroughModelsSectionProps) {
- const [newModel, setNewModel] = useState("");
- const [adding, setAdding] = useState(false);
- const [modelFilter, setModelFilter] = useState("");
- const [testingAll, setTestingAll] = useState(false);
- const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);
- const [autoHideFailed, setAutoHideFailed] = useState(true);
- const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
- const notify = useNotificationStore();
- const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);
-
- const handleTestAll = async () => {
- const modelsToTest = filteredModels.filter((m) => !m.isHidden);
- if (modelsToTest.length === 0) {
- notify.error(providerText(t, "noModelsToTest", "No models to test"));
- return;
- }
- setTestingAll(true);
- setTestProgress({ done: 0, total: modelsToTest.length });
-
- let ok = 0;
- let error = 0;
- let hiddenCount = 0;
-
- for (const model of modelsToTest) {
- try {
- const result: {
- results?: Record<
- string,
- {
- status?: "ok" | "error";
- rateLimited?: boolean;
- isTimeout?: boolean;
- error?: string;
- }
- >;
- } = await fetch("/api/models/test-all", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- providerId,
- connectionId,
- modelIds: [model.modelId],
- }),
- }).then((r) => r.json());
-
- const entry = result.results?.[model.modelId];
- if (entry?.status === "ok") {
- ok++;
- } else {
- error++;
- if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {
- await onToggleHidden(model.modelId, true);
- hiddenCount++;
- }
- }
- } catch (e) {
- error++;
- }
- setTestProgress((prev) => (prev ? { done: prev.done + 1, total: prev.total } : null));
- }
-
- notify.info(providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error }));
- if (hiddenCount > 0) {
- notify.info(providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount }));
- }
- setTestingAll(false);
- setTestProgress(null);
- };
-
- const providerAliases = useMemo(
- () =>
- Object.entries(modelAliases).filter(([, model]: [string, any]) =>
- (model as string).startsWith(`${providerAlias}/`)
- ),
- [modelAliases, providerAlias]
- );
-
- const allModels = useMemo(() => {
- const prefix = `${providerAlias}/`;
- const aliasByModelId = new Map<string, string>();
- const fullModelByModelId = new Map<string, string>();
- const rows: Array<{
- modelId: string;
- fullModel: string;
- alias: string | null;
- displayName: string;
- source: string;
- isFree: boolean;
- isHidden: boolean;
- }> = [];
- const seenModelIds = new Set<string>();
-
- for (const [alias, fullModel] of providerAliases) {
- const fmStr = fullModel as string;
- const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
- aliasByModelId.set(modelId, alias as string);
- fullModelByModelId.set(modelId, fmStr);
- }
-
- const addModel = (model: CompatModelRow, source: string) => {
- if (!model?.id || seenModelIds.has(model.id)) return;
- const fullModel = fullModelByModelId.get(model.id) || `${providerAlias}/${model.id}`;
- rows.push({
- modelId: model.id,
- fullModel,
- alias: aliasByModelId.get(model.id) || null,
- displayName: model.name || model.id,
- source,
- isFree:
- Boolean((model as any).free) ||
- model.id.endsWith(":free") ||
- /\bgr[aá]tis\b|\bfree\b/i.test(model.name || ""),
- isHidden: isModelHidden(model.id),
- });
- seenModelIds.add(model.id);
- };
-
- for (const model of availableModels) {
- addModel(model, "imported");
- }
-
- for (const model of customModels) {
- addModel(
- model,
- normalizeModelCatalogSource(model.source) === "imported" ? "imported" : "custom"
- );
- }
-
- for (const [alias, fullModel] of providerAliases) {
- const fmStr = fullModel as string;
- const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
- if (!modelId || seenModelIds.has(modelId)) continue;
- const customModel = customModelMap.get(modelId);
- rows.push({
- modelId,
- fullModel: fmStr,
- alias: alias as string,
- displayName: alias as string,
- source: customModel ? customModel.source || "custom" : "alias",
- isFree:
- modelId.endsWith(":free") ||
- Boolean((customModel as any)?.free) ||
- /\bgr[aá]tis\b|\bfree\b/i.test(customModel?.name || alias || ""),
- isHidden: isModelHidden(modelId),
- });
- seenModelIds.add(modelId);
- }
-
- return rows;
- }, [
- availableModels,
- customModelMap,
- customModels,
- isModelHidden,
- providerAlias,
- providerAliases,
- ]);
- const filteredModels = allModels.filter((model) => {
- const matchesQuery = matchesModelCatalogQuery(modelFilter, {
- modelId: model.modelId,
- modelName: model.displayName,
- alias: model.alias,
- source: model.source,
- });
-
- const matchesVisibility =
- visibilityFilter === "all"
- ? true
- : visibilityFilter === "visible"
- ? !model.isHidden
- : model.isHidden;
-
- return matchesQuery && matchesVisibility;
- });
- const activeCount = allModels.filter((model) => !model.isHidden).length;
- const hiddenFilteredCount = filteredModels.filter((model) => model.isHidden).length;
- const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;
-
- // Generate default alias from modelId (last part after /)
- const generateDefaultAlias = (modelId) => {
- const parts = modelId.split("/");
- return parts[parts.length - 1];
- };
-
- const handleAdd = async () => {
- if (!newModel.trim() || adding) return;
- const modelId = newModel.trim();
- const defaultAlias = generateDefaultAlias(modelId);
-
- // Check if alias already exists
- if (modelAliases[defaultAlias]) {
- alert(t("aliasExistsAlert", { alias: defaultAlias }));
- return;
- }
-
- setAdding(true);
- try {
- await onSetAlias(modelId, defaultAlias);
- setNewModel("");
- } catch (error) {
- console.error("Error adding model:", error);
- } finally {
- setAdding(false);
- }
- };
-
- return (
- <div className="flex flex-col gap-4">
- <p className="text-sm text-text-muted">{description}</p>
-
- {/* Add new model */}
- <div className="flex items-end gap-2">
- <div className="flex-1">
- <label htmlFor="new-model-input" className="text-xs text-text-muted mb-1 block">
- {inputLabel}
- </label>
- <input
- id="new-model-input"
- type="text"
- value={newModel}
- onChange={(e) => setNewModel(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleAdd()}
- placeholder={inputPlaceholder}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- />
- </div>
- <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModel.trim() || adding}>
- {adding ? t("adding") : t("add")}
- </Button>
- </div>
-
- {/* Models list */}
- {allModels.length > 0 && (
- <div className="flex flex-col gap-3">
- <ModelVisibilityToolbar
- t={t}
- filterValue={modelFilter}
- onFilterChange={setModelFilter}
- activeCount={activeCount}
- totalCount={allModels.length}
- onSelectAll={() =>
- onBulkToggleHidden(
- filteredModels.map((m) => m.modelId),
- false
- )
- }
- onDeselectAll={() =>
- onBulkToggleHidden(
- filteredModels.map((m) => m.modelId),
- true
- )
- }
- selectAllDisabled={bulkTogglePending || filteredModels.length === 0}
- deselectAllDisabled={bulkTogglePending || filteredModels.length === 0}
- onTestAll={handleTestAll}
- testingAll={testingAll}
- visibilityFilter={visibilityFilter}
- onVisibilityFilterChange={setVisibilityFilter}
- autoHideFailed={autoHideFailed}
- onAutoHideFailedChange={setAutoHideFailed}
- />
- <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
- {filteredModels.map(({ modelId, fullModel, alias, isHidden, source, isFree }) => (
- <PassthroughModelRow
- key={fullModel as string}
- modelId={modelId}
- fullModel={fullModel}
- source={source}
- isFree={isFree}
- isHidden={isHidden}
- copied={copied}
- onCopy={onCopy}
- onDeleteAlias={source === "alias" && alias ? () => onDeleteAlias(alias) : undefined}
- t={t}
- showDeveloperToggle
- effectiveModelNormalize={effectiveModelNormalize}
- effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
- getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecord(modelId, p)}
- saveModelCompatFlags={saveModelCompatFlags}
- compatDisabled={compatSavingModelId === modelId}
- onToggleHidden={onToggleHidden}
- togglingHidden={togglingModelId === modelId}
- onTestModel={onTestModel}
- testStatus={modelTestStatus?.[modelId] || null}
- testingModel={testingModelId === modelId}
- />
- ))}
- </div>
- {filteredModels.length === 0 && modelFilter && (
- <p className="py-2 text-sm text-text-muted">
- {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
- filter: modelFilter,
- })}
- </p>
- )}
- </div>
- )}
- </div>
- );
-}
-
-function PassthroughModelRow({
- modelId,
- fullModel,
- source,
- isFree,
- isHidden,
- copied,
- onCopy,
- onDeleteAlias,
- t,
- showDeveloperToggle = true,
- effectiveModelNormalize,
- effectiveModelPreserveDeveloper,
- getUpstreamHeadersRecord,
- saveModelCompatFlags,
- compatDisabled,
- onToggleHidden,
- togglingHidden,
- onTestModel,
- testStatus,
- testingModel,
-}: PassthroughModelRowProps) {
- return (
- <div
- className={`flex min-w-0 flex-col gap-2 rounded-lg border border-border px-3.5 py-3 transition-opacity hover:bg-sidebar/50 ${
- isHidden ? "opacity-50" : ""
- }`}
- >
- <div className="flex min-w-0 items-center gap-2">
- <span
- className="material-symbols-outlined shrink-0 text-base text-text-muted"
- style={{ color: isHidden ? "var(--color-text-muted)" : undefined }}
- >
- smart_toy
- </span>
- <code
- className="min-w-0 truncate rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted"
- title={fullModel}
- >
- {fullModel}
- </code>
- </div>
- <div className="flex min-w-0 items-center justify-between gap-2">
- <div className="flex min-w-0 flex-wrap items-center gap-1.5">
- <ModelSourceBadge source={source} />
- {isFree && (
- <Badge variant="success" className="shrink-0 px-1.5 py-0 text-[10px]">
- {providerText(t, "freeBadge", "Free")}
- </Badge>
- )}
- </div>
- <div className="flex shrink-0 items-center gap-1">
- <button
- onClick={() => onCopy(fullModel, `model-${modelId}`)}
- className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary"
- title={t("copyModel")}
- >
- <span className="material-symbols-outlined text-sm">
- {copied === `model-${modelId}` ? "check" : "content_copy"}
- </span>
- </button>
- {onTestModel && (
- <button
- onClick={() => onTestModel(modelId, fullModel)}
- disabled={testingModel}
- className={`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}`}
- title={
- testingModel
- ? t("testingModel")
- : testStatus === "ok"
- ? "OK"
- : testStatus === "error"
- ? "Error"
- : t("testModel")
- }
- >
- {testingModel ? (
- <span className="material-symbols-outlined text-sm animate-spin">
- progress_activity
- </span>
- ) : testStatus === "ok" ? (
- <span className="material-symbols-outlined text-sm">check_circle</span>
- ) : testStatus === "error" ? (
- <span className="material-symbols-outlined text-sm">error</span>
- ) : (
- <span className="material-symbols-outlined text-sm">play_circle</span>
- )}
- </button>
- )}
- {onToggleHidden && (
- <button
- onClick={() => onToggleHidden(modelId, !isHidden)}
- disabled={togglingHidden}
- className="rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary disabled:cursor-not-allowed disabled:opacity-40"
- title={
- isHidden
- ? providerText(t, "showModel", "Show model")
- : providerText(t, "hideModel", "Hide model")
- }
- >
- <span className="material-symbols-outlined text-sm">
- {isHidden ? "visibility_off" : "visibility"}
- </span>
- </button>
- )}
- <ModelCompatPopover
- t={t}
- effectiveModelNormalize={(p) => effectiveModelNormalize(modelId, p)}
- effectiveModelPreserveDeveloper={(p) => effectiveModelPreserveDeveloper(modelId, p)}
- getUpstreamHeadersRecord={getUpstreamHeadersRecord}
- onCompatPatch={(protocol, payload) =>
- saveModelCompatFlags(modelId, { compatByProtocol: { [protocol]: payload } })
- }
- showDeveloperToggle={showDeveloperToggle}
- compact
- disabled={compatDisabled}
- />
- {onDeleteAlias && (
- <button
- onClick={onDeleteAlias}
- className="rounded p-1 text-red-500 hover:bg-red-50"
- title={t("removeModel")}
- >
- <span className="material-symbols-outlined text-sm">delete</span>
- </button>
- )}
- </div>
- </div>
- </div>
- );
-}
-
-// ============ Custom Models Section (for ALL providers) ============
-
-function CustomModelsSection({
- providerId,
- providerAlias,
- copied,
- onCopy,
- onModelsChanged,
-}: CustomModelsSectionProps) {
- const t = useTranslations("providers");
- const notify = useNotificationStore();
- const [customModels, setCustomModels] = useState<CompatModelRow[]>([]);
- const [modelCompatOverrides, setModelCompatOverrides] = useState<
- Array<CompatModelRow & { id: string }>
- >([]);
- const [newModelId, setNewModelId] = useState("");
- const [newModelName, setNewModelName] = useState("");
- const [newApiFormat, setNewApiFormat] = useState("chat-completions");
- const [newEndpoints, setNewEndpoints] = useState(["chat"]);
- const [adding, setAdding] = useState(false);
- const [loading, setLoading] = useState(true);
- const [editingModelId, setEditingModelId] = useState<string | null>(null);
- const [editingApiFormat, setEditingApiFormat] = useState("chat-completions");
- const [editingEndpoints, setEditingEndpoints] = useState<string[]>(["chat"]);
- const [savingModelId, setSavingModelId] = useState<string | null>(null);
- const [togglingModelId, setTogglingModelId] = useState<string | null>(null);
-
- const customMap = useMemo(() => buildCompatMap(customModels), [customModels]);
- const overrideMap = useMemo(() => buildCompatMap(modelCompatOverrides), [modelCompatOverrides]);
-
- const fetchCustomModels = useCallback(async () => {
- try {
- const res = await fetch(`/api/provider-models?provider=${encodeURIComponent(providerId)}`);
- if (res.ok) {
- const data = await res.json();
- setCustomModels(data.models || []);
- setModelCompatOverrides(data.modelCompatOverrides || []);
- }
- } catch (e) {
- console.error("Failed to fetch custom models:", e);
- } finally {
- setLoading(false);
- }
- }, [providerId]);
-
- useEffect(() => {
- fetchCustomModels();
- }, [fetchCustomModels]);
-
- const handleAdd = async () => {
- if (!newModelId.trim() || adding) return;
- setAdding(true);
- try {
- const res = await fetch("/api/provider-models", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: providerId,
- modelId: newModelId.trim(),
- modelName: newModelName.trim() || undefined,
- apiFormat: newApiFormat,
- supportedEndpoints: newEndpoints,
- }),
- });
- if (res.ok) {
- setNewModelId("");
- setNewModelName("");
- setNewApiFormat("chat-completions");
- setNewEndpoints(["chat"]);
- await fetchCustomModels();
- onModelsChanged?.();
- }
- } catch (e) {
- console.error("Failed to add custom model:", e);
- } finally {
- setAdding(false);
- }
- };
-
- const handleRemove = async (modelId) => {
- try {
- await fetch(
- `/api/provider-models?provider=${encodeURIComponent(providerId)}&model=${encodeURIComponent(modelId)}`,
- {
- method: "DELETE",
- }
- );
- await fetchCustomModels();
- onModelsChanged?.();
- } catch (e) {
- console.error("Failed to remove custom model:", e);
- }
- };
-
- const handleToggleHidden = async (modelId: string, hidden: boolean) => {
- setTogglingModelId(modelId);
- try {
- const res = await fetch(
- `/api/provider-models?provider=${encodeURIComponent(providerId)}&modelId=${encodeURIComponent(modelId)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ isHidden: hidden }),
- }
- );
- if (res.ok) {
- await fetchCustomModels();
- onModelsChanged?.();
- }
- } catch (e) {
- console.error("Failed to toggle model visibility:", e);
- } finally {
- setTogglingModelId(null);
- }
- };
-
- const beginEdit = (model) => {
- setEditingModelId(model.id);
- setEditingApiFormat(model.apiFormat || "chat-completions");
- setEditingEndpoints(
- Array.isArray(model.supportedEndpoints) && model.supportedEndpoints.length
- ? model.supportedEndpoints
- : ["chat"]
- );
- };
-
- const cancelEdit = () => {
- setEditingModelId(null);
- setEditingApiFormat("chat-completions");
- setEditingEndpoints(["chat"]);
- setSavingModelId(null);
- };
-
- const saveCustomCompat = async (
- modelId: string,
- patch: { compatByProtocol?: CompatByProtocolMap }
- ) => {
- setSavingModelId(modelId);
- try {
- const res = await fetch("/api/provider-models", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider: providerId, modelId, ...patch }),
- });
- if (!res.ok) {
- const detail = await formatProviderModelsErrorResponse(res);
- notify.error(
- detail ? `${t("failedSaveCustomModel")} — ${detail}` : t("failedSaveCustomModel")
- );
- return;
- }
- } catch {
- notify.error(t("failedSaveCustomModel"));
- return;
- } finally {
- setSavingModelId(null);
- }
- try {
- await fetchCustomModels();
- onModelsChanged?.();
- } catch {
- /* refresh failure is non-critical — data was already saved */
- }
- };
-
- const saveEdit = async (modelId) => {
- if (!editingModelId || editingModelId !== modelId) return;
- if (!editingEndpoints.length) {
- notify.error("Select at least one supported endpoint");
- return;
- }
-
- setSavingModelId(modelId);
- try {
- const model = customModels.find((m) => m.id === modelId);
- const res = await fetch("/api/provider-models", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: providerId,
- modelId,
- modelName: model?.name || modelId,
- source: model?.source || "manual",
- apiFormat: editingApiFormat,
- supportedEndpoints: editingEndpoints,
- }),
- });
-
- if (!res.ok) {
- const detail = await formatProviderModelsErrorResponse(res);
- throw new Error(detail || "Failed to save model endpoint settings");
- }
-
- await fetchCustomModels();
- onModelsChanged?.();
- notify.success("Saved model endpoint settings");
- cancelEdit();
- } catch (e) {
- console.error("Failed to save custom model:", e);
- notify.error(
- e instanceof Error && e.message ? e.message : "Failed to save model endpoint settings"
- );
- } finally {
- setSavingModelId(null);
- }
- };
-
- return (
- <div className="mt-6 pt-6 border-t border-border">
- <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
- <span className="material-symbols-outlined text-base text-primary">tune</span>
- {t("customModels")}
- </h3>
- <p className="text-xs text-text-muted mb-3">{t("customModelsHint")}</p>
-
- {/* Add form */}
- <div className="flex flex-col gap-3 mb-3">
- <div className="flex items-end gap-2">
- <div className="flex-1">
- <label htmlFor="custom-model-id" className="text-xs text-text-muted mb-1 block">
- {t("modelId")}
- </label>
- <input
- id="custom-model-id"
- type="text"
- value={newModelId}
- onChange={(e) => setNewModelId(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleAdd()}
- placeholder={t("customModelPlaceholder")}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- />
- </div>
- <div className="w-40">
- <label htmlFor="custom-model-name" className="text-xs text-text-muted mb-1 block">
- {t("displayName")}
- </label>
- <input
- id="custom-model-name"
- type="text"
- value={newModelName}
- onChange={(e) => setNewModelName(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleAdd()}
- placeholder={t("optional")}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- />
- </div>
- <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModelId.trim() || adding}>
- {adding ? t("adding") : t("add")}
- </Button>
- </div>
-
- {/* API Format + Supported Endpoints */}
- <div className="flex items-end gap-4 flex-wrap">
- <div className="w-48">
- <label htmlFor="custom-api-format" className="text-xs text-text-muted mb-1 block">
- API Format
- </label>
- <select
- id="custom-api-format"
- value={newApiFormat}
- onChange={(e) => setNewApiFormat(e.target.value)}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- >
- <option value="chat-completions">{t("chatCompletions")}</option>
- <option value="responses">{t("responsesApi")}</option>
- <option value="embeddings">{t("embeddings")}</option>
- <option value="rerank">Rerank</option>
- <option value="audio-transcriptions">{t("audioTranscriptions")}</option>
- <option value="audio-speech">{t("audioSpeech")}</option>
- <option value="images-generations">{t("imagesGenerations")}</option>
- </select>
- </div>
- <div className="flex-1">
- <span className="text-xs text-text-muted mb-1 block">
- {t("supportedEndpointsLabel")}
- </span>
- <div className="flex items-center gap-3">
- {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (
- <label
- key={ep}
- className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer"
- >
- <input
- type="checkbox"
- checked={newEndpoints.includes(ep)}
- onChange={(e) => {
- if (e.target.checked) {
- setNewEndpoints((prev) => [...prev, ep]);
- } else {
- setNewEndpoints((prev) => prev.filter((x) => x !== ep));
- }
- }}
- className="rounded border-border"
- />
- {ep === "chat"
- ? `💬 ${t("supportedEndpointChat")}`
- : ep === "embeddings"
- ? `📐 ${t("supportedEndpointEmbeddings")}`
- : ep === "rerank"
- ? "Rerank"
- : ep === "images"
- ? `🖼️ ${t("supportedEndpointImages")}`
- : `🔊 ${t("supportedEndpointAudio")}`}
- </label>
- ))}
- </div>
- </div>
- </div>
- </div>
-
- {/* List */}
- {loading ? (
- <p className="text-xs text-text-muted">{t("loading")}</p>
- ) : customModels.length > 0 ? (
- <div className="flex flex-col gap-2">
- {customModels.map((model) => {
- const fullModel = `${providerAlias}/${model.id}`;
- const copyKey = `custom-${model.id}`;
- return (
- <div
- key={model.id}
- className="flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-sidebar/50"
- >
- {editingModelId !== model.id && (
- <span className="material-symbols-outlined text-base text-primary shrink-0">
- tune
- </span>
- )}
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">{model.name || model.id}</p>
- <div className="flex items-center gap-1 mt-1 flex-wrap">
- <code className="text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded">
- {fullModel}
- </code>
- <button
- onClick={() => onCopy(fullModel, copyKey)}
- className="p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary"
- title={t("copyModel")}
- >
- <span className="material-symbols-outlined text-sm">
- {copied === copyKey ? "check" : "content_copy"}
- </span>
- </button>
- {model.apiFormat === "responses" && (
- <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 font-medium">
- {t("responses")}
- </span>
- )}
- {model.supportedEndpoints?.includes("embeddings") && (
- <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-purple-500/15 text-purple-400 font-medium">
- {`📐 ${t("supportedEndpointEmbeddings")}`}
- </span>
- )}
- {model.supportedEndpoints?.includes("images") && (
- <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-400 font-medium">
- {`🖼️ ${t("imagesShortLabel")}`}
- </span>
- )}
- {model.supportedEndpoints?.includes("audio") && (
- <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 font-medium">
- {`🔊 ${t("audioShortLabel")}`}
- </span>
- )}
- {anyNormalizeCompatBadge(model.id, customMap, overrideMap) && (
- <span
- className="text-[10px] px-1.5 py-0.5 rounded-full bg-slate-500/15 text-slate-400 font-medium"
- title={t("normalizeToolCallIdLabel")}
- >
- ID×9
- </span>
- )}
- {anyNoPreserveCompatBadge(model.id, customMap, overrideMap) && (
- <span
- className="text-[10px] px-1.5 py-0.5 rounded-full bg-cyan-500/15 text-cyan-400 font-medium"
- title={t("compatDoNotPreserveDeveloper")}
- >
- {t("compatBadgeNoPreserve")}
- </span>
- )}
- {anyUpstreamHeadersBadge(model.id, customMap, overrideMap) && (
- <span
- className="text-[10px] px-1.5 py-0.5 rounded-full bg-violet-500/15 text-violet-400 font-medium"
- title={t("compatUpstreamHeadersLabel")}
- >
- {t("compatBadgeUpstreamHeaders")}
- </span>
- )}
- </div>
-
- {editingModelId === model.id && (
- <div className="mt-3 min-w-0 max-w-full rounded-lg border border-border bg-muted p-3 dark:bg-zinc-900">
- <div className="flex min-w-0 flex-wrap items-end gap-x-3 gap-y-2">
- <div className="w-[11rem] shrink-0 min-w-0">
- <label className="text-xs text-text-muted mb-1 block">
- {t("apiFormatLabel")}
- </label>
- <select
- value={editingApiFormat}
- onChange={(e) => setEditingApiFormat(e.target.value)}
- className="w-full px-2.5 py-2 text-xs border border-border rounded-lg bg-background text-text-main focus:outline-none focus:border-primary"
- >
- <option value="chat-completions">{t("chatCompletions")}</option>
- <option value="responses">{t("responsesApi")}</option>
- <option value="embeddings">{t("embeddings")}</option>
- <option value="rerank">Rerank</option>
- <option value="audio-transcriptions">{t("audioTranscriptions")}</option>
- <option value="audio-speech">{t("audioSpeech")}</option>
- <option value="images-generations">{t("imagesGenerations")}</option>
- </select>
- </div>
- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1 overflow-x-auto overflow-y-visible [scrollbar-width:thin]">
- <span className="text-xs text-text-muted shrink-0">
- {t("supportedEndpointsLabel")}
- </span>
- <div className="flex flex-wrap items-center gap-x-2 sm:gap-x-3 gap-y-1 min-w-0">
- {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (
- <label
- key={ep}
- className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer whitespace-nowrap"
- >
- <input
- type="checkbox"
- checked={editingEndpoints.includes(ep)}
- onChange={(e) => {
- if (e.target.checked) {
- setEditingEndpoints((prev) =>
- prev.includes(ep) ? prev : [...prev, ep]
- );
- } else {
- setEditingEndpoints((prev) => prev.filter((x) => x !== ep));
- }
- }}
- className="rounded border-border"
- />
- {ep === "chat"
- ? `💬 ${t("supportedEndpointChat")}`
- : ep === "embeddings"
- ? `📐 ${t("supportedEndpointEmbeddings")}`
- : ep === "rerank"
- ? "Rerank"
- : ep === "images"
- ? `🖼️ ${t("supportedEndpointImages")}`
- : `🔊 ${t("supportedEndpointAudio")}`}
- </label>
- ))}
- </div>
- </div>
- <div className="flex shrink-0 flex-wrap items-center gap-2 pb-0.5">
- <Button
- size="sm"
- onClick={() => saveEdit(model.id)}
- disabled={savingModelId === model.id}
- >
- {savingModelId === model.id ? t("saving") : t("save")}
- </Button>
- <Button size="sm" variant="ghost" onClick={cancelEdit}>
- {t("cancel")}
- </Button>
- </div>
- </div>
- </div>
- )}
- </div>
- <div className="flex shrink-0 items-center gap-1">
- <button
- onClick={() => beginEdit(model)}
- className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary"
- title={t("edit")}
- >
- <span className="material-symbols-outlined text-sm">edit</span>
- </button>
- <ModelCompatPopover
- t={t}
- effectiveModelNormalize={(p) =>
- effectiveNormalizeForProtocol(model.id, p, customMap, overrideMap)
- }
- effectiveModelPreserveDeveloper={(p) =>
- effectivePreserveForProtocol(model.id, p, customMap, overrideMap)
- }
- getUpstreamHeadersRecord={(p) =>
- effectiveUpstreamHeadersForProtocol(model.id, p, customMap, overrideMap)
- }
- onCompatPatch={(protocol, payload) =>
- saveCustomCompat(model.id, {
- compatByProtocol: { [protocol]: payload },
- })
- }
- showDeveloperToggle
- disabled={savingModelId === model.id}
- />
- <button
- onClick={() => handleToggleHidden(model.id, !model.isHidden)}
- disabled={togglingModelId === model.id}
- className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary disabled:opacity-50"
- title={model.isHidden ? t("unhideModel") : t("hideModel")}
- >
- <span className="material-symbols-outlined text-sm">
- {model.isHidden ? "visibility_off" : "visibility"}
- </span>
- </button>
- <button
- onClick={() => handleRemove(model.id)}
- className="rounded p-1 text-red-500 hover:bg-red-50"
- title={t("removeCustomModel")}
- >
- <span className="material-symbols-outlined text-sm">delete</span>
- </button>
- </div>
- </div>
- );
- })}
- </div>
- ) : (
- <p className="text-xs text-text-muted">{t("noCustomModels")}</p>
- )}
- </div>
- );
-}
-
-function CompatibleModelsSection({
- providerStorageAlias,
- providerDisplayAlias,
- modelAliases,
- availableModels = [],
- customModels = [],
- fallbackModels = [],
- description,
- inputLabel,
- inputPlaceholder,
- copied,
- onCopy,
- onSetAlias,
- onDeleteAlias,
- connections,
- isAnthropic,
- onImportWithProgress,
- t,
- effectiveModelNormalize,
- effectiveModelPreserveDeveloper,
- getUpstreamHeadersRecord,
- saveModelCompatFlags,
- compatSavingModelId,
- onModelsChanged,
- allowImport,
- isModelHidden,
- onToggleHidden,
- onBulkToggleHidden,
- bulkTogglePending,
- togglingModelId,
- onTestModel,
- modelTestStatus,
- testingModelId,
- onTestAll,
- testingAll,
- testProgress,
- autoHideFailed,
- onAutoHideFailedChange,
-}: CompatibleModelsSectionProps) {
- const [newModel, setNewModel] = useState("");
- const [adding, setAdding] = useState(false);
- const [importing, setImporting] = useState(false);
- const [modelFilter, setModelFilter] = useState("");
- const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");
- const notify = useNotificationStore();
- const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);
-
- const providerAliases = useMemo(
- () =>
- Object.entries(modelAliases).filter(([, model]: [string, any]) =>
- (model as string).startsWith(`${providerStorageAlias}/`)
- ),
- [modelAliases, providerStorageAlias]
- );
-
- const allModels = useMemo(() => {
- const prefix = `${providerStorageAlias}/`;
- const aliasByModelId = new Map<string, string>();
- const rows: Array<{
- modelId: string;
- alias: string | null;
- displayName: string;
- source: string;
- isFree: boolean;
- isHidden: boolean;
- }> = [];
- const seenModelIds = new Set<string>();
-
- for (const [alias, fullModel] of providerAliases) {
- const fmStr = fullModel as string;
- const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
- aliasByModelId.set(modelId, alias as string);
- }
-
- const addModel = (model: CompatModelRow, source: string) => {
- if (!model?.id || seenModelIds.has(model.id)) return;
- rows.push({
- modelId: model.id,
- alias: aliasByModelId.get(model.id) || null,
- displayName: model.name || model.id,
- source,
- isFree:
- Boolean((model as any).free) ||
- model.id.endsWith(":free") ||
- /\bgr[aá]tis\b|\bfree\b/i.test(model.name || ""),
- isHidden: isModelHidden(model.id),
- });
- seenModelIds.add(model.id);
- };
-
- for (const model of availableModels) {
- addModel(model, "imported");
- }
-
- for (const model of customModels) {
- addModel(
- model,
- normalizeModelCatalogSource(model.source) === "imported" ? "imported" : "custom"
- );
- }
-
- for (const model of fallbackModels) {
- addModel(model, "fallback");
- }
-
- for (const [alias, fullModel] of providerAliases) {
- const fmStr = fullModel as string;
- const modelId = fmStr.startsWith(prefix) ? fmStr.slice(prefix.length) : fmStr;
- if (!modelId || seenModelIds.has(modelId)) continue;
- const customModel = customModelMap.get(modelId);
- rows.push({
- modelId,
- alias: alias as string,
- displayName: alias as string,
- source: customModel ? customModel.source || "custom" : "alias",
- isFree:
- modelId.endsWith(":free") ||
- Boolean((customModel as any)?.free) ||
- /\bgr[aá]tis\b|\bfree\b/i.test(customModel?.name || alias || ""),
- isHidden: isModelHidden(modelId),
- });
- seenModelIds.add(modelId);
- }
-
- return rows;
- }, [
- availableModels,
- customModelMap,
- customModels,
- fallbackModels,
- isModelHidden,
- providerAliases,
- providerStorageAlias,
- ]);
- const filteredModels = allModels.filter((model) => {
- const matchesQuery = matchesModelCatalogQuery(modelFilter, {
- modelId: model.modelId,
- modelName: model.displayName,
- alias: model.alias,
- source: model.source,
- });
- const matchesVisibility =
- visibilityFilter === "all"
- ? true
- : visibilityFilter === "visible"
- ? !model.isHidden
- : model.isHidden;
- return matchesQuery && matchesVisibility;
- });
- const activeCount = allModels.filter((model) => !model.isHidden).length;
- const hiddenFilteredCount = filteredModels.filter((model) => model.isHidden).length;
- const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;
-
- const resolveAlias = useCallback(
- (modelId: string, workingAliases: Record<string, string>) =>
- resolveManagedModelAlias({
- modelId,
- fullModel: `${providerStorageAlias}/${modelId}`,
- providerDisplayAlias,
- existingAliases: workingAliases,
- }),
- [providerDisplayAlias, providerStorageAlias]
- );
-
- const handleAdd = async () => {
- if (!newModel.trim() || adding) return;
- const modelId = newModel.trim();
- const resolvedAlias = resolveAlias(modelId, modelAliases);
- if (!resolvedAlias) {
- notify.error(t("allSuggestedAliasesExist"));
- return;
- }
-
- setAdding(true);
- try {
- // Save to customModels DB FIRST - only create alias if this succeeds
- const customModelRes = await fetch("/api/provider-models", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: providerStorageAlias,
- modelId,
- modelName: modelId,
- source: "manual",
- }),
- });
-
- if (!customModelRes.ok) {
- let errorData: { error?: { message?: string } } = {};
- try {
- errorData = await customModelRes.json();
- } catch (jsonError) {
- console.error("Failed to parse error response from custom model API:", jsonError);
- }
- throw new Error(errorData.error?.message || t("failedSaveCustomModel"));
- }
-
- // Only create alias after customModel is saved successfully
- await onSetAlias(modelId, resolvedAlias, providerStorageAlias);
- setNewModel("");
- notify.success(t("modelAddedSuccess", { modelId }));
- onModelsChanged?.();
- } catch (error) {
- console.error("Error adding model:", error);
- notify.error(error instanceof Error ? error.message : t("failedAddModelTryAgain"));
- } finally {
- setAdding(false);
- }
- };
-
- const handleImport = async () => {
- if (!allowImport || importing) return;
- const activeConnection = connections.find((conn) => conn.isActive !== false);
- if (!activeConnection?.id) return;
-
- setImporting(true);
- try {
- await onImportWithProgress(activeConnection.id);
- } catch (error) {
- console.error("Error importing models:", error);
- notify.error(t("failedImportModelsTryAgain"));
- } finally {
- setImporting(false);
- }
- };
-
- const canImport = connections.some((conn) => conn.isActive !== false);
-
- // Handle delete: remove from both alias and customModels DB
- const handleDeleteModel = async (modelId: string, alias?: string | null) => {
- try {
- // Remove from customModels DB
- const res = await fetch(
- `/api/provider-models?provider=${encodeURIComponent(providerStorageAlias)}&model=${encodeURIComponent(modelId)}`,
- { method: "DELETE" }
- );
- if (!res.ok) {
- throw new Error(t("failedRemoveModelFromDatabase"));
- }
- // Also delete the alias
- if (alias) {
- await onDeleteAlias(alias);
- }
- notify.success(t("modelRemovedSuccess"));
- onModelsChanged?.();
- } catch (error) {
- console.error("Error deleting model:", error);
- notify.error(error instanceof Error ? error.message : t("failedDeleteModelTryAgain"));
- }
- };
-
- return (
- <div className="flex flex-col gap-4">
- <p className="text-sm text-text-muted">{description}</p>
-
- <div className="flex items-end gap-2 flex-wrap">
- <div className="flex-1 min-w-[240px]">
- <label
- htmlFor="new-compatible-model-input"
- className="text-xs text-text-muted mb-1 block"
- >
- {inputLabel}
- </label>
- <input
- id="new-compatible-model-input"
- type="text"
- value={newModel}
- onChange={(e) => setNewModel(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleAdd()}
- placeholder={inputPlaceholder}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- />
- </div>
- <Button size="sm" icon="add" onClick={handleAdd} disabled={!newModel.trim() || adding}>
- {adding ? t("adding") : t("add")}
- </Button>
- {allowImport && (
- <Button
- size="sm"
- variant="secondary"
- icon="download"
- onClick={handleImport}
- disabled={!canImport || importing}
- >
- {importing ? t("importingModels") : t("importFromModels")}
- </Button>
- )}
- </div>
-
- {allowImport && !canImport && (
- <p className="text-xs text-text-muted">{t("addConnectionToImport")}</p>
- )}
-
- {allModels.length > 0 && (
- <div className="flex flex-col gap-3">
- <ModelVisibilityToolbar
- t={t}
- filterValue={modelFilter}
- onFilterChange={setModelFilter}
- activeCount={activeCount}
- totalCount={allModels.length}
- onSelectAll={() =>
- onBulkToggleHidden(
- filteredModels.map((model) => model.modelId),
- false
- )
- }
- onDeselectAll={() =>
- onBulkToggleHidden(
- filteredModels.map((model) => model.modelId),
- true
- )
- }
- selectAllDisabled={hiddenFilteredCount === 0 || bulkTogglePending}
- deselectAllDisabled={visibleFilteredCount === 0 || bulkTogglePending}
- visibilityFilter={visibilityFilter}
- onVisibilityFilterChange={setVisibilityFilter}
- onTestAll={() => {
- const targets = filteredModels
- .filter((m) => !m.isHidden)
- .map((m) => ({
- modelId: m.modelId,
- fullModel: `${providerDisplayAlias}/${m.modelId}`,
- }));
- return onTestAll?.(targets);
- }}
- testingAll={testingAll}
- testProgress={testProgress}
- autoHideFailed={autoHideFailed}
- onAutoHideFailedChange={onAutoHideFailedChange}
- />
- <div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
- {filteredModels.map(({ modelId, alias, isHidden, source, isFree }) => {
- const fullModel = `${providerDisplayAlias}/${modelId}`;
- return (
- <PassthroughModelRow
- key={`${providerStorageAlias}:${modelId}`}
- modelId={modelId}
- fullModel={fullModel}
- source={source}
- isFree={isFree}
- isHidden={isHidden}
- copied={copied}
- onCopy={onCopy}
- onDeleteAlias={
- source === "custom" || source === "manual"
- ? () => handleDeleteModel(modelId, alias)
- : source === "alias" && alias
- ? () => onDeleteAlias(alias)
- : undefined
- }
- t={t}
- showDeveloperToggle={!isAnthropic}
- effectiveModelNormalize={effectiveModelNormalize}
- effectiveModelPreserveDeveloper={effectiveModelPreserveDeveloper}
- getUpstreamHeadersRecord={(p) => getUpstreamHeadersRecord(modelId, p)}
- saveModelCompatFlags={saveModelCompatFlags}
- compatDisabled={compatSavingModelId === modelId}
- onToggleHidden={onToggleHidden}
- togglingHidden={togglingModelId === modelId}
- onTestModel={onTestModel}
- testStatus={modelTestStatus?.[modelId] || null}
- testingModel={testingModelId === modelId}
- />
- );
- })}
- </div>
- {filteredModels.length === 0 && modelFilter && (
- <p className="py-2 text-sm text-text-muted">
- {providerText(t, "noModelsMatch", `No models match "${modelFilter}"`, {
- filter: modelFilter,
- })}
- </p>
- )}
- </div>
- )}
- </div>
- );
-}
-
-function CooldownTimer({ until }: CooldownTimerProps) {
- const [remaining, setRemaining] = useState("");
-
- useEffect(() => {
- const updateRemaining = () => {
- const diff = new Date(until).getTime() - Date.now();
- if (diff <= 0) {
- setRemaining("");
- return;
- }
- const secs = Math.floor(diff / 1000);
- if (secs < 60) {
- setRemaining(`${secs}s`);
- } else if (secs < 3600) {
- setRemaining(`${Math.floor(secs / 60)}m ${secs % 60}s`);
- } else {
- const hrs = Math.floor(secs / 3600);
- const mins = Math.floor((secs % 3600) / 60);
- setRemaining(`${hrs}h ${mins}m`);
- }
- };
-
- updateRemaining();
- const interval = setInterval(updateRemaining, 1000);
- return () => clearInterval(interval);
- }, [until]);
-
- if (!remaining) return null;
-
- return <span className="text-xs text-orange-500 font-mono">⏱ {remaining}</span>;
-}
-
-const ERROR_TYPE_LABELS = {
- runtime_error: { labelKey: "errorTypeRuntime", variant: "warning" },
- upstream_auth_error: { labelKey: "errorTypeUpstreamAuth", variant: "error" },
- account_deactivated: { labelKey: "Account Deactivated", variant: "error" },
- auth_missing: { labelKey: "errorTypeMissingCredential", variant: "warning" },
- token_refresh_failed: { labelKey: "errorTypeRefreshFailed", variant: "warning" },
- token_expired: { labelKey: "errorTypeTokenExpired", variant: "warning" },
- upstream_rate_limited: { labelKey: "errorTypeRateLimited", variant: "warning" },
- upstream_unavailable: { labelKey: "errorTypeUpstreamUnavailable", variant: "error" },
- network_error: { labelKey: "errorTypeNetworkError", variant: "warning" },
- unsupported: { labelKey: "errorTypeTestUnsupported", variant: "default" },
- upstream_error: { labelKey: "errorTypeUpstreamError", variant: "error" },
- banned: { labelKey: "errorTypeBanned", variant: "error" },
- credits_exhausted: { labelKey: "errorTypeCreditsExhausted", variant: "warning" },
-};
-
-function inferErrorType(connection, isCooldown) {
- if (isCooldown) return "upstream_rate_limited";
- if (connection.testStatus === "banned") return "banned";
- if (connection.testStatus === "credits_exhausted") return "credits_exhausted";
- if (connection.lastErrorType) return connection.lastErrorType;
-
- const code = Number(connection.errorCode);
- if (code === 401 || code === 403) return "upstream_auth_error";
- if (code === 429) return "upstream_rate_limited";
- if (code >= 500) return "upstream_unavailable";
-
- const msg = (connection.lastError || "").toLowerCase();
- if (!msg) return null;
- if (
- msg.includes("runtime") ||
- msg.includes("not runnable") ||
- msg.includes("not installed") ||
- msg.includes("healthcheck")
- )
- return "runtime_error";
- if (msg.includes("refresh failed")) return "token_refresh_failed";
- if (msg.includes("token expired") || msg.includes("expired")) return "token_expired";
- if (
- msg.includes("invalid api key") ||
- msg.includes("token invalid") ||
- msg.includes("revoked") ||
- msg.includes("access denied") ||
- msg.includes("unauthorized")
- )
- return "upstream_auth_error";
- if (
- msg.includes("rate limit") ||
- msg.includes("quota") ||
- msg.includes("too many requests") ||
- msg.includes("429")
- )
- return "upstream_rate_limited";
- if (
- msg.includes("fetch failed") ||
- msg.includes("network") ||
- msg.includes("timeout") ||
- msg.includes("econn") ||
- msg.includes("enotfound")
- )
- return "network_error";
- if (msg.includes("not supported")) return "unsupported";
- return "upstream_error";
-}
-
-function getStatusPresentation(connection, effectiveStatus, isCooldown, t) {
- if (connection.isActive === false) {
- return {
- statusVariant: "default",
- statusLabel: t("statusDisabled"),
- errorType: null,
- errorBadge: null,
- errorTextClass: "text-text-muted",
- };
- }
-
- if (effectiveStatus === "active" || effectiveStatus === "success") {
- return {
- statusVariant: "success",
- statusLabel: t("statusConnected"),
- errorType: null,
- errorBadge: null,
- errorTextClass: "text-text-muted",
- };
- }
-
- const errorType = inferErrorType(connection, isCooldown);
- const errorBadge = errorType ? ERROR_TYPE_LABELS[errorType] || null : null;
-
- if (errorType === "runtime_error") {
- return {
- statusVariant: "warning",
- statusLabel: t("statusRuntimeIssue"),
- errorType,
- errorBadge,
- errorTextClass: "text-yellow-600 dark:text-yellow-400",
- };
- }
-
- if (errorType === "account_deactivated") {
- return {
- statusVariant: "error",
- statusLabel: t("statusDeactivated", "Deactivated"),
- errorType,
- errorBadge,
- errorTextClass: "text-red-600 font-bold",
- };
- }
-
- if (
- errorType === "upstream_auth_error" ||
- errorType === "auth_missing" ||
- errorType === "token_refresh_failed" ||
- errorType === "token_expired"
- ) {
- return {
- statusVariant: "error",
- statusLabel: t("statusAuthFailed"),
- errorType,
- errorBadge,
- errorTextClass: "text-red-500",
- };
- }
-
- if (errorType === "upstream_rate_limited") {
- return {
- statusVariant: "warning",
- statusLabel: t("statusRateLimited"),
- errorType,
- errorBadge,
- errorTextClass: "text-yellow-600 dark:text-yellow-400",
- };
- }
-
- if (errorType === "network_error") {
- return {
- statusVariant: "warning",
- statusLabel: t("statusNetworkIssue"),
- errorType,
- errorBadge,
- errorTextClass: "text-yellow-600 dark:text-yellow-400",
- };
- }
-
- if (errorType === "unsupported") {
- return {
- statusVariant: "default",
- statusLabel: t("statusTestUnsupported"),
- errorType,
- errorBadge,
- errorTextClass: "text-text-muted",
- };
- }
-
- if (errorType === "banned") {
- return {
- statusVariant: "error",
- statusLabel: t("statusBanned", "Banned (403)"),
- errorType,
- errorBadge,
- errorTextClass: "text-red-600 font-bold",
- };
- }
-
- if (errorType === "credits_exhausted") {
- return {
- statusVariant: "warning",
- statusLabel: t("statusCreditsExhausted", "Out of Credits"),
- errorType,
- errorBadge,
- errorTextClass: "text-amber-500",
- };
- }
-
- const fallbackStatusMap = {
- unavailable: t("statusUnavailable"),
- failed: t("statusFailed"),
- error: t("statusError"),
- };
-
- return {
- statusVariant: "error",
- statusLabel: fallbackStatusMap[effectiveStatus] || effectiveStatus || t("statusError"),
- errorType,
- errorBadge,
- errorTextClass: "text-red-500",
- };
-}
-
-function ConnectionRow({
- connection,
- isOAuth,
- isClaude,
- isCodex,
- isGeminiCli,
- codexGlobalServiceMode,
- isCcCompatible,
- cliproxyapiEnabled,
- isFirst,
- isLast,
- isSelected,
- onToggleSelect,
- onMoveUp,
- onMoveDown,
- onToggleActive,
- onToggleRateLimit,
- onToggleClaudeExtraUsage,
- onToggleCodex5h,
- onToggleCodexWeekly,
- onToggleCliproxyapiMode,
- onRetest,
- isRetesting,
- onEdit,
- onDelete,
- onReauth,
- onProxy,
- hasProxy,
- proxySource,
- proxyHost,
- onRefreshToken,
- isRefreshing,
- onApplyCodexAuthLocal,
- isApplyingCodexAuthLocal,
- onExportCodexAuthFile,
- isExportingCodexAuthFile,
- onApplyClaudeAuthLocal,
- isApplyingClaudeAuthLocal,
- onExportClaudeAuthFile,
- isExportingClaudeAuthFile,
- onApplyGeminiAuthLocal,
- isApplyingGeminiAuthLocal,
- onExportGeminiAuthFile,
- isExportingGeminiAuthFile,
- perKeyProxyEnabled,
- onTogglePerKeyProxyEnabled,
- proxyEnabled,
- onToggleProxyEnabled,
-}: ConnectionRowProps) {
- const t = useTranslations("providers");
- const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);
- const displayName = isOAuth
- ? pickDisplayValue(
- [connection.name, connection.email, connection.displayName],
- emailsVisible,
- t("oauthAccount")
- )
- : connection.name;
- const applyCodexAuthLabel =
- typeof t.has === "function" && t.has("applyCodexAuthLocal")
- ? t("applyCodexAuthLocal")
- : "Apply auth";
- const exportCodexAuthLabel =
- typeof t.has === "function" && t.has("exportCodexAuthFile")
- ? t("exportCodexAuthFile")
- : "Export auth";
- const applyClaudeAuthLabel =
- typeof t.has === "function" && t.has("applyClaudeAuthLocal")
- ? t("applyClaudeAuthLocal")
- : "Apply auth";
- const exportClaudeAuthLabel =
- typeof t.has === "function" && t.has("exportClaudeAuthFile")
- ? t("exportClaudeAuthFile")
- : "Export auth";
- const applyGeminiAuthLabel =
- typeof t.has === "function" && t.has("applyGeminiAuthLocal")
- ? t("applyGeminiAuthLocal")
- : "Apply auth";
- const exportGeminiAuthLabel =
- typeof t.has === "function" && t.has("exportGeminiAuthFile")
- ? t("exportGeminiAuthFile")
- : "Export auth";
-
- // Use useState + useEffect for impure Date.now() to avoid calling during render
- const [isCooldown, setIsCooldown] = useState(false);
- // T12: token expiry status — lazy init avoids calling Date.now() during render;
- // updates every 30s via interval only (no sync setState in effect body).
- // Prefer tokenExpiresAt (updated on each refresh) over expiresAt (original grant date).
- const effectiveExpiresAt = connection.tokenExpiresAt || connection.expiresAt;
- const getTokenMinsLeft = () => {
- if (!isOAuth || !effectiveExpiresAt) return null;
- const expiresMs = new Date(effectiveExpiresAt).getTime();
- return Math.floor((expiresMs - Date.now()) / 60000);
- };
- const [tokenMinsLeft, setTokenMinsLeft] = useState<number | null>(getTokenMinsLeft);
-
- useEffect(() => {
- if (!isOAuth || !effectiveExpiresAt) return;
- const update = () => {
- const expiresMs = new Date(effectiveExpiresAt).getTime();
- setTokenMinsLeft(Math.floor((expiresMs - Date.now()) / 60000));
- };
- update();
- const iv = setInterval(update, 30000);
- return () => clearInterval(iv);
- }, [isOAuth, effectiveExpiresAt]);
-
- useEffect(() => {
- const checkCooldown = () => {
- const cooldown =
- connection.rateLimitedUntil && new Date(connection.rateLimitedUntil).getTime() > Date.now();
- setIsCooldown(cooldown);
- };
-
- checkCooldown();
- // Update every second while in cooldown
- const interval = connection.rateLimitedUntil ? setInterval(checkCooldown, 1000) : null;
- return () => {
- if (interval) clearInterval(interval);
- };
- }, [connection.rateLimitedUntil]);
-
- // Determine effective status (override unavailable if cooldown expired)
- const effectiveStatus =
- connection.testStatus === "unavailable" && !isCooldown
- ? "active" // Cooldown expired → treat as active
- : connection.testStatus;
-
- const statusPresentation = getStatusPresentation(connection, effectiveStatus, isCooldown, t);
- const rateLimitEnabled = !!connection.rateLimitProtection;
- const codexPolicy =
- connection.providerSpecificData &&
- typeof connection.providerSpecificData === "object" &&
- connection.providerSpecificData.codexLimitPolicy &&
- typeof connection.providerSpecificData.codexLimitPolicy === "object"
- ? connection.providerSpecificData.codexLimitPolicy
- : {};
- const normalizedCodexPolicy = normalizeCodexLimitPolicy(codexPolicy);
- const codex5hEnabled = normalizedCodexPolicy.use5h;
- const codexWeeklyEnabled = normalizedCodexPolicy.useWeekly;
- const codexServiceTier = isCodex
- ? getCodexEffectiveServiceTier(
- connection.providerSpecificData,
- codexGlobalServiceMode ?? "none"
- )
- : "default";
- const codexServiceTierIsGlobal =
- isCodex && codexGlobalServiceMode !== undefined && codexGlobalServiceMode !== "none";
- const codexServiceTierBadge =
- codexServiceTier === "priority"
- ? {
- label: providerText(t, "codexTierFastLabel", "Fast"),
- icon: "bolt",
- className: "bg-sky-500/15 text-sky-500",
- title: codexServiceTierIsGlobal
- ? providerText(
- t,
- "providerDetailGlobalPriorityActive",
- "Global Codex priority service tier is active"
- )
- : providerText(
- t,
- "providerDetailConnectionPriorityActive",
- "Codex priority service tier is active for this connection"
- ),
- }
- : codexServiceTier === "flex"
- ? {
- label: providerText(t, "codexTierFlexLabel", "Flex"),
- icon: "speed",
- className: "bg-cyan-500/15 text-cyan-500",
- title: codexServiceTierIsGlobal
- ? providerText(
- t,
- "providerDetailGlobalFlexActive",
- "Global Codex flex service tier is active"
- )
- : providerText(
- t,
- "providerDetailConnectionFlexActive",
- "Codex flex service tier is active for this connection"
- ),
- }
- : null;
- const claudeBlockExtraUsageEnabled = isClaude
- ? isClaudeExtraUsageBlockEnabled("claude", connection.providerSpecificData)
- : false;
- const cliproxyapiDeepMode = !!cliproxyapiEnabled;
-
- return (
- <div
- className={`group flex items-center justify-between p-3 rounded-lg hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${connection.isActive === false ? "opacity-60" : ""}`}
- >
- <div className="flex items-center gap-3 flex-1 min-w-0">
- {onToggleSelect && (
- <input
- type="checkbox"
- checked={isSelected}
- onChange={onToggleSelect}
- className="w-4 h-4 shrink-0 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
- />
- )}
- {/* Priority arrows */}
- <div className="flex flex-col">
- <button
- onClick={onMoveUp}
- disabled={isFirst}
- className={`p-0.5 rounded ${isFirst ? "text-text-muted/30 cursor-not-allowed" : "hover:bg-sidebar text-text-muted hover:text-primary"}`}
- >
- <span className="material-symbols-outlined text-sm">keyboard_arrow_up</span>
- </button>
- <button
- onClick={onMoveDown}
- disabled={isLast}
- className={`p-0.5 rounded ${isLast ? "text-text-muted/30 cursor-not-allowed" : "hover:bg-sidebar text-text-muted hover:text-primary"}`}
- >
- <span className="material-symbols-outlined text-sm">keyboard_arrow_down</span>
- </button>
- </div>
- <span className="material-symbols-outlined text-base text-text-muted">
- {isOAuth ? "lock" : "key"}
- </span>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">{displayName}</p>
- <div className="flex items-center gap-2 mt-1 flex-wrap">
- <Badge variant={statusPresentation.statusVariant as any} size="sm" dot>
- {statusPresentation.statusLabel}
- </Badge>
- {/* T12: Token expiry status indicator (state-driven, no Date.now in render) */}
- {tokenMinsLeft !== null &&
- (tokenMinsLeft < 0 ? (
- <span
- className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-500"
- title={t("tokenExpiredTitle", { date: effectiveExpiresAt })}
- >
- <span className="material-symbols-outlined text-[11px]">error</span>
- {t("tokenExpiredBadge")}
- </span>
- ) : tokenMinsLeft < 30 ? (
- <span
- className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-500"
- title={t("tokenExpiresSoonTitle", { minutes: tokenMinsLeft })}
- >
- <span className="material-symbols-outlined text-[11px]">warning</span>
- {`~${tokenMinsLeft}m`}
- </span>
- ) : null)}
- {isCooldown && connection.isActive !== false && (
- <CooldownTimer until={connection.rateLimitedUntil} />
- )}
- {statusPresentation.errorBadge && connection.isActive !== false && (
- <Badge variant={statusPresentation.errorBadge.variant} size="sm">
- {t(statusPresentation.errorBadge.labelKey)}
- </Badge>
- )}
- {connection.lastError && connection.isActive !== false && (
- <span
- className={`text-xs truncate max-w-[300px] ${statusPresentation.errorTextClass}`}
- title={connection.lastError}
- >
- {connection.lastError}
- </span>
- )}
- <span className="text-xs text-text-muted">#{connection.priority}</span>
- {connection.globalPriority && (
- <span className="text-xs text-text-muted">
- {t("autoPriority", { priority: connection.globalPriority })}
- </span>
- )}
- {connection.maxConcurrent != null && connection.maxConcurrent > 0 && (
- <span
- className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-zinc-500/15 text-zinc-500 dark:bg-zinc-400/15 dark:text-zinc-400"
- title={t("accountConcurrencyCapLabel")}
- >
- <span className="material-symbols-outlined text-[11px]">dynamic_feed</span>
- {connection.maxConcurrent}
- </span>
- )}
- {/* Rate Limit Protection — inline toggle with label */}
- <span className="text-text-muted/30 select-none">|</span>
- <button
- onClick={() => onToggleRateLimit(!rateLimitEnabled)}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- rateLimitEnabled
- ? "bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={
- rateLimitEnabled ? t("disableRateLimitProtection") : t("enableRateLimitProtection")
- }
- >
- <span className="material-symbols-outlined text-[13px]">shield</span>
- {rateLimitEnabled ? t("rateLimitProtected") : t("rateLimitUnprotected")}
- </button>
- {isClaude && (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- <button
- onClick={() => onToggleClaudeExtraUsage?.(!claudeBlockExtraUsageEnabled)}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- !claudeBlockExtraUsageEnabled
- ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={t("claudeExtraUsageToggleTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">payments</span>
- {t("claudeExtraUsageShort")}{" "}
- {!claudeBlockExtraUsageEnabled ? t("toggleOnShort") : t("toggleOffShort")}
- </button>
- </>
- )}
- {isCcCompatible && (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- <button
- onClick={() => onToggleCliproxyapiMode?.(!cliproxyapiDeepMode)}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- cliproxyapiDeepMode
- ? "bg-indigo-500/15 text-indigo-500 hover:bg-indigo-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={cliproxyapiDeepMode ? t("cpaModeEnabledTitle") : t("cpaModeDisabledTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">swap_horiz</span>
- CPA {cliproxyapiDeepMode ? t("toggleOnShort") : t("toggleOffShort")}
- </button>
- </>
- )}
- {isCodex && (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- {codexServiceTierBadge && (
- <span
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium ${codexServiceTierBadge.className}`}
- title={codexServiceTierBadge.title}
- >
- <span className="material-symbols-outlined text-[13px]">
- {codexServiceTierBadge.icon}
- </span>
- {codexServiceTierBadge.label}
- </span>
- )}
- <button
- onClick={() => onToggleCodex5h?.(!codex5hEnabled)}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- codex5hEnabled
- ? "bg-blue-500/15 text-blue-500 hover:bg-blue-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={t("codex5hToggleTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">timer</span>
- 5h {codex5hEnabled ? t("toggleOnShort") : t("toggleOffShort")}
- </button>
- <button
- onClick={() => onToggleCodexWeekly?.(!codexWeeklyEnabled)}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- codexWeeklyEnabled
- ? "bg-violet-500/15 text-violet-500 hover:bg-violet-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={t("codexWeeklyToggleTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">date_range</span>
- {t("weeklyShort")} {codexWeeklyEnabled ? t("toggleOnShort") : t("toggleOffShort")}
- </button>
- </>
- )}
- {onToggleProxyEnabled && (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- <button
- onClick={() => onToggleProxyEnabled(!proxyEnabled)}
- aria-label={proxyEnabled ? t("proxyEnabledTitle") : t("proxyDisabledTitle")}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- proxyEnabled
- ? "bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={proxyEnabled ? t("proxyEnabledTitle") : t("proxyDisabledTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">vpn_lock</span>
- {proxyEnabled ? <span className="sr-only">{t("proxyOn")}</span> : t("proxyOff")}
- </button>
- </>
- )}
- {onTogglePerKeyProxyEnabled && (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- <button
- onClick={() => onTogglePerKeyProxyEnabled(!perKeyProxyEnabled)}
- aria-label={perKeyProxyEnabled ? t("perKeyProxyEnabledTitle") : t("perKeyProxyDisabledTitle")}
- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${
- perKeyProxyEnabled
- ? "bg-violet-500/15 text-violet-500 hover:bg-violet-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={perKeyProxyEnabled ? t("perKeyProxyEnabledTitle") : t("perKeyProxyDisabledTitle")}
- >
- <span className="material-symbols-outlined text-[13px]">key</span>
- {perKeyProxyEnabled ? (
- t("perKeyProxyOn")
- ) : (
- <span className="sr-only">{t("perKeyProxyOff")}</span>
- )}
- </button>
- </>
- )}
- {hasProxy &&
- (() => {
- const colorClass =
- proxySource === "global"
- ? "bg-emerald-500/15 text-emerald-500"
- : proxySource === "provider"
- ? "bg-amber-500/15 text-amber-500"
- : "bg-blue-500/15 text-blue-500";
- const label =
- proxySource === "global"
- ? t("proxySourceGlobal")
- : proxySource === "provider"
- ? t("proxySourceProvider")
- : t("proxySourceKey");
- return (
- <>
- <span className="text-text-muted/30 select-none">|</span>
- <span
- className={`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${colorClass}`}
- title={t("proxyConfiguredBySource", {
- source: label,
- host: proxyHost || t("configured"),
- })}
- >
- <span className="material-symbols-outlined text-[13px]">vpn_lock</span>
- {proxyHost || t("proxy")}
- </span>
- </>
- );
- })()}
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2">
- <Button
- size="sm"
- variant="ghost"
- icon="refresh"
- loading={isRetesting}
- disabled={connection.isActive === false}
- onClick={onRetest}
- className="!h-7 !px-2 text-xs"
- title={t("retestAuthentication")}
- >
- {t("retest")}
- </Button>
- {/* T12: Manual token refresh for OAuth accounts */}
- {onRefreshToken && (
- <Button
- size="sm"
- variant="ghost"
- icon="token"
- loading={isRefreshing}
- disabled={connection.isActive === false || isRefreshing}
- onClick={onRefreshToken}
- className="!h-7 !px-2 text-xs text-amber-500 hover:text-amber-400"
- title={t("refreshOauthTokenTitle")}
- >
- {t("tokenShort")}
- </Button>
- )}
- {isCodex && onApplyCodexAuthLocal && (
- <Button
- size="sm"
- variant="ghost"
- icon="download_done"
- loading={isApplyingCodexAuthLocal}
- disabled={isApplyingCodexAuthLocal}
- onClick={onApplyCodexAuthLocal}
- className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
- title={applyCodexAuthLabel}
- >
- {applyCodexAuthLabel}
- </Button>
- )}
- {isCodex && onExportCodexAuthFile && (
- <Button
- size="sm"
- variant="ghost"
- icon="download"
- loading={isExportingCodexAuthFile}
- disabled={isExportingCodexAuthFile}
- onClick={onExportCodexAuthFile}
- className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
- title={exportCodexAuthLabel}
- >
- {exportCodexAuthLabel}
- </Button>
- )}
- {isClaude && onApplyClaudeAuthLocal && (
- <Button
- size="sm"
- variant="ghost"
- icon="install_desktop"
- loading={isApplyingClaudeAuthLocal}
- disabled={isApplyingClaudeAuthLocal}
- onClick={onApplyClaudeAuthLocal}
- className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
- title={applyClaudeAuthLabel}
- >
- {applyClaudeAuthLabel}
- </Button>
- )}
- {isClaude && onExportClaudeAuthFile && (
- <Button
- size="sm"
- variant="ghost"
- icon="download"
- loading={isExportingClaudeAuthFile}
- disabled={isExportingClaudeAuthFile}
- onClick={onExportClaudeAuthFile}
- className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
- title={exportClaudeAuthLabel}
- >
- {exportClaudeAuthLabel}
- </Button>
- )}
- {isGeminiCli && onApplyGeminiAuthLocal && (
- <Button
- size="sm"
- variant="ghost"
- icon="install_desktop"
- loading={isApplyingGeminiAuthLocal}
- disabled={isApplyingGeminiAuthLocal}
- onClick={onApplyGeminiAuthLocal}
- className="!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400"
- title={applyGeminiAuthLabel}
- >
- {applyGeminiAuthLabel}
- </Button>
- )}
- {isGeminiCli && onExportGeminiAuthFile && (
- <Button
- size="sm"
- variant="ghost"
- icon="download"
- loading={isExportingGeminiAuthFile}
- disabled={isExportingGeminiAuthFile}
- onClick={onExportGeminiAuthFile}
- className="!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400"
- title={exportGeminiAuthLabel}
- >
- {exportGeminiAuthLabel}
- </Button>
- )}
- <Toggle
- size="sm"
- checked={connection.isActive ?? true}
- onChange={onToggleActive}
- title={(connection.isActive ?? true) ? t("disableConnection") : t("enableConnection")}
- />
- <div className="flex gap-1 ml-1 transition-opacity">
- {onReauth && (
- <button
- onClick={onReauth}
- className="p-2 hover:bg-amber-500/10 rounded text-amber-600 hover:text-amber-500"
- title={t("reauthenticateConnection")}
- >
- <span className="material-symbols-outlined text-[18px]">passkey</span>
- </button>
- )}
- <button
- onClick={onEdit}
- className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary"
- title={t("edit")}
- >
- <span className="material-symbols-outlined text-[18px]">edit</span>
- </button>
- <button
- onClick={onProxy}
- className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary"
- title={t("proxyConfig")}
- >
- <span className="material-symbols-outlined text-[18px]">vpn_lock</span>
- </button>
- <button
- onClick={onDelete}
- className="p-2 hover:bg-red-500/10 rounded text-red-500"
- title={t("delete")}
- >
- <span className="material-symbols-outlined text-[18px]">delete</span>
- </button>
- </div>
- </div>
- </div>
- );
-}
-
-const CONFIGURABLE_BASE_URL_PROVIDERS = new Set([
- "azure-openai",
- "azure-ai",
- "bailian-coding-plan",
- "xiaomi-mimo",
- "siliconflow",
- "heroku",
- "databricks",
- "snowflake",
- "searxng-search",
- "petals",
-]);
-
-const DEFAULT_PROVIDER_BASE_URLS: Record<string, string> = {
- "azure-openai": "https://example-resource.openai.azure.com",
- "azure-ai": "https://example-resource.services.ai.azure.com/openai/v1",
- "bailian-coding-plan": "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",
- "xiaomi-mimo": "https://token-plan-sgp.xiaomimimo.com/v1",
- siliconflow: "https://api.siliconflow.com/v1",
- "searxng-search": "http://localhost:8888/search",
- petals: "https://chat.petals.dev/api/v1/generate",
-};
-
-function getLocalProviderMetadata(providerId?: string | null) {
- if (!providerId || !isSelfHostedChatProvider(providerId)) return null;
- return (LOCAL_PROVIDERS as Record<string, LocalProviderMetadata>)[providerId] || null;
-}
-
-function isBaseUrlConfigurableProvider(providerId?: string | null) {
- return Boolean(
- providerId &&
- (CONFIGURABLE_BASE_URL_PROVIDERS.has(providerId) || isSelfHostedChatProvider(providerId))
- );
-}
-
-function getProviderBaseUrlDefault(providerId?: string | null) {
- const localProvider = getLocalProviderMetadata(providerId);
- if (typeof localProvider?.localDefault === "string" && localProvider.localDefault.trim()) {
- return localProvider.localDefault;
- }
- return providerId ? DEFAULT_PROVIDER_BASE_URLS[providerId] || "" : "";
-}
-
-function getProviderBaseUrlHint(
- providerId?: string | null,
- t?: ((key: string, values?: Record<string, unknown>) => string) | null
-) {
- const localProvider = getLocalProviderMetadata(providerId);
- if (localProvider && t) {
- return t("localProviderBaseUrlHint", {
- provider: localProvider.name || providerId,
- baseUrl: getProviderBaseUrlDefault(providerId),
- });
- }
- switch (providerId) {
- case "azure-openai":
- return t ? t("azureOpenAiBaseUrlHint") : undefined;
- case "bailian-coding-plan":
- return t ? t("bailianBaseUrlHint") : undefined;
- case "xiaomi-mimo":
- return t ? t("xiaomiMimoBaseUrlHint") : undefined;
- case "heroku":
- return t ? t("herokuBaseUrlHint") : undefined;
- case "databricks":
- return t ? t("databricksBaseUrlHint") : undefined;
- case "snowflake":
- return t ? t("snowflakeBaseUrlHint") : undefined;
- case "searxng-search":
- return t ? t("searxngBaseUrlHint") : undefined;
- default:
- return undefined;
- }
-}
-
-function getProviderBaseUrlPlaceholder(providerId?: string | null) {
- if (isSelfHostedChatProvider(providerId || "")) {
- return getProviderBaseUrlDefault(providerId);
- }
- switch (providerId) {
- case "azure-openai":
- return "https://my-resource.openai.azure.com";
- case "bailian-coding-plan":
- case "xiaomi-mimo":
- return getProviderBaseUrlDefault(providerId);
- case "siliconflow":
- return "https://api.siliconflow.cn/v1";
- case "heroku":
- return "https://us.inference.heroku.com";
- case "databricks":
- return "https://adb-1234567890123456.7.azuredatabricks.net/serving-endpoints";
- case "snowflake":
- return "https://example-account.snowflakecomputing.com";
- case "searxng-search":
- return "http://localhost:8888/search";
- default:
- return "";
- }
-}
-
-function isGlmProvider(providerId?: string | null) {
- return providerId === "glm" || providerId === "glm-cn" || providerId === "glmt";
-}
-
-function parseRoutingTagsInput(value: string): string[] | undefined {
- const tags = Array.from(
- new Set(
- value
- .split(",")
- .map((tag) => tag.trim().toLowerCase())
- .filter(Boolean)
- )
- );
- return tags.length > 0 ? tags : undefined;
-}
-
-function parseExcludedModelsInput(value: string): string[] | undefined {
- const patterns = Array.from(
- new Set(
- value
- .split(",")
- .map((pattern) => pattern.trim())
- .filter(Boolean)
- )
- );
- return patterns.length > 0 ? patterns : undefined;
-}
-
-function formatRoutingTagsInput(value: unknown): string {
- if (!Array.isArray(value)) return "";
- return value
- .filter((tag): tag is string => typeof tag === "string" && tag.trim().length > 0)
- .join(", ");
-}
-
-function formatExcludedModelsInput(value: unknown): string {
- if (!Array.isArray(value)) return "";
- return value
- .filter(
- (pattern): pattern is string => typeof pattern === "string" && pattern.trim().length > 0
- )
- .join(", ");
-}
-
-function extractCommandCodeCredentialInput(value: string): string {
- const trimmed = value.trim();
- if (!trimmed) return "";
-
- try {
- const parsed = JSON.parse(trimmed) as unknown;
- if (parsed && typeof parsed === "object") {
- const record = parsed as Record<string, unknown>;
- const direct = record.apiKey || record.api_key || record.key || record.token;
- if (typeof direct === "string" && direct.trim()) return direct.trim();
- const nested = record.data;
- if (nested && typeof nested === "object") {
- const nestedRecord = nested as Record<string, unknown>;
- const nestedKey = nestedRecord.apiKey || nestedRecord.api_key || nestedRecord.key;
- if (typeof nestedKey === "string" && nestedKey.trim()) return nestedKey.trim();
- }
- }
- } catch {
- // Not JSON; continue with URL/raw parsing.
- }
-
- try {
- const url = new URL(trimmed);
- const key =
- url.searchParams.get("apiKey") ||
- url.searchParams.get("api_key") ||
- url.searchParams.get("key") ||
- url.searchParams.get("token");
- if (key?.trim()) return key.trim();
- const hash = url.hash.replace(/^#/, "");
- if (hash) {
- const hashParams = new URLSearchParams(hash);
- const hashKey =
- hashParams.get("apiKey") ||
- hashParams.get("api_key") ||
- hashParams.get("key") ||
- hashParams.get("token");
- if (hashKey?.trim()) return hashKey.trim();
- }
- } catch {
- // Not a URL; use the raw value.
- }
-
- return trimmed;
-}
-
-function SiliconFlowEndpointModal({
- isOpen,
- onSelect,
- onClose,
-}: {
- isOpen: boolean;
- onSelect: (baseUrl: string) => void;
- onClose: () => void;
-}) {
- const t = useTranslations("providers");
-
- return (
- <Modal
- isOpen={isOpen}
- title={providerText(t, "connectSiliconFlow", "Connect SiliconFlow")}
- onClose={onClose}
- size="lg"
- >
- <div className="space-y-3">
- <p className="text-sm text-text-muted mb-4">
- {providerText(t, "chooseSiliconFlowEndpoint", "Choose your SiliconFlow endpoint:")}
- </p>
- {SILICONFLOW_ENDPOINTS.map((endpoint) => (
- <button
- key={endpoint.id}
- type="button"
- onClick={() => onSelect(endpoint.baseUrl)}
- className="w-full p-4 text-left border border-border rounded-lg hover:bg-sidebar transition-colors"
- >
- <div className="flex items-start gap-3">
- <span className="material-symbols-outlined text-primary mt-0.5">public</span>
- <div className="flex-1">
- <h3 className="font-semibold mb-1">
- {providerText(
- t,
- endpoint.id === "siliconflow" ? "endpointGlobal" : "endpointChina",
- endpoint.label
- )}
- </h3>
- <p className="text-sm text-text-muted font-mono">{endpoint.baseUrl}</p>
- </div>
- </div>
- </button>
- ))}
- </div>
- </Modal>
- );
-}
-
-function AddApiKeyModal({
- isOpen,
- provider,
- providerName,
- initialBaseUrl,
- isCompatible,
- isAnthropic,
- isCcCompatible,
- isCommandCode,
- commandCodeAuthState,
- onStartCommandCodeAuth,
- onSave,
- onClose,
-}: AddApiKeyModalProps) {
- const t = useTranslations("providers");
- const usesBaseUrl = isBaseUrlConfigurableProvider(provider);
- const defaultBaseUrl = getProviderBaseUrlDefault(provider);
- const isVertex = provider === "vertex" || provider === "vertex-partner";
- const isBedrock = provider === "bedrock";
- const showsRegion = isVertex || isBedrock;
- const defaultRegion = isBedrock ? "eu-west-2" : "us-central1";
- const isGlm = isGlmProvider(provider);
- const isQoder = provider === "qoder";
- const isCloudflare = provider === "cloudflare-ai";
- const localProviderMetadata = getLocalProviderMetadata(provider);
- const isLocalSelfHostedProvider = !!localProviderMetadata;
- const isGooglePse = provider === "google-pse-search";
- const webSessionCredential = getWebSessionCredentialRequirement(provider);
- const isNoAuthWebSessionCredential = webSessionCredential?.kind === "none";
- const isWebSessionCredential = !!webSessionCredential && webSessionCredential.kind !== "none";
- const providerDisplayName = providerName || provider || "";
- const apiKeyOptional =
- providerAllowsOptionalApiKey(provider) || Boolean(isNoAuthWebSessionCredential);
- const commandCodeAuthPhaseLabel = commandCodeAuthState
- ? {
- idle: "Ready",
- starting: "Starting…",
- polling: "Waiting for browser…",
- received: "Browser approved",
- applying: "Applying key…",
- applied: "Connected",
- expired: "Link expired",
- error: "Connection failed",
- }[commandCodeAuthState.phase]
- : null;
-
- const [formData, setFormData] = useState({
- name: "",
- apiKey: "",
- priority: 1,
- baseUrl: initialBaseUrl || defaultBaseUrl,
- cx: "",
- region: showsRegion ? defaultRegion : "",
- apiRegion: "international",
- validationModelId: "",
- routingTags: "",
- excludedModels: "",
- customUserAgent: "",
- accountId: "",
- consoleApiKey: "",
- ccCompatibleContext1m: false,
- passthroughModels: false,
- });
- const [validating, setValidating] = useState(false);
- const [validationResult, setValidationResult] = useState(null);
- const [saving, setSaving] = useState(false);
- const [saveError, setSaveError] = useState<string | null>(null);
- const [showAdvanced, setShowAdvanced] = useState(false);
- const [copiedCommandCodeField, setCopiedCommandCodeField] = useState<string | null>(null);
- const wasOpenRef = useRef(false);
-
- useEffect(() => {
- const wasOpen = wasOpenRef.current;
- wasOpenRef.current = isOpen;
- if (!isOpen || wasOpen) return;
- setFormData((current) => ({
- ...current,
- baseUrl: initialBaseUrl || defaultBaseUrl,
- }));
- }, [defaultBaseUrl, initialBaseUrl, isOpen]);
-
- const bulkSupported = supportsBulkApiKey(provider);
- const [mode, setMode] = useState<"single" | "bulk">("single");
- const [bulkText, setBulkText] = useState("");
- const [bulkValidateKeys, setBulkValidateKeys] = useState(false);
- const [bulkResult, setBulkResult] = useState<{
- success: number;
- failed: number;
- total: number;
- errors: Array<{ index: number; name: string; message: string }>;
- } | null>(null);
- const [bulkWarnings, setBulkWarnings] = useState<string[]>([]);
- const apiCredentialLabel = isQoder
- ? t("personalAccessTokenLabel")
- : webSessionCredential
- ? getWebSessionCredentialLabel(t, webSessionCredential, apiKeyOptional)
- : apiKeyOptional
- ? `${t("apiKeyLabel")} (${t("optional").toLowerCase()})`
- : t("apiKeyLabel");
- const apiCredentialPlaceholder = isVertex
- ? t("vertexServiceAccountPlaceholder")
- : isWebSessionCredential
- ? webSessionCredential.placeholder
- : isQoder
- ? t("qoderPatPlaceholder")
- : apiKeyOptional
- ? t("optional")
- : undefined;
- const apiCredentialHint = isQoder
- ? t("qoderPatHint")
- : isWebSessionCredential
- ? getWebSessionCredentialHint(t, webSessionCredential, providerDisplayName, false)
- : isLocalSelfHostedProvider
- ? t("localProviderApiKeyOptionalHint", {
- provider: localProviderMetadata?.name || providerName || provider || "",
- })
- : apiKeyOptional
- ? t("apiKeyOptionalHint")
- : undefined;
- const credentialValidationFailedMessage = isWebSessionCredential
- ? providerText(
- t,
- "webSessionCredentialValidationFailed",
- "Session credential validation failed. Sign in again, copy a fresh credential, and try again."
- )
- : t("apiKeyValidationFailed");
-
- const handleValidate = async () => {
- setValidating(true);
- setSaveError(null);
- try {
- const credentialInput = isCommandCode
- ? extractCommandCodeCredentialInput(formData.apiKey)
- : formData.apiKey;
- const res = await fetch("/api/providers/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider,
- apiKey: credentialInput,
- validationModelId: formData.validationModelId || undefined,
- customUserAgent: formData.customUserAgent.trim() || undefined,
- baseUrl: formData.baseUrl.trim() || undefined,
- region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
- cx: formData.cx.trim() || undefined,
- }),
- });
- const data = await res.json();
- setValidationResult(data.valid ? "success" : "failed");
- } catch {
- setValidationResult("failed");
- } finally {
- setValidating(false);
- }
- };
-
- const copyCommandCodeValue = async (value: string | undefined, key: string) => {
- if (!value) return;
- try {
- await navigator.clipboard.writeText(value);
- setCopiedCommandCodeField(key);
- window.setTimeout(() => setCopiedCommandCodeField(null), 1500);
- } catch {
- setSaveError("Copy failed. Select the text and copy it manually.");
- }
- };
-
- const handleSubmit = async () => {
- const credentialInput = isCommandCode
- ? extractCommandCodeCredentialInput(formData.apiKey)
- : formData.apiKey;
- if (!provider || (!isCompatible && !apiKeyOptional && !credentialInput)) return;
-
- setSaving(true);
- setSaveError(null);
- try {
- if (isGooglePse && !formData.cx.trim()) {
- setSaveError(t("searchEngineIdRequired"));
- return;
- }
-
- let validatedBaseUrl = null;
- if (usesBaseUrl) {
- const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
- if (checked.error) {
- setSaveError(checked.error);
- return;
- }
- validatedBaseUrl = checked.value;
- }
-
- let isValid = Boolean(isNoAuthWebSessionCredential && !credentialInput);
- let validationError: string | null = null;
- if (!isValid) {
- try {
- setValidating(true);
- setValidationResult(null);
- const res = await fetch("/api/providers/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider,
- apiKey: credentialInput,
- validationModelId: formData.validationModelId || undefined,
- customUserAgent: formData.customUserAgent.trim() || undefined,
- baseUrl: formData.baseUrl.trim() || undefined,
- region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
- cx: formData.cx.trim() || undefined,
- }),
- });
- const data = await res.json();
- isValid = !!data.valid;
- if (!isValid && data.error) {
- validationError = data.error;
- }
- setValidationResult(isValid ? "success" : "failed");
- } catch {
- setValidationResult("failed");
- } finally {
- setValidating(false);
- }
- }
-
- if (!isValid) {
- if (apiKeyOptional && !credentialInput) {
- // Bypass validation block for local/optional providers when no key is provided
- console.debug("Validation failed but apiKey is optional; proceeding to save.");
- } else {
- setSaveError(validationError || credentialValidationFailedMessage);
- return;
- }
- }
-
- const providerSpecificData: Record<string, unknown> = {};
- if (formData.customUserAgent.trim()) {
- providerSpecificData.customUserAgent = formData.customUserAgent.trim();
- }
- if (formData.routingTags.trim()) {
- providerSpecificData.tags = parseRoutingTagsInput(formData.routingTags);
- }
- if (formData.excludedModels.trim()) {
- providerSpecificData.excludedModels = parseExcludedModelsInput(formData.excludedModels);
- }
- if (formData.passthroughModels) {
- providerSpecificData.passthroughModels = true;
- }
- if (provider === "bailian-coding-plan" && formData.consoleApiKey.trim()) {
- providerSpecificData.consoleApiKey = formData.consoleApiKey.trim();
- }
- if (isGooglePse && formData.cx.trim()) {
- providerSpecificData.cx = formData.cx.trim();
- }
- if (usesBaseUrl) {
- providerSpecificData.baseUrl = validatedBaseUrl;
- } else if (showsRegion) {
- providerSpecificData.region = formData.region.trim() || defaultRegion;
- } else if (isGlm) {
- providerSpecificData.apiRegion = formData.apiRegion;
- } else if (isCloudflare && formData.accountId.trim()) {
- providerSpecificData.accountId = formData.accountId.trim();
- }
- if (isCcCompatible && formData.ccCompatibleContext1m) {
- providerSpecificData.requestDefaults = { context1m: true };
- }
-
- const payload = {
- name: formData.name,
- apiKey: credentialInput.trim() || undefined,
- priority: formData.priority,
- testStatus: "active",
- providerSpecificData:
- Object.keys(providerSpecificData).length > 0 ? providerSpecificData : undefined,
- };
-
- const error = await onSave(payload);
- if (error) {
- setSaveError(typeof error === "string" ? error : t("failedSaveConnection"));
- }
- } finally {
- setSaving(false);
- }
- };
-
- const handleBulkSubmit = async () => {
- if (!provider) return;
- const parsed = parseBulkApiKeys(bulkText);
- setBulkWarnings(parsed.warnings);
- if (parsed.entries.length === 0) return;
-
- setSaving(true);
- setBulkResult(null);
- setSaveError(null);
-
- try {
- let providerSpecificData: Record<string, unknown> | undefined;
- if (usesBaseUrl) {
- const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
- if (checked.error) {
- setSaveError(checked.error);
- return;
- }
- providerSpecificData = { baseUrl: checked.value };
- }
-
- const res = await fetch("/api/providers/bulk", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider,
- entries: parsed.entries.map((e) => ({ name: e.name, apiKey: e.apiKey })),
- priority: formData.priority || 1,
- providerSpecificData,
- validateKeys: bulkValidateKeys,
- }),
- });
- const data = await res.json();
- if (!res.ok) {
- setSaveError(typeof data?.error === "string" ? data.error : t("failedSaveConnection"));
- return;
- }
- setBulkResult({
- success: data.success || 0,
- failed: data.failed || 0,
- total: data.total || 0,
- errors: Array.isArray(data.errors) ? data.errors : [],
- });
- } catch (err) {
- setSaveError(err instanceof Error ? err.message : t("failedSaveConnection"));
- } finally {
- setSaving(false);
- }
- };
-
- if (!provider) return null;
-
- return (
- <Modal
- isOpen={isOpen}
- title={getAddCredentialModalTitle(t, providerDisplayName, webSessionCredential)}
- onClose={onClose}
- >
- <div className="flex flex-col gap-4">
- {bulkSupported && (
- <div className="flex gap-1 border-b border-border">
- <button
- type="button"
- onClick={() => {
- setMode("single");
- setBulkResult(null);
- setBulkWarnings([]);
- }}
- className={`px-3 py-1.5 text-sm font-medium transition-colors ${
- mode === "single"
- ? "border-b-2 border-primary text-text-main"
- : "text-text-muted hover:text-text-main"
- }`}
- >
- {t("bulkTabSingle")}
- </button>
- <button
- type="button"
- onClick={() => {
- setMode("bulk");
- setSaveError(null);
- }}
- className={`px-3 py-1.5 text-sm font-medium transition-colors ${
- mode === "bulk"
- ? "border-b-2 border-primary text-text-main"
- : "text-text-muted hover:text-text-main"
- }`}
- >
- {t("bulkTabBulkAdd")}
- </button>
- </div>
- )}
-
- {bulkSupported && mode === "bulk" && (
- <div className="flex flex-col gap-3">
- <p className="text-xs text-text-muted">{t("bulkAddFormatHint")}</p>
- <textarea
- className="w-full rounded border border-border bg-background p-2 text-sm font-mono resize-y min-h-[140px] focus:outline-none focus:ring-1 focus:ring-primary"
- placeholder={"name1|sk-key1\nname2|sk-key2\nsk-key-only-auto-named"}
- value={bulkText}
- onChange={(e) => setBulkText(e.target.value)}
- />
- <div className="flex items-center gap-4 flex-wrap">
- <div className="flex items-center gap-2">
- <label className="text-sm text-text-muted">{t("priorityLabel")}</label>
- <input
- type="number"
- min={1}
- max={100}
- value={formData.priority}
- onChange={(e) =>
- setFormData({
- ...formData,
- priority: Number.parseInt(e.target.value) || 1,
- })
- }
- className="w-20 px-2 py-1 text-sm border border-border rounded bg-background"
- />
- </div>
- <label className="flex items-center gap-2 text-sm text-text-muted cursor-pointer">
- <input
- type="checkbox"
- checked={bulkValidateKeys}
- onChange={(e) => setBulkValidateKeys(e.target.checked)}
- className="rounded border-border"
- />
- {t("bulkValidateKeys")}
- </label>
- </div>
- {bulkWarnings.length > 0 && (
- <div className="rounded border border-amber-500/25 bg-amber-500/10 p-2 text-xs text-amber-200 space-y-1">
- {bulkWarnings.map((w, i) => (
- <div key={i}>{w}</div>
- ))}
- </div>
- )}
- {bulkResult && (
- <div
- className={`text-sm font-medium ${
- bulkResult.failed > 0 ? "text-amber-300" : "text-emerald-400"
- }`}
- >
- {t("bulkAddedCount", { count: bulkResult.success })}
- {bulkResult.failed > 0 && (
- <>, {t("bulkFailedCount", { count: bulkResult.failed })}</>
- )}
- {bulkResult.errors.length > 0 && (
- <ul className="mt-2 list-disc pl-5 text-xs text-text-muted font-normal space-y-0.5">
- {bulkResult.errors.slice(0, 10).map((err, i) => (
- <li key={i}>
- {err.name}: {err.message}
- </li>
- ))}
- {bulkResult.errors.length > 10 && (
- <li>… {bulkResult.errors.length - 10} more</li>
- )}
- </ul>
- )}
- </div>
- )}
- {saveError && <div className="text-sm text-rose-400">{saveError}</div>}
- <div className="flex gap-2">
- <Button onClick={handleBulkSubmit} fullWidth disabled={saving || !bulkText.trim()}>
- {saving ? t("adding") : t("bulkAddAllKeys")}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </div>
- )}
-
- {(!bulkSupported || mode === "single") && (
- <>
- {isCcCompatible && (
- <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
- warning
- </span>
- <p>{t("ccCompatibleValidationHint")}</p>
- </div>
- </div>
- )}
- {isCommandCode && onStartCommandCodeAuth && (
- <div className="rounded-lg border border-sky-500/20 bg-sky-500/10 px-3 py-3 text-sm">
- <div className="flex items-start gap-3">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-sky-500">
- open_in_new
- </span>
- <div className="min-w-0 flex-1">
- <p className="font-medium text-text-main">
- {t("providerDetailBrowserManualConnect")}
- </p>
- <p className="mt-1 text-xs text-text-muted">
- Open Command Code Studio, then paste the returned key/JSON/URL into the API
- key field below.
- </p>
- {commandCodeAuthState?.message && (
- <p className="mt-2 text-xs text-text-muted">
- {commandCodeAuthPhaseLabel}: {commandCodeAuthState.message}
- </p>
- )}
- {commandCodeAuthState?.authUrl && (
- <div className="mt-3 space-y-2">
- <div>
- <p className="mb-1 text-xs font-medium text-text-main">
- {t("providerDetailAuthUrl")}
- </p>
- <div className="flex gap-2">
- <Input
- value={commandCodeAuthState.authUrl}
- readOnly
- className="flex-1 font-mono text-xs"
- />
- <Button
- variant="ghost"
- size="sm"
- icon={copiedCommandCodeField === "authUrl" ? "check" : "content_copy"}
- onClick={() =>
- copyCommandCodeValue(commandCodeAuthState.authUrl, "authUrl")
- }
- />
- </div>
- </div>
- {commandCodeAuthState.callbackUrl && (
- <div>
- <p className="mb-1 text-xs font-medium text-text-main">
- {t("providerDetailCallbackUrl")}
- </p>
- <div className="flex gap-2">
- <Input
- value={commandCodeAuthState.callbackUrl}
- readOnly
- className="flex-1 font-mono text-xs"
- />
- <Button
- variant="ghost"
- size="sm"
- icon={
- copiedCommandCodeField === "callbackUrl"
- ? "check"
- : "content_copy"
- }
- onClick={() =>
- copyCommandCodeValue(
- commandCodeAuthState.callbackUrl,
- "callbackUrl"
- )
- }
- />
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- <Button
- variant="secondary"
- size="sm"
- icon="open_in_new"
- loading={
- commandCodeAuthState?.phase === "starting" ||
- commandCodeAuthState?.phase === "polling" ||
- commandCodeAuthState?.phase === "applying"
- }
- onClick={onStartCommandCodeAuth}
- >
- Connect in browser
- </Button>
- </div>
- </div>
- )}
- <Input
- label={t("nameLabel")}
- value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
- placeholder={isQoder ? t("personalAccessTokenLabel") : t("productionKey")}
- />
- {webSessionCredential && (
- <WebSessionCredentialGuide
- requirement={webSessionCredential}
- providerName={providerDisplayName}
- t={t}
- />
- )}
- {!isNoAuthWebSessionCredential && (
- <div className="flex gap-2">
- <Input
- label={apiCredentialLabel}
- type="password"
- value={formData.apiKey}
- onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
- className="flex-1"
- placeholder={apiCredentialPlaceholder}
- hint={apiCredentialHint}
- autoComplete="off"
- spellCheck={false}
- autoCapitalize="off"
- />
- <div className="pt-6">
- <Button
- onClick={handleValidate}
- disabled={
- (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
- (isGooglePse && !formData.cx.trim()) ||
- validating ||
- saving
- }
- variant="secondary"
- >
- {validating
- ? t("checking")
- : webSessionCredential
- ? getWebSessionCredentialCheckLabel(t, webSessionCredential)
- : t("check")}
- </Button>
- </div>
- </div>
- )}
- {isGooglePse && (
- <Input
- label={t("searchEngineIdLabel")}
- value={formData.cx}
- onChange={(e) => setFormData({ ...formData, cx: e.target.value })}
- placeholder="012345678901234567890:abc123xyz"
- hint={t("searchEngineIdHint")}
- />
- )}
- {validationResult && (
- <Badge variant={validationResult === "success" ? "success" : "error"}>
- {validationResult === "success" ? t("valid") : t("invalid")}
- </Badge>
- )}
- {saveError && (
- <div className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">
- {saveError}
- </div>
- )}
- {isCcCompatible && (
- <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- <Toggle
- checked={formData.ccCompatibleContext1m}
- onChange={(checked) =>
- setFormData({ ...formData, ccCompatibleContext1m: checked })
- }
- label={t("ccCompatibleContext1mLabel")}
- description={t("ccCompatibleContext1mDescription")}
- />
- </div>
- )}
- {isCompatible && !isCcCompatible && (
- <p className="text-xs text-text-muted">
- {isAnthropic
- ? t("validationChecksAnthropicCompatible", {
- provider: providerName || t("anthropicCompatibleName"),
- })
- : t("validationChecksOpenAiCompatible", {
- provider: providerName || t("openaiCompatibleName"),
- })}
- </p>
- )}
- <button
- type="button"
- className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
- onClick={() => setShowAdvanced(!showAdvanced)}
- aria-expanded={showAdvanced}
- aria-controls="add-api-key-advanced-settings"
- >
- <span
- className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
- aria-hidden="true"
- >
- ▶
- </span>
- {t("advancedSettings")}
- </button>
- {showAdvanced && (
- <div
- id="add-api-key-advanced-settings"
- className="flex flex-col gap-3 pl-2 border-l-2 border-border"
- >
- <Input
- label={t("customUserAgentLabel")}
- value={formData.customUserAgent}
- onChange={(e) => setFormData({ ...formData, customUserAgent: e.target.value })}
- placeholder="my-app/1.0"
- hint={t("customUserAgentHint")}
- />
- <Input
- label={t("routingTagsLabel")}
- value={formData.routingTags}
- onChange={(e) => setFormData({ ...formData, routingTags: e.target.value })}
- placeholder={t("routingTagsPlaceholder")}
- hint={t("routingTagsHint")}
- />
- <Input
- label={t("excludedModelsLabel")}
- value={formData.excludedModels}
- onChange={(e) => setFormData({ ...formData, excludedModels: e.target.value })}
- placeholder={t("excludedModelsPlaceholder")}
- hint={t("excludedModelsHint")}
- />
- <Toggle
- size="sm"
- checked={formData.passthroughModels}
- onChange={(checked) => setFormData({ ...formData, passthroughModels: checked })}
- label={t("perModelQuotaLabel")}
- description={t("perModelQuotaDescription")}
- />
- {provider === "bailian-coding-plan" && (
- <Input
- label={t("consoleApiKeyOracleLabel")}
- value={formData.consoleApiKey}
- onChange={(e) => setFormData({ ...formData, consoleApiKey: e.target.value })}
- placeholder={t("consoleApiKeyOraclePlaceholder")}
- hint={t("consoleApiKeyOracleHint")}
- type="password"
- />
- )}
- </div>
- )}
- <Input
- label={t("validationModelIdLabel")}
- placeholder={t("validationModelIdPlaceholder")}
- value={formData.validationModelId}
- onChange={(e) => setFormData({ ...formData, validationModelId: e.target.value })}
- hint={t("validationModelIdHint")}
- />
- <Input
- label={t("priorityLabel")}
- type="number"
- value={formData.priority}
- onChange={(e) =>
- setFormData({ ...formData, priority: Number.parseInt(e.target.value) || 1 })
- }
- />
- {usesBaseUrl && (
- <Input
- label={t("baseUrlLabel")}
- value={formData.baseUrl}
- onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
- placeholder={getProviderBaseUrlPlaceholder(provider)}
- hint={getProviderBaseUrlHint(provider, t)}
- />
- )}
- {showsRegion && (
- <Input
- label={t("regionLabel")}
- value={formData.region}
- onChange={(e) => setFormData({ ...formData, region: e.target.value })}
- placeholder={defaultRegion}
- hint={t("regionHint")}
- />
- )}
- {isCloudflare && (
- <Input
- label={t("accountIdLabel")}
- value={formData.accountId}
- onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
- placeholder={t("accountIdPlaceholder")}
- hint={t("accountIdHint")}
- />
- )}
- {isGlm && (
- <div>
- <label className="text-sm font-medium text-text-main mb-1 block">
- {t("apiRegionLabel")}
- </label>
- <select
- value={formData.apiRegion}
- onChange={(e) => setFormData({ ...formData, apiRegion: e.target.value })}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- >
- <option value="international">{t("apiRegionInternational")}</option>
- <option value="china">{t("apiRegionChina")}</option>
- </select>
- <p className="text-xs text-text-muted mt-1">{t("apiRegionHint")}</p>
- </div>
- )}
- <div className="flex gap-2">
- <Button
- onClick={handleSubmit}
- fullWidth
- disabled={
- !formData.name ||
- (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
- (isGooglePse && !formData.cx.trim()) ||
- saving ||
- (usesBaseUrl && !formData.baseUrl.trim() && !defaultBaseUrl)
- }
- >
- {saving ? t("saving") : t("save")}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </>
- )}
- </div>
- </Modal>
- );
-}
-
-// ──── ImportCodexAuthModal ────────────────────────────────────────────────────
-
-interface ImportCodexAuthModalProps {
- onClose: () => void;
- onSuccess: () => void;
-}
-
-type ImportTopTab = "single" | "bulk";
-type BulkSubMode = "upload" | "paste" | "zip";
-
-interface BulkEntry {
- name: string;
- json: unknown;
- parseError: string | null;
- email: string | null;
-}
-
-function extractEmailFromJwtLocal(idToken: string): string | null {
- try {
- const parts = idToken.split(".");
- if (parts.length !== 3) return null;
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
- return typeof payload.email === "string" ? payload.email : null;
- } catch {
- return null;
- }
-}
-
-function previewCodexJson(json: unknown): { valid: boolean; email: string | null } {
- try {
- const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
- // Codex CLI no longer writes auth_mode — accept both with and without it.
- // Only reject when auth_mode is explicitly set to something other than "chatgpt".
- if (
- !doc ||
- (doc.auth_mode !== undefined && doc.auth_mode !== null && doc.auth_mode !== "chatgpt")
- )
- return { valid: false, email: null };
- const tokens =
- doc.tokens && typeof doc.tokens === "object" ? (doc.tokens as Record<string, unknown>) : null;
- if (!tokens?.id_token || typeof tokens.id_token !== "string")
- return { valid: false, email: null };
- return { valid: true, email: extractEmailFromJwtLocal(tokens.id_token as string) };
- } catch {
- return { valid: false, email: null };
- }
-}
-
-function parseBulkPasteText(text: string): BulkEntry[] {
- const trimmed = text.trim();
- if (!trimmed) return [];
-
- const tryParse = (s: string): BulkEntry => {
- try {
- const json = JSON.parse(s);
- const { email } = previewCodexJson(json);
- return { name: email || "unknown", json, parseError: null, email };
- } catch {
- return { name: "parse error", json: null, parseError: "Invalid JSON", email: null };
- }
- };
-
- try {
- const arr = JSON.parse(trimmed);
- if (Array.isArray(arr))
- return arr.map((item) => {
- const { email } = previewCodexJson(item);
- return { name: email || "unknown", json: item, parseError: null, email };
- });
- const { email } = previewCodexJson(arr);
- return [{ name: email || "unknown", json: arr, parseError: null, email }];
- } catch {
- return trimmed
- .split(/^---$/m)
- .map((s) => tryParse(s.trim()))
- .filter((e) => e.json !== null || e.parseError !== null);
- }
-}
-
-function ImportCodexAuthModal({ onClose, onSuccess }: ImportCodexAuthModalProps) {
- const t = useTranslations("providers");
- const notify = useNotificationStore();
-
- // Top-level tab: Single / Bulk
- const [topTab, setTopTab] = useState<ImportTopTab>("single");
-
- // ── Single mode state ──
- const [singleTab, setSingleTab] = useState<"upload" | "paste">("upload");
- const [singleParsedJson, setSingleParsedJson] = useState<unknown>(null);
- const [singleParseError, setSingleParseError] = useState<string | null>(null);
- const [singleDetectedEmail, setSingleDetectedEmail] = useState<string | null>(null);
- const [singlePasteText, setSinglePasteText] = useState("");
- const [singleName, setSingleName] = useState("");
- const [singleEmail, setSingleEmail] = useState("");
- const [singleOverwrite, setSingleOverwrite] = useState(false);
- const [singleLoading, setSingleLoading] = useState(false);
- const [singleError, setSingleError] = useState<string | null>(null);
-
- // ── Bulk mode state ──
- const [bulkMode, setBulkMode] = useState<BulkSubMode>("upload");
- const [bulkEntries, setBulkEntries] = useState<BulkEntry[]>([]);
- const [bulkPasteText, setBulkPasteText] = useState("");
- const [bulkZipExtracting, setBulkZipExtracting] = useState(false);
- const [bulkZipError, setBulkZipError] = useState<string | null>(null);
- const [bulkOverwrite, setBulkOverwrite] = useState(false);
- const [bulkLoading, setBulkLoading] = useState(false);
- const [bulkResult, setBulkResult] = useState<{
- success: number;
- failed: number;
- errors: { index: number; name: string; message: string }[];
- } | null>(null);
-
- // ── Single helpers ──
-
- function handleSinglePreview(json: unknown) {
- setSingleParseError(null);
- setSingleDetectedEmail(null);
- setSingleParsedJson(null);
- const { valid, email } = previewCodexJson(json);
- if (!valid) {
- setSingleParseError(t("codexImportInvalidShape") || "Not a valid Codex auth.json");
- return;
- }
- setSingleDetectedEmail(email);
- if (email && !singleEmail) setSingleEmail(email);
- setSingleParsedJson(json);
- }
-
- function handleSingleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
- const file = e.target.files?.[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- handleSinglePreview(JSON.parse(ev.target?.result as string));
- } catch {
- setSingleParseError(t("codexImportInvalidJson") || "Could not parse JSON");
- }
- };
- reader.readAsText(file);
- }
-
- function handleSinglePasteChange(text: string) {
- setSinglePasteText(text);
- if (!text.trim()) {
- setSingleParsedJson(null);
- setSingleParseError(null);
- setSingleDetectedEmail(null);
- return;
- }
- try {
- handleSinglePreview(JSON.parse(text));
- } catch {
- setSingleParseError(t("codexImportInvalidJson") || "Could not parse JSON");
- setSingleParsedJson(null);
- }
- }
-
- async function handleSingleSubmit() {
- if (!singleParsedJson) return;
- setSingleLoading(true);
- setSingleError(null);
- try {
- const res = await fetch("/api/providers/codex-auth/import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- source: { kind: "json", json: singleParsedJson },
- name: singleName.trim() || undefined,
- email: singleEmail.trim() || undefined,
- overwriteExisting: singleOverwrite,
- }),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- setSingleError(
- data.code === "duplicate_account"
- ? t("codexImportDuplicate") ||
- "Account already exists — enable Replace existing to overwrite"
- : data.error || t("codexImportFailed") || "Failed to import"
- );
- return;
- }
- notify.success(t("codexImportSuccess") || "Codex connection imported successfully");
- onSuccess();
- } catch {
- setSingleError(t("codexImportFailed") || "Failed to import Codex auth");
- } finally {
- setSingleLoading(false);
- }
- }
-
- // ── Bulk helpers ──
-
- function handleBulkFilesChange(e: React.ChangeEvent<HTMLInputElement>) {
- const files = Array.from(e.target.files || []);
- const entries: BulkEntry[] = [];
- let pending = files.length;
- if (pending === 0) return;
- files.forEach((file) => {
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- const json = JSON.parse(ev.target?.result as string);
- const { email } = previewCodexJson(json);
- entries.push({
- name: email || file.name.replace(".json", ""),
- json,
- parseError: null,
- email,
- });
- } catch {
- entries.push({ name: file.name, json: null, parseError: "Invalid JSON", email: null });
- }
- if (--pending === 0) setBulkEntries([...entries]);
- };
- reader.readAsText(file);
- });
- }
-
- function handleBulkPasteChange(text: string) {
- setBulkPasteText(text);
- if (!text.trim()) {
- setBulkEntries([]);
- return;
- }
- setBulkEntries(parseBulkPasteText(text));
- }
-
- async function handleZipUpload(e: React.ChangeEvent<HTMLInputElement>) {
- const file = e.target.files?.[0];
- if (!file) return;
- setBulkZipExtracting(true);
- setBulkZipError(null);
- setBulkEntries([]);
- try {
- const res = await fetch("/api/providers/codex-auth/zip-extract", {
- method: "POST",
- headers: { "Content-Type": "application/octet-stream" },
- body: file,
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- setBulkZipError(data.error || t("codexImportBulkZipError") || "Failed to extract ZIP");
- return;
- }
- const extracted: BulkEntry[] = (data.entries || []).map(
- (entry: { name: string; json: unknown; parseError: string | null }) => {
- if (entry.parseError)
- return { name: entry.name, json: null, parseError: entry.parseError, email: null };
- const { email } = previewCodexJson(entry.json);
- return {
- name: email || entry.name.replace(".json", ""),
- json: entry.json,
- parseError: null,
- email,
- };
- }
- );
- setBulkEntries(extracted);
- } catch {
- setBulkZipError(t("codexImportBulkZipError") || "Failed to extract ZIP");
- } finally {
- setBulkZipExtracting(false);
- }
- }
-
- async function handleBulkSubmit() {
- const validEntries = bulkEntries.filter((e) => !e.parseError && e.json !== null);
- if (validEntries.length === 0) return;
- setBulkLoading(true);
- setBulkResult(null);
- try {
- const res = await fetch("/api/providers/codex-auth/import-bulk", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- entries: validEntries.map((e) => ({
- json: e.json,
- name: e.name || undefined,
- email: e.email || undefined,
- })),
- overwriteExisting: bulkOverwrite,
- }),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- notify.error(data.error || t("codexImportFailed") || "Failed to import");
- return;
- }
- setBulkResult({ success: data.success, failed: data.failed, errors: data.errors || [] });
- if (data.success > 0) onSuccess();
- } catch {
- notify.error(t("codexImportFailed") || "Failed to import Codex auth");
- } finally {
- setBulkLoading(false);
- }
- }
-
- const singleCanSubmit = !!singleParsedJson && !singleParseError && !singleLoading;
- const validBulkCount = bulkEntries.filter((e) => !e.parseError && e.json !== null).length;
- const bulkCanSubmit = validBulkCount > 0 && !bulkLoading && !bulkZipExtracting;
-
- const TOP_TABS: { id: ImportTopTab; label: string }[] = [
- { id: "single", label: t("codexImportTabSingle") || "Single" },
- { id: "bulk", label: t("codexImportTabBulk") || "Bulk" },
- ];
-
- const BULK_MODES: { id: BulkSubMode; label: string }[] = [
- { id: "upload", label: t("codexImportBulkModeUpload") || "Upload files" },
- { id: "paste", label: t("codexImportBulkModePaste") || "Paste list" },
- { id: "zip", label: t("codexImportBulkModeZip") || "ZIP archive" },
- ];
-
- return (
- <Modal
- isOpen
- onClose={onClose}
- title={t("codexImportModalTitle") || "Import Codex Auth"}
- maxWidth="max-w-lg"
- >
- <div className="flex flex-col gap-4">
- {/* Top-level Single / Bulk tabs */}
- <div className="flex border-b border-border">
- {TOP_TABS.map(({ id, label }) => (
- <button
- key={id}
- onClick={() => {
- setTopTab(id);
- setBulkResult(null);
- setSingleError(null);
- }}
- className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
- topTab === id
- ? "border-primary text-primary"
- : "border-transparent text-text-muted hover:text-text-main"
- }`}
- >
- {label}
- </button>
- ))}
- </div>
-
- {/* ── Single tab ── */}
- {topTab === "single" && (
- <>
- {/* Source sub-tabs */}
- <div className="flex border-b border-border">
- {(["upload", "paste"] as const).map((id) => (
- <button
- key={id}
- onClick={() => {
- setSingleTab(id);
- setSingleParsedJson(null);
- setSingleParseError(null);
- setSingleDetectedEmail(null);
- }}
- className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
- singleTab === id
- ? "border-primary text-primary"
- : "border-transparent text-text-muted hover:text-text-main"
- }`}
- >
- {id === "upload"
- ? t("codexImportTabUpload") || "Upload file"
- : t("codexImportTabPaste") || "Paste JSON"}
- </button>
- ))}
- </div>
-
- {singleTab === "upload" && (
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-text-main">
- {t("codexImportFileLabel") || "Choose auth.json"}
- </label>
- <input
- type="file"
- accept=".json"
- onChange={handleSingleFileChange}
- className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer"
- />
- <p className="text-xs text-text-muted">
- {t("codexImportFileHint") ||
- "Select the auth.json file exported from Codex or OmniRoute."}
- </p>
- </div>
- )}
-
- {singleTab === "paste" && (
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-text-main">
- {t("codexImportPasteLabel") || "Paste the JSON content"}
- </label>
- <textarea
- value={singlePasteText}
- onChange={(e) => handleSinglePasteChange(e.target.value)}
- rows={7}
- placeholder='{ "auth_mode": "chatgpt", ... }'
- className="w-full rounded-lg border border-border bg-bg-subtle px-3 py-2 text-xs font-mono text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40 resize-none"
- />
- </div>
- )}
-
- {singleParseError && <p className="text-sm text-red-500">{singleParseError}</p>}
- {singleDetectedEmail && !singleParseError && (
- <p className="text-xs text-text-muted">
- {t("codexImportDetectedEmail", { email: singleDetectedEmail }) ||
- `Detected: ${singleDetectedEmail}`}
- </p>
- )}
-
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-1">
- <label className="text-sm font-medium text-text-main">
- {t("codexImportEmailLabel") || "Account email"}
- </label>
- <input
- type="email"
- value={singleEmail}
- onChange={(e) => setSingleEmail(e.target.value)}
- placeholder="[email protected]"
- className="rounded-lg border border-border bg-bg-subtle px-3 py-2 text-sm text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40"
- />
- <p className="text-xs text-text-muted">
- {t("codexImportEmailHint") || "Auto-detected from the file; edit if needed."}
- </p>
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-sm font-medium text-text-main">
- {t("codexImportNameLabel") || "Connection name (optional)"}
- </label>
- <input
- type="text"
- value={singleName}
- onChange={(e) => setSingleName(e.target.value)}
- placeholder={singleEmail || "Codex (imported)"}
- className="rounded-lg border border-border bg-bg-subtle px-3 py-2 text-sm text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40"
- />
- </div>
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={singleOverwrite}
- onChange={(e) => setSingleOverwrite(e.target.checked)}
- className="rounded border-border"
- />
- <span className="text-sm text-text-main">
- {t("codexImportOverwriteLabel") ||
- "Replace existing connection if account already exists"}
- </span>
- </label>
- </div>
-
- {singleError && (
- <div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3 text-sm text-red-400">
- {singleError}
- </div>
- )}
-
- <div className="flex gap-2 pt-1">
- <Button
- onClick={handleSingleSubmit}
- disabled={!singleCanSubmit}
- loading={singleLoading}
- fullWidth
- >
- {t("codexImportSubmit") || "Import"}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </>
- )}
-
- {/* ── Bulk tab ── */}
- {topTab === "bulk" && (
- <>
- {/* Sub-mode selector */}
- <div className="flex gap-1 p-1 bg-bg-subtle rounded-lg">
- {BULK_MODES.map(({ id, label }) => (
- <button
- key={id}
- onClick={() => {
- setBulkMode(id);
- setBulkEntries([]);
- setBulkZipError(null);
- setBulkPasteText("");
- setBulkResult(null);
- }}
- className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
- bulkMode === id
- ? "bg-bg-primary text-text-main shadow-sm"
- : "text-text-muted hover:text-text-main"
- }`}
- >
- {label}
- </button>
- ))}
- </div>
-
- {/* Upload mode */}
- {bulkMode === "upload" && (
- <div className="flex flex-col gap-2">
- <input
- type="file"
- accept=".json"
- multiple
- onChange={handleBulkFilesChange}
- className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer"
- />
- <p className="text-xs text-text-muted">
- {t("codexImportBulkUploadHint") || "Select multiple .json files"}
- </p>
- </div>
- )}
-
- {/* Paste mode */}
- {bulkMode === "paste" && (
- <div className="flex flex-col gap-2">
- <textarea
- value={bulkPasteText}
- onChange={(e) => handleBulkPasteChange(e.target.value)}
- rows={7}
- placeholder={'[{ "auth_mode": "chatgpt", ... }, ...]'}
- className="w-full rounded-lg border border-border bg-bg-subtle px-3 py-2 text-xs font-mono text-text-main placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/40 resize-none"
- />
- <p className="text-xs text-text-muted">
- {t("codexImportBulkPasteHint") || "JSON array or multiple JSONs separated by ---"}
- </p>
- </div>
- )}
-
- {/* ZIP mode */}
- {bulkMode === "zip" && (
- <div className="flex flex-col gap-2">
- <input
- type="file"
- accept=".zip"
- onChange={handleZipUpload}
- disabled={bulkZipExtracting}
- className="text-sm text-text-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-border file:text-xs file:bg-bg-subtle file:text-text-main hover:file:bg-bg-hover cursor-pointer disabled:opacity-50"
- />
- {bulkZipExtracting && (
- <p className="text-xs text-text-muted animate-pulse">
- {t("codexImportBulkZipExtracting") || "Extracting ZIP…"}
- </p>
- )}
- {bulkZipError && <p className="text-sm text-red-500">{bulkZipError}</p>}
- <p className="text-xs text-text-muted">
- {t("codexImportBulkZipHint") ||
- "Upload a .zip containing auth.json files (max 50 files, 10 MB)"}
- </p>
- </div>
- )}
-
- {/* Entry preview list */}
- {bulkEntries.length > 0 && !bulkResult && (
- <div className="flex flex-col gap-1 max-h-40 overflow-y-auto rounded-lg border border-border bg-bg-subtle p-2">
- <p className="text-xs font-medium text-text-muted px-1">
- {validBulkCount} / {bulkEntries.length} valid
- </p>
- {bulkEntries.map((entry, i) => (
- <div key={i} className="flex items-center gap-2 px-2 py-1 rounded">
- <span
- className={`material-symbols-outlined text-[14px] ${entry.parseError ? "text-red-500" : "text-emerald-500"}`}
- >
- {entry.parseError ? "error" : "check_circle"}
- </span>
- <span className="text-xs text-text-main flex-1 truncate">{entry.name}</span>
- {entry.parseError && (
- <span className="text-xs text-red-400">{entry.parseError}</span>
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* Overwrite checkbox */}
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={bulkOverwrite}
- onChange={(e) => setBulkOverwrite(e.target.checked)}
- className="rounded border-border"
- />
- <span className="text-sm text-text-main">
- {t("codexImportOverwriteLabel") ||
- "Replace existing connections if accounts already exist"}
- </span>
- </label>
-
- {/* Result panel */}
- {bulkResult && (
- <div
- className={`rounded-lg border px-4 py-3 text-sm ${
- bulkResult.failed === 0
- ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400"
- : "bg-amber-500/10 border-amber-500/20 text-amber-400"
- }`}
- >
- <p className="font-medium">
- {bulkResult.success}{" "}
- {t("codexImportBulkSuccess", { count: bulkResult.success }) || "imported"} ·{" "}
- {bulkResult.failed}{" "}
- {t("codexImportBulkFailed", { count: bulkResult.failed }) || "failed"}
- </p>
- {bulkResult.errors.length > 0 && (
- <ul className="mt-2 space-y-0.5 text-xs">
- {bulkResult.errors.map((e, i) => (
- <li key={i}>
- <span className="font-medium">{e.name}:</span> {e.message}
- </li>
- ))}
- </ul>
- )}
- </div>
- )}
-
- <div className="flex gap-2 pt-1">
- <Button
- onClick={handleBulkSubmit}
- disabled={!bulkCanSubmit}
- loading={bulkLoading}
- fullWidth
- >
- {bulkLoading
- ? t("saving") || "Importing…"
- : typeof t.has === "function" && t.has("codexImportBulkSubmit")
- ? t("codexImportBulkSubmit", { count: validBulkCount })
- : `Import ${validBulkCount} accounts`}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </>
- )}
- </div>
- </Modal>
- );
-}
-
-function ApplyCodexAuthModal({
- connectionId,
- inProgress,
- onConfirm,
- onClose,
-}: {
- connectionId: string | null;
- inProgress: boolean;
- onConfirm: (id: string) => Promise<void>;
- onClose: () => void;
-}) {
- const t = useTranslations("providers");
- // `key`-reset pattern: caller re-mounts the modal each open (different
- // connectionId triggers a new instance), so local confirmation state is
- // naturally fresh without any post-render bookkeeping.
- const [confirmed, setConfirmed] = useState(false);
- const isOpen = !!connectionId;
-
- if (!connectionId) return null;
-
- const title =
- typeof t.has === "function" && t.has("codexApplyModalTitle")
- ? t("codexApplyModalTitle")
- : "Apply to Local Codex";
- const targetLabel =
- typeof t.has === "function" && t.has("codexApplyTargetLabel")
- ? t("codexApplyTargetLabel")
- : "Target path";
- const backupLabel =
- typeof t.has === "function" && t.has("codexApplyBackupLabel")
- ? t("codexApplyBackupLabel")
- : "Backups";
- const warning =
- typeof t.has === "function" && t.has("codexApplyWarning")
- ? t("codexApplyWarning")
- : "This will replace the existing auth.json. Continue?";
- const confirmText =
- typeof t.has === "function" && t.has("codexApplyConfirmCheckbox")
- ? t("codexApplyConfirmCheckbox")
- : "I confirm I want to replace the existing auth.json";
- const applyText = typeof t.has === "function" && t.has("codexApply") ? t("codexApply") : "Apply";
-
- return (
- <Modal isOpen={isOpen} title={title} onClose={onClose}>
- <div className="flex flex-col gap-4">
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
- <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
- ~/.codex/auth.json
- </code>
- <p className="mt-1 text-xs text-text-muted">{t("providerDetailPathAutoDetectedAllOs")}</p>
- </div>
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
- <ul className="text-xs text-text-muted space-y-0.5 list-disc pl-4">
- <li>
- <code className="text-text-main">~/.codex/auth-&lt;timestamp&gt;.bak</code> — quick
- local rollback
- </li>
- <li>Centralized backup history (audit trail)</li>
- </ul>
- </div>
- <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-amber-200">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
- warning
- </span>
- <span>{warning}</span>
- </div>
- </div>
- <label className="flex items-center gap-2 text-sm text-text-muted cursor-pointer">
- <input
- type="checkbox"
- checked={confirmed}
- onChange={(e) => setConfirmed(e.target.checked)}
- className="rounded border-border"
- />
- {confirmText}
- </label>
- <div className="flex gap-2">
- <Button
- onClick={() => void onConfirm(connectionId)}
- fullWidth
- disabled={!confirmed || inProgress}
- >
- {inProgress ? t("saving") : applyText}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth disabled={inProgress}>
- {t("cancel")}
- </Button>
- </div>
- </div>
- </Modal>
- );
-}
-
-// ──── ImportClaudeAuthModal ────────────────────────────────────────────────────
-
-interface ImportClaudeAuthModalProps {
- onClose: () => void;
- onSuccess: () => void;
-}
-
-type ClaudeImportTopTab = "single" | "bulk";
-type ClaudeBulkSubMode = "upload" | "paste" | "zip";
-
-interface ClaudeBulkEntry {
- name: string;
- json: unknown;
- parseError: string | null;
- email: string | null;
-}
-
-function extractEmailFromClaudeJson(json: unknown): string | null {
- try {
- const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
- if (!doc) return null;
- const oauth =
- doc.claudeAiOauth && typeof doc.claudeAiOauth === "object"
- ? (doc.claudeAiOauth as Record<string, unknown>)
- : null;
- if (!oauth) return null;
- return null; // email comes from bootstrap, not the file
- } catch {
- return null;
- }
-}
-
-function previewClaudeJson(json: unknown): { valid: boolean; email: string | null } {
- try {
- const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
- if (!doc) return { valid: false, email: null };
- const oauth =
- doc.claudeAiOauth && typeof doc.claudeAiOauth === "object"
- ? (doc.claudeAiOauth as Record<string, unknown>)
- : null;
- if (!oauth || !oauth.accessToken || !oauth.refreshToken) return { valid: false, email: null };
- return { valid: true, email: null };
- } catch {
- return { valid: false, email: null };
- }
-}
-
-function ImportClaudeAuthModal({ onClose, onSuccess }: ImportClaudeAuthModalProps) {
- const t = useTranslations("providers");
- const notify = useNotificationStore();
-
- const [topTab, setTopTab] = useState<ClaudeImportTopTab>("single");
- const [singleSubTab, setSingleSubTab] = useState<"upload" | "paste">("upload");
- const [bulkSubMode, setBulkSubMode] = useState<ClaudeBulkSubMode>("upload");
-
- // Single
- const [singleJson, setSingleJson] = useState<unknown>(null);
- const [singlePasteText, setSinglePasteText] = useState("");
- const [singleName, setSingleName] = useState("");
- const [singleEmail, setSingleEmail] = useState("");
- const [overwriteExisting, setOverwriteExisting] = useState(false);
- const [submitting, setSubmitting] = useState(false);
-
- // Bulk
- const [bulkEntries, setBulkEntries] = useState<ClaudeBulkEntry[]>([]);
- const [bulkPasteText, setBulkPasteText] = useState("");
- const [bulkSubmitting, setBulkSubmitting] = useState(false);
- const [bulkErrors, setBulkErrors] = useState<{ index: number; name: string; message: string }[]>(
- []
- );
- const [bulkResult, setBulkResult] = useState<{
- success: number;
- failed: number;
- total: number;
- } | null>(null);
- const [zipExtracting, setZipExtracting] = useState(false);
-
- const handleSingleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- const json = JSON.parse(ev.target?.result as string);
- setSingleJson(json);
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportInvalidJson")
- ? t("claudeImportInvalidJson")
- : "Could not parse the file as JSON"
- );
- }
- };
- reader.readAsText(file);
- };
-
- const handleSingleSubmit = async () => {
- if (submitting) return;
- setSubmitting(true);
- try {
- let rawJson: unknown;
- if (singleSubTab === "upload") {
- rawJson = singleJson;
- } else {
- try {
- rawJson = JSON.parse(singlePasteText);
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportInvalidJson")
- ? t("claudeImportInvalidJson")
- : "Could not parse the pasted content as JSON"
- );
- return;
- }
- }
-
- const body =
- singleSubTab === "paste"
- ? {
- source: { kind: "text", text: singlePasteText },
- name: singleName || undefined,
- email: singleEmail || undefined,
- overwriteExisting,
- }
- : {
- source: { kind: "json", json: rawJson },
- name: singleName || undefined,
- email: singleEmail || undefined,
- overwriteExisting,
- };
-
- const res = await fetch("/api/providers/claude-auth/import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
-
- const data = await res.json().catch(() => ({}));
-
- if (!res.ok) {
- if (data.code === "duplicate_account") {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportDuplicate")
- ? t("claudeImportDuplicate")
- : 'Account already exists — enable "Replace existing" to overwrite'
- );
- } else if (data.code === "identity_unverified") {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportIdentityUnverified")
- ? t("claudeImportIdentityUnverified")
- : 'Bootstrap could not verify the account. Enable "Replace existing" or provide an email.'
- );
- } else {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("claudeImportFailed")
- ? t("claudeImportFailed")
- : "Failed to import Claude auth")
- );
- }
- return;
- }
-
- notify.success(
- typeof t.has === "function" && t.has("claudeImportSuccess")
- ? t("claudeImportSuccess")
- : "Claude connection imported successfully"
- );
- onSuccess();
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportFailed")
- ? t("claudeImportFailed")
- : "Failed to import Claude auth"
- );
- } finally {
- setSubmitting(false);
- }
- };
-
- const handleBulkFilesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const files = Array.from(e.target.files || []);
- const newEntries: ClaudeBulkEntry[] = [];
- let pending = files.length;
- if (!pending) return;
- files.forEach((file) => {
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- const json = JSON.parse(ev.target?.result as string);
- const email = extractEmailFromClaudeJson(json);
- newEntries.push({
- name: file.name.replace(/\.json$/, ""),
- json,
- parseError: null,
- email,
- });
- } catch {
- newEntries.push({
- name: file.name,
- json: null,
- parseError: "Not valid JSON",
- email: null,
- });
- }
- pending--;
- if (pending === 0) setBulkEntries((prev) => [...prev, ...newEntries]);
- };
- reader.readAsText(file);
- });
- };
-
- const handleBulkPasteChange = (text: string) => {
- setBulkPasteText(text);
- const trimmed = text.trim();
- if (!trimmed) {
- setBulkEntries([]);
- return;
- }
- try {
- const arr = JSON.parse(trimmed);
- if (Array.isArray(arr)) {
- setBulkEntries(
- arr.map((item, i) => ({
- name: `entry ${i + 1}`,
- json: item,
- parseError: null,
- email: null,
- }))
- );
- } else {
- setBulkEntries([{ name: "entry 1", json: arr, parseError: null, email: null }]);
- }
- } catch {
- setBulkEntries([
- { name: "parse error", json: null, parseError: "Invalid JSON", email: null },
- ]);
- }
- };
-
- const handleZipUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- setZipExtracting(true);
- try {
- const res = await fetch("/api/providers/claude-auth/zip-extract", {
- method: "POST",
- headers: { "Content-Type": "application/zip" },
- body: file,
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("claudeImportBulkZipError")
- ? t("claudeImportBulkZipError")
- : "Failed to extract ZIP")
- );
- return;
- }
- const entries: ClaudeBulkEntry[] = (data.entries || []).map(
- (e: { name: string; json: unknown; parseError: string | null }) => ({
- name: e.name,
- json: e.json,
- parseError: e.parseError,
- email: null,
- })
- );
- setBulkEntries(entries);
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportBulkZipError")
- ? t("claudeImportBulkZipError")
- : "Failed to extract ZIP"
- );
- } finally {
- setZipExtracting(false);
- }
- };
-
- const handleBulkSubmit = async () => {
- if (bulkSubmitting) return;
- setBulkSubmitting(true);
- setBulkErrors([]);
- setBulkResult(null);
- try {
- const validEntries = bulkEntries.filter((e) => e.json !== null);
- if (validEntries.length === 0) {
- notify.error("No valid entries to import");
- return;
- }
- const res = await fetch("/api/providers/claude-auth/import-bulk", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- entries: validEntries.map((e) => ({
- json: e.json,
- name: e.name,
- email: e.email || undefined,
- })),
- overwriteExisting,
- }),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("claudeImportBulkFailed")
- ? t("claudeImportBulkFailed")
- : "Some entries failed to import")
- );
- return;
- }
- setBulkResult({ success: data.success, failed: data.failed, total: data.total });
- if (data.errors?.length > 0) setBulkErrors(data.errors);
- if (data.success > 0) {
- notify.success(
- typeof t.has === "function" && t.has("claudeImportBulkSuccess")
- ? t("claudeImportBulkSuccess", { count: data.success })
- : `Imported ${data.success} Claude connections`
- );
- if (data.failed === 0) onSuccess();
- }
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("claudeImportBulkFailed")
- ? t("claudeImportBulkFailed")
- : "Some entries failed to import"
- );
- } finally {
- setBulkSubmitting(false);
- }
- };
-
- const tabLabels: Record<ClaudeImportTopTab, string> = {
- single:
- typeof t.has === "function" && t.has("claudeImportTabSingle")
- ? t("claudeImportTabSingle")
- : "Single",
- bulk:
- typeof t.has === "function" && t.has("claudeImportTabBulk")
- ? t("claudeImportTabBulk")
- : "Bulk",
- };
-
- const modalTitle =
- typeof t.has === "function" && t.has("claudeImportModalTitle")
- ? t("claudeImportModalTitle")
- : "Import Claude Auth";
-
- return (
- <Modal isOpen onClose={onClose} title={modalTitle}>
- <div className="flex flex-col gap-4">
- {/* Top tabs */}
- <div className="flex gap-1 border-b border-border pb-0">
- {(["single", "bulk"] as ClaudeImportTopTab[]).map((tab) => (
- <button
- key={tab}
- onClick={() => setTopTab(tab)}
- className={`px-3 py-1.5 text-sm rounded-t-md transition-colors ${
- topTab === tab
- ? "bg-primary/10 text-primary border-b-2 border-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {tabLabels[tab]}
- </button>
- ))}
- </div>
-
- {topTab === "single" && (
- <div className="flex flex-col gap-3">
- {/* Sub-tabs */}
- <div className="flex gap-1">
- {(["upload", "paste"] as const).map((sub) => (
- <button
- key={sub}
- onClick={() => setSingleSubTab(sub)}
- className={`px-2 py-1 text-xs rounded transition-colors ${
- singleSubTab === sub
- ? "bg-bg-subtle text-text-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {sub === "upload"
- ? typeof t.has === "function" && t.has("claudeImportTabUpload")
- ? t("claudeImportTabUpload")
- : "Upload file"
- : typeof t.has === "function" && t.has("claudeImportTabPaste")
- ? t("claudeImportTabPaste")
- : "Paste JSON"}
- </button>
- ))}
- </div>
- {singleSubTab === "upload" ? (
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportFileLabel")
- ? t("claudeImportFileLabel")
- : "Choose .credentials.json"}
- </label>
- <input
- type="file"
- accept=".json"
- onChange={handleSingleFileChange}
- className="block w-full text-sm"
- />
- {singleJson && previewClaudeJson(singleJson).valid && (
- <p className="mt-1 text-xs text-emerald-500">
- {t("providerDetailValidClaudeCredentialsFile")}
- </p>
- )}
- {singleJson && !previewClaudeJson(singleJson).valid && (
- <p className="mt-1 text-xs text-red-500">
- {typeof t.has === "function" && t.has("claudeImportInvalidShape")
- ? t("claudeImportInvalidShape")
- : "The file is not a valid .credentials.json"}
- </p>
- )}
- </div>
- ) : (
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportPasteLabel")
- ? t("claudeImportPasteLabel")
- : "Paste the JSON content"}
- </label>
- <textarea
- value={singlePasteText}
- onChange={(e) => setSinglePasteText(e.target.value)}
- rows={6}
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
- placeholder='{ "claudeAiOauth": { ... } }'
- />
- </div>
- )}
- <div className="grid grid-cols-2 gap-2">
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportEmailLabel")
- ? t("claudeImportEmailLabel")
- : "Account email"}
- </label>
- <input
- type="email"
- value={singleEmail}
- onChange={(e) => setSingleEmail(e.target.value)}
- placeholder="auto-detected"
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
- />
- </div>
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportNameLabel")
- ? t("claudeImportNameLabel")
- : "Connection name (optional)"}
- </label>
- <input
- type="text"
- value={singleName}
- onChange={(e) => setSingleName(e.target.value)}
- placeholder="My Claude account"
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
- />
- </div>
- </div>
- <label className="flex items-center gap-2 text-xs text-text-muted">
- <input
- type="checkbox"
- checked={overwriteExisting}
- onChange={(e) => setOverwriteExisting(e.target.checked)}
- />
- {typeof t.has === "function" && t.has("claudeImportOverwriteLabel")
- ? t("claudeImportOverwriteLabel")
- : "Replace existing connection if account already exists"}
- </label>
- <Button
- loading={submitting}
- onClick={handleSingleSubmit}
- disabled={singleSubTab === "upload" ? !singleJson : !singlePasteText.trim()}
- >
- {typeof t.has === "function" && t.has("claudeImportSubmit")
- ? t("claudeImportSubmit")
- : "Import"}
- </Button>
- </div>
- )}
-
- {topTab === "bulk" && (
- <div className="flex flex-col gap-3">
- {/* Sub-mode tabs */}
- <div className="flex gap-1">
- {(["upload", "paste", "zip"] as ClaudeBulkSubMode[]).map((mode) => (
- <button
- key={mode}
- onClick={() => {
- setBulkSubMode(mode);
- setBulkEntries([]);
- }}
- className={`px-2 py-1 text-xs rounded transition-colors ${
- bulkSubMode === mode
- ? "bg-bg-subtle text-text-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {mode === "upload"
- ? typeof t.has === "function" && t.has("claudeImportBulkModeUpload")
- ? t("claudeImportBulkModeUpload")
- : "Upload files"
- : mode === "paste"
- ? typeof t.has === "function" && t.has("claudeImportBulkModePaste")
- ? t("claudeImportBulkModePaste")
- : "Paste JSON array"
- : typeof t.has === "function" && t.has("claudeImportBulkModeZip")
- ? t("claudeImportBulkModeZip")
- : "Upload ZIP"}
- </button>
- ))}
- </div>
-
- {bulkSubMode === "upload" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportBulkUploadHint")
- ? t("claudeImportBulkUploadHint")
- : "Drop or pick up to 50 .credentials.json files (256KB each, 10MB total)."}
- </p>
- <input
- type="file"
- accept=".json"
- multiple
- onChange={handleBulkFilesChange}
- className="block w-full text-sm"
- />
- </div>
- )}
- {bulkSubMode === "paste" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportBulkPasteHint")
- ? t("claudeImportBulkPasteHint")
- : "Paste an array of objects: [{ json, name?, email? }, ...]"}
- </p>
- <textarea
- value={bulkPasteText}
- onChange={(e) => handleBulkPasteChange(e.target.value)}
- rows={6}
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
- placeholder="[{ ... }, { ... }]"
- />
- </div>
- )}
- {bulkSubMode === "zip" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("claudeImportBulkZipHint")
- ? t("claudeImportBulkZipHint")
- : "ZIP containing .json entries. Max 50 entries, 10MB unpacked."}
- </p>
- {zipExtracting ? (
- <p className="text-xs text-primary animate-pulse">
- {typeof t.has === "function" && t.has("claudeImportBulkZipExtracting")
- ? t("claudeImportBulkZipExtracting")
- : "Extracting ZIP…"}
- </p>
- ) : (
- <input
- type="file"
- accept=".zip"
- onChange={handleZipUpload}
- className="block w-full text-sm"
- />
- )}
- </div>
- )}
-
- {bulkEntries.length > 0 && (
- <div className="rounded border border-border bg-bg-subtle px-2 py-1.5 max-h-36 overflow-y-auto">
- {bulkEntries.map((e, i) => (
- <div
- key={i}
- className={`text-xs py-0.5 flex items-center gap-1 ${e.parseError ? "text-red-500" : "text-text-main"}`}
- >
- <span className="material-symbols-outlined text-[12px]">
- {e.parseError ? "error" : "check_circle"}
- </span>
- {e.name}
- {e.email ? ` (${e.email})` : ""}
- {e.parseError ? ` — ${e.parseError}` : ""}
- </div>
- ))}
- </div>
- )}
-
- <label className="flex items-center gap-2 text-xs text-text-muted">
- <input
- type="checkbox"
- checked={overwriteExisting}
- onChange={(e) => setOverwriteExisting(e.target.checked)}
- />
- {typeof t.has === "function" && t.has("claudeImportOverwriteLabel")
- ? t("claudeImportOverwriteLabel")
- : "Replace existing connection if account already exists"}
- </label>
-
- {bulkResult && (
- <div className="rounded bg-bg-subtle px-2 py-1.5 text-xs">
- {bulkResult.success}/{bulkResult.total} imported
- {bulkResult.failed > 0 ? `, ${bulkResult.failed} failed` : ""}
- </div>
- )}
- {bulkErrors.length > 0 && (
- <div className="rounded border border-red-500/30 bg-red-500/5 px-2 py-1.5 max-h-28 overflow-y-auto">
- {bulkErrors.map((e) => (
- <div key={e.index} className="text-xs text-red-500 py-0.5">
- {e.name}: {e.message}
- </div>
- ))}
- </div>
- )}
-
- <Button
- loading={bulkSubmitting}
- onClick={handleBulkSubmit}
- disabled={bulkEntries.filter((e) => e.json !== null).length === 0}
- >
- {typeof t.has === "function" && t.has("claudeImportBulkSubmit")
- ? t("claudeImportBulkSubmit")
- : "Import all"}
- </Button>
- </div>
- )}
- </div>
- </Modal>
- );
-}
-
-// ──── ApplyClaudeAuthModal ────────────────────────────────────────────────────
-
-function ApplyClaudeAuthModal({
- connectionId,
- inProgress,
- onConfirm,
- onClose,
-}: {
- connectionId: string | null;
- inProgress: boolean;
- onConfirm: (id: string) => Promise<void>;
- onClose: () => void;
-}) {
- const t = useTranslations("providers");
- const [confirmed, setConfirmed] = useState(false);
- const isOpen = !!connectionId;
-
- if (!connectionId) return null;
-
- const title =
- typeof t.has === "function" && t.has("claudeApplyModalTitle")
- ? t("claudeApplyModalTitle")
- : "Apply to Local Claude Code";
- const targetLabel =
- typeof t.has === "function" && t.has("claudeApplyTargetLabel")
- ? t("claudeApplyTargetLabel")
- : "Target path";
- const backupLabel =
- typeof t.has === "function" && t.has("claudeApplyBackupLabel")
- ? t("claudeApplyBackupLabel")
- : "Backups";
- const warning =
- typeof t.has === "function" && t.has("claudeApplyWarning")
- ? t("claudeApplyWarning")
- : "This will replace the existing claudeAiOauth section. Continue?";
- const confirmText =
- typeof t.has === "function" && t.has("claudeApplyConfirmCheckbox")
- ? t("claudeApplyConfirmCheckbox")
- : "I confirm I want to replace the existing claudeAiOauth section";
- const applyText =
- typeof t.has === "function" && t.has("claudeApply") ? t("claudeApply") : "Apply";
- const mcpHint =
- typeof t.has === "function" && t.has("claudeApplyMcpHint")
- ? t("claudeApplyMcpHint")
- : "Existing MCP OAuth state will be preserved.";
-
- return (
- <Modal isOpen={isOpen} title={title} onClose={onClose}>
- <div className="flex flex-col gap-4">
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
- <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
- ~/.claude/.credentials.json
- </code>
- <p className="mt-1 text-xs text-text-muted">Path is auto-detected per OS (Linux/Mac).</p>
- </div>
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
- <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
- {"~/.claude/credentials-{timestamp}.bak"}
- </code>
- </div>
- <div className="rounded bg-sky-500/10 border border-sky-500/20 px-3 py-2 text-xs text-sky-400">
- {mcpHint}
- </div>
- <p className="text-sm text-text-muted">{warning}</p>
- <label className="flex items-center gap-2 text-sm">
- <input
- type="checkbox"
- checked={confirmed}
- onChange={(e) => setConfirmed(e.target.checked)}
- />
- {confirmText}
- </label>
- <div className="flex justify-end gap-2">
- <Button variant="secondary" onClick={onClose} disabled={inProgress}>
- Cancel
- </Button>
- <Button
- loading={inProgress}
- disabled={!confirmed || inProgress}
- onClick={() => void onConfirm(connectionId)}
- >
- {applyText}
- </Button>
- </div>
- </div>
- </Modal>
- );
-}
-
-function normalizeAndValidateHttpBaseUrl(rawValue, fallbackUrl) {
- const value = (typeof rawValue === "string" ? rawValue.trim() : "") || fallbackUrl;
- try {
- const parsed = new URL(value);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
- return { value: null, error: "Base URL must use http or https" };
- }
- return { value, error: null };
- } catch {
- return { value: null, error: "Base URL must be a valid URL" };
- }
-}
-
-function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnectionModalProps) {
- const t = useTranslations("providers");
- const notify = useNotificationStore();
- const [formData, setFormData] = useState({
- name: "",
- priority: 1,
- maxConcurrent: "",
- rpm: "",
- tpm: "",
- tpd: "",
- minTime: "",
- rateLimitMaxConcurrent: "",
- apiKey: "",
- healthCheckInterval: 60,
- baseUrl: "",
- cx: "",
- region: "",
- apiRegion: "international",
- validationModelId: "",
- tag: "",
- routingTags: "",
- excludedModels: "",
- customUserAgent: "",
- accountId: "",
- codexReasoningEffort: "medium",
- codexServiceTier: "default" as CodexServiceTier,
- codexOpenaiStoreEnabled: false,
- consoleApiKey: "",
- ccCompatibleContext1m: false,
- cloudCodeProjectId: "",
- antigravityClientProfile: "ide",
- blockExtraUsage:
- connection?.provider === "claude"
- ? isClaudeExtraUsageBlockEnabled(connection?.provider, connection?.providerSpecificData)
- : false,
- passthroughModels: connection?.providerSpecificData?.passthroughModels === true,
- });
- const [testing, setTesting] = useState(false);
- const [testResult, setTestResult] = useState(null);
- const [validating, setValidating] = useState(false);
- const [validationResult, setValidationResult] = useState(null);
- const [saving, setSaving] = useState(false);
- const [saveError, setSaveError] = useState<string | null>(null);
- const [extraApiKeys, setExtraApiKeys] = useState<string[]>([]);
- const [newExtraKey, setNewExtraKey] = useState("");
- const [apiKeyHealth, setApiKeyHealth] = useState<
- Record<
- string,
- {
- status: "active" | "warning" | "invalid";
- failures: number;
- lastFailure: string | null;
- totalRequests?: number;
- totalFailures?: number;
- }
- >
- >({});
- const [showAdvanced, setShowAdvanced] = useState(false);
- const { emailsVisible: showEmail, toggleEmailVisibility: toggleShowEmail } =
- useEmailPrivacyStore();
-
- const usesBaseUrl = isBaseUrlConfigurableProvider(connection?.provider);
- const defaultBaseUrl = getProviderBaseUrlDefault(connection?.provider);
- const isVertex = connection?.provider === "vertex" || connection?.provider === "vertex-partner";
- const isBedrock = connection?.provider === "bedrock";
- const showsRegion = isVertex || isBedrock;
- const isGlm = isGlmProvider(connection?.provider);
- const isCloudflare = connection?.provider === "cloudflare-ai";
- const isCodex = connection?.provider === "codex";
- const isClaude = connection?.provider === "claude";
- const isGeminiCli = connection?.provider === "gemini-cli";
- const isAntigravity = connection?.provider === "antigravity";
- const supportsGoogleProjectId = isGeminiCli || isAntigravity;
- const localProviderMetadata = getLocalProviderMetadata(connection?.provider);
- const isLocalSelfHostedProvider = !!localProviderMetadata;
- const isGooglePse = connection?.provider === "google-pse-search";
- const webSessionCredential = getWebSessionCredentialRequirement(connection?.provider);
- const isNoAuthWebSessionCredential = webSessionCredential?.kind === "none";
- const isWebSessionCredential = !!webSessionCredential && webSessionCredential.kind !== "none";
- const providerDisplayName =
- (connection?.provider ? resolveDashboardProviderInfo(connection.provider)?.name : null) ||
- connection?.provider ||
- "";
- const apiKeyOptional =
- providerAllowsOptionalApiKey(connection?.provider) || Boolean(isNoAuthWebSessionCredential);
- const isCcCompatible = isClaudeCodeCompatibleProvider(connection?.provider);
- const defaultRegion = isBedrock ? "eu-west-2" : "us-central1";
- const apiCredentialLabel = webSessionCredential
- ? getWebSessionCredentialLabel(t, webSessionCredential, apiKeyOptional)
- : apiKeyOptional
- ? t("apiKeyOptionalLabel")
- : t("apiKeyLabel");
- const apiCredentialPlaceholder = isWebSessionCredential
- ? webSessionCredential.placeholder
- : isVertex
- ? t("vertexServiceAccountPlaceholder")
- : t("enterNewApiKey");
- const apiCredentialHint = isWebSessionCredential
- ? getWebSessionCredentialHint(t, webSessionCredential, providerDisplayName, true)
- : isLocalSelfHostedProvider
- ? t("localProviderApiKeyOptionalHint", {
- provider: localProviderMetadata?.name || connection?.provider || "",
- })
- : apiKeyOptional
- ? t("apiKeyOptionalHint")
- : t("leaveBlankKeepCurrentApiKey");
- const codexAccountServiceTierOptions = useMemo(
- () =>
- CODEX_ACCOUNT_SERVICE_TIER_VALUES.map((value) => ({
- value,
- label: getCodexServiceTierLabel(t, value),
- })),
- [t]
- );
-
- useEffect(() => {
- if (isOpen && connection) {
- const rawBaseUrl = connection.providerSpecificData?.baseUrl;
- const existingBaseUrl = typeof rawBaseUrl === "string" ? rawBaseUrl : "";
- const rawRegion = connection.providerSpecificData?.region;
- const existingRegion = typeof rawRegion === "string" ? rawRegion : "";
- const rawCustomUserAgent = connection.providerSpecificData?.customUserAgent;
- const existingCustomUserAgent =
- typeof rawCustomUserAgent === "string" ? rawCustomUserAgent : "";
- const rawCx = connection.providerSpecificData?.cx;
- const existingCx = typeof rawCx === "string" ? rawCx : "";
- const rawAccountId = connection.providerSpecificData?.accountId;
- const existingAccountId = typeof rawAccountId === "string" ? rawAccountId : "";
- const codexRequestDefaults = getCodexRequestDefaults(connection.providerSpecificData);
- const ccRequestDefaults = getClaudeCodeCompatibleRequestDefaults(
- connection.providerSpecificData
- );
- const rawConsoleApiKey = connection.providerSpecificData?.consoleApiKey;
- const existingConsoleApiKey = typeof rawConsoleApiKey === "string" ? rawConsoleApiKey : "";
- setFormData({
- name: connection.name || "",
- priority: connection.priority || 1,
- maxConcurrent:
- connection.maxConcurrent !== null && connection.maxConcurrent !== undefined
- ? String(connection.maxConcurrent)
- : "",
- rpm:
- connection.rateLimitOverrides?.rpm != null
- ? String(connection.rateLimitOverrides.rpm)
- : "",
- tpm:
- connection.rateLimitOverrides?.tpm != null
- ? String(connection.rateLimitOverrides.tpm)
- : "",
- tpd:
- connection.rateLimitOverrides?.tpd != null
- ? String(connection.rateLimitOverrides.tpd)
- : "",
- minTime:
- connection.rateLimitOverrides?.minTime != null
- ? String(connection.rateLimitOverrides.minTime)
- : "",
- rateLimitMaxConcurrent:
- connection.rateLimitOverrides?.maxConcurrent != null
- ? String(connection.rateLimitOverrides.maxConcurrent)
- : "",
- apiKey: "",
- healthCheckInterval: connection.healthCheckInterval ?? 60,
- baseUrl: existingBaseUrl || defaultBaseUrl,
- cx: existingCx,
- region: existingRegion || (showsRegion ? defaultRegion : ""),
- apiRegion: (connection.providerSpecificData?.apiRegion as string) || "international",
- validationModelId: (connection.providerSpecificData?.validationModelId as string) || "",
- tag: (connection.providerSpecificData?.tag as string) || "",
- routingTags: formatRoutingTagsInput(connection.providerSpecificData?.tags),
- excludedModels: formatExcludedModelsInput(
- connection.providerSpecificData?.excludedModels ??
- connection.providerSpecificData?.excluded_models
- ),
- customUserAgent: existingCustomUserAgent,
- accountId: existingAccountId,
- codexReasoningEffort: codexRequestDefaults.reasoningEffort,
- codexServiceTier: codexRequestDefaults.serviceTier ?? "default",
- codexOpenaiStoreEnabled: connection.providerSpecificData?.openaiStoreEnabled === true,
- consoleApiKey: existingConsoleApiKey,
- ccCompatibleContext1m: ccRequestDefaults.context1m,
- cloudCodeProjectId:
- (connection.providerSpecificData?.projectId as string) || connection.projectId || "",
- antigravityClientProfile: normalizeAntigravityClientProfileSetting(
- connection.providerSpecificData?.clientProfile
- ),
- blockExtraUsage: isClaudeExtraUsageBlockEnabled(
- connection.provider,
- connection.providerSpecificData
- ),
- passthroughModels: connection?.providerSpecificData?.passthroughModels === true,
- });
- // Load existing extra keys from providerSpecificData
- const existing = connection.providerSpecificData?.extraApiKeys;
- setExtraApiKeys(Array.isArray(existing) ? existing : []);
- // Load API key health status
- const health = connection.providerSpecificData?.apiKeyHealth as
- | Record<
- string,
- {
- status: "active" | "warning" | "invalid";
- failures: number;
- lastFailure: string | null;
- totalRequests?: number;
- totalFailures?: number;
- }
- >
- | undefined;
- setApiKeyHealth(health || {});
- setNewExtraKey("");
- setShowAdvanced(!!existingCustomUserAgent);
- // email visibility controlled by global store
- setTestResult(null);
- setValidationResult(null);
- setSaveError(null);
- }
- }, [isOpen, connection, defaultBaseUrl, showsRegion, defaultRegion]);
-
- const handleTest = async () => {
- if (!connection?.provider) return;
- setTesting(true);
- setTestResult(null);
- try {
- const res = await fetch(`/api/providers/${connection.id}/test`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- validationModelId: formData.validationModelId || undefined,
- }),
- });
- const data = await res.json();
- setTestResult({
- valid: !!data.valid,
- diagnosis: data.diagnosis || null,
- message: data.error || null,
- });
- } catch {
- setTestResult({
- valid: false,
- diagnosis: { type: "network_error" },
- message: t("failedTestConnection"),
- });
- } finally {
- setTesting(false);
- }
- };
-
- const handleValidate = async () => {
- if (
- !connection?.provider ||
- isNoAuthWebSessionCredential ||
- (!isCompatible && !apiKeyOptional && !formData.apiKey)
- ) {
- return;
- }
- setValidating(true);
- setValidationResult(null);
- try {
- const res = await fetch("/api/providers/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: connection.provider,
- apiKey: formData.apiKey,
- validationModelId: formData.validationModelId || undefined,
- customUserAgent: formData.customUserAgent.trim() || undefined,
- baseUrl: formData.baseUrl.trim() || undefined,
- region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
- cx: formData.cx.trim() || undefined,
- }),
- });
- const data = await res.json();
- setValidationResult(data.valid ? "success" : "failed");
- } catch {
- setValidationResult("failed");
- } finally {
- setValidating(false);
- }
- };
-
- const handleAddParsedExtraKeys = (raw: string) => {
- const { added, duplicates } = parseExtraApiKeys(raw, extraApiKeys);
- if (added.length > 0) {
- setExtraApiKeys((prev) => [...prev, ...added]);
- notify.success(t("bulkPasteAdded", { count: added.length }));
- }
- if (duplicates > 0) {
- notify.warning(t("bulkPasteDuplicatesIgnored", { count: duplicates }));
- }
- };
-
- const handleSubmit = async () => {
- setSaving(true);
- setSaveError(null);
- try {
- const trimmedMaxConcurrent = formData.maxConcurrent.trim();
- const trimmedCloudCodeProjectId = formData.cloudCodeProjectId.trim();
- let parsedMaxConcurrent: number | null = null;
- if (trimmedMaxConcurrent) {
- const numericMaxConcurrent = Number(trimmedMaxConcurrent);
- if (!Number.isInteger(numericMaxConcurrent) || numericMaxConcurrent < 0) {
- setSaveError(t("maxConcurrentWholeNumberError"));
- return;
- }
- parsedMaxConcurrent = numericMaxConcurrent;
- }
-
- const updates: any = {
- name: formData.name,
- priority: formData.priority,
- maxConcurrent: parsedMaxConcurrent,
- healthCheckInterval: formData.healthCheckInterval,
- };
-
- // Build rateLimitOverrides from non-empty fields
- const overrides: Record<string, number> = {};
- if (formData.rpm.trim()) overrides.rpm = Number(formData.rpm);
- if (formData.tpm.trim()) overrides.tpm = Number(formData.tpm);
- if (formData.tpd.trim()) overrides.tpd = Number(formData.tpd);
- if (formData.minTime.trim()) overrides.minTime = Number(formData.minTime);
- if (formData.rateLimitMaxConcurrent.trim())
- overrides.maxConcurrent = Number(formData.rateLimitMaxConcurrent);
- updates.rateLimitOverrides = Object.keys(overrides).length > 0 ? overrides : null;
-
- if (supportsGoogleProjectId) {
- updates.projectId = trimmedCloudCodeProjectId || null;
- }
-
- if (isGooglePse && !formData.cx.trim()) {
- setSaveError(t("searchEngineIdRequired"));
- return;
- }
-
- let validatedBaseUrl = null;
- if (usesBaseUrl) {
- const checked = normalizeAndValidateHttpBaseUrl(formData.baseUrl, defaultBaseUrl);
- if (checked.error) {
- setSaveError(checked.error);
- return;
- }
- validatedBaseUrl = checked.value;
- }
-
- if (!isOAuth && formData.apiKey) {
- updates.apiKey = formData.apiKey;
- let isValid = validationResult === "success";
- if (!isValid) {
- try {
- setValidating(true);
- setValidationResult(null);
- const res = await fetch("/api/providers/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- provider: connection.provider,
- apiKey: formData.apiKey,
- validationModelId: formData.validationModelId || undefined,
- customUserAgent: formData.customUserAgent.trim() || undefined,
- baseUrl: formData.baseUrl.trim() || undefined,
- region: showsRegion ? formData.region.trim() || defaultRegion : undefined,
- cx: formData.cx.trim() || undefined,
- }),
- });
- const data = await res.json();
- isValid = !!data.valid;
- setValidationResult(isValid ? "success" : "failed");
- } catch {
- setValidationResult("failed");
- } finally {
- setValidating(false);
- }
- }
- if (isValid) {
- updates.testStatus = "active";
- updates.lastError = null;
- updates.lastErrorAt = null;
- updates.lastErrorType = null;
- updates.lastErrorSource = null;
- updates.errorCode = null;
- updates.rateLimitedUntil = null;
- }
- }
- // Persist extra API keys and baseUrl in providerSpecificData
- if (!isOAuth) {
- updates.providerSpecificData = {
- ...(connection.providerSpecificData || {}),
- extraApiKeys: extraApiKeys.filter((k) => k.trim().length > 0),
- tag: formData.tag.trim() || undefined,
- tags: parseRoutingTagsInput(formData.routingTags),
- excludedModels: parseExcludedModelsInput(formData.excludedModels),
- customUserAgent: formData.customUserAgent.trim(),
- // Only write when explicitly enabled; omit to let registry default take effect
- ...(formData.passthroughModels ? { passthroughModels: true } : {}),
- };
- if (connection.provider === "bailian-coding-plan") {
- if (formData.consoleApiKey.trim()) {
- updates.providerSpecificData.consoleApiKey = formData.consoleApiKey.trim();
- } else {
- updates.providerSpecificData.consoleApiKey = undefined;
- }
- }
- if (formData.validationModelId) {
- updates.providerSpecificData.validationModelId = formData.validationModelId;
- }
- if (isGooglePse) {
- updates.providerSpecificData.cx = formData.cx.trim() || undefined;
- }
- if (usesBaseUrl) {
- updates.providerSpecificData.baseUrl = validatedBaseUrl;
- } else if (showsRegion) {
- updates.providerSpecificData.region = formData.region.trim() || defaultRegion;
- } else if (isGlm) {
- updates.providerSpecificData.apiRegion = formData.apiRegion;
- } else if (isCloudflare && formData.accountId.trim()) {
- updates.providerSpecificData.accountId = formData.accountId.trim();
- }
- if (supportsGoogleProjectId) {
- updates.providerSpecificData.projectId = trimmedCloudCodeProjectId || null;
- }
- if (isCcCompatible) {
- const currentRequestDefaults =
- updates.providerSpecificData.requestDefaults &&
- typeof updates.providerSpecificData.requestDefaults === "object" &&
- !Array.isArray(updates.providerSpecificData.requestDefaults)
- ? { ...(updates.providerSpecificData.requestDefaults as Record<string, unknown>) }
- : {};
- if (formData.ccCompatibleContext1m) {
- currentRequestDefaults.context1m = true;
- } else {
- delete currentRequestDefaults.context1m;
- }
- updates.providerSpecificData.requestDefaults =
- Object.keys(currentRequestDefaults).length > 0 ? currentRequestDefaults : undefined;
- }
- } else {
- // Also persist tag for OAuth accounts
- updates.providerSpecificData = {
- ...(connection.providerSpecificData || {}),
- tag: formData.tag.trim() || undefined,
- tags: parseRoutingTagsInput(formData.routingTags),
- excludedModels: parseExcludedModelsInput(formData.excludedModels),
- };
- if (isClaude) {
- updates.providerSpecificData.blockExtraUsage = formData.blockExtraUsage;
- }
- if (isCodex) {
- updates.providerSpecificData.requestDefaults = {
- reasoningEffort: formData.codexReasoningEffort,
- ...(formData.codexServiceTier !== "default"
- ? { serviceTier: formData.codexServiceTier }
- : {}),
- };
- updates.providerSpecificData.openaiStoreEnabled =
- formData.codexOpenaiStoreEnabled === true;
- }
- if (supportsGoogleProjectId) {
- updates.providerSpecificData.projectId = trimmedCloudCodeProjectId || null;
- }
- }
- if (isAntigravity) {
- updates.providerSpecificData = {
- ...(connection.providerSpecificData || {}),
- ...(updates.providerSpecificData || {}),
- clientProfile: normalizeAntigravityClientProfileSetting(
- formData.antigravityClientProfile
- ),
- };
- }
- const error = (await onSave(updates)) as void | unknown;
- if (error) {
- setSaveError(typeof error === "string" ? error : t("failedSaveConnection"));
- }
- } finally {
- setSaving(false);
- }
- };
-
- if (!connection) return null;
-
- const isOAuth = connection.authType === "oauth";
- const isCompatible =
- isOpenAICompatibleProvider(connection.provider) ||
- isAnthropicCompatibleProvider(connection.provider);
- const testErrorMeta =
- !testResult?.valid && testResult?.diagnosis?.type
- ? ERROR_TYPE_LABELS[testResult.diagnosis.type] || null
- : null;
-
- return (
- <Modal isOpen={isOpen} title={t("editConnection")} onClose={onClose}>
- <div className="flex flex-col gap-4">
- <Input
- label={t("nameLabel")}
- value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
- placeholder={isOAuth ? t("accountName") : t("productionKey")}
- />
- <Input
- label={t("tagGroupLabel")}
- value={formData.tag}
- onChange={(e) => setFormData({ ...formData, tag: e.target.value })}
- placeholder={t("tagGroupPlaceholder")}
- hint={t("tagGroupHint")}
- />
- <Input
- label={t("routingTagsLabel")}
- value={formData.routingTags}
- onChange={(e) => setFormData({ ...formData, routingTags: e.target.value })}
- placeholder={t("routingTagsPlaceholder")}
- hint={t("routingTagsHint")}
- />
- <Input
- label={t("excludedModelsLabel")}
- value={formData.excludedModels}
- onChange={(e) => setFormData({ ...formData, excludedModels: e.target.value })}
- placeholder={t("excludedModelsPlaceholder")}
- hint={t("excludedModelsHint")}
- />
- {isCodex && (
- <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- <Select
- label={t("defaultThinkingStrengthLabel")}
- value={formData.codexReasoningEffort}
- options={CODEX_REASONING_STRENGTH_OPTIONS}
- onChange={(e) => setFormData({ ...formData, codexReasoningEffort: e.target.value })}
- hint={t("defaultThinkingStrengthHint")}
- />
- <Select
- label={providerText(t, "codexServiceTierLabel", "Codex service tier")}
- value={formData.codexServiceTier}
- options={codexAccountServiceTierOptions}
- onChange={(event) =>
- setFormData({
- ...formData,
- codexServiceTier: event.target.value as CodexServiceTier,
- })
- }
- hint={providerText(
- t,
- "codexServiceTierDescription",
- "Default uses the normal Codex tier. Priority shows as Fast; Flex uses the flex service tier when available."
- )}
- />
- <Toggle
- checked={formData.codexOpenaiStoreEnabled}
- onChange={(checked) => setFormData({ ...formData, codexOpenaiStoreEnabled: checked })}
- label={t("openaiResponsesStoreLabel")}
- description={t("openaiResponsesStoreDescription")}
- />
- </div>
- )}
- {isClaude && (
- <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- <Toggle
- checked={formData.blockExtraUsage}
- onChange={(checked) => setFormData({ ...formData, blockExtraUsage: checked })}
- label={t("blockClaudeExtraUsageLabel")}
- description={t("blockClaudeExtraUsageDescription")}
- />
- </div>
- )}
- {isCcCompatible && (
- <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- <Toggle
- checked={formData.ccCompatibleContext1m}
- onChange={(checked) => setFormData({ ...formData, ccCompatibleContext1m: checked })}
- label={t("ccCompatibleContext1mLabel")}
- description={t("ccCompatibleContext1mDescription")}
- />
- </div>
- )}
- {supportsGoogleProjectId && (
- <div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- {isAntigravity && (
- <Select
- label={t("antigravityClientProfileLabel")}
- value={formData.antigravityClientProfile}
- options={ANTIGRAVITY_CLIENT_PROFILE_OPTIONS.map((option) => ({
- value: option.value,
- label: t(option.labelKey),
- }))}
- onChange={(e) =>
- setFormData({ ...formData, antigravityClientProfile: e.target.value })
- }
- hint={t("antigravityClientProfileHint")}
- />
- )}
- <Input
- label={isAntigravity ? t("antigravityProjectIdLabel") : t("geminiCliProjectIdLabel")}
- value={formData.cloudCodeProjectId}
- onChange={(e) => setFormData({ ...formData, cloudCodeProjectId: e.target.value })}
- placeholder={
- isAntigravity
- ? t("antigravityProjectIdPlaceholder")
- : t("geminiCliProjectIdPlaceholder")
- }
- hint={isAntigravity ? t("antigravityProjectIdHint") : t("geminiCliProjectIdHint")}
- className="font-mono text-xs"
- />
- </div>
- )}
- {isOAuth && connection.email && (
- <div className="bg-sidebar/50 p-3 rounded-lg">
- <p className="text-sm text-text-muted mb-1">{t("email")}</p>
- <div className="flex items-center gap-2">
- <p className="font-medium" title={showEmail ? connection.email : undefined}>
- {showEmail ? connection.email : maskEmail(connection.email)}
- </p>
- <button
- type="button"
- onClick={toggleShowEmail}
- className="rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary"
- title={showEmail ? t("hideEmail") : t("showEmail")}
- >
- <span className="material-symbols-outlined text-sm">
- {showEmail ? "visibility_off" : "visibility"}
- </span>
- </button>
- </div>
- </div>
- )}
- {isOAuth && (
- <Input
- label={t("healthCheckMinutes")}
- type="number"
- value={formData.healthCheckInterval}
- onChange={(e) =>
- setFormData({
- ...formData,
- healthCheckInterval: Math.max(0, Number.parseInt(e.target.value) || 0),
- })
- }
- hint={t("healthCheckHint")}
- />
- )}
- <Input
- label={t("priorityLabel")}
- type="number"
- value={formData.priority}
- onChange={(e) =>
- setFormData({ ...formData, priority: Number.parseInt(e.target.value) || 1 })
- }
- />
- <Input
- label={t("accountConcurrencyCapLabel")}
- type="number"
- min={0}
- step={1}
- value={formData.maxConcurrent}
- onChange={(e) => {
- const nextValue = e.target.value;
- setFormData({ ...formData, maxConcurrent: nextValue });
- if (saveError && nextValue.trim()) {
- const numericValue = Number(nextValue);
- if (Number.isInteger(numericValue) && numericValue >= 0) {
- setSaveError(null);
- }
- }
- }}
- placeholder="0"
- hint={t("accountConcurrencyCapHint")}
- />
- {saveError && (
- <div className="text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">
- {saveError}
- </div>
- )}
- {!isOAuth && (
- <>
- {webSessionCredential && (
- <WebSessionCredentialGuide
- requirement={webSessionCredential}
- providerName={providerDisplayName}
- t={t}
- />
- )}
- {!isNoAuthWebSessionCredential && (
- <div className="flex gap-2">
- <Input
- label={apiCredentialLabel}
- type="password"
- value={formData.apiKey}
- onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
- placeholder={apiCredentialPlaceholder}
- hint={apiCredentialHint}
- className="flex-1"
- autoComplete="off"
- spellCheck={false}
- autoCapitalize="off"
- />
- <div className="pt-6">
- <Button
- onClick={handleValidate}
- disabled={
- (!isCompatible && !apiKeyOptional && !formData.apiKey) ||
- (isGooglePse && !formData.cx.trim()) ||
- validating ||
- saving
- }
- variant="secondary"
- >
- {validating
- ? t("checking")
- : webSessionCredential
- ? getWebSessionCredentialCheckLabel(t, webSessionCredential)
- : t("check")}
- </Button>
- </div>
- </div>
- )}
- {isGooglePse && (
- <Input
- label={t("searchEngineIdLabel")}
- value={formData.cx}
- onChange={(e) => setFormData({ ...formData, cx: e.target.value })}
- placeholder="012345678901234567890:abc123xyz"
- hint={t("searchEngineIdHint")}
- />
- )}
- {validationResult && (
- <Badge variant={validationResult === "success" ? "success" : "error"}>
- {validationResult === "success" ? t("valid") : t("invalid")}
- </Badge>
- )}
- <button
- type="button"
- className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
- onClick={() => setShowAdvanced(!showAdvanced)}
- aria-expanded={showAdvanced}
- aria-controls="edit-connection-advanced-settings"
- >
- <span
- className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
- aria-hidden="true"
- >
- ▶
- </span>
- {t("advancedSettings")}
- </button>
- {showAdvanced && (
- <div
- id="edit-connection-advanced-settings"
- className="flex flex-col gap-3 pl-2 border-l-2 border-border"
- >
- <Input
- label={t("customUserAgentLabel")}
- value={formData.customUserAgent}
- onChange={(e) => setFormData({ ...formData, customUserAgent: e.target.value })}
- placeholder="my-app/1.0"
- hint={t("customUserAgentHint")}
- />
- <Toggle
- size="sm"
- checked={formData.passthroughModels}
- onChange={(checked) => setFormData({ ...formData, passthroughModels: checked })}
- label={t("perModelQuotaLabel")}
- description={t("perModelQuotaDescription")}
- />
- {connection.provider === "bailian-coding-plan" && (
- <Input
- label={t("consoleApiKeyOracleLabel")}
- value={formData.consoleApiKey}
- onChange={(e) => setFormData({ ...formData, consoleApiKey: e.target.value })}
- placeholder={t("consoleApiKeyOraclePlaceholder")}
- hint={t("consoleApiKeyOracleHint")}
- type="password"
- />
- )}
- <div className="border-t border-border/30 pt-3 mt-1">
- <p className="text-xs font-medium text-text-muted mb-2">
- {t("rateLimitOverridesSection")}
- </p>
- <div className="grid grid-cols-2 gap-3">
- <Input
- label={t("rateLimitOverridesRpmLabel")}
- type="number"
- min={0}
- value={formData.rpm}
- onChange={(e) => setFormData({ ...formData, rpm: e.target.value })}
- placeholder="Inherit"
- hint={t("rateLimitOverridesRpmHint")}
- />
- <Input
- label={t("rateLimitOverridesTpmLabel")}
- type="number"
- min={0}
- value={formData.tpm}
- onChange={(e) => setFormData({ ...formData, tpm: e.target.value })}
- placeholder="Inherit"
- hint={t("rateLimitOverridesTpmHint")}
- />
- <Input
- label={t("rateLimitOverridesTpdLabel")}
- type="number"
- min={0}
- value={formData.tpd}
- onChange={(e) => setFormData({ ...formData, tpd: e.target.value })}
- placeholder="Inherit"
- hint={t("rateLimitOverridesTpdHint")}
- />
- <Input
- label={t("rateLimitOverridesMinTimeLabel")}
- type="number"
- min={0}
- value={formData.minTime}
- onChange={(e) => setFormData({ ...formData, minTime: e.target.value })}
- placeholder="Inherit"
- hint={t("rateLimitOverridesMinTimeHint")}
- />
- <Input
- label={t("rateLimitOverridesMaxConcurrentLabel")}
- type="number"
- min={0}
- value={formData.rateLimitMaxConcurrent}
- onChange={(e) =>
- setFormData({ ...formData, rateLimitMaxConcurrent: e.target.value })
- }
- placeholder="Inherit"
- hint={t("rateLimitOverridesMaxConcurrentHint")}
- />
- </div>
- </div>
- </div>
- )}
- <Input
- label={t("validationModelIdLabel")}
- placeholder={t("validationModelIdPlaceholder")}
- value={formData.validationModelId}
- onChange={(e) => setFormData({ ...formData, validationModelId: e.target.value })}
- hint={t("validationModelIdHint")}
- />
- </>
- )}
-
- {usesBaseUrl && (
- <Input
- label={t("baseUrlLabel")}
- value={formData.baseUrl}
- onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
- placeholder={getProviderBaseUrlPlaceholder(connection.provider)}
- hint={getProviderBaseUrlHint(connection.provider, t)}
- />
- )}
-
- {showsRegion && (
- <Input
- label={t("regionLabel")}
- value={formData.region}
- onChange={(e) => setFormData({ ...formData, region: e.target.value })}
- placeholder={defaultRegion}
- hint={t("regionHint")}
- />
- )}
-
- {isCloudflare && (
- <Input
- label={t("accountIdLabel")}
- value={formData.accountId}
- onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
- placeholder={t("accountIdPlaceholder")}
- hint={t("accountIdHint")}
- />
- )}
-
- {isGlm && (
- <div>
- <label className="text-sm font-medium text-text-main mb-1 block">
- {t("apiRegionLabel")}
- </label>
- <select
- value={formData.apiRegion}
- onChange={(e) => setFormData({ ...formData, apiRegion: e.target.value })}
- className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"
- >
- <option value="international">{t("apiRegionInternational")}</option>
- <option value="china">{t("apiRegionChina")}</option>
- </select>
- <p className="text-xs text-text-muted mt-1">{t("apiRegionHint")}</p>
- </div>
- )}
-
- {/* T07: API Key Health Status */}
- {!isOAuth && connection?.apiKey && (
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-text-main">{t("apiKeyHealthLabel")}</label>
- <div className="flex flex-col gap-1.5">
- {/* Primary Key Health */}
- {(() => {
- const keyId = "primary";
- const health = apiKeyHealth[keyId];
- const statusColor =
- health?.status === "invalid"
- ? "text-red-400"
- : health?.status === "warning"
- ? "text-yellow-400"
- : "text-text-muted";
- const statusIcon =
- health?.status === "invalid" ? "🔴" : health?.status === "warning" ? "🟡" : "🟢";
- const statusLabel =
- health?.status === "invalid"
- ? t("apiKeyStatusInvalid")
- : health?.status === "warning"
- ? t("apiKeyStatusWarning", { count: health.failures })
- : t("apiKeyStatusActive");
-
- return (
- <div className="flex items-center gap-2">
- <span
- className={`flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border truncate ${statusColor}`}
- >
- {statusIcon} {t("primaryKey")}: {connection.apiKey.slice(0, 6)}...
- {connection.apiKey.slice(-4)}
- </span>
- {health && (
- <span
- className="text-[10px] text-text-muted whitespace-nowrap"
- title={statusLabel}
- >
- {health.failures}x
- {health.lastFailure ? ` · ${formatTimeAgo(health.lastFailure)}` : ""}
- {health.totalRequests != null
- ? ` · (${health.totalRequests} req${health.totalFailures != null ? `, ${health.totalFailures} fail` : ""})`
- : ""}
- </span>
- )}
- </div>
- );
- })()}
- </div>
- </div>
- )}
-
- {/* T07: Extra API Keys for round-robin rotation */}
- {!isOAuth && (
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between gap-2">
- <label className="text-sm font-medium text-text-main">
- {t("extraApiKeysLabel")}
- <span className="ml-2 text-[11px] font-normal text-text-muted">
- ({t("extraApiKeysHint")})
- </span>
- </label>
- {extraApiKeys.length > 0 && (
- <button
- type="button"
- onClick={() => setExtraApiKeys([])}
- className="px-2.5 py-1.5 rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20 hover:text-red-300 text-xs font-medium transition-colors"
- >
- {t("deleteAllExtraApiKeys")}
- </button>
- )}
- </div>
- {extraApiKeys.length > 0 && (
- <div className="flex flex-col gap-1.5">
- {extraApiKeys.map((key, idx) => {
- const keyId = `extra_${idx}`;
- const health = apiKeyHealth[keyId];
- const statusColor =
- health?.status === "invalid"
- ? "text-red-400"
- : health?.status === "warning"
- ? "text-yellow-400"
- : "text-text-muted";
- const statusIcon =
- health?.status === "invalid"
- ? "🔴"
- : health?.status === "warning"
- ? "🟡"
- : "🟢";
- const statusLabel =
- health?.status === "invalid"
- ? t("apiKeyStatusInvalid")
- : health?.status === "warning"
- ? t("apiKeyStatusWarning", { count: health.failures })
- : t("apiKeyStatusActive");
-
- return (
- <div key={idx} className="flex items-center gap-2">
- <span
- className={`flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border truncate ${statusColor}`}
- >
- {statusIcon}{" "}
- {t("extraApiKeyMasked", {
- index: idx + 2,
- prefix: key.slice(0, 6),
- suffix: key.slice(-4),
- })}
- </span>
- <div className="flex items-center gap-1">
- {health && (
- <span
- className="text-[10px] text-text-muted whitespace-nowrap"
- title={statusLabel}
- >
- {health.failures}x
- {health.lastFailure ? ` · ${formatTimeAgo(health.lastFailure)}` : ""}
- {health.totalRequests != null
- ? ` · (${health.totalRequests} req${health.totalFailures != null ? `, ${health.totalFailures} fail` : ""})`
- : ""}
- </span>
- )}
- <button
- onClick={() => setExtraApiKeys(extraApiKeys.filter((_, i) => i !== idx))}
- className="p-1.5 rounded hover:bg-red-500/10 text-red-400 hover:text-red-500"
- title={t("removeThisKey")}
- >
- <span className="material-symbols-outlined text-[16px]">close</span>
- </button>
- </div>
- </div>
- );
- })}
- </div>
- )}
- <div className="flex gap-2">
- <input
- type="password"
- value={newExtraKey}
- onChange={(e) => setNewExtraKey(e.target.value)}
- placeholder={t("addAnotherApiKey")}
- className="flex-1 text-sm bg-sidebar/50 border border-border rounded px-3 py-2 text-text-main placeholder:text-text-muted focus:ring-1 focus:ring-primary outline-none"
- onKeyDown={(e) => {
- if (e.key === "Enter" && newExtraKey.trim()) {
- setExtraApiKeys([...extraApiKeys, newExtraKey.trim()]);
- setNewExtraKey("");
- }
- }}
- onPaste={(e) => {
- const text = e.clipboardData.getData("text");
- if (!/\r?\n/.test(text)) return;
- e.preventDefault();
- handleAddParsedExtraKeys(text);
- }}
- />
- <button
- onClick={() => {
- if (newExtraKey.trim()) {
- setExtraApiKeys([...extraApiKeys, newExtraKey.trim()]);
- setNewExtraKey("");
- }
- }}
- disabled={!newExtraKey.trim()}
- className="px-3 py-2 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-40 text-sm font-medium"
- >
- {t("add")}
- </button>
- </div>
- <p className="text-[11px] text-text-muted">{t("bulkPasteHint")}</p>
- {extraApiKeys.length > 0 && (
- <p className="text-[11px] text-text-muted">
- {t("totalKeysRotating", { count: extraApiKeys.length + 1 })}
- </p>
- )}
- </div>
- )}
-
- {/* Test Connection */}
- {!isCompatible && (
- <div className="flex items-center gap-3">
- <Button onClick={handleTest} variant="secondary" disabled={testing}>
- {testing ? t("testing") : t("testConnection")}
- </Button>
- {testResult && (
- <>
- <Badge variant={testResult.valid ? "success" : "error"}>
- {testResult.valid ? t("valid") : t("failed")}
- </Badge>
- {testErrorMeta && (
- <Badge variant={testErrorMeta.variant}>{t(testErrorMeta.labelKey)}</Badge>
- )}
- </>
- )}
- </div>
- )}
-
- <div className="flex gap-2">
- <Button
- onClick={handleSubmit}
- fullWidth
- disabled={saving || (isGooglePse && !formData.cx.trim())}
- >
- {saving ? t("saving") : t("save")}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </div>
- </Modal>
- );
-}
-
-function EditCompatibleNodeModal({
- isOpen,
- node,
- onSave,
- onClose,
- isAnthropic,
- isCcCompatible,
-}: EditCompatibleNodeModalProps) {
- const t = useTranslations("providers");
- const [formData, setFormData] = useState({
- name: "",
- prefix: "",
- apiType: "chat",
- baseUrl: "https://api.openai.com/v1",
- chatPath: "",
- modelsPath: "",
- });
- const [saving, setSaving] = useState(false);
- const [checkKey, setCheckKey] = useState("");
- const [validating, setValidating] = useState(false);
- const [validationResult, setValidationResult] = useState(null);
- const [showAdvanced, setShowAdvanced] = useState(false);
-
- useEffect(() => {
- if (node) {
- setFormData({
- name: node.name || "",
- prefix: node.prefix || "",
- apiType: node.apiType || "chat",
- baseUrl:
- node.baseUrl ||
- (isCcCompatible
- ? "https://api.anthropic.com"
- : isAnthropic
- ? "https://api.anthropic.com/v1"
- : "https://api.openai.com/v1"),
- chatPath: node.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
- modelsPath: isCcCompatible ? "" : node.modelsPath || "",
- });
- setShowAdvanced(
- !!(
- node.chatPath ||
- (!isCcCompatible && node.modelsPath) ||
- (isCcCompatible && !node.chatPath)
- )
- );
- }
- }, [node, isAnthropic, isCcCompatible]);
-
- const apiTypeOptions = [
- { value: "chat", label: t("chatCompletions") },
- { value: "responses", label: t("responsesApi") },
- { value: "embeddings", label: t("embeddings") },
- { value: "audio-transcriptions", label: t("audioTranscriptions") },
- { value: "audio-speech", label: t("audioSpeech") },
- { value: "images-generations", label: t("imagesGenerations") },
- ];
-
- const handleSubmit = async () => {
- if (!formData.name.trim() || !formData.prefix.trim() || !formData.baseUrl.trim()) return;
- setSaving(true);
- try {
- const payload: any = {
- name: formData.name,
- prefix: formData.prefix,
- baseUrl: formData.baseUrl,
- chatPath: formData.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
- modelsPath: isCcCompatible ? "" : formData.modelsPath,
- };
- if (!isAnthropic) {
- payload.apiType = formData.apiType;
- }
- await onSave(payload);
- } finally {
- setSaving(false);
- }
- };
-
- const handleValidate = async () => {
- setValidating(true);
- try {
- const res = await fetch("/api/provider-nodes/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- baseUrl: formData.baseUrl,
- apiKey: checkKey,
- type: isAnthropic ? "anthropic-compatible" : "openai-compatible",
- compatMode: isCcCompatible ? "cc" : undefined,
- chatPath: formData.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
- modelsPath: isCcCompatible ? "" : formData.modelsPath,
- }),
- });
- const data = await res.json();
- setValidationResult(data.valid ? "success" : "failed");
- } catch {
- setValidationResult("failed");
- } finally {
- setValidating(false);
- }
- };
-
- if (!node) return null;
-
- return (
- <Modal
- isOpen={isOpen}
- title={
- isCcCompatible
- ? t("ccCompatibleDetailsTitle")
- : t("editCompatibleTitle", { type: isAnthropic ? t("anthropic") : t("openai") })
- }
- onClose={onClose}
- >
- <div className="flex flex-col gap-4">
- {isCcCompatible && (
- <div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
- <div className="flex items-start gap-2">
- <span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
- warning
- </span>
- <p>{t("ccCompatibleValidationHint")}</p>
- </div>
- </div>
- )}
- <Input
- label={t("nameLabel")}
- value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
- placeholder={
- isCcCompatible
- ? t("ccCompatibleNamePlaceholder")
- : t("compatibleProdPlaceholder", {
- type: isAnthropic ? t("anthropic") : t("openai"),
- })
- }
- hint={isCcCompatible ? t("ccCompatibleNameHint") : t("nameHint")}
- />
- <Input
- label={t("prefixLabel")}
- value={formData.prefix}
- onChange={(e) => setFormData({ ...formData, prefix: e.target.value })}
- placeholder={
- isCcCompatible
- ? t("ccCompatiblePrefixPlaceholder")
- : isAnthropic
- ? t("anthropicPrefixPlaceholder")
- : t("openaiPrefixPlaceholder")
- }
- hint={isCcCompatible ? t("ccCompatiblePrefixHint") : t("prefixHint")}
- />
- {!isAnthropic && (
- <Select
- label={t("apiTypeLabel")}
- options={apiTypeOptions}
- value={formData.apiType}
- onChange={(e) => setFormData({ ...formData, apiType: e.target.value })}
- />
- )}
- <Input
- label={t("baseUrlLabel")}
- value={formData.baseUrl}
- onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
- placeholder={
- isCcCompatible
- ? t("ccCompatibleBaseUrlPlaceholder")
- : isAnthropic
- ? t("anthropicBaseUrlPlaceholder")
- : t("openaiBaseUrlPlaceholder")
- }
- hint={
- isCcCompatible
- ? t("ccCompatibleBaseUrlHint")
- : t("compatibleBaseUrlHint", {
- type: isAnthropic ? t("anthropic") : t("openai"),
- })
- }
- />
- <button
- type="button"
- className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
- onClick={() => setShowAdvanced(!showAdvanced)}
- aria-expanded={showAdvanced}
- aria-controls="advanced-settings"
- >
- <span
- className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
- aria-hidden="true"
- >
- ▶
- </span>
- {t("advancedSettings")}
- </button>
- {showAdvanced && (
- <div id="advanced-settings" className="flex flex-col gap-3 pl-2 border-l-2 border-border">
- <Input
- label={t("chatPathLabel")}
- value={formData.chatPath}
- onChange={(e) => setFormData({ ...formData, chatPath: e.target.value })}
- placeholder={
- isCcCompatible
- ? CC_COMPATIBLE_DEFAULT_CHAT_PATH
- : isAnthropic
- ? "/messages"
- : t("chatPathPlaceholder")
- }
- hint={isCcCompatible ? t("ccCompatibleChatPathHint") : t("chatPathHint")}
- />
- {!isCcCompatible && (
- <Input
- label={t("modelsPathLabel")}
- value={formData.modelsPath}
- onChange={(e) => setFormData({ ...formData, modelsPath: e.target.value })}
- placeholder={t("modelsPathPlaceholder")}
- hint={t("modelsPathHint")}
- />
- )}
- </div>
- )}
- <div className="flex gap-2">
- <Input
- label={t("apiKeyForCheck")}
- type="password"
- value={checkKey}
- onChange={(e) => setCheckKey(e.target.value)}
- className="flex-1"
- />
- <div className="pt-6">
- <Button
- onClick={handleValidate}
- disabled={!checkKey || validating || !formData.baseUrl.trim()}
- variant="secondary"
- >
- {validating ? t("checking") : t("check")}
- </Button>
- </div>
- </div>
- {validationResult && (
- <Badge variant={validationResult === "success" ? "success" : "error"}>
- {validationResult === "success" ? t("valid") : t("invalid")}
- </Badge>
- )}
- <div className="flex gap-2">
- <Button
- onClick={handleSubmit}
- fullWidth
- disabled={
- !formData.name.trim() || !formData.prefix.trim() || !formData.baseUrl.trim() || saving
- }
- >
- {saving ? t("saving") : t("save")}
- </Button>
- <Button onClick={onClose} variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </div>
- </div>
- </Modal>
- );
-}
-
-// ──── ImportGeminiAuthModal ────────────────────────────────────────────────────
-
-interface ImportGeminiAuthModalProps {
- onClose: () => void;
- onSuccess: () => void;
-}
-
-type GeminiImportTopTab = "single" | "bulk";
-type GeminiBulkSubMode = "upload" | "paste" | "zip";
-
-interface GeminiBulkEntry {
- name: string;
- json: unknown;
- parseError: string | null;
- email: string | null;
-}
-
-function extractEmailFromGeminiJwt(idToken: string): string | null {
- try {
- const parts = idToken.split(".");
- if (parts.length !== 3) return null;
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
- return typeof payload.email === "string" ? payload.email : null;
- } catch {
- return null;
- }
-}
-
-function previewGeminiJson(json: unknown): { valid: boolean; email: string | null } {
- try {
- const doc = json && typeof json === "object" ? (json as Record<string, unknown>) : null;
- if (!doc) return { valid: false, email: null };
- if (!doc.access_token || !doc.refresh_token || !doc.id_token)
- return { valid: false, email: null };
- const email = typeof doc.id_token === "string" ? extractEmailFromGeminiJwt(doc.id_token) : null;
- return { valid: true, email };
- } catch {
- return { valid: false, email: null };
- }
-}
-
-function ImportGeminiAuthModal({ onClose, onSuccess }: ImportGeminiAuthModalProps) {
- const t = useTranslations("providers");
- const notify = useNotificationStore();
-
- const [topTab, setTopTab] = useState<GeminiImportTopTab>("single");
- const [singleSubTab, setSingleSubTab] = useState<"upload" | "paste">("upload");
- const [bulkSubMode, setBulkSubMode] = useState<GeminiBulkSubMode>("upload");
-
- // Single
- const [singleJson, setSingleJson] = useState<unknown>(null);
- const [singlePasteText, setSinglePasteText] = useState("");
- const [singleName, setSingleName] = useState("");
- const [singleEmail, setSingleEmail] = useState("");
- const [overwriteExisting, setOverwriteExisting] = useState(false);
- const [submitting, setSubmitting] = useState(false);
-
- // Bulk
- const [bulkEntries, setBulkEntries] = useState<GeminiBulkEntry[]>([]);
- const [bulkPasteText, setBulkPasteText] = useState("");
- const [bulkSubmitting, setBulkSubmitting] = useState(false);
- const [bulkErrors, setBulkErrors] = useState<{ index: number; name: string; message: string }[]>(
- []
- );
- const [bulkResult, setBulkResult] = useState<{
- success: number;
- failed: number;
- total: number;
- } | null>(null);
- const [zipExtracting, setZipExtracting] = useState(false);
-
- const handleSingleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- const json = JSON.parse(ev.target?.result as string);
- setSingleJson(json);
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportInvalidJson")
- ? t("geminiImportInvalidJson")
- : "Could not parse the file as JSON"
- );
- }
- };
- reader.readAsText(file);
- };
-
- const handleSingleSubmit = async () => {
- if (submitting) return;
- setSubmitting(true);
- try {
- const body =
- singleSubTab === "paste"
- ? {
- source: { kind: "text", text: singlePasteText },
- name: singleName || undefined,
- email: singleEmail || undefined,
- overwriteExisting,
- }
- : {
- source: { kind: "json", json: singleJson },
- name: singleName || undefined,
- email: singleEmail || undefined,
- overwriteExisting,
- };
-
- const res = await fetch("/api/providers/gemini-cli-auth/import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
-
- const data = await res.json().catch(() => ({}));
-
- if (!res.ok) {
- if (data.code === "duplicate_account") {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportDuplicate")
- ? t("geminiImportDuplicate")
- : 'Account already exists — enable "Replace existing" to overwrite'
- );
- } else if (data.code === "identity_unverified") {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportIdentityUnverified")
- ? t("geminiImportIdentityUnverified")
- : 'Could not verify identity from id_token. Enable "Replace existing" or provide an email.'
- );
- } else {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("geminiImportFailed")
- ? t("geminiImportFailed")
- : "Failed to import Gemini auth")
- );
- }
- return;
- }
-
- const preview = previewGeminiJson(singleJson);
- notify.success(
- typeof t.has === "function" && t.has("geminiImportSuccess")
- ? t("geminiImportSuccess")
- : `Gemini connection imported successfully${preview.email ? ` (${preview.email})` : ""}`
- );
- onSuccess();
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportFailed")
- ? t("geminiImportFailed")
- : "Failed to import Gemini auth"
- );
- } finally {
- setSubmitting(false);
- }
- };
-
- const handleBulkFilesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const files = Array.from(e.target.files || []);
- const newEntries: GeminiBulkEntry[] = [];
- let pending = files.length;
- if (!pending) return;
- files.forEach((file) => {
- const reader = new FileReader();
- reader.onload = (ev) => {
- try {
- const json = JSON.parse(ev.target?.result as string);
- const { email } = previewGeminiJson(json);
- newEntries.push({
- name: file.name.replace(/\.json$/, ""),
- json,
- parseError: null,
- email,
- });
- } catch {
- newEntries.push({
- name: file.name,
- json: null,
- parseError: "Not valid JSON",
- email: null,
- });
- }
- pending--;
- if (pending === 0) setBulkEntries((prev) => [...prev, ...newEntries]);
- };
- reader.readAsText(file);
- });
- };
-
- const handleBulkPasteChange = (text: string) => {
- setBulkPasteText(text);
- const trimmed = text.trim();
- if (!trimmed) {
- setBulkEntries([]);
- return;
- }
- try {
- const arr = JSON.parse(trimmed);
- if (Array.isArray(arr)) {
- setBulkEntries(
- arr.map((item, i) => {
- const { email } = previewGeminiJson(item);
- return { name: email || `entry ${i + 1}`, json: item, parseError: null, email };
- })
- );
- } else {
- const { email } = previewGeminiJson(arr);
- setBulkEntries([{ name: email || "entry 1", json: arr, parseError: null, email }]);
- }
- } catch {
- setBulkEntries([
- { name: "parse error", json: null, parseError: "Invalid JSON", email: null },
- ]);
- }
- };
-
- const handleZipUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- setZipExtracting(true);
- try {
- const res = await fetch("/api/providers/gemini-cli-auth/zip-extract", {
- method: "POST",
- headers: { "Content-Type": "application/zip" },
- body: file,
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("geminiImportBulkZipError")
- ? t("geminiImportBulkZipError")
- : "Failed to extract ZIP")
- );
- return;
- }
- const entries: GeminiBulkEntry[] = (data.entries || []).map(
- (e: { name: string; json: unknown; parseError: string | null }) => {
- const { email } = previewGeminiJson(e.json);
- return { name: e.name, json: e.json, parseError: e.parseError, email };
- }
- );
- setBulkEntries(entries);
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportBulkZipError")
- ? t("geminiImportBulkZipError")
- : "Failed to extract ZIP"
- );
- } finally {
- setZipExtracting(false);
- }
- };
-
- const handleBulkSubmit = async () => {
- if (bulkSubmitting) return;
- setBulkSubmitting(true);
- setBulkErrors([]);
- setBulkResult(null);
- try {
- const validEntries = bulkEntries.filter((e) => e.json !== null);
- if (validEntries.length === 0) {
- notify.error("No valid entries to import");
- return;
- }
- const res = await fetch("/api/providers/gemini-cli-auth/import-bulk", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- entries: validEntries.map((e) => ({
- json: e.json,
- name: e.name,
- email: e.email || undefined,
- })),
- overwriteExisting,
- }),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- notify.error(
- data.error ||
- (typeof t.has === "function" && t.has("geminiImportBulkFailed")
- ? t("geminiImportBulkFailed")
- : "Some entries failed to import")
- );
- return;
- }
- setBulkResult({ success: data.success, failed: data.failed, total: data.total });
- if (data.errors?.length > 0) setBulkErrors(data.errors);
- if (data.success > 0) {
- notify.success(
- typeof t.has === "function" && t.has("geminiImportBulkSuccess")
- ? t("geminiImportBulkSuccess", { count: data.success })
- : `Imported ${data.success} Gemini connections`
- );
- if (data.failed === 0) onSuccess();
- }
- } catch {
- notify.error(
- typeof t.has === "function" && t.has("geminiImportBulkFailed")
- ? t("geminiImportBulkFailed")
- : "Some entries failed to import"
- );
- } finally {
- setBulkSubmitting(false);
- }
- };
-
- const tabLabels: Record<GeminiImportTopTab, string> = {
- single:
- typeof t.has === "function" && t.has("geminiImportTabSingle")
- ? t("geminiImportTabSingle")
- : "Single",
- bulk:
- typeof t.has === "function" && t.has("geminiImportTabBulk")
- ? t("geminiImportTabBulk")
- : "Bulk",
- };
-
- const modalTitle =
- typeof t.has === "function" && t.has("geminiImportModalTitle")
- ? t("geminiImportModalTitle")
- : "Import Gemini Auth";
-
- return (
- <Modal isOpen onClose={onClose} title={modalTitle}>
- <div className="flex flex-col gap-4">
- <div className="flex gap-1 border-b border-border pb-0">
- {(["single", "bulk"] as GeminiImportTopTab[]).map((tab) => (
- <button
- key={tab}
- onClick={() => setTopTab(tab)}
- className={`px-3 py-1.5 text-sm rounded-t-md transition-colors ${
- topTab === tab
- ? "bg-primary/10 text-primary border-b-2 border-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {tabLabels[tab]}
- </button>
- ))}
- </div>
-
- {topTab === "single" && (
- <div className="flex flex-col gap-3">
- <div className="flex gap-1">
- {(["upload", "paste"] as const).map((sub) => (
- <button
- key={sub}
- onClick={() => setSingleSubTab(sub)}
- className={`px-2 py-1 text-xs rounded transition-colors ${
- singleSubTab === sub
- ? "bg-bg-subtle text-text-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {sub === "upload"
- ? typeof t.has === "function" && t.has("geminiImportTabUpload")
- ? t("geminiImportTabUpload")
- : "Upload file"
- : typeof t.has === "function" && t.has("geminiImportTabPaste")
- ? t("geminiImportTabPaste")
- : "Paste JSON"}
- </button>
- ))}
- </div>
- {singleSubTab === "upload" ? (
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportFileLabel")
- ? t("geminiImportFileLabel")
- : "Choose oauth_creds.json"}
- </label>
- <input
- type="file"
- accept=".json"
- onChange={handleSingleFileChange}
- className="block w-full text-sm"
- />
- {singleJson && previewGeminiJson(singleJson).valid && (
- <p className="mt-1 text-xs text-emerald-500">
- Valid Gemini OAuth credentials
- {previewGeminiJson(singleJson).email
- ? ` (${previewGeminiJson(singleJson).email})`
- : ""}
- </p>
- )}
- {singleJson && !previewGeminiJson(singleJson).valid && (
- <p className="mt-1 text-xs text-red-500">
- {typeof t.has === "function" && t.has("geminiImportInvalidShape")
- ? t("geminiImportInvalidShape")
- : "The file is not a valid oauth_creds.json"}
- </p>
- )}
- </div>
- ) : (
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportPasteLabel")
- ? t("geminiImportPasteLabel")
- : "Paste the JSON content"}
- </label>
- <textarea
- value={singlePasteText}
- onChange={(e) => setSinglePasteText(e.target.value)}
- rows={6}
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
- placeholder='{ "access_token": "...", "refresh_token": "...", "id_token": "..." }'
- />
- </div>
- )}
- <div className="grid grid-cols-2 gap-2">
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportEmailLabel")
- ? t("geminiImportEmailLabel")
- : "Account email"}
- </label>
- <input
- type="email"
- value={singleEmail}
- onChange={(e) => setSingleEmail(e.target.value)}
- placeholder="auto-detected from id_token"
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
- />
- </div>
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportNameLabel")
- ? t("geminiImportNameLabel")
- : "Connection name (optional)"}
- </label>
- <input
- type="text"
- value={singleName}
- onChange={(e) => setSingleName(e.target.value)}
- placeholder="My Gemini account"
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs text-text-main"
- />
- </div>
- </div>
- <label className="flex items-center gap-2 text-xs text-text-muted">
- <input
- type="checkbox"
- checked={overwriteExisting}
- onChange={(e) => setOverwriteExisting(e.target.checked)}
- />
- {typeof t.has === "function" && t.has("geminiImportOverwriteLabel")
- ? t("geminiImportOverwriteLabel")
- : "Replace existing connection if account already exists"}
- </label>
- <Button
- loading={submitting}
- onClick={handleSingleSubmit}
- disabled={singleSubTab === "upload" ? !singleJson : !singlePasteText.trim()}
- >
- {typeof t.has === "function" && t.has("geminiImportSubmit")
- ? t("geminiImportSubmit")
- : "Import"}
- </Button>
- </div>
- )}
-
- {topTab === "bulk" && (
- <div className="flex flex-col gap-3">
- <div className="flex gap-1">
- {(["upload", "paste", "zip"] as GeminiBulkSubMode[]).map((mode) => (
- <button
- key={mode}
- onClick={() => {
- setBulkSubMode(mode);
- setBulkEntries([]);
- }}
- className={`px-2 py-1 text-xs rounded transition-colors ${
- bulkSubMode === mode
- ? "bg-bg-subtle text-text-primary"
- : "text-text-muted hover:text-text-primary"
- }`}
- >
- {mode === "upload"
- ? typeof t.has === "function" && t.has("geminiImportBulkModeUpload")
- ? t("geminiImportBulkModeUpload")
- : "Upload files"
- : mode === "paste"
- ? typeof t.has === "function" && t.has("geminiImportBulkModePaste")
- ? t("geminiImportBulkModePaste")
- : "Paste JSON array"
- : typeof t.has === "function" && t.has("geminiImportBulkModeZip")
- ? t("geminiImportBulkModeZip")
- : "Upload ZIP"}
- </button>
- ))}
- </div>
-
- {bulkSubMode === "upload" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportBulkUploadHint")
- ? t("geminiImportBulkUploadHint")
- : "Drop or pick up to 50 oauth_creds.json files (256KB each, 10MB total)."}
- </p>
- <input
- type="file"
- accept=".json"
- multiple
- onChange={handleBulkFilesChange}
- className="block w-full text-sm"
- />
- </div>
- )}
- {bulkSubMode === "paste" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportBulkPasteHint")
- ? t("geminiImportBulkPasteHint")
- : "Paste an array of objects: [{ json, name?, email? }, ...]"}
- </p>
- <textarea
- value={bulkPasteText}
- onChange={(e) => handleBulkPasteChange(e.target.value)}
- rows={6}
- className="w-full rounded border border-border bg-bg-subtle px-2 py-1.5 text-xs font-mono text-text-main"
- placeholder="[{ ... }, { ... }]"
- />
- </div>
- )}
- {bulkSubMode === "zip" && (
- <div>
- <p className="text-xs text-text-muted mb-1">
- {typeof t.has === "function" && t.has("geminiImportBulkZipHint")
- ? t("geminiImportBulkZipHint")
- : "ZIP containing oauth_creds.json entries. Max 50 entries, 10MB unpacked."}
- </p>
- {zipExtracting ? (
- <p className="text-xs text-primary animate-pulse">
- {typeof t.has === "function" && t.has("geminiImportBulkZipExtracting")
- ? t("geminiImportBulkZipExtracting")
- : "Extracting ZIP…"}
- </p>
- ) : (
- <input
- type="file"
- accept=".zip"
- onChange={handleZipUpload}
- className="block w-full text-sm"
- />
- )}
- </div>
- )}
-
- {bulkEntries.length > 0 && (
- <div className="rounded border border-border bg-bg-subtle px-2 py-1.5 max-h-36 overflow-y-auto">
- {bulkEntries.map((e, i) => (
- <div
- key={i}
- className={`text-xs py-0.5 flex items-center gap-1 ${e.parseError ? "text-red-500" : "text-text-main"}`}
- >
- <span className="material-symbols-outlined text-[12px]">
- {e.parseError ? "error" : "check_circle"}
- </span>
- {e.name}
- {e.email ? ` (${e.email})` : ""}
- {e.parseError ? ` — ${e.parseError}` : ""}
- </div>
- ))}
- </div>
- )}
-
- <label className="flex items-center gap-2 text-xs text-text-muted">
- <input
- type="checkbox"
- checked={overwriteExisting}
- onChange={(e) => setOverwriteExisting(e.target.checked)}
- />
- {typeof t.has === "function" && t.has("geminiImportOverwriteLabel")
- ? t("geminiImportOverwriteLabel")
- : "Replace existing connection if account already exists"}
- </label>
-
- {bulkResult && (
- <div className="rounded bg-bg-subtle px-2 py-1.5 text-xs">
- {bulkResult.success}/{bulkResult.total} imported
- {bulkResult.failed > 0 ? `, ${bulkResult.failed} failed` : ""}
- </div>
- )}
- {bulkErrors.length > 0 && (
- <div className="rounded border border-red-500/30 bg-red-500/5 px-2 py-1.5 max-h-28 overflow-y-auto">
- {bulkErrors.map((e) => (
- <div key={e.index} className="text-xs text-red-500 py-0.5">
- {e.name}: {e.message}
- </div>
- ))}
- </div>
- )}
-
- <Button
- loading={bulkSubmitting}
- onClick={handleBulkSubmit}
- disabled={bulkEntries.filter((e) => e.json !== null).length === 0}
- >
- {typeof t.has === "function" && t.has("geminiImportBulkSubmit")
- ? t("geminiImportBulkSubmit")
- : "Import all"}
- </Button>
- </div>
- )}
- </div>
- </Modal>
- );
-}
-
-// ──── ApplyGeminiAuthModal ────────────────────────────────────────────────────
-
-function ApplyGeminiAuthModal({
- connectionId,
- inProgress,
- onConfirm,
- onClose,
-}: {
- connectionId: string | null;
- inProgress: boolean;
- onConfirm: (id: string) => Promise<void>;
- onClose: () => void;
-}) {
- const t = useTranslations("providers");
- const [confirmed, setConfirmed] = useState(false);
- const isOpen = !!connectionId;
-
- if (!connectionId) return null;
-
- const title =
- typeof t.has === "function" && t.has("geminiApplyModalTitle")
- ? t("geminiApplyModalTitle")
- : "Apply to Local Gemini CLI";
- const targetLabel =
- typeof t.has === "function" && t.has("geminiApplyTargetLabel")
- ? t("geminiApplyTargetLabel")
- : "Target path";
- const backupLabel =
- typeof t.has === "function" && t.has("geminiApplyBackupLabel")
- ? t("geminiApplyBackupLabel")
- : "Backups";
- const warning =
- typeof t.has === "function" && t.has("geminiApplyWarning")
- ? t("geminiApplyWarning")
- : "This will replace the existing oauth_creds.json and update google_accounts.json. Continue?";
- const confirmText =
- typeof t.has === "function" && t.has("geminiApplyConfirmCheckbox")
- ? t("geminiApplyConfirmCheckbox")
- : "I confirm I want to replace the existing oauth_creds.json";
- const applyText =
- typeof t.has === "function" && t.has("geminiApply") ? t("geminiApply") : "Apply";
- const accountsHint =
- typeof t.has === "function" && t.has("geminiApplyAccountsHint")
- ? t("geminiApplyAccountsHint")
- : "The google_accounts.json active account will be updated to match this connection.";
-
- return (
- <Modal isOpen={isOpen} title={title} onClose={onClose}>
- <div className="flex flex-col gap-4">
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{targetLabel}</div>
- <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
- ~/.gemini/oauth_creds.json
- </code>
- <p className="mt-1 text-xs text-text-muted">Path is auto-detected per OS (Linux/Mac).</p>
- </div>
- <div>
- <div className="text-xs uppercase text-text-muted mb-1">{backupLabel}</div>
- <code className="block rounded bg-sidebar px-2 py-1.5 text-xs font-mono text-text-main">
- ~/.gemini/oauth_creds-&#123;timestamp&#125;.bak
- </code>
- </div>
- <div className="rounded bg-amber-500/10 border border-amber-500/20 px-3 py-2 text-xs text-amber-400">
- {accountsHint}
- </div>
- <p className="text-sm text-text-muted">{warning}</p>
- <label className="flex items-center gap-2 text-sm">
- <input
- type="checkbox"
- checked={confirmed}
- onChange={(e) => setConfirmed(e.target.checked)}
- />
- {confirmText}
- </label>
- <div className="flex justify-end gap-2">
- <Button variant="secondary" onClick={onClose} disabled={inProgress}>
- Cancel
- </Button>
- <Button
- loading={inProgress}
- disabled={!confirmed || inProgress}
- onClick={() => void onConfirm(connectionId)}
- >
- {applyText}
- </Button>
- </div>
- </div>
- </Modal>
- );
+ return <ProviderDetailPageClient />;
}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/providerDetailConstants.ts b/src/app/(dashboard)/dashboard/providers/[id]/providerDetailConstants.ts
new file mode 100644
index 0000000000..0c7cbb5327
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/providerDetailConstants.ts
@@ -0,0 +1,6 @@
+// Shared constants for the provider-detail page and its extracted modals
+// (Issue #3501 strangler-fig decomposition). Kept in a leaf module so both the
+// page client and the colocated modals can import without a circular dependency.
+
+/** Default chat path for Claude-Code-compatible (Anthropic-shaped) custom nodes. */
+export const CC_COMPATIBLE_DEFAULT_CHAT_PATH = "/v1/messages?beta=true";
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/providerPageHelpers.ts b/src/app/(dashboard)/dashboard/providers/[id]/providerPageHelpers.ts
new file mode 100644
index 0000000000..da5b053e0a
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/providers/[id]/providerPageHelpers.ts
@@ -0,0 +1,821 @@
+// Pure, shared helpers for the provider-detail page and its extracted modals
+// (Issue #3501 strangler-fig decomposition, Phase 2). Leaf module — imports only
+// from @/shared, @/lib and colocated sibling modules that are themselves acyclic,
+// so the page client AND colocated modals can import these without a circular
+// dependency. Extracting them here unblocks moving the heavier modals
+// (AddApiKeyModal / EditConnectionModal) out of the god-component in later phases.
+import { LOCAL_PROVIDERS, isSelfHostedChatProvider } from "@/shared/constants/providers";
+import {
+ MODEL_COMPAT_PROTOCOL_KEYS,
+ type ModelCompatProtocolKey,
+} from "@/shared/constants/modelCompat";
+import {
+ getClaudeCodeCompatibleRequestDefaults as _getClaudeCodeCompatibleRequestDefaults,
+ getCodexRequestDefaults as _getCodexRequestDefaults,
+ type CodexServiceTier,
+} from "@/lib/providers/requestDefaults";
+import { type CodexGlobalServiceMode } from "@/lib/providers/codexFastTier";
+import { type WebSessionCredentialRequirement } from "./webSessionCredentials";
+
+// ---------------------------------------------------------------------------
+// Types shared between page + modals
+// ---------------------------------------------------------------------------
+
+export type ProviderMessageTranslator = ((
+ key: string,
+ values?: Record<string, unknown>
+) => string) & {
+ has?: (key: string) => boolean;
+};
+
+export type LocalProviderMetadata = {
+ name?: string;
+ localDefault?: string;
+ [key: string]: unknown;
+};
+
+export type CommandCodeAuthFlowState = {
+ phase:
+ | "idle"
+ | "starting"
+ | "polling"
+ | "received"
+ | "applying"
+ | "applied"
+ | "expired"
+ | "error";
+ state: string;
+ authUrl: string;
+ callbackUrl: string;
+ expiresAt: string | null;
+ message?: string;
+};
+
+// ---------------------------------------------------------------------------
+// Compat model map types (shared by upstream-headers helpers and the page)
+// ---------------------------------------------------------------------------
+
+export type CompatByProtocolMap = Partial<
+ Record<
+ ModelCompatProtocolKey,
+ {
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ }
+ >
+>;
+
+export type CompatModelRow = {
+ id?: string;
+ name?: string;
+ source?: string;
+ apiFormat?: string;
+ supportedEndpoints?: string[];
+ normalizeToolCallId?: boolean;
+ preserveOpenAIDeveloperRole?: boolean;
+ isHidden?: boolean;
+ upstreamHeaders?: Record<string, string>;
+ compatByProtocol?: CompatByProtocolMap;
+};
+
+export type CompatModelMap = Map<string, CompatModelRow>;
+
+export type HeaderDraftRow = { id: string; name: string; value: string };
+
+// ---------------------------------------------------------------------------
+// Utility — message translation with fallback
+// ---------------------------------------------------------------------------
+
+export function providerText(
+ t: ProviderMessageTranslator,
+ key: string,
+ fallback: string,
+ values?: Record<string, unknown>
+): string {
+ if (typeof t.has === "function" && t.has(key)) {
+ return t(key, values);
+ }
+ if (values) {
+ return Object.entries(values).reduce(
+ (acc, [name, value]) => acc.replaceAll(`{${name}}`, String(value)),
+ fallback
+ );
+ }
+ return fallback;
+}
+
+export function providerCountText(
+ t: ProviderMessageTranslator,
+ key: string,
+ count: number,
+ singularFallback: string,
+ pluralFallback: string
+): string {
+ return providerText(t, key, count === 1 ? singularFallback : pluralFallback, { count });
+}
+
+export function readBooleanToggle(value: unknown, fallback: boolean): boolean {
+ if (typeof value === "boolean") return value;
+ if (typeof value === "number") return value === 1;
+ if (typeof value === "string") {
+ const normalized = value.trim().toLowerCase();
+ if (normalized === "1" || normalized === "true") return true;
+ if (normalized === "0" || normalized === "false") return false;
+ }
+ return fallback;
+}
+
+// ---------------------------------------------------------------------------
+// Base-URL helpers
+// ---------------------------------------------------------------------------
+
+export const CONFIGURABLE_BASE_URL_PROVIDERS = new Set([
+ "azure-openai",
+ "azure-ai",
+ "bailian-coding-plan",
+ "xiaomi-mimo",
+ "siliconflow",
+ "heroku",
+ "databricks",
+ "snowflake",
+ "searxng-search",
+ "petals",
+]);
+
+export const DEFAULT_PROVIDER_BASE_URLS: Record<string, string> = {
+ "azure-openai": "https://example-resource.openai.azure.com",
+ "azure-ai": "https://example-resource.services.ai.azure.com/openai/v1",
+ "bailian-coding-plan": "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",
+ "xiaomi-mimo": "https://token-plan-sgp.xiaomimimo.com/v1",
+ siliconflow: "https://api.siliconflow.com/v1",
+ "searxng-search": "http://localhost:8888/search",
+ petals: "https://chat.petals.dev/api/v1/generate",
+};
+
+export function getLocalProviderMetadata(providerId?: string | null) {
+ if (!providerId || !isSelfHostedChatProvider(providerId)) return null;
+ return (LOCAL_PROVIDERS as Record<string, LocalProviderMetadata>)[providerId] || null;
+}
+
+export function isBaseUrlConfigurableProvider(providerId?: string | null) {
+ return Boolean(
+ providerId &&
+ (CONFIGURABLE_BASE_URL_PROVIDERS.has(providerId) || isSelfHostedChatProvider(providerId))
+ );
+}
+
+export function getProviderBaseUrlDefault(providerId?: string | null) {
+ const localProvider = getLocalProviderMetadata(providerId);
+ if (typeof localProvider?.localDefault === "string" && localProvider.localDefault.trim()) {
+ return localProvider.localDefault;
+ }
+ return providerId ? DEFAULT_PROVIDER_BASE_URLS[providerId] || "" : "";
+}
+
+export function getProviderBaseUrlHint(
+ providerId?: string | null,
+ t?: ((key: string, values?: Record<string, unknown>) => string) | null
+) {
+ const localProvider = getLocalProviderMetadata(providerId);
+ if (localProvider && t) {
+ return t("localProviderBaseUrlHint", {
+ provider: localProvider.name || providerId,
+ baseUrl: getProviderBaseUrlDefault(providerId),
+ });
+ }
+ switch (providerId) {
+ case "azure-openai":
+ return t ? t("azureOpenAiBaseUrlHint") : undefined;
+ case "bailian-coding-plan":
+ return t ? t("bailianBaseUrlHint") : undefined;
+ case "xiaomi-mimo":
+ return t ? t("xiaomiMimoBaseUrlHint") : undefined;
+ case "heroku":
+ return t ? t("herokuBaseUrlHint") : undefined;
+ case "databricks":
+ return t ? t("databricksBaseUrlHint") : undefined;
+ case "snowflake":
+ return t ? t("snowflakeBaseUrlHint") : undefined;
+ case "searxng-search":
+ return t ? t("searxngBaseUrlHint") : undefined;
+ default:
+ return undefined;
+ }
+}
+
+export function getProviderBaseUrlPlaceholder(providerId?: string | null) {
+ if (isSelfHostedChatProvider(providerId || "")) {
+ return getProviderBaseUrlDefault(providerId);
+ }
+ switch (providerId) {
+ case "azure-openai":
+ return "https://my-resource.openai.azure.com";
+ case "bailian-coding-plan":
+ case "xiaomi-mimo":
+ return getProviderBaseUrlDefault(providerId);
+ case "siliconflow":
+ return "https://api.siliconflow.cn/v1";
+ case "heroku":
+ return "https://us.inference.heroku.com";
+ case "databricks":
+ return "https://adb-1234567890123456.7.azuredatabricks.net/serving-endpoints";
+ case "snowflake":
+ return "https://example-account.snowflakecomputing.com";
+ case "searxng-search":
+ return "http://localhost:8888/search";
+ default:
+ return "";
+ }
+}
+
+export function isGlmProvider(providerId?: string | null) {
+ return providerId === "glm" || providerId === "glm-cn" || providerId === "glmt";
+}
+
+// ---------------------------------------------------------------------------
+// Routing-tags / excluded-models parse + format
+// ---------------------------------------------------------------------------
+
+export function parseRoutingTagsInput(value: string): string[] | undefined {
+ const tags = Array.from(
+ new Set(
+ value
+ .split(",")
+ .map((tag) => tag.trim().toLowerCase())
+ .filter(Boolean)
+ )
+ );
+ return tags.length > 0 ? tags : undefined;
+}
+
+export function parseExcludedModelsInput(value: string): string[] | undefined {
+ const patterns = Array.from(
+ new Set(
+ value
+ .split(",")
+ .map((pattern) => pattern.trim())
+ .filter(Boolean)
+ )
+ );
+ return patterns.length > 0 ? patterns : undefined;
+}
+
+export function formatRoutingTagsInput(value: unknown): string {
+ if (!Array.isArray(value)) return "";
+ return value
+ .filter((tag): tag is string => typeof tag === "string" && tag.trim().length > 0)
+ .join(", ");
+}
+
+export function formatExcludedModelsInput(value: unknown): string {
+ if (!Array.isArray(value)) return "";
+ return value
+ .filter(
+ (pattern): pattern is string => typeof pattern === "string" && pattern.trim().length > 0
+ )
+ .join(", ");
+}
+
+// ---------------------------------------------------------------------------
+// Web-session credential label / hint helpers (Phase 2b)
+// ---------------------------------------------------------------------------
+
+export function getWebSessionCredentialLabel(
+ t: ProviderMessageTranslator,
+ requirement: WebSessionCredentialRequirement,
+ optional: boolean
+): string {
+ if (requirement.kind === "none") {
+ return providerText(t, "webNoAuthCredentialLabel", "No credential required");
+ }
+ const baseLabel =
+ requirement.kind === "token"
+ ? providerText(t, "webTokenCredentialLabel", "Web session token")
+ : t("sessionCookieLabel");
+ return optional ? `${baseLabel} (${t("optional").toLowerCase()})` : baseLabel;
+}
+
+export function getWebSessionCredentialHint(
+ t: ProviderMessageTranslator,
+ requirement: WebSessionCredentialRequirement,
+ providerName: string,
+ editing: boolean
+): string | undefined {
+ if (requirement.kind === "none") return undefined;
+
+ const values = { provider: providerName, credential: requirement.credentialName };
+ if (editing) {
+ return requirement.kind === "token"
+ ? providerText(
+ t,
+ "webTokenEditHint",
+ "Leave blank to keep the current web session token. Credential: {credential}.",
+ values
+ )
+ : providerText(
+ t,
+ "webCookieEditHint",
+ "Leave blank to keep the current session cookie. Required cookie: {credential}.",
+ values
+ );
+ }
+
+ return requirement.kind === "token"
+ ? providerText(
+ t,
+ "webTokenCredentialHint",
+ "Credential: {credential}. Paste the token value from your own signed-in {provider} web session, or a DevTools HAR export if the provider supports it.",
+ values
+ )
+ : providerText(
+ t,
+ "webCookieCredentialHint",
+ "Required cookie: {credential}. Paste the Cookie header value from your own signed-in {provider} web session. Do not include the Cookie: prefix.",
+ values
+ );
+}
+
+export function getWebSessionCredentialCheckLabel(
+ t: ProviderMessageTranslator,
+ requirement: WebSessionCredentialRequirement
+): string {
+ if (requirement.kind === "token") return providerText(t, "checkWebToken", "Check token");
+ return providerText(t, "checkCookie", "Check cookie");
+}
+
+export function getAddCredentialModalTitle(
+ t: ProviderMessageTranslator,
+ providerName: string,
+ requirement: WebSessionCredentialRequirement | null
+): string {
+ if (!requirement) return t("addProviderApiKeyTitle", { provider: providerName });
+ if (requirement.kind === "none") {
+ return providerText(t, "addProviderConnectionTitle", "Add {provider} connection", {
+ provider: providerName,
+ });
+ }
+ if (requirement.kind === "token") {
+ return providerText(t, "addProviderWebTokenTitle", "Add {provider} web token", {
+ provider: providerName,
+ });
+ }
+ return providerText(t, "addProviderSessionCookieTitle", "Add {provider} session cookie", {
+ provider: providerName,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Upstream-headers helpers (Phase 2b)
+// ---------------------------------------------------------------------------
+
+export const UPSTREAM_HEADERS_UI_MAX = 16;
+
+export function upstreamHeadersRecordsEqual(
+ a: Record<string, string>,
+ b: Record<string, string>
+): boolean {
+ const ka = Object.keys(a).sort();
+ const kb = Object.keys(b).sort();
+ if (ka.length !== kb.length) return false;
+ return ka.every((k, i) => k === kb[i] && a[k] === b[k]);
+}
+
+export function headerRowsToRecord(rows: HeaderDraftRow[]): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const r of rows) {
+ const k = r.name.trim();
+ if (!k) continue;
+ out[k] = r.value;
+ }
+ return out;
+}
+
+// Internal helper: returns the per-protocol compat slice for a model (custom
+// overrides take precedence over overrideMap).
+export function getProtoSlice(
+ c: CompatModelRow | undefined,
+ o: CompatModelRow | undefined,
+ protocol: string
+) {
+ return c?.compatByProtocol?.[protocol] ?? o?.compatByProtocol?.[protocol];
+}
+
+export function effectiveUpstreamHeadersForProtocol(
+ modelId: string,
+ protocol: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): Record<string, string> {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ const base: Record<string, string> = {};
+ if (c?.upstreamHeaders && typeof c.upstreamHeaders === "object") {
+ Object.assign(base, c.upstreamHeaders);
+ } else if (o?.upstreamHeaders && typeof o.upstreamHeaders === "object") {
+ Object.assign(base, o.upstreamHeaders);
+ }
+ const pc = getProtoSlice(c, o, protocol);
+ if (pc?.upstreamHeaders && typeof pc.upstreamHeaders === "object") {
+ Object.assign(base, pc.upstreamHeaders);
+ }
+ return base;
+}
+
+export function anyUpstreamHeadersBadge(
+ modelId: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ const nonempty = (u: unknown) =>
+ u && typeof u === "object" && !Array.isArray(u) && Object.keys(u as object).length > 0;
+ if (nonempty(c?.upstreamHeaders) || nonempty(o?.upstreamHeaders)) return true;
+ for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
+ const pc = getProtoSlice(c, o, p);
+ if (nonempty(pc?.upstreamHeaders)) return true;
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------------------
+// Model-compat compute helpers (Phase 1e — moved from god-component).
+// These are pure functions that derive effective compat state from the two
+// maps (customModels + modelCompatOverrides). They live here so both the
+// page client AND extracted components can import them without a cycle.
+// ---------------------------------------------------------------------------
+
+export function buildCompatMap(rows: CompatModelRow[]): CompatModelMap {
+ const m = new Map<string, CompatModelRow>();
+ for (const r of rows) if (r.id) m.set(r.id, r);
+ return m;
+}
+
+export function isModelHiddenFn(
+ modelId: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ if (c && Object.prototype.hasOwnProperty.call(c, "isHidden")) {
+ return Boolean(c.isHidden);
+ }
+ const o = overrideMap.get(modelId);
+ if (o && Object.prototype.hasOwnProperty.call(o, "isHidden")) {
+ return Boolean(o.isHidden);
+ }
+ return false;
+}
+
+export function effectiveNormalizeForProtocol(
+ modelId: string,
+ protocol: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ const pc = getProtoSlice(c, o, protocol);
+ if (pc && Object.prototype.hasOwnProperty.call(pc, "normalizeToolCallId")) {
+ return Boolean(pc.normalizeToolCallId);
+ }
+ if (c?.normalizeToolCallId) return true;
+ return Boolean(o?.normalizeToolCallId);
+}
+
+export function effectivePreserveForProtocol(
+ modelId: string,
+ protocol: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ const pc = getProtoSlice(c, o, protocol);
+ if (pc && Object.prototype.hasOwnProperty.call(pc, "preserveOpenAIDeveloperRole")) {
+ return Boolean(pc.preserveOpenAIDeveloperRole);
+ }
+ if (c && Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole")) {
+ return Boolean(c.preserveOpenAIDeveloperRole);
+ }
+ if (o && Object.prototype.hasOwnProperty.call(o, "preserveOpenAIDeveloperRole")) {
+ return Boolean(o.preserveOpenAIDeveloperRole);
+ }
+ return true;
+}
+
+export function anyNormalizeCompatBadge(
+ modelId: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ if (c?.normalizeToolCallId || o?.normalizeToolCallId) return true;
+ for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
+ const pc = getProtoSlice(c, o, p);
+ if (pc?.normalizeToolCallId) return true;
+ }
+ return false;
+}
+
+export function anyNoPreserveCompatBadge(
+ modelId: string,
+ customMap: CompatModelMap,
+ overrideMap: CompatModelMap
+): boolean {
+ const c = customMap.get(modelId);
+ const o = overrideMap.get(modelId);
+ if (
+ c &&
+ Object.prototype.hasOwnProperty.call(c, "preserveOpenAIDeveloperRole") &&
+ c.preserveOpenAIDeveloperRole === false
+ ) {
+ return true;
+ }
+ if (
+ o &&
+ Object.prototype.hasOwnProperty.call(o, "preserveOpenAIDeveloperRole") &&
+ o.preserveOpenAIDeveloperRole === false
+ ) {
+ return true;
+ }
+ for (const p of MODEL_COMPAT_PROTOCOL_KEYS) {
+ const pc = getProtoSlice(c, o, p);
+ if (
+ pc &&
+ Object.prototype.hasOwnProperty.call(pc, "preserveOpenAIDeveloperRole") &&
+ pc.preserveOpenAIDeveloperRole === false
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------------------
+// Codex helpers + consts (Phase 2b)
+// ---------------------------------------------------------------------------
+
+export const CODEX_REASONING_STRENGTH_OPTIONS = [
+ { value: "none", label: "None" },
+ { value: "low", label: "Low" },
+ { value: "medium", label: "Medium" },
+ { value: "high", label: "High" },
+ { value: "xhigh", label: "XHigh" },
+];
+
+export const CODEX_ACCOUNT_SERVICE_TIER_VALUES: CodexServiceTier[] = [
+ "default",
+ "priority",
+ "flex",
+];
+
+export const CODEX_GLOBAL_SERVICE_MODE_VALUES: CodexGlobalServiceMode[] = [
+ "none",
+ ...CODEX_ACCOUNT_SERVICE_TIER_VALUES,
+];
+
+export function getCodexServiceTierLabel(
+ t: ProviderMessageTranslator,
+ value: CodexGlobalServiceMode
+): string {
+ if (value === "none") {
+ return providerText(t, "codexServiceModeNone", "No global setting");
+ }
+ if (value === "default") return providerText(t, "codexServiceTierDefault", "Default");
+ if (value === "priority") return providerText(t, "codexServiceTierPriority", "Priority");
+ return providerText(t, "codexServiceTierFlex", "Flex");
+}
+
+export function normalizeCodexLimitPolicy(policy: unknown): { use5h: boolean; useWeekly: boolean } {
+ const record =
+ policy && typeof policy === "object" && !Array.isArray(policy)
+ ? (policy as Record<string, unknown>)
+ : {};
+ return {
+ use5h: typeof record.use5h === "boolean" ? record.use5h : true,
+ useWeekly: typeof record.useWeekly === "boolean" ? record.useWeekly : true,
+ };
+}
+
+/**
+ * UI adapter around the canonical getCodexRequestDefaults from requestDefaults.ts.
+ * Adds the "medium" fallback for reasoningEffort required by the connection form.
+ */
+export function getCodexRequestDefaults(providerSpecificData: unknown): {
+ reasoningEffort: string;
+ serviceTier?: CodexServiceTier;
+} {
+ const defaults = _getCodexRequestDefaults(providerSpecificData);
+ return {
+ reasoningEffort: defaults.reasoningEffort ?? "medium",
+ ...(defaults.serviceTier ? { serviceTier: defaults.serviceTier } : {}),
+ };
+}
+
+export function getClaudeCodeCompatibleRequestDefaults(providerSpecificData: unknown): {
+ context1m: boolean;
+} {
+ const defaults = _getClaudeCodeCompatibleRequestDefaults(providerSpecificData);
+ return {
+ context1m: defaults.context1m === true,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Misc pure helpers (Phase 2b)
+// ---------------------------------------------------------------------------
+
+export const SILICONFLOW_ENDPOINTS = [
+ { id: "siliconflow", label: "Global", baseUrl: "https://api.siliconflow.com/v1" },
+ { id: "siliconflow-cn", label: "China", baseUrl: "https://api.siliconflow.cn/v1" },
+] as const;
+
+export function compatProtocolLabelKey(protocol: string): string {
+ if (protocol === "openai") return "compatProtocolOpenAI";
+ if (protocol === "openai-responses") return "compatProtocolOpenAIResponses";
+ if (protocol === "claude") return "compatProtocolClaude";
+ return "compatProtocolOpenAI";
+}
+
+export function extractCommandCodeCredentialInput(value: string): string {
+ const trimmed = value.trim();
+ if (!trimmed) return "";
+
+ try {
+ const parsed = JSON.parse(trimmed) as unknown;
+ if (parsed && typeof parsed === "object") {
+ const record = parsed as Record<string, unknown>;
+ const direct = record.apiKey || record.api_key || record.key || record.token;
+ if (typeof direct === "string" && direct.trim()) return direct.trim();
+ const nested = record.data;
+ if (nested && typeof nested === "object") {
+ const nestedRecord = nested as Record<string, unknown>;
+ const nestedKey = nestedRecord.apiKey || nestedRecord.api_key || nestedRecord.key;
+ if (typeof nestedKey === "string" && nestedKey.trim()) return nestedKey.trim();
+ }
+ }
+ } catch {
+ // Not JSON; continue with URL/raw parsing.
+ }
+
+ try {
+ const url = new URL(trimmed);
+ const key =
+ url.searchParams.get("apiKey") ||
+ url.searchParams.get("api_key") ||
+ url.searchParams.get("key") ||
+ url.searchParams.get("token");
+ if (key?.trim()) return key.trim();
+ const hash = url.hash.replace(/^#/, "");
+ if (hash) {
+ const hashParams = new URLSearchParams(hash);
+ const hashKey =
+ hashParams.get("apiKey") ||
+ hashParams.get("api_key") ||
+ hashParams.get("key") ||
+ hashParams.get("token");
+ if (hashKey?.trim()) return hashKey.trim();
+ }
+ } catch {
+ // Not a URL; use the raw value.
+ }
+
+ return trimmed;
+}
+
+export function normalizeAndValidateHttpBaseUrl(
+ rawValue: unknown,
+ fallbackUrl: string
+): { value: string | null; error: string | null } {
+ const value = (typeof rawValue === "string" ? rawValue.trim() : "") || fallbackUrl;
+ try {
+ const parsed = new URL(value);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ return { value: null, error: "Base URL must use http or https" };
+ }
+ return { value, error: null };
+ } catch {
+ return { value: null, error: "Base URL must be a valid URL" };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// PassthroughModelsSection test-all helpers (Issue #3610)
+// ---------------------------------------------------------------------------
+
+/**
+ * Builds the JSON body for a single-model batch-test request.
+ * When `autoHideFailed` is true the server will persist the hide,
+ * so this flag MUST be threaded through from the UI state.
+ */
+export function buildPassthroughTestBody(opts: {
+ providerId: string;
+ connectionId: string;
+ modelId: string;
+ autoHideFailed: boolean;
+}): {
+ providerId: string;
+ connectionId: string;
+ modelIds: string[];
+ autoHideFailed: boolean;
+} {
+ return {
+ providerId: opts.providerId,
+ connectionId: opts.connectionId,
+ modelIds: [opts.modelId],
+ autoHideFailed: opts.autoHideFailed,
+ };
+}
+
+/**
+ * Decides whether the visibility filter should be switched to "visible"
+ * after a test-all run completes.
+ *
+ * The rule: only switch when at least one model was hidden during the run
+ * AND the user had autoHideFailed enabled. This ensures that models that
+ * were just hidden don't remain on-screen, giving the user instant feedback.
+ */
+export function shouldSwitchToVisibleFilter(opts: {
+ autoHideFailed: boolean;
+ hiddenCount: number;
+}): boolean {
+ return opts.autoHideFailed && opts.hiddenCount > 0;
+}
+
+// ---------------------------------------------------------------------------
+// Error-type label map — shared by ConnectionRow and EditConnectionModal
+// ---------------------------------------------------------------------------
+export const ERROR_TYPE_LABELS: Record<
+ string,
+ { labelKey: string; variant: string }
+> = {
+ runtime_error: { labelKey: "errorTypeRuntime", variant: "warning" },
+ upstream_auth_error: { labelKey: "errorTypeUpstreamAuth", variant: "error" },
+ account_deactivated: { labelKey: "Account Deactivated", variant: "error" },
+ auth_missing: { labelKey: "errorTypeMissingCredential", variant: "warning" },
+ token_refresh_failed: { labelKey: "errorTypeRefreshFailed", variant: "warning" },
+ token_expired: { labelKey: "errorTypeTokenExpired", variant: "warning" },
+ upstream_rate_limited: { labelKey: "errorTypeRateLimited", variant: "warning" },
+ upstream_unavailable: { labelKey: "errorTypeUpstreamUnavailable", variant: "error" },
+ network_error: { labelKey: "errorTypeNetworkError", variant: "warning" },
+ unsupported: { labelKey: "errorTypeTestUnsupported", variant: "default" },
+ upstream_error: { labelKey: "errorTypeUpstreamError", variant: "error" },
+ banned: { labelKey: "errorTypeBanned", variant: "error" },
+ credits_exhausted: { labelKey: "errorTypeCreditsExhausted", variant: "warning" },
+};
+
+// ---------------------------------------------------------------------------
+// formatProviderModelsErrorResponse — shared error formatter for provider-models
+// API calls. Used by both the page client and CustomModelsSection.
+// ---------------------------------------------------------------------------
+
+type ProviderModelsApiErrorBody = {
+ error?: {
+ message?: string;
+ details?: Array<{ field?: string; message?: string }>;
+ };
+};
+
+export async function formatProviderModelsErrorResponse(res: Response): Promise<string> {
+ try {
+ const data = (await res.json()) as ProviderModelsApiErrorBody;
+ const err = data?.error;
+ if (Array.isArray(err?.details) && err.details.length > 0) {
+ return err.details
+ .map((d) => {
+ const f = typeof d.field === "string" && d.field ? d.field : "?";
+ const m = typeof d.message === "string" ? d.message : "";
+ return m ? `${f}: ${m}` : f;
+ })
+ .join("; ");
+ }
+ if (typeof err?.message === "string" && err.message.trim()) {
+ return err.message.trim();
+ }
+ } catch {
+ /* ignore */
+ }
+ const st = res.statusText?.trim();
+ return st || `HTTP ${res.status}`;
+}
+
+// ---------------------------------------------------------------------------
+// formatTimeAgo — used in EditConnectionModal's extra-key health display
+// ---------------------------------------------------------------------------
+export function formatTimeAgo(dateStr: string): string {
+ const now = Date.now();
+ const date = new Date(dateStr).getTime();
+ const diff = now - date;
+ if (diff < 0) return "just now";
+ const minutes = Math.floor(diff / 60000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return new Date(dateStr).toLocaleDateString();
+}
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCard.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCard.tsx
index 09bdfe91e2..8384840b0b 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCard.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCard.tsx
@@ -30,6 +30,8 @@ interface QuotaCardProps {
providerLabel: string;
onRefresh: () => void;
onOpenCutoff: () => void;
+ onToggleActive: (nextActive: boolean) => void;
+ togglingActive: boolean;
}
export default function QuotaCard({
@@ -42,7 +44,10 @@ export default function QuotaCard({
providerLabel,
onRefresh,
onOpenCutoff,
+ onToggleActive,
+ togglingActive,
}: QuotaCardProps) {
+ const isActive = connection.isActive ?? true;
const quotas = quota?.quotas ?? [];
const cardStatus = useMemo<CardStatus>(() => worstStatus(quotas), [quotas]);
const tierMeta = useMemo(
@@ -66,7 +71,7 @@ export default function QuotaCard({
return (
<Card
padding="none"
- className="flex flex-col overflow-hidden"
+ className={`flex flex-col overflow-hidden transition-opacity ${isActive ? "" : "opacity-60"}`}
style={{ borderLeft: `3px solid ${STATUS_BORDER[cardStatus]}` }}
>
<QuotaCardHeader
@@ -81,6 +86,8 @@ export default function QuotaCard({
onRefresh={onRefresh}
onOpenCutoff={onOpenCutoff}
hasCutoffOverrides={hasOverrides}
+ onToggleActive={onToggleActive}
+ togglingActive={togglingActive}
/>
<QuotaCardExpanded
quotas={quotas}
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCardGrid.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCardGrid.tsx
index 7406e0ad77..ea61c1f3b9 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCardGrid.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaCardGrid.tsx
@@ -12,6 +12,8 @@ interface Props {
providerLabels: Record<string, string>;
onRefresh: (id: string, provider: string) => void;
onOpenCutoff: (connection: any) => void;
+ onToggleActive: (id: string, nextActive: boolean) => void;
+ togglingActiveId: string | null;
}
export default function QuotaCardGrid({
@@ -24,6 +26,8 @@ export default function QuotaCardGrid({
providerLabels,
onRefresh,
onOpenCutoff,
+ onToggleActive,
+ togglingActiveId,
}: Props) {
if (connections.length === 0) return null;
@@ -58,6 +62,8 @@ export default function QuotaCardGrid({
providerLabel={providerLabels[conn.provider] || conn.provider}
onRefresh={() => onRefresh(conn.id, conn.provider)}
onOpenCutoff={() => onOpenCutoff(conn)}
+ onToggleActive={(nextActive) => onToggleActive(conn.id, nextActive)}
+ togglingActive={togglingActiveId === conn.id}
/>
))}
</div>
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx
index 968c189fe9..fc13c6578d 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx
@@ -16,6 +16,7 @@ import { CardSkeleton } from "@/shared/components/Loading";
import { USAGE_SUPPORTED_PROVIDERS } from "@/shared/constants/providers";
import { pickDisplayValue } from "@/shared/utils/maskEmail";
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
+import { useNotificationStore } from "@/store/notificationStore";
import EmailPrivacyToggle from "@/shared/components/EmailPrivacyToggle";
import QuotaCutoffModal from "./QuotaCutoffModal";
import QuotaCardGrid from "./QuotaCardGrid";
@@ -233,7 +234,9 @@ export default function ProviderLimits({
[t]
);
const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);
+ const notify = useNotificationStore();
const [connections, setConnections] = useState<any[]>([]);
+ const [togglingActiveId, setTogglingActiveId] = useState<string | null>(null);
const [quotaData, setQuotaData] = useState<Record<string, any>>({});
const [loading, setLoading] = useState<Record<string, boolean>>({});
const [errors, setErrors] = useState<Record<string, string | null>>({});
@@ -321,6 +324,36 @@ export default function ProviderLimits({
}
}, []);
+ // Toggle a connection's active state straight from the quota overview, so an
+ // operator can park an account that is being routed to despite low quota.
+ // Mirrors saveQuotaWindowThresholds: PUT /api/providers/[id] + optimistic state.
+ const handleToggleActive = useCallback(
+ async (connectionId: string, nextActive: boolean) => {
+ setTogglingActiveId(connectionId);
+ try {
+ const res = await fetch(`/api/providers/${connectionId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ isActive: nextActive }),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ setConnections((prev) =>
+ prev.map((c) => (c.id === connectionId ? { ...c, isActive: nextActive } : c))
+ );
+ notify.success(
+ nextActive
+ ? tr("accountActivated", "Account activated")
+ : tr("accountDeactivated", "Account deactivated")
+ );
+ } catch {
+ notify.error(tr("toggleActiveFailed", "Failed to update account status"));
+ } finally {
+ setTogglingActiveId(null);
+ }
+ },
+ [notify, tr]
+ );
+
const applyCachedQuotaState = useCallback(
(connectionList: any[], caches: Record<string, any>) => {
const nextQuotaData: Record<string, any> = {};
@@ -985,6 +1018,8 @@ export default function ProviderLimits({
setCutoffModalWindows(windows);
setCutoffModalConn(conn);
}}
+ onToggleActive={handleToggleActive}
+ togglingActiveId={togglingActiveId}
/>
</div>
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx
index 2b3cf96acb..a76a99063c 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx
@@ -20,6 +20,10 @@ interface Props {
onRefresh: () => void;
onOpenCutoff: () => void;
hasCutoffOverrides: boolean;
+ /** Toggle the connection's active state (routing on/off). */
+ onToggleActive: (nextActive: boolean) => void;
+ /** True while the active-state PUT is in flight. */
+ togglingActive: boolean;
}
export default function QuotaCardHeader({
@@ -34,8 +38,14 @@ export default function QuotaCardHeader({
onRefresh,
onOpenCutoff,
hasCutoffOverrides,
+ onToggleActive,
+ togglingActive,
}: Props) {
const t = useTranslations("usage");
+ const isActive = connection.isActive ?? true;
+ const toggleActiveLabel = isActive
+ ? translateUsageOrFallback(t, "deactivateAccount", "Deactivate account (stop routing)")
+ : translateUsageOrFallback(t, "activateAccount", "Activate account (resume routing)");
const accountName = pickDisplayValue(
[connection.name, connection.displayName, connection.email],
emailsVisible,
@@ -59,9 +69,7 @@ export default function QuotaCardHeader({
time: tokenCountdown,
})
: translateUsageOrFallback(t, "tokenExpired", "Token expired");
- const tokenExpiryTitle = hasTokenExpiry
- ? new Date(tokenExpiryMs).toLocaleString()
- : undefined;
+ const tokenExpiryTitle = hasTokenExpiry ? new Date(tokenExpiryMs).toLocaleString() : undefined;
return (
<div className="flex items-start justify-between gap-2 px-3 pt-2.5 pb-1.5">
@@ -118,6 +126,24 @@ export default function QuotaCardHeader({
</div>
</div>
<div className="flex items-center gap-0.5 shrink-0">
+ <button
+ type="button"
+ disabled={togglingActive}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (togglingActive) return;
+ onToggleActive(!isActive);
+ }}
+ title={toggleActiveLabel}
+ aria-label={toggleActiveLabel}
+ className={`p-1 rounded-md cursor-pointer transition-colors hover:bg-black/[0.04] dark:hover:bg-white/[0.04] disabled:opacity-40 disabled:cursor-not-allowed ${
+ isActive ? "text-text-muted" : "text-rose-500"
+ }`}
+ >
+ <span className="material-symbols-outlined text-[14px]">
+ {isActive ? "toggle_on" : "toggle_off"}
+ </span>
+ </button>
<button
type="button"
onClick={(e) => {
diff --git a/src/app/(dashboard)/home/topologyUtils.ts b/src/app/(dashboard)/home/topologyUtils.ts
new file mode 100644
index 0000000000..ef731f72f8
--- /dev/null
+++ b/src/app/(dashboard)/home/topologyUtils.ts
@@ -0,0 +1,27 @@
+/**
+ * Pure helpers for the home-page Provider Topology panel.
+ */
+
+/** Minimal shape expected by <ProviderTopology activeRequests={...}> */
+export interface TopologyActiveRequest {
+ provider: string;
+ model: string;
+}
+
+/** Minimal in-flight request shape (subset of LiveRequest from useLiveRequests) */
+interface InFlightRequest {
+ provider: string;
+ model: string;
+}
+
+/**
+ * Maps an array of in-flight LiveRequest entries to the flat
+ * { provider, model }[] shape consumed by <ProviderTopology>.
+ *
+ * The input is expected to contain only pending/running entries — the
+ * useLiveRequests hook already filters out completed and failed requests
+ * before exposing them via `activeRequests`.
+ */
+export function selectActiveRequests(requests: InFlightRequest[]): TopologyActiveRequest[] {
+ return requests.map(({ provider, model }) => ({ provider, model }));
+}
diff --git a/src/app/api/analytics/auto-routing/route.ts b/src/app/api/analytics/auto-routing/route.ts
index 9f0b4e5c84..f4a5874b20 100644
--- a/src/app/api/analytics/auto-routing/route.ts
+++ b/src/app/api/analytics/auto-routing/route.ts
@@ -1,6 +1,10 @@
import { NextResponse } from "next/server";
-import { getDbInstance } from "@/lib/db/core";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+import {
+ getAutoRoutingTotalCount,
+ getAutoRoutingVariantBreakdown,
+ getAutoRoutingTopProviders,
+} from "@/lib/db/usageLogs";
export const dynamic = "force-dynamic";
@@ -12,37 +16,11 @@ export async function GET(request: Request) {
const authError = await requireManagementAuth(request);
if (authError) return authError;
try {
- const db = getDbInstance();
-
// Query usage_logs for auto/ prefix requests
- const totalRequests = db
- .prepare(
- `
- SELECT COUNT(*) as count
- FROM usage_logs
- WHERE model = 'auto' OR model LIKE 'auto/%'
- `
- )
- .get() as { count: number };
+ const totalRequests = getAutoRoutingTotalCount();
// Variant breakdown
- const variantRows = db
- .prepare(
- `
- SELECT
- CASE
- WHEN model = 'auto' THEN 'default'
- WHEN model LIKE 'auto/%' THEN SUBSTR(model, 6)
- ELSE 'other'
- END as variant,
- COUNT(*) as count
- FROM usage_logs
- WHERE model = 'auto' OR model LIKE 'auto/%'
- GROUP BY variant
- ORDER BY count DESC
- `
- )
- .all() as Array<{ variant: string; count: number }>;
+ const variantRows = getAutoRoutingVariantBreakdown();
const variantBreakdown: Record<string, number> = {};
variantRows.forEach((row) => {
@@ -50,18 +28,7 @@ export async function GET(request: Request) {
});
// Top providers (from LKGP cache or usage logs)
- const topProviders = db
- .prepare(
- `
- SELECT provider, COUNT(*) as count
- FROM usage_logs
- WHERE model = 'auto' OR model LIKE 'auto/%'
- GROUP BY provider
- ORDER BY count DESC
- LIMIT 10
- `
- )
- .all() as Array<{ provider: string; count: number }>;
+ const topProviders = getAutoRoutingTopProviders();
return NextResponse.json({
totalRequests: totalRequests.count,
diff --git a/src/app/api/cache/entries/route.ts b/src/app/api/cache/entries/route.ts
index 97ff51ca9a..48fc5e88fe 100644
--- a/src/app/api/cache/entries/route.ts
+++ b/src/app/api/cache/entries/route.ts
@@ -1,16 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
-import { getDbInstance } from "@/lib/db/core";
import { isAuthenticated } from "@/shared/utils/apiAuth";
-
-interface CacheEntry {
- id: string;
- signature: string;
- model: string;
- hit_count: number;
- tokens_saved: number;
- created_at: string;
- expires_at: string;
-}
+import {
+ listSemanticCacheEntries,
+ deleteSemanticCacheBySignature,
+ deleteSemanticCacheByModel,
+} from "@/lib/db/semanticCache";
export async function GET(req: NextRequest) {
if (!(await isAuthenticated(req))) {
@@ -26,48 +20,15 @@ export async function GET(req: NextRequest) {
const sortBy = searchParams.get("sortBy") || "created_at";
const sortOrder = searchParams.get("sortOrder") || "desc";
- const db = getDbInstance();
- const offset = (page - 1) * limit;
-
- const conditions: string[] = [];
- const params: unknown[] = [];
-
- if (search) {
- conditions.push("(signature LIKE ? OR model LIKE ?)");
- params.push(`%${search}%`, `%${search}%`);
- }
-
- if (model) {
- conditions.push("model = ?");
- params.push(model);
- }
-
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
-
- const validSortColumns = ["created_at", "expires_at", "hit_count", "tokens_saved", "model"];
- const orderBy = validSortColumns.includes(sortBy) ? sortBy : "created_at";
- const order = sortOrder === "asc" ? "ASC" : "DESC";
-
- const countRow = db
- .prepare(`SELECT COUNT(*) as total FROM semantic_cache ${whereClause}`)
- .get(...params) as { total: number };
-
- const entries = db
- .prepare(
- `SELECT id, signature, model, hit_count, tokens_saved, created_at, expires_at
- FROM semantic_cache ${whereClause}
- ORDER BY ${orderBy} ${order}
- LIMIT ? OFFSET ?`
- )
- .all(...params, limit, offset) as CacheEntry[];
+ const { entries, total } = listSemanticCacheEntries({ page, limit, search, model, sortBy, sortOrder });
return NextResponse.json({
entries,
pagination: {
page,
limit,
- total: countRow?.total || 0,
- totalPages: Math.ceil((countRow?.total || 0) / limit),
+ total,
+ totalPages: Math.ceil(total / limit),
},
});
} catch (error) {
@@ -85,16 +46,14 @@ export async function DELETE(req: NextRequest) {
const signature = searchParams.get("signature");
const model = searchParams.get("model");
- const db = getDbInstance();
-
if (signature) {
- db.prepare("DELETE FROM semantic_cache WHERE signature = ?").run(signature);
- return NextResponse.json({ ok: true, deleted: 1 });
+ const { deleted } = deleteSemanticCacheBySignature(signature);
+ return NextResponse.json({ ok: true, deleted });
}
if (model) {
- const result = db.prepare("DELETE FROM semantic_cache WHERE model = ?").run(model);
- return NextResponse.json({ ok: true, deleted: result.changes });
+ const { deleted } = deleteSemanticCacheByModel(model);
+ return NextResponse.json({ ok: true, deleted });
}
return NextResponse.json({ error: "Provide signature or model parameter" }, { status: 400 });
diff --git a/src/app/api/cli-tools/hermes-agent-settings/route.ts b/src/app/api/cli-tools/hermes-agent-settings/route.ts
index fffafff902..69c98f4303 100644
--- a/src/app/api/cli-tools/hermes-agent-settings/route.ts
+++ b/src/app/api/cli-tools/hermes-agent-settings/route.ts
@@ -1,7 +1,6 @@
import { NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";
-import os from "os";
import { z } from "zod";
import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
import { getCliPrimaryConfigPath } from "@/shared/services/cliRuntime";
@@ -10,6 +9,7 @@ import {
generateHermesAgentConfig,
getCurrentHermesAgentRoles,
} from "@/lib/cli-helper/config-generator/hermes-agent";
+import { getHermesConfigPath } from "@/lib/cli-helper/config-generator/hermesHome";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
const hermesAgentSettingsSchema = z.object({
@@ -35,7 +35,8 @@ const hermesAgentSettingsSchema = z.object({
* POST -> accepts { baseUrl, keyId?, apiKey?, selections: [{role, model}, ...] }
*/
-const CONFIG_PATH = path.join(os.homedir(), ".hermes", "config.yaml");
+// Resolved lazily so HERMES_HOME is always honoured (#3628).
+const getConfigPath = () => getHermesConfigPath();
function getMetadataPath(configPath: string) {
return path.join(path.dirname(configPath), ".first-setup.json");
@@ -48,7 +49,7 @@ export async function GET(request: Request) {
try {
const roles = await getCurrentHermesAgentRoles();
- const configPath = getCliPrimaryConfigPath("hermes-agent") || CONFIG_PATH;
+ const configPath = getCliPrimaryConfigPath("hermes-agent") || getConfigPath();
let firstSetupAt: string | null = null;
try {
@@ -93,7 +94,7 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "baseUrl must be a valid http(s) URL" }, { status: 400 });
}
- const configPath = getCliPrimaryConfigPath("hermes-agent") || CONFIG_PATH;
+ const configPath = getCliPrimaryConfigPath("hermes-agent") || getConfigPath();
const configDir = path.dirname(configPath);
await fs.mkdir(configDir, { recursive: true });
diff --git a/src/app/api/combos/auto/route.ts b/src/app/api/combos/auto/route.ts
index 87ff185b22..7c282dd046 100644
--- a/src/app/api/combos/auto/route.ts
+++ b/src/app/api/combos/auto/route.ts
@@ -34,6 +34,10 @@ export async function GET(request: Request) {
isHidden: false,
candidatePool: virtual.candidatePool ?? [],
candidateCount: virtual.candidatePool?.length ?? 0,
+ // MAX of candidates' windows — consumers (opencode plugin) need a
+ // real value here: advertising 0 disables client auto-compaction.
+ context_length: virtual.advertisedContextLength ?? null,
+ max_output_tokens: virtual.advertisedMaxOutputTokens ?? null,
config: virtual.config ?? {},
});
} catch {
diff --git a/src/app/api/db-backups/exportAll/route.ts b/src/app/api/db-backups/exportAll/route.ts
index 5b6343c541..35dba50bd4 100644
--- a/src/app/api/db-backups/exportAll/route.ts
+++ b/src/app/api/db-backups/exportAll/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { getDbInstance, SQLITE_FILE } from "@/lib/db/core";
+import { exportAllSummaryRows } from "@/lib/db/backup";
import { CALL_LOGS_DIR } from "@/lib/usage/callLogArtifacts";
import fs from "fs";
import path from "path";
@@ -38,57 +39,11 @@ export async function GET(request: NextRequest) {
const dbBackupPath = path.join(tempDir, "storage.sqlite");
await db.backup(dbBackupPath);
- // 2. Export settings as JSON
- const settings: Record<string, string> = {};
- try {
- const rows = db.prepare("SELECT key, value FROM key_value").all() as {
- key: string;
- value: string;
- }[];
- for (const row of rows) {
- settings[row.key] = row.value;
- }
- } catch {
- // key_value table might not exist
- }
+ // 2–5. Export settings, combos, provider connections, API keys (via db module)
+ const { settings, combos, providers, apiKeys } = exportAllSummaryRows();
fs.writeFileSync(path.join(tempDir, "settings.json"), JSON.stringify(settings, null, 2));
-
- // 3. Export combos summary
- const combos: unknown[] = [];
- try {
- const rows = db.prepare("SELECT * FROM combos").all();
- combos.push(...rows);
- } catch {
- // combos table might not exist
- }
fs.writeFileSync(path.join(tempDir, "combos.json"), JSON.stringify(combos, null, 2));
-
- // 4. Export provider connections (without sensitive credentials)
- const providers: unknown[] = [];
- try {
- const rows = db
- .prepare(
- "SELECT id, provider, name, auth_type, is_active, email, created_at FROM provider_connections"
- )
- .all();
- providers.push(...rows);
- } catch {
- // provider_connections table might not exist
- }
fs.writeFileSync(path.join(tempDir, "providers.json"), JSON.stringify(providers, null, 2));
-
- // 5. Export API keys summary (masked)
- const apiKeys: unknown[] = [];
- try {
- const rows = db
- .prepare(
- "SELECT id, name, substr(key, 1, 8) as prefix, machine_id, created_at FROM api_keys"
- )
- .all();
- apiKeys.push(...rows);
- } catch {
- // api_keys table might not exist
- }
fs.writeFileSync(path.join(tempDir, "api-keys.json"), JSON.stringify(apiKeys, null, 2));
// 6. Export call log artifacts directory
diff --git a/src/app/api/db-backups/import/route.ts b/src/app/api/db-backups/import/route.ts
index f25a3285da..12ee0c678a 100644
--- a/src/app/api/db-backups/import/route.ts
+++ b/src/app/api/db-backups/import/route.ts
@@ -5,7 +5,7 @@ import os from "os";
import { getDbInstance, resetDbInstance, SQLITE_FILE } from "@/lib/db/core";
import { openDatabaseAsync } from "@/lib/db/adapters/driverFactory";
import type { SqliteAdapter } from "@/lib/db/adapters/types";
-import { backupDbFile } from "@/lib/db/backup";
+import { backupDbFile, getTableNamesFromAdapter, countImportedRows } from "@/lib/db/backup";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
import { getSettings } from "@/lib/db/settings";
import { setSystemPromptConfig } from "@omniroute/open-sse/services/systemPrompt.ts";
@@ -104,10 +104,7 @@ export async function POST(request: Request) {
}
// Validate required tables exist
- const tables = testDb
- .prepare("SELECT name FROM sqlite_master WHERE type='table'")
- .all()
- .map((row: any) => row.name);
+ const tables = getTableNamesFromAdapter(testDb);
const missingTables = REQUIRED_TABLES.filter((t) => !tables.includes(t));
if (missingTables.length > 0) {
@@ -153,13 +150,8 @@ export async function POST(request: Request) {
fs.copyFileSync(tmpPath, SQLITE_FILE!);
// Reopen and verify
- const db = getDbInstance();
- const connCount =
- (db.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get() as any)?.cnt || 0;
- const nodeCount =
- (db.prepare("SELECT COUNT(*) as cnt FROM provider_nodes").get() as any)?.cnt || 0;
- const comboCount = (db.prepare("SELECT COUNT(*) as cnt FROM combos").get() as any)?.cnt || 0;
- const keyCount = (db.prepare("SELECT COUNT(*) as cnt FROM api_keys").get() as any)?.cnt || 0;
+ getDbInstance();
+ const { connCount, nodeCount, comboCount, keyCount } = countImportedRows();
console.log(
`[DB] Imported database from upload: ${connCount} connections, ${nodeCount} nodes, ${comboCount} combos, ${keyCount} API keys`
diff --git a/src/app/api/gamification/federation/leaderboard/route.ts b/src/app/api/gamification/federation/leaderboard/route.ts
index b7dde05699..e198ae2aef 100644
--- a/src/app/api/gamification/federation/leaderboard/route.ts
+++ b/src/app/api/gamification/federation/leaderboard/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { type LeaderboardScope, getTopN } from "@/lib/gamification/leaderboard";
+import { getConnectedServerByKeyHash } from "@/lib/db/gamification";
import crypto from "crypto";
export async function OPTIONS() {
@@ -26,11 +27,7 @@ export async function GET(request: NextRequest) {
const tokenHash = crypto
.pbkdf2Sync(token, "omniroute-federation-salt", 120000, 32, "sha256")
.toString("hex");
- const { getDbInstance } = await import("@/lib/db/core");
- const db = getDbInstance();
- const server = db
- .prepare("SELECT id FROM community_servers WHERE api_key_hash = ? AND status = 'connected'")
- .get(tokenHash) as { id: string } | undefined;
+ const server = getConnectedServerByKeyHash(tokenHash);
if (!server) {
return NextResponse.json(
diff --git a/src/app/api/gamification/federation/score/route.ts b/src/app/api/gamification/federation/score/route.ts
index 5b7c37d955..9503c56327 100644
--- a/src/app/api/gamification/federation/score/route.ts
+++ b/src/app/api/gamification/federation/score/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { updateScore } from "@/lib/gamification/leaderboard";
+import { getConnectedServerByKeyHash } from "@/lib/db/gamification";
import { z } from "zod";
import crypto from "crypto";
@@ -24,11 +25,7 @@ export async function POST(request: NextRequest) {
const tokenHash = crypto
.pbkdf2Sync(token, "omniroute-federation-salt", 120000, 32, "sha256")
.toString("hex");
- const { getDbInstance } = await import("@/lib/db/core");
- const db = getDbInstance();
- const server = db
- .prepare("SELECT id FROM community_servers WHERE api_key_hash = ? AND status = 'connected'")
- .get(tokenHash) as { id: string } | undefined;
+ const server = getConnectedServerByKeyHash(tokenHash);
if (!server) {
return NextResponse.json(
diff --git a/src/app/api/internal/codex-responses-ws/route.ts b/src/app/api/internal/codex-responses-ws/route.ts
index d5b2cb715b..5bc72d44ca 100644
--- a/src/app/api/internal/codex-responses-ws/route.ts
+++ b/src/app/api/internal/codex-responses-ws/route.ts
@@ -9,6 +9,7 @@ import { getProviderCredentialsWithQuotaPreflight } from "@/sse/services/auth";
import { checkAndRefreshToken } from "@/sse/services/tokenRefresh";
import { resolveCodexWsModelInfo } from "./modelResolution";
import { isFeatureFlagEnabled } from "@/shared/utils/featureFlags";
+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
const CODEX_RESPONSES_WS_URL = "wss://chatgpt.com/backend-api/codex/responses";
const executor = new CodexExecutor();
@@ -28,6 +29,74 @@ function isRecord(value: unknown): value is JsonRecord {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+function toStringOrNull(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+}
+
+function toFiniteNumber(value: unknown, fallback = 0): number {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
+
+function toHttpStatus(value: unknown, fallback: number): number {
+ const status = Number(value);
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : fallback;
+}
+
+function getResponseCreateBody(body: JsonRecord): JsonRecord {
+ if (isRecord(body.clientRequest)) return body.clientRequest;
+ if (isRecord(body.response)) return body.response;
+ return {};
+}
+
+function getTerminalMessage(body: JsonRecord): JsonRecord | null {
+ return isRecord(body.terminalMessage) ? body.terminalMessage : null;
+}
+
+function getTerminalResponseBody(body: JsonRecord): JsonRecord | null {
+ if (isRecord(body.responseBody)) return body.responseBody;
+ const terminalMessage = getTerminalMessage(body);
+ if (isRecord(terminalMessage?.response)) return terminalMessage.response;
+ return terminalMessage;
+}
+
+function getErrorRecord(body: JsonRecord, responseBody: JsonRecord | null): JsonRecord | null {
+ if (isRecord(body.error)) return body.error;
+ if (isRecord(responseBody?.error)) return responseBody.error;
+ const terminalMessage = getTerminalMessage(body);
+ if (isRecord(terminalMessage?.error)) return terminalMessage.error;
+ return null;
+}
+
+function getTimestamp(value: unknown): string {
+ const raw = toStringOrNull(value);
+ if (!raw) return new Date().toISOString();
+ const parsed = new Date(raw);
+ return Number.isNaN(parsed.getTime()) ? new Date().toISOString() : parsed.toISOString();
+}
+
+function getRequestPath(body: JsonRecord): string {
+ const explicitPath = toStringOrNull(body.path);
+ if (explicitPath) return explicitPath;
+
+ try {
+ const requestUrl = toStringOrNull(body.requestUrl) || "/v1/responses";
+ return new URL(requestUrl, "http://omniroute.local").pathname;
+ } catch {
+ return "/v1/responses";
+ }
+}
+
+function getServiceTier(requestBody: JsonRecord): string | null {
+ return toStringOrNull(requestBody.service_tier) || toStringOrNull(requestBody.serviceTier);
+}
+
+async function getApiKeyMetadataFromBody(body: JsonRecord) {
+ const authRequest = getAuthRequest(body);
+ const apiKey = extractWsTokenFromRequest(authRequest);
+ return apiKey ? getApiKeyMetadata(apiKey).catch(() => null) : null;
+}
+
function getBridgeSecret(): string {
return process.env.OMNIROUTE_WS_BRIDGE_SECRET || "";
}
@@ -184,12 +253,121 @@ async function prepare(body: JsonRecord) {
browser: "chrome_142",
os: "windows",
connectionId: refreshedCredentials.connectionId,
+ provider,
+ account: refreshedCredentials.email || null,
model,
headers,
response: transformed,
});
}
+async function persistResponsesWsCallHistory(body: JsonRecord) {
+ const [{ saveCallLog }, { saveRequestUsage }, { logProxyEvent }] = await Promise.all([
+ import("@/lib/usage/callLogs"),
+ import("@/lib/usage/usageHistory"),
+ import("@/lib/proxyLogger"),
+ ]);
+
+ const metadata = await getApiKeyMetadataFromBody(body);
+ const requestBody = getResponseCreateBody(body);
+ const terminalMessage = getTerminalMessage(body);
+ const responseBody = getTerminalResponseBody(body);
+ const usage = isRecord(responseBody?.usage) ? responseBody.usage : {};
+ const errorRecord = getErrorRecord(body, responseBody);
+ const status = toHttpStatus(
+ body.status ?? errorRecord?.status_code ?? errorRecord?.status,
+ body.success === false ? 500 : 200
+ );
+ const success = typeof body.success === "boolean" ? body.success : status < 400;
+ const errorCode =
+ toStringOrNull(body.errorCode) ||
+ toStringOrNull(errorRecord?.code) ||
+ (success ? null : "responses_websocket_failed");
+ const errorMessage = success
+ ? null
+ : sanitizeErrorMessage(
+ toStringOrNull(body.errorMessage) ||
+ toStringOrNull(errorRecord?.message) ||
+ "Responses WebSocket request failed"
+ );
+ const timestamp = getTimestamp(body.startedAt);
+ const durationMs = Math.max(0, Math.round(toFiniteNumber(body.durationMs, 0)));
+ const provider = toStringOrNull(body.provider) || "codex";
+ const model =
+ toStringOrNull(body.model) ||
+ toStringOrNull(responseBody?.model) ||
+ toStringOrNull(requestBody.model) ||
+ "-";
+ const requestedModel = toStringOrNull(body.requestedModel) || toStringOrNull(requestBody.model);
+ const connectionId = toStringOrNull(body.connectionId);
+ const apiKeyId = metadata?.id || null;
+ const apiKeyName = metadata?.name || null;
+ const noLog = metadata?.noLog === true;
+ const path = getRequestPath(body);
+ const sourceFormat = toStringOrNull(body.sourceFormat) || "openai-responses";
+ const targetFormat = toStringOrNull(body.targetFormat) || "openai-responses";
+ const targetUrl = toStringOrNull(body.upstreamUrl) || CODEX_RESPONSES_WS_URL;
+ const account = toStringOrNull(body.account);
+
+ await saveCallLog({
+ id: toStringOrNull(body.sessionId) || undefined,
+ timestamp,
+ method: "WEBSOCKET",
+ path,
+ status,
+ model,
+ requestedModel,
+ provider,
+ connectionId,
+ duration: durationMs,
+ tokens: usage,
+ requestType: "responses_websocket",
+ sourceFormat,
+ targetFormat,
+ apiKeyId,
+ apiKeyName,
+ noLog,
+ requestBody,
+ responseBody: responseBody ?? terminalMessage,
+ error: errorMessage ? { code: errorCode, message: errorMessage } : null,
+ pipelinePayloads: {
+ clientRequest: requestBody,
+ providerRequest: requestBody,
+ providerResponse: responseBody,
+ clientResponse: terminalMessage,
+ },
+ });
+
+ await saveRequestUsage({
+ timestamp,
+ provider,
+ model,
+ connectionId,
+ apiKeyId,
+ apiKeyName,
+ tokens: usage,
+ serviceTier: getServiceTier(requestBody),
+ status: String(status),
+ success,
+ latencyMs: durationMs,
+ timeToFirstTokenMs: durationMs,
+ errorCode,
+ });
+
+ logProxyEvent({
+ status: success ? "success" : "error",
+ level: "direct",
+ provider,
+ targetUrl,
+ latencyMs: durationMs,
+ error: errorMessage,
+ connectionId,
+ account,
+ });
+
+ return NextResponse.json({ ok: true, logged: true });
+}
+
export async function POST(request: Request) {
const expectedSecret = getBridgeSecret();
const receivedSecret = request.headers.get("x-omniroute-ws-bridge-secret") || "";
@@ -215,6 +393,17 @@ export async function POST(request: Request) {
if (action === "prepare") {
return prepare(body);
}
+ if (action === "log") {
+ try {
+ return await persistResponsesWsCallHistory(body);
+ } catch (error) {
+ return jsonError(
+ 500,
+ "responses_ws_history_log_failed",
+ sanitizeErrorMessage(error instanceof Error ? error.message : String(error))
+ );
+ }
+ }
return jsonError(400, "invalid_action", "Unsupported bridge action");
}
diff --git a/src/app/api/logs/export/route.ts b/src/app/api/logs/export/route.ts
index ea10b60ae9..8efe2fd486 100644
--- a/src/app/api/logs/export/route.ts
+++ b/src/app/api/logs/export/route.ts
@@ -1,6 +1,6 @@
-import { getDbInstance } from "@/lib/db/core";
import { exportCallLogsSince } from "@/lib/usage/callLogs";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+import { exportProxyLogsSince } from "@/lib/db/proxyLogs";
/**
* GET /api/logs/export — export logs as JSON
@@ -17,7 +17,6 @@ export async function GET(request: Request) {
const logType = searchParams.get("type") || "call-logs";
const since = new Date(Date.now() - hours * 3600 * 1000).toISOString();
- const db = getDbInstance();
let rows: unknown[] = [];
let tableName = "";
@@ -27,14 +26,11 @@ export async function GET(request: Request) {
rows = await exportCallLogsSince(since);
} else if (logType === "proxy-logs") {
tableName = "proxy_logs";
- // NOTE: raw SELECT * returns the historical `public_ip` column, NOT `clientIp`.
+ // NOTE: exportProxyLogsSince returns the historical `public_ip` column, NOT `clientIp`.
// This intentionally differs from GET /api/usage/proxy-logs which exposes the
// value as `clientIp`. Callers of this export endpoint should read `public_ip`.
// This inconsistency will be resolved in a future DB migration (#2880).
- const stmt = db.prepare(
- "SELECT * FROM proxy_logs WHERE timestamp >= @since ORDER BY timestamp DESC"
- );
- rows = stmt.all({ since });
+ rows = exportProxyLogsSince(since);
}
const filename = `omniroute-${tableName}-${hours}h-${new Date().toISOString().slice(0, 10)}.json`;
diff --git a/src/app/api/oauth/kiro/auto-import/route.ts b/src/app/api/oauth/kiro/auto-import/route.ts
index 6bacc16d62..eb8c104520 100755
--- a/src/app/api/oauth/kiro/auto-import/route.ts
+++ b/src/app/api/oauth/kiro/auto-import/route.ts
@@ -2,7 +2,13 @@ import { NextResponse } from "next/server";
import { homedir } from "os";
import { join } from "path";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
-import { createProviderConnection, isCloudEnabled, resolveProxyForProvider } from "@/models";
+import {
+ createProviderConnection,
+ getProviderConnections,
+ updateProviderConnection,
+ isCloudEnabled,
+ resolveProxyForProvider,
+} from "@/models";
import { syncToCloud } from "@/lib/cloudSync";
import { getConsistentMachineId } from "@/shared/utils/machineId";
import { KiroService } from "@/lib/oauth/services/kiro";
@@ -235,6 +241,59 @@ async function tryAwsSsoCache(targetProvider: string): Promise<{
return { found: false, triedPath: cachePath };
}
+// ── Helpers (exported for unit-testing) ──────────────────────────────────────
+
+/**
+ * Derives a human-readable display name for a Kiro/AWS connection when the
+ * OAuth token carries no email claim (social-auth / AWS SSO tokens). Falls
+ * back through: email → profileArn-based label → provider+region label.
+ *
+ * Exported for unit tests (#3615).
+ */
+export function deriveKiroConnectionName(opts: {
+ email: string | null | undefined;
+ profileArn: string | undefined;
+ region: string | undefined;
+ targetProvider: string;
+}): string {
+ const { email, profileArn, region, targetProvider } = opts;
+ if (email) return email;
+ const r = region || "us-east-1";
+ if (profileArn) return `AWS CodeWhisperer (${r})`;
+ if (targetProvider === "amazon-q") return `Amazon Q (${r})`;
+ return `Kiro (${r})`;
+}
+
+type ProviderConnectionLike = {
+ id?: unknown;
+ providerSpecificData?: unknown;
+ [key: string]: unknown;
+};
+
+/**
+ * Scans a list of existing provider connections and returns the first one
+ * whose stored `providerSpecificData.profileArn` matches the given ARN.
+ * Returns null when profileArn is undefined/null or no match is found.
+ *
+ * Exported for unit tests (#3615).
+ */
+export function findKiroConnectionByProfileArn(
+ connections: ProviderConnectionLike[],
+ profileArn: string | undefined
+): ProviderConnectionLike | null {
+ if (!profileArn) return null;
+ for (const conn of connections) {
+ const psd = conn.providerSpecificData;
+ if (psd && typeof psd === "object" && !Array.isArray(psd)) {
+ const stored = (psd as Record<string, unknown>).profileArn;
+ if (typeof stored === "string" && stored === profileArn) {
+ return conn;
+ }
+ }
+ }
+ return null;
+}
+
// ── Save to OmniRoute DB ──────────────────────────────────────────────────────
async function saveAndRespond(
@@ -299,16 +358,44 @@ async function saveAndRespond(
const email = kiroService.extractEmailFromJWT(accessToken);
- await createProviderConnection({
- provider: targetProvider,
- authType: "oauth",
- accessToken,
- refreshToken,
- expiresAt,
- email: email || null,
- providerSpecificData,
- testStatus: "active",
- } as any);
+ // Derive a descriptive name so the UI never shows a blank "OAuth Account"
+ // when the token carries no email claim (Kiro social-auth / AWS SSO).
+ const connectionName = deriveKiroConnectionName({
+ email,
+ profileArn,
+ region: result.region,
+ targetProvider,
+ });
+
+ // Dedup by profileArn: if an existing connection already has the same ARN
+ // just refresh its tokens instead of inserting a new row. This prevents the
+ // duplicate-row accumulation reported in #3615 (4 rows after 6 days).
+ const existingConnections = await getProviderConnections({ provider: targetProvider });
+ const existingByArn = findKiroConnectionByProfileArn(existingConnections, profileArn);
+
+ if (existingByArn && typeof existingByArn.id === "string") {
+ await updateProviderConnection(existingByArn.id, {
+ accessToken,
+ refreshToken,
+ expiresAt,
+ email: email || null,
+ name: connectionName,
+ providerSpecificData,
+ testStatus: "active",
+ });
+ } else {
+ await createProviderConnection({
+ provider: targetProvider,
+ authType: "oauth",
+ accessToken,
+ refreshToken,
+ expiresAt,
+ email: email || null,
+ name: connectionName,
+ providerSpecificData,
+ testStatus: "active",
+ } as any);
+ }
if (isCloudEnabled()) {
const machineId = await getConsistentMachineId();
diff --git a/src/app/api/provider-metrics/route.ts b/src/app/api/provider-metrics/route.ts
index 90ca80ad7b..d849cb9a9e 100644
--- a/src/app/api/provider-metrics/route.ts
+++ b/src/app/api/provider-metrics/route.ts
@@ -3,12 +3,10 @@ import pino from "pino";
import { buildErrorBody } from "@omniroute/open-sse/utils/error.ts";
-import { getDbInstance } from "@/lib/db/core";
+import { getProviderMetrics } from "@/lib/db/callLogStats";
const logger = pino({ name: "provider-metrics-api" });
-type JsonRecord = Record<string, unknown>;
-
function toNumber(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim().length > 0) {
@@ -24,46 +22,7 @@ function toNumber(value: unknown): number {
*/
export async function GET() {
try {
- const db = getDbInstance();
- const rows = db
- .prepare(
- `SELECT
- c.provider,
- COUNT(*) as totalRequests,
- SUM(CASE WHEN status >= 200 AND status < 400 THEN 1 ELSE 0 END) as totalSuccesses,
- ROUND(AVG(duration)) as avgLatencyMs,
- MAX(timestamp) as lastRequestAt,
- MAX(
- CASE
- WHEN (status IS NOT NULL AND (status < 200 OR status >= 400))
- OR error_summary IS NOT NULL
- THEN timestamp
- ELSE NULL
- END
- ) as lastErrorAt,
- (
- SELECT c2.status
- FROM call_logs c2
- WHERE c2.provider = c.provider
- ORDER BY c2.timestamp DESC, c2.id DESC
- LIMIT 1
- ) as lastStatus,
- (
- SELECT c3.status
- FROM call_logs c3
- WHERE c3.provider = c.provider
- AND (
- (c3.status IS NOT NULL AND (c3.status < 200 OR c3.status >= 400))
- OR c3.error_summary IS NOT NULL
- )
- ORDER BY c3.timestamp DESC, c3.id DESC
- LIMIT 1
- ) as lastErrorStatus
- FROM call_logs c
- WHERE c.provider IS NOT NULL AND c.provider != '-'
- GROUP BY c.provider`
- )
- .all() as JsonRecord[];
+ const rows = getProviderMetrics();
const metrics: Record<
string,
@@ -112,7 +71,12 @@ export async function GET() {
lastProviderTs = requestTs;
}
- const errorTs = lastErrorAt ? Date.parse(lastErrorAt) : 0;
+ // Only flag as errorProvider if the provider's MOST RECENT request was itself
+ // a failure. A provider with a historical lastErrorAt but a recent success
+ // (lastStatus 2xx/3xx) must not be shown as currently errored (#3619).
+ const isCurrentlyInError =
+ lastStatus !== null && (lastStatus < 200 || lastStatus >= 400);
+ const errorTs = isCurrentlyInError && lastErrorAt ? Date.parse(lastErrorAt) : 0;
if (Number.isFinite(errorTs) && errorTs > errorProviderTs) {
errorProvider = provider;
errorProviderTs = errorTs;
diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.ts
index e3733dd5f1..78c9865f71 100755
--- a/src/app/api/providers/[id]/models/route.ts
+++ b/src/app/api/providers/[id]/models/route.ts
@@ -764,6 +764,63 @@ export async function GET(
const isNoAuthProvider =
(NOAUTH_PROVIDERS as Record<string, { noAuth?: boolean }>)[id]?.noAuth === true;
if (isNoAuthProvider) {
+ // #3611 — if the registry entry has a modelsUrl, attempt a live fetch so
+ // the model picker shows the current catalog instead of the stale
+ // hardcoded list (opencode provider had 9 hardcoded models while the live
+ // endpoint exposes many more). No auth header is added because noAuth
+ // providers are genuinely public. Fall through to local_catalog on any error.
+ const noAuthRegistryEntry = getRegistryEntry(id);
+ const noAuthModelsUrl =
+ typeof noAuthRegistryEntry?.modelsUrl === "string" &&
+ noAuthRegistryEntry.modelsUrl.length > 0
+ ? noAuthRegistryEntry.modelsUrl
+ : null;
+
+ if (noAuthModelsUrl) {
+ try {
+ const liveResponse = await safeOutboundFetch(noAuthModelsUrl, {
+ ...SAFE_OUTBOUND_FETCH_PRESETS.modelsDiscovery,
+ guard: getProviderOutboundGuard(),
+ method: "GET",
+ headers: { "Content-Type": "application/json" },
+ });
+
+ if (liveResponse.ok) {
+ const data = await liveResponse.json();
+ const liveModels: Array<{ id: string; name: string }> = (
+ (data.data || data.models || []) as Array<Record<string, unknown>>
+ )
+ .map((item) => {
+ const itemId =
+ typeof item.id === "string" ? item.id.trim() : "";
+ if (!itemId) return null;
+ const itemName =
+ typeof item.display_name === "string"
+ ? item.display_name
+ : typeof item.name === "string"
+ ? item.name
+ : itemId;
+ return { id: itemId, name: itemName };
+ })
+ .filter((m): m is { id: string; name: string } => m !== null);
+
+ if (liveModels.length > 0) {
+ const visible = excludeHidden
+ ? liveModels.filter((m) => !getModelIsHidden(id, m.id))
+ : liveModels;
+ return NextResponse.json({
+ provider: id,
+ connectionId: id,
+ models: visible,
+ source: "upstream",
+ });
+ }
+ }
+ } catch {
+ // Live fetch failed — fall through to local_catalog below.
+ }
+ }
+
const catalog = mergeLocalCatalogModels(
getModelsByProviderId(id) || [],
getStaticModelsForProvider(id) || []
diff --git a/src/app/api/providers/route.ts b/src/app/api/providers/route.ts
index 98bbeacc1f..cd6aef3870 100644
--- a/src/app/api/providers/route.ts
+++ b/src/app/api/providers/route.ts
@@ -197,16 +197,11 @@ export async function POST(request: Request) {
void fetch(syncUrl, { method: "POST", headers: syncHeaders })
.then((syncRes) => {
if (!syncRes.ok) {
- console.log(
- `[providers] Auto-sync failed for ${newConnection.id}: ${syncRes.status}`
- );
+ console.log(`[providers] Auto-sync failed for ${newConnection.id}: ${syncRes.status}`);
}
})
.catch((err) => {
- console.log(
- `[providers] Auto-sync error for ${newConnection.id}:`,
- err?.message || err
- );
+ console.log(`[providers] Auto-sync error for ${newConnection.id}:`, err?.message || err);
});
} catch (syncSetupError) {
// Defensive: if URL parsing or header construction itself throws, do
@@ -284,11 +279,13 @@ export async function PATCH(request: Request) {
await syncToCloudIfEnabled();
+ // Partial failure (some ids no longer exist) is logged as "warn" so the
+ // Activity feed reflects that not every requested id was applied.
logAuditEvent({
action: "provider.credentials.batch_updated",
actor: "admin",
resourceType: "provider_credentials",
- status: "success",
+ status: notFoundIds.length > 0 ? "warn" : "success",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: { isActive, updated: updatedIds.length, notFound: notFoundIds, ids },
@@ -303,7 +300,7 @@ export async function PATCH(request: Request) {
{ status: 200 }
);
} catch (error) {
- console.log("Error batch updating connections:", error);
+ console.error("Error batch updating connections:", error);
return NextResponse.json({ error: "Failed to batch update connections" }, { status: 500 });
}
}
diff --git a/src/app/api/providers/test-batch/route.ts b/src/app/api/providers/test-batch/route.ts
index f8b743160f..1c71dcb10e 100644
--- a/src/app/api/providers/test-batch/route.ts
+++ b/src/app/api/providers/test-batch/route.ts
@@ -136,11 +136,14 @@ export async function POST(request) {
}
if (connectionsToTest.length === 0) {
+ // Include a summary so consumers gated on `summary` still get feedback
+ // (e.g. mode=selected where the chosen ids were deleted before testing).
return NextResponse.json({
mode,
providerId: providerId || null,
results: [],
testedAt: new Date().toISOString(),
+ summary: { total: 0, passed: 0, failed: 0 },
});
}
diff --git a/src/app/api/search/stats/route.ts b/src/app/api/search/stats/route.ts
index 361f1f05c3..bf0992f1a4 100644
--- a/src/app/api/search/stats/route.ts
+++ b/src/app/api/search/stats/route.ts
@@ -1,35 +1,24 @@
import { NextResponse } from "next/server";
import { getCacheStats } from "@omniroute/open-sse/services/searchCache.ts";
import { SEARCH_PROVIDERS } from "@omniroute/open-sse/config/searchRegistry.ts";
-import { getDbInstance } from "@/lib/db/core";
import { isAuthenticated } from "@/shared/utils/apiAuth";
+import { getSearchProviderStats, getRecentSearchLogs } from "@/lib/db/callLogStats";
export async function GET(request: Request) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
- const db = getDbInstance();
const cache = getCacheStats();
// Provider aggregate stats — cost is per-query from registry
- const providerStats = db
- .prepare(
- `
- SELECT provider, COUNT(*) as requests,
- CAST(AVG(duration) AS INTEGER) as avg_latency_ms
- FROM call_logs
- WHERE request_type = 'search'
- GROUP BY provider
- `
- )
- .all();
+ const providerStats = getSearchProviderStats();
const providers: Record<
string,
{ requests: number; avg_latency_ms: number; total_cost: number }
> = {};
- for (const row of providerStats as any[]) {
+ for (const row of providerStats) {
const costPerQuery = SEARCH_PROVIDERS[row.provider]?.costPerQuery || 0;
providers[row.provider] = {
requests: row.requests,
@@ -39,23 +28,13 @@ export async function GET(request: Request) {
}
// Recent searches
- const recentRows = db
- .prepare(
- `
- SELECT request_summary, provider, timestamp
- FROM call_logs
- WHERE request_type = 'search'
- ORDER BY timestamp DESC
- LIMIT 10
- `
- )
- .all();
+ const recentRows = getRecentSearchLogs();
- const recent_searches = (recentRows as any[]).map((row) => {
+ const recent_searches = recentRows.map((row) => {
let query = "";
let filters = {};
try {
- const summary = JSON.parse(row.request_summary);
+ const summary = JSON.parse(row.request_summary ?? "");
query = summary.query || "";
filters = summary.filters || {};
} catch {
diff --git a/src/app/api/settings/export-json/route.ts b/src/app/api/settings/export-json/route.ts
index 16f6984410..51dc429414 100644
--- a/src/app/api/settings/export-json/route.ts
+++ b/src/app/api/settings/export-json/route.ts
@@ -6,8 +6,12 @@ import {
getCombos,
getApiKeys,
} from "@/lib/localDb";
-import { getDbInstance } from "@/lib/db/core";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
+import {
+ getAllUsageHistory,
+ getAllDomainCostHistory,
+ getAllDomainBudgets,
+} from "@/lib/db/usageAnalytics";
/**
* GET /api/settings/export-json
@@ -56,10 +60,9 @@ export async function GET(request: Request) {
// These tables (usage_history, domain_cost_history, domain_budgets) can contain
// thousands of rows and make the config backup grow to many MBs.
if (includeHistory) {
- const db = getDbInstance();
- exportData.usageHistory = db.prepare("SELECT * FROM usage_history").all();
- exportData.domainCostHistory = db.prepare("SELECT * FROM domain_cost_history").all();
- exportData.domainBudgets = db.prepare("SELECT * FROM domain_budgets").all();
+ exportData.usageHistory = getAllUsageHistory();
+ exportData.domainCostHistory = getAllDomainCostHistory();
+ exportData.domainBudgets = getAllDomainBudgets();
}
return new NextResponse(JSON.stringify(exportData, null, 2), {
diff --git a/src/app/api/settings/obsidian/webdav/route.ts b/src/app/api/settings/obsidian/webdav/route.ts
new file mode 100644
index 0000000000..1465b1dafd
--- /dev/null
+++ b/src/app/api/settings/obsidian/webdav/route.ts
@@ -0,0 +1,81 @@
+import { NextRequest, NextResponse } from "next/server";
+import { z } from "zod";
+import { isAuthenticated } from "@/shared/utils/apiAuth";
+import { buildErrorBody } from "@omniroute/open-sse/utils/error";
+import {
+ getObsidianSyncStatus,
+ enableObsidianVaultSync,
+ disableObsidianVaultSync,
+} from "@/lib/obsidianSync";
+
+const enableSchema = z
+ .object({
+ vaultPath: z.string().min(1).max(4096),
+ })
+ .strict();
+
+export async function GET(request: NextRequest) {
+ if (!(await isAuthenticated(request))) {
+ return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
+ }
+
+ try {
+ const status = await getObsidianSyncStatus();
+ return NextResponse.json({
+ webdavEnabled: status.webdavEnabled,
+ webdavUsername: status.webdavEnabled ? status.webdavUsername : null,
+ webdavPassword: status.webdavEnabled ? status.webdavPassword : null,
+ vaultPath: status.vaultPath,
+ });
+ } catch (error) {
+ const msg = error instanceof Error ? error.message : String(error);
+ return NextResponse.json(buildErrorBody(500, msg), { status: 500 });
+ }
+}
+
+export async function POST(request: NextRequest) {
+ if (!(await isAuthenticated(request))) {
+ return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
+ }
+
+ let rawBody: unknown;
+ try {
+ rawBody = await request.json();
+ } catch {
+ return NextResponse.json(buildErrorBody(400, "Invalid JSON body"), { status: 400 });
+ }
+
+ const parsed = enableSchema.safeParse(rawBody);
+ if (!parsed.success) {
+ return NextResponse.json(
+ buildErrorBody(400, "Missing or invalid vaultPath"),
+ { status: 400 }
+ );
+ }
+
+ const result = await enableObsidianVaultSync(parsed.data.vaultPath);
+ if (!result.success) {
+ return NextResponse.json(buildErrorBody(400, result.error), { status: 400 });
+ }
+
+ return NextResponse.json({
+ username: result.username,
+ password: result.password,
+ vaultPath: result.vaultPath,
+ });
+}
+
+export async function DELETE(request: NextRequest) {
+ if (!(await isAuthenticated(request))) {
+ return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
+ }
+
+ const result = await disableObsidianVaultSync();
+ if (!result.success) {
+ return NextResponse.json(buildErrorBody(500, result.error ?? "Failed to disable WebDAV sync"), {
+ status: 500,
+ });
+ }
+
+ return NextResponse.json({ success: true });
+}
diff --git a/src/app/api/skills/[id]/route.ts b/src/app/api/skills/[id]/route.ts
index 50d5045c5d..8a9aa82e7c 100644
--- a/src/app/api/skills/[id]/route.ts
+++ b/src/app/api/skills/[id]/route.ts
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server";
-import { getDbInstance } from "@/lib/db/core";
+import { updateSkill } from "@/lib/db/skills";
import { skillRegistry } from "@/lib/skills/registry";
import { z } from "zod";
import { validateBody, isValidationFailure } from "@/shared/validation/helpers";
@@ -39,37 +39,29 @@ export async function PUT(request: Request, props: { params: Promise<{ id: strin
return NextResponse.json(validation.error, { status: 400 });
}
- const db = getDbInstance();
- const updates: string[] = [];
- const params: unknown[] = [];
+ const patch: Record<string, unknown> = {};
if (validation.data.enabled !== undefined) {
- updates.push("enabled = ?");
- params.push(validation.data.enabled ? 1 : 0);
+ patch.enabled = validation.data.enabled ? 1 : 0;
// Legacy enabled toggle should also keep mode in sync.
// Without this, skills created as mode="off" remain excluded even after enabled=true.
if (validation.data.mode === undefined) {
- updates.push("mode = ?");
- params.push(validation.data.enabled ? "on" : "off");
+ patch.mode = validation.data.enabled ? "on" : "off";
}
}
if (validation.data.mode !== undefined) {
- updates.push("mode = ?");
- params.push(validation.data.mode);
+ patch.mode = validation.data.mode;
// keep enabled column consistent for older codepaths
- updates.push("enabled = ?");
- params.push(validation.data.mode === "off" ? 0 : 1);
+ patch.enabled = validation.data.mode === "off" ? 0 : 1;
}
- if (updates.length === 0) {
+ if (Object.keys(patch).length === 0) {
return NextResponse.json({ error: "No update payload provided" }, { status: 400 });
}
- updates.push("updated_at = datetime('now')");
- params.push(id);
- db.prepare(`UPDATE skills SET ${updates.join(", ")} WHERE id = ?`).run(...params);
+ updateSkill(id, patch);
await skillRegistry.loadFromDatabase();
diff --git a/src/app/api/usage/analytics/route.ts b/src/app/api/usage/analytics/route.ts
index 62a61ce420..b8a3347c55 100644
--- a/src/app/api/usage/analytics/route.ts
+++ b/src/app/api/usage/analytics/route.ts
@@ -1,8 +1,26 @@
import { NextResponse } from "next/server";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { getApiKeys } from "@/lib/db/apiKeys";
-import { getDbInstance } from "@/lib/db/core";
import { getUserDatabaseSettings } from "@/lib/db/databaseSettings";
+import {
+ buildUnifiedSource,
+ buildPresetUnifiedSource,
+ getUsageSummary,
+ getDailyUsage,
+ getDailyCostRows,
+ getHeatmapRows,
+ getModelUsageRows,
+ getProviderCostRows,
+ getProviderUsageRows,
+ getAccountCostRows,
+ getAccountUsageRows,
+ getApiKeyUsageRows,
+ getServiceTierUsageRows,
+ getApiKeyMetadataRows,
+ getWeeklyPatternRows,
+ getPresetCostModelRows,
+} from "@/lib/db/usageAnalytics";
+import { getFallbackStats } from "@/lib/db/callLogStats";
function getRangeStartIso(range: string): string | null {
const end = new Date();
@@ -319,7 +337,6 @@ export async function GET(request: Request) {
const untilIso = endDate || null;
const presetsParam = searchParams.get("presets");
- const db = getDbInstance();
const apiKeys = await getApiKeys();
const currentApiKeyNames = new Map<string, string>();
for (const apiKey of apiKeys) {
@@ -360,118 +377,21 @@ export async function GET(request: Request) {
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
- // Build a UNION data source that merges recent raw rows with aggregated history.
- // daily_usage_summary rows are included only when the query window extends before
- // rawCutoffIso. They are gated off entirely when an api_key filter is active:
- // daily_usage_summary does not store api_key/connection, so including it under a
- // key filter would leak other keys' aggregated usage. With a key filter we serve
- // only raw rows (older key-scoped data beyond retention is intentionally unavailable).
+ // Build the UNION data source that merges recent raw rows with older aggregated history.
+ // SQL is encapsulated in usageAnalytics.ts — the route only supplies filter parameters.
const rawCutoffDate = rawCutoffIso.split("T")[0];
- const needsAggregated = (!sinceIso || sinceIso < rawCutoffDate) && apiKeyIds.length === 0;
-
- // Build a separate params object for the unified CTE source.
- // better-sqlite3 rejects named params that don't appear in the SQL,
- // so each query context must only receive the placeholders it references.
- const unifiedParams: Record<string, string> = {};
-
- // Raw leg: when aggregated rows are also included, lower-bound the raw leg at the
- // raw cutoff so the two legs never overlap (prevents double-counting).
- const rawConditions: string[] = [];
- if (needsAggregated) {
- rawConditions.push("timestamp >= @rawCutoff");
- unifiedParams.rawCutoff = rawCutoffDate;
- } else if (sinceIso) {
- rawConditions.push("timestamp >= @since");
- unifiedParams.since = sinceIso;
- }
- if (untilIso) {
- rawConditions.push("timestamp <= @until");
- unifiedParams.until = untilIso;
- }
- if (apiKeyWhere) {
- rawConditions.push(apiKeyWhere);
- apiKeyIds.forEach((key, i) => {
- unifiedParams[`apiKey${i}`] = key;
- });
- }
- const rawWhere = rawConditions.length > 0 ? `WHERE ${rawConditions.join(" AND ")}` : "";
-
- // Aggregated rows span the requested window but strictly before the raw cutoff,
- // so they never overlap the raw leg above (no api_key filter — see note above).
- // Only build agg params when the agg branch is actually used in the CTE.
- const aggConditions: string[] = [];
- if (needsAggregated) {
- if (sinceIso) {
- // Use date comparison on the summary's date column (YYYY-MM-DD).
- const sinceDate = sinceIso.split("T")[0];
- aggConditions.push("date >= @sinceDate");
- unifiedParams.sinceDate = sinceDate;
- }
- if (untilIso) {
- const untilDate = untilIso.split("T")[0];
- aggConditions.push("date <= @untilDate");
- unifiedParams.untilDate = untilDate;
- }
- aggConditions.push("date < @rawCutoffDate");
- unifiedParams.rawCutoffDate = rawCutoffDate;
- }
- const aggWhere = aggConditions.length > 0 ? `WHERE ${aggConditions.join(" AND ")}` : "";
-
- // Unified source CTE: columns aligned to usage_history shape needed by analytics queries.
- // Fields not available in daily_usage_summary default to 0/NULL.
- const unifiedSource = needsAggregated
- ? `(
- SELECT
- timestamp,
- provider,
- model,
- tokens_input,
- tokens_output,
- tokens_cache_read,
- tokens_cache_creation,
- tokens_reasoning,
- service_tier,
- success,
- latency_ms,
- connection_id,
- api_key_id,
- api_key_name
- FROM usage_history
- ${rawWhere}
- UNION ALL
- SELECT
- date || 'T12:00:00.000Z' as timestamp,
- provider,
- model,
- total_input_tokens as tokens_input,
- total_output_tokens as tokens_output,
- 0 as tokens_cache_read,
- 0 as tokens_cache_creation,
- 0 as tokens_reasoning,
- 'standard' as service_tier,
- 1 as success,
- 0 as latency_ms,
- NULL as connection_id,
- NULL as api_key_id,
- NULL as api_key_name
- FROM daily_usage_summary
- ${aggWhere}
- )`
- : `(SELECT
- timestamp, provider, model,
- tokens_input, tokens_output,
- tokens_cache_read, tokens_cache_creation, tokens_reasoning,
- service_tier, success, latency_ms,
- connection_id, api_key_id, api_key_name
- FROM usage_history
- ${whereClause}
- )`;
-
- // When using the unified source the WHERE filters are already embedded inside.
- // For the original whereClause-based queries that still reference usage_history directly
- // (e.g. fallbackRow, accountRows) we keep them as-is since they need joins or
- // columns only present in usage_history.
- const unifiedWhere = ""; // no additional WHERE needed — filters embedded in unifiedSource
+ const apiKeyParamEntries: Record<string, string> = {};
+ apiKeyIds.forEach((key, i) => {
+ apiKeyParamEntries[`apiKey${i}`] = key;
+ });
+
+ const { unifiedSource, unifiedParams } = buildUnifiedSource({
+ sinceIso: sinceIso ?? null,
+ untilIso: untilIso ?? null,
+ rawCutoffDate,
+ apiKeyWhere,
+ apiKeyParams: apiKeyParamEntries,
+ });
// Fetch pricing data for cost calculation (no rows loaded)
const { getPricing } = await import("@/lib/db/settings");
@@ -490,64 +410,11 @@ export async function GET(request: Request) {
await import("@/lib/usage/costCalculator");
const { PROVIDER_ID_TO_ALIAS } = await import("@omniroute/open-sse/config/providerModels");
- const summaryRow = db
- .prepare(
- `
- SELECT
- COUNT(*) as totalRequests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COUNT(DISTINCT model) as uniqueModels,
- COUNT(DISTINCT connection_id) as uniqueAccounts,
- COUNT(DISTINCT COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''))) as uniqueApiKeys,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(MIN(timestamp), '') as firstRequest,
- COALESCE(MAX(timestamp), '') as lastRequest
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- `
- )
- .get(unifiedParams) as Record<string, unknown>;
-
- const dailyRows = db
- .prepare(
- `
- SELECT
- DATE(timestamp) as date,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY DATE(timestamp)
- ORDER BY date ASC
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const dailyCostRows = db
- .prepare(
- `
- SELECT
- DATE(timestamp) as date,
- LOWER(provider) as provider,
- LOWER(model) as model,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY DATE(timestamp), LOWER(provider), LOWER(model), serviceTier
- ORDER BY date ASC
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
+ const summaryRow = getUsageSummary(unifiedSource, unifiedParams) as Record<string, unknown>;
+
+ const dailyRows = getDailyUsage(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const dailyCostRows = getDailyCostRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
const heatmapStart = new Date();
heatmapStart.setUTCDate(heatmapStart.getUTCDate() - 364);
@@ -569,189 +436,30 @@ export async function GET(request: Request) {
});
}
- const heatmapRows = db
- .prepare(
- `
- SELECT
- DATE(timestamp) as date,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- WHERE ${heatmapConditions.join(" AND ")}
- GROUP BY DATE(timestamp)
- ORDER BY date ASC
- `
- )
- .all(heatmapParams) as Array<Record<string, unknown>>;
-
- const modelRows = db
- .prepare(
- `
- SELECT
- LOWER(model) as model,
- LOWER(provider) as provider,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
- COALESCE(MAX(timestamp), '') as lastUsed
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY LOWER(model), LOWER(provider), serviceTier
- ORDER BY requests DESC
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const providerCostRows = db
- .prepare(
- `
- SELECT
- LOWER(provider) as provider,
- LOWER(model) as model,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY LOWER(provider), LOWER(model), serviceTier
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const providerRows = db
- .prepare(
- `
- SELECT
- LOWER(provider) as provider,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY LOWER(provider)
- ORDER BY requests DESC
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const accountCostRows = db
- .prepare(
- `
- SELECT
- COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,
- LOWER(usage_history.provider) as provider,
- LOWER(usage_history.model) as model,
- COALESCE(NULLIF(usage_history.service_tier, ''), 'standard') as serviceTier,
- COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,
- COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,
- COALESCE(SUM(usage_history.tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(usage_history.tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(usage_history.tokens_reasoning), 0) as reasoningTokens
- FROM usage_history
- LEFT JOIN provider_connections c ON c.id = usage_history.connection_id
- ${whereClause.replace(/timestamp/g, "usage_history.timestamp").replace(/api_key_/g, "usage_history.api_key_")}
- GROUP BY account, LOWER(usage_history.provider), LOWER(usage_history.model), serviceTier
- `
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const accountRows = db
- .prepare(
- `
- SELECT
- COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,
- COUNT(usage_history.id) as requests,
- COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,
- COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,
- COALESCE(SUM(usage_history.tokens_input + usage_history.tokens_output), 0) as totalTokens,
- COALESCE(AVG(usage_history.latency_ms), 0) as avgLatencyMs,
- COALESCE(MAX(usage_history.timestamp), '') as lastUsed
- FROM usage_history
- LEFT JOIN provider_connections c ON c.id = usage_history.connection_id
- ${whereClause.replace(/timestamp/g, "usage_history.timestamp").replace(/api_key_/g, "usage_history.api_key_")}
- GROUP BY account
- ORDER BY requests DESC
- LIMIT 50
- `
- )
- .all(params) as Array<Record<string, unknown>>;
+ const heatmapRows = getHeatmapRows(heatmapConditions, heatmapParams) as Array<Record<string, unknown>>;
+
+ const modelRows = getModelUsageRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const providerCostRows = getProviderCostRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const providerRows = getProviderUsageRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const accountCostWhereClause = whereClause
+ .replace(/timestamp/g, "usage_history.timestamp")
+ .replace(/api_key_/g, "usage_history.api_key_");
+ const accountCostRows = getAccountCostRows(accountCostWhereClause, params) as Array<Record<string, unknown>>;
+
+ const accountRows = getAccountUsageRows(accountCostWhereClause, params) as Array<Record<string, unknown>>;
const apiKeyWhereClause = appendWhereCondition(
whereClause,
"(api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')"
);
- const apiKeyRows = db
- .prepare(
- `
- SELECT
- NULLIF(api_key_id, '') as apiKeyId,
- COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown') as apiKeyGroupKey,
- LOWER(provider) as provider,
- LOWER(model) as model,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- ${apiKeyWhereClause}
- GROUP BY COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown'), NULLIF(api_key_id, ''), LOWER(provider), LOWER(model), serviceTier
- `
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const serviceTierRows = db
- .prepare(
- `
- SELECT
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- LOWER(provider) as provider,
- LOWER(model) as model,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY serviceTier, LOWER(provider), LOWER(model)
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const apiKeyMetadataRows = db
- .prepare(
- `
- SELECT
- NULLIF(api_key_id, '') as apiKeyId,
- NULLIF(api_key_name, '') as apiKeyName,
- COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown') as apiKeyGroupKey,
- MAX(timestamp) as lastUsed
- FROM usage_history
- ${apiKeyWhereClause}
- GROUP BY NULLIF(api_key_id, ''), NULLIF(api_key_name, '')
- ORDER BY lastUsed DESC
- `
- )
- .all(params) as Array<Record<string, unknown>>;
+ const apiKeyRows = getApiKeyUsageRows(apiKeyWhereClause, params) as Array<Record<string, unknown>>;
+
+ const serviceTierRows = getServiceTierUsageRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const apiKeyMetadataRows = getApiKeyMetadataRows(apiKeyWhereClause, params) as Array<Record<string, unknown>>;
const apiKeyMetadata = new Map<string, { latestName: string; aliases: Set<string> }>();
for (const row of apiKeyMetadataRows) {
@@ -768,58 +476,9 @@ export async function GET(request: Request) {
apiKeyMetadata.set(groupKey, existing);
}
- const weeklyRows = db
- .prepare(
- `
- SELECT
- dayOfWeek,
- COUNT(*) as days,
- COALESCE(SUM(requests), 0) as requests,
- COALESCE(SUM(totalTokens), 0) as totalTokens
- FROM (
- SELECT
- DATE(timestamp) as date,
- strftime('%w', timestamp) as dayOfWeek,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM ${unifiedSource} AS _u
- ${unifiedWhere}
- GROUP BY DATE(timestamp), strftime('%w', timestamp)
- )
- GROUP BY dayOfWeek
- ORDER BY dayOfWeek ASC
- `
- )
- .all(unifiedParams) as Array<Record<string, unknown>>;
-
- const fallbackRow = db
- .prepare(
- `
- SELECT
- SUM(CASE WHEN (combo_name IS NULL OR combo_name = '') THEN 1 ELSE 0 END) as total,
- SUM(CASE WHEN requested_model IS NOT NULL AND requested_model != '' AND (combo_name IS NULL OR combo_name = '') THEN 1 ELSE 0 END) as with_requested,
- SUM(CASE
- WHEN (combo_name IS NULL OR combo_name = '')
- AND requested_model IS NOT NULL
- AND requested_model != ''
- AND model IS NOT NULL
- AND model != ''
- THEN 1 ELSE 0 END
- ) as fallback_eligible,
- SUM(CASE
- WHEN (combo_name IS NULL OR combo_name = '')
- AND requested_model IS NOT NULL
- AND requested_model != ''
- AND model IS NOT NULL
- AND model != ''
- AND LOWER(CASE WHEN instr(requested_model, '/') > 0 THEN substr(requested_model, instr(requested_model, '/') + 1) ELSE requested_model END) != LOWER(model)
- THEN 1 ELSE 0 END
- ) as fallbacks
- FROM call_logs
- ${whereClause}
- `
- )
- .get(params) as Record<string, unknown>;
+ const weeklyRows = getWeeklyPatternRows(unifiedSource, unifiedParams) as Array<Record<string, unknown>>;
+
+ const fallbackRow = getFallbackStats(whereClause, params) as Record<string, unknown>;
const summary = {
totalRequests: Number(summaryRow?.totalRequests || 0),
@@ -1237,89 +896,16 @@ export async function GET(request: Request) {
}
const presetSinceIso = getRangeStartIso(presetRange);
- const presetParams: Record<string, string> = {};
-
- // Build unified source for preset cost queries (same UNION logic as main query).
- // Aggregated rows are gated off when an api_key filter is active (leakage) and
- // bounded strictly before the raw cutoff (overlap / double-count) — see main query.
- const presetNeedsAggregated =
- (!presetSinceIso || presetSinceIso < rawCutoffDate) && apiKeyIds.length === 0;
-
- const presetRawConds: string[] = [];
- if (presetNeedsAggregated) {
- presetRawConds.push("timestamp >= @presetRawCutoff");
- presetParams.presetRawCutoff = rawCutoffDate;
- } else if (presetSinceIso) {
- presetRawConds.push("timestamp >= @presetSince");
- presetParams.presetSince = presetSinceIso;
- }
- if (apiKeyWhere) {
- presetRawConds.push(apiKeyWhere);
- // Only copy apiKey params — better-sqlite3 rejects unknown named params.
- apiKeyIds.forEach((key, i) => {
- presetParams[`apiKey${i}`] = key;
+ const { unifiedSource: presetUnifiedSource, unifiedParams: presetParams } =
+ buildPresetUnifiedSource({
+ sinceIso: presetSinceIso ?? null,
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere,
+ apiKeyParams: apiKeyParamEntries,
});
- }
- const presetRawWhere =
- presetRawConds.length > 0 ? `WHERE ${presetRawConds.join(" AND ")}` : "";
-
- const presetAggConds: string[] = [];
- if (presetNeedsAggregated) {
- if (presetSinceIso) {
- const presetSinceDate = presetSinceIso.split("T")[0];
- presetAggConds.push("date >= @presetSinceDate");
- presetParams.presetSinceDate = presetSinceDate;
- }
- presetAggConds.push("date < @presetRawCutoffDate");
- presetParams.presetRawCutoffDate = rawCutoffDate;
- }
- const presetAggWhere =
- presetAggConds.length > 0 ? `WHERE ${presetAggConds.join(" AND ")}` : "";
-
- const presetUnifiedSource = presetNeedsAggregated
- ? `(
- SELECT timestamp, provider, model, service_tier,
- tokens_input, tokens_output,
- tokens_cache_read, tokens_cache_creation, tokens_reasoning
- FROM usage_history
- ${presetRawWhere}
- UNION ALL
- SELECT
- date || 'T12:00:00.000Z' as timestamp,
- provider, model,
- 'standard' as service_tier,
- total_input_tokens as tokens_input,
- total_output_tokens as tokens_output,
- 0 as tokens_cache_read,
- 0 as tokens_cache_creation,
- 0 as tokens_reasoning
- FROM daily_usage_summary
- ${presetAggWhere}
- )`
- : `(SELECT timestamp, provider, model, service_tier,
- tokens_input, tokens_output,
- tokens_cache_read, tokens_cache_creation, tokens_reasoning
- FROM usage_history
- ${presetRawWhere}
- )`;
-
- const presetModelRows = db
- .prepare(
- `
- SELECT
- LOWER(model) as model,
- LOWER(provider) as provider,
- COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM ${presetUnifiedSource} AS _pu
- GROUP BY LOWER(model), LOWER(provider), serviceTier
- `
- )
- .all(presetParams) as Array<Record<string, unknown>>;
+
+ const presetModelRows = getPresetCostModelRows(presetUnifiedSource, presetParams) as Array<Record<string, unknown>>;
let presetTotalCost = 0;
for (const row of presetModelRows) {
diff --git a/src/app/api/v1/search/analytics/route.ts b/src/app/api/v1/search/analytics/route.ts
index 68341baeac..a2cd7e275d 100644
--- a/src/app/api/v1/search/analytics/route.ts
+++ b/src/app/api/v1/search/analytics/route.ts
@@ -7,40 +7,20 @@
import { NextResponse } from "next/server";
import { SEARCH_PROVIDERS } from "@omniroute/open-sse/config/searchRegistry.ts";
-import { getDbInstance } from "@/lib/db/core";
import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";
+import { getSearchAggregateStats, getSearchProviderCounts } from "@/lib/db/callLogStats";
export async function GET(req: Request) {
const policy = await enforceApiKeyPolicy(req, "analytics");
if (policy.rejection) return policy.rejection;
try {
- const db = getDbInstance();
-
// Single aggregated query for all scalar metrics — replaces 5 separate round-trips
const todayStart = new Date();
todayStart.setUTCHours(0, 0, 0, 0);
const todayIso = todayStart.toISOString();
- type StatsRow = {
- total: number;
- today: number;
- errors: number;
- avg_duration: number | null;
- cached: number;
- };
- const statsRow = db
- .prepare(
- `SELECT
- COUNT(*) as total,
- COALESCE(SUM(CASE WHEN timestamp >= ? THEN 1 ELSE 0 END), 0) as today,
- COALESCE(SUM(CASE WHEN status >= 400 OR error_summary IS NOT NULL THEN 1 ELSE 0 END), 0) as errors,
- AVG(CASE WHEN duration > 0 THEN duration END) as avg_duration,
- COALESCE(SUM(CASE WHEN duration > 0 AND duration < 5 THEN 1 ELSE 0 END), 0) as cached
- FROM call_logs
- WHERE request_type = 'search'`
- )
- .get(todayIso) as StatsRow | undefined;
+ const statsRow = getSearchAggregateStats(todayIso);
const total = statsRow?.total ?? 0;
const today = statsRow?.today ?? 0;
@@ -49,13 +29,7 @@ export async function GET(req: Request) {
const cached = statsRow?.cached ?? 0;
// Per-provider breakdown
- const provRows = db
- .prepare(
- `SELECT provider, COUNT(*) as cnt
- FROM call_logs WHERE request_type = 'search'
- GROUP BY provider ORDER BY cnt DESC`
- )
- .all() as Array<{ provider: string; cnt: number }>;
+ const provRows = getSearchProviderCounts();
const byProvider: Record<string, { count: number; costUsd: number }> = {};
let totalCostUsd = 0;
diff --git a/src/i18n/messages/ar.json b/src/i18n/messages/ar.json
index 0d5bac6446..1dcf7802f5 100644
--- a/src/i18n/messages/ar.json
+++ b/src/i18n/messages/ar.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "فشل في تعيين الاسم المستعار",
"failedSaveConnection": "فشل حفظ الاتصال",
"failedSaveConnectionRetry": "فشل حفظ الاتصال. يرجى المحاولة مرة أخرى.",
diff --git a/src/i18n/messages/az.json b/src/i18n/messages/az.json
index 7ba60d7218..4861ac7244 100644
--- a/src/i18n/messages/az.json
+++ b/src/i18n/messages/az.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/bg.json b/src/i18n/messages/bg.json
index 0a979f4420..d6a06a4ad1 100644
--- a/src/i18n/messages/bg.json
+++ b/src/i18n/messages/bg.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Неуспешно задаване на псевдоним",
"failedSaveConnection": "Неуспешно запазване на връзката",
"failedSaveConnectionRetry": "Неуспешно запазване на връзката. Моля, опитайте отново.",
diff --git a/src/i18n/messages/bn.json b/src/i18n/messages/bn.json
index 18d38b4be3..c198c97a0f 100644
--- a/src/i18n/messages/bn.json
+++ b/src/i18n/messages/bn.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/cs.json b/src/i18n/messages/cs.json
index 5370f35c5f..b867dddf40 100644
--- a/src/i18n/messages/cs.json
+++ b/src/i18n/messages/cs.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nastavení aliasu selhalo",
"failedSaveConnection": "Uložení připojení selhalo",
"failedSaveConnectionRetry": "Uložení připojení selhalo. Zkuste to prosím znovu.",
diff --git a/src/i18n/messages/da.json b/src/i18n/messages/da.json
index 3bced90366..53c921d565 100644
--- a/src/i18n/messages/da.json
+++ b/src/i18n/messages/da.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Aliaset kunne ikke indstilles",
"failedSaveConnection": "Forbindelsen kunne ikke gemmes",
"failedSaveConnectionRetry": "Forbindelsen kunne ikke gemmes. Prøv venligst igen.",
diff --git a/src/i18n/messages/de.json b/src/i18n/messages/de.json
index eeb509339d..2d9ce013a1 100644
--- a/src/i18n/messages/de.json
+++ b/src/i18n/messages/de.json
@@ -3755,6 +3755,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Alias konnte nicht festgelegt werden",
"failedSaveConnection": "Die Verbindung konnte nicht gespeichert werden",
"failedSaveConnectionRetry": "Die Verbindung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",
diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.json
index fc986794f2..565c97cc34 100644
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@ -1325,7 +1325,7 @@
"settings.update_failed": "Settings Update Failed",
"sync.token.created": "Sync Token Created",
"sync.token.revoked": "Sync Token Revoked"
- }
+ }
},
"themesPage": {
"title": "Themes",
@@ -4000,6 +4000,10 @@
"batchRetestSelected": "Retest",
"batchActivateSuccess": "Activated {count} connection(s)",
"batchDeactivateSuccess": "Deactivated {count} connection(s)",
+ "batchUpdatePartial": "{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "Retest up to {max} connections at a time",
+ "noConnectionsToTest": "No matching connections to test",
"batchDeleteConfirmTitle": "Delete connections",
"batchDeleteConfirmButton": "Delete",
"filterAll": "All",
@@ -6585,6 +6589,11 @@
"quotaCutoffsButtonDefault": "Default",
"quotaCutoffsButtonHelp": "Edit minimum remaining quota cutoffs for this account.",
"quotaCutoffsButtonDisabled": "No quota windows are available for this account yet.",
+ "deactivateAccount": "Deactivate account (stop routing)",
+ "activateAccount": "Activate account (resume routing)",
+ "accountActivated": "Account activated",
+ "accountDeactivated": "Account deactivated",
+ "toggleActiveFailed": "Failed to update account status",
"quotaCutoffsTitle": "Quota cutoffs for {name} ({provider})",
"quotaCutoffsExplainer": "Override the minimum remaining quota percentage where this account stops being selected for each quota window. Leave blank to inherit the provider default.",
"quotaCutoffsDefaultHint": "Default min remaining: {default}%",
@@ -8232,6 +8241,7 @@
"providerCredentialsUpdated": "{actor} updated credentials for {target}",
"providerCredentialsRevoked": "{actor} revoked credentials for {target}",
"providerCredentialsBatchRevoked": "{actor} batch-revoked credentials",
+ "providerCredentialsBatchUpdated": "{actor} batch-updated credentials",
"providerCredentialsBulkCreated": "{actor} bulk-created credentials",
"providerCredentialsBulkImported": "{actor} bulk-imported credentials",
"providerCredentialsImported": "{actor} imported credentials",
diff --git a/src/i18n/messages/es.json b/src/i18n/messages/es.json
index 060d3f35ba..39e6a823ad 100644
--- a/src/i18n/messages/es.json
+++ b/src/i18n/messages/es.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "No se pudo establecer el alias",
"failedSaveConnection": "No se pudo guardar la conexión",
"failedSaveConnectionRetry": "No se pudo guardar la conexión. Por favor inténtalo de nuevo.",
diff --git a/src/i18n/messages/fa.json b/src/i18n/messages/fa.json
index 9b1afb83d1..b6154633b4 100644
--- a/src/i18n/messages/fa.json
+++ b/src/i18n/messages/fa.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/fi.json b/src/i18n/messages/fi.json
index 1c2cd4c08e..254ca4d30e 100644
--- a/src/i18n/messages/fi.json
+++ b/src/i18n/messages/fi.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Aliaksen asettaminen epäonnistui",
"failedSaveConnection": "Yhteyden tallentaminen epäonnistui",
"failedSaveConnectionRetry": "Yhteyden tallentaminen epäonnistui. Yritä uudelleen.",
diff --git a/src/i18n/messages/fr.json b/src/i18n/messages/fr.json
index edb077d784..b5423cb923 100644
--- a/src/i18n/messages/fr.json
+++ b/src/i18n/messages/fr.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Échec de la définition de l'alias",
"failedSaveConnection": "Échec de l'enregistrement de la connexion",
"failedSaveConnectionRetry": "Échec de l'enregistrement de la connexion. Veuillez réessayer.",
diff --git a/src/i18n/messages/gu.json b/src/i18n/messages/gu.json
index 759c6781fd..8e05ddad6f 100644
--- a/src/i18n/messages/gu.json
+++ b/src/i18n/messages/gu.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/he.json b/src/i18n/messages/he.json
index 2c1212f9d2..8c5db72b30 100644
--- a/src/i18n/messages/he.json
+++ b/src/i18n/messages/he.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "הגדרת הכינוי נכשלה",
"failedSaveConnection": "שמירת החיבור נכשלה",
"failedSaveConnectionRetry": "שמירת החיבור נכשלה. אנא נסה שוב.",
diff --git a/src/i18n/messages/hi.json b/src/i18n/messages/hi.json
index 918e44820c..333d2aa80d 100644
--- a/src/i18n/messages/hi.json
+++ b/src/i18n/messages/hi.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "उपनाम सेट करने में विफल",
"failedSaveConnection": "कनेक्शन सहेजने में विफल",
"failedSaveConnectionRetry": "कनेक्शन सहेजने में विफल. कृपया पुन: प्रयास करें।",
diff --git a/src/i18n/messages/hu.json b/src/i18n/messages/hu.json
index 323c0d6252..871c3d265a 100644
--- a/src/i18n/messages/hu.json
+++ b/src/i18n/messages/hu.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nem sikerült beállítani az aliast",
"failedSaveConnection": "Nem sikerült menteni a kapcsolatot",
"failedSaveConnectionRetry": "Nem sikerült menteni a kapcsolatot. Kérjük, próbálja újra.",
diff --git a/src/i18n/messages/id.json b/src/i18n/messages/id.json
index fc970dcae1..53ba10bd7f 100644
--- a/src/i18n/messages/id.json
+++ b/src/i18n/messages/id.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Gagal menyetel alias",
"failedSaveConnection": "Gagal menyimpan koneksi",
"failedSaveConnectionRetry": "Gagal menyimpan koneksi. Silakan coba lagi.",
diff --git a/src/i18n/messages/in.json b/src/i18n/messages/in.json
index f12d68891d..c41b047211 100644
--- a/src/i18n/messages/in.json
+++ b/src/i18n/messages/in.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/it.json b/src/i18n/messages/it.json
index 853620a414..de0c14fd66 100644
--- a/src/i18n/messages/it.json
+++ b/src/i18n/messages/it.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Impossibile impostare l'alias",
"failedSaveConnection": "Impossibile salvare la connessione",
"failedSaveConnectionRetry": "Impossibile salvare la connessione. Per favore riprova.",
diff --git a/src/i18n/messages/ja.json b/src/i18n/messages/ja.json
index cebcaefae0..39c7cd6a73 100644
--- a/src/i18n/messages/ja.json
+++ b/src/i18n/messages/ja.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "エイリアスの設定に失敗しました",
"failedSaveConnection": "接続の保存に失敗しました",
"failedSaveConnectionRetry": "接続を保存できませんでした。もう一度試してください。",
diff --git a/src/i18n/messages/ko.json b/src/i18n/messages/ko.json
index 8c2c59e4b1..aef4af53ea 100644
--- a/src/i18n/messages/ko.json
+++ b/src/i18n/messages/ko.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "별칭을 설정하지 못했습니다.",
"failedSaveConnection": "연결을 저장하지 못했습니다.",
"failedSaveConnectionRetry": "연결을 저장하지 못했습니다. 다시 시도해 주세요.",
diff --git a/src/i18n/messages/mr.json b/src/i18n/messages/mr.json
index 7f43664c63..d872d24d74 100644
--- a/src/i18n/messages/mr.json
+++ b/src/i18n/messages/mr.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/ms.json b/src/i18n/messages/ms.json
index eda6234480..f34663c3ee 100644
--- a/src/i18n/messages/ms.json
+++ b/src/i18n/messages/ms.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Gagal menetapkan alias",
"failedSaveConnection": "Gagal menyimpan sambungan",
"failedSaveConnectionRetry": "Gagal menyimpan sambungan. Sila cuba lagi.",
diff --git a/src/i18n/messages/nl.json b/src/i18n/messages/nl.json
index 14aef8ba1d..2583c6be03 100644
--- a/src/i18n/messages/nl.json
+++ b/src/i18n/messages/nl.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Kan alias niet instellen",
"failedSaveConnection": "Kan de verbinding niet opslaan",
"failedSaveConnectionRetry": "Kan de verbinding niet opslaan. Probeer het opnieuw.",
diff --git a/src/i18n/messages/no.json b/src/i18n/messages/no.json
index 0b71a6b107..60cf96e24f 100644
--- a/src/i18n/messages/no.json
+++ b/src/i18n/messages/no.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Kunne ikke angi alias",
"failedSaveConnection": "Kunne ikke lagre tilkoblingen",
"failedSaveConnectionRetry": "Kunne ikke lagre tilkoblingen. Vennligst prøv igjen.",
diff --git a/src/i18n/messages/phi.json b/src/i18n/messages/phi.json
index ff52d53f9d..d4f5be8da6 100644
--- a/src/i18n/messages/phi.json
+++ b/src/i18n/messages/phi.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nabigong itakda ang alias",
"failedSaveConnection": "Nabigong i-save ang koneksyon",
"failedSaveConnectionRetry": "Nabigong i-save ang koneksyon. Pakisubukang muli.",
diff --git a/src/i18n/messages/pl.json b/src/i18n/messages/pl.json
index 142d74f45c..c213a7f260 100644
--- a/src/i18n/messages/pl.json
+++ b/src/i18n/messages/pl.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nie udało się ustawić aliasu",
"failedSaveConnection": "Nie udało się zapisać połączenia",
"failedSaveConnectionRetry": "Nie udało się zapisać połączenia. Spróbuj ponownie.",
diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.json
index 5a8c0a38b7..735431d842 100644
--- a/src/i18n/messages/pt-BR.json
+++ b/src/i18n/messages/pt-BR.json
@@ -4507,6 +4507,10 @@
"batchRetestSelected": "Retestar",
"batchActivateSuccess": "{count} conexão(ões) ativada(s)",
"batchDeactivateSuccess": "{count} conexão(ões) desativada(s)",
+ "batchUpdatePartial": "{count} atualizada(s), {skipped} ignorada(s) (não existem mais)",
+ "batchUpdateNone": "Nenhuma conexão foi atualizada (podem não existir mais)",
+ "batchRetestLimit": "Reteste até {max} conexões por vez",
+ "noConnectionsToTest": "Nenhuma conexão correspondente para testar",
"failedSetAlias": "Falha ao definir alias",
"failedSaveConnection": "Falha ao salvar conexão",
"failedSaveConnectionRetry": "Falha ao salvar conexão. Tente novamente.",
@@ -7846,6 +7850,11 @@
"quotaCutoffsButtonDefault": "Padrão",
"quotaCutoffsButtonHelp": "Edite os limites mínimos de cota restantes para esta conta.",
"quotaCutoffsButtonDisabled": "Ainda não há janelas de cota disponíveis para esta conta.",
+ "deactivateAccount": "Desativar conta (parar roteamento)",
+ "activateAccount": "Ativar conta (retomar roteamento)",
+ "accountActivated": "Conta ativada",
+ "accountDeactivated": "Conta desativada",
+ "toggleActiveFailed": "Falha ao atualizar o status da conta",
"quotaCutoffsTitle": "Limites de cota para {name} ({provider})",
"quotaCutoffsExplainer": "Substitua a porcentagem mínima de cota restante onde esta conta deixa de ser selecionada para cada janela de cota. Deixe em branco para herdar o padrão do provedor.",
"quotaCutoffsDefaultHint": "Minuto restante padrão: {default}%",
@@ -8138,6 +8147,7 @@
"providerCredentialsUpdated": "{actor} atualizou credenciais de {target}",
"providerCredentialsRevoked": "{actor} revogou credenciais de {target}",
"providerCredentialsBatchRevoked": "{actor} revogou credenciais em lote",
+ "providerCredentialsBatchUpdated": "{actor} atualizou credenciais em lote",
"providerCredentialsBulkCreated": "{actor} criou credenciais em lote",
"providerCredentialsBulkImported": "{actor} importou credenciais em lote",
"providerCredentialsImported": "{actor} importou credenciais",
diff --git a/src/i18n/messages/pt.json b/src/i18n/messages/pt.json
index c00d37b459..9354037bac 100644
--- a/src/i18n/messages/pt.json
+++ b/src/i18n/messages/pt.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "Retestar",
"batchActivateSuccess": "{count} conexão(ões) ativada(s)",
"batchDeactivateSuccess": "{count} conexão(ões) desativada(s)",
+ "batchUpdatePartial": "{count} atualizada(s), {skipped} ignorada(s) (não existem mais)",
+ "batchUpdateNone": "Nenhuma conexão foi atualizada (podem não existir mais)",
+ "batchRetestLimit": "Reteste até {max} conexões por vez",
+ "noConnectionsToTest": "Nenhuma conexão correspondente para testar",
"failedSetAlias": "Falha ao definir o alias",
"failedSaveConnection": "Falha ao salvar conexão",
"failedSaveConnectionRetry": "Falha ao salvar a conexão. Por favor, tente novamente.",
diff --git a/src/i18n/messages/ro.json b/src/i18n/messages/ro.json
index afe051ea6b..ce1102d2e4 100644
--- a/src/i18n/messages/ro.json
+++ b/src/i18n/messages/ro.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nu s-a putut seta aliasul",
"failedSaveConnection": "Nu s-a putut salva conexiunea",
"failedSaveConnectionRetry": "Nu s-a putut salva conexiunea. Vă rugăm să încercați din nou.",
diff --git a/src/i18n/messages/ru.json b/src/i18n/messages/ru.json
index fa4c86f9bb..461cd46dbe 100644
--- a/src/i18n/messages/ru.json
+++ b/src/i18n/messages/ru.json
@@ -3966,6 +3966,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Не удалось установить псевдоним",
"failedSaveConnection": "Не удалось сохранить соединение.",
"failedSaveConnectionRetry": "Не удалось сохранить соединение. Пожалуйста, попробуйте еще раз.",
@@ -8093,6 +8097,7 @@
"providerCredentialsUpdated": "{actor} обновил учетные данные для {target}",
"providerCredentialsRevoked": "{actor} отозвал учетные данные для {target}",
"providerCredentialsBatchRevoked": "{actor} пакетно отозвал учетные данные",
+ "providerCredentialsBatchUpdated": "__MISSING__:{actor} batch-updated credentials",
"providerCredentialsBulkCreated": "{actor} массово создал учетные данные",
"providerCredentialsBulkImported": "{actor} массово импортировал учетные данные",
"providerCredentialsImported": "{actor} импортированные учетные данные",
diff --git a/src/i18n/messages/sk.json b/src/i18n/messages/sk.json
index ce3964e6f5..4ff8163482 100644
--- a/src/i18n/messages/sk.json
+++ b/src/i18n/messages/sk.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Nepodarilo sa nastaviť alias",
"failedSaveConnection": "Pripojenie sa nepodarilo uložiť",
"failedSaveConnectionRetry": "Pripojenie sa nepodarilo uložiť. Skúste to znova.",
diff --git a/src/i18n/messages/sv.json b/src/i18n/messages/sv.json
index ddc4c30089..9ec80eb0a2 100644
--- a/src/i18n/messages/sv.json
+++ b/src/i18n/messages/sv.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Det gick inte att ange alias",
"failedSaveConnection": "Det gick inte att spara anslutningen",
"failedSaveConnectionRetry": "Det gick inte att spara anslutningen. Försök igen.",
diff --git a/src/i18n/messages/sw.json b/src/i18n/messages/sw.json
index 7fa0a1ec1e..1ebde70d5e 100644
--- a/src/i18n/messages/sw.json
+++ b/src/i18n/messages/sw.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/ta.json b/src/i18n/messages/ta.json
index 21c678ed0e..bb2fdc1539 100644
--- a/src/i18n/messages/ta.json
+++ b/src/i18n/messages/ta.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/te.json b/src/i18n/messages/te.json
index 96ad5f0ee2..5567ddeacb 100644
--- a/src/i18n/messages/te.json
+++ b/src/i18n/messages/te.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/th.json b/src/i18n/messages/th.json
index 6661b69f81..fb4da324b5 100644
--- a/src/i18n/messages/th.json
+++ b/src/i18n/messages/th.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "ไม่สามารถตั้งชื่อแทนได้",
"failedSaveConnection": "ไม่สามารถบันทึกการเชื่อมต่อ",
"failedSaveConnectionRetry": "ไม่สามารถบันทึกการเชื่อมต่อ โปรดลองอีกครั้ง",
diff --git a/src/i18n/messages/tr.json b/src/i18n/messages/tr.json
index 64b0fdbac2..d5790c0497 100644
--- a/src/i18n/messages/tr.json
+++ b/src/i18n/messages/tr.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Takma ad ayarlanamadı",
"failedSaveConnection": "Bağlantı kaydedilemedi",
"failedSaveConnectionRetry": "Bağlantı kaydedilemedi. Lütfen tekrar deneyin.",
diff --git a/src/i18n/messages/uk-UA.json b/src/i18n/messages/uk-UA.json
index 330b81ab3c..c2ca0a307e 100644
--- a/src/i18n/messages/uk-UA.json
+++ b/src/i18n/messages/uk-UA.json
@@ -3747,6 +3747,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Не вдалося встановити псевдонім",
"failedSaveConnection": "Не вдалося зберегти з’єднання",
"failedSaveConnectionRetry": "Не вдалося зберегти з’єднання. Спробуйте ще раз.",
diff --git a/src/i18n/messages/ur.json b/src/i18n/messages/ur.json
index 5de02a4bed..3d0d83f67f 100644
--- a/src/i18n/messages/ur.json
+++ b/src/i18n/messages/ur.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Failed to set alias",
"failedSaveConnection": "Failed to save connection",
"failedSaveConnectionRetry": "Failed to save connection. Please try again.",
diff --git a/src/i18n/messages/vi.json b/src/i18n/messages/vi.json
index e19a4a3b47..e368d8ee0f 100644
--- a/src/i18n/messages/vi.json
+++ b/src/i18n/messages/vi.json
@@ -3750,6 +3750,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"failedSetAlias": "Không đặt được bí danh",
"failedSaveConnection": "Không lưu được kết nối",
"failedSaveConnectionRetry": "Không lưu được kết nối. Vui lòng thử lại.",
diff --git a/src/i18n/messages/zh-CN.json b/src/i18n/messages/zh-CN.json
index e629bcea71..95e18c959b 100644
--- a/src/i18n/messages/zh-CN.json
+++ b/src/i18n/messages/zh-CN.json
@@ -3966,6 +3966,10 @@
"batchRetestSelected": "__MISSING__:Retest",
"batchActivateSuccess": "__MISSING__:Activated {count} connection(s)",
"batchDeactivateSuccess": "__MISSING__:Deactivated {count} connection(s)",
+ "batchUpdatePartial": "__MISSING__:{count} updated, {skipped} skipped (no longer exist)",
+ "batchUpdateNone": "__MISSING__:No connections were updated (they may no longer exist)",
+ "batchRetestLimit": "__MISSING__:Retest up to {max} connections at a time",
+ "noConnectionsToTest": "__MISSING__:No matching connections to test",
"batchDeleteConfirmTitle": "删除连接",
"batchDeleteConfirmButton": "删除",
"filterAll": "全部",
@@ -8101,6 +8105,7 @@
"providerCredentialsUpdated": "{actor} 更新了 {target} 的凭据",
"providerCredentialsRevoked": "{actor} 撤销了 {target} 的凭据",
"providerCredentialsBatchRevoked": "{actor} 批量撤销凭证",
+ "providerCredentialsBatchUpdated": "__MISSING__:{actor} batch-updated credentials",
"providerCredentialsBulkCreated": "{actor} 批量创建了凭据",
"providerCredentialsBulkImported": "{actor} 批量导入了凭据",
"providerCredentialsImported": "{actor} 导入的凭据",
diff --git a/src/instrumentation-node.ts b/src/instrumentation-node.ts
index cc3bfa9ea4..0af866d350 100755
--- a/src/instrumentation-node.ts
+++ b/src/instrumentation-node.ts
@@ -83,6 +83,25 @@ export async function registerNodejs(): Promise<void> {
const { initConsoleInterceptor } = await import("@/lib/consoleInterceptor");
initConsoleInterceptor();
+ // Clear stale transient connection cooldowns persisted from an unclean crash.
+ // A crash mid-burst can leave far-future `rate_limited_until` values in the DB
+ // that cause every connection to be skipped by getProviderCredentials(), making
+ // all subsequent requests time out at Bottleneck's maxWaitMs (120 s default).
+ // Terminal states (banned / expired / credits_exhausted) are intentionally kept.
+ // See: https://github.com/diegosouzapw/OmniRoute/issues/3625 (Part A)
+ try {
+ const { clearStaleCrashCooldowns } = await import("@/lib/db/providers");
+ const { cleared } = clearStaleCrashCooldowns();
+ if (cleared > 0) {
+ console.log(
+ `[STARTUP] Cleared ${cleared} stale transient connection cooldown(s) from prior crash (#3625)`
+ );
+ }
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.warn("[STARTUP] Could not clear stale crash cooldowns (non-fatal):", msg);
+ }
+
const [
{ initGracefulShutdown },
{ initApiBridgeServer },
diff --git a/src/lib/audit/activityIcons.ts b/src/lib/audit/activityIcons.ts
index 09be23a191..ce6ded6fa0 100644
--- a/src/lib/audit/activityIcons.ts
+++ b/src/lib/audit/activityIcons.ts
@@ -8,12 +8,31 @@ export interface ActivityIconSpec {
export const ACTIVITY_ICONS: Record<string, ActivityIconSpec> = {
// providers
"provider.credentials.created": { icon: "extension", i18nKeyVerb: "providerCredentialsCreated" },
- "provider.credentials.applied": { icon: "check_circle", i18nKeyVerb: "providerCredentialsApplied" },
+ "provider.credentials.applied": {
+ icon: "check_circle",
+ i18nKeyVerb: "providerCredentialsApplied",
+ },
"provider.credentials.updated": { icon: "edit", i18nKeyVerb: "providerCredentialsUpdated" },
- "provider.credentials.revoked": { icon: "extension_off", i18nKeyVerb: "providerCredentialsRevoked" },
- "provider.credentials.batch_revoked": { icon: "extension_off", i18nKeyVerb: "providerCredentialsBatchRevoked" },
- "provider.credentials.bulk_created": { icon: "extension", i18nKeyVerb: "providerCredentialsBulkCreated" },
- "provider.credentials.bulk_imported": { icon: "upload", i18nKeyVerb: "providerCredentialsBulkImported" },
+ "provider.credentials.revoked": {
+ icon: "extension_off",
+ i18nKeyVerb: "providerCredentialsRevoked",
+ },
+ "provider.credentials.batch_revoked": {
+ icon: "extension_off",
+ i18nKeyVerb: "providerCredentialsBatchRevoked",
+ },
+ "provider.credentials.batch_updated": {
+ icon: "edit",
+ i18nKeyVerb: "providerCredentialsBatchUpdated",
+ },
+ "provider.credentials.bulk_created": {
+ icon: "extension",
+ i18nKeyVerb: "providerCredentialsBulkCreated",
+ },
+ "provider.credentials.bulk_imported": {
+ icon: "upload",
+ i18nKeyVerb: "providerCredentialsBulkImported",
+ },
"provider.credentials.imported": { icon: "upload", i18nKeyVerb: "providerCredentialsImported" },
"provider.validation.ssrf_blocked": { icon: "block", i18nKeyVerb: "providerSsrfBlocked" },
diff --git a/src/lib/audit/highLevelActions.ts b/src/lib/audit/highLevelActions.ts
index 92d062d600..a76bae5763 100644
--- a/src/lib/audit/highLevelActions.ts
+++ b/src/lib/audit/highLevelActions.ts
@@ -16,6 +16,7 @@ export const HIGH_LEVEL_ACTIONS = [
"provider.credentials.updated",
"provider.credentials.revoked",
"provider.credentials.batch_revoked",
+ "provider.credentials.batch_updated",
"provider.credentials.bulk_created",
"provider.credentials.bulk_imported",
"provider.credentials.imported",
diff --git a/src/lib/cli-helper/config-generator/hermes-agent.ts b/src/lib/cli-helper/config-generator/hermes-agent.ts
index e037d17cb2..ee5d05fd2c 100644
--- a/src/lib/cli-helper/config-generator/hermes-agent.ts
+++ b/src/lib/cli-helper/config-generator/hermes-agent.ts
@@ -26,9 +26,8 @@
* }
*/
-import path from "node:path";
-import os from "node:os";
import * as yaml from "js-yaml";
+import { getHermesConfigPath } from "./hermesHome.ts";
export const HERMES_AGENT_ROLES = [
{ id: "default", label: "Default (main)", description: "Primary conversation model" },
@@ -58,7 +57,8 @@ export interface HermesAgentConfigPayload {
selections: HermesAgentRoleSelection[];
}
-const CONFIG_PATH = path.join(os.homedir(), ".hermes", "config.yaml");
+// Resolved lazily at call-time so HERMES_HOME is always honoured (#3628).
+const getConfigPath = () => getHermesConfigPath();
// Build a normalized base URL for Hermes (no trailing slash, no /v1 suffix on the provider entry)
function normalizeBaseUrl(base: string): string {
@@ -98,7 +98,7 @@ export async function generateHermesAgentConfig(
let existing: any = {};
try {
const fs = await import("node:fs/promises");
- const raw = await fs.readFile(CONFIG_PATH, "utf-8");
+ const raw = await fs.readFile(getConfigPath(), "utf-8");
existing = yaml.load(raw) || {};
} catch {
// no existing file — start fresh
@@ -167,7 +167,7 @@ export async function getCurrentHermesAgentRoles(): Promise<
let config: any = {};
try {
- const raw = await fs.readFile(CONFIG_PATH, "utf-8");
+ const raw = await fs.readFile(getConfigPath(), "utf-8");
config = yaml.load(raw) || {};
} catch {
return {};
diff --git a/src/lib/cli-helper/config-generator/hermesHome.ts b/src/lib/cli-helper/config-generator/hermesHome.ts
new file mode 100644
index 0000000000..c7f485b354
--- /dev/null
+++ b/src/lib/cli-helper/config-generator/hermesHome.ts
@@ -0,0 +1,40 @@
+/**
+ * Shared Hermes home-directory resolver (#3628).
+ *
+ * The Hermes PowerShell installer (Windows) writes its default config under
+ * `%LOCALAPPDATA%\hermes`, exposed as the `HERMES_HOME` env var. OmniRoute
+ * previously hard-coded `~/.hermes` everywhere, so the two config files never
+ * met on Windows.
+ *
+ * IMPORTANT: the env var MUST be read at call-time (i.e. inside a function),
+ * never at module-load time. `TOOL_CONFIG_PATHS` in index.ts is evaluated
+ * eagerly — any constant defined there would freeze the path at import.
+ * That's why this module exports plain functions instead of constants.
+ */
+
+import path from "node:path";
+import os from "node:os";
+
+/**
+ * Returns the Hermes home directory.
+ *
+ * Resolution order:
+ * 1. `HERMES_HOME` env var (if non-empty)
+ * 2. `~/.hermes` (cross-platform fallback)
+ *
+ * Reads `process.env.HERMES_HOME` every call so tests can set/unset the var
+ * without module-cache interference.
+ */
+export function getHermesHome(): string {
+ const override = (process.env.HERMES_HOME || "").trim();
+ return override || path.join(os.homedir(), ".hermes");
+}
+
+/**
+ * Returns the canonical path to the Hermes Agent `config.yaml`.
+ * Always delegates to `getHermesHome()` so it picks up `HERMES_HOME` at
+ * call-time.
+ */
+export function getHermesConfigPath(): string {
+ return path.join(getHermesHome(), "config.yaml");
+}
diff --git a/src/lib/cli-helper/config-generator/index.ts b/src/lib/cli-helper/config-generator/index.ts
index bdc5f884cb..24eac4f41a 100644
--- a/src/lib/cli-helper/config-generator/index.ts
+++ b/src/lib/cli-helper/config-generator/index.ts
@@ -1,6 +1,7 @@
import path from "node:path";
import os from "node:os";
+import { getHermesConfigPath } from "./hermesHome.ts";
import { generateClaudeConfig } from "./claude";
import { generateClineConfig } from "./cline";
import { generateCodexConfig } from "./codex";
@@ -37,17 +38,29 @@ function expandHome(p: string): string {
return p.replace(/^~\//, home + "/");
}
-const TOOL_CONFIG_PATHS: Record<string, string> = {
+// Static paths that do not depend on runtime env vars can stay eagerly computed.
+const STATIC_TOOL_CONFIG_PATHS: Record<string, string> = {
claude: path.join(os.homedir(), ".claude", "settings.json"),
codex: path.join(os.homedir(), ".codex", "config.yaml"),
opencode: path.join(os.homedir(), ".config", "opencode", "opencode.json"),
cline: path.join(os.homedir(), ".cline", "data", "globalState.json"),
kilocode: path.join(os.homedir(), ".config", "kilocode", "settings.json"),
continue: path.join(os.homedir(), ".continue", "config.yaml"),
- hermes: path.join(os.homedir(), ".hermes", "config.yaml"),
- "hermes-agent": path.join(os.homedir(), ".hermes", "config.yaml"),
};
+/**
+ * Returns the config path for a given tool.
+ *
+ * Hermes entries are resolved lazily at call-time so `HERMES_HOME` is always
+ * honoured (#3628). All other tools use the eagerly-computed static map.
+ */
+function getToolConfigPath(toolId: string): string {
+ if (toolId === "hermes" || toolId === "hermes-agent") {
+ return getHermesConfigPath();
+ }
+ return STATIC_TOOL_CONFIG_PATHS[toolId] ?? "";
+}
+
type ConfigGenerator = (options: GenerateOptions) => string | Promise<string>;
const GENERATORS: Record<string, ConfigGenerator> = {
@@ -83,7 +96,7 @@ export async function generateConfig(
return { success: false, configPath: "", error: `Unknown tool: ${toolId}` };
}
const content = await generate(options);
- const configPath = TOOL_CONFIG_PATHS[toolId] || "";
+ const configPath = getToolConfigPath(toolId);
return { success: true, configPath, content };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/src/lib/db/backup.ts b/src/lib/db/backup.ts
index ce2981588c..ac93730831 100644
--- a/src/lib/db/backup.ts
+++ b/src/lib/db/backup.ts
@@ -435,3 +435,120 @@ export async function restoreDbBackup(backupId: string) {
apiKeyCount: keyCount,
};
}
+
+// ──────────────── Export-All helpers (for /api/db-backups/exportAll) ────────────────
+
+export interface ExportAllRows {
+ settings: Record<string, string>;
+ combos: unknown[];
+ providers: unknown[];
+ apiKeys: unknown[];
+}
+
+/**
+ * Reads summary rows used by the exportAll backup route.
+ *
+ * - settings: full key_value table (key → value map)
+ * - combos: full combos table
+ * - providers: provider_connections rows, **excluding sensitive credentials**
+ * (id, provider, name, auth_type, is_active, email, created_at only)
+ * - apiKeys: api_keys rows with masked prefix
+ * (id, name, first 8 chars of key, machine_id, created_at)
+ *
+ * Each category is wrapped in a try/catch so a missing table never aborts the
+ * entire export — consistent with the original inline behaviour.
+ */
+export function exportAllSummaryRows(): ExportAllRows {
+ const db = getDbInstance();
+
+ const settings: Record<string, string> = {};
+ try {
+ const rows = db.prepare("SELECT key, value FROM key_value").all() as {
+ key: string;
+ value: string;
+ }[];
+ for (const row of rows) {
+ settings[row.key] = row.value;
+ }
+ } catch {
+ // key_value table might not exist
+ }
+
+ const combos: unknown[] = [];
+ try {
+ combos.push(...db.prepare("SELECT * FROM combos").all());
+ } catch {
+ // combos table might not exist
+ }
+
+ const providers: unknown[] = [];
+ try {
+ providers.push(
+ ...db
+ .prepare(
+ "SELECT id, provider, name, auth_type, is_active, email, created_at FROM provider_connections"
+ )
+ .all()
+ );
+ } catch {
+ // provider_connections table might not exist
+ }
+
+ const apiKeys: unknown[] = [];
+ try {
+ apiKeys.push(
+ ...db
+ .prepare(
+ "SELECT id, name, substr(key, 1, 8) as prefix, machine_id, created_at FROM api_keys"
+ )
+ .all()
+ );
+ } catch {
+ // api_keys table might not exist
+ }
+
+ return { settings, combos, providers, apiKeys };
+}
+
+// ──────────────── Import validation helpers (for /api/db-backups/import) ────────────────
+
+/**
+ * Queries an **already-opened** SQLite adapter for the list of table names.
+ *
+ * Used by the import route to validate that a candidate database contains the
+ * required OmniRoute tables before replacing the live database.
+ *
+ * Accepting an adapter as a parameter (rather than calling getDbInstance()) is
+ * intentional: the import route opens a *temporary* database for validation,
+ * not the live one.
+ */
+export function getTableNamesFromAdapter(adapter: {
+ prepare: (sql: string) => { all: () => unknown[] };
+}): string[] {
+ const rows = adapter
+ .prepare("SELECT name FROM sqlite_master WHERE type='table'")
+ .all() as Array<{ name: string }>;
+ return rows.map((r) => r.name);
+}
+
+/**
+ * Counts rows in a set of tables from the **live** database (post-import).
+ * Returns an object keyed by table name with the row count as value.
+ */
+export function countImportedRows(): {
+ connCount: number;
+ nodeCount: number;
+ comboCount: number;
+ keyCount: number;
+} {
+ const db = getDbInstance();
+ const connCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get() as any)?.cnt || 0;
+ const nodeCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM provider_nodes").get() as any)?.cnt || 0;
+ const comboCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM combos").get() as any)?.cnt || 0;
+ const keyCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM api_keys").get() as any)?.cnt || 0;
+ return { connCount, nodeCount, comboCount, keyCount };
+}
diff --git a/src/lib/db/callLogStats.ts b/src/lib/db/callLogStats.ts
new file mode 100644
index 0000000000..7a8ef741be
--- /dev/null
+++ b/src/lib/db/callLogStats.ts
@@ -0,0 +1,235 @@
+import { getDbInstance } from "./core";
+
+/**
+ * Aggregation queries over `call_logs` extracted from route handlers.
+ *
+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the
+ * /api/provider-metrics, /api/search/stats, and /api/v1/search/analytics routes
+ * can delegate. Read-only aggregation; no writes.
+ *
+ * Sliced out of #3500 (call_logs cluster).
+ */
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface ProviderMetricRow {
+ provider: string;
+ totalRequests: number;
+ totalSuccesses: number;
+ avgLatencyMs: number;
+ lastRequestAt: string | null;
+ lastErrorAt: string | null;
+ lastStatus: number | null;
+ lastErrorStatus: number | null;
+}
+
+export interface SearchProviderStatRow {
+ provider: string;
+ requests: number;
+ avg_latency_ms: number;
+}
+
+export interface SearchRecentRow {
+ request_summary: string | null;
+ provider: string;
+ timestamp: string;
+}
+
+export interface SearchAggregateStats {
+ total: number;
+ today: number;
+ errors: number;
+ avg_duration: number | null;
+ cached: number;
+}
+
+export interface SearchProviderCountRow {
+ provider: string;
+ cnt: number;
+}
+
+// ---------------------------------------------------------------------------
+// /api/provider-metrics — aggregate per-provider stats
+// ---------------------------------------------------------------------------
+
+/**
+ * Returns one row per provider with call-level aggregates plus last-status
+ * subselects. Excludes rows where provider is NULL or '-'.
+ */
+export function getProviderMetrics(): ProviderMetricRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `SELECT
+ c.provider,
+ COUNT(*) as totalRequests,
+ SUM(CASE WHEN status >= 200 AND status < 400 THEN 1 ELSE 0 END) as totalSuccesses,
+ ROUND(AVG(duration)) as avgLatencyMs,
+ MAX(timestamp) as lastRequestAt,
+ MAX(
+ CASE
+ WHEN (status IS NOT NULL AND (status < 200 OR status >= 400))
+ OR error_summary IS NOT NULL
+ THEN timestamp
+ ELSE NULL
+ END
+ ) as lastErrorAt,
+ (
+ SELECT c2.status
+ FROM call_logs c2
+ WHERE c2.provider = c.provider
+ ORDER BY c2.timestamp DESC, c2.id DESC
+ LIMIT 1
+ ) as lastStatus,
+ (
+ SELECT c3.status
+ FROM call_logs c3
+ WHERE c3.provider = c.provider
+ AND (
+ (c3.status IS NOT NULL AND (c3.status < 200 OR c3.status >= 400))
+ OR c3.error_summary IS NOT NULL
+ )
+ ORDER BY c3.timestamp DESC, c3.id DESC
+ LIMIT 1
+ ) as lastErrorStatus
+ FROM call_logs c
+ WHERE c.provider IS NOT NULL AND c.provider != '-'
+ GROUP BY c.provider`
+ )
+ .all() as ProviderMetricRow[];
+}
+
+// ---------------------------------------------------------------------------
+// /api/search/stats — search provider aggregates + recent entries
+// ---------------------------------------------------------------------------
+
+/**
+ * Per-provider request count and average latency for search requests.
+ */
+export function getSearchProviderStats(): SearchProviderStatRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT provider, COUNT(*) as requests,
+ CAST(AVG(duration) AS INTEGER) as avg_latency_ms
+ FROM call_logs
+ WHERE request_type = 'search'
+ GROUP BY provider
+ `
+ )
+ .all() as SearchProviderStatRow[];
+}
+
+/**
+ * Most recent 10 search entries (request_summary + provider + timestamp).
+ */
+export function getRecentSearchLogs(): SearchRecentRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT request_summary, provider, timestamp
+ FROM call_logs
+ WHERE request_type = 'search'
+ ORDER BY timestamp DESC
+ LIMIT 10
+ `
+ )
+ .all() as SearchRecentRow[];
+}
+
+// ---------------------------------------------------------------------------
+// /api/v1/search/analytics — aggregated search analytics
+// ---------------------------------------------------------------------------
+
+/**
+ * Single-pass scalar aggregations for all search entries since `todayIso`.
+ * `todayIso` is the ISO-8601 UTC start-of-day string used for the "today" count.
+ */
+export function getSearchAggregateStats(todayIso: string): SearchAggregateStats {
+ const db = getDbInstance();
+ const row = db
+ .prepare(
+ `SELECT
+ COUNT(*) as total,
+ COALESCE(SUM(CASE WHEN timestamp >= ? THEN 1 ELSE 0 END), 0) as today,
+ COALESCE(SUM(CASE WHEN status >= 400 OR error_summary IS NOT NULL THEN 1 ELSE 0 END), 0) as errors,
+ AVG(CASE WHEN duration > 0 THEN duration END) as avg_duration,
+ COALESCE(SUM(CASE WHEN duration > 0 AND duration < 5 THEN 1 ELSE 0 END), 0) as cached
+ FROM call_logs
+ WHERE request_type = 'search'`
+ )
+ .get(todayIso) as SearchAggregateStats | undefined;
+ return row ?? { total: 0, today: 0, errors: 0, avg_duration: null, cached: 0 };
+}
+
+/**
+ * Per-provider request count for search entries, ordered by count descending.
+ */
+export function getSearchProviderCounts(): SearchProviderCountRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `SELECT provider, COUNT(*) as cnt
+ FROM call_logs WHERE request_type = 'search'
+ GROUP BY provider ORDER BY cnt DESC`
+ )
+ .all() as SearchProviderCountRow[];
+}
+
+// ---------------------------------------------------------------------------
+// /api/usage/analytics — fallback-rate aggregates over call_logs
+// ---------------------------------------------------------------------------
+
+export interface FallbackStatsRow {
+ total: number;
+ with_requested: number;
+ fallback_eligible: number;
+ fallbacks: number;
+}
+
+/**
+ * Scalar fallback-rate stats over `call_logs` for the usage analytics endpoint.
+ *
+ * @param whereClause - SQL WHERE clause (may be empty string) using the same
+ * named params as the usage_history queries.
+ * @param params - Named params object (string values).
+ */
+export function getFallbackStats(
+ whereClause: string,
+ params: Record<string, string>
+): FallbackStatsRow {
+ const db = getDbInstance();
+ const row = db
+ .prepare(
+ `
+ SELECT
+ SUM(CASE WHEN (combo_name IS NULL OR combo_name = '') THEN 1 ELSE 0 END) as total,
+ SUM(CASE WHEN requested_model IS NOT NULL AND requested_model != '' AND (combo_name IS NULL OR combo_name = '') THEN 1 ELSE 0 END) as with_requested,
+ SUM(CASE
+ WHEN (combo_name IS NULL OR combo_name = '')
+ AND requested_model IS NOT NULL
+ AND requested_model != ''
+ AND model IS NOT NULL
+ AND model != ''
+ THEN 1 ELSE 0 END
+ ) as fallback_eligible,
+ SUM(CASE
+ WHEN (combo_name IS NULL OR combo_name = '')
+ AND requested_model IS NOT NULL
+ AND requested_model != ''
+ AND model IS NOT NULL
+ AND model != ''
+ AND LOWER(CASE WHEN instr(requested_model, '/') > 0 THEN substr(requested_model, instr(requested_model, '/') + 1) ELSE requested_model END) != LOWER(model)
+ THEN 1 ELSE 0 END
+ ) as fallbacks
+ FROM call_logs
+ ${whereClause}
+ `
+ )
+ .get(params) as FallbackStatsRow | undefined;
+ return row ?? { total: 0, with_requested: 0, fallback_eligible: 0, fallbacks: 0 };
+}
diff --git a/src/lib/db/compressionAnalytics.ts b/src/lib/db/compressionAnalytics.ts
index fd84fe35b6..ec5c025212 100644
--- a/src/lib/db/compressionAnalytics.ts
+++ b/src/lib/db/compressionAnalytics.ts
@@ -59,75 +59,38 @@ export interface CompressionAnalyticsSummary {
let columnsEnsuredForDb: unknown = null;
+const COMPRESSION_ANALYTICS_COLUMNS = [
+ ["actual_prompt_tokens", "INTEGER"],
+ ["actual_completion_tokens", "INTEGER"],
+ ["actual_total_tokens", "INTEGER"],
+ ["actual_cache_read_tokens", "INTEGER"],
+ ["actual_cache_write_tokens", "INTEGER"],
+ ["estimated_usd_saved", "REAL"],
+ ["mcp_description_tokens_saved", "INTEGER DEFAULT 0"],
+ ["multimodal_skip_count", "INTEGER DEFAULT 0"],
+ ["receipt_source", "TEXT"],
+ ["validation_fallback", "INTEGER DEFAULT 0"],
+ ["output_mode", "TEXT"],
+ ["compression_combo_id", "TEXT"],
+ ["engine", "TEXT"],
+ ["rtk_raw_output_pointer", "TEXT"],
+ ["rtk_raw_output_bytes", "INTEGER"],
+ ["rtk_raw_output_pointers", "TEXT"],
+ ["rtk_raw_output_total_bytes", "INTEGER"],
+] as const;
+
function ensureCompressionAnalyticsColumns(): void {
const db = getDbInstance();
if (columnsEnsuredForDb === db) return;
const rows = db.prepare("PRAGMA table_info(compression_analytics)").all() as Array<{
name: string;
}>;
- const columns = new Set(rows.map((row) => row.name));
- const addColumn = (name: string, sql: string) => {
- if (!columns.has(name)) db.exec(sql);
- };
- addColumn(
- "actual_prompt_tokens",
- "ALTER TABLE compression_analytics ADD COLUMN actual_prompt_tokens INTEGER"
- );
- addColumn(
- "actual_completion_tokens",
- "ALTER TABLE compression_analytics ADD COLUMN actual_completion_tokens INTEGER"
- );
- addColumn(
- "actual_total_tokens",
- "ALTER TABLE compression_analytics ADD COLUMN actual_total_tokens INTEGER"
- );
- addColumn(
- "actual_cache_read_tokens",
- "ALTER TABLE compression_analytics ADD COLUMN actual_cache_read_tokens INTEGER"
- );
- addColumn(
- "actual_cache_write_tokens",
- "ALTER TABLE compression_analytics ADD COLUMN actual_cache_write_tokens INTEGER"
- );
- addColumn(
- "estimated_usd_saved",
- "ALTER TABLE compression_analytics ADD COLUMN estimated_usd_saved REAL"
- );
- addColumn(
- "mcp_description_tokens_saved",
- "ALTER TABLE compression_analytics ADD COLUMN mcp_description_tokens_saved INTEGER DEFAULT 0"
- );
- addColumn(
- "multimodal_skip_count",
- "ALTER TABLE compression_analytics ADD COLUMN multimodal_skip_count INTEGER DEFAULT 0"
- );
- addColumn("receipt_source", "ALTER TABLE compression_analytics ADD COLUMN receipt_source TEXT");
- addColumn(
- "validation_fallback",
- "ALTER TABLE compression_analytics ADD COLUMN validation_fallback INTEGER DEFAULT 0"
- );
- addColumn("output_mode", "ALTER TABLE compression_analytics ADD COLUMN output_mode TEXT");
- addColumn(
- "compression_combo_id",
- "ALTER TABLE compression_analytics ADD COLUMN compression_combo_id TEXT"
- );
- addColumn("engine", "ALTER TABLE compression_analytics ADD COLUMN engine TEXT");
- addColumn(
- "rtk_raw_output_pointer",
- "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_pointer TEXT"
- );
- addColumn(
- "rtk_raw_output_bytes",
- "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_bytes INTEGER"
- );
- addColumn(
- "rtk_raw_output_pointers",
- "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_pointers TEXT"
- );
- addColumn(
- "rtk_raw_output_total_bytes",
- "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_total_bytes INTEGER"
- );
+ const existing = new Set(rows.map((row) => row.name));
+ for (const [name, type] of COMPRESSION_ANALYTICS_COLUMNS) {
+ if (!existing.has(name)) {
+ db.exec(`ALTER TABLE compression_analytics ADD COLUMN ${name} ${type}`);
+ }
+ }
columnsEnsuredForDb = db;
}
diff --git a/src/lib/db/gamification.ts b/src/lib/db/gamification.ts
index 7bfb5e4e37..731c5d82ad 100644
--- a/src/lib/db/gamification.ts
+++ b/src/lib/db/gamification.ts
@@ -485,6 +485,17 @@ export function revokeInvite(id: string): void {
// ──────────────── Community Servers ────────────────
+/**
+ * Look up a connected community server by its API key hash.
+ * Returns the server id if the key hash matches a 'connected' server, or undefined.
+ * Used by federation routes to authenticate bearer tokens.
+ */
+export function getConnectedServerByKeyHash(apiKeyHash: string): { id: string } | undefined {
+ return db()
+ .prepare("SELECT id FROM community_servers WHERE api_key_hash = ? AND status = 'connected'")
+ .get(apiKeyHash) as { id: string } | undefined;
+}
+
export function connectServer(id: string, name: string, url: string, apiKeyHash: string): void {
db()
.prepare(
diff --git a/src/lib/db/obsidian.ts b/src/lib/db/obsidian.ts
index da1291b230..be74db78ad 100644
--- a/src/lib/db/obsidian.ts
+++ b/src/lib/db/obsidian.ts
@@ -1,5 +1,6 @@
import { getDbInstance } from "./core";
import { getApiKeyContextSource } from "./apiKeyContextSources";
+import { encrypt, decrypt } from "./encryption";
const OBSIDIAN_NAMESPACE = "obsidian";
const OBSIDIAN_TOKEN_KEY = "api_key";
@@ -14,7 +15,11 @@ export function getObsidianToken(): string | null {
const row = db
.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
.get(OBSIDIAN_NAMESPACE, OBSIDIAN_TOKEN_KEY) as KeyValueRow | undefined;
- return typeof row?.value === "string" ? JSON.parse(row.value) : null;
+ if (typeof row?.value !== "string") return null;
+ const parsed = JSON.parse(row.value);
+ if (typeof parsed !== "string" || parsed.length === 0) return null;
+ // Graceful fallback: if decrypt fails (e.g. no key set) return as-is
+ return decrypt(parsed) ?? parsed;
} catch {
return null;
}
@@ -23,9 +28,10 @@ export function getObsidianToken(): string | null {
export function setObsidianToken(token: string): void {
try {
const db = getDbInstance();
+ const encrypted = encrypt(token) ?? token;
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"
- ).run(OBSIDIAN_NAMESPACE, OBSIDIAN_TOKEN_KEY, JSON.stringify(token));
+ ).run(OBSIDIAN_NAMESPACE, OBSIDIAN_TOKEN_KEY, JSON.stringify(encrypted));
} catch {
// Non-fatal — token still works in-memory if persistence fails.
}
@@ -168,7 +174,9 @@ export function getWebdavPassword(): string | null {
.get(OBSIDIAN_NAMESPACE, "webdav_password") as KeyValueRow | undefined;
if (typeof row?.value === "string") {
const parsed = JSON.parse(row.value);
- return typeof parsed === "string" && parsed.length > 0 ? parsed : null;
+ if (typeof parsed !== "string" || parsed.length === 0) return null;
+ // Graceful fallback: if decrypt fails return as-is (plaintext backward compat)
+ return decrypt(parsed) ?? parsed;
}
return null;
} catch {
@@ -179,9 +187,10 @@ export function getWebdavPassword(): string | null {
export function setWebdavPassword(password: string): void {
try {
const db = getDbInstance();
+ const encrypted = encrypt(password) ?? password;
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"
- ).run(OBSIDIAN_NAMESPACE, "webdav_password", JSON.stringify(password));
+ ).run(OBSIDIAN_NAMESPACE, "webdav_password", JSON.stringify(encrypted));
} catch {
// Non-fatal.
}
diff --git a/src/lib/db/providers.ts b/src/lib/db/providers.ts
index d328c41dc9..74be63c616 100644
--- a/src/lib/db/providers.ts
+++ b/src/lib/db/providers.ts
@@ -102,7 +102,7 @@ function sanitizeRateLimitOverrides(value: unknown): Record<string, number> | nu
}
// Serialize an already-sanitized map for SQLite TEXT storage.
-function serializeRateLimitOverrides(value: unknown): string | null {
+function serializeJsonField(value: unknown): string | null {
if (value === null || value === undefined) return null;
if (typeof value !== "object" || Array.isArray(value)) return null;
return JSON.stringify(value);
@@ -128,15 +128,6 @@ function sanitizeQuotaWindowThresholds(value: unknown): Record<string, number> |
return Object.keys(map).length === 0 ? null : map;
}
-// Serialize an already-sanitized map for SQLite TEXT storage. Pass `null` to
-// store a NULL column; anything else is expected to be the output of
-// sanitizeQuotaWindowThresholds above.
-function serializeQuotaWindowThresholds(value: unknown): string | null {
- if (value === null || value === undefined) return null;
- if (typeof value !== "object" || Array.isArray(value)) return null;
- return JSON.stringify(value);
-}
-
function toStringOrNull(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
@@ -476,8 +467,8 @@ function _insertConnectionRow(db: DbLike, conn: JsonRecord) {
maxConcurrent: conn.maxConcurrent ?? null,
proxyEnabled: normalizeBooleanColumn(conn.proxyEnabled, true) ? 1 : 0,
perKeyProxyEnabled: normalizeBooleanColumn(conn.perKeyProxyEnabled, false) ? 1 : 0,
- quotaWindowThresholdsJson: serializeQuotaWindowThresholds(conn.quotaWindowThresholds),
- rateLimitOverridesJson: serializeRateLimitOverrides(conn.rateLimitOverrides),
+ quotaWindowThresholdsJson: serializeJsonField(conn.quotaWindowThresholds),
+ rateLimitOverridesJson: serializeJsonField(conn.rateLimitOverrides),
createdAt: conn.createdAt,
updatedAt: conn.updatedAt,
});
@@ -552,10 +543,10 @@ function _updateConnectionRow(db: DbLike, id: string, data: JsonRecord) {
lastUsedAt: data.lastUsedAt || null,
group: data.group || null,
maxConcurrent: data.maxConcurrent ?? null,
- quotaWindowThresholdsJson: serializeQuotaWindowThresholds(data.quotaWindowThresholds),
+ quotaWindowThresholdsJson: serializeJsonField(data.quotaWindowThresholds),
proxyEnabled: normalizeBooleanColumn(data.proxyEnabled, true) ? 1 : 0,
perKeyProxyEnabled: normalizeBooleanColumn(data.perKeyProxyEnabled, false) ? 1 : 0,
- rateLimitOverridesJson: serializeRateLimitOverrides(data.rateLimitOverrides),
+ rateLimitOverridesJson: serializeJsonField(data.rateLimitOverrides),
updatedAt: now,
});
}
@@ -972,6 +963,72 @@ export function getEffectiveQuotaUsage(
return used;
}
+/**
+ * T05: Startup crash-recovery — clear stale transient connection cooldowns.
+ *
+ * After an unclean crash (SIGKILL, OOM-kill, large-body burst) the normal
+ * error-handler paths that would clear/normalise cooldowns never run.
+ * A connection's `rate_limited_until` may have been pushed far into the
+ * future by exponential back-off. On next startup that leaves all affected
+ * connections excluded by `getProviderCredentials()`, so every request sits
+ * in the Bottleneck queue and times out at `maxWaitMs` (120 s default).
+ *
+ * Safe invariants:
+ * - Only connections with `rate_limited_until IS NOT NULL` are touched.
+ * - Terminal states (`banned`, `expired`, `credits_exhausted`) are skipped —
+ * those require a deliberate credential change or operator reset.
+ * - Past timestamps are also cleared: they are already expired in the lazy
+ * expiry sense, but clearing them resets `backoffLevel` / transient error
+ * fields so the connection gets a clean slate on this fresh process.
+ *
+ * Must be called once, early in the startup sequence, before any request
+ * is handled. Returns the number of connections that were cleared.
+ */
+export function clearStaleCrashCooldowns(): { cleared: number } {
+ const db = getDbInstance() as unknown as DbLike;
+ const now = new Date().toISOString();
+
+ // Fetch all connections that have a rate_limited_until set and are NOT in
+ // a terminal state. We do the terminal-status filter in JS to reuse the
+ // canonical `TERMINAL_STATUSES` set rather than duplicating the list in SQL.
+ const TERMINAL_STATUSES = new Set(["banned", "expired", "credits_exhausted"]);
+
+ const rows = db
+ .prepare(
+ `SELECT id, test_status FROM provider_connections WHERE rate_limited_until IS NOT NULL`
+ )
+ .all() as Array<{ id: string; test_status: string | null }>;
+
+ const toReset = rows.filter((r) => {
+ const status = (r.test_status || "").trim().toLowerCase();
+ return !TERMINAL_STATUSES.has(status);
+ });
+
+ if (toReset.length === 0) return { cleared: 0 };
+
+ const stmt = db.prepare(
+ `UPDATE provider_connections SET
+ rate_limited_until = NULL,
+ test_status = 'active',
+ backoff_level = 0,
+ last_error = NULL,
+ last_error_at = NULL,
+ last_error_type = NULL,
+ last_error_source = NULL,
+ error_code = NULL,
+ updated_at = ?
+ WHERE id = ?`
+ );
+
+ for (const row of toReset) {
+ stmt.run(now, row.id);
+ }
+
+ invalidateDbCache("connections");
+
+ return { cleared: toReset.length };
+}
+
/**
* T13: Format a reset countdown as a human-readable string: "2h 35m" or "4m 30s".
* Returns null if resetAt is in the past or not set.
diff --git a/src/lib/db/proxyLogs.ts b/src/lib/db/proxyLogs.ts
new file mode 100644
index 0000000000..033945d9d2
--- /dev/null
+++ b/src/lib/db/proxyLogs.ts
@@ -0,0 +1,35 @@
+/**
+ * db/proxyLogs.ts — Read queries over the `proxy_logs` table.
+ * Extracted from the /api/logs/export route handler.
+ *
+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the
+ * /api/logs/export route can delegate.
+ *
+ * NOTE: The SELECT * intentionally returns the historical `public_ip` column,
+ * NOT `clientIp`. This differs from GET /api/usage/proxy-logs which exposes
+ * the value as `clientIp`. Callers of the export endpoint should read
+ * `public_ip`. This inconsistency will be resolved in a future DB migration
+ * (#2880).
+ *
+ * Sliced out of #3500 (proxy_logs cluster, slice 4).
+ */
+
+import { getDbInstance } from "./core";
+
+// ---------------------------------------------------------------------------
+// Queries
+// ---------------------------------------------------------------------------
+
+/**
+ * Returns all proxy_logs rows with timestamp >= `since`, ordered by timestamp
+ * descending (most recent first).
+ *
+ * @param since - ISO-8601 timestamp lower bound, e.g. "2024-01-01T00:00:00.000Z".
+ */
+export function exportProxyLogsSince(since: string): Record<string, unknown>[] {
+ const db = getDbInstance();
+ const stmt = db.prepare(
+ "SELECT * FROM proxy_logs WHERE timestamp >= @since ORDER BY timestamp DESC"
+ );
+ return stmt.all({ since }) as Record<string, unknown>[];
+}
diff --git a/src/lib/db/semanticCache.ts b/src/lib/db/semanticCache.ts
new file mode 100644
index 0000000000..5b3d38664e
--- /dev/null
+++ b/src/lib/db/semanticCache.ts
@@ -0,0 +1,117 @@
+/**
+ * db/semanticCache.ts — CRUD queries over the `semantic_cache` table.
+ * Extracted from the /api/cache/entries route handler.
+ *
+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the
+ * /api/cache/entries route can delegate.
+ *
+ * Sliced out of #3500 (semantic_cache cluster, slice 4).
+ */
+
+import { getDbInstance } from "./core";
+
+// ---------------------------------------------------------------------------
+// Shared types
+// ---------------------------------------------------------------------------
+
+export interface SemanticCacheEntry {
+ id: string;
+ signature: string;
+ model: string;
+ hit_count: number;
+ tokens_saved: number;
+ created_at: string;
+ expires_at: string;
+}
+
+export interface SemanticCacheListOptions {
+ page: number;
+ limit: number;
+ search: string;
+ model: string;
+ sortBy: string;
+ sortOrder: string;
+}
+
+export interface SemanticCacheListResult {
+ entries: SemanticCacheEntry[];
+ total: number;
+}
+
+// ---------------------------------------------------------------------------
+// Queries
+// ---------------------------------------------------------------------------
+
+const VALID_SORT_COLUMNS = ["created_at", "expires_at", "hit_count", "tokens_saved", "model"];
+
+/**
+ * Returns a paginated, filtered, sorted list of semantic cache entries.
+ * All dynamic inputs (sortBy/sortOrder) are validated before use.
+ */
+export function listSemanticCacheEntries(opts: SemanticCacheListOptions): SemanticCacheListResult {
+ const db = getDbInstance();
+ const { page, limit, search, model, sortBy, sortOrder } = opts;
+ const offset = (page - 1) * limit;
+
+ const conditions: string[] = [];
+ const params: unknown[] = [];
+
+ if (search) {
+ conditions.push("(signature LIKE ? OR model LIKE ?)");
+ params.push(`%${search}%`, `%${search}%`);
+ }
+
+ if (model) {
+ conditions.push("model = ?");
+ params.push(model);
+ }
+
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
+ const orderBy = VALID_SORT_COLUMNS.includes(sortBy) ? sortBy : "created_at";
+ const order = sortOrder === "asc" ? "ASC" : "DESC";
+
+ const countRow = db
+ .prepare(`SELECT COUNT(*) as total FROM semantic_cache ${whereClause}`)
+ .get(...params) as { total: number };
+
+ const entries = db
+ .prepare(
+ `SELECT id, signature, model, hit_count, tokens_saved, created_at, expires_at
+ FROM semantic_cache ${whereClause}
+ ORDER BY ${orderBy} ${order}
+ LIMIT ? OFFSET ?`
+ )
+ .all(...params, limit, offset) as SemanticCacheEntry[];
+
+ return { entries, total: countRow?.total || 0 };
+}
+
+export interface DeleteSemanticCacheBySignatureResult {
+ deleted: number;
+}
+
+/**
+ * Deletes the single semantic cache entry matching the given signature.
+ * Returns `{ deleted: 1 }` on success.
+ */
+export function deleteSemanticCacheBySignature(
+ signature: string
+): DeleteSemanticCacheBySignatureResult {
+ const db = getDbInstance();
+ db.prepare("DELETE FROM semantic_cache WHERE signature = ?").run(signature);
+ return { deleted: 1 };
+}
+
+export interface DeleteSemanticCacheByModelResult {
+ deleted: number;
+}
+
+/**
+ * Deletes all semantic cache entries for the given model.
+ * Returns `{ deleted: N }` where N is the number of rows removed.
+ */
+export function deleteSemanticCacheByModel(model: string): DeleteSemanticCacheByModelResult {
+ const db = getDbInstance();
+ const result = db.prepare("DELETE FROM semantic_cache WHERE model = ?").run(model);
+ return { deleted: result.changes };
+}
diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.ts
index c9ec88c002..6df1b6b23a 100644
--- a/src/lib/db/settings.ts
+++ b/src/lib/db/settings.ts
@@ -31,6 +31,10 @@ type ProxyResolutionCacheEntry = {
const PROXY_RESOLUTION_CACHE_MAX_ENTRIES = 100;
+function isTruthyEnvFlag(value: string | undefined): boolean {
+ return typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim());
+}
+
let proxyConfigGeneration = 0;
const proxyResolutionCache = new Map<string, ProxyResolutionCacheEntry>();
@@ -100,6 +104,9 @@ export async function getSettings() {
hideEndpointCloudflaredTunnel: false,
hideEndpointTailscaleFunnel: false,
hideEndpointNgrokTunnel: false,
+ preferClaudeCodeForUnprefixedClaudeModels: isTruthyEnvFlag(
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS
+ ),
autoRefreshProviderQuota: false,
autoRefreshProviderQuotaInterval: 180,
comboConfigMode: "guided",
diff --git a/src/lib/db/skills.ts b/src/lib/db/skills.ts
new file mode 100644
index 0000000000..b7e5e10345
--- /dev/null
+++ b/src/lib/db/skills.ts
@@ -0,0 +1,62 @@
+/**
+ * db/skills.ts — Database operations for the skills table.
+ *
+ * Encapsulates all SQL for the `skills` and `skill_executions` tables so that
+ * route handlers never contain raw SQL (Hard Rule #5).
+ */
+
+import { getDbInstance } from "./core";
+
+// ──────────────── Allowed patch columns ────────────────
+//
+// updateSkill builds a SET clause dynamically. To prevent SQL injection the
+// column names are validated against this allowlist of known, writable columns.
+// Any key in the patch that is NOT in this set is silently ignored.
+const UPDATABLE_COLUMNS = new Set<string>([
+ "enabled",
+ "mode",
+ "updated_at",
+ // future-safe: add writable columns here as schema grows
+]);
+
+export interface SkillPatch {
+ enabled?: number | boolean;
+ mode?: string;
+}
+
+/**
+ * Update a skill row with a parameterized, injection-safe dynamic SET clause.
+ *
+ * @param id - Row ID of the skill to update.
+ * @param patch - Plain-object of column→value pairs to apply.
+ * Only columns present in UPDATABLE_COLUMNS are touched;
+ * unknown keys are silently ignored.
+ *
+ * The function always appends `updated_at = datetime('now')` so the record's
+ * timestamp reflects the mutation.
+ *
+ * @returns number of rows changed (0 if skill not found, 1 if updated).
+ */
+export function updateSkill(id: string, patch: SkillPatch): number {
+ const db = getDbInstance();
+
+ const setClauses: string[] = [];
+ const params: unknown[] = [];
+
+ for (const [key, value] of Object.entries(patch)) {
+ if (!UPDATABLE_COLUMNS.has(key)) continue; // allowlist guard
+ setClauses.push(`${key} = ?`);
+ params.push(value);
+ }
+
+ if (setClauses.length === 0) {
+ // Nothing to update (all keys were filtered out).
+ return 0;
+ }
+
+ setClauses.push("updated_at = datetime('now')");
+ params.push(id);
+
+ const result = db.prepare(`UPDATE skills SET ${setClauses.join(", ")} WHERE id = ?`).run(...params);
+ return (result as { changes: number }).changes;
+}
diff --git a/src/lib/db/usageAnalytics.ts b/src/lib/db/usageAnalytics.ts
new file mode 100644
index 0000000000..e85b698967
--- /dev/null
+++ b/src/lib/db/usageAnalytics.ts
@@ -0,0 +1,872 @@
+/**
+ * db/usageAnalytics.ts — Read-only aggregation queries over `usage_history`
+ * and `daily_usage_summary` extracted from route handlers.
+ *
+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the
+ * /api/usage/analytics and /api/settings/export-json routes can delegate.
+ * Read-only aggregation; no writes.
+ *
+ * Sliced out of #3500 (usage_history / daily_usage_summary cluster).
+ */
+
+import { getDbInstance } from "./core";
+
+// ---------------------------------------------------------------------------
+// Shared parameter types
+// ---------------------------------------------------------------------------
+
+/**
+ * Named-param bag used by analytics queries.
+ * Values are always strings because better-sqlite3 named params are strings.
+ */
+export type AnalyticsParams = Record<string, string>;
+
+// ---------------------------------------------------------------------------
+// Unified source CTE builder
+// ---------------------------------------------------------------------------
+
+export interface BuildUnifiedSourceOptions {
+ /** ISO-8601 timestamp lower bound (e.g. "2024-01-01T00:00:00.000Z"). Null = all time. */
+ sinceIso: string | null;
+ /** ISO-8601 timestamp upper bound. Null = no upper bound. */
+ untilIso: string | null;
+ /** YYYY-MM-DD date string: rows older than this have been rolled up to daily_usage_summary. */
+ rawCutoffDate: string;
+ /**
+ * SQL condition fragment for API-key filtering, e.g.
+ * "(api_key_name IN (@apiKey0) OR api_key_id IN (@apiKey0))".
+ * Empty string = no API-key filter.
+ */
+ apiKeyWhere: string;
+ /** Named-param entries for the apiKey placeholders (apiKey0, apiKey1, …). */
+ apiKeyParams: AnalyticsParams;
+}
+
+export interface UnifiedSourceResult {
+ /** Pre-built subquery SQL string (parenthesised, suitable for `FROM <unifiedSource> AS _u`). */
+ unifiedSource: string;
+ /** Named params that must be passed to every query that uses `unifiedSource`. */
+ unifiedParams: AnalyticsParams;
+}
+
+/**
+ * Builds the UNION subquery that merges recent `usage_history` rows with
+ * older `daily_usage_summary` aggregates, preventing double-counting and
+ * preventing api_key leakage from summary rows.
+ *
+ * The returned `unifiedSource` is a parenthesised subquery suitable for use
+ * as `FROM ${unifiedSource} AS _u`. All WHERE filters are embedded inside
+ * the subquery — no additional outer WHERE is needed.
+ */
+export function buildUnifiedSource(opts: BuildUnifiedSourceOptions): UnifiedSourceResult {
+ const { sinceIso, untilIso, rawCutoffDate, apiKeyWhere, apiKeyParams } = opts;
+
+ // daily_usage_summary rows are included only when the query window extends
+ // before rawCutoffDate AND no api_key filter is active (summary rows don't
+ // carry api_key/connection, so including them under a key filter leaks usage).
+ const needsAggregated = (!sinceIso || sinceIso < rawCutoffDate) && !apiKeyWhere;
+
+ const unifiedParams: AnalyticsParams = {};
+
+ // Raw leg lower bound: when agg rows are also included, floor at rawCutoffDate
+ // so the two legs never overlap (prevents double-counting).
+ const rawConditions: string[] = [];
+ if (needsAggregated) {
+ rawConditions.push("timestamp >= @rawCutoff");
+ unifiedParams.rawCutoff = rawCutoffDate;
+ } else if (sinceIso) {
+ rawConditions.push("timestamp >= @since");
+ unifiedParams.since = sinceIso;
+ }
+ if (untilIso) {
+ rawConditions.push("timestamp <= @until");
+ unifiedParams.until = untilIso;
+ }
+ if (apiKeyWhere) {
+ rawConditions.push(apiKeyWhere);
+ Object.assign(unifiedParams, apiKeyParams);
+ }
+ const rawWhere = rawConditions.length > 0 ? `WHERE ${rawConditions.join(" AND ")}` : "";
+
+ // Aggregated leg: bounded strictly before rawCutoffDate so it never overlaps raw.
+ const aggConditions: string[] = [];
+ if (needsAggregated) {
+ if (sinceIso) {
+ aggConditions.push("date >= @sinceDate");
+ unifiedParams.sinceDate = sinceIso.split("T")[0];
+ }
+ if (untilIso) {
+ aggConditions.push("date <= @untilDate");
+ unifiedParams.untilDate = untilIso.split("T")[0];
+ }
+ aggConditions.push("date < @rawCutoffDate");
+ unifiedParams.rawCutoffDate = rawCutoffDate;
+ }
+ const aggWhere = aggConditions.length > 0 ? `WHERE ${aggConditions.join(" AND ")}` : "";
+
+ const unifiedSource = needsAggregated
+ ? `(
+ SELECT
+ timestamp,
+ provider,
+ model,
+ tokens_input,
+ tokens_output,
+ tokens_cache_read,
+ tokens_cache_creation,
+ tokens_reasoning,
+ service_tier,
+ success,
+ latency_ms,
+ connection_id,
+ api_key_id,
+ api_key_name
+ FROM usage_history
+ ${rawWhere}
+ UNION ALL
+ SELECT
+ date || 'T12:00:00.000Z' as timestamp,
+ provider,
+ model,
+ total_input_tokens as tokens_input,
+ total_output_tokens as tokens_output,
+ 0 as tokens_cache_read,
+ 0 as tokens_cache_creation,
+ 0 as tokens_reasoning,
+ 'standard' as service_tier,
+ 1 as success,
+ 0 as latency_ms,
+ NULL as connection_id,
+ NULL as api_key_id,
+ NULL as api_key_name
+ FROM daily_usage_summary
+ ${aggWhere}
+ )`
+ : `(SELECT
+ timestamp, provider, model,
+ tokens_input, tokens_output,
+ tokens_cache_read, tokens_cache_creation, tokens_reasoning,
+ service_tier, success, latency_ms,
+ connection_id, api_key_id, api_key_name
+ FROM usage_history
+ ${rawWhere}
+ )`;
+
+ return { unifiedSource, unifiedParams };
+}
+
+/**
+ * Builds the UNION subquery for preset cost calculations (narrower column set
+ * than the main analytics query — no connection_id / api_key columns needed).
+ */
+export function buildPresetUnifiedSource(opts: BuildUnifiedSourceOptions): UnifiedSourceResult {
+ const { sinceIso, untilIso, rawCutoffDate, apiKeyWhere, apiKeyParams } = opts;
+
+ const needsAggregated = (!sinceIso || sinceIso < rawCutoffDate) && !apiKeyWhere;
+
+ const presetParams: AnalyticsParams = {};
+
+ const rawConditions: string[] = [];
+ if (needsAggregated) {
+ rawConditions.push("timestamp >= @presetRawCutoff");
+ presetParams.presetRawCutoff = rawCutoffDate;
+ } else if (sinceIso) {
+ rawConditions.push("timestamp >= @presetSince");
+ presetParams.presetSince = sinceIso;
+ }
+ if (apiKeyWhere) {
+ rawConditions.push(apiKeyWhere);
+ Object.assign(presetParams, apiKeyParams);
+ }
+ const presetRawWhere =
+ rawConditions.length > 0 ? `WHERE ${rawConditions.join(" AND ")}` : "";
+
+ const aggConditions: string[] = [];
+ if (needsAggregated) {
+ if (sinceIso) {
+ aggConditions.push("date >= @presetSinceDate");
+ presetParams.presetSinceDate = sinceIso.split("T")[0];
+ }
+ aggConditions.push("date < @presetRawCutoffDate");
+ presetParams.presetRawCutoffDate = rawCutoffDate;
+ }
+ const presetAggWhere =
+ aggConditions.length > 0 ? `WHERE ${aggConditions.join(" AND ")}` : "";
+
+ const unifiedSource = needsAggregated
+ ? `(
+ SELECT timestamp, provider, model, service_tier,
+ tokens_input, tokens_output,
+ tokens_cache_read, tokens_cache_creation, tokens_reasoning
+ FROM usage_history
+ ${presetRawWhere}
+ UNION ALL
+ SELECT
+ date || 'T12:00:00.000Z' as timestamp,
+ provider, model,
+ 'standard' as service_tier,
+ total_input_tokens as tokens_input,
+ total_output_tokens as tokens_output,
+ 0 as tokens_cache_read,
+ 0 as tokens_cache_creation,
+ 0 as tokens_reasoning
+ FROM daily_usage_summary
+ ${presetAggWhere}
+ )`
+ : `(SELECT timestamp, provider, model, service_tier,
+ tokens_input, tokens_output,
+ tokens_cache_read, tokens_cache_creation, tokens_reasoning
+ FROM usage_history
+ ${presetRawWhere}
+ )`;
+
+ return { unifiedSource, unifiedParams: presetParams };
+}
+
+// ---------------------------------------------------------------------------
+// Analytics summary — /api/usage/analytics
+// ---------------------------------------------------------------------------
+
+export interface UsageSummaryRow {
+ totalRequests: number;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ uniqueModels: number;
+ uniqueAccounts: number;
+ uniqueApiKeys: number;
+ successfulRequests: number;
+ avgLatencyMs: number;
+ firstRequest: string;
+ lastRequest: string;
+}
+
+/**
+ * Scalar summary over the unified source CTE.
+ *
+ * @param unifiedSource - Pre-built subquery string (UNION of raw + aggregated rows).
+ * @param params - Named params referenced inside `unifiedSource`.
+ */
+export function getUsageSummary(
+ unifiedSource: string,
+ params: AnalyticsParams
+): UsageSummaryRow {
+ const db = getDbInstance();
+ const row = db
+ .prepare(
+ `
+ SELECT
+ COUNT(*) as totalRequests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
+ COUNT(DISTINCT model) as uniqueModels,
+ COUNT(DISTINCT connection_id) as uniqueAccounts,
+ COUNT(DISTINCT COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''))) as uniqueApiKeys,
+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
+ COALESCE(MIN(timestamp), '') as firstRequest,
+ COALESCE(MAX(timestamp), '') as lastRequest
+ FROM ${unifiedSource} AS _u
+ `
+ )
+ .get(params) as UsageSummaryRow | undefined;
+ return (
+ row ?? {
+ totalRequests: 0,
+ promptTokens: 0,
+ completionTokens: 0,
+ totalTokens: 0,
+ uniqueModels: 0,
+ uniqueAccounts: 0,
+ uniqueApiKeys: 0,
+ successfulRequests: 0,
+ avgLatencyMs: 0,
+ firstRequest: "",
+ lastRequest: "",
+ }
+ );
+}
+
+// ---------------------------------------------------------------------------
+
+export interface DailyUsageRow {
+ date: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+}
+
+/**
+ * Daily request + token counts aggregated from the unified source CTE.
+ */
+export function getDailyUsage(
+ unifiedSource: string,
+ params: AnalyticsParams
+): DailyUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ DATE(timestamp) as date,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
+ FROM ${unifiedSource} AS _u
+ GROUP BY DATE(timestamp)
+ ORDER BY date ASC
+ `
+ )
+ .all(params) as DailyUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface DailyCostRow {
+ date: string;
+ provider: string;
+ model: string;
+ serviceTier: string;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+}
+
+/**
+ * Per-day, per-provider, per-model token breakdown for cost calculation.
+ */
+export function getDailyCostRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): DailyCostRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ DATE(timestamp) as date,
+ LOWER(provider) as provider,
+ LOWER(model) as model,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
+ FROM ${unifiedSource} AS _u
+ GROUP BY DATE(timestamp), LOWER(provider), LOWER(model), serviceTier
+ ORDER BY date ASC
+ `
+ )
+ .all(params) as DailyCostRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface HeatmapRow {
+ date: string;
+ totalTokens: number;
+}
+
+/**
+ * Per-day token totals for the activity heatmap.
+ * Uses `usage_history` directly (not the unified CTE) since the heatmap has its
+ * own independent time window and api_key filter.
+ *
+ * @param heatmapConditions - Array of SQL condition strings (combined with AND).
+ * @param params - Named params referenced inside the conditions.
+ */
+export function getHeatmapRows(
+ heatmapConditions: string[],
+ params: AnalyticsParams
+): HeatmapRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ DATE(timestamp) as date,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
+ FROM usage_history
+ WHERE ${heatmapConditions.join(" AND ")}
+ GROUP BY DATE(timestamp)
+ ORDER BY date ASC
+ `
+ )
+ .all(params) as HeatmapRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ModelUsageRow {
+ model: string;
+ provider: string;
+ serviceTier: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+ totalTokens: number;
+ avgLatencyMs: number;
+ successfulRequests: number;
+ lastUsed: string;
+}
+
+/**
+ * Per-model usage aggregates from the unified source CTE.
+ */
+export function getModelUsageRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): ModelUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ LOWER(model) as model,
+ LOWER(provider) as provider,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
+ COALESCE(MAX(timestamp), '') as lastUsed
+ FROM ${unifiedSource} AS _u
+ GROUP BY LOWER(model), LOWER(provider), serviceTier
+ ORDER BY requests DESC
+ `
+ )
+ .all(params) as ModelUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ProviderCostRow {
+ provider: string;
+ model: string;
+ serviceTier: string;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+}
+
+/**
+ * Per-provider, per-model token breakdown for provider cost calculation.
+ */
+export function getProviderCostRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): ProviderCostRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ LOWER(provider) as provider,
+ LOWER(model) as model,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
+ FROM ${unifiedSource} AS _u
+ GROUP BY LOWER(provider), LOWER(model), serviceTier
+ `
+ )
+ .all(params) as ProviderCostRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ProviderUsageRow {
+ provider: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ avgLatencyMs: number;
+ successfulRequests: number;
+}
+
+/**
+ * Per-provider usage aggregates from the unified source CTE.
+ */
+export function getProviderUsageRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): ProviderUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ LOWER(provider) as provider,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
+ COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
+ COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests
+ FROM ${unifiedSource} AS _u
+ GROUP BY LOWER(provider)
+ ORDER BY requests DESC
+ `
+ )
+ .all(params) as ProviderUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface AccountCostRow {
+ account: string;
+ provider: string;
+ model: string;
+ serviceTier: string;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+}
+
+/**
+ * Per-account cost breakdown joined with provider_connections for display names.
+ * Uses `usage_history` directly (JOIN requires real table, not a subquery alias).
+ *
+ * @param whereClause - SQL WHERE clause (may be empty string); column refs already
+ * prefixed with `usage_history.` by the caller.
+ * @param params - Named params referenced inside `whereClause`.
+ */
+export function getAccountCostRows(
+ whereClause: string,
+ params: AnalyticsParams
+): AccountCostRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,
+ LOWER(usage_history.provider) as provider,
+ LOWER(usage_history.model) as model,
+ COALESCE(NULLIF(usage_history.service_tier, ''), 'standard') as serviceTier,
+ COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,
+ COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,
+ COALESCE(SUM(usage_history.tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(usage_history.tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(usage_history.tokens_reasoning), 0) as reasoningTokens
+ FROM usage_history
+ LEFT JOIN provider_connections c ON c.id = usage_history.connection_id
+ ${whereClause}
+ GROUP BY account, LOWER(usage_history.provider), LOWER(usage_history.model), serviceTier
+ `
+ )
+ .all(params) as AccountCostRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface AccountUsageRow {
+ account: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ avgLatencyMs: number;
+ lastUsed: string;
+}
+
+/**
+ * Per-account usage aggregates joined with provider_connections for display names.
+ *
+ * @param whereClause - SQL WHERE clause (may be empty string); column refs already
+ * prefixed with `usage_history.` by the caller.
+ * @param params - Named params referenced inside `whereClause`.
+ */
+export function getAccountUsageRows(
+ whereClause: string,
+ params: AnalyticsParams
+): AccountUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,
+ COUNT(usage_history.id) as requests,
+ COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,
+ COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,
+ COALESCE(SUM(usage_history.tokens_input + usage_history.tokens_output), 0) as totalTokens,
+ COALESCE(AVG(usage_history.latency_ms), 0) as avgLatencyMs,
+ COALESCE(MAX(usage_history.timestamp), '') as lastUsed
+ FROM usage_history
+ LEFT JOIN provider_connections c ON c.id = usage_history.connection_id
+ ${whereClause}
+ GROUP BY account
+ ORDER BY requests DESC
+ LIMIT 50
+ `
+ )
+ .all(params) as AccountUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ApiKeyUsageRow {
+ apiKeyId: string | null;
+ apiKeyGroupKey: string;
+ provider: string;
+ model: string;
+ serviceTier: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+ totalTokens: number;
+}
+
+/**
+ * Per-API-key usage aggregates from usage_history.
+ *
+ * @param apiKeyWhereClause - Full WHERE clause including api_key presence guard.
+ * @param params - Named params referenced inside `apiKeyWhereClause`.
+ */
+export function getApiKeyUsageRows(
+ apiKeyWhereClause: string,
+ params: AnalyticsParams
+): ApiKeyUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ NULLIF(api_key_id, '') as apiKeyId,
+ COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown') as apiKeyGroupKey,
+ LOWER(provider) as provider,
+ LOWER(model) as model,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
+ FROM usage_history
+ ${apiKeyWhereClause}
+ GROUP BY COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown'), NULLIF(api_key_id, ''), LOWER(provider), LOWER(model), serviceTier
+ `
+ )
+ .all(params) as ApiKeyUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ServiceTierUsageRow {
+ serviceTier: string;
+ provider: string;
+ model: string;
+ requests: number;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+ totalTokens: number;
+}
+
+/**
+ * Per-service-tier, per-provider, per-model usage aggregates.
+ */
+export function getServiceTierUsageRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): ServiceTierUsageRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ LOWER(provider) as provider,
+ LOWER(model) as model,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
+ FROM ${unifiedSource} AS _u
+ GROUP BY serviceTier, LOWER(provider), LOWER(model)
+ `
+ )
+ .all(params) as ServiceTierUsageRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface ApiKeyMetadataRow {
+ apiKeyId: string | null;
+ apiKeyName: string | null;
+ apiKeyGroupKey: string;
+ lastUsed: string;
+}
+
+/**
+ * Latest API key name + group key from usage_history for display metadata.
+ *
+ * @param apiKeyWhereClause - Full WHERE clause including api_key presence guard.
+ * @param params - Named params referenced inside `apiKeyWhereClause`.
+ */
+export function getApiKeyMetadataRows(
+ apiKeyWhereClause: string,
+ params: AnalyticsParams
+): ApiKeyMetadataRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ NULLIF(api_key_id, '') as apiKeyId,
+ NULLIF(api_key_name, '') as apiKeyName,
+ COALESCE(NULLIF(api_key_id, ''), NULLIF(api_key_name, ''), 'unknown') as apiKeyGroupKey,
+ MAX(timestamp) as lastUsed
+ FROM usage_history
+ ${apiKeyWhereClause}
+ GROUP BY NULLIF(api_key_id, ''), NULLIF(api_key_name, '')
+ ORDER BY lastUsed DESC
+ `
+ )
+ .all(params) as ApiKeyMetadataRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface WeeklyPatternRow {
+ dayOfWeek: string;
+ days: number;
+ requests: number;
+ totalTokens: number;
+}
+
+/**
+ * Day-of-week aggregates for the weekly activity pattern chart.
+ */
+export function getWeeklyPatternRows(
+ unifiedSource: string,
+ params: AnalyticsParams
+): WeeklyPatternRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ dayOfWeek,
+ COUNT(*) as days,
+ COALESCE(SUM(requests), 0) as requests,
+ COALESCE(SUM(totalTokens), 0) as totalTokens
+ FROM (
+ SELECT
+ DATE(timestamp) as date,
+ strftime('%w', timestamp) as dayOfWeek,
+ COUNT(*) as requests,
+ COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
+ FROM ${unifiedSource} AS _u
+ GROUP BY DATE(timestamp), strftime('%w', timestamp)
+ )
+ GROUP BY dayOfWeek
+ ORDER BY dayOfWeek ASC
+ `
+ )
+ .all(params) as WeeklyPatternRow[];
+}
+
+// ---------------------------------------------------------------------------
+
+export interface PresetCostModelRow {
+ model: string;
+ provider: string;
+ serviceTier: string;
+ promptTokens: number;
+ completionTokens: number;
+ cacheReadTokens: number;
+ cacheCreationTokens: number;
+ reasoningTokens: number;
+}
+
+/**
+ * Per-model token breakdown for preset range cost calculation.
+ * Uses a preset-specific unified source (may differ from the main query window).
+ */
+export function getPresetCostModelRows(
+ presetUnifiedSource: string,
+ params: AnalyticsParams
+): PresetCostModelRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ LOWER(model) as model,
+ LOWER(provider) as provider,
+ COALESCE(NULLIF(service_tier, ''), 'standard') as serviceTier,
+ COALESCE(SUM(tokens_input), 0) as promptTokens,
+ COALESCE(SUM(tokens_output), 0) as completionTokens,
+ COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
+ COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
+ COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
+ FROM ${presetUnifiedSource} AS _pu
+ GROUP BY LOWER(model), LOWER(provider), serviceTier
+ `
+ )
+ .all(params) as PresetCostModelRow[];
+}
+
+// ---------------------------------------------------------------------------
+// Export-JSON backup — /api/settings/export-json
+// ---------------------------------------------------------------------------
+
+/**
+ * Returns all rows from `usage_history` for backup export.
+ * Only called when `?includeHistory=true` is explicitly requested.
+ */
+export function getAllUsageHistory(): Record<string, unknown>[] {
+ const db = getDbInstance();
+ return db.prepare("SELECT * FROM usage_history").all() as Record<string, unknown>[];
+}
+
+/**
+ * Returns all rows from `domain_cost_history` for backup export.
+ */
+export function getAllDomainCostHistory(): Record<string, unknown>[] {
+ const db = getDbInstance();
+ return db.prepare("SELECT * FROM domain_cost_history").all() as Record<string, unknown>[];
+}
+
+/**
+ * Returns all rows from `domain_budgets` for backup export.
+ */
+export function getAllDomainBudgets(): Record<string, unknown>[] {
+ const db = getDbInstance();
+ return db.prepare("SELECT * FROM domain_budgets").all() as Record<string, unknown>[];
+}
diff --git a/src/lib/db/usageLogs.ts b/src/lib/db/usageLogs.ts
new file mode 100644
index 0000000000..7549f93880
--- /dev/null
+++ b/src/lib/db/usageLogs.ts
@@ -0,0 +1,94 @@
+/**
+ * db/usageLogs.ts — Read-only aggregation queries over `usage_logs`
+ * extracted from the /api/analytics/auto-routing route handler.
+ *
+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the
+ * /api/analytics/auto-routing route can delegate.
+ *
+ * Sliced out of #3500 (usage_logs cluster, slice 4).
+ */
+
+import { getDbInstance } from "./core";
+
+// ---------------------------------------------------------------------------
+// Auto-routing analytics
+// ---------------------------------------------------------------------------
+
+export interface AutoRoutingTotalResult {
+ count: number;
+}
+
+/**
+ * Returns the total number of requests routed through auto/ prefix models.
+ * Matches model = 'auto' OR model LIKE 'auto/%'.
+ */
+export function getAutoRoutingTotalCount(): AutoRoutingTotalResult {
+ const db = getDbInstance();
+ const row = db
+ .prepare(
+ `
+ SELECT COUNT(*) as count
+ FROM usage_logs
+ WHERE model = 'auto' OR model LIKE 'auto/%'
+ `
+ )
+ .get() as AutoRoutingTotalResult | undefined;
+ return row ?? { count: 0 };
+}
+
+export interface AutoRoutingVariantRow {
+ variant: string;
+ count: number;
+}
+
+/**
+ * Returns per-variant request counts for auto/ prefix models.
+ * Variant is derived from the model name:
+ * 'auto' → 'default'
+ * 'auto/X' → 'X'
+ * other → 'other' (should not occur given the WHERE clause)
+ */
+export function getAutoRoutingVariantBreakdown(): AutoRoutingVariantRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT
+ CASE
+ WHEN model = 'auto' THEN 'default'
+ WHEN model LIKE 'auto/%' THEN SUBSTR(model, 6)
+ ELSE 'other'
+ END as variant,
+ COUNT(*) as count
+ FROM usage_logs
+ WHERE model = 'auto' OR model LIKE 'auto/%'
+ GROUP BY variant
+ ORDER BY count DESC
+ `
+ )
+ .all() as AutoRoutingVariantRow[];
+}
+
+export interface AutoRoutingTopProviderRow {
+ provider: string;
+ count: number;
+}
+
+/**
+ * Returns the top 10 providers used for auto/ prefix model requests.
+ */
+export function getAutoRoutingTopProviders(): AutoRoutingTopProviderRow[] {
+ const db = getDbInstance();
+ return db
+ .prepare(
+ `
+ SELECT provider, COUNT(*) as count
+ FROM usage_logs
+ WHERE model = 'auto' OR model LIKE 'auto/%'
+ GROUP BY provider
+ ORDER BY count DESC
+ LIMIT 10
+ `
+ )
+ .all() as AutoRoutingTopProviderRow[];
+}
diff --git a/src/lib/localDb.ts b/src/lib/localDb.ts
index 1c620b5ef5..ff428ae949 100755
--- a/src/lib/localDb.ts
+++ b/src/lib/localDb.ts
@@ -30,6 +30,9 @@ export {
isConnectionRateLimited,
getRateLimitedConnections,
+ // T05 startup recovery: clear stale transient cooldowns left by a prior crash
+ clearStaleCrashCooldowns,
+
// T13: Stale quota display fix (zero out usage after window resets)
getEffectiveQuotaUsage,
formatResetCountdown,
@@ -200,8 +203,21 @@ export {
getDbBackupRetentionDays,
listDbBackups,
restoreDbBackup,
+ // Export-All / Import helpers (#3500 slice 5)
+ exportAllSummaryRows,
+ getTableNamesFromAdapter,
+ countImportedRows,
} from "./db/backup";
+export type { ExportAllRows } from "./db/backup";
+
+export {
+ // Skills DB operations (#3500 slice 5)
+ updateSkill,
+} from "./db/skills";
+
+export type { SkillPatch } from "./db/skills";
+
export {
// Read Cache (cached wrappers for hot-read paths)
getCachedSettings,
@@ -419,6 +435,7 @@ export {
connectServer,
disconnectServer,
listServers,
+ getConnectedServerByKeyHash,
} from "./db/gamification";
export type {
@@ -618,3 +635,96 @@ export {
export type { ApiKeyContextSource } from "./db/apiKeyContextSources";
export { sumUsageTokensThisMonth } from "./db/usageSummary";
+
+export {
+ getProviderMetrics,
+ getSearchProviderStats,
+ getRecentSearchLogs,
+ getSearchAggregateStats,
+ getSearchProviderCounts,
+ getFallbackStats,
+} from "./db/callLogStats";
+export type {
+ ProviderMetricRow,
+ SearchProviderStatRow,
+ SearchRecentRow,
+ SearchAggregateStats,
+ SearchProviderCountRow,
+ FallbackStatsRow,
+} from "./db/callLogStats";
+
+export {
+ buildUnifiedSource,
+ buildPresetUnifiedSource,
+ getUsageSummary,
+ getDailyUsage,
+ getDailyCostRows,
+ getHeatmapRows,
+ getModelUsageRows,
+ getProviderCostRows,
+ getProviderUsageRows,
+ getAccountCostRows,
+ getAccountUsageRows,
+ getApiKeyUsageRows,
+ getServiceTierUsageRows,
+ getApiKeyMetadataRows,
+ getWeeklyPatternRows,
+ getPresetCostModelRows,
+ getAllUsageHistory,
+ getAllDomainCostHistory,
+ getAllDomainBudgets,
+} from "./db/usageAnalytics";
+export type {
+ AnalyticsParams,
+ BuildUnifiedSourceOptions,
+ UnifiedSourceResult,
+ UsageSummaryRow,
+ DailyUsageRow,
+ DailyCostRow,
+ HeatmapRow,
+ ModelUsageRow,
+ ProviderCostRow,
+ ProviderUsageRow,
+ AccountCostRow,
+ AccountUsageRow,
+ ApiKeyUsageRow,
+ ServiceTierUsageRow,
+ ApiKeyMetadataRow,
+ WeeklyPatternRow,
+ PresetCostModelRow,
+} from "./db/usageAnalytics";
+
+// ---------------------------------------------------------------------------
+// usage_logs — auto-routing analytics (#3500 slice 4)
+// ---------------------------------------------------------------------------
+export {
+ getAutoRoutingTotalCount,
+ getAutoRoutingVariantBreakdown,
+ getAutoRoutingTopProviders,
+} from "./db/usageLogs";
+export type {
+ AutoRoutingTotalResult,
+ AutoRoutingVariantRow,
+ AutoRoutingTopProviderRow,
+} from "./db/usageLogs";
+
+// ---------------------------------------------------------------------------
+// semantic_cache — cache entries CRUD (#3500 slice 4)
+// ---------------------------------------------------------------------------
+export {
+ listSemanticCacheEntries,
+ deleteSemanticCacheBySignature,
+ deleteSemanticCacheByModel,
+} from "./db/semanticCache";
+export type {
+ SemanticCacheEntry,
+ SemanticCacheListOptions,
+ SemanticCacheListResult,
+ DeleteSemanticCacheBySignatureResult,
+ DeleteSemanticCacheByModelResult,
+} from "./db/semanticCache";
+
+// ---------------------------------------------------------------------------
+// proxy_logs — export query (#3500 slice 4)
+// ---------------------------------------------------------------------------
+export { exportProxyLogsSince } from "./db/proxyLogs";
diff --git a/src/lib/oauth/providers/kiro.ts b/src/lib/oauth/providers/kiro.ts
index 80c03a7d81..63d9965114 100644
--- a/src/lib/oauth/providers/kiro.ts
+++ b/src/lib/oauth/providers/kiro.ts
@@ -76,7 +76,7 @@ export const kiro = {
};
},
pollToken: async (config, deviceCode, codeVerifier, extraData) => {
- const tokenRegion = extraData?._region || "us-east-1";
+ const tokenRegion = String(extraData?._region || "us-east-1").toLowerCase();
const tokenUrl = `https://oidc.${tokenRegion}.amazonaws.com/token`;
const response = await fetch(tokenUrl, {
@@ -123,7 +123,46 @@ export const kiro = {
},
};
},
- mapTokens: (tokens) => ({
+ // Enterprise IAM Identity Center accounts require a region-bound Q Developer profileArn on every
+ // CodeWhisperer call; without it AWS returns 403 "User is not authorized to make this call". The
+ // device-code flow does not return one, so discover it here via ListAvailableProfiles against the
+ // same regional endpoint the token was issued for. Best-effort: AWS Builder ID accounts have no
+ // profile and this simply yields none; failures never block login.
+ postExchange: async (tokenData) => {
+ const accessToken = tokenData?.access_token;
+ if (!accessToken) return null;
+ const region = String(tokenData?._region || "us-east-1").toLowerCase();
+ const runtimeHost =
+ region === "us-east-1"
+ ? "https://codewhisperer.us-east-1.amazonaws.com"
+ : `https://q.${region}.amazonaws.com`;
+ try {
+ const profRes = await fetch(`${runtimeHost}/`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-amz-json-1.0",
+ Accept: "application/json",
+ "x-amz-target": "AmazonCodeWhispererService.ListAvailableProfiles",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ body: JSON.stringify({ maxResults: 10 }),
+ signal: AbortSignal.timeout(10000),
+ });
+ if (!profRes.ok) return null;
+ const profData = await profRes.json();
+ const profiles = Array.isArray(profData?.profiles) ? profData.profiles : [];
+ const matched =
+ profiles.find(
+ (p: { arn?: string }) => typeof p?.arn === "string" && p.arn.includes(`:${region}:`)
+ ) || profiles[0];
+ const arn = matched && typeof matched.arn === "string" ? matched.arn : undefined;
+ return arn ? { profileArn: arn } : null;
+ } catch {
+ // Best-effort profile discovery — never block login on it.
+ return null;
+ }
+ },
+ mapTokens: (tokens, extra) => ({
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiresIn: tokens.expires_in,
@@ -131,6 +170,7 @@ export const kiro = {
clientId: tokens._clientId,
clientSecret: tokens._clientSecret,
region: tokens._region,
+ ...(extra?.profileArn ? { profileArn: extra.profileArn } : {}),
},
}),
};
diff --git a/src/mitm/systemCommands.ts b/src/mitm/systemCommands.ts
index bbf3327d64..45e1eac4ff 100644
--- a/src/mitm/systemCommands.ts
+++ b/src/mitm/systemCommands.ts
@@ -20,7 +20,12 @@ export function execFileText(command: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
execFile(command, args, { encoding: "utf8" }, (error, stdout, stderr) => {
if (error) {
- reject(new Error(`Command failed: ${getErrorMessage(error)}\n${stderr}`));
+ // Node's execFile already sets error.message to "Command failed: <cmd>"
+ // (for non-zero exit) or "spawn <cmd> ENOENT" (for missing binary).
+ // Re-prefixing with "Command failed: " would double the prefix for the
+ // non-zero exit case. Surface Node's message directly and only append
+ // stderr when it contains additional context. (#3641)
+ reject(new Error(getErrorMessage(error) + (stderr ? `\n${stderr}` : "")));
return;
}
resolve(stdout);
diff --git a/src/shared/components/LanguageSelector.tsx b/src/shared/components/LanguageSelector.tsx
index 12f9ba1c58..7786e3fbfa 100644
--- a/src/shared/components/LanguageSelector.tsx
+++ b/src/shared/components/LanguageSelector.tsx
@@ -65,7 +65,7 @@ export default function LanguageSelector() {
{/* Dropdown */}
{open && (
- <div className="absolute right-0 top-full mt-1 w-56 max-h-80 rounded-xl border border-border bg-bg shadow-xl z-50 overflow-y-auto animate-in fade-in slide-in-from-top-1 duration-150">
+ <div className="absolute end-0 top-full mt-1 w-56 max-h-80 rounded-xl border border-border bg-bg shadow-xl z-50 overflow-y-auto animate-in fade-in slide-in-from-top-1 duration-150">
{LANGUAGES.map((lang) => (
<button
key={lang.code}
@@ -77,7 +77,7 @@ export default function LanguageSelector() {
}`}
>
<span className="text-base leading-none">{lang.flag}</span>
- <span className="flex-1 text-left">{lang.name}</span>
+ <span className="flex-1 text-start">{lang.name}</span>
{lang.code === locale && (
<span className="material-symbols-outlined text-[16px] text-primary">check</span>
)}
diff --git a/src/shared/components/NoAuthAccountCard.tsx b/src/shared/components/NoAuthAccountCard.tsx
new file mode 100644
index 0000000000..9f03a5f80b
--- /dev/null
+++ b/src/shared/components/NoAuthAccountCard.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import Card from "./Card";
+import Button from "./Button";
+
+interface NoAuthAccountCardProps {
+ providerId: string;
+ /** Display name for the provider (e.g. "MiMoCode", "OpenCode") */
+ providerName: string;
+ /** Generates a unique account identifier (fingerprint, session token, etc.) */
+ generateAccountId: () => string;
+ /** Key in providerSpecificData where account IDs are stored (default: "fingerprints") */
+ dataKey?: string;
+ /** Custom description text */
+ description?: string;
+ /** Custom "add" button label */
+ addLabel?: string;
+}
+
+interface Connection {
+ id: string;
+ provider: string;
+ apiKey?: string;
+ providerSpecificData?: Record<string, string[]>;
+ isActive?: boolean;
+}
+
+export default function NoAuthAccountCard({
+ providerId,
+ providerName,
+ generateAccountId,
+ dataKey = "fingerprints",
+ description = "Ready to use — no signup needed. Add accounts for rate-limit rotation.",
+ addLabel = "Add Account",
+}: NoAuthAccountCardProps) {
+ const [connections, setConnections] = useState<Connection[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [adding, setAdding] = useState(false);
+
+ const fetchConnections = useCallback(async () => {
+ try {
+ const res = await fetch("/api/providers");
+ if (res.ok) {
+ const data = await res.json();
+ const filtered = (data.connections || []).filter(
+ (c: Connection) => c.provider === providerId
+ );
+ setConnections(filtered);
+ }
+ } catch (err) {
+ console.error("Failed to fetch connections:", err);
+ } finally {
+ setLoading(false);
+ }
+ }, [providerId]);
+
+ useEffect(() => {
+ void fetchConnections();
+ }, [fetchConnections]);
+
+ const allAccountIds = connections.flatMap(
+ (c) => c.providerSpecificData?.[dataKey] || []
+ );
+
+ const handleAddAccount = async () => {
+ setAdding(true);
+ try {
+ const accountId = generateAccountId();
+ if (connections.length === 0) {
+ const res = await fetch("/api/providers", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider: providerId,
+ name: `${providerName} Account 1`,
+ providerSpecificData: { [dataKey]: [accountId] },
+ }),
+ });
+ if (!res.ok) throw new Error("Failed to create connection");
+ } else {
+ const conn = connections[0];
+ const updated = [...allAccountIds, accountId];
+ const res = await fetch(`/api/providers/${conn.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerSpecificData: { [dataKey]: updated },
+ }),
+ });
+ if (!res.ok) throw new Error("Failed to update connection");
+ }
+ await fetchConnections();
+ } catch (err) {
+ console.error("Failed to add account:", err);
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ const handleRemoveAccount = async (accountId: string) => {
+ if (connections.length === 0) return;
+ const conn = connections[0];
+ const updated = allAccountIds.filter((id) => id !== accountId);
+ try {
+ const res = await fetch(`/api/providers/${conn.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ providerSpecificData: { [dataKey]: updated },
+ }),
+ });
+ if (res.ok) await fetchConnections();
+ } catch (err) {
+ console.error("Failed to remove account:", err);
+ }
+ };
+
+ return (
+ <Card>
+ <div className="flex items-center gap-3 mb-3">
+ <div className="inline-flex shrink-0 items-center justify-center w-10 h-10 rounded-full bg-green-500/10 text-green-500">
+ <span className="material-symbols-outlined text-[20px]">lock_open</span>
+ </div>
+ <div className="flex-1">
+ <p className="text-sm font-medium">No authentication required</p>
+ <p className="text-xs text-text-muted">{description}</p>
+ </div>
+ </div>
+
+ <div className="border-t border-border pt-3 mt-3">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-sm font-medium">
+ Accounts ({loading ? "..." : allAccountIds.length})
+ </span>
+ <Button size="sm" icon="add" onClick={handleAddAccount} disabled={adding}>
+ {adding ? "Adding..." : addLabel}
+ </Button>
+ </div>
+
+ {!loading && allAccountIds.length === 0 && (
+ <p className="text-xs text-text-muted py-2">
+ Using auto-generated account. Click &quot;{addLabel}&quot; for rate-limit rotation.
+ </p>
+ )}
+
+ {!loading && allAccountIds.length > 0 && (
+ <div className="space-y-1">
+ {allAccountIds.map((id, i) => (
+ <div
+ key={id}
+ className="flex items-center justify-between rounded-md bg-bg-secondary px-3 py-1.5 text-xs"
+ >
+ <span className="font-mono text-text-muted">
+ Account {i + 1}: {id.slice(0, 12)}...
+ </span>
+ <button
+ onClick={() => handleRemoveAccount(id)}
+ className="text-red-500 hover:text-red-400 text-xs"
+ >
+ Remove
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </Card>
+ );
+}
diff --git a/src/shared/components/Select.tsx b/src/shared/components/Select.tsx
index 8abcfd7755..494f5f5031 100644
--- a/src/shared/components/Select.tsx
+++ b/src/shared/components/Select.tsx
@@ -62,7 +62,7 @@ export default function Select({
aria-invalid={error ? true : undefined}
aria-describedby={describedBy}
className={cn(
- "w-full py-2 px-3 pr-10 text-sm text-text-main",
+ "w-full py-2 px-3 pe-10 text-sm text-text-main",
"bg-surface border border-black/10 dark:border-white/10 rounded-md appearance-none",
"focus:ring-1 focus:ring-primary/30 focus:border-primary/50 focus:outline-none",
"transition-all disabled:opacity-50 disabled:cursor-not-allowed",
@@ -86,7 +86,7 @@ export default function Select({
{children}
</select>
<div
- className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none text-text-muted"
+ className="absolute inset-y-0 end-0 flex items-center pe-3 pointer-events-none text-text-muted"
aria-hidden="true"
>
<span className="material-symbols-outlined text-[20px]">expand_more</span>
diff --git a/src/shared/components/Sidebar.tsx b/src/shared/components/Sidebar.tsx
index 85ec4b833c..9576b0d1c3 100644
--- a/src/shared/components/Sidebar.tsx
+++ b/src/shared/components/Sidebar.tsx
@@ -448,7 +448,7 @@ export default function Sidebar({
className={cn(
"rounded-md p-1 text-text-muted/50 transition-colors hover:bg-black/5 hover:text-text-muted dark:hover:bg-white/5",
collapsed && !isMacElectron && "mt-2",
- isMacElectron && "ml-auto"
+ isMacElectron && "ms-auto"
)}
>
<span className="material-symbols-outlined text-[16px]" aria-hidden="true">
diff --git a/src/shared/components/index.tsx b/src/shared/components/index.tsx
index 2c6b5e822f..9d47f02fdd 100644
--- a/src/shared/components/index.tsx
+++ b/src/shared/components/index.tsx
@@ -35,6 +35,7 @@ export { default as FilterBar } from "./FilterBar";
export { default as ColumnToggle } from "./ColumnToggle";
export { default as DataTable } from "./DataTable";
export { default as NoAuthProviderCard } from "./NoAuthProviderCard";
+export { default as NoAuthAccountCard } from "./NoAuthAccountCard";
export { default as CollapsibleSection } from "./CollapsibleSection";
export { default as InfoTooltip } from "./InfoTooltip";
export { default as PresetSlider } from "./PresetSlider";
diff --git a/src/shared/components/layouts/DashboardLayout.tsx b/src/shared/components/layouts/DashboardLayout.tsx
index c2a7b871e9..958450a776 100644
--- a/src/shared/components/layouts/DashboardLayout.tsx
+++ b/src/shared/components/layouts/DashboardLayout.tsx
@@ -82,7 +82,7 @@ export default function DashboardLayout({ children }) {
{/* Sidebar - Mobile: full viewport height with proper scroll containment */}
<div
- className={`fixed inset-y-0 left-0 z-50 transform lg:hidden transition-transform duration-300 ease-in-out h-dvh overflow-y-auto ${
+ className={`fixed inset-y-0 start-0 z-50 transform lg:hidden transition-transform duration-300 ease-in-out h-dvh overflow-y-auto ${
sidebarOpen ? "translate-x-0" : "-translate-x-full"
}`}
>
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index ec4bedc8fa..38e8d672c8 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -106,9 +106,28 @@ export const NOAUTH_PROVIDERS = {
freeNote: "Free video generation — VEO 3.1, Seedance. 6 requests/hour.",
authHint: "No auth required. Rate limited to 6 requests/hour per IP.",
},
+ mimocode: {
+ id: "mimocode",
+ alias: "mcode",
+ name: "MiMoCode (Free)",
+ icon: "devices",
+ color: "#FF6B35",
+ textIcon: "MC",
+ website: "https://mimo.mi.com",
+ noAuth: true,
+ hasFree: true,
+ serviceKinds: ["llm"],
+ freeNote:
+ "Free — Xiaomi MiMo models via bootstrap JWT auth. No API key required. Supports streaming.",
+ authHint:
+ "No API key required. The executor auto-generates JWT tokens via device fingerprint bootstrap.",
+ notice: {
+ text: "MiMoCode uses Xiaomi's public free AI endpoint with bootstrap-based JWT authentication. No signup needed. Rate limits apply.",
+ },
+ },
};
-export const FREE_APIKEY_PROVIDER_IDS = new Set(["qoder"]);
+export const FREE_APIKEY_PROVIDER_IDS = new Set(["qoder", "mimocode", "opencode"]);
export function supportsApiKeyOnFreeProvider(providerId: unknown): boolean {
return typeof providerId === "string" && FREE_APIKEY_PROVIDER_IDS.has(providerId);
@@ -2853,6 +2872,8 @@ export function providerAllowsOptionalApiKey(providerId: unknown): boolean {
providerId === "huggingchat" ||
providerId === "gitlawb" ||
providerId === "gitlawb-gmi" ||
+ providerId === "mimocode" ||
+ providerId === "opencode" ||
isLocalProvider(providerId) ||
isSelfHostedChatProvider(providerId) ||
isOpenAICompatibleProvider(providerId) ||
diff --git a/src/shared/services/cliRuntime.ts b/src/shared/services/cliRuntime.ts
index 2041071bc6..d0db6ae2de 100644
--- a/src/shared/services/cliRuntime.ts
+++ b/src/shared/services/cliRuntime.ts
@@ -3,6 +3,7 @@ import fsSync from "fs";
import os from "os";
import path from "path";
import { spawn, execFileSync } from "child_process";
+import { getHermesHome } from "@/lib/cli-helper/config-generator/hermesHome";
const VALID_RUNTIME_MODES = new Set(["auto", "host", "container"]);
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
@@ -147,7 +148,10 @@ const CLI_TOOLS: Record<string, any> = {
requiresBinary: true,
healthcheckTimeoutMs: 4000,
paths: {
- config: ".hermes/config.yaml",
+ // The relative path is kept for documentation purposes; getCliConfigPaths()
+ // has a special case for hermes-agent that calls getHermesHome() instead of
+ // getCliConfigHome(), so HERMES_HOME is always honoured (#3628).
+ config: "config.yaml",
},
},
amp: {
@@ -963,6 +967,13 @@ export const getCliConfigPaths = (toolId: string) => {
};
}
+ // hermes-agent: honour HERMES_HOME env var instead of the generic CLI_CONFIG_HOME (#3628).
+ if (toolId === "hermes-agent") {
+ return {
+ config: path.join(getHermesHome(), "config.yaml"),
+ };
+ }
+
const home = getCliConfigHome();
return Object.fromEntries(
Object.entries(tool.paths).map(([key, relativePath]) => {
diff --git a/src/shared/utils/machine.ts b/src/shared/utils/machine.ts
index 8a7168f2c3..702af51a7c 100644
--- a/src/shared/utils/machine.ts
+++ b/src/shared/utils/machine.ts
@@ -1,18 +1,5 @@
import { getConsistentMachineId } from "./machineId";
-// Get machine ID using node-machine-id with salt
export async function getMachineId() {
return await getConsistentMachineId();
}
-
-// Keep sync functions for backward compatibility but make them no-ops
-// (Frontend sync is disabled - use backend sync instead)
-export async function syncProviderDataToCloud(cloudUrl) {
- console.log("Frontend sync is disabled. Use backend sync instead.");
- return Promise.resolve(true);
-}
-
-export async function getProvidersNeedingRefresh() {
- console.log("Frontend sync is disabled. Use backend sync instead.");
- return Promise.resolve([]);
-}
diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.ts
index fac4880acd..b5b9ec81eb 100644
--- a/src/shared/validation/schemas.ts
+++ b/src/shared/validation/schemas.ts
@@ -748,6 +748,7 @@ export const updateSettingsSchema = z.object({
hideEndpointCloudflaredTunnel: z.boolean().optional(),
hideEndpointTailscaleFunnel: z.boolean().optional(),
hideEndpointNgrokTunnel: z.boolean().optional(),
+ preferClaudeCodeForUnprefixedClaudeModels: z.boolean().optional(),
pinProviderQuotaToHome: z.boolean().optional(),
showQuickStartOnHome: z.boolean().optional(),
showProviderTopologyOnHome: z.boolean().optional(),
diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.ts
index d426feaef1..40ae9f3268 100644
--- a/src/shared/validation/settingsSchemas.ts
+++ b/src/shared/validation/settingsSchemas.ts
@@ -36,6 +36,7 @@ export const updateSettingsSchema = z.object({
hideEndpointCloudflaredTunnel: z.boolean().optional(),
hideEndpointTailscaleFunnel: z.boolean().optional(),
hideEndpointNgrokTunnel: z.boolean().optional(),
+ preferClaudeCodeForUnprefixedClaudeModels: z.boolean().optional(),
autoRefreshProviderQuota: z.boolean().optional(),
autoRefreshProviderQuotaInterval: z.number().int().min(10).max(3600).optional(),
pinProviderQuotaToHome: z.boolean().optional(),
diff --git a/src/types/settings.ts b/src/types/settings.ts
index f5af082fcc..b46b68cfc7 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -29,6 +29,7 @@ export interface Settings {
hideEndpointCloudflaredTunnel?: boolean;
hideEndpointTailscaleFunnel?: boolean;
hideEndpointNgrokTunnel?: boolean;
+ preferClaudeCodeForUnprefixedClaudeModels?: boolean;
autoRefreshProviderQuota?: boolean;
autoRefreshProviderQuotaInterval?: number;
pinProviderQuotaToHome?: boolean;
diff --git a/tests/unit/audit-allowlist-real-actions.test.ts b/tests/unit/audit-allowlist-real-actions.test.ts
index 6647f9d784..9283fcdb12 100644
--- a/tests/unit/audit-allowlist-real-actions.test.ts
+++ b/tests/unit/audit-allowlist-real-actions.test.ts
@@ -15,7 +15,7 @@ import assert from "node:assert/strict";
import { HIGH_LEVEL_ACTIONS, isHighLevelAction } from "../../src/lib/audit/highLevelActions";
import { ACTIVITY_ICONS, getActivityIcon } from "../../src/lib/audit/activityIcons";
-/** All 26 real actions discovered via grep logAuditEvent in the repo (B/G3, 2026-05). */
+/** All 27 real actions discovered via grep logAuditEvent in the repo (B/G3, 2026-05). */
const REAL_REPO_ACTIONS = [
"auth.login.success",
"auth.login.error",
@@ -26,6 +26,7 @@ const REAL_REPO_ACTIONS = [
"auth.logout.success",
"provider.credentials.applied",
"provider.credentials.batch_revoked",
+ "provider.credentials.batch_updated",
"provider.credentials.bulk_created",
"provider.credentials.bulk_imported",
"provider.credentials.created",
@@ -58,18 +59,18 @@ test("ACTIVITY_ICONS has no extra entries beyond HIGH_LEVEL_ACTIONS (strict 1:1)
}
});
-test("all 26 real repo actions are present in HIGH_LEVEL_ACTIONS", () => {
+test("all 27 real repo actions are present in HIGH_LEVEL_ACTIONS", () => {
const allowlistSet = new Set<string>(HIGH_LEVEL_ACTIONS);
for (const action of REAL_REPO_ACTIONS) {
assert.ok(allowlistSet.has(action), `HIGH_LEVEL_ACTIONS missing real repo action: '${action}'`);
}
});
-test("HIGH_LEVEL_ACTIONS contains exactly the same 26 real repo actions (no extras, no missing)", () => {
+test("HIGH_LEVEL_ACTIONS contains exactly the same 27 real repo actions (no extras, no missing)", () => {
assert.equal(
(HIGH_LEVEL_ACTIONS as readonly string[]).length,
REAL_REPO_ACTIONS.length,
- `Expected ${REAL_REPO_ACTIONS.length} actions, got ${(HIGH_LEVEL_ACTIONS as readonly string[]).length}`,
+ `Expected ${REAL_REPO_ACTIONS.length} actions, got ${(HIGH_LEVEL_ACTIONS as readonly string[]).length}`
);
});
@@ -77,6 +78,16 @@ test("isHighLevelAction('provider.credentials.created') === true", () => {
assert.equal(isHighLevelAction("provider.credentials.created"), true);
});
+// Regression for #3271 follow-up: the bulk activate/deactivate endpoint emits
+// provider.credentials.batch_updated, so it must appear in the Activity feed
+// allowlist and have a non-fallback icon (emitter + registries kept atomic).
+test("provider.credentials.batch_updated is a registered high-level action", () => {
+ assert.equal(isHighLevelAction("provider.credentials.batch_updated"), true);
+ const spec = getActivityIcon("provider.credentials.batch_updated");
+ assert.notDeepEqual(spec, { icon: "info", i18nKeyVerb: "genericEvent" });
+ assert.equal(spec.i18nKeyVerb, "providerCredentialsBatchUpdated");
+});
+
test("isHighLevelAction('nonexistent.action') === false", () => {
assert.equal(isHighLevelAction("nonexistent.action"), false);
});
diff --git a/tests/unit/audit-high-level-actions.test.ts b/tests/unit/audit-high-level-actions.test.ts
index 3ff2b1ae70..a3fc1f7cf4 100644
--- a/tests/unit/audit-high-level-actions.test.ts
+++ b/tests/unit/audit-high-level-actions.test.ts
@@ -5,9 +5,9 @@ import { HIGH_LEVEL_ACTIONS, isHighLevelAction } from "../../src/lib/audit/highL
const ALL = HIGH_LEVEL_ACTIONS as readonly string[];
-// B/G3: allowlist now has 26 real actions aligned with logAuditEvent emitters.
-test("HIGH_LEVEL_ACTIONS has exactly 26 entries", () => {
- assert.equal(ALL.length, 26);
+// B/G3: allowlist aligned with logAuditEvent emitters (27 after batch_updated).
+test("HIGH_LEVEL_ACTIONS has exactly 27 entries", () => {
+ assert.equal(ALL.length, 27);
});
test("HIGH_LEVEL_ACTIONS has no duplicates", () => {
diff --git a/tests/unit/auto-combo-context-advertising.test.ts b/tests/unit/auto-combo-context-advertising.test.ts
new file mode 100644
index 0000000000..e316cdae52
--- /dev/null
+++ b/tests/unit/auto-combo-context-advertising.test.ts
@@ -0,0 +1,210 @@
+/**
+ * TDD regression tests — auto-combo context-window advertising + per-target
+ * combo compression limit (the "premature auto compaction" bug).
+ *
+ * Bug chain (discussion report: coding agents "keep forgetting things"):
+ * 1. /api/combos/auto never exposed context_length, so the opencode plugin
+ * advertised `limit: { context: 0 }` for auto combos. opencode disables
+ * its smart auto-compaction entirely when context === 0, letting the
+ * conversation grow until OmniRoute's destructive purifyHistory() drops
+ * old messages silently.
+ * 2. chatCore's proactive-compression block overrode the per-target context
+ * limit with min(...allComboTargets) even though chatCore always executes
+ * with the CONCRETE target's provider/model (handleSingleModel resolves
+ * the target before calling chatCore) — compressing at the smallest
+ * target's window while running on the largest target.
+ *
+ * Fixes under test:
+ * - virtualFactory.computeAdvertisedLimits(): MAX of candidates' known
+ * context windows (the auto-combo context pre-filter routes oversized
+ * requests to large-window candidates, so MAX is safe to advertise).
+ * - GET /api/combos/auto includes context_length / max_output_tokens.
+ * - contextManager.resolveComboContextLimit(): prefers the executing
+ * target's own limit; min(...targets) only as a defensive fallback when
+ * the current provider/model resolves no specific limit.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-auto-combo-ctx-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET ?? "auto-combo-ctx-test-secret";
+
+const core = await import("../../src/lib/db/core.ts");
+const settingsDb = await import("../../src/lib/db/settings.ts");
+
+const virtualFactory = await import("../../open-sse/services/autoCombo/virtualFactory.ts");
+const contextManager = await import("../../open-sse/services/contextManager.ts");
+const combosAutoRoute = await import("../../src/app/api/combos/auto/route.ts");
+
+test.after(() => {
+ core.resetDbInstance();
+ try {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ } catch {
+ // best-effort cleanup
+ }
+});
+
+// ── virtualFactory.computeAdvertisedLimits ───────────────────────────────────
+
+test("computeAdvertisedLimits returns MAX of candidates' known context windows", () => {
+ const { computeAdvertisedLimits } = virtualFactory as unknown as {
+ computeAdvertisedLimits: (candidates: Array<{ provider: string; model: string }>) => {
+ contextLength: number | null;
+ maxOutputTokens: number | null;
+ };
+ };
+ assert.equal(
+ typeof computeAdvertisedLimits,
+ "function",
+ "virtualFactory should export computeAdvertisedLimits()"
+ );
+
+ // gemini has registry defaultContextLength=1048576; claude has 200000.
+ const result = computeAdvertisedLimits([
+ { provider: "claude", model: "claude-sonnet-4-6" },
+ { provider: "gemini", model: "gemini-2.5-pro" },
+ ]);
+ assert.equal(result.contextLength, 1048576, "MAX of candidate windows should win");
+ assert.ok(
+ typeof result.maxOutputTokens === "number" && result.maxOutputTokens > 0,
+ "maxOutputTokens should be a positive number"
+ );
+});
+
+test("computeAdvertisedLimits returns null limits for an empty candidate pool", () => {
+ const { computeAdvertisedLimits } = virtualFactory as unknown as {
+ computeAdvertisedLimits: (candidates: Array<{ provider: string; model: string }>) => {
+ contextLength: number | null;
+ maxOutputTokens: number | null;
+ };
+ };
+ const result = computeAdvertisedLimits([]);
+ assert.equal(result.contextLength, null);
+ assert.equal(result.maxOutputTokens, null);
+});
+
+test("computeAdvertisedLimits never returns 0 for a non-empty pool (unknown models fall back)", () => {
+ const { computeAdvertisedLimits } = virtualFactory as unknown as {
+ computeAdvertisedLimits: (candidates: Array<{ provider: string; model: string }>) => {
+ contextLength: number | null;
+ maxOutputTokens: number | null;
+ };
+ };
+ const result = computeAdvertisedLimits([
+ { provider: "totally-unknown-provider", model: "mystery-model" },
+ ]);
+ assert.ok(
+ typeof result.contextLength === "number" && result.contextLength > 0,
+ `unknown candidates should fall back to a positive default, got ${result.contextLength}`
+ );
+});
+
+// ── GET /api/combos/auto advertises context_length ──────────────────────────
+
+test("GET /api/combos/auto includes positive context_length for combos with candidates", async () => {
+ await settingsDb.updateSettings({ requireLogin: false });
+
+ const req = new Request("http://localhost/api/combos/auto", { method: "GET" });
+ const res = await combosAutoRoute.GET(req as never);
+ const body = await res.json();
+
+ assert.equal(res.status, 200);
+ assert.ok(Array.isArray(body.combos), "body.combos should be an array");
+ assert.ok(body.combos.length > 0, "should list at least the default auto combo");
+
+ for (const combo of body.combos) {
+ if ((combo.candidateCount ?? 0) > 0) {
+ assert.ok(
+ typeof combo.context_length === "number" && combo.context_length > 0,
+ `combo ${combo.id} with ${combo.candidateCount} candidates must advertise a positive context_length, got ${combo.context_length}`
+ );
+ assert.ok(
+ typeof combo.max_output_tokens === "number" && combo.max_output_tokens > 0,
+ `combo ${combo.id} must advertise a positive max_output_tokens, got ${combo.max_output_tokens}`
+ );
+ }
+ }
+});
+
+// ── contextManager.resolveComboContextLimit (per-target compression limit) ──
+
+test("resolveComboContextLimit prefers the executing target's own limit over combo min", () => {
+ const { resolveComboContextLimit } = contextManager as unknown as {
+ resolveComboContextLimit: (opts: {
+ provider: string;
+ model: string | null;
+ comboTargetLimits: number[];
+ }) => { limit: number; source: string };
+ };
+ assert.equal(
+ typeof resolveComboContextLimit,
+ "function",
+ "contextManager should export resolveComboContextLimit()"
+ );
+
+ // Executing on gemini (1048576 provider default) while the combo also has
+ // a tiny 32k target: compression must use the EXECUTING target's window.
+ const result = resolveComboContextLimit({
+ provider: "gemini",
+ model: "gemini-2.5-pro",
+ comboTargetLimits: [32000, 1048576],
+ });
+ assert.equal(result.limit, 1048576, "must not regress to min(...targets) on a known target");
+ assert.equal(result.source, "target");
+});
+
+test("resolveComboContextLimit regression: claude target must not be compressed at an 8k sibling", () => {
+ const { resolveComboContextLimit } = contextManager as unknown as {
+ resolveComboContextLimit: (opts: {
+ provider: string;
+ model: string | null;
+ comboTargetLimits: number[];
+ }) => { limit: number; source: string };
+ };
+ const result = resolveComboContextLimit({
+ provider: "claude",
+ model: "claude-sonnet-4-6",
+ comboTargetLimits: [8000],
+ });
+ assert.equal(result.limit, 200000);
+ assert.equal(result.source, "target");
+});
+
+test("resolveComboContextLimit falls back to combo min when the target has no specific limit", () => {
+ const { resolveComboContextLimit } = contextManager as unknown as {
+ resolveComboContextLimit: (opts: {
+ provider: string;
+ model: string | null;
+ comboTargetLimits: number[];
+ }) => { limit: number; source: string };
+ };
+ const result = resolveComboContextLimit({
+ provider: "totally-unknown-provider",
+ model: "mystery-model",
+ comboTargetLimits: [32000, 200000],
+ });
+ assert.equal(result.limit, 32000, "unknown target should defensively use min of combo targets");
+ assert.equal(result.source, "combo-min");
+});
+
+test("resolveComboContextLimit uses generic fallback when nothing else is known", () => {
+ const { resolveComboContextLimit } = contextManager as unknown as {
+ resolveComboContextLimit: (opts: {
+ provider: string;
+ model: string | null;
+ comboTargetLimits: number[];
+ }) => { limit: number; source: string };
+ };
+ const result = resolveComboContextLimit({
+ provider: "totally-unknown-provider",
+ model: "mystery-model",
+ comboTargetLimits: [],
+ });
+ assert.equal(result.limit, 128000, "generic default fallback");
+ assert.equal(result.source, "fallback");
+});
diff --git a/tests/unit/check-db-rules-classification.test.ts b/tests/unit/check-db-rules-classification.test.ts
new file mode 100644
index 0000000000..7c3d6a804c
--- /dev/null
+++ b/tests/unit/check-db-rules-classification.test.ts
@@ -0,0 +1,213 @@
+/**
+ * Regression guard for INTENTIONALLY_INTERNAL classification (#3499).
+ *
+ * Every module in INTENTIONALLY_INTERNAL must be genuinely consumed via a
+ * direct/dynamic import somewhere in src/, open-sse/, bin/, or within
+ * src/lib/db/ itself (for db-internal coordination modules like stateReset,
+ * healthCheck, migrationRunner), OR documented as type-only / DEAD?.
+ *
+ * Purpose: if a future cleanup removes the last consumer of a module that is
+ * still in INTENTIONALLY_INTERNAL, this test turns red and forces a conscious
+ * reclassification decision — the DEAD? category must be explicitly expanded,
+ * not silently accumulated.
+ *
+ * Hard Rule #18 compliance: this test was written BEFORE the fix was applied,
+ * confirmed to fail on the old framing, and now passes on the audited truth.
+ */
+import { test } from "node:test";
+import assert from "node:assert";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { INTENTIONALLY_INTERNAL } from "../../scripts/check/check-db-rules.mjs";
+
+const REPO_ROOT = path.resolve(fileURLToPath(import.meta.url), "../../..");
+
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+/**
+ * Walk a directory tree, calling cb(absolutePath) for every file.
+ */
+function walkSync(dir: string, cb: (p: string) => void): void {
+ if (!fs.existsSync(dir)) return;
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ // Skip well-known non-source dirs to keep the walk fast
+ if (["node_modules", ".git", ".next", "dist", "out"].includes(entry.name)) continue;
+ walkSync(full, cb);
+ } else {
+ cb(full);
+ }
+ }
+}
+
+/**
+ * Returns true if any file in the search roots imports db/<mod> (static or dynamic).
+ * Patterns matched:
+ * from "@/lib/db/<mod>"
+ * from "../db/<mod>" (any relative path ending /db/<mod>)
+ * import("@/lib/db/<mod>")
+ * require(".../db/<mod>")
+ * import(`${...}/db/<mod>.ts`) — dynamic template (bin/cli/runtime.mjs pattern)
+ */
+function hasImporter(mod: string, roots: string[]): boolean {
+ // Escape special regex chars in mod name (underscore-prefixed names like _rowTypes)
+ const escaped = mod.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const patterns = [
+ // static: from "…/db/<mod>"
+ new RegExp(`from\\s+['""][^'"]+/db/${escaped}['"]`),
+ // dynamic: import("…/db/<mod>") or require("…/db/<mod>")
+ new RegExp(`(?:import|require)\\s*\\(\\s*['""][^'"]+/db/${escaped}['"]`),
+ // dynamic template: import(`…/db/<mod>.ts`) — bin/cli/runtime.mjs uses template literals
+ new RegExp(`import\\s*\\(\`[^'"\`]+/db/${escaped}\\.ts\`\\)`),
+ // relative import within db/: from "./<mod>" or from "./<mod>"
+ new RegExp(`from\\s+['"]\\.\\.?/${escaped}['"]`),
+ ];
+ // The canonical db module path — we must skip ONLY this exact file, not all files
+ // that happen to share the same basename (e.g. src/lib/usage/comboForecast.ts must
+ // NOT be skipped when searching for importers of src/lib/db/comboForecast.ts).
+ const dbModulePath = path.join(REPO_ROOT, "src", "lib", "db", `${mod}.ts`);
+ let found = false;
+ for (const root of roots) {
+ if (found) break;
+ walkSync(root, (filePath) => {
+ if (found) return;
+ // Only scan TS/JS/MJS source files
+ if (!/\.(ts|tsx|mjs|js|cjs)$/.test(filePath)) return;
+ // Skip only the db module itself (not same-name files in other dirs)
+ if (filePath === dbModulePath) return;
+ let src: string;
+ try {
+ src = fs.readFileSync(filePath, "utf8");
+ } catch {
+ return;
+ }
+ if (patterns.some((rx) => rx.test(src))) found = true;
+ });
+ }
+ return found;
+}
+
+// ── Audit roots ────────────────────────────────────────────────────────────
+
+// Modules marked "type-only": exports only TypeScript types; no runtime import
+// needed — the ts compiler erases them. These are genuinely correct as-is.
+const TYPE_ONLY = new Set(["_rowTypes"]);
+
+// Modules explicitly documented as DEAD? in the classification comments.
+// They remain in INTENTIONALLY_INTERNAL for schema-reservation reasons.
+// Flag them but do NOT fail — a separate decision is needed to remove them.
+const DOCUMENTED_DEAD = new Set([
+ "compressionScheduler", // DEAD?: 0 production importers as of 2026-06-11
+ "discovery", // DEAD?: 0 importers; lib/discovery/index.ts is independent
+ "pluginMetrics", // DEAD? (production): write path not yet wired (self-documented)
+ "prompts", // DEAD? (production): zero production callers; integration test only verifies interface shape
+]);
+
+const SEARCH_ROOTS = [
+ path.join(REPO_ROOT, "src"),
+ path.join(REPO_ROOT, "open-sse"),
+ path.join(REPO_ROOT, "bin"),
+ path.join(REPO_ROOT, "tests"),
+];
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+test("INTENTIONALLY_INTERNAL is exported from check-db-rules.mjs", () => {
+ assert.ok(
+ INTENTIONALLY_INTERNAL instanceof Set,
+ "INTENTIONALLY_INTERNAL must be a Set exported from the gate script"
+ );
+ assert.ok(INTENTIONALLY_INTERNAL.size > 0, "INTENTIONALLY_INTERNAL must not be empty");
+});
+
+test("INTENTIONALLY_INTERNAL contains the expected 25 audited modules", () => {
+ const expected = [
+ "_rowTypes",
+ "cleanup",
+ "cliToolState",
+ "comboForecast",
+ "commandCodeAuth",
+ "compression",
+ "compressionScheduler",
+ "detailedLogs",
+ "discovery",
+ "domainState",
+ "encryption",
+ "healthCheck",
+ "jsonMigration",
+ "migrationRunner",
+ "notion",
+ "obsidian",
+ "pluginMetrics",
+ "prompts",
+ "providerStats",
+ "recovery",
+ "secrets",
+ "serviceModels",
+ "stateReset",
+ "stats",
+ "tierConfig",
+ ];
+ for (const mod of expected) {
+ assert.ok(
+ INTENTIONALLY_INTERNAL.has(mod),
+ `Expected ${mod} to be in INTENTIONALLY_INTERNAL after audit`
+ );
+ }
+ assert.equal(
+ INTENTIONALLY_INTERNAL.size,
+ expected.length,
+ `INTENTIONALLY_INTERNAL has ${INTENTIONALLY_INTERNAL.size} entries; expected ${expected.length}`
+ );
+});
+
+test("every non-type-only, non-dead module in INTENTIONALLY_INTERNAL has ≥1 real importer", () => {
+ const failures: string[] = [];
+ for (const mod of INTENTIONALLY_INTERNAL) {
+ if (TYPE_ONLY.has(mod)) continue; // type-only: no runtime import expected
+ if (DOCUMENTED_DEAD.has(mod)) continue; // dead modules exempted with explicit flag
+ if (!hasImporter(mod, SEARCH_ROOTS)) {
+ failures.push(mod);
+ }
+ }
+ assert.deepEqual(
+ failures,
+ [],
+ `These INTENTIONALLY_INTERNAL modules have ZERO importers — either they became dead ` +
+ `(add to DOCUMENTED_DEAD with a DEAD? comment) or they were misclassified:\n ${failures.join(", ")}`
+ );
+});
+
+test("type-only module _rowTypes is imported within src/lib/db/ by its consumers", () => {
+ // _rowTypes exports only TypeScript interfaces, so the import is always `import type`.
+ // It should be consumed within db/ itself (AgentBridge, Inspector CRUD modules).
+ const dbDir = path.join(REPO_ROOT, "src/lib/db");
+ let found = false;
+ if (fs.existsSync(dbDir)) {
+ for (const entry of fs.readdirSync(dbDir, { withFileTypes: true })) {
+ if (!entry.isFile() || !/\.ts$/.test(entry.name)) continue;
+ if (entry.name === "_rowTypes.ts") continue;
+ const src = fs.readFileSync(path.join(dbDir, entry.name), "utf8");
+ if (/from\s+['"]\.\/_rowTypes['"]/.test(src)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ assert.ok(
+ found,
+ "_rowTypes must be imported (as type) by at least one sibling module in src/lib/db/"
+ );
+});
+
+test("DOCUMENTED_DEAD modules are still in INTENTIONALLY_INTERNAL (dead list must stay honest)", () => {
+ for (const mod of DOCUMENTED_DEAD) {
+ assert.ok(
+ INTENTIONALLY_INTERNAL.has(mod),
+ `DOCUMENTED_DEAD module "${mod}" is no longer in INTENTIONALLY_INTERNAL — ` +
+ `remove it from DOCUMENTED_DEAD in this test if it was intentionally removed from the gate`
+ );
+ }
+});
diff --git a/tests/unit/cli-helper/hermes-home-env.test.ts b/tests/unit/cli-helper/hermes-home-env.test.ts
new file mode 100644
index 0000000000..941e53c9aa
--- /dev/null
+++ b/tests/unit/cli-helper/hermes-home-env.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Regression test for #3628: Hermes Agent config must honour the HERMES_HOME env var.
+ *
+ * Hard Rule #18 — TDD gate: this file was written BEFORE the fix and was red,
+ * then turned green once getHermesHome() was introduced and all callsites
+ * were routed through it.
+ */
+import { describe, it, before, after } from "node:test";
+import assert from "node:assert";
+import os from "node:os";
+import path from "node:path";
+
+// Keep the original value so we can restore it in teardown.
+const _originalHermesHome = process.env.HERMES_HOME;
+
+describe("getHermesHome (#3628 — HERMES_HOME env var)", () => {
+ // ── helper: dynamic import so we always get a fresh module evaluation
+ // Note: Node ESM caches modules. We test the exported helper directly.
+
+ after(() => {
+ // Restore the env var regardless of test outcome.
+ if (_originalHermesHome === undefined) {
+ delete process.env.HERMES_HOME;
+ } else {
+ process.env.HERMES_HOME = _originalHermesHome;
+ }
+ });
+
+ it("falls back to ~/.hermes when HERMES_HOME is not set", async () => {
+ delete process.env.HERMES_HOME;
+
+ const { getHermesHome } = await import(
+ "../../../src/lib/cli-helper/config-generator/hermesHome.ts"
+ );
+
+ const result = getHermesHome();
+ assert.strictEqual(result, path.join(os.homedir(), ".hermes"));
+ });
+
+ it("returns HERMES_HOME when the env var is set", async () => {
+ process.env.HERMES_HOME = "/custom/hermes";
+
+ const { getHermesHome } = await import(
+ "../../../src/lib/cli-helper/config-generator/hermesHome.ts"
+ );
+
+ const result = getHermesHome();
+ assert.ok(
+ result.startsWith("/custom/hermes"),
+ `Expected path to start with /custom/hermes, got: ${result}`
+ );
+ });
+
+ it("hermes-agent CONFIG_PATH uses HERMES_HOME when set", async () => {
+ process.env.HERMES_HOME = "/custom/hermes";
+
+ const { getHermesConfigPath } = await import(
+ "../../../src/lib/cli-helper/config-generator/hermesHome.ts"
+ );
+
+ const configPath = getHermesConfigPath();
+ assert.ok(
+ configPath.startsWith("/custom/hermes"),
+ `Expected config path to start with /custom/hermes, got: ${configPath}`
+ );
+ assert.ok(
+ configPath.endsWith("config.yaml"),
+ `Expected config path to end with config.yaml, got: ${configPath}`
+ );
+ });
+
+ it("TOOL_CONFIG_PATHS['hermes-agent'] reflects HERMES_HOME (lazy evaluation)", async () => {
+ process.env.HERMES_HOME = "/custom/hermes";
+
+ // Force a fresh dynamic import of index.ts to test lazy evaluation.
+ // Because Node caches ESM modules by URL, we test the helper which is
+ // what index.ts should delegate to.
+ const { getHermesConfigPath } = await import(
+ "../../../src/lib/cli-helper/config-generator/hermesHome.ts"
+ );
+
+ // The path returned by the generator index must equal what getHermesConfigPath() returns.
+ const expected = getHermesConfigPath();
+ assert.ok(
+ expected.startsWith("/custom/hermes"),
+ `Expected ${expected} to start with /custom/hermes`
+ );
+ });
+
+ it("getCliConfigPaths('hermes-agent') uses HERMES_HOME (cliRuntime integration)", async () => {
+ process.env.HERMES_HOME = "/custom/hermes";
+
+ const { getCliConfigPaths } = await import(
+ "../../../src/shared/services/cliRuntime.ts"
+ );
+
+ const paths = getCliConfigPaths("hermes-agent");
+ assert.ok(paths !== null, "getCliConfigPaths('hermes-agent') returned null");
+ const configPath = (paths as Record<string, string>)["config"];
+ assert.ok(
+ configPath.startsWith("/custom/hermes"),
+ `Expected hermes-agent config path to start with /custom/hermes, got: ${configPath}`
+ );
+ });
+});
diff --git a/tests/unit/db-backups-skills-3500.test.ts b/tests/unit/db-backups-skills-3500.test.ts
new file mode 100644
index 0000000000..a2f0118ab2
--- /dev/null
+++ b/tests/unit/db-backups-skills-3500.test.ts
@@ -0,0 +1,236 @@
+/**
+ * #3500 slice 5 — skills UPDATE + db-backups SQL extracted into db modules
+ * (Hard Rule #5).
+ *
+ * Seeds a temp SQLite DB and asserts:
+ * 1. updateSkill applies a patch correctly (allowed columns), including the
+ * co-update of `mode` when only `enabled` is provided (legacy sync logic).
+ * 2. updateSkill ignores unknown columns (allowlist guard — injection-safe).
+ * 3. exportAllSummaryRows returns seeded rows from key_value / combos /
+ * provider_connections / api_keys.
+ * 4. getTableNamesFromAdapter returns table names from an adapter.
+ * 5. countImportedRows returns correct counts from the live DB.
+ *
+ * DB handles are released in test.after to prevent the Node native runner from
+ * hanging indefinitely (CLAUDE.md PII/Stream Learnings #3).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-db-backups-skills-3500-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const skillsMod = await import("../../src/lib/db/skills.ts");
+const backupMod = await import("../../src/lib/db/backup.ts");
+
+// ──────────────── Helpers ────────────────
+
+function uniqueId(prefix = "test") {
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
+}
+
+/** Insert a minimal skills row directly (bypasses the module under test). */
+function seedSkill(overrides: Partial<Record<string, unknown>> = {}) {
+ const db = core.getDbInstance();
+ const id = uniqueId("skill");
+ db.prepare(
+ `INSERT INTO skills
+ (id, api_key_id, name, version, description, schema, handler, enabled, mode)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ ).run(
+ overrides.id ?? id,
+ overrides.api_key_id ?? "key-1",
+ overrides.name ?? "test-skill",
+ overrides.version ?? "1.0.0",
+ overrides.description ?? "desc",
+ overrides.schema ?? "{}",
+ overrides.handler ?? "handler",
+ overrides.enabled ?? 1,
+ overrides.mode ?? "auto"
+ );
+ return (overrides.id as string) ?? id;
+}
+
+// ──────────────── updateSkill ────────────────
+
+test("updateSkill — patches enabled+mode, updates updated_at", () => {
+ const id = seedSkill({ enabled: 1, mode: "auto" });
+
+ // Act
+ const changed = skillsMod.updateSkill(id, { enabled: 0, mode: "off" });
+
+ assert.equal(changed, 1, "should affect 1 row");
+
+ const db = core.getDbInstance();
+ const row = db.prepare("SELECT enabled, mode FROM skills WHERE id = ?").get(id) as {
+ enabled: number;
+ mode: string;
+ };
+ assert.equal(row.enabled, 0);
+ assert.equal(row.mode, "off");
+});
+
+test("updateSkill — only mode provided keeps enabled consistent", () => {
+ const id = seedSkill({ enabled: 0, mode: "off" });
+
+ skillsMod.updateSkill(id, { mode: "on" });
+
+ const db = core.getDbInstance();
+ const row = db.prepare("SELECT enabled, mode FROM skills WHERE id = ?").get(id) as {
+ enabled: number;
+ mode: string;
+ };
+ assert.equal(row.mode, "on");
+});
+
+test("updateSkill — unknown columns are silently ignored (allowlist guard)", () => {
+ const id = seedSkill({ enabled: 1, mode: "auto" });
+
+ // Inject an unknown key; this must NOT throw or produce SQL with an injected column.
+ const patch = { enabled: 0, "'; DROP TABLE skills; --": 1 } as Record<string, unknown>;
+ // Cast via any to bypass TS type — testing the runtime allowlist
+ const changed = skillsMod.updateSkill(id, patch as Parameters<typeof skillsMod.updateSkill>[1]);
+ assert.equal(changed, 1, "should still apply the known field");
+
+ const db = core.getDbInstance();
+ const tableExists = db
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='skills'")
+ .get();
+ assert.ok(tableExists, "skills table must still exist after attempted injection");
+});
+
+test("updateSkill — empty patch (all unknown columns) returns 0 changes", () => {
+ const id = seedSkill();
+ const patch = { unknownField: "x" } as Parameters<typeof skillsMod.updateSkill>[1];
+ const changed = skillsMod.updateSkill(id, patch);
+ assert.equal(changed, 0);
+});
+
+test("updateSkill — non-existent id returns 0 changes", () => {
+ const changed = skillsMod.updateSkill("non-existent-id", { enabled: 1 });
+ assert.equal(changed, 0);
+});
+
+// ──────────────── exportAllSummaryRows ────────────────
+
+test("exportAllSummaryRows — returns key_value rows", () => {
+ const db = core.getDbInstance();
+ // key_value schema: namespace TEXT, key TEXT, value TEXT — PK is (namespace, key)
+ db.prepare("INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)").run(
+ "settings",
+ "test.export.key",
+ "hello-value"
+ );
+
+ const { settings } = backupMod.exportAllSummaryRows();
+
+ // exportAllSummaryRows does "SELECT key, value FROM key_value" (all namespaces)
+ assert.equal(settings["test.export.key"], "hello-value", "settings must contain seeded key");
+});
+
+test("exportAllSummaryRows — returns combos rows", () => {
+ const db = core.getDbInstance();
+ const comboId = uniqueId("combo");
+ const now = new Date().toISOString();
+ // combos schema: id, name, data, created_at, updated_at (sort_order optional)
+ db.prepare(
+ `INSERT INTO combos (id, name, data, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`
+ ).run(comboId, "export-test-combo", "{}", now, now);
+
+ const { combos } = backupMod.exportAllSummaryRows();
+
+ assert.ok(
+ (combos as Array<{ id: string }>).some((c) => c.id === comboId),
+ "combos must include seeded row"
+ );
+});
+
+test("exportAllSummaryRows — returns provider_connections rows (no credentials)", () => {
+ const db = core.getDbInstance();
+ const connId = uniqueId("conn");
+ const now = new Date().toISOString();
+ db.prepare(
+ `INSERT INTO provider_connections
+ (id, provider, name, auth_type, is_active, email, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
+ ).run(connId, "openai", "My Key", "api_key", 1, "[email protected]", now, now);
+
+ const { providers } = backupMod.exportAllSummaryRows();
+
+ const found = (providers as Array<{ id: string; provider: string }>).find(
+ (p) => p.id === connId
+ );
+ assert.ok(found, "providers must include seeded row");
+ assert.equal(found?.provider, "openai");
+ // Sensitive credential columns must NOT be exported — the query only selects
+ // id, provider, name, auth_type, is_active, email, created_at.
+ assert.ok(!("api_key" in (found as object)), "api_key column must not be exported");
+ assert.ok(!("oauth_token" in (found as object)), "oauth_token column must not be exported");
+});
+
+test("exportAllSummaryRows — returns api_keys rows (masked prefix only)", () => {
+ const db = core.getDbInstance();
+ const keyId = uniqueId("apikey");
+ const fullKey = "sk-supersecretvalue123456";
+ // api_keys schema: id, name, key, machine_id, created_at
+ db.prepare(
+ `INSERT INTO api_keys (id, name, key, created_at)
+ VALUES (?, ?, ?, datetime('now'))`
+ ).run(keyId, "export-test-key", fullKey);
+
+ const { apiKeys } = backupMod.exportAllSummaryRows();
+
+ const found = (apiKeys as Array<{ id: string; prefix?: string }>).find((k) => k.id === keyId);
+ assert.ok(found, "apiKeys must include seeded row");
+ assert.equal(found?.prefix, fullKey.slice(0, 8), "only the first 8 chars must be exported");
+ assert.ok(!("key" in (found as object)), "full key column must not be exported");
+});
+
+// ──────────────── getTableNamesFromAdapter ────────────────
+
+test("getTableNamesFromAdapter — returns table names from the live db adapter", () => {
+ // Use the live db instance (which has been initialized with all migrations)
+ // cast to the minimal interface the function requires.
+ const db = core.getDbInstance() as {
+ prepare: (sql: string) => { all: () => unknown[] };
+ };
+ const tables = backupMod.getTableNamesFromAdapter(db);
+
+ assert.ok(Array.isArray(tables), "must return an array");
+ assert.ok(tables.includes("skills"), "skills table must be present");
+ assert.ok(tables.includes("combos"), "combos table must be present");
+ assert.ok(tables.includes("provider_connections"), "provider_connections must be present");
+ assert.ok(tables.includes("api_keys"), "api_keys must be present");
+});
+
+// ──────────────── countImportedRows ────────────────
+
+test("countImportedRows — returns correct non-negative counts", () => {
+ const counts = backupMod.countImportedRows();
+
+ // Counts must be non-negative integers (we can't assert exact values since
+ // other tests may have inserted rows, but we verify the shape).
+ assert.ok(typeof counts.connCount === "number" && counts.connCount >= 0);
+ assert.ok(typeof counts.nodeCount === "number" && counts.nodeCount >= 0);
+ assert.ok(typeof counts.comboCount === "number" && counts.comboCount >= 0);
+ assert.ok(typeof counts.keyCount === "number" && counts.keyCount >= 0);
+});
+
+// ──────────────── Teardown ────────────────
+
+test.after(() => {
+ try {
+ core.resetDbInstance();
+ } catch {
+ /* best effort */
+ }
+ try {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ } catch {
+ /* best effort */
+ }
+});
diff --git a/tests/unit/db-call-log-stats-3500.test.ts b/tests/unit/db-call-log-stats-3500.test.ts
new file mode 100644
index 0000000000..5240ea97f4
--- /dev/null
+++ b/tests/unit/db-call-log-stats-3500.test.ts
@@ -0,0 +1,262 @@
+/**
+ * #3500 — call_logs aggregation functions extracted into callLogStats.ts (Hard Rule #5).
+ *
+ * Seeds an in-memory temp SQLite DB and asserts each new db function returns the
+ * correct aggregation. DB handles are released in test.after to prevent Node
+ * native test runner from hanging (CLAUDE.md PII/Stream Learnings #3).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-db-callogstats-3500-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const mod = await import("../../src/lib/db/callLogStats.ts");
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+let _idSeq = 0;
+function insertCallLog(row: Record<string, unknown>) {
+ const db = core.getDbInstance();
+ const full = {
+ method: "POST",
+ path: "/v1/chat/completions",
+ status: 200,
+ model: "openai/gpt-4.1",
+ requested_model: null,
+ provider: "openai",
+ account: null,
+ connection_id: null,
+ duration: 100,
+ tokens_in: 10,
+ tokens_out: 20,
+ cache_source: "upstream",
+ source_format: null,
+ target_format: null,
+ api_key_id: null,
+ api_key_name: null,
+ combo_name: null,
+ combo_step_id: null,
+ combo_execution_key: null,
+ error_summary: null,
+ detail_state: "none",
+ artifact_relpath: null,
+ artifact_size_bytes: null,
+ artifact_sha256: null,
+ has_request_body: 0,
+ has_response_body: 0,
+ has_pipeline_details: 0,
+ request_summary: null,
+ request_type: null,
+ ...row,
+ id: row.id ?? `log-3500-${++_idSeq}`,
+ timestamp: row.timestamp ?? new Date().toISOString(),
+ };
+ db.prepare(
+ `INSERT INTO call_logs (
+ id, timestamp, method, path, status, model, requested_model, provider, account,
+ connection_id, duration, tokens_in, tokens_out, cache_source, source_format, target_format,
+ api_key_id, api_key_name, combo_name, combo_step_id, combo_execution_key,
+ error_summary, detail_state, artifact_relpath, artifact_size_bytes, artifact_sha256,
+ has_request_body, has_response_body, has_pipeline_details, request_summary, request_type
+ ) VALUES (
+ @id, @timestamp, @method, @path, @status, @model, @requested_model, @provider, @account,
+ @connection_id, @duration, @tokens_in, @tokens_out, @cache_source, @source_format, @target_format,
+ @api_key_id, @api_key_name, @combo_name, @combo_step_id, @combo_execution_key,
+ @error_summary, @detail_state, @artifact_relpath, @artifact_size_bytes, @artifact_sha256,
+ @has_request_body, @has_response_body, @has_pipeline_details, @request_summary, @request_type
+ )`
+ ).run(full);
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+test.before(() => {
+ core.resetDbInstance();
+});
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ---------------------------------------------------------------------------
+// getProviderMetrics
+// ---------------------------------------------------------------------------
+
+test("#3500 getProviderMetrics — aggregates totals and latency per provider", () => {
+ // Two openai rows: one success, one error with error_summary
+ const ts1 = "2025-06-01T10:00:00.000Z";
+ const ts2 = "2025-06-01T11:00:00.000Z";
+ insertCallLog({ provider: "openai", status: 200, duration: 100, timestamp: ts1 });
+ insertCallLog({
+ provider: "openai",
+ status: 500,
+ duration: 300,
+ error_summary: "upstream error",
+ timestamp: ts2,
+ });
+ // One anthropic success row
+ const ts3 = "2025-06-01T09:00:00.000Z";
+ insertCallLog({ provider: "anthropic", status: 200, duration: 50, timestamp: ts3 });
+ // Provider '-' should be excluded
+ insertCallLog({ provider: "-", status: 200 });
+ // Provider null should be excluded (insert directly to avoid type issue)
+ core.getDbInstance().prepare(
+ `INSERT INTO call_logs (id, timestamp, method, path, status, model, provider, duration,
+ tokens_in, tokens_out, cache_source, detail_state, has_request_body, has_response_body, has_pipeline_details)
+ VALUES (?, ?, 'POST', '/v1/test', 200, 'x', NULL, 100, 0, 0, 'upstream', 'none', 0, 0, 0)`
+ ).run(`log-3500-null-${++_idSeq}`, new Date().toISOString());
+
+ const rows = mod.getProviderMetrics();
+
+ // '-' and null providers must not appear
+ assert.ok(!rows.some((r) => r.provider === "-"), "provider '-' excluded");
+ assert.ok(!rows.some((r) => r.provider === null), "null provider excluded");
+
+ const openai = rows.find((r) => r.provider === "openai");
+ assert.ok(openai, "openai row present");
+ assert.equal(openai.totalRequests, 2);
+ assert.equal(openai.totalSuccesses, 1); // only the 200
+ assert.equal(openai.avgLatencyMs, 200); // ROUND((100+300)/2) = 200
+ assert.equal(openai.lastRequestAt, ts2, "lastRequestAt = most recent ts");
+ assert.equal(openai.lastErrorAt, ts2, "lastErrorAt = ts of the 500/error row");
+ assert.equal(openai.lastStatus, 500, "lastStatus = most recent status");
+ assert.equal(openai.lastErrorStatus, 500, "lastErrorStatus = most recent error status");
+
+ const anthropic = rows.find((r) => r.provider === "anthropic");
+ assert.ok(anthropic, "anthropic row present");
+ assert.equal(anthropic.totalRequests, 1);
+ assert.equal(anthropic.totalSuccesses, 1);
+ assert.equal(anthropic.lastErrorAt, null, "no error row → lastErrorAt is null");
+ assert.equal(anthropic.lastStatus, 200);
+ assert.equal(anthropic.lastErrorStatus, null, "no error → lastErrorStatus is null");
+});
+
+// ---------------------------------------------------------------------------
+// getSearchProviderStats
+// ---------------------------------------------------------------------------
+
+test("#3500 getSearchProviderStats — aggregates search requests per provider", () => {
+ insertCallLog({ provider: "brave", status: 200, duration: 50, request_type: "search" });
+ insertCallLog({ provider: "brave", status: 200, duration: 150, request_type: "search" });
+ insertCallLog({ provider: "serper", status: 200, duration: 80, request_type: "search" });
+ // non-search row — must NOT appear
+ insertCallLog({ provider: "openai", status: 200, duration: 100, request_type: null });
+
+ const rows = mod.getSearchProviderStats();
+
+ // Only search request_type rows
+ assert.ok(!rows.some((r) => r.provider === "openai"), "non-search row excluded");
+
+ const brave = rows.find((r) => r.provider === "brave");
+ assert.ok(brave, "brave row present");
+ assert.equal(brave.requests, 2);
+ assert.equal(brave.avg_latency_ms, 100); // CAST(AVG(50,150) AS INTEGER) = 100
+
+ const serper = rows.find((r) => r.provider === "serper");
+ assert.ok(serper, "serper row present");
+ assert.equal(serper.requests, 1);
+});
+
+// ---------------------------------------------------------------------------
+// getRecentSearchLogs
+// ---------------------------------------------------------------------------
+
+test("#3500 getRecentSearchLogs — returns up to 10 most recent search rows", () => {
+ // Insert 12 search rows with incrementing timestamps
+ for (let i = 1; i <= 12; i++) {
+ const ts = new Date(Date.UTC(2025, 5, i, 12, 0, 0)).toISOString();
+ insertCallLog({
+ provider: "brave",
+ status: 200,
+ request_type: "search",
+ timestamp: ts,
+ request_summary: JSON.stringify({ query: `q${i}` }),
+ });
+ }
+
+ const rows = mod.getRecentSearchLogs();
+ assert.equal(rows.length, 10, "limited to 10 rows");
+ // Most recent first (i=12 is the newest)
+ assert.ok(rows[0].timestamp >= rows[rows.length - 1].timestamp, "ordered newest-first");
+});
+
+// ---------------------------------------------------------------------------
+// getSearchAggregateStats
+// ---------------------------------------------------------------------------
+
+test("#3500 getSearchAggregateStats — correct totals, today, errors, avg, cached", () => {
+ const todayStart = new Date();
+ todayStart.setUTCHours(0, 0, 0, 0);
+ const todayIso = todayStart.toISOString();
+
+ // Rows inserted after todayStart qualify as "today"
+ const nowIso = new Date().toISOString();
+ // duration=0 → excluded from avg_duration; duration=3 → cached (>0 && <5)
+ insertCallLog({ provider: "brave", status: 200, duration: 100, request_type: "search", timestamp: nowIso });
+ insertCallLog({ provider: "brave", status: 200, duration: 3, request_type: "search", timestamp: nowIso });
+ insertCallLog({ provider: "brave", status: 500, duration: 80, request_type: "search", timestamp: nowIso });
+ // Old row (yesterday) — not in today count
+ const yesterday = new Date(Date.now() - 86_400_000).toISOString();
+ insertCallLog({ provider: "brave", status: 200, duration: 200, request_type: "search", timestamp: yesterday });
+
+ const result = mod.getSearchAggregateStats(todayIso);
+
+ assert.ok(result.total >= 4, "total includes all search rows (across all tests in file)");
+ assert.ok(result.today >= 3, "today counts rows from today");
+ assert.ok(result.errors >= 1, "errors counts status >= 400");
+ assert.ok(result.cached >= 1, "cached counts duration in (0,5)");
+ assert.ok(result.avg_duration !== null, "avg_duration not null when rows have duration > 0");
+});
+
+test("#3500 getSearchAggregateStats — returns zero struct when no search rows match", () => {
+ // Use a far-future todayIso so no row qualifies
+ const farFuture = "2999-01-01T00:00:00.000Z";
+ const result = mod.getSearchAggregateStats(farFuture);
+ // total should be 0 (no rows WHERE request_type='search' AND timestamp >= 2999…)
+ // Actually the total counts ALL search rows regardless of todayIso; only "today" is gated.
+ // The function never returns null, so we just check the shape.
+ assert.equal(typeof result.total, "number");
+ assert.equal(typeof result.today, "number");
+ assert.equal(result.today, 0, "no rows qualify as 'today' in far future");
+});
+
+// ---------------------------------------------------------------------------
+// getSearchProviderCounts
+// ---------------------------------------------------------------------------
+
+test("#3500 getSearchProviderCounts — ordered by cnt desc", () => {
+ // brave has multiple rows from earlier tests; add a burst to ensure ordering
+ for (let i = 0; i < 5; i++) {
+ insertCallLog({ provider: "bing", status: 200, request_type: "search" });
+ }
+ for (let i = 0; i < 2; i++) {
+ insertCallLog({ provider: "rare_provider", status: 200, request_type: "search" });
+ }
+
+ const rows = mod.getSearchProviderCounts();
+ // Each row must have provider + cnt
+ for (const row of rows) {
+ assert.equal(typeof row.provider, "string");
+ assert.equal(typeof row.cnt, "number");
+ }
+ // First row should have count >= last row (ordered desc)
+ if (rows.length >= 2) {
+ assert.ok(rows[0].cnt >= rows[rows.length - 1].cnt, "ordered by cnt desc");
+ }
+ // bing (5 added) should beat rare_provider (2 added) if both appear
+ const bing = rows.find((r) => r.provider === "bing");
+ const rare = rows.find((r) => r.provider === "rare_provider");
+ if (bing && rare) {
+ assert.ok(bing.cnt > rare.cnt, "bing cnt > rare_provider cnt");
+ }
+});
diff --git a/tests/unit/db-gamification-federation-3500.test.ts b/tests/unit/db-gamification-federation-3500.test.ts
new file mode 100644
index 0000000000..5fd1876fec
--- /dev/null
+++ b/tests/unit/db-gamification-federation-3500.test.ts
@@ -0,0 +1,81 @@
+/**
+ * tests/unit/db-gamification-federation-3500.test.ts
+ *
+ * TDD regression for #3500 slice 3: getConnectedServerByKeyHash extracted from
+ * gamification federation routes into src/lib/db/gamification.ts.
+ *
+ * Seeding a temp SQLite DB with community_servers rows, exercising
+ * getConnectedServerByKeyHash for hit/miss/status-filter cases.
+ *
+ * PII-Learnings #3: resetDbInstance() + close handles in test.after to avoid hang.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Set temp DATA_DIR BEFORE importing any db module
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-gamif-fed-3500-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const gamifDb = await import("../../src/lib/db/gamification.ts");
+
+// Seed a connected and a disconnected server row for use across assertions.
+function seedServers() {
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT OR REPLACE INTO community_servers (id, name, url, api_key_hash, status)
+ VALUES (?, ?, ?, ?, ?)`
+ ).run("srv-connected", "Connected Server", "https://connected.example", "hash-connected", "connected");
+ db.prepare(
+ `INSERT OR REPLACE INTO community_servers (id, name, url, api_key_hash, status)
+ VALUES (?, ?, ?, ?, ?)`
+ ).run("srv-disconnected", "Disconnected Server", "https://disconnected.example", "hash-disconnected", "disconnected");
+}
+
+test.after(async () => {
+ core.resetDbInstance();
+ await new Promise<void>((resolve) => {
+ // Brief retry loop in case the file is briefly locked
+ const tryRm = (attempts: number) => {
+ try {
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ resolve();
+ } catch (err: any) {
+ if ((err?.code === "EBUSY" || err?.code === "EPERM") && attempts > 0) {
+ setTimeout(() => tryRm(attempts - 1), 50);
+ } else {
+ resolve(); // best-effort, do not hang
+ }
+ }
+ };
+ tryRm(10);
+ });
+});
+
+test("getConnectedServerByKeyHash returns the id for a connected server", () => {
+ seedServers();
+ const result = gamifDb.getConnectedServerByKeyHash("hash-connected");
+ assert.ok(result, "should find the connected server");
+ assert.equal(result.id, "srv-connected");
+});
+
+test("getConnectedServerByKeyHash returns undefined for an unknown hash", () => {
+ seedServers();
+ const result = gamifDb.getConnectedServerByKeyHash("hash-does-not-exist");
+ assert.equal(result, undefined, "should return undefined for unknown hash");
+});
+
+test("getConnectedServerByKeyHash returns undefined for a disconnected server (status filter)", () => {
+ seedServers();
+ const result = gamifDb.getConnectedServerByKeyHash("hash-disconnected");
+ assert.equal(
+ result,
+ undefined,
+ "should not return a server whose status is not 'connected'"
+ );
+});
diff --git a/tests/unit/db-logs-cache-3500.test.ts b/tests/unit/db-logs-cache-3500.test.ts
new file mode 100644
index 0000000000..6377bbe3d0
--- /dev/null
+++ b/tests/unit/db-logs-cache-3500.test.ts
@@ -0,0 +1,348 @@
+/**
+ * #3500 — usage_logs / semantic_cache / proxy_logs SQL extracted into db modules
+ * (Hard Rule #5, slice 4).
+ *
+ * Seeds an in-memory temp SQLite DB for each table and asserts each new db
+ * function returns the correct rows / counts. DB handles are released in
+ * test.after to prevent Node native test runner from hanging
+ * (CLAUDE.md PII/Stream Learnings #3).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-db-logs-cache-3500-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const usageLogs = await import("../../src/lib/db/usageLogs.ts");
+const semanticCache = await import("../../src/lib/db/semanticCache.ts");
+const proxyLogs = await import("../../src/lib/db/proxyLogs.ts");
+
+// ---------------------------------------------------------------------------
+// Helpers — usage_logs seeding
+// usage_logs is NOT in the core.ts schema; create it as a lightweight table
+// mirroring the columns used by the auto-routing queries (model, provider).
+// ---------------------------------------------------------------------------
+
+function ensureUsageLogsTable() {
+ const db = core.getDbInstance();
+ db.prepare(
+ `CREATE TABLE IF NOT EXISTS usage_logs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ model TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ timestamp TEXT NOT NULL
+ )`
+ ).run();
+}
+
+function insertUsageLog(row: { model: string; provider: string }) {
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT INTO usage_logs (model, provider, timestamp) VALUES (?, ?, ?)`
+ ).run(row.model, row.provider, new Date().toISOString());
+}
+
+// ---------------------------------------------------------------------------
+// Helpers — semantic_cache seeding
+// ---------------------------------------------------------------------------
+
+function insertSemanticCache(row: {
+ id: string;
+ signature: string;
+ model: string;
+ hit_count?: number;
+ tokens_saved?: number;
+}) {
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT INTO semantic_cache
+ (id, signature, model, prompt_hash, response, tokens_saved, hit_count, created_at, expires_at)
+ VALUES
+ (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now', '+1 hour'))`
+ ).run(
+ row.id,
+ row.signature,
+ row.model,
+ "hash_" + row.id,
+ "{}",
+ row.tokens_saved ?? 0,
+ row.hit_count ?? 0,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Helpers — proxy_logs seeding
+// ---------------------------------------------------------------------------
+
+function insertProxyLog(row: { id: string; timestamp: string; provider?: string }) {
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT INTO proxy_logs (id, timestamp, provider, status, proxy_type) VALUES (?, ?, ?, ?, ?)`
+ ).run(row.id, row.timestamp, row.provider ?? "openai", "ok", "http");
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+test.before(() => {
+ core.resetDbInstance();
+ ensureUsageLogsTable();
+});
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ===========================================================================
+// usageLogs — getAutoRoutingTotalCount
+// ===========================================================================
+
+test("#3500 getAutoRoutingTotalCount — returns 0 when no rows", () => {
+ const result = usageLogs.getAutoRoutingTotalCount();
+ assert.equal(result.count, 0);
+});
+
+test("#3500 getAutoRoutingTotalCount — counts auto and auto/* models", () => {
+ insertUsageLog({ model: "auto", provider: "openai" });
+ insertUsageLog({ model: "auto/fast", provider: "anthropic" });
+ insertUsageLog({ model: "gpt-4", provider: "openai" }); // must NOT be counted
+
+ const result = usageLogs.getAutoRoutingTotalCount();
+ assert.ok(result.count >= 2, `expected >= 2, got ${result.count}`);
+});
+
+// ===========================================================================
+// usageLogs — getAutoRoutingVariantBreakdown
+// ===========================================================================
+
+test("#3500 getAutoRoutingVariantBreakdown — maps auto → default, auto/X → X", () => {
+ // Insert another auto and auto/fast to have stable counts
+ insertUsageLog({ model: "auto", provider: "openai" });
+ insertUsageLog({ model: "auto/fast", provider: "anthropic" });
+
+ const rows = usageLogs.getAutoRoutingVariantBreakdown();
+ const byVariant: Record<string, number> = {};
+ for (const r of rows) byVariant[r.variant] = r.count;
+
+ assert.ok("default" in byVariant, "should have a 'default' variant for bare 'auto'");
+ assert.ok("fast" in byVariant, "should have a 'fast' variant for 'auto/fast'");
+ assert.ok(byVariant["default"] >= 1, "default count >= 1");
+ assert.ok(byVariant["fast"] >= 1, "fast count >= 1");
+});
+
+// ===========================================================================
+// usageLogs — getAutoRoutingTopProviders
+// ===========================================================================
+
+test("#3500 getAutoRoutingTopProviders — returns top providers for auto/* models", () => {
+ const rows = usageLogs.getAutoRoutingTopProviders();
+ assert.ok(Array.isArray(rows), "result is array");
+ assert.ok(rows.length > 0, "at least one provider row");
+ for (const r of rows) {
+ assert.equal(typeof r.provider, "string");
+ assert.equal(typeof r.count, "number");
+ }
+ // Should be ordered descending by count (first row has highest count)
+ if (rows.length > 1) {
+ assert.ok(rows[0].count >= rows[1].count, "ordered descending by count");
+ }
+});
+
+// ===========================================================================
+// semanticCache — listSemanticCacheEntries
+// ===========================================================================
+
+test("#3500 listSemanticCacheEntries — returns entries with pagination", () => {
+ insertSemanticCache({ id: "sc-1", signature: "sig-alpha", model: "gpt-4", hit_count: 5 });
+ insertSemanticCache({ id: "sc-2", signature: "sig-beta", model: "claude-3", hit_count: 2 });
+ insertSemanticCache({ id: "sc-3", signature: "sig-gamma", model: "gpt-4", hit_count: 1 });
+
+ const result = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 10,
+ search: "",
+ model: "",
+ sortBy: "hit_count",
+ sortOrder: "desc",
+ });
+
+ assert.ok(result.total >= 3, `total >= 3, got ${result.total}`);
+ assert.ok(result.entries.length >= 3, "at least 3 entries returned");
+
+ // First entry should have highest hit_count (sorted desc)
+ if (result.entries.length >= 2) {
+ assert.ok(
+ result.entries[0].hit_count >= result.entries[1].hit_count,
+ "sorted desc by hit_count"
+ );
+ }
+});
+
+test("#3500 listSemanticCacheEntries — search filter narrows results", () => {
+ const result = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 10,
+ search: "sig-alpha",
+ model: "",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+
+ assert.ok(result.total >= 1, "should find at least 1 matching entry");
+ assert.ok(
+ result.entries.some((e) => e.signature === "sig-alpha"),
+ "sig-alpha in results"
+ );
+});
+
+test("#3500 listSemanticCacheEntries — model filter works", () => {
+ const result = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 10,
+ search: "",
+ model: "claude-3",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+
+ assert.ok(result.total >= 1, "at least 1 claude-3 entry");
+ for (const e of result.entries) {
+ assert.equal(e.model, "claude-3", "all entries are claude-3");
+ }
+});
+
+test("#3500 listSemanticCacheEntries — pagination offset works", () => {
+ const p1 = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 2,
+ search: "",
+ model: "",
+ sortBy: "created_at",
+ sortOrder: "asc",
+ });
+ const p2 = semanticCache.listSemanticCacheEntries({
+ page: 2,
+ limit: 2,
+ search: "",
+ model: "",
+ sortBy: "created_at",
+ sortOrder: "asc",
+ });
+
+ if (p1.entries.length > 0 && p2.entries.length > 0) {
+ assert.notEqual(
+ p1.entries[0].id,
+ p2.entries[0].id,
+ "page 1 and page 2 must not have the same first entry"
+ );
+ }
+});
+
+// ===========================================================================
+// semanticCache — deleteSemanticCacheBySignature
+// ===========================================================================
+
+test("#3500 deleteSemanticCacheBySignature — deletes exactly the matching entry", () => {
+ insertSemanticCache({ id: "sc-del-sig", signature: "sig-to-delete", model: "gpt-4" });
+
+ // Verify it exists first
+ const before = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 100,
+ search: "sig-to-delete",
+ model: "",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+ assert.ok(before.total >= 1, "entry exists before delete");
+
+ const result = semanticCache.deleteSemanticCacheBySignature("sig-to-delete");
+ assert.equal(result.deleted, 1);
+
+ const after = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 100,
+ search: "sig-to-delete",
+ model: "",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+ assert.equal(after.total, 0, "entry removed after delete");
+});
+
+// ===========================================================================
+// semanticCache — deleteSemanticCacheByModel
+// ===========================================================================
+
+test("#3500 deleteSemanticCacheByModel — deletes all entries for the given model", () => {
+ insertSemanticCache({ id: "sc-m1", signature: "sig-model-a-1", model: "model-to-purge" });
+ insertSemanticCache({ id: "sc-m2", signature: "sig-model-a-2", model: "model-to-purge" });
+
+ const before = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 100,
+ search: "",
+ model: "model-to-purge",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+ assert.ok(before.total >= 2, "2 entries before delete");
+
+ const result = semanticCache.deleteSemanticCacheByModel("model-to-purge");
+ assert.ok(result.deleted >= 2, `deleted >= 2, got ${result.deleted}`);
+
+ const after = semanticCache.listSemanticCacheEntries({
+ page: 1,
+ limit: 100,
+ search: "",
+ model: "model-to-purge",
+ sortBy: "created_at",
+ sortOrder: "desc",
+ });
+ assert.equal(after.total, 0, "no entries remain after delete");
+});
+
+// ===========================================================================
+// proxyLogs — exportProxyLogsSince
+// ===========================================================================
+
+test("#3500 exportProxyLogsSince — returns rows with timestamp >= since", () => {
+ const base = new Date("2025-01-15T10:00:00.000Z");
+ const old = new Date("2025-01-14T10:00:00.000Z");
+
+ insertProxyLog({ id: "pl-new-1", timestamp: new Date("2025-01-15T11:00:00.000Z").toISOString(), provider: "openai" });
+ insertProxyLog({ id: "pl-new-2", timestamp: new Date("2025-01-15T12:00:00.000Z").toISOString(), provider: "anthropic" });
+ insertProxyLog({ id: "pl-old-1", timestamp: old.toISOString(), provider: "openai" }); // outside window
+
+ const rows = proxyLogs.exportProxyLogsSince(base.toISOString());
+
+ assert.ok(Array.isArray(rows), "result is array");
+ const ids = rows.map((r) => (r as { id: string }).id);
+ assert.ok(ids.includes("pl-new-1"), "pl-new-1 included");
+ assert.ok(ids.includes("pl-new-2"), "pl-new-2 included");
+ assert.ok(!ids.includes("pl-old-1"), "pl-old-1 excluded (before since)");
+});
+
+test("#3500 exportProxyLogsSince — results are ordered descending by timestamp", () => {
+ const rows = proxyLogs.exportProxyLogsSince(new Date("2025-01-01T00:00:00.000Z").toISOString());
+ assert.ok(rows.length >= 2, "at least 2 rows");
+
+ // Verify descending order
+ for (let i = 1; i < rows.length; i++) {
+ const prev = (rows[i - 1] as { timestamp: string }).timestamp;
+ const curr = (rows[i] as { timestamp: string }).timestamp;
+ assert.ok(prev >= curr, `row ${i - 1} timestamp (${prev}) >= row ${i} (${curr})`);
+ }
+});
+
+test("#3500 exportProxyLogsSince — returns empty array when no rows match", () => {
+ const future = new Date(Date.now() + 86_400_000 * 365).toISOString();
+ const rows = proxyLogs.exportProxyLogsSince(future);
+ assert.deepEqual(rows, []);
+});
diff --git a/tests/unit/db-usage-analytics-3500.test.ts b/tests/unit/db-usage-analytics-3500.test.ts
new file mode 100644
index 0000000000..4157dd2866
--- /dev/null
+++ b/tests/unit/db-usage-analytics-3500.test.ts
@@ -0,0 +1,573 @@
+/**
+ * #3500 — usage_history / daily_usage_summary aggregation functions extracted
+ * into usageAnalytics.ts (Hard Rule #5, slice 2).
+ *
+ * Seeds an in-memory temp SQLite DB and asserts each new db function returns the
+ * correct aggregation. DB handles are released in test.after to prevent Node
+ * native test runner from hanging (CLAUDE.md PII/Stream Learnings #3).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-db-usageanalytics-3500-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const mod = await import("../../src/lib/db/usageAnalytics.ts");
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+let _idSeq = 0;
+
+function insertUsageHistory(row: Record<string, unknown>) {
+ const db = core.getDbInstance();
+ const full = {
+ provider: "openai",
+ model: "gpt-4.1",
+ tokens_input: 10,
+ tokens_output: 20,
+ tokens_cache_read: 0,
+ tokens_cache_creation: 0,
+ tokens_reasoning: 0,
+ service_tier: "standard",
+ success: 1,
+ latency_ms: 100,
+ connection_id: null,
+ api_key_id: null,
+ api_key_name: null,
+ ...row,
+ timestamp: row.timestamp ?? new Date().toISOString(),
+ };
+ // id is AUTOINCREMENT — omit it to let SQLite assign it
+ db.prepare(
+ `INSERT INTO usage_history (
+ timestamp, provider, model,
+ tokens_input, tokens_output, tokens_cache_read, tokens_cache_creation, tokens_reasoning,
+ service_tier, success, latency_ms, connection_id, api_key_id, api_key_name
+ ) VALUES (
+ @timestamp, @provider, @model,
+ @tokens_input, @tokens_output, @tokens_cache_read, @tokens_cache_creation, @tokens_reasoning,
+ @service_tier, @success, @latency_ms, @connection_id, @api_key_id, @api_key_name
+ )`
+ ).run(full);
+}
+
+function insertDailyUsageSummary(row: Record<string, unknown>) {
+ const db = core.getDbInstance();
+ const full = {
+ provider: "openai",
+ model: "gpt-4.1",
+ total_input_tokens: 100,
+ total_output_tokens: 200,
+ total_requests: 5,
+ total_cost: 0.0,
+ ...row,
+ date: row.date ?? "2024-01-01",
+ };
+ // id is AUTOINCREMENT — omit it to let SQLite assign it
+ db.prepare(
+ `INSERT INTO daily_usage_summary (
+ date, provider, model, total_input_tokens, total_output_tokens, total_requests, total_cost
+ ) VALUES (
+ @date, @provider, @model, @total_input_tokens, @total_output_tokens, @total_requests, @total_cost
+ )`
+ ).run(full);
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+test.before(() => {
+ core.resetDbInstance();
+});
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ---------------------------------------------------------------------------
+// buildUnifiedSource — raw-only branch (no agg needed)
+// ---------------------------------------------------------------------------
+
+test("#3500 buildUnifiedSource — raw-only branch when sinceIso is recent", () => {
+ // A very recent sinceIso means no aggregated rows are needed
+ const recentIso = new Date(Date.now() - 3600_000).toISOString(); // 1 hour ago
+ const today = new Date().toISOString().split("T")[0];
+ const result = mod.buildUnifiedSource({
+ sinceIso: recentIso,
+ untilIso: null,
+ rawCutoffDate: today,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ assert.equal(typeof result.unifiedSource, "string");
+ assert.ok(result.unifiedSource.includes("usage_history"), "source references usage_history");
+ assert.ok(!result.unifiedSource.includes("daily_usage_summary"), "no agg table needed");
+ assert.ok(result.unifiedSource.includes("@since"), "has @since param");
+ assert.ok("since" in result.unifiedParams, "unifiedParams has since key");
+});
+
+// ---------------------------------------------------------------------------
+// buildUnifiedSource — UNION branch (agg needed)
+// ---------------------------------------------------------------------------
+
+test("#3500 buildUnifiedSource — UNION branch when sinceIso is old", () => {
+ // sinceIso must be BEFORE rawCutoffDate to trigger the UNION branch
+ const oldIso = "2024-01-01T00:00:00.000Z"; // sinceIso before rawCutoffDate
+ const rawCutoffDate = "2025-01-01"; // rawCutoffDate after sinceIso → UNION fires
+ const result = mod.buildUnifiedSource({
+ sinceIso: oldIso,
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ assert.ok(result.unifiedSource.includes("usage_history"), "raw leg present");
+ assert.ok(result.unifiedSource.includes("daily_usage_summary"), "agg leg present");
+ assert.ok(result.unifiedSource.includes("UNION ALL"), "UNION ALL present");
+ assert.ok("rawCutoff" in result.unifiedParams, "rawCutoff param present");
+ assert.ok("sinceDate" in result.unifiedParams, "sinceDate param present");
+ assert.ok("rawCutoffDate" in result.unifiedParams, "rawCutoffDate param present");
+});
+
+// ---------------------------------------------------------------------------
+// buildUnifiedSource — api_key filter disables agg leg
+// ---------------------------------------------------------------------------
+
+test("#3500 buildUnifiedSource — api_key filter suppresses daily_usage_summary leg", () => {
+ const oldIso = "2024-01-01T00:00:00.000Z";
+ const rawCutoffDate = "2025-01-01"; // after sinceIso, so UNION would fire without the api_key filter
+ const result = mod.buildUnifiedSource({
+ sinceIso: oldIso,
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere: "(api_key_id IN (@apiKey0))",
+ apiKeyParams: { apiKey0: "key-abc" },
+ });
+
+ assert.ok(!result.unifiedSource.includes("daily_usage_summary"), "agg leg suppressed with api_key filter");
+ assert.ok(result.unifiedSource.includes("usage_history"), "raw leg still present");
+ assert.equal(result.unifiedParams.apiKey0, "key-abc", "apiKey0 propagated");
+});
+
+// ---------------------------------------------------------------------------
+// getUsageSummary
+// ---------------------------------------------------------------------------
+
+test("#3500 getUsageSummary — returns correct scalar aggregations", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = new Date().toISOString();
+
+ insertUsageHistory({ tokens_input: 50, tokens_output: 80, success: 1, latency_ms: 200, timestamp: ts });
+ insertUsageHistory({ tokens_input: 30, tokens_output: 40, success: 0, latency_ms: 400, timestamp: ts });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: null,
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const row = mod.getUsageSummary(unifiedSource, unifiedParams);
+
+ assert.ok(row.totalRequests >= 2, "totalRequests >= 2");
+ assert.ok(row.promptTokens >= 80, "promptTokens >= 80");
+ assert.ok(row.completionTokens >= 120, "completionTokens >= 120");
+ assert.ok(row.totalTokens >= 200, "totalTokens >= 200");
+ assert.ok(row.successfulRequests >= 1, "successfulRequests >= 1");
+ assert.ok(row.avgLatencyMs > 0, "avgLatencyMs > 0");
+ assert.equal(typeof row.firstRequest, "string");
+ assert.equal(typeof row.lastRequest, "string");
+});
+
+// ---------------------------------------------------------------------------
+// getDailyUsage
+// ---------------------------------------------------------------------------
+
+test("#3500 getDailyUsage — groups by date, ascending order", () => {
+ // Use far-future rawCutoffDate so all rows fall in the raw leg (no UNION needed)
+ const rawCutoffDate = "2020-01-01";
+ const day1 = "2025-03-01T12:00:00.000Z";
+ const day2 = "2025-03-02T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: day1, tokens_input: 10, tokens_output: 20 });
+ insertUsageHistory({ timestamp: day1, tokens_input: 5, tokens_output: 10 });
+ insertUsageHistory({ timestamp: day2, tokens_input: 20, tokens_output: 30 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-03-01T00:00:00.000Z",
+ untilIso: "2025-03-02T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getDailyUsage(unifiedSource, unifiedParams);
+
+ const march1 = rows.find((r) => r.date === "2025-03-01");
+ const march2 = rows.find((r) => r.date === "2025-03-02");
+
+ assert.ok(march1, "2025-03-01 row present");
+ assert.ok(march2, "2025-03-02 row present");
+ assert.equal(march1!.requests, 2, "2 requests on march 1");
+ assert.equal(march1!.promptTokens, 15, "promptTokens summed on march 1");
+ assert.equal(march1!.completionTokens, 30, "completionTokens summed on march 1");
+ assert.equal(march1!.totalTokens, 45, "totalTokens summed on march 1");
+});
+
+// ---------------------------------------------------------------------------
+// getDailyCostRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getDailyCostRows — groups by date+provider+model+serviceTier", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-04-01T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "anthropic", model: "claude-3-5-sonnet", tokens_input: 100, tokens_output: 200, service_tier: "priority" });
+ insertUsageHistory({ timestamp: ts, provider: "anthropic", model: "claude-3-5-sonnet", tokens_input: 50, tokens_output: 100, service_tier: "priority" });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-04-01T00:00:00.000Z",
+ untilIso: "2025-04-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getDailyCostRows(unifiedSource, unifiedParams);
+ const row = rows.find((r) => r.provider === "anthropic" && r.model === "claude-3-5-sonnet");
+
+ assert.ok(row, "anthropic/claude row present");
+ assert.equal(row!.date, "2025-04-01");
+ assert.equal(row!.serviceTier, "priority");
+ assert.equal(row!.promptTokens, 150, "promptTokens aggregated");
+ assert.equal(row!.completionTokens, 300, "completionTokens aggregated");
+});
+
+// ---------------------------------------------------------------------------
+// getHeatmapRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getHeatmapRows — groups by date, respects conditions", () => {
+ const ts = "2025-05-15T10:00:00.000Z";
+ insertUsageHistory({ timestamp: ts, tokens_input: 40, tokens_output: 60 });
+
+ const rows = mod.getHeatmapRows(
+ ["timestamp >= @heatmapStart"],
+ { heatmapStart: "2025-05-15T00:00:00.000Z" }
+ );
+
+ const may15 = rows.find((r) => r.date === "2025-05-15");
+ assert.ok(may15, "2025-05-15 row present");
+ assert.ok(may15!.totalTokens >= 100, "totalTokens >= 100 (40+60)");
+});
+
+// ---------------------------------------------------------------------------
+// getModelUsageRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getModelUsageRows — returns per-model aggregates", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-06-01T10:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-5", tokens_input: 100, tokens_output: 200, success: 1, latency_ms: 150 });
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-5", tokens_input: 50, tokens_output: 100, success: 1, latency_ms: 250 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-06-01T00:00:00.000Z",
+ untilIso: "2025-06-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getModelUsageRows(unifiedSource, unifiedParams);
+ const row = rows.find((r) => r.model === "gpt-5" && r.provider === "openai");
+
+ assert.ok(row, "gpt-5/openai row present");
+ assert.equal(row!.requests, 2);
+ assert.equal(row!.promptTokens, 150);
+ assert.equal(row!.completionTokens, 300);
+ assert.equal(row!.successfulRequests, 2);
+ assert.ok(row!.avgLatencyMs > 0, "avgLatencyMs > 0");
+});
+
+// ---------------------------------------------------------------------------
+// getProviderCostRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getProviderCostRows — groups by provider+model+serviceTier", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-07-01T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "gemini", model: "gemini-2.5-flash", tokens_input: 200, tokens_output: 300, tokens_cache_read: 50 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-07-01T00:00:00.000Z",
+ untilIso: "2025-07-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getProviderCostRows(unifiedSource, unifiedParams);
+ const row = rows.find((r) => r.provider === "gemini");
+
+ assert.ok(row, "gemini row present");
+ assert.equal(row!.cacheReadTokens, 50, "cacheReadTokens passed through");
+});
+
+// ---------------------------------------------------------------------------
+// getProviderUsageRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getProviderUsageRows — aggregates per provider", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-08-01T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "mistral", tokens_input: 100, tokens_output: 100, success: 1, latency_ms: 200 });
+ insertUsageHistory({ timestamp: ts, provider: "mistral", tokens_input: 100, tokens_output: 100, success: 0, latency_ms: 400 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-08-01T00:00:00.000Z",
+ untilIso: "2025-08-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getProviderUsageRows(unifiedSource, unifiedParams);
+ const row = rows.find((r) => r.provider === "mistral");
+
+ assert.ok(row, "mistral row present");
+ assert.equal(row!.requests, 2);
+ assert.equal(row!.successfulRequests, 1);
+ assert.equal(row!.totalTokens, 400, "200 input + 200 output");
+ assert.ok(row!.avgLatencyMs > 0);
+});
+
+// ---------------------------------------------------------------------------
+// getApiKeyUsageRows + getApiKeyMetadataRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getApiKeyUsageRows — groups by api_key identity", () => {
+ const ts = new Date().toISOString();
+ const apiKeyWhereClause =
+ "WHERE (api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')";
+
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-4.1", api_key_id: "key-xyz", tokens_input: 50, tokens_output: 80 });
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-4.1", api_key_id: "key-xyz", tokens_input: 30, tokens_output: 40 });
+
+ const rows = mod.getApiKeyUsageRows(apiKeyWhereClause, {});
+ const row = rows.find((r) => r.apiKeyId === "key-xyz");
+
+ assert.ok(row, "key-xyz row present");
+ assert.ok(row!.requests >= 2, "at least 2 requests");
+ assert.ok(row!.promptTokens >= 80, "promptTokens >= 80");
+});
+
+test("#3500 getApiKeyMetadataRows — returns api key metadata with lastUsed", () => {
+ const ts = new Date().toISOString();
+ const apiKeyWhereClause =
+ "WHERE (api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')";
+
+ insertUsageHistory({ timestamp: ts, api_key_id: "key-meta-1", api_key_name: "My Key" });
+
+ const rows = mod.getApiKeyMetadataRows(apiKeyWhereClause, {});
+ const row = rows.find((r) => r.apiKeyId === "key-meta-1");
+
+ assert.ok(row, "key-meta-1 present in metadata");
+ assert.equal(row!.apiKeyName, "My Key");
+ assert.equal(typeof row!.lastUsed, "string");
+});
+
+// ---------------------------------------------------------------------------
+// getServiceTierUsageRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getServiceTierUsageRows — groups by serviceTier+provider+model", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-09-01T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-5", service_tier: "flex", tokens_input: 100, tokens_output: 150 });
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-5", service_tier: "flex", tokens_input: 50, tokens_output: 75 });
+ insertUsageHistory({ timestamp: ts, provider: "openai", model: "gpt-5", service_tier: "standard", tokens_input: 200, tokens_output: 300 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-09-01T00:00:00.000Z",
+ untilIso: "2025-09-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getServiceTierUsageRows(unifiedSource, unifiedParams);
+
+ const flexRow = rows.find((r) => r.serviceTier === "flex" && r.model === "gpt-5");
+ const stdRow = rows.find((r) => r.serviceTier === "standard" && r.model === "gpt-5");
+
+ assert.ok(flexRow, "flex tier row present");
+ assert.ok(stdRow, "standard tier row present");
+ assert.equal(flexRow!.requests, 2, "2 flex requests");
+ assert.equal(flexRow!.totalTokens, 375, "flex totalTokens = 100+150+50+75");
+ assert.equal(stdRow!.requests, 1, "1 standard request");
+});
+
+// ---------------------------------------------------------------------------
+// getWeeklyPatternRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getWeeklyPatternRows — groups by day of week, ascending", () => {
+ const rawCutoffDate = "2020-01-01";
+ // Monday 2025-06-02
+ insertUsageHistory({ timestamp: "2025-06-02T10:00:00.000Z", tokens_input: 10, tokens_output: 20 });
+ insertUsageHistory({ timestamp: "2025-06-02T11:00:00.000Z", tokens_input: 5, tokens_output: 10 });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2025-06-02T00:00:00.000Z",
+ untilIso: "2025-06-02T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getWeeklyPatternRows(unifiedSource, unifiedParams);
+ // Monday is strftime('%w', ...) = 1
+ const monday = rows.find((r) => r.dayOfWeek === "1");
+
+ assert.ok(monday, "Monday row present");
+ assert.ok(monday!.requests >= 2, "at least 2 requests on Monday");
+ assert.ok(monday!.totalTokens >= 45, "totalTokens >= 45");
+});
+
+// ---------------------------------------------------------------------------
+// buildPresetUnifiedSource
+// ---------------------------------------------------------------------------
+
+test("#3500 buildPresetUnifiedSource — UNION branch with old sinceIso", () => {
+ // sinceIso must be < rawCutoffDate for UNION to fire
+ const rawCutoffDate = "2025-01-01";
+ const result = mod.buildPresetUnifiedSource({
+ sinceIso: "2024-01-01T00:00:00.000Z",
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ assert.ok(result.unifiedSource.includes("daily_usage_summary"), "agg leg present");
+ assert.ok("presetRawCutoff" in result.unifiedParams, "presetRawCutoff param present");
+});
+
+test("#3500 buildPresetUnifiedSource — raw-only with recent sinceIso", () => {
+ // sinceIso >= rawCutoffDate → no UNION needed
+ const rawCutoffDate = "2020-01-01";
+ const recentIso = new Date(Date.now() - 1000).toISOString(); // today > 2020-01-01 → raw-only
+ const result = mod.buildPresetUnifiedSource({
+ sinceIso: recentIso,
+ untilIso: null,
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ assert.ok(!result.unifiedSource.includes("daily_usage_summary"), "no agg leg needed");
+ assert.ok("presetSince" in result.unifiedParams, "presetSince param present");
+});
+
+// ---------------------------------------------------------------------------
+// getPresetCostModelRows
+// ---------------------------------------------------------------------------
+
+test("#3500 getPresetCostModelRows — groups by model+provider+serviceTier", () => {
+ const rawCutoffDate = "2020-01-01";
+ const ts = "2025-10-01T12:00:00.000Z";
+
+ insertUsageHistory({ timestamp: ts, provider: "cohere", model: "command-r-plus", tokens_input: 200, tokens_output: 300, tokens_cache_read: 10, tokens_cache_creation: 5, tokens_reasoning: 0 });
+
+ const { unifiedSource, unifiedParams } = mod.buildPresetUnifiedSource({
+ sinceIso: "2025-10-01T00:00:00.000Z",
+ untilIso: "2025-10-01T23:59:59.000Z",
+ rawCutoffDate,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ const rows = mod.getPresetCostModelRows(unifiedSource, unifiedParams);
+ const row = rows.find((r) => r.provider === "cohere" && r.model === "command-r-plus");
+
+ assert.ok(row, "cohere/command-r-plus row present");
+ assert.equal(row!.promptTokens, 200);
+ assert.equal(row!.completionTokens, 300);
+ assert.equal(row!.cacheReadTokens, 10);
+ assert.equal(row!.cacheCreationTokens, 5);
+});
+
+// ---------------------------------------------------------------------------
+// getAllUsageHistory / getAllDomainCostHistory / getAllDomainBudgets
+// ---------------------------------------------------------------------------
+
+test("#3500 getAllUsageHistory — returns array (empty or rows)", () => {
+ const rows = mod.getAllUsageHistory();
+ assert.ok(Array.isArray(rows), "returns array");
+});
+
+test("#3500 getAllDomainCostHistory — returns array", () => {
+ const rows = mod.getAllDomainCostHistory();
+ assert.ok(Array.isArray(rows), "returns array");
+});
+
+test("#3500 getAllDomainBudgets — returns array", () => {
+ const rows = mod.getAllDomainBudgets();
+ assert.ok(Array.isArray(rows), "returns array");
+});
+
+// ---------------------------------------------------------------------------
+// UNION source integration — daily_usage_summary rows included in aggregates
+// ---------------------------------------------------------------------------
+
+test("#3500 buildUnifiedSource UNION — summary rows merged into getDailyUsage result", () => {
+ // Set rawCutoffDate to tomorrow so today's usage_history rows are in the raw leg;
+ // also insert a daily_usage_summary row for a past date that is below rawCutoffDate.
+ const tomorrow = new Date(Date.now() + 86_400_000);
+ const tomorrowStr = tomorrow.toISOString().split("T")[0];
+
+ // Past date clearly before rawCutoffDate
+ const pastDate = "2023-06-01";
+ insertDailyUsageSummary({
+ date: pastDate,
+ provider: "google",
+ model: "gemini-1.5-pro",
+ total_input_tokens: 500,
+ total_output_tokens: 750,
+ total_requests: 10,
+ });
+
+ const { unifiedSource, unifiedParams } = mod.buildUnifiedSource({
+ sinceIso: "2023-06-01T00:00:00.000Z",
+ untilIso: "2023-06-01T23:59:59.000Z",
+ rawCutoffDate: tomorrowStr,
+ apiKeyWhere: "",
+ apiKeyParams: {},
+ });
+
+ // UNION branch must be used because sinceIso < rawCutoffDate
+ assert.ok(unifiedSource.includes("daily_usage_summary"), "UNION branch active");
+
+ const rows = mod.getDailyUsage(unifiedSource, unifiedParams);
+ const june1 = rows.find((r) => r.date === pastDate);
+
+ assert.ok(june1, "2023-06-01 summary row is visible through UNION");
+ // daily_usage_summary synthesizes a timestamp at noon; totalTokens = 500+750 = 1250
+ assert.equal(june1!.totalTokens, 1250, "tokens from summary row: 500+750=1250");
+});
diff --git a/tests/unit/electron-resolve-server-entry.test.ts b/tests/unit/electron-resolve-server-entry.test.ts
new file mode 100644
index 0000000000..eb90286400
--- /dev/null
+++ b/tests/unit/electron-resolve-server-entry.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Tests for electron/lib/resolveServerEntry.js (#3386)
+ *
+ * The Electron main process must launch `server-ws.mjs` (the peer-stamp wrapper)
+ * instead of bare `server.js` so that LOCAL_ONLY routes (AgentBridge, MCP, services)
+ * pass the loopback authz check. This helper is unit-tested here with an injectable
+ * existsSync so no filesystem or Electron binary is needed.
+ *
+ * TDD sequence:
+ * BEFORE the fix: main.js hardcodes "server.js" — the helper did not exist yet.
+ * AFTER the fix: main.js delegates to resolveServerEntry(); tests verify both branches.
+ */
+
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { join } from "node:path";
+import { createRequire } from "node:module";
+
+const require = createRequire(import.meta.url);
+
+const { resolveServerEntry } = require("../../electron/lib/resolveServerEntry");
+
+describe("resolveServerEntry (#3386 — Electron 403 LOCAL_ONLY fix)", () => {
+ const FAKE_SERVER_DIR = "/fake/standalone";
+
+ it("returns 'server-ws.mjs' when it exists in the server directory", () => {
+ // existsSync returns true for the server-ws.mjs path, false for anything else
+ const existsSyncFn = (p: string) => p === join(FAKE_SERVER_DIR, "server-ws.mjs");
+ const result = resolveServerEntry(FAKE_SERVER_DIR, existsSyncFn);
+ assert.equal(result, "server-ws.mjs", "should prefer server-ws.mjs when present");
+ });
+
+ it("falls back to 'server.js' when server-ws.mjs is absent", () => {
+ // existsSync always returns false — simulates a build without the WS wrapper
+ const existsSyncFn = (_p: string) => false;
+ const result = resolveServerEntry(FAKE_SERVER_DIR, existsSyncFn);
+ assert.equal(result, "server.js", "should fall back to server.js when server-ws.mjs is absent");
+ });
+
+ it("only checks for server-ws.mjs inside the given serverDir, not a parent dir", () => {
+ const checked: string[] = [];
+ const existsSyncFn = (p: string) => {
+ checked.push(p);
+ return false;
+ };
+ resolveServerEntry(FAKE_SERVER_DIR, existsSyncFn);
+ assert.equal(checked.length, 1, "should only call existsSync once");
+ assert.ok(
+ checked[0].startsWith(FAKE_SERVER_DIR),
+ `checked path "${checked[0]}" should be inside serverDir "${FAKE_SERVER_DIR}"`
+ );
+ assert.ok(
+ checked[0].endsWith("server-ws.mjs"),
+ `checked path "${checked[0]}" should end with "server-ws.mjs"`
+ );
+ });
+
+ it("returns a plain filename (no directory component) in both branches", () => {
+ const withWs = resolveServerEntry(FAKE_SERVER_DIR, () => true);
+ const withoutWs = resolveServerEntry(FAKE_SERVER_DIR, () => false);
+ assert.ok(!withWs.includes("/") && !withWs.includes("\\"), "server-ws.mjs result must be a bare filename");
+ assert.ok(!withoutWs.includes("/") && !withoutWs.includes("\\"), "server.js result must be a bare filename");
+ });
+});
diff --git a/tests/unit/kiro-auto-import-name-dedup-3615.test.ts b/tests/unit/kiro-auto-import-name-dedup-3615.test.ts
new file mode 100644
index 0000000000..e491b6d309
--- /dev/null
+++ b/tests/unit/kiro-auto-import-name-dedup-3615.test.ts
@@ -0,0 +1,153 @@
+/**
+ * Regression tests for #3615 — Kiro/AWS auto-import creates a nameless
+ * "OAuth Account" when email is null, and accumulates duplicate rows for
+ * subsequent imports with the same profileArn.
+ *
+ * Two bugs:
+ * (a) No display name derived when email=null → UI shows blank "OAuth Account".
+ * (b) No profileArn dedup guard → every import creates a new DB row.
+ *
+ * Both tests use the helpers extracted from saveAndRespond() so we can test
+ * them without spinning up a full Next.js route.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+
+// Hermetic temp DATA_DIR so importing the route's dependency graph is safe.
+import fs from "node:fs";
+import os from "node:os";
+
+const tmpDir = fs.mkdtempSync(os.tmpdir() + "/omniroute-kiro-3615-");
+process.env.DATA_DIR = tmpDir;
+process.env.JWT_SECRET = process.env.JWT_SECRET || "test-jwt-secret-3615";
+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "test-api-key-secret-3615";
+
+test.after(() => {
+ try {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ } catch {
+ // best effort
+ }
+});
+
+// ── helpers under test ────────────────────────────────────────────────────────
+
+import {
+ deriveKiroConnectionName,
+ findKiroConnectionByProfileArn,
+} from "../../src/app/api/oauth/kiro/auto-import/route.ts";
+
+// ── (a) Display name derivation ───────────────────────────────────────────────
+
+test("derives email as name when email is present", () => {
+ const name = deriveKiroConnectionName({
+ email: "[email protected]",
+ profileArn: "arn:aws:iam::123456789012:user/test",
+ region: "us-east-1",
+ targetProvider: "kiro",
+ });
+ assert.equal(name, "[email protected]");
+});
+
+test("derives AWS CodeWhisperer label from profileArn when email is null (enterprise SSO)", () => {
+ const name = deriveKiroConnectionName({
+ email: null,
+ profileArn: "arn:aws:iam::123456789012:user/test",
+ region: "eu-west-1",
+ targetProvider: "kiro",
+ });
+ assert.equal(name, "AWS CodeWhisperer (eu-west-1)");
+});
+
+test("derives Kiro label from region when email is null and no profileArn", () => {
+ const name = deriveKiroConnectionName({
+ email: null,
+ profileArn: undefined,
+ region: "ap-northeast-1",
+ targetProvider: "kiro",
+ });
+ assert.equal(name, "Kiro (ap-northeast-1)");
+});
+
+test("uses fallback region when region is also absent", () => {
+ const name = deriveKiroConnectionName({
+ email: null,
+ profileArn: undefined,
+ region: undefined,
+ targetProvider: "kiro",
+ });
+ assert.equal(name, "Kiro (us-east-1)");
+});
+
+test("uses amazon-q label for amazon-q targetProvider with no email", () => {
+ const name = deriveKiroConnectionName({
+ email: null,
+ profileArn: undefined,
+ region: "us-east-1",
+ targetProvider: "amazon-q",
+ });
+ assert.equal(name, "Amazon Q (us-east-1)");
+});
+
+test("derived name is never empty or null", () => {
+ const name = deriveKiroConnectionName({
+ email: null,
+ profileArn: undefined,
+ region: undefined,
+ targetProvider: "kiro",
+ });
+ assert.ok(name && name.length > 0, `expected a non-empty name, got: ${JSON.stringify(name)}`);
+});
+
+// ── (b) ProfileArn dedup ──────────────────────────────────────────────────────
+
+// We mock the DB layer to assert that findKiroConnectionByProfileArn calls
+// getProviderConnections with the right filter and returns the matching row.
+
+const FAKE_PROFILE_ARN = "arn:aws:iam::123456789012:user/sso-user";
+
+const fakeConnectionWithArn = {
+ id: "conn-abc",
+ provider: "kiro",
+ authType: "oauth",
+ email: null,
+ providerSpecificData: { profileArn: FAKE_PROFILE_ARN, region: "us-east-1" },
+};
+
+const fakeConnectionNoArn = {
+ id: "conn-xyz",
+ provider: "kiro",
+ authType: "oauth",
+ email: "[email protected]",
+ providerSpecificData: { region: "us-east-1" },
+};
+
+test("findKiroConnectionByProfileArn returns the matching connection", async () => {
+ // The function should scan existing kiro connections and match by profileArn.
+ const result = await findKiroConnectionByProfileArn(
+ [fakeConnectionWithArn, fakeConnectionNoArn],
+ FAKE_PROFILE_ARN
+ );
+ assert.deepEqual(result, fakeConnectionWithArn);
+});
+
+test("findKiroConnectionByProfileArn returns null when no match exists", async () => {
+ const result = await findKiroConnectionByProfileArn(
+ [fakeConnectionNoArn],
+ FAKE_PROFILE_ARN
+ );
+ assert.equal(result, null);
+});
+
+test("findKiroConnectionByProfileArn returns null for empty connection list", async () => {
+ const result = await findKiroConnectionByProfileArn([], FAKE_PROFILE_ARN);
+ assert.equal(result, null);
+});
+
+test("findKiroConnectionByProfileArn returns null when profileArn arg is undefined", async () => {
+ const result = await findKiroConnectionByProfileArn(
+ [fakeConnectionWithArn],
+ undefined
+ );
+ assert.equal(result, null);
+});
diff --git a/tests/unit/kiro-iam-region.test.ts b/tests/unit/kiro-iam-region.test.ts
new file mode 100644
index 0000000000..a3e8bf8611
--- /dev/null
+++ b/tests/unit/kiro-iam-region.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Kiro enterprise IAM Identity Center region routing.
+ *
+ * Kiro/CodeWhisperer access tokens and Q Developer profile ARNs are region-bound. Enterprise
+ * IAM Identity Center accounts whose profile lives outside us-east-1 (e.g. eu-central-1) must
+ * route to the regional Amazon Q endpoint (q.{region}.amazonaws.com) with the region-matched
+ * profileArn — sending them to the default us-east-1 host fails with 403/400. These tests cover
+ * the region resolver, the regional host mapping, and the profileArn discovery added to the
+ * device-code login.
+ */
+
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { resolveKiroRegion, kiroRuntimeHost } from "../../open-sse/executors/kiro.ts";
+import { kiro } from "@/lib/oauth/providers/kiro";
+
+test("resolveKiroRegion prefers the stored region", () => {
+ assert.equal(resolveKiroRegion({ providerSpecificData: { region: "eu-central-1" } }), "eu-central-1");
+});
+
+test("resolveKiroRegion falls back to the region in the profileArn", () => {
+ assert.equal(
+ resolveKiroRegion({
+ providerSpecificData: {
+ profileArn: "arn:aws:codewhisperer:ap-southeast-2:123456789012:profile/ABC123",
+ },
+ }),
+ "ap-southeast-2"
+ );
+});
+
+test("resolveKiroRegion defaults to us-east-1 when nothing is set", () => {
+ assert.equal(resolveKiroRegion({ providerSpecificData: {} }), "us-east-1");
+ assert.equal(resolveKiroRegion(null), "us-east-1");
+ assert.equal(resolveKiroRegion(undefined), "us-east-1");
+});
+
+test("resolveKiroRegion normalizes case and whitespace", () => {
+ assert.equal(
+ resolveKiroRegion({ providerSpecificData: { region: " EU-CENTRAL-1 " } }),
+ "eu-central-1"
+ );
+});
+
+test("kiroRuntimeHost keeps the legacy host for us-east-1 and uses regional Q hosts otherwise", () => {
+ assert.equal(kiroRuntimeHost("us-east-1"), "https://codewhisperer.us-east-1.amazonaws.com");
+ assert.equal(kiroRuntimeHost("eu-central-1"), "https://q.eu-central-1.amazonaws.com");
+ assert.equal(kiroRuntimeHost("ap-southeast-2"), "https://q.ap-southeast-2.amazonaws.com");
+});
+
+test("kiro.postExchange discovers the region-matched profileArn via ListAvailableProfiles", async () => {
+ const originalFetch = global.fetch;
+ let requestedUrl = "";
+ let requestedTarget = "";
+
+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ requestedUrl = String(input);
+ requestedTarget = String((init?.headers as Record<string, string>)?.["x-amz-target"] || "");
+ return new Response(
+ JSON.stringify({
+ profiles: [
+ { arn: "arn:aws:codewhisperer:us-east-1:111111111111:profile/USEAST" },
+ { arn: "arn:aws:codewhisperer:eu-central-1:820374639727:profile/RX4VNUHGHGAQ" },
+ ],
+ }),
+ { status: 200 }
+ );
+ }) as typeof fetch;
+
+ try {
+ const extra = await kiro.postExchange({ access_token: "token", _region: "eu-central-1" });
+ assert.equal(requestedUrl, "https://q.eu-central-1.amazonaws.com/");
+ assert.equal(requestedTarget, "AmazonCodeWhispererService.ListAvailableProfiles");
+ assert.deepEqual(extra, {
+ profileArn: "arn:aws:codewhisperer:eu-central-1:820374639727:profile/RX4VNUHGHGAQ",
+ });
+ } finally {
+ global.fetch = originalFetch;
+ }
+});
+
+test("kiro.postExchange returns null when no profile is available (AWS Builder ID)", async () => {
+ const originalFetch = global.fetch;
+ global.fetch = (async () =>
+ new Response(JSON.stringify({ profiles: [] }), { status: 200 })) as typeof fetch;
+ try {
+ assert.equal(await kiro.postExchange({ access_token: "token", _region: "us-east-1" }), null);
+ } finally {
+ global.fetch = originalFetch;
+ }
+});
+
+test("kiro.postExchange never throws on network failure", async () => {
+ const originalFetch = global.fetch;
+ global.fetch = (async () => {
+ throw new Error("network down");
+ }) as typeof fetch;
+ try {
+ assert.equal(await kiro.postExchange({ access_token: "token", _region: "eu-central-1" }), null);
+ } finally {
+ global.fetch = originalFetch;
+ }
+});
+
+test("kiro.mapTokens stores the discovered profileArn from postExchange extra", () => {
+ const mapped = kiro.mapTokens(
+ { access_token: "at", refresh_token: "rt", expires_in: 3600, _region: "eu-central-1" },
+ { profileArn: "arn:aws:codewhisperer:eu-central-1:820374639727:profile/RX4VNUHGHGAQ" }
+ );
+ assert.equal(
+ mapped.providerSpecificData.profileArn,
+ "arn:aws:codewhisperer:eu-central-1:820374639727:profile/RX4VNUHGHGAQ"
+ );
+});
+
+test("kiro.mapTokens omits profileArn when postExchange found none", () => {
+ const mapped = kiro.mapTokens(
+ { access_token: "at", refresh_token: "rt", expires_in: 3600, _region: "us-east-1" },
+ null
+ );
+ assert.equal("profileArn" in mapped.providerSpecificData, false);
+});
diff --git a/tests/unit/mimocode-executor.test.ts b/tests/unit/mimocode-executor.test.ts
new file mode 100644
index 0000000000..ed89ca81ca
--- /dev/null
+++ b/tests/unit/mimocode-executor.test.ts
@@ -0,0 +1,169 @@
+import { describe, it } from "node:test";
+import assert from "node:assert";
+import { MimocodeExecutor, generateFingerprint } from "../../open-sse/executors/mimocode.ts";
+
+const executor = new MimocodeExecutor();
+
+describe("MimocodeExecutor", () => {
+ it("generateFingerprint returns a 64-char hex string", () => {
+ const fp = generateFingerprint();
+ assert.match(fp, /^[0-9a-f]{64}$/);
+ });
+
+ it("generateFingerprint is deterministic", () => {
+ assert.strictEqual(generateFingerprint(), generateFingerprint());
+ });
+
+ it("generateFingerprint with seed is deterministic", () => {
+ assert.strictEqual(generateFingerprint("seed-a"), generateFingerprint("seed-a"));
+ });
+
+ it("generateFingerprint with different seeds differs", () => {
+ assert.notStrictEqual(generateFingerprint("seed-a"), generateFingerprint("seed-b"));
+ });
+
+ it("buildUrl returns the free-ai chat endpoint", () => {
+ const url = executor.buildUrl("mimo-auto", false);
+ assert.ok(url.includes("/api/free-ai/openai/chat"));
+ assert.ok(url.startsWith("https://"));
+ });
+
+ it("buildHeaders includes X-Mimo-Source and Content-Type", () => {
+ const headers = (executor as any).buildHeaders({}, true);
+ assert.strictEqual(headers["Content-Type"], "application/json");
+ assert.strictEqual(headers["X-Mimo-Source"], "mimocode-cli-free");
+ });
+
+ it("buildHeaders includes Accept for streaming", () => {
+ const headers = (executor as any).buildHeaders({}, true);
+ assert.ok(headers["Accept"]?.includes("text/event-stream"));
+ });
+
+ it("buildHeaders omits Accept for non-streaming", () => {
+ const headers = (executor as any).buildHeaders({}, false);
+ assert.ok(!headers["Accept"]?.includes("text/event-stream"));
+ });
+
+ it("transformRequest strips model prefix", () => {
+ const result = (executor as any).transformRequest(
+ "mcode/mimo-auto",
+ { model: "mcode/mimo-auto", messages: [{ role: "user", content: "hi" }] },
+ false,
+ );
+ assert.strictEqual(result.model, "mimo-auto");
+ });
+
+ it("transformRequest passes model through when no prefix", () => {
+ const result = (executor as any).transformRequest(
+ "mimo-auto",
+ { model: "mimo-auto", messages: [{ role: "user", content: "hi" }] },
+ false,
+ );
+ assert.strictEqual(result.model, "mimo-auto");
+ });
+
+ it("returns 499 on pre-aborted signal", async () => {
+ const controller = new AbortController();
+ controller.abort(new Error("cancelled"));
+
+ const result = await executor.execute({
+ model: "mimo-auto",
+ body: { messages: [{ role: "user", content: "hi" }], stream: false },
+ stream: false,
+ signal: controller.signal,
+ credentials: {},
+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },
+ });
+
+ assert.strictEqual((result as any).response.status, 499);
+ });
+
+ it("is registered in executor index", async () => {
+ const { getExecutor } = await import("../../open-sse/executors/index.ts");
+ const exec = getExecutor("mimocode");
+ assert.ok(exec instanceof MimocodeExecutor);
+ });
+
+ it("mcode alias works", async () => {
+ const { getExecutor } = await import("../../open-sse/executors/index.ts");
+ const exec = getExecutor("mcode");
+ assert.ok(exec instanceof MimocodeExecutor);
+ });
+});
+
+describe("mimocode multi-account", () => {
+ it("executor has at least one account", () => {
+ const accounts = (executor as any).accounts;
+ assert.ok(Array.isArray(accounts));
+ assert.ok(accounts.length >= 1);
+ });
+
+ it("each account has required fields", () => {
+ const accounts = (executor as any).accounts;
+ for (const acct of accounts) {
+ assert.ok(typeof acct.fingerprint === "string");
+ assert.ok(typeof acct.jwt === "string");
+ assert.ok(typeof acct.expiresAt === "number");
+ assert.ok(typeof acct.cooldownUntil === "number");
+ assert.ok(typeof acct.consecutiveFails === "number");
+ }
+ });
+
+ it("pickAccount returns an account", () => {
+ const acct = (executor as any).pickAccount();
+ assert.ok(acct);
+ assert.ok(typeof acct.fingerprint === "string");
+ });
+
+ it("markCooldown increases consecutiveFails and sets cooldownUntil", () => {
+ const acct = (executor as any).accounts[0];
+ const before = acct.consecutiveFails;
+ (executor as any).markCooldown(acct);
+ assert.strictEqual(acct.consecutiveFails, before + 1);
+ assert.ok(acct.cooldownUntil > Date.now());
+ });
+
+ it("markSuccess resets consecutiveFails", () => {
+ const acct = (executor as any).accounts[0];
+ acct.consecutiveFails = 5;
+ (executor as any).markSuccess(acct);
+ assert.strictEqual(acct.consecutiveFails, 0);
+ });
+});
+
+describe("mimocode provider registration", () => {
+ it("provider is registered in NOAUTH_PROVIDERS", async () => {
+ const { NOAUTH_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
+ const provider = (NOAUTH_PROVIDERS as Record<string, any>)["mimocode"];
+ assert.ok(provider);
+ assert.strictEqual(provider.id, "mimocode");
+ assert.strictEqual(provider.alias, "mcode");
+ assert.strictEqual(provider.noAuth, true);
+ assert.strictEqual(provider.hasFree, true);
+ });
+
+ it("provider has correct service kinds", async () => {
+ const { NOAUTH_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
+ const provider = (NOAUTH_PROVIDERS as Record<string, any>)["mimocode"];
+ assert.ok(provider.serviceKinds?.includes("llm"));
+ });
+});
+
+describe("mimocode providerRegistry entry", () => {
+ it("registry entry exists with correct executor", async () => {
+ const { getRegistryEntry } = await import("../../open-sse/config/providerRegistry.ts");
+ const entry = getRegistryEntry("mimocode");
+ assert.ok(entry);
+ assert.strictEqual(entry.executor, "mimocode");
+ assert.strictEqual(entry.format, "openai");
+ assert.strictEqual(entry.authType, "none");
+ });
+
+ it("registry entry has mimo-auto model", async () => {
+ const { getRegistryEntry } = await import("../../open-sse/config/providerRegistry.ts");
+ const entry = getRegistryEntry("mimocode");
+ const models = entry.models as Array<{ id: string }>;
+ const mimoAuto = models.find((m) => m.id === "mimo-auto");
+ assert.ok(mimoAuto);
+ });
+});
diff --git a/tests/unit/mitm-system-commands-prefix-3641.test.ts b/tests/unit/mitm-system-commands-prefix-3641.test.ts
new file mode 100644
index 0000000000..1b32a7a437
--- /dev/null
+++ b/tests/unit/mitm-system-commands-prefix-3641.test.ts
@@ -0,0 +1,55 @@
+/**
+ * Regression test for #3641 — `execFileText` produces a doubled
+ * "Command failed: Command failed: ..." prefix in error messages.
+ *
+ * Node's `execFile` already sets `error.message` to
+ * "Command failed: <command>" when the child process exits non-zero.
+ * `execFileText` was prepending its own "Command failed: " prefix on top of
+ * that, producing the doubled string.
+ *
+ * The fix: surface `getErrorMessage(error)` directly (Node's message already
+ * contains the command), only appending stderr when it is non-empty.
+ *
+ * Uses `/bin/false` (always exits 1) as the deterministic failing command on
+ * Linux/macOS. This is the only case that triggers "Command failed: ..." in
+ * Node's error.message (ENOENT from a missing binary uses "spawn ... ENOENT"
+ * instead, so it never doubles).
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileText } from "../../src/mitm/systemCommands.ts";
+
+// `/bin/false` exits with code 1 — guaranteed to produce a "Command failed:"
+// error.message from Node's execFile, which is exactly the case that was
+// being doubled by the bug.
+const FALSE_CMD = "/bin/false";
+
+test("execFileText: error message does NOT contain a doubled 'Command failed:' prefix", async () => {
+ await assert.rejects(
+ () => execFileText(FALSE_CMD, []),
+ (err: unknown) => {
+ assert.ok(err instanceof Error, "expected an Error");
+ const msg = err.message;
+ assert.ok(
+ !msg.includes("Command failed: Command failed:"),
+ `Error message contains doubled prefix: ${JSON.stringify(msg)}`,
+ );
+ return true;
+ },
+ );
+});
+
+test("execFileText: error message for a non-zero exit still contains 'Command failed:'", async () => {
+ await assert.rejects(
+ () => execFileText(FALSE_CMD, []),
+ (err: unknown) => {
+ assert.ok(err instanceof Error, "expected an Error");
+ // The message should still contain the Node-generated prefix once.
+ assert.ok(
+ err.message.includes("Command failed:"),
+ `Error message should still contain "Command failed:": ${JSON.stringify(err.message)}`,
+ );
+ return true;
+ },
+ );
+});
diff --git a/tests/unit/model-resolver.test.ts b/tests/unit/model-resolver.test.ts
index 2e4b860d8b..d7d0d0e739 100644
--- a/tests/unit/model-resolver.test.ts
+++ b/tests/unit/model-resolver.test.ts
@@ -1,8 +1,51 @@
import test from "node:test";
import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const previousDataDir = process.env.DATA_DIR;
+const modelResolverDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-model-resolver-"));
+process.env.DATA_DIR = modelResolverDataDir;
const model = await import("../../open-sse/services/model.ts");
+function withEnv(name: string, value: string | undefined, fn: () => Promise<void>) {
+ return async () => {
+ const { invalidateDbCache } = await import("../../src/lib/db/readCache.ts");
+ const previous = process.env[name];
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ invalidateDbCache("settings");
+ try {
+ await fn();
+ } finally {
+ if (previous === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = previous;
+ }
+ invalidateDbCache("settings");
+ }
+ };
+}
+
+test.after(async () => {
+ const core = await import("../../src/lib/db/core.ts");
+ const { invalidateDbCache } = await import("../../src/lib/db/readCache.ts");
+ core.resetDbInstance();
+ invalidateDbCache();
+ fs.rmSync(modelResolverDataDir, { recursive: true, force: true });
+ if (previousDataDir === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = previousDataDir;
+ }
+});
+
test("resolveProviderAlias returns null for null/undefined", () => {
assert.equal(model.resolveProviderAlias(null), null);
assert.equal(model.resolveProviderAlias(undefined), null);
@@ -116,3 +159,84 @@ test("getModelInfoCore handles null", async () => {
assert.ok(result);
assert.ok(typeof result === "object");
});
+
+test(
+ "getModelInfoCore routes newly released unprefixed Claude models to Claude Code when enabled",
+ withEnv("OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS", "true", async () => {
+ const result = await model.getModelInfoCore("claude-fable-5", {});
+ assert.deepEqual(result, {
+ provider: "claude",
+ model: "claude-fable-5",
+ extendedContext: false,
+ });
+ })
+);
+
+test(
+ "getModelInfoCore resolves ambiguous unprefixed Claude catalog models to Claude Code when enabled",
+ withEnv("OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS", "true", async () => {
+ const result = await model.getModelInfoCore("claude-haiku-4-5-20251001", {});
+ assert.deepEqual(result, {
+ provider: "claude",
+ model: "claude-haiku-4-5-20251001",
+ extendedContext: false,
+ });
+ })
+);
+
+test("getModelInfoCore routes unprefixed Claude models to Claude Code from settings toggle", async () => {
+ const previousEnvFlag =
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS;
+ delete process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS;
+
+ try {
+ const { updateSettings } = await import("../../src/lib/db/settings.ts");
+ await updateSettings({ preferClaudeCodeForUnprefixedClaudeModels: true });
+
+ const result = await model.getModelInfoCore("claude-fable-5", {});
+ assert.deepEqual(result, {
+ provider: "claude",
+ model: "claude-fable-5",
+ extendedContext: false,
+ });
+
+ const extendedResult = await model.getModelInfoCore("claude-fable-5[1m]", {});
+ assert.deepEqual(extendedResult, {
+ provider: "claude",
+ model: "claude-fable-5",
+ extendedContext: true,
+ });
+ } finally {
+ if (previousEnvFlag === undefined) {
+ delete process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS;
+ } else {
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS = previousEnvFlag;
+ }
+ }
+});
+
+test("getModelInfoCore lets settings toggle disable Claude Code preference", async () => {
+ const previousEnvFlag =
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS;
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS = "true";
+
+ try {
+ const { updateSettings } = await import("../../src/lib/db/settings.ts");
+ await updateSettings({ preferClaudeCodeForUnprefixedClaudeModels: false });
+
+ // With the toggle OFF, a bare `claude-*` id must NOT be auto-preferred to the
+ // Claude Code ("claude") provider — it falls back to normal inference. The exact
+ // fallback target depends on the live catalog (an id present in a single provider
+ // resolves there; one present in several is reported ambiguous and requires a
+ // provider prefix), so assert the toggle's effect rather than a catalog-dependent
+ // target: the result is simply not routed to Claude Code.
+ const result = await model.getModelInfoCore("claude-fable-5", {});
+ assert.notEqual(result.provider, "claude");
+ } finally {
+ if (previousEnvFlag === undefined) {
+ delete process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS;
+ } else {
+ process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS = previousEnvFlag;
+ }
+ }
+});
diff --git a/tests/unit/obsidian-webdav-route.test.ts b/tests/unit/obsidian-webdav-route.test.ts
new file mode 100644
index 0000000000..cfc839a607
--- /dev/null
+++ b/tests/unit/obsidian-webdav-route.test.ts
@@ -0,0 +1,301 @@
+/**
+ * TDD tests for /api/settings/obsidian/webdav route (PR1 of #3485).
+ *
+ * Covers:
+ * - GET: no config → disabled shape with null creds
+ * - POST: valid temp dir → enabled, returns { username, password }
+ * - POST: non-existent path → 400 with no stack trace leaked
+ * - DELETE: after enable → disabled, creds cleared
+ * - Unauthenticated → 401
+ * - Encryption round-trip: set password → raw DB value is NOT plaintext → get returns plaintext
+ */
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { NextRequest } from "next/server";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-obsidian-webdav-route-"));
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
+const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
+const ORIGINAL_STORAGE_ENCRYPTION_KEY = process.env.STORAGE_ENCRYPTION_KEY;
+
+// Set DATA_DIR before any module imports so the DB picks up the temp dir.
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+// Import settings to control auth requirements
+const settingsDb = await import("../../src/lib/db/settings.ts");
+// Import the route under test
+const route = await import("../../src/app/api/settings/obsidian/webdav/route.ts");
+// Import DB module to inspect raw stored values
+const obsidianDb = await import("../../src/lib/db/obsidian.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+function makeRequest(url: string, options?: RequestInit): NextRequest {
+ return new Request(url, options) as unknown as NextRequest;
+}
+
+test.beforeEach(async () => {
+ delete process.env.INITIAL_PASSWORD;
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ await resetStorage();
+});
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+ }
+ if (ORIGINAL_INITIAL_PASSWORD === undefined) {
+ delete process.env.INITIAL_PASSWORD;
+ } else {
+ process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
+ }
+ if (ORIGINAL_JWT_SECRET === undefined) {
+ delete process.env.JWT_SECRET;
+ } else {
+ process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
+ }
+ if (ORIGINAL_STORAGE_ENCRYPTION_KEY === undefined) {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ } else {
+ process.env.STORAGE_ENCRYPTION_KEY = ORIGINAL_STORAGE_ENCRYPTION_KEY;
+ }
+});
+
+// ── Auth is disabled by default (requireLogin not set) so requests succeed ──
+
+test("GET with no config → webdavEnabled:false, all creds null", async () => {
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav");
+ const res = await route.GET(req);
+
+ assert.equal(res.status, 200);
+ const body = (await res.json()) as Record<string, unknown>;
+ assert.equal(body.webdavEnabled, false);
+ assert.equal(body.webdavUsername, null);
+ assert.equal(body.webdavPassword, null);
+ assert.equal(body.vaultPath, null);
+});
+
+test("POST with a valid temp dir → returns { username, password }, GET shows enabled", async () => {
+ const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-"));
+ try {
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ vaultPath: vaultDir }),
+ });
+ const res = await route.POST(req);
+
+ assert.equal(res.status, 200);
+ const body = (await res.json()) as Record<string, unknown>;
+ assert.ok(typeof body.username === "string" && (body.username as string).length > 0, "username non-empty");
+ assert.ok(typeof body.password === "string" && (body.password as string).length > 0, "password non-empty");
+ assert.ok(typeof body.vaultPath === "string", "vaultPath returned");
+
+ // GET should now reflect enabled state
+ const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
+ const getRes = await route.GET(getReq);
+ assert.equal(getRes.status, 200);
+ const getBody = (await getRes.json()) as Record<string, unknown>;
+ assert.equal(getBody.webdavEnabled, true);
+ assert.ok(typeof getBody.webdavUsername === "string" && (getBody.webdavUsername as string).length > 0);
+ assert.ok(typeof getBody.webdavPassword === "string" && (getBody.webdavPassword as string).length > 0);
+ } finally {
+ fs.rmSync(vaultDir, { recursive: true, force: true });
+ }
+});
+
+test("POST with a non-existent path → 400, body does NOT contain a stack trace", async () => {
+ const nonExistentPath = path.join(os.tmpdir(), "omni-nonexistent-vault-" + Date.now());
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ vaultPath: nonExistentPath }),
+ });
+ const res = await route.POST(req);
+
+ assert.equal(res.status, 400);
+ const body = (await res.json()) as Record<string, unknown>;
+ const errorMsg = (body.error as Record<string, unknown> | undefined)?.message as string | undefined;
+ // Must not leak stack trace
+ assert.ok(
+ !errorMsg || !errorMsg.includes("at /"),
+ `Error message should not contain a stack trace, got: ${errorMsg}`
+ );
+});
+
+test("POST with invalid body (missing vaultPath) → 400", async () => {
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({}),
+ });
+ const res = await route.POST(req);
+ assert.equal(res.status, 400);
+});
+
+test("DELETE after enable → webdavEnabled:false, creds cleared in GET", async () => {
+ const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault2-"));
+ try {
+ // Enable first
+ const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ vaultPath: vaultDir }),
+ });
+ const enableRes = await route.POST(enableReq);
+ assert.equal(enableRes.status, 200);
+
+ // Delete
+ const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "DELETE",
+ });
+ const deleteRes = await route.DELETE(deleteReq);
+ assert.equal(deleteRes.status, 200);
+ const deleteBody = (await deleteRes.json()) as Record<string, unknown>;
+ assert.equal(deleteBody.success, true);
+
+ // GET should now show disabled
+ const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
+ const getRes = await route.GET(getReq);
+ const getBody = (await getRes.json()) as Record<string, unknown>;
+ assert.equal(getBody.webdavEnabled, false);
+ assert.equal(getBody.webdavUsername, null);
+ assert.equal(getBody.webdavPassword, null);
+ } finally {
+ fs.rmSync(vaultDir, { recursive: true, force: true });
+ }
+});
+
+test("GET when disabled does not leak password even if stale data exists", async () => {
+ const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault3-"));
+ try {
+ // Enable, then disable
+ const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ vaultPath: vaultDir }),
+ });
+ await route.POST(enableReq);
+ const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "DELETE",
+ });
+ await route.DELETE(deleteReq);
+
+ // GET now: password must be null (not a stale value)
+ const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
+ const getRes = await route.GET(getReq);
+ const getBody = (await getRes.json()) as Record<string, unknown>;
+ assert.equal(getBody.webdavEnabled, false);
+ assert.equal(getBody.webdavPassword, null);
+ } finally {
+ fs.rmSync(vaultDir, { recursive: true, force: true });
+ }
+});
+
+// ── Auth guard tests ──
+
+test("Unauthenticated GET → 401 when auth is required", async () => {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav");
+ const res = await route.GET(req);
+ assert.equal(res.status, 401);
+});
+
+test("Unauthenticated POST → 401 when auth is required", async () => {
+ const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault4-"));
+ try {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ vaultPath: vaultDir }),
+ });
+ const res = await route.POST(req);
+ assert.equal(res.status, 401);
+ } finally {
+ fs.rmSync(vaultDir, { recursive: true, force: true });
+ }
+});
+
+test("Unauthenticated DELETE → 401 when auth is required", async () => {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+
+ const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
+ method: "DELETE",
+ });
+ const res = await route.DELETE(req);
+ assert.equal(res.status, 401);
+});
+
+// ── Encryption round-trip ──
+
+test("encryption round-trip: setWebdavPassword stores encrypted, getWebdavPassword returns plaintext", async () => {
+ // Enable encryption
+ process.env.STORAGE_ENCRYPTION_KEY = "test-encryption-key-for-webdav-route-tests";
+
+ // Invalidate cached encryption keys so the new env var is picked up.
+ // The encryption module caches keys in module-level vars; we reset via db instance.
+ core.resetDbInstance();
+
+ const plaintext = "super-secret-webdav-password-12345";
+ obsidianDb.setWebdavPassword(plaintext);
+
+ // Inspect raw DB row — it must NOT be the plaintext
+ const db = core.getDbInstance();
+ type KVRow = { value: string };
+ const row = db
+ .prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
+ .get("obsidian", "webdav_password") as KVRow | undefined;
+
+ assert.ok(row !== undefined, "Row should exist");
+ // The stored JSON string — parse to get inner value
+ const storedInner = JSON.parse(row!.value) as string;
+ assert.notEqual(
+ storedInner,
+ plaintext,
+ "Raw DB value must NOT be plaintext when encryption is enabled"
+ );
+ assert.ok(
+ storedInner.startsWith("enc:v1:"),
+ `Raw DB value should start with enc:v1: prefix, got: ${storedInner.slice(0, 40)}`
+ );
+
+ // getWebdavPassword must round-trip back to plaintext
+ const retrieved = obsidianDb.getWebdavPassword();
+ assert.equal(retrieved, plaintext, "getWebdavPassword must return original plaintext");
+
+ // Clean up env for other tests
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ core.resetDbInstance();
+});
+
+test("encryption graceful fallback: plaintext stored without key reads back correctly", async () => {
+ // No encryption key set — store plaintext
+ const plaintext = "plaintext-webdav-password";
+ obsidianDb.setWebdavPassword(plaintext);
+
+ // Must read back the same value
+ const retrieved = obsidianDb.getWebdavPassword();
+ assert.equal(retrieved, plaintext, "Plaintext value must read back unchanged when no encryption key");
+});
diff --git a/tests/unit/opencode-noauth-models-route.test.ts b/tests/unit/opencode-noauth-models-route.test.ts
index 685b9d8ed5..3e031a31e6 100644
--- a/tests/unit/opencode-noauth-models-route.test.ts
+++ b/tests/unit/opencode-noauth-models-route.test.ts
@@ -17,8 +17,10 @@ test.after(() => {
// #3047 — OpenCode Free (no-auth) has no connection row, so the
// "Import from /models" button used to hit a 404 and silently no-op. The models
-// route must serve the provider's catalog when called with a no-auth provider id.
-test("models route serves the catalog for a no-auth provider id (#3047)", async () => {
+// route must serve a non-empty model list when called with a no-auth provider id.
+// #3611 — the source may now be "upstream" (live fetch succeeded) or
+// "local_catalog" (live fetch failed/unavailable); both are acceptable here.
+test("models route serves models for a no-auth provider id (#3047)", async () => {
const response = await modelsRoute.GET(
new Request("http://localhost/api/providers/opencode/models?refresh=true"),
{ params: { id: "opencode" } }
@@ -26,7 +28,10 @@ test("models route serves the catalog for a no-auth provider id (#3047)", async
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.provider, "opencode");
- assert.equal(body.source, "local_catalog");
+ assert.ok(
+ body.source === "local_catalog" || body.source === "upstream",
+ `source must be 'local_catalog' or 'upstream', got '${body.source}'`
+ );
assert.ok(Array.isArray(body.models) && body.models.length > 0, "should return catalog models");
assert.ok(
body.models.every((m: { id?: unknown }) => typeof m.id === "string" && m.id.length > 0),
@@ -41,3 +46,87 @@ test("models route still 404s for an unknown provider/connection id", async () =
);
assert.equal(response.status, 404);
});
+
+// #3611 — OpenCode Free (noAuth + modelsUrl) must fetch live models from the
+// provider's modelsUrl instead of always returning the stale local_catalog.
+
+const LIVE_MODEL_LIST = [
+ { id: "live-model-alpha", object: "model" },
+ { id: "live-model-beta", object: "model" },
+];
+
+test("models route fetches live models from modelsUrl for noAuth provider with modelsUrl (#3611)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url: string | URL, _init?: RequestInit) => {
+ const urlStr = String(url);
+ if (urlStr === "https://opencode.ai/zen/v1/models") {
+ return Response.json({ data: LIVE_MODEL_LIST });
+ }
+ return new Response("unexpected fetch: " + urlStr, { status: 500 });
+ };
+
+ try {
+ const response = await modelsRoute.GET(
+ new Request("http://localhost/api/providers/opencode/models"),
+ { params: { id: "opencode" } }
+ );
+ assert.equal(response.status, 200);
+ const body = await response.json();
+ assert.equal(body.provider, "opencode");
+ assert.equal(body.source, "upstream", "should report source as 'upstream' when live fetch succeeds");
+ assert.ok(Array.isArray(body.models), "models should be an array");
+ const ids = body.models.map((m: { id: string }) => m.id);
+ assert.ok(ids.includes("live-model-alpha"), "should include live model alpha");
+ assert.ok(ids.includes("live-model-beta"), "should include live model beta");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("models route falls back to local_catalog when live modelsUrl fetch throws (#3611 fallback on error)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url: string | URL, _init?: RequestInit) => {
+ if (String(url) === "https://opencode.ai/zen/v1/models") {
+ throw new Error("network failure");
+ }
+ return new Response("unexpected", { status: 500 });
+ };
+
+ try {
+ const response = await modelsRoute.GET(
+ new Request("http://localhost/api/providers/opencode/models"),
+ { params: { id: "opencode" } }
+ );
+ assert.equal(response.status, 200);
+ const body = await response.json();
+ assert.equal(body.provider, "opencode");
+ assert.equal(body.source, "local_catalog", "should fall back to local_catalog on fetch error");
+ assert.ok(Array.isArray(body.models) && body.models.length > 0, "should have catalog models");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("models route falls back to local_catalog when live modelsUrl fetch returns non-OK (#3611 fallback on non-OK)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url: string | URL, _init?: RequestInit) => {
+ if (String(url) === "https://opencode.ai/zen/v1/models") {
+ return new Response("Service Unavailable", { status: 503 });
+ }
+ return new Response("unexpected", { status: 500 });
+ };
+
+ try {
+ const response = await modelsRoute.GET(
+ new Request("http://localhost/api/providers/opencode/models"),
+ { params: { id: "opencode" } }
+ );
+ assert.equal(response.status, 200);
+ const body = await response.json();
+ assert.equal(body.provider, "opencode");
+ assert.equal(body.source, "local_catalog", "should fall back to local_catalog when upstream returns non-OK");
+ assert.ok(Array.isArray(body.models) && body.models.length > 0, "should have catalog models");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
diff --git a/tests/unit/provider-metrics-route.test.ts b/tests/unit/provider-metrics-route.test.ts
index e56a71afea..ca5def5bb5 100644
--- a/tests/unit/provider-metrics-route.test.ts
+++ b/tests/unit/provider-metrics-route.test.ts
@@ -85,6 +85,43 @@ test("GET /api/provider-metrics includes provider recency and error topology", a
assert.equal(body.topology.errorProvider, "openai");
});
+test("GET /api/provider-metrics errorProvider must NOT flag a provider whose most recent request succeeded", async () => {
+ // Arrange: providerA had an error long ago but recovered (last request = 200).
+ // providerB never errored.
+ // Bug (pre-fix): errorProvider = "providerA" because lastErrorAt > 0.
+ // Fix (post-fix): errorProvider = "" because lastStatus for providerA is 200.
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT INTO call_logs (id, timestamp, provider, status, duration, error_summary)
+ VALUES (?, ?, ?, ?, ?, ?)`
+ ).run("a-old-error", "2026-01-01T00:00:00.000Z", "providerA", 500, 100, "old error");
+ db.prepare(
+ `INSERT INTO call_logs (id, timestamp, provider, status, duration, error_summary)
+ VALUES (?, ?, ?, ?, ?, ?)`
+ ).run("a-recent-ok", "2026-06-01T00:00:00.000Z", "providerA", 200, 80, null);
+ db.prepare(
+ `INSERT INTO call_logs (id, timestamp, provider, status, duration, error_summary)
+ VALUES (?, ?, ?, ?, ?, ?)`
+ ).run("b-ok", "2026-05-01T00:00:00.000Z", "providerB", 200, 60, null);
+
+ const response = await providerMetricsRoute.GET();
+ const body = (await response.json()) as ProviderMetricsResponse;
+
+ assert.equal(response.status, 200);
+ // providerA's last request succeeded — must NOT appear as errorProvider
+ assert.notEqual(
+ body.topology.errorProvider,
+ "providerA",
+ "providerA recovered (lastStatus=200) and must not be marked as errorProvider"
+ );
+ // No provider is currently in error — errorProvider should be empty
+ assert.equal(
+ body.topology.errorProvider,
+ "",
+ "errorProvider must be empty when no provider's most recent request was a failure"
+ );
+});
+
test("GET /api/provider-metrics returns sanitized 500 when metrics cannot be loaded", async () => {
const db = core.getDbInstance();
db.close();
diff --git a/tests/unit/provider-page-helpers-3501.test.ts b/tests/unit/provider-page-helpers-3501.test.ts
new file mode 100644
index 0000000000..81eef3648d
--- /dev/null
+++ b/tests/unit/provider-page-helpers-3501.test.ts
@@ -0,0 +1,239 @@
+// Phase 2 unit tests for Issue #3501: the pure helpers extracted from the
+// provider-detail god-component into providerPageHelpers.ts. Beyond asserting
+// behaviour, exercising EVERY exported function guards against a missing
+// transitive import in the extracted module (the Phase 0 smoke test caught one
+// such gap — isSelfHostedChatProvider — at mount time; this locks it down).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ providerText,
+ providerCountText,
+ readBooleanToggle,
+ getLocalProviderMetadata,
+ isBaseUrlConfigurableProvider,
+ getProviderBaseUrlDefault,
+ getProviderBaseUrlHint,
+ getProviderBaseUrlPlaceholder,
+ isGlmProvider,
+ parseRoutingTagsInput,
+ parseExcludedModelsInput,
+ formatRoutingTagsInput,
+ formatExcludedModelsInput,
+ // Phase 2b additions
+ getWebSessionCredentialLabel,
+ getWebSessionCredentialHint,
+ getWebSessionCredentialCheckLabel,
+ getAddCredentialModalTitle,
+ upstreamHeadersRecordsEqual,
+ UPSTREAM_HEADERS_UI_MAX,
+ headerRowsToRecord,
+ effectiveUpstreamHeadersForProtocol,
+ anyUpstreamHeadersBadge,
+ getProtoSlice,
+ CODEX_REASONING_STRENGTH_OPTIONS,
+ CODEX_ACCOUNT_SERVICE_TIER_VALUES,
+ CODEX_GLOBAL_SERVICE_MODE_VALUES,
+ getCodexServiceTierLabel,
+ normalizeCodexLimitPolicy,
+ getCodexRequestDefaults,
+ getClaudeCodeCompatibleRequestDefaults,
+ compatProtocolLabelKey,
+ extractCommandCodeCredentialInput,
+ normalizeAndValidateHttpBaseUrl,
+ SILICONFLOW_ENDPOINTS,
+ type HeaderDraftRow,
+ type CompatModelRow,
+ type CompatModelMap,
+} from "../../src/app/(dashboard)/dashboard/providers/[id]/providerPageHelpers.ts";
+
+const tStub = Object.assign((key: string) => key, { has: (_k: string) => false });
+
+test("providerText falls back when key missing and interpolates values", () => {
+ assert.equal(providerText(tStub, "missing.key", "Hello {name}", { name: "X" }), "Hello X");
+ const tHas = Object.assign((key: string) => `T:${key}`, { has: (_k: string) => true });
+ assert.equal(providerText(tHas, "present.key", "fallback"), "T:present.key");
+});
+
+test("providerCountText picks singular/plural by count", () => {
+ assert.equal(providerCountText(tStub, "k", 1, "{count} item", "{count} items"), "1 item");
+ assert.equal(providerCountText(tStub, "k", 3, "{count} item", "{count} items"), "3 items");
+});
+
+test("readBooleanToggle coerces booleans/numbers/strings with fallback", () => {
+ assert.equal(readBooleanToggle(true, false), true);
+ assert.equal(readBooleanToggle(1, false), true);
+ assert.equal(readBooleanToggle("false", true), false);
+ assert.equal(readBooleanToggle(undefined, true), true);
+});
+
+test("base-url helpers run without throwing (transitive imports present)", () => {
+ // The key regression guard: isBaseUrlConfigurableProvider internally calls
+ // isSelfHostedChatProvider — a transitive import that must be wired up.
+ assert.doesNotThrow(() => isBaseUrlConfigurableProvider("openai"));
+ assert.equal(typeof isBaseUrlConfigurableProvider("openai"), "boolean");
+ assert.doesNotThrow(() => getLocalProviderMetadata("openai"));
+ assert.doesNotThrow(() => getProviderBaseUrlDefault("openai"));
+ assert.doesNotThrow(() => getProviderBaseUrlHint("openai", null));
+ assert.doesNotThrow(() => getProviderBaseUrlPlaceholder("openai"));
+ assert.equal(typeof isGlmProvider("glm"), "boolean");
+ assert.doesNotThrow(() => isBaseUrlConfigurableProvider(null));
+});
+
+test("routing-tags / excluded-models parse + format round-trip", () => {
+ assert.deepEqual(parseRoutingTagsInput("a, b ,c"), ["a", "b", "c"]);
+ assert.equal(parseRoutingTagsInput(" "), undefined);
+ assert.deepEqual(parseExcludedModelsInput("m1, m2"), ["m1", "m2"]);
+ assert.equal(formatRoutingTagsInput(["x", "y"]), "x, y");
+ assert.equal(formatExcludedModelsInput(["a", "b"]), "a, b");
+ assert.equal(formatRoutingTagsInput(undefined), "");
+});
+
+// ---------------------------------------------------------------------------
+// Phase 2b — runtime guards for the newly-moved helpers
+// ---------------------------------------------------------------------------
+
+const tokenReq = { kind: "token" as const, credentialName: "myToken" };
+const cookieReq = { kind: "cookie" as const, credentialName: "SESS" };
+const noneReq = { kind: "none" as const, credentialName: "" };
+
+test("getWebSessionCredentialLabel (Phase 2b — transitive import guard)", () => {
+ assert.ok(getWebSessionCredentialLabel(tStub, tokenReq, false).length > 0);
+ assert.ok(getWebSessionCredentialLabel(tStub, cookieReq, true).length > 0);
+ assert.ok(getWebSessionCredentialLabel(tStub, noneReq, false).length > 0);
+});
+
+test("getWebSessionCredentialHint returns undefined for none-kind, string otherwise", () => {
+ assert.equal(getWebSessionCredentialHint(tStub, noneReq, "Acme", false), undefined);
+ assert.equal(typeof getWebSessionCredentialHint(tStub, tokenReq, "Acme", false), "string");
+ assert.equal(typeof getWebSessionCredentialHint(tStub, cookieReq, "Acme", true), "string");
+});
+
+test("getWebSessionCredentialCheckLabel returns a non-empty string", () => {
+ assert.ok(getWebSessionCredentialCheckLabel(tStub, tokenReq).length > 0);
+ assert.ok(getWebSessionCredentialCheckLabel(tStub, cookieReq).length > 0);
+});
+
+test("getAddCredentialModalTitle handles null/none/token/cookie requirements", () => {
+ assert.ok(getAddCredentialModalTitle(tStub, "Acme", null).length > 0);
+ assert.ok(getAddCredentialModalTitle(tStub, "Acme", noneReq).length > 0);
+ assert.ok(getAddCredentialModalTitle(tStub, "Acme", tokenReq).length > 0);
+ assert.ok(getAddCredentialModalTitle(tStub, "Acme", cookieReq).length > 0);
+});
+
+test("upstreamHeadersRecordsEqual is order-insensitive and correct", () => {
+ assert.ok(upstreamHeadersRecordsEqual({ a: "1", b: "2" }, { b: "2", a: "1" }));
+ assert.ok(!upstreamHeadersRecordsEqual({ a: "1" }, { a: "2" }));
+ assert.ok(!upstreamHeadersRecordsEqual({ a: "1" }, { a: "1", b: "2" }));
+ assert.equal(UPSTREAM_HEADERS_UI_MAX, 16);
+});
+
+test("headerRowsToRecord filters blank name rows and builds record", () => {
+ const rows: HeaderDraftRow[] = [
+ { id: "1", name: "X-Foo", value: "bar" },
+ { id: "2", name: " ", value: "ignored" },
+ { id: "3", name: "X-Baz", value: "qux" },
+ ];
+ assert.deepEqual(headerRowsToRecord(rows), { "X-Foo": "bar", "X-Baz": "qux" });
+});
+
+test("effectiveUpstreamHeadersForProtocol merges base and protocol-specific headers", () => {
+ const row: CompatModelRow = {
+ id: "m1",
+ upstreamHeaders: { "X-Base": "base" },
+ compatByProtocol: { openai: { upstreamHeaders: { "X-Proto": "proto" } } },
+ };
+ const customMap: CompatModelMap = new Map([["m1", row]]);
+ const overrideMap: CompatModelMap = new Map();
+ const result = effectiveUpstreamHeadersForProtocol("m1", "openai", customMap, overrideMap);
+ assert.equal(result["X-Base"], "base");
+ assert.equal(result["X-Proto"], "proto");
+});
+
+test("anyUpstreamHeadersBadge detects non-empty upstream headers", () => {
+ const row: CompatModelRow = { id: "m1", upstreamHeaders: { "X-Foo": "bar" } };
+ const customMap: CompatModelMap = new Map([["m1", row]]);
+ const overrideMap: CompatModelMap = new Map();
+ assert.ok(anyUpstreamHeadersBadge("m1", customMap, overrideMap));
+ const emptyRow: CompatModelRow = { id: "m2", upstreamHeaders: {} };
+ const emptyMap: CompatModelMap = new Map([["m2", emptyRow]]);
+ assert.ok(!anyUpstreamHeadersBadge("m2", emptyMap, new Map()));
+});
+
+test("getProtoSlice returns custom compat over override", () => {
+ const custom: CompatModelRow = {
+ compatByProtocol: { openai: { normalizeToolCallId: true } },
+ };
+ const override: CompatModelRow = {
+ compatByProtocol: { openai: { normalizeToolCallId: false } },
+ };
+ const result = getProtoSlice(custom, override, "openai");
+ assert.equal(result?.normalizeToolCallId, true);
+});
+
+test("CODEX_REASONING_STRENGTH_OPTIONS has expected values", () => {
+ const values = CODEX_REASONING_STRENGTH_OPTIONS.map((o) => o.value);
+ assert.ok(values.includes("none"));
+ assert.ok(values.includes("high"));
+});
+
+test("CODEX_ACCOUNT_SERVICE_TIER_VALUES contains expected tiers", () => {
+ assert.ok(CODEX_ACCOUNT_SERVICE_TIER_VALUES.includes("default"));
+ assert.ok(CODEX_ACCOUNT_SERVICE_TIER_VALUES.includes("flex"));
+});
+
+test("CODEX_GLOBAL_SERVICE_MODE_VALUES starts with none", () => {
+ assert.equal(CODEX_GLOBAL_SERVICE_MODE_VALUES[0], "none");
+ assert.ok(CODEX_GLOBAL_SERVICE_MODE_VALUES.includes("priority"));
+});
+
+test("getCodexServiceTierLabel returns a string for every mode (transitive import guard)", () => {
+ for (const mode of CODEX_GLOBAL_SERVICE_MODE_VALUES) {
+ assert.equal(typeof getCodexServiceTierLabel(tStub, mode), "string");
+ }
+});
+
+test("normalizeCodexLimitPolicy defaults use5h and useWeekly to true", () => {
+ assert.deepEqual(normalizeCodexLimitPolicy(null), { use5h: true, useWeekly: true });
+ assert.deepEqual(normalizeCodexLimitPolicy({ use5h: false }), { use5h: false, useWeekly: true });
+});
+
+test("getCodexRequestDefaults returns reasoningEffort (transitive import guard)", () => {
+ const result = getCodexRequestDefaults(null);
+ assert.equal(typeof result.reasoningEffort, "string");
+});
+
+test("getClaudeCodeCompatibleRequestDefaults returns context1m boolean", () => {
+ const result = getClaudeCodeCompatibleRequestDefaults(null);
+ assert.equal(typeof result.context1m, "boolean");
+});
+
+test("compatProtocolLabelKey maps protocol strings to i18n keys", () => {
+ assert.equal(compatProtocolLabelKey("openai"), "compatProtocolOpenAI");
+ assert.equal(compatProtocolLabelKey("claude"), "compatProtocolClaude");
+ assert.equal(compatProtocolLabelKey("unknown"), "compatProtocolOpenAI");
+});
+
+test("extractCommandCodeCredentialInput extracts from JSON/URL/raw (transitive import guard)", () => {
+ assert.equal(extractCommandCodeCredentialInput(" "), "");
+ assert.equal(extractCommandCodeCredentialInput("rawtoken"), "rawtoken");
+ assert.equal(
+ extractCommandCodeCredentialInput(JSON.stringify({ apiKey: "abc123" })),
+ "abc123"
+ );
+});
+
+test("normalizeAndValidateHttpBaseUrl validates http/https URLs", () => {
+ const ok = normalizeAndValidateHttpBaseUrl("https://api.example.com/v1", "");
+ assert.equal(ok.error, null);
+ assert.equal(ok.value, "https://api.example.com/v1");
+ const bad = normalizeAndValidateHttpBaseUrl("ftp://nope.com", "");
+ assert.ok(bad.error !== null);
+ const invalid = normalizeAndValidateHttpBaseUrl("not-a-url", "");
+ assert.ok(invalid.error !== null);
+});
+
+test("SILICONFLOW_ENDPOINTS has global and china entries", () => {
+ const ids = SILICONFLOW_ENDPOINTS.map((e) => e.id);
+ assert.ok(ids.includes("siliconflow"));
+ assert.ok(ids.includes("siliconflow-cn"));
+});
diff --git a/tests/unit/quota-deactivate-toggle.test.ts b/tests/unit/quota-deactivate-toggle.test.ts
new file mode 100644
index 0000000000..50de83a3b0
--- /dev/null
+++ b/tests/unit/quota-deactivate-toggle.test.ts
@@ -0,0 +1,83 @@
+/**
+ * Quota overview gains a per-account deactivate/activate toggle, so an operator
+ * can park an account that is still being routed to despite low quota. The
+ * toggle reuses PUT /api/providers/[id] with { isActive } and dims the card when
+ * the account is inactive. Validated by asserting the wiring in the component
+ * sources (same lightweight approach as quota-token-expiry-display.test.ts).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
+const base = "src/app/(dashboard)/dashboard/usage/components/ProviderLimits";
+const read = (rel: string) => fs.readFileSync(path.join(repoRoot, base, rel), "utf8");
+
+const header = read("parts/QuotaCardHeader.tsx");
+const card = read("QuotaCard.tsx");
+const grid = read("QuotaCardGrid.tsx");
+const index = read("index.tsx");
+
+test("QuotaCardHeader renders a toggle that flips the current active state", () => {
+ assert.match(header, /onToggleActive:\s*\(nextActive: boolean\)\s*=>\s*void/);
+ assert.match(header, /const isActive = connection\.isActive \?\? true/);
+ assert.match(header, /onToggleActive\(!isActive\)/, "click must flip the current state");
+ assert.match(header, /toggle_on/, "active state icon");
+ assert.match(header, /toggle_off/, "inactive state icon");
+ assert.match(header, /disabled=\{togglingActive\}/, "disabled while the PUT is in flight");
+});
+
+test("QuotaCard dims the card and threads the toggle props through", () => {
+ assert.match(card, /const isActive = connection\.isActive \?\? true/);
+ assert.match(card, /opacity-60/, "inactive accounts are visually dimmed");
+ assert.match(card, /onToggleActive=\{onToggleActive\}/);
+ assert.match(card, /togglingActive=\{togglingActive\}/);
+});
+
+test("QuotaCardGrid forwards the per-connection toggle handler and busy id", () => {
+ assert.match(grid, /onToggleActive:\s*\(id: string, nextActive: boolean\)\s*=>\s*void/);
+ assert.match(
+ grid,
+ /onToggleActive=\{\(nextActive\)\s*=>\s*onToggleActive\(conn\.id, nextActive\)\}/
+ );
+ assert.match(grid, /togglingActive=\{togglingActiveId === conn\.id\}/);
+});
+
+test("index handleToggleActive PUTs isActive, updates state and notifies", () => {
+ assert.match(index, /const handleToggleActive = useCallback\(/);
+ assert.match(
+ index,
+ /fetch\(`\/api\/providers\/\$\{connectionId\}`,\s*\{[\s\S]*method:\s*"PUT"[\s\S]*isActive: nextActive/,
+ "must PUT { isActive } to the per-connection route"
+ );
+ assert.match(
+ index,
+ /c\.id === connectionId \? \{ \.\.\.c, isActive: nextActive \} : c/,
+ "must optimistically update local connection state"
+ );
+ assert.match(
+ index,
+ /onToggleActive=\{handleToggleActive\}/,
+ "must wire the handler into the grid"
+ );
+ assert.match(index, /togglingActiveId=\{togglingActiveId\}/);
+});
+
+test("toggle i18n keys exist in en and pt-BR", () => {
+ for (const locale of ["en", "pt-BR"]) {
+ const msgs = JSON.parse(
+ fs.readFileSync(path.join(repoRoot, `src/i18n/messages/${locale}.json`), "utf8")
+ );
+ for (const key of [
+ "deactivateAccount",
+ "activateAccount",
+ "accountActivated",
+ "accountDeactivated",
+ "toggleActiveFailed",
+ ]) {
+ assert.ok(msgs.usage?.[key], `${locale}: usage.${key} must exist`);
+ }
+ }
+});
diff --git a/tests/unit/reasoning-cache.test.ts b/tests/unit/reasoning-cache.test.ts
index 9731ac3428..acc32671d1 100644
--- a/tests/unit/reasoning-cache.test.ts
+++ b/tests/unit/reasoning-cache.test.ts
@@ -772,9 +772,8 @@ describe("Reasoning Replay Cache — Translator Replay", () => {
},
});
- const { NON_ANTHROPIC_THINKING_PLACEHOLDER } = await import(
- "../../open-sse/translator/helpers/claudeHelper.ts"
- );
+ const { NON_ANTHROPIC_THINKING_PLACEHOLDER } =
+ await import("../../open-sse/translator/helpers/claudeHelper.ts");
// No cache entry → cache miss
const translated = translateRequest(
@@ -810,6 +809,99 @@ describe("Reasoning Replay Cache — Translator Replay", () => {
"empty reasoning_content should be replaced with placeholder on cache miss"
);
});
+
+ it("should inject placeholder for a plain (non-tool-call) DeepSeek turn missing reasoning_content (#1682)", async () => {
+ // Regression (#1682): a multi-turn text conversation where the prior assistant
+ // turn has NO tool calls and the client (e.g. Cursor) stripped reasoning_content
+ // from history. DeepSeek V4+ still requires reasoning_content on every assistant
+ // message in thinking mode, so without a placeholder the upstream returns 400.
+ clearReasoningCacheAll();
+ clearModelsDevCapabilities();
+ saveModelsDevCapabilities({
+ deepseek: {
+ "deepseek-v4-pro": buildCapability({
+ interleaved_field: "reasoning_content",
+ reasoning: true,
+ tool_call: true,
+ }),
+ },
+ });
+
+ const { NON_ANTHROPIC_THINKING_PLACEHOLDER } =
+ await import("../../open-sse/translator/helpers/claudeHelper.ts");
+
+ const translated = translateRequest(
+ FORMATS.OPENAI,
+ FORMATS.OPENAI,
+ "deepseek-v4-pro",
+ {
+ messages: [
+ { role: "user", content: "hi" },
+ // Plain assistant turn, no tool_calls, reasoning_content stripped by client.
+ { role: "assistant", content: "Hello! How can I help?" },
+ { role: "user", content: "tell me more" },
+ ],
+ },
+ false,
+ null,
+ "deepseek"
+ );
+
+ assert.equal(
+ translated.messages[1].reasoning_content,
+ NON_ANTHROPIC_THINKING_PLACEHOLDER,
+ "plain DeepSeek assistant turn missing reasoning_content should get the placeholder"
+ );
+ });
+
+ it("should replay cached reasoning for a plain (non-tool-call) DeepSeek turn when available (#1682)", () => {
+ // When a request_id-keyed cache entry exists for the plain turn, the real
+ // reasoning is replayed instead of the placeholder.
+ clearReasoningCacheAll();
+ clearModelsDevCapabilities();
+ saveModelsDevCapabilities({
+ deepseek: {
+ "deepseek-v4-pro": buildCapability({
+ interleaved_field: "reasoning_content",
+ reasoning: true,
+ tool_call: true,
+ }),
+ },
+ });
+ // NOTE: the non-tool-call cache key is built as `getAssistantMessageCacheKey(result, 0)`
+ // — the message index is hardcoded to 0 in the translator, so the key is always
+ // `request:<id>:message:0` regardless of the assistant message's actual position.
+ cacheReasoning(
+ "request:req-plain-1:message:0",
+ "deepseek",
+ "deepseek-v4-pro",
+ "Real cached plain-turn reasoning"
+ );
+
+ const translated = translateRequest(
+ FORMATS.OPENAI,
+ FORMATS.OPENAI,
+ "deepseek-v4-pro",
+ {
+ request_id: "req-plain-1",
+ messages: [
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Hello! How can I help?" },
+ { role: "user", content: "tell me more" },
+ ],
+ },
+ false,
+ null,
+ "deepseek"
+ );
+
+ assert.equal(
+ translated.messages[1].reasoning_content,
+ "Real cached plain-turn reasoning",
+ "plain DeepSeek assistant turn should replay the real cached reasoning when present"
+ );
+ assert.equal(getReasoningCacheServiceStats().replays, 1);
+ });
});
describe("Reasoning Replay Cache — API Route", () => {
diff --git a/tests/unit/responses-ws-proxy.test.mjs b/tests/unit/responses-ws-proxy.test.mjs
index 382ced9b9c..e9de940650 100644
--- a/tests/unit/responses-ws-proxy.test.mjs
+++ b/tests/unit/responses-ws-proxy.test.mjs
@@ -75,6 +75,10 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket events
ok: true,
upstreamUrl: "wss://chatgpt.com/backend-api/codex/responses",
headers: { Authorization: "Bearer upstream-token" },
+ connectionId: "conn_1",
+ provider: "codex",
+ account: "[email protected]",
+ model: "gpt-5.5",
response: {
...body.response,
model: "gpt-5.5",
@@ -84,6 +88,12 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket events
);
return;
}
+
+ if (body.action === "log") {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true, logged: true }));
+ return;
+ }
}
res.writeHead(404, { "content-type": "application/json" });
@@ -97,7 +107,12 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket events
fakeUpstream.onmessage?.({
data: JSON.stringify({
type: "response.completed",
- response: { id: "resp_1", status: "completed" },
+ response: {
+ id: "resp_1",
+ model: "gpt-5.5",
+ status: "completed",
+ usage: { input_tokens: 29, output_tokens: 42, total_tokens: 71 },
+ },
}),
});
}, 10);
@@ -145,6 +160,7 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket events
);
await waitFor(() => downstreamMessages.find((entry) => entry.type === "response.completed"));
+ const logRequest = await waitFor(() => internalRequests.find((entry) => entry.action === "log"));
assert.equal(internalRequests[0].action, "authenticate");
assert.equal(internalRequests[1].action, "prepare");
@@ -153,6 +169,104 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket events
assert.equal(upstreamSends[0].model, "gpt-5.5");
assert.equal(upstreamSends[0].reasoning.effort, "xhigh");
assert.equal("stream" in upstreamSends[0], false);
+ assert.equal(logRequest.transport, "responses_websocket");
+ assert.equal(logRequest.status, 200);
+ assert.equal(logRequest.success, true);
+ assert.equal(logRequest.connectionId, "conn_1");
+ assert.equal(logRequest.provider, "codex");
+ assert.equal(logRequest.model, "gpt-5.5");
+ assert.equal(logRequest.requestedModel, "gpt-5.5");
+ assert.equal(logRequest.clientRequest.model, "gpt-5.5");
+ assert.equal(logRequest.responseBody.usage.input_tokens, 29);
+ assert.equal(logRequest.responseBody.usage.output_tokens, 42);
+ assert.equal(logRequest.terminalMessage.type, "response.completed");
+
+ ws.close();
+ await close(server);
+});
+
+test("responses ws proxy logs prepare failures to request history", async () => {
+ const internalRequests = [];
+ const downstreamMessages = [];
+
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
+ if (url.pathname === "/api/internal/codex-responses-ws") {
+ const body = JSON.parse((await readRequestBody(req)) || "{}");
+ internalRequests.push(body);
+
+ if (body.action === "authenticate") {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true, authenticated: true, authType: "api_key" }));
+ return;
+ }
+
+ if (body.action === "prepare") {
+ res.writeHead(503, { "content-type": "application/json" });
+ res.end(
+ JSON.stringify({
+ error: {
+ code: "codex_credentials_unavailable",
+ message: "No available Codex OAuth connection for Responses WebSocket",
+ },
+ })
+ );
+ return;
+ }
+
+ if (body.action === "log") {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true, logged: true }));
+ return;
+ }
+ }
+
+ res.writeHead(404, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: "not_found" }));
+ });
+
+ const port = await listen(server);
+ const proxy = createResponsesWsProxy({
+ baseUrl: `http://127.0.0.1:${port}`,
+ bridgeSecret: "bridge-secret",
+ pingIntervalMs: 1000,
+ idleTimeoutMs: 10000,
+ wsFactory: async () => {
+ throw new Error("prepare failure should not connect upstream");
+ },
+ });
+
+ server.on("upgrade", async (req, socket, head) => {
+ const handled = await proxy.handleUpgrade(req, socket, head);
+ if (!handled && !socket.destroyed) {
+ socket.destroy();
+ }
+ });
+
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/api/v1/responses?api_key=local-token`);
+ ws.addEventListener("message", (event) => {
+ downstreamMessages.push(JSON.parse(String(event.data)));
+ });
+
+ await new Promise((resolve) => ws.addEventListener("open", resolve, { once: true }));
+ ws.send(
+ JSON.stringify({
+ type: "response.create",
+ model: "gpt-5.5",
+ input: [{ role: "user", content: "hello" }],
+ })
+ );
+
+ await waitFor(() => downstreamMessages.find((entry) => entry.type === "response.failed"));
+ const logRequest = await waitFor(() => internalRequests.find((entry) => entry.action === "log"));
+
+ assert.equal(logRequest.transport, "responses_websocket");
+ assert.equal(logRequest.status, 503);
+ assert.equal(logRequest.success, false);
+ assert.equal(logRequest.errorCode, "codex_credentials_unavailable");
+ assert.match(logRequest.errorMessage, /No available Codex OAuth connection/);
+ assert.equal(logRequest.clientRequest.model, "gpt-5.5");
+ assert.equal(logRequest.terminalMessage.type, "response.failed");
ws.close();
await close(server);
diff --git a/tests/unit/rtl-logical-classes.test.tsx b/tests/unit/rtl-logical-classes.test.tsx
new file mode 100644
index 0000000000..8d92525a85
--- /dev/null
+++ b/tests/unit/rtl-logical-classes.test.tsx
@@ -0,0 +1,117 @@
+/**
+ * RTL layout regression test — #3541 (partial, core layout)
+ *
+ * For RTL locales (ar/fa/he/ur) the sidebar and key overlays must flip
+ * correctly when `dir=rtl` is set on <html>. Tailwind v4 supports logical
+ * direction utilities natively (`start-*`, `end-*`, `ps-*`, `pe-*`, `ms-*`,
+ * `me-*`, `text-start`, `text-end`) which auto-mirror under dir=rtl without
+ * extra `rtl:` variants.
+ *
+ * This test reads the source files and asserts that the four high-impact
+ * components use logical classes instead of physical directional ones where
+ * those classes govern layout placement / offset.
+ *
+ * Runner: Vitest (included via `tests/unit/**\/*.test.tsx` in vitest.config.ts)
+ * Command: npm run test:vitest -- --reporter=verbose --testPathPattern=rtl-logical
+ */
+
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "fs";
+import { resolve } from "path";
+
+const cwd = process.cwd();
+
+function src(rel: string) {
+ return readFileSync(resolve(cwd, rel), "utf-8");
+}
+
+// ─── DashboardLayout.tsx ──────────────────────────────────────────────────────
+
+describe("DashboardLayout — mobile sidebar drawer uses logical classes", () => {
+ const code = src("src/shared/components/layouts/DashboardLayout.tsx");
+
+ it('uses start-0 (not bare left-0) for the mobile sidebar drawer', () => {
+ // The drawer must anchor to the inline-start edge so it flips in RTL.
+ expect(code).toContain("start-0");
+ });
+
+ it('does not use bare left-0 for the mobile sidebar drawer', () => {
+ // "inset-y-0 left-0" is the old physical class that breaks RTL.
+ expect(code).not.toContain("inset-y-0 left-0");
+ });
+
+ it('uses -translate-x-full only when combined with RTL-aware transform or logical alternative', () => {
+ // We keep -translate-x-full/translate-x-0 for slide animation but anchor
+ // with start-0 so physical translate still produces correct visual result
+ // in both LTR and RTL (the drawer always slides in from its own start edge).
+ // Just confirm start-0 is present (already asserted above).
+ expect(code).toContain("start-0");
+ });
+});
+
+// ─── Sidebar.tsx ─────────────────────────────────────────────────────────────
+
+describe("Sidebar — collapse toggle button uses logical margin", () => {
+ const code = src("src/shared/components/Sidebar.tsx");
+
+ it('uses ms-auto (not ml-auto) for the macOS collapse-toggle alignment', () => {
+ // ml-auto is a physical class; ms-auto mirrors in RTL.
+ expect(code).toContain("ms-auto");
+ });
+
+ it('does not use bare ml-auto in the collapse-toggle className', () => {
+ expect(code).not.toContain("ml-auto");
+ });
+});
+
+// ─── LanguageSelector.tsx ─────────────────────────────────────────────────────
+
+describe("LanguageSelector — dropdown anchors to inline-end", () => {
+ const code = src("src/shared/components/LanguageSelector.tsx");
+
+ it('uses end-0 (not right-0) for the dropdown panel', () => {
+ expect(code).toContain("end-0");
+ });
+
+ it('does not use bare right-0 for the dropdown panel', () => {
+ expect(code).not.toContain("right-0");
+ });
+
+ it('uses text-start (not text-left) for lang name text alignment', () => {
+ expect(code).toContain("text-start");
+ });
+
+ it('does not use text-left for lang name text alignment', () => {
+ expect(code).not.toContain("text-left");
+ });
+});
+
+// ─── Select.tsx ───────────────────────────────────────────────────────────────
+
+describe("Select — chevron icon uses logical inset classes", () => {
+ const code = src("src/shared/components/Select.tsx");
+
+ it('uses end-0 (not right-0) for the chevron wrapper', () => {
+ expect(code).toContain("end-0");
+ });
+
+ it('does not use bare right-0 for the chevron wrapper', () => {
+ expect(code).not.toContain("right-0");
+ });
+
+ it('uses pe-3 (not pr-3) for chevron wrapper padding', () => {
+ expect(code).toContain("pe-3");
+ });
+
+ it('does not use bare pr-3 for chevron wrapper padding', () => {
+ expect(code).not.toContain("pr-3");
+ });
+
+ it('uses pe-10 (not pr-10) for the select element right-pad (space for chevron)', () => {
+ expect(code).toContain("pe-10");
+ });
+
+ it('does not use bare pr-10 for the select element', () => {
+ expect(code).not.toContain("pr-10");
+ });
+});
diff --git a/tests/unit/settings-schema-routing-strategies.test.ts b/tests/unit/settings-schema-routing-strategies.test.ts
index 2e0fb878ee..04b94523a4 100644
--- a/tests/unit/settings-schema-routing-strategies.test.ts
+++ b/tests/unit/settings-schema-routing-strategies.test.ts
@@ -58,6 +58,18 @@ test("settings schemas accept wsAuth toggle", () => {
assert.equal(sharedParsed.wsAuth, false);
});
+test("settings schemas accept Claude Code unprefixed model routing toggle", () => {
+ const routeParsed = settingsRouteSchema.parse({
+ preferClaudeCodeForUnprefixedClaudeModels: true,
+ });
+ const sharedParsed = sharedSettingsSchema.parse({
+ preferClaudeCodeForUnprefixedClaudeModels: false,
+ });
+
+ assert.equal(routeParsed.preferClaudeCodeForUnprefixedClaudeModels, true);
+ assert.equal(sharedParsed.preferClaudeCodeForUnprefixedClaudeModels, false);
+});
+
test("settings schemas accept combo configuration modes", () => {
const routeParsed = settingsRouteSchema.parse({ comboConfigMode: "expert" });
const sharedParsed = sharedSettingsSchema.parse({ comboConfigMode: "guided" });
diff --git a/tests/unit/startup-stale-cooldown-recovery.test.ts b/tests/unit/startup-stale-cooldown-recovery.test.ts
new file mode 100644
index 0000000000..3c637eae85
--- /dev/null
+++ b/tests/unit/startup-stale-cooldown-recovery.test.ts
@@ -0,0 +1,277 @@
+/**
+ * TDD regression guard for issue #3625 (Part A).
+ *
+ * After an unclean process crash (SIGKILL / large-body burst), provider
+ * connections can be left in the DB with a far-future `rate_limited_until`
+ * (stale exponential-backoff value). On restart, getProviderCredentials()
+ * skips those connections and Bottleneck queues time out at 120 s.
+ *
+ * The fix: on startup, scan `provider_connections` and clear transient
+ * cooldown fields for any non-terminal connection that has a
+ * `rate_limited_until` set (past *or* future). Terminal states
+ * (banned / expired / credits_exhausted) must not be touched.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(
+ path.join(os.tmpdir(), "omniroute-startup-cooldown-recovery-")
+);
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const providersDb = await import("../../src/lib/db/providers.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ break;
+ } catch (error: any) {
+ if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
+ } else {
+ throw error;
+ }
+ }
+ }
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ─── helpers ────────────────────────────────────────────────────────────────
+
+/** Far-future epoch ms (simulates a crash-burst backoff). */
+const FAR_FUTURE = Date.now() + 60 * 60 * 1000; // +1 hour
+
+/** Slightly past timestamp (normal lazy expiry — also cleared on startup). */
+const JUST_PAST = Date.now() - 10_000; // -10 s
+
+// ─── tests ──────────────────────────────────────────────────────────────────
+
+test("clearStaleCrashCooldowns clears far-future transient cooldown on restart", async () => {
+ const conn = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "Stale Cooldown",
+ apiKey: "sk-test",
+ });
+
+ // Simulate crash-burst state: far-future cooldown, transient error fields
+ await providersDb.updateProviderConnection(conn.id, {
+ ...conn,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "unavailable",
+ lastError: "upstream timeout",
+ lastErrorType: "timeout",
+ backoffLevel: 3,
+ });
+
+ // Verify pre-condition: connection has a far-future cooldown persisted
+ const pre = await providersDb.getProviderConnectionById(conn.id);
+ assert.ok(
+ pre?.rateLimitedUntil && new Date(pre.rateLimitedUntil as string).getTime() > Date.now(),
+ "connection should have a future rate_limited_until before recovery"
+ );
+
+ // Run startup recovery
+ const result = providersDb.clearStaleCrashCooldowns();
+
+ assert.ok(result.cleared >= 1, `expected at least 1 cleared, got ${result.cleared}`);
+
+ // Verify post-condition: cooldown is gone (cleanNulls strips null → undefined)
+ const updated = await providersDb.getProviderConnectionById(conn.id);
+ assert.ok(!updated?.rateLimitedUntil, "rateLimitedUntil should be absent/falsy after recovery");
+ assert.equal(updated?.testStatus, "active", "testStatus should be 'active' after recovery");
+ assert.equal(updated?.backoffLevel, 0, "backoffLevel should be 0 after recovery");
+ assert.ok(!updated?.lastError, "lastError should be absent/falsy after recovery");
+ assert.ok(!updated?.lastErrorType, "lastErrorType should be absent/falsy after recovery");
+});
+
+test("clearStaleCrashCooldowns clears past-dated transient cooldown on restart", async () => {
+ const conn = await providersDb.createProviderConnection({
+ provider: "anthropic",
+ authType: "apikey",
+ name: "Past Cooldown",
+ apiKey: "sk-anth",
+ });
+
+ await providersDb.updateProviderConnection(conn.id, {
+ ...conn,
+ rateLimitedUntil: new Date(JUST_PAST).toISOString(),
+ testStatus: "unavailable",
+ backoffLevel: 1,
+ });
+
+ const result = providersDb.clearStaleCrashCooldowns();
+
+ assert.ok(result.cleared >= 1, `expected at least 1 cleared, got ${result.cleared}`);
+
+ const updated = await providersDb.getProviderConnectionById(conn.id);
+ assert.ok(!updated?.rateLimitedUntil, "past cooldown should also be cleared on startup");
+ assert.equal(updated?.testStatus, "active", "testStatus should be 'active'");
+ assert.equal(updated?.backoffLevel, 0, "backoffLevel should be 0");
+});
+
+test("clearStaleCrashCooldowns does NOT clear terminal states (banned)", async () => {
+ const conn = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "Banned Key",
+ apiKey: "sk-banned",
+ });
+
+ await providersDb.updateProviderConnection(conn.id, {
+ ...conn,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "banned",
+ backoffLevel: 5,
+ });
+
+ const result = providersDb.clearStaleCrashCooldowns();
+
+ // The banned connection must NOT be cleared
+ const updated = await providersDb.getProviderConnectionById(conn.id);
+ assert.equal(updated?.testStatus, "banned", "banned connection must not be touched");
+ assert.ok(
+ updated?.rateLimitedUntil,
+ "rate_limited_until on a banned connection must not be cleared"
+ );
+ // cleared count should be 0 (only the banned conn exists in this test)
+ assert.equal(result.cleared, 0, "no transient connections to clear");
+});
+
+test("clearStaleCrashCooldowns does NOT clear terminal states (expired)", async () => {
+ const conn = await providersDb.createProviderConnection({
+ provider: "glm",
+ authType: "oauth",
+ name: "Expired Token",
+ });
+
+ await providersDb.updateProviderConnection(conn.id, {
+ ...conn,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "expired",
+ backoffLevel: 2,
+ });
+
+ providersDb.clearStaleCrashCooldowns();
+
+ const updated = await providersDb.getProviderConnectionById(conn.id);
+ assert.equal(updated?.testStatus, "expired", "expired connection must not be touched");
+});
+
+test("clearStaleCrashCooldowns does NOT clear terminal states (credits_exhausted)", async () => {
+ const conn = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "Exhausted",
+ apiKey: "sk-exhausted",
+ });
+
+ await providersDb.updateProviderConnection(conn.id, {
+ ...conn,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "credits_exhausted",
+ backoffLevel: 4,
+ });
+
+ providersDb.clearStaleCrashCooldowns();
+
+ const updated = await providersDb.getProviderConnectionById(conn.id);
+ assert.equal(
+ updated?.testStatus,
+ "credits_exhausted",
+ "credits_exhausted connection must not be touched"
+ );
+});
+
+test("clearStaleCrashCooldowns returns cleared=0 when no transient cooldowns exist", async () => {
+ // Create a clean connection (no cooldown)
+ await providersDb.createProviderConnection({
+ provider: "gemini",
+ authType: "apikey",
+ name: "Clean",
+ apiKey: "ai-key",
+ });
+
+ const result = providersDb.clearStaleCrashCooldowns();
+
+ assert.equal(result.cleared, 0, "no cooldowns to clear");
+});
+
+test("clearStaleCrashCooldowns handles mixed transient + terminal connections correctly", async () => {
+ // Transient — should be cleared
+ const transient1 = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "Transient 1",
+ apiKey: "sk-t1",
+ });
+ await providersDb.updateProviderConnection(transient1.id, {
+ ...transient1,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "unavailable",
+ backoffLevel: 2,
+ });
+
+ const transient2 = await providersDb.createProviderConnection({
+ provider: "anthropic",
+ authType: "apikey",
+ name: "Transient 2",
+ apiKey: "sk-t2",
+ });
+ await providersDb.updateProviderConnection(transient2.id, {
+ ...transient2,
+ rateLimitedUntil: new Date(JUST_PAST).toISOString(),
+ testStatus: "unavailable",
+ backoffLevel: 1,
+ });
+
+ // Terminal — must NOT be cleared
+ const terminal = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "Banned",
+ apiKey: "sk-banned",
+ });
+ await providersDb.updateProviderConnection(terminal.id, {
+ ...terminal,
+ rateLimitedUntil: new Date(FAR_FUTURE).toISOString(),
+ testStatus: "banned",
+ backoffLevel: 5,
+ });
+
+ const result = providersDb.clearStaleCrashCooldowns();
+
+ assert.equal(result.cleared, 2, "exactly 2 transient connections cleared");
+
+ const updatedT1 = await providersDb.getProviderConnectionById(transient1.id);
+ assert.ok(!updatedT1?.rateLimitedUntil, "transient1 cooldown cleared");
+ assert.equal(updatedT1?.testStatus, "active", "transient1 status active");
+
+ const updatedT2 = await providersDb.getProviderConnectionById(transient2.id);
+ assert.ok(!updatedT2?.rateLimitedUntil, "transient2 cooldown cleared");
+ assert.equal(updatedT2?.testStatus, "active", "transient2 status active");
+
+ const updatedTerminal = await providersDb.getProviderConnectionById(terminal.id);
+ assert.equal(updatedTerminal?.testStatus, "banned", "terminal connection untouched");
+ assert.ok(
+ updatedTerminal?.rateLimitedUntil,
+ "terminal rate_limited_until preserved"
+ );
+});
diff --git a/tests/unit/stream-readiness.test.ts b/tests/unit/stream-readiness.test.ts
index bcd36ab671..ebfedf1c11 100644
--- a/tests/unit/stream-readiness.test.ts
+++ b/tests/unit/stream-readiness.test.ts
@@ -327,6 +327,8 @@ test("hasStreamReadinessSignal accepts structural chat completion chunk starts",
),
false
);
+ // #3612: index-only tool_call chunk (first chunk in OpenAI streaming — no id yet)
+ // MUST be treated as a readiness signal (tool-call has started)
assert.equal(
hasStreamReadinessSignal(
`data: ${JSON.stringify({
@@ -334,7 +336,7 @@ test("hasStreamReadinessSignal accepts structural chat completion chunk starts",
choices: [{ index: 0, delta: { tool_calls: [{ index: 0 }] } }],
})}\n\n`
),
- false
+ true
);
assert.equal(
hasStreamReadinessSignal(
@@ -345,6 +347,27 @@ test("hasStreamReadinessSignal accepts structural chat completion chunk starts",
),
false
);
+ // #3612: chunk with valid choices but NO object/type field (some OA-compatible backends
+ // omit object) — must be accepted as a readiness signal when delta.role is present
+ assert.equal(
+ hasStreamReadinessSignal(
+ `data: ${JSON.stringify({
+ id: "chatcmpl-xyz",
+ choices: [{ index: 0, delta: { role: "assistant" } }],
+ })}\n\n`
+ ),
+ true
+ );
+ // object present but a different (non-chat-chunk) type must still be rejected
+ assert.equal(
+ hasStreamReadinessSignal(
+ `data: ${JSON.stringify({
+ object: "chat.completion",
+ choices: [{ index: 0, delta: { role: "assistant" } }],
+ })}\n\n`
+ ),
+ false
+ );
});
test("ensureStreamReadiness preserves buffered chunks when stream starts", async () => {
diff --git a/tests/unit/topology-active-requests-3507.test.ts b/tests/unit/topology-active-requests-3507.test.ts
new file mode 100644
index 0000000000..17de320151
--- /dev/null
+++ b/tests/unit/topology-active-requests-3507.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #3507 — the home Provider Topology pulse was dead because activeRequests was
+ * hardcoded to []. Fix: map the in-flight LiveRequest entries (pending/running)
+ * from useLiveRequests to the { provider, model }[] shape expected by
+ * <ProviderTopology>.
+ *
+ * selectActiveRequests() is a pure mapping function — no React required.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { selectActiveRequests } from "../../src/app/(dashboard)/home/topologyUtils.ts";
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+function makeRequest(
+ overrides: Partial<{
+ id: string;
+ model: string;
+ provider: string;
+ status: "pending" | "running" | "success" | "error";
+ }>
+) {
+ return {
+ id: "req-1",
+ model: "gpt-4",
+ provider: "openai",
+ timestamp: Date.now(),
+ status: "pending" as const,
+ ...overrides,
+ };
+}
+
+// ── tests ─────────────────────────────────────────────────────────────────────
+
+test("selectActiveRequests: maps pending requests to {provider, model}", () => {
+ const input = [makeRequest({ id: "a", provider: "anthropic", model: "claude-opus-4", status: "pending" })];
+ const result = selectActiveRequests(input);
+ assert.deepEqual(result, [{ provider: "anthropic", model: "claude-opus-4" }]);
+});
+
+test("selectActiveRequests: maps running requests to {provider, model}", () => {
+ const input = [makeRequest({ id: "b", provider: "openai", model: "gpt-4o", status: "running" })];
+ const result = selectActiveRequests(input);
+ assert.deepEqual(result, [{ provider: "openai", model: "gpt-4o" }]);
+});
+
+test("selectActiveRequests: returns empty array for empty input", () => {
+ assert.deepEqual(selectActiveRequests([]), []);
+});
+
+test("selectActiveRequests: maps multiple concurrent in-flight requests", () => {
+ const input = [
+ makeRequest({ id: "c1", provider: "anthropic", model: "claude-sonnet-4", status: "pending" }),
+ makeRequest({ id: "c2", provider: "gemini", model: "gemini-2.5-pro", status: "running" }),
+ ];
+ const result = selectActiveRequests(input);
+ assert.deepEqual(result, [
+ { provider: "anthropic", model: "claude-sonnet-4" },
+ { provider: "gemini", model: "gemini-2.5-pro" },
+ ]);
+});
+
+test("selectActiveRequests: only extracts provider and model fields (not id/timestamp/etc)", () => {
+ const input = [makeRequest({ id: "d", provider: "groq", model: "llama3-70b", status: "running" })];
+ const result = selectActiveRequests(input);
+ assert.equal(Object.keys(result[0]).length, 2);
+ assert.ok("provider" in result[0]);
+ assert.ok("model" in result[0]);
+ assert.ok(!("id" in result[0]));
+ assert.ok(!("timestamp" in result[0]));
+});
diff --git a/tests/unit/webdav-server-3485.test.ts b/tests/unit/webdav-server-3485.test.ts
new file mode 100644
index 0000000000..92876c8b13
--- /dev/null
+++ b/tests/unit/webdav-server-3485.test.ts
@@ -0,0 +1,784 @@
+/**
+ * TDD tests for the WebDAV server (PR2, issue #3485).
+ *
+ * Tests cover the PURE logic exported by scripts/dev/webdav-handler.mjs:
+ * - resolveVaultPath: path traversal guard
+ * - verifyBasicAuth: correct/wrong/malformed creds, constant-time path
+ * - decryptStored: values encrypted by src/lib/db/encryption.ts decrypt correctly
+ * - buildPropfindXml: structure, special-char escaping, collection vs file
+ * - PUT/GET round-trip, DELETE, MKCOL, MOVE via thin HTTP test harness
+ * - disabled/no-creds → 503 (not served)
+ *
+ * Uses Node's native test runner (no vitest dependency).
+ * Filesystem operations use a real temp dir (fs.mkdtempSync).
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import http from "node:http";
+import { EventEmitter } from "node:events";
+import { createCipheriv, randomBytes, scryptSync } from "node:crypto";
+import { pathToFileURL } from "node:url";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Helpers
+// ─────────────────────────────────────────────────────────────────────────────
+
+const HANDLER_PATH = path.resolve(
+ path.dirname(new URL(import.meta.url).pathname),
+ "../../scripts/dev/webdav-handler.mjs"
+);
+
+/** Import the handler module fresh (bust module cache for env-dependent tests). */
+async function importHandler(): Promise<typeof import("../../scripts/dev/webdav-handler.mjs")> {
+ const url = pathToFileURL(HANDLER_PATH).href;
+ return import(`${url}?t=${Date.now()}-${Math.random().toString(36).slice(2)}`);
+}
+
+/** Encrypt a string with the OmniRoute enc:v1: format using the given secret.
+ * Mirrors src/lib/db/encryption.ts: scrypt with static salt, AES-256-GCM. */
+function encryptTs(secret: string, plaintext: string): string {
+ const STATIC_SALT = "omniroute-field-encryption-v1";
+ const key = scryptSync(secret, STATIC_SALT, 32);
+ const iv = randomBytes(16);
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
+ let encrypted = cipher.update(plaintext, "utf8", "hex");
+ encrypted += cipher.final("hex");
+ const authTag = cipher.getAuthTag().toString("hex");
+ return `enc:v1:${iv.toString("hex")}:${encrypted}:${authTag}`;
+}
+
+/** Create a simple IncomingMessage-like object for unit tests. */
+function fakeReq(
+ method: string,
+ url: string,
+ headers: Record<string, string> = {},
+ body: Buffer | null = null
+): http.IncomingMessage {
+ const req = Object.assign(new EventEmitter(), {
+ method,
+ url,
+ headers: Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])),
+ socket: { remoteAddress: "127.0.0.1" },
+ }) as unknown as http.IncomingMessage;
+
+ if (body !== null) {
+ // Emit data/end on next tick so async consumers can wire listeners first
+ setImmediate(() => {
+ req.emit("data", body);
+ req.emit("end");
+ });
+ } else {
+ setImmediate(() => {
+ req.emit("end");
+ });
+ }
+
+ return req;
+}
+
+/** Capture a ServerResponse into { status, headers, body }. */
+async function captureRes(
+ req: http.IncomingMessage,
+ handler: (req: http.IncomingMessage, res: http.ServerResponse) => Promise<boolean>
+): Promise<{ status: number; headers: http.OutgoingHttpHeaders; body: string }> {
+ return new Promise((resolve) => {
+ const chunks: Buffer[] = [];
+ let status = 200;
+ let headers: http.OutgoingHttpHeaders = {};
+
+ const res = {
+ headersSent: false,
+ writeHead(s: number, h: http.OutgoingHttpHeaders) {
+ status = s;
+ headers = h ?? {};
+ this.headersSent = true;
+ },
+ end(data?: Buffer | string) {
+ if (data) chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
+ resolve({ status, headers, body: Buffer.concat(chunks).toString("utf8") });
+ },
+ write(chunk: Buffer | string) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ },
+ destroy() {
+ resolve({ status, headers, body: Buffer.concat(chunks).toString("utf8") });
+ },
+ on() {
+ return this;
+ },
+ pipe(dest: NodeJS.WritableStream) {
+ dest.end();
+ resolve({ status, headers, body: "" });
+ },
+ } as unknown as http.ServerResponse;
+
+ handler(req, res).then(() => {
+ // resolve was already called via res.end
+ });
+ });
+}
+
+/** Build a Basic-Auth Authorization header value. */
+function basicAuth(user: string, pass: string): string {
+ return "Basic " + Buffer.from(`${user}:${pass}`).toString("base64");
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Setup
+// ─────────────────────────────────────────────────────────────────────────────
+
+const VAULT_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-vault-"));
+const ORIG_KEY = process.env.STORAGE_ENCRYPTION_KEY;
+
+test.after(() => {
+ fs.rmSync(VAULT_ROOT, { recursive: true, force: true });
+ if (ORIG_KEY === undefined) {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ } else {
+ process.env.STORAGE_ENCRYPTION_KEY = ORIG_KEY;
+ }
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 1. Path traversal guard (resolveVaultPath)
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("resolveVaultPath: simple path inside vault resolves correctly", async () => {
+ const { resolveVaultPath } = await importHandler();
+ const { absPath } = resolveVaultPath(VAULT_ROOT, "/api/v1/webdav/notes/file.md");
+ assert.equal(absPath, path.join(VAULT_ROOT, "notes", "file.md"));
+});
+
+test("resolveVaultPath: root path resolves to vaultRoot", async () => {
+ const { resolveVaultPath } = await importHandler();
+ const { absPath } = resolveVaultPath(VAULT_ROOT, "/api/v1/webdav/");
+ assert.equal(absPath, path.resolve(VAULT_ROOT));
+});
+
+test("resolveVaultPath: ../ traversal is rejected with 403", async () => {
+ const { resolveVaultPath } = await importHandler();
+ assert.throws(
+ () => resolveVaultPath(VAULT_ROOT, "/api/v1/webdav/../../../etc/passwd"),
+ (err: { status: number }) => err.status === 403
+ );
+});
+
+test("resolveVaultPath: encoded %2e%2e%2f traversal is rejected with 403", async () => {
+ const { resolveVaultPath } = await importHandler();
+ assert.throws(
+ () => resolveVaultPath(VAULT_ROOT, "/api/v1/webdav/%2e%2e%2fetc/passwd"),
+ (err: { status: number }) => err.status === 403
+ );
+});
+
+test("resolveVaultPath: encoded %2e%2e traversal variant is rejected", async () => {
+ const { resolveVaultPath } = await importHandler();
+ assert.throws(
+ () => resolveVaultPath(VAULT_ROOT, "/api/v1/webdav/%2e%2e/secret"),
+ (err: { status: number }) => err.status === 403
+ );
+});
+
+test("resolveVaultPath: absolute path injection outside vault is rejected", async () => {
+ const { resolveVaultPath } = await importHandler();
+ // The guard must catch paths that escape the vault root after resolution.
+ // We test by passing a request path whose decoded form resolves outside VAULT_ROOT.
+ // The URL segment /api/v1/webdav is stripped, then the remaining path is decoded
+ // and resolved relative to vaultRoot. A path like /../../../outside must be caught.
+
+ // Use an alternative vault root with a deeper subdir so we can craft an escape
+ const deepVault = path.join(VAULT_ROOT, "sub", "deep");
+ // /api/v1/webdav/../../secret: after prefix strip → /../../secret
+ // stripped of leading slashes → ../../secret
+ // path.resolve(deepVault, "../../secret") → VAULT_ROOT/secret which is OUTSIDE deepVault
+ assert.throws(
+ () => resolveVaultPath(deepVault, "/api/v1/webdav/../../secret"),
+ (err: { status: number }) => err.status === 403
+ );
+});
+
+test("resolveDestinationPath: raw path that escapes vault is rejected", async () => {
+ const { resolveDestinationPath } = await importHandler();
+ // Use a deep vault so we can craft an escape path.
+ // Pass a raw path (not a full URL) so the URL parser does not normalise away the ..
+ const deepVault = path.join(VAULT_ROOT, "sub", "deep");
+ // A raw Destination header path that resolves outside deepVault
+ assert.throws(
+ () => resolveDestinationPath(deepVault, "/api/v1/webdav/../../escape-target"),
+ (err: { status: number }) => err.status === 403
+ );
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 2. verifyBasicAuth
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("verifyBasicAuth: correct credentials return true", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth(basicAuth("alice", "s3cr3t"), "alice", "s3cr3t"), true);
+});
+
+test("verifyBasicAuth: wrong password returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth(basicAuth("alice", "wrong"), "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: wrong username returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth(basicAuth("bob", "s3cr3t"), "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: missing header returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth(undefined, "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: empty header returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth("", "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: non-Basic scheme returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(
+ verifyBasicAuth("Bearer some-token", "alice", "s3cr3t"),
+ false
+ );
+});
+
+test("verifyBasicAuth: malformed base64 returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ assert.equal(verifyBasicAuth("Basic !!!notbase64!!!", "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: base64 with no colon separator returns false", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ const noColon = "Basic " + Buffer.from("alices3cr3t").toString("base64");
+ assert.equal(verifyBasicAuth(noColon, "alice", "s3cr3t"), false);
+});
+
+test("verifyBasicAuth: constant-time path exercised (long password diff)", async () => {
+ const { verifyBasicAuth } = await importHandler();
+ const longPassword = "a".repeat(1000);
+ // Should return false without throwing on length mismatch
+ assert.equal(verifyBasicAuth(basicAuth("alice", longPassword), "alice", "short"), false);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 3. decryptStored (port of encryption.ts)
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("decryptStored: plaintext passthrough when no enc: prefix", async () => {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ const { decryptStored } = await importHandler();
+ assert.equal(decryptStored("plaintext-password"), "plaintext-password");
+});
+
+test("decryptStored: null input returns null", async () => {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ const { decryptStored } = await importHandler();
+ assert.equal(decryptStored(null), null);
+});
+
+test("decryptStored: value encrypted by TS encrypt() decrypts correctly", async () => {
+ const SECRET = "webdav-test-encryption-key-32chars-ok";
+ process.env.STORAGE_ENCRYPTION_KEY = SECRET;
+ const encrypted = encryptTs(SECRET, "my-vault-password");
+
+ const { decryptStored } = await importHandler();
+ const result = decryptStored(encrypted);
+ assert.equal(result, "my-vault-password");
+});
+
+test("decryptStored: encrypted value with no key configured returns null", async () => {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ // Even if a value has enc:v1: prefix, without the key we cannot decrypt
+ const { decryptStored } = await importHandler();
+ const fakeEncrypted = "enc:v1:aabbccdd:eeff0011:22334455";
+ assert.equal(decryptStored(fakeEncrypted), null);
+});
+
+test("decryptStored: malformed enc:v1: format returns null", async () => {
+ process.env.STORAGE_ENCRYPTION_KEY = "some-key-value-here";
+ const { decryptStored } = await importHandler();
+ assert.equal(decryptStored("enc:v1:onlytwoparts:missing"), null);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 4. buildPropfindXml
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("buildPropfindXml: produces valid XML with entries", async () => {
+ const { buildPropfindXml } = await importHandler();
+ const now = new Date("2026-01-01T00:00:00Z");
+ const xml = buildPropfindXml(
+ [
+ { name: "notes", href: "/api/v1/webdav/notes/", isDir: true, size: 0, mtime: now },
+ {
+ name: "file.md",
+ href: "/api/v1/webdav/notes/file.md",
+ isDir: false,
+ size: 1234,
+ mtime: now,
+ },
+ ],
+ "/api/v1/webdav/"
+ );
+
+ assert.match(xml, /<?xml version="1.0"/);
+ assert.match(xml, /D:multistatus/);
+ assert.match(xml, /D:response/);
+ assert.match(xml, /notes/);
+ assert.match(xml, /file\.md/);
+ assert.match(xml, /1234/); // content-length for file
+ assert.match(xml, /D:collection/); // dir has collection resourcetype
+});
+
+test("buildPropfindXml: escapes XML special chars in names", async () => {
+ const { buildPropfindXml } = await importHandler();
+ const xml = buildPropfindXml(
+ [
+ {
+ name: "a <b> & c 'quote' \"double\"",
+ href: "/api/v1/webdav/a",
+ isDir: false,
+ size: 10,
+ mtime: new Date(),
+ },
+ ],
+ "/api/v1/webdav/"
+ );
+
+ // Unescaped < > & ' " must not appear inside element content
+ assert.doesNotMatch(xml, /<D:displayname>[^<]*<[^/]/);
+ assert.match(xml, /&lt;/);
+ assert.match(xml, /&gt;/);
+ assert.match(xml, /&amp;/);
+});
+
+test("buildPropfindXml: file entry has no D:collection resourcetype", async () => {
+ const { buildPropfindXml } = await importHandler();
+ const xml = buildPropfindXml(
+ [{ name: "note.md", href: "/api/v1/webdav/note.md", isDir: false, size: 99, mtime: new Date() }],
+ "/api/v1/webdav/"
+ );
+ // File should have empty resourcetype, not a collection
+ assert.doesNotMatch(xml, /D:collection/);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 5. Integration: PUT/GET/DELETE/MKCOL/MOVE with real temp vault
+// Uses maybeHandleWebdav via a fake DB config injected via loadWebdavConfig mock.
+// We test the pure HTTP dispatch against the real filesystem here.
+// ─────────────────────────────────────────────────────────────────────────────
+
+/**
+ * Build a partial handler that bypasses DB (loadWebdavConfig) and uses a
+ * hard-coded config for integration tests. We do this by wrapping maybeHandleWebdav
+ * through a thin shim that patches the module's DB loader.
+ *
+ * Because ES module mocking is complex, we instead test the HTTP method handlers
+ * directly via the private functions. Since those are not exported, we use a
+ * small in-process test server that wires up the real maybeHandleWebdav with
+ * a SQLite DB pre-populated with our test config.
+ */
+
+// Create a minimal SQLite DB for integration tests
+async function createTestDb(
+ dataDir: string,
+ opts: { enabled: boolean; username: string; password: string; vaultPath: string }
+) {
+ const { createRequire } = await import("node:module");
+ const _require = createRequire(import.meta.url);
+ const Database = _require("better-sqlite3");
+ const dbPath = path.join(dataDir, "storage.sqlite");
+ const db = new Database(dbPath);
+
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS key_value (
+ namespace TEXT NOT NULL,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL,
+ PRIMARY KEY (namespace, key)
+ );
+ `);
+
+ const upsert = db.prepare(
+ "INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"
+ );
+
+ upsert.run("obsidian", "webdav_enabled", JSON.stringify(opts.enabled));
+ upsert.run("obsidian", "webdav_username", JSON.stringify(opts.username));
+ upsert.run("obsidian", "webdav_password", JSON.stringify(opts.password));
+ upsert.run("obsidian", "vault_path", JSON.stringify(opts.vaultPath));
+
+ db.close();
+ return dbPath;
+}
+
+/** Run a single WebDAV request through the real handler with a test DB. */
+async function webdavRequest(opts: {
+ method: string;
+ url: string;
+ headers?: Record<string, string>;
+ body?: Buffer;
+ dataDir: string;
+}): Promise<{ status: number; headers: http.OutgoingHttpHeaders; body: string }> {
+ const origDataDir = process.env.DATA_DIR;
+ process.env.DATA_DIR = opts.dataDir;
+
+ try {
+ const handler = await importHandler();
+ const req = fakeReq(opts.method, opts.url, opts.headers || {}, opts.body || null);
+ return captureRes(req, (r, s) => handler.maybeHandleWebdav(r, s));
+ } finally {
+ if (origDataDir === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = origDataDir;
+ }
+ }
+}
+
+const TEST_USER = "obsidian";
+const TEST_PASS = "test-password-123";
+const AUTH_HEADER = basicAuth(TEST_USER, TEST_PASS);
+
+// Create integration test environment
+const intDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-int-"));
+const intVaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-vault-int-"));
+
+test.before(async () => {
+ await createTestDb(intDataDir, {
+ enabled: true,
+ username: TEST_USER,
+ password: TEST_PASS, // plaintext (no enc: prefix — backward compat)
+ vaultPath: intVaultDir,
+ });
+});
+
+test.after(() => {
+ fs.rmSync(intDataDir, { recursive: true, force: true });
+ fs.rmSync(intVaultDir, { recursive: true, force: true });
+});
+
+test("PUT then GET round-trips a file correctly", async () => {
+ const content = Buffer.from("# Hello Obsidian\nThis is a test note.", "utf8");
+
+ const putRes = await webdavRequest({
+ method: "PUT",
+ url: "/api/v1/webdav/hello.md",
+ headers: { authorization: AUTH_HEADER, "content-length": String(content.length) },
+ body: content,
+ dataDir: intDataDir,
+ });
+ // 201 Created (new file)
+ assert.ok([201, 204].includes(putRes.status), `PUT expected 201/204, got ${putRes.status}`);
+
+ const getRes = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/hello.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: intDataDir,
+ });
+ assert.equal(getRes.status, 200);
+ assert.equal(getRes.body, content.toString("utf8"));
+});
+
+test("PUT (update) returns 204, GET reflects updated content", async () => {
+ // First create
+ await webdavRequest({
+ method: "PUT",
+ url: "/api/v1/webdav/update-me.md",
+ headers: { authorization: AUTH_HEADER },
+ body: Buffer.from("original", "utf8"),
+ dataDir: intDataDir,
+ });
+
+ // Then update
+ const updated = Buffer.from("updated content", "utf8");
+ const putRes2 = await webdavRequest({
+ method: "PUT",
+ url: "/api/v1/webdav/update-me.md",
+ headers: { authorization: AUTH_HEADER },
+ body: updated,
+ dataDir: intDataDir,
+ });
+ assert.equal(putRes2.status, 204);
+
+ const getRes = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/update-me.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: intDataDir,
+ });
+ assert.equal(getRes.body, "updated content");
+});
+
+test("DELETE removes a file, subsequent GET returns 404", async () => {
+ await webdavRequest({
+ method: "PUT",
+ url: "/api/v1/webdav/delete-me.md",
+ headers: { authorization: AUTH_HEADER },
+ body: Buffer.from("temp", "utf8"),
+ dataDir: intDataDir,
+ });
+
+ const delRes = await webdavRequest({
+ method: "DELETE",
+ url: "/api/v1/webdav/delete-me.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: intDataDir,
+ });
+ assert.equal(delRes.status, 204);
+
+ const getRes = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/delete-me.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: intDataDir,
+ });
+ assert.equal(getRes.status, 404);
+});
+
+test("MKCOL creates a directory", async () => {
+ const mkcolRes = await webdavRequest({
+ method: "MKCOL",
+ url: "/api/v1/webdav/newdir",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: intDataDir,
+ });
+ assert.equal(mkcolRes.status, 201);
+
+ const stat = fs.statSync(path.join(intVaultDir, "newdir"));
+ assert.ok(stat.isDirectory());
+});
+
+test("MOVE renames a file", async () => {
+ // Create source
+ await webdavRequest({
+ method: "PUT",
+ url: "/api/v1/webdav/move-src.md",
+ headers: { authorization: AUTH_HEADER },
+ body: Buffer.from("move me", "utf8"),
+ dataDir: intDataDir,
+ });
+
+ const moveRes = await webdavRequest({
+ method: "MOVE",
+ url: "/api/v1/webdav/move-src.md",
+ headers: {
+ authorization: AUTH_HEADER,
+ destination: "http://localhost/api/v1/webdav/move-dst.md",
+ },
+ dataDir: intDataDir,
+ });
+ assert.ok([201, 204].includes(moveRes.status), `MOVE expected 201/204, got ${moveRes.status}`);
+
+ assert.ok(!fs.existsSync(path.join(intVaultDir, "move-src.md")), "Source should not exist");
+ assert.ok(fs.existsSync(path.join(intVaultDir, "move-dst.md")), "Dest should exist");
+});
+
+test("PROPFIND on vault root returns 207 with entries", async () => {
+ // Ensure at least one file exists
+ fs.writeFileSync(path.join(intVaultDir, "propfind-test.md"), "content");
+
+ const propfindRes = await webdavRequest({
+ method: "PROPFIND",
+ url: "/api/v1/webdav/",
+ headers: { authorization: AUTH_HEADER, depth: "1" },
+ dataDir: intDataDir,
+ });
+ assert.equal(propfindRes.status, 207);
+ assert.match(propfindRes.body, /D:multistatus/);
+ assert.match(propfindRes.body, /propfind-test\.md/);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 6. Auth failure paths
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("GET without auth returns 401 with WWW-Authenticate", async () => {
+ const res = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/hello.md",
+ headers: {},
+ dataDir: intDataDir,
+ });
+ assert.equal(res.status, 401);
+ const wwwAuth = res.headers["WWW-Authenticate"] || res.headers["www-authenticate"];
+ assert.ok(typeof wwwAuth === "string" && wwwAuth.includes("Basic"), "WWW-Authenticate missing");
+});
+
+test("GET with wrong password returns 401", async () => {
+ const res = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/hello.md",
+ headers: { authorization: basicAuth(TEST_USER, "wrong-pass") },
+ dataDir: intDataDir,
+ });
+ assert.equal(res.status, 401);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 7. Disabled / no-creds → not served
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("disabled WebDAV returns 503", async () => {
+ const disabledDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-disabled-"));
+ const disabledVaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-disabled-vault-"));
+
+ try {
+ await createTestDb(disabledDataDir, {
+ enabled: false,
+ username: TEST_USER,
+ password: TEST_PASS,
+ vaultPath: disabledVaultDir,
+ });
+
+ const res = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/file.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: disabledDataDir,
+ });
+ assert.equal(res.status, 503);
+ } finally {
+ fs.rmSync(disabledDataDir, { recursive: true, force: true });
+ fs.rmSync(disabledVaultDir, { recursive: true, force: true });
+ }
+});
+
+test("no DB / missing config returns 503", async () => {
+ const emptyDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-empty-"));
+
+ try {
+ // No DB file at all
+ const res = await webdavRequest({
+ method: "GET",
+ url: "/api/v1/webdav/file.md",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: emptyDataDir,
+ });
+ assert.equal(res.status, 503);
+ } finally {
+ fs.rmSync(emptyDataDir, { recursive: true, force: true });
+ }
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 8. Non-WebDAV paths are not handled (returns false)
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("non-webdav path returns false (not handled)", async () => {
+ const origDataDir = process.env.DATA_DIR;
+ process.env.DATA_DIR = intDataDir;
+
+ try {
+ const handler = await importHandler();
+ const req = fakeReq("GET", "/api/v1/chat/completions", {});
+
+ let capturedResult: boolean | undefined;
+ const fakeRes = {
+ headersSent: false,
+ writeHead() {},
+ end() {},
+ write() {},
+ } as unknown as http.ServerResponse;
+
+ capturedResult = await handler.maybeHandleWebdav(req, fakeRes);
+ assert.equal(capturedResult, false);
+ } finally {
+ if (origDataDir === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = origDataDir;
+ }
+ }
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// 9. Encrypted password round-trip in integration
+// ─────────────────────────────────────────────────────────────────────────────
+
+test("encrypted password in DB is decrypted and auth works", async () => {
+ const encSecret = "integration-enc-key-value-32chars!";
+ process.env.STORAGE_ENCRYPTION_KEY = encSecret;
+
+ const encDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-enc-"));
+ const encVaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-webdav-enc-vault-"));
+
+ try {
+ const encryptedPass = encryptTs(encSecret, TEST_PASS);
+
+ await createTestDb(encDataDir, {
+ enabled: true,
+ username: TEST_USER,
+ password: encryptedPass,
+ vaultPath: encVaultDir,
+ });
+
+ const res = await webdavRequest({
+ method: "OPTIONS",
+ url: "/api/v1/webdav/",
+ headers: { authorization: AUTH_HEADER },
+ dataDir: encDataDir,
+ });
+ // OPTIONS with correct creds should succeed (200 or 207)
+ assert.ok(res.status < 400, `Expected success with encrypted password, got ${res.status}`);
+ } finally {
+ fs.rmSync(encDataDir, { recursive: true, force: true });
+ fs.rmSync(encVaultDir, { recursive: true, force: true });
+ // Restore encryption key state
+ if (ORIG_KEY === undefined) {
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ } else {
+ process.env.STORAGE_ENCRYPTION_KEY = ORIG_KEY;
+ }
+ }
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// DATA_DIR resolution parity: the .mjs handler MUST resolve the same SQLite file
+// the app does, or WebDAV silently reads the wrong DB and 503s. Pin parity against
+// the real resolveDataDir() in src/lib/dataPaths.ts across env combinations.
+// ─────────────────────────────────────────────────────────────────────────────
+test("resolveDataDir: parity with src/lib/dataPaths.ts across env combos", async () => {
+ const { resolveDataDir: mjsResolve } = await importHandler();
+ const { resolveDataDir: tsResolve } = await import("../../src/lib/dataPaths.ts");
+
+ const ORIG_DATA = process.env.DATA_DIR;
+ const ORIG_XDG = process.env.XDG_CONFIG_HOME;
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ddir-"));
+ try {
+ const combos: Array<Record<string, string | undefined>> = [
+ { DATA_DIR: tmp, XDG_CONFIG_HOME: undefined },
+ { DATA_DIR: ` ${tmp} `, XDG_CONFIG_HOME: undefined }, // trims + resolves
+ { DATA_DIR: undefined, XDG_CONFIG_HOME: path.join(tmp, "xdg") },
+ { DATA_DIR: undefined, XDG_CONFIG_HOME: undefined }, // bare default
+ ];
+ for (const combo of combos) {
+ if (combo.DATA_DIR === undefined) delete process.env.DATA_DIR;
+ else process.env.DATA_DIR = combo.DATA_DIR;
+ if (combo.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME;
+ else process.env.XDG_CONFIG_HOME = combo.XDG_CONFIG_HOME;
+
+ const fromMjs = mjsResolve();
+ const fromTs = tsResolve();
+ assert.equal(
+ fromMjs,
+ fromTs,
+ `DATA_DIR resolver diverged for ${JSON.stringify(combo)}: mjs=${fromMjs} ts=${fromTs}`
+ );
+ }
+ } finally {
+ if (ORIG_DATA === undefined) delete process.env.DATA_DIR;
+ else process.env.DATA_DIR = ORIG_DATA;
+ if (ORIG_XDG === undefined) delete process.env.XDG_CONFIG_HOME;
+ else process.env.XDG_CONFIG_HOME = ORIG_XDG;
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index db9541a360..d448bdeb6c 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -13,6 +13,7 @@ export default defineConfig({
include: [
"src/app/**/dashboard/cache/__tests__/**/*.test.tsx",
"src/app/**/dashboard/endpoint/__tests__/**/*.test.tsx",
+ "src/app/**/dashboard/providers/**/__tests__/**/*.test.tsx",
"src/app/**/dashboard/webhooks/__tests__/**/*.test.tsx",
"src/shared/hooks/__tests__/**/*.test.tsx",
"src/lib/memory/__tests__/**/*.test.ts",