From 2ca64fffdd1f09561aa1a11325b81aac953a110b Mon Sep 17 00:00:00 2001 From: Foshati Date: Fri, 30 Oct 2026 02:19:04 +0400 Subject: [PATCH] feat: add native Anthropic & OpenAI providers, launcher controls, and admin redesign (v1.3.0) - Add native Anthropic provider (anthropic_api/...) with Messages API forwarding, prompt caching, server tools, thinking signatures, and automatic error recovery. - Add OpenAI platform provider (openai_api/...) with Chat Completions, reasoning effort translation, non-chat model filtering, and unsupported parameter auto-drop. - Improve terminal launchers (codefa claude, codefa codex) with detached background server lifecycle, status tracking, and codefa status/codefa stop commands. - Redesign Admin UI dashboard with categorized provider groupings, search, status indicators, accessible modals, and improved log streaming. - Fix installer non-interactive detection in scripts/install.sh to prevent hanging on controlling TTY in headless environments. - Stabilize provider admission test timing under parallel multi-core execution. - Bump version to 1.3.0 in pyproject.toml and uv.lock. --- .env.example | 14 +- CHANGELOG.md | 6 + README.md | 13 + pyproject.toml | 2 +- scripts/install.sh | 3 + src/codefa/api/admin_static/admin.css | 2285 +++++++++++------ src/codefa/api/admin_static/admin.js | 1302 +++++++--- src/codefa/api/admin_static/index.html | 209 +- src/codefa/api/handlers/messages.py | 11 + src/codefa/api/routes.py | 12 + src/codefa/cli/background_server.py | 214 ++ src/codefa/cli/entrypoints.py | 94 +- src/codefa/config/admin/provider_manifest.py | 18 + src/codefa/config/paths.py | 14 + src/codefa/config/provider_catalog.py | 28 +- src/codefa/config/settings.py | 8 + src/codefa/core/anthropic/errors.py | 28 + src/codefa/providers/anthropic/__init__.py | 5 + src/codefa/providers/anthropic/client.py | 258 ++ src/codefa/providers/anthropic/errors.py | 120 + src/codefa/providers/anthropic/request.py | 327 +++ src/codefa/providers/anthropic/stream.py | 131 + .../providers/openai_platform/__init__.py | 5 + .../providers/openai_platform/client.py | 129 + .../providers/openai_platform/parameters.py | 115 + src/codefa/providers/runtime/factory.py | 22 + tests/api/test_anthropic_beta_header.py | 39 + tests/api/test_web_server_tools.py | 53 +- tests/cli/test_background_server.py | 191 ++ tests/contracts/test_feature_manifest.py | 4 + .../contracts/test_provider_catalog_order.py | 2 + tests/providers/test_anthropic.py | 644 +++++ tests/providers/test_openai_platform.py | 214 ++ tests/providers/test_provider_admission.py | 6 +- tests/providers/test_provider_runtime.py | 8 + uv.lock | 2 +- 36 files changed, 5186 insertions(+), 1350 deletions(-) mode change 100755 => 100644 src/codefa/api/admin_static/admin.js create mode 100644 src/codefa/cli/background_server.py create mode 100644 src/codefa/providers/anthropic/__init__.py create mode 100644 src/codefa/providers/anthropic/client.py create mode 100644 src/codefa/providers/anthropic/errors.py create mode 100644 src/codefa/providers/anthropic/request.py create mode 100644 src/codefa/providers/anthropic/stream.py create mode 100644 src/codefa/providers/openai_platform/__init__.py create mode 100644 src/codefa/providers/openai_platform/client.py create mode 100644 src/codefa/providers/openai_platform/parameters.py create mode 100644 tests/api/test_anthropic_beta_header.py create mode 100644 tests/cli/test_background_server.py create mode 100644 tests/providers/test_anthropic.py create mode 100644 tests/providers/test_openai_platform.py diff --git a/.env.example b/.env.example index 8585f3e..36e3a24 100755 --- a/.env.example +++ b/.env.example @@ -2,6 +2,14 @@ NVIDIA_NIM_API_KEY="" +# Anthropic Config (native Claude Messages API at api.anthropic.com; no protocol conversion) +ANTHROPIC_API_KEY="" + + +# OpenAI Config (GPT models over Chat Completions at api.openai.com/v1) +OPENAI_API_KEY="" + + # OpenRouter Config OPENROUTER_API_KEY="" @@ -116,7 +124,7 @@ OLLAMA_BASE_URL="http://localhost:11434" # All Claude model requests are mapped to these models, plain model is fallback # Format: provider_type/model/name -# Valid providers: "nvidia_nim" | "open_router" | "gemini" | "vertex" | "deepseek" | "mistral" | "mistral_codestral" | "opencode" | "opencode_go" | "vercel" | "bedrock" | "huggingface" | "cohere" | "github_models" | "wafer" | "kimi" | "kimi_code" | "minimax" | "cerebras" | "groq" | "sambanova" | "fireworks" | "cloudflare" | "zai" | "ollama_cloud" | "tokenrouter" | "lmstudio" | "llamacpp" | "ollama" +# Valid providers: "nvidia_nim" | "anthropic_api" | "openai_api" | "open_router" | "gemini" | "vertex" | "deepseek" | "mistral" | "mistral_codestral" | "opencode" | "opencode_go" | "vercel" | "bedrock" | "huggingface" | "cohere" | "github_models" | "wafer" | "kimi" | "kimi_code" | "minimax" | "cerebras" | "groq" | "sambanova" | "fireworks" | "cloudflare" | "zai" | "ollama_cloud" | "tokenrouter" | "lmstudio" | "llamacpp" | "ollama" MODEL_FABLE= MODEL_OPUS= MODEL_SONNET= @@ -127,6 +135,8 @@ MODEL="nvidia_nim/nvidia/nemotron-3-super-120b-a12b" # Optional live smoke model overrides. Provider smoke runs once per configured # provider even when MODEL/MODEL_* route to a different provider. CODEFA_SMOKE_MODEL_NVIDIA_NIM= +CODEFA_SMOKE_MODEL_ANTHROPIC_API= +CODEFA_SMOKE_MODEL_OPENAI_API= CODEFA_SMOKE_MODEL_OPEN_ROUTER= CODEFA_SMOKE_MODEL_MISTRAL= CODEFA_SMOKE_MODEL_MISTRAL_REASONING= @@ -176,6 +186,8 @@ REASONING_HAIKU=inherit # Provider config # Per-provider proxy support: http and socks5, example: "http://username:password@host:port" NVIDIA_NIM_PROXY="" +ANTHROPIC_PROXY="" +OPENAI_PROXY="" OPENROUTER_PROXY="" MISTRAL_PROXY="" CODESTRAL_PROXY="" diff --git a/CHANGELOG.md b/CHANGELOG.md index cda6b74..15f91c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [v1.3.0] - 2026-10-29 +- **Native Anthropic provider (`anthropic_api/...`)**: Uses `ANTHROPIC_API_KEY` and sends requests straight to the Claude Messages API with no conversion, so thinking signatures, prompt caching, server tools (web search/fetch), `anthropic-beta` flags, and exact usage all work. Before any output reaches the client it retries on overload, and it automatically corrects requests the API rejects (beta flags, thinking type, effort, invalid thinking signatures). +- **OpenAI provider (`openai_api/...`)**: Uses `OPENAI_API_KEY` for GPT models over Chat Completions. It sends `max_completion_tokens`, maps reasoning effort to OpenAI's levels, and learns which parameters each model rejects (`reasoning_effort`, `temperature`, token fields) and drops them. The model list hides non-chat models, and quota exhaustion is reported instead of retried. +- **Terminal launcher fixes**: `codefa claude` / `codefa codex` start one shared server detached from the terminal (no browser pop-up, no longer killed when another session exits, 45s startup window). Server output is saved to `~/.codefa/logs/server-console.log`, and the actual startup error is shown if the server fails. New `codefa status` and `codefa stop` commands. +- **Admin dashboard redesign**: Providers are grouped into cloud and local with search, a configured-only filter, and status badges. The provider dialog is accessible, the log viewer is improved, and narrow windows are supported. Fixes several XSS-prone `innerHTML` uses and log-polling bugs. + ## [v1.2.50] - 2026-07-30 - **Automated GitHub Releases**: Integrated GitHub Actions release workflow and full `CHANGELOG.md` documentation. - **Vibrant Gradient Logo**: Updated `assets/codefa.svg` with modern electric blue (`#2563eb` -> `#38bdf8`) gradient. diff --git a/README.md b/README.md index df5f733..b3def00 100755 --- a/README.md +++ b/README.md @@ -82,9 +82,13 @@ You can also bypass the menu and launch directly: codefa claude # Direct launcher for Claude Code codefa codex # Direct launcher for Codex CLI codefa server # Start server & open Admin UI +codefa status # Show whether the background server is running +codefa stop # Stop the auto-started background server codefa-init # Initialize ~/.codefa/.env config ``` +`codefa claude` / `codefa codex` start one shared server in the background, detached from the terminal, if none is running. It keeps running when the client exits, so several terminals can use it at once; stop it with `codefa stop`. If startup fails, the real error is printed, and the full output is kept in `~/.codefa/logs/server-console.log`. + --- ## ## Choose A Provider @@ -92,6 +96,8 @@ codefa-init # Initialize ~/.codefa/.env config | Provider | Description | Example Model | | --- | --- | --- | | [NVIDIA NIM](https://build.nvidia.com) | Accelerated NIM microservices | `nvidia_nim/meta/llama-3.3-70b-instruct` | +| [Anthropic](https://console.anthropic.com) | Native Claude Messages API (no conversion: thinking, caching, server tools) | `anthropic_api/claude-sonnet-4-5` | +| [OpenAI](https://platform.openai.com) | OpenAI GPT models (Chat Completions) | `openai_api/gpt-5` | | [OpenRouter](https://openrouter.ai) | Unified multi-provider gateway | `open_router/auto` | | [Gemini](https://ai.google.dev) | Google Gemini API | `gemini/gemini-2.5-flash` | | [Vertex AI](https://cloud.google.com/vertex-ai) | Google Cloud Vertex AI | `vertex/gemini-2.5-flash` | @@ -121,6 +127,13 @@ codefa-init # Initialize ~/.codefa/.env config | [llama.cpp](https://github.com/ggerganov/llama.cpp) | Local llama.cpp server | `llamacpp/local-model` | | [Ollama](https://ollama.com) | Local Ollama instance | `ollama/llama3.3:latest` | +### First-party Claude and GPT + +- **Anthropic** (`anthropic_api/...`, key `ANTHROPIC_API_KEY`): requests are forwarded natively to the Claude Messages API, with no conversion. Thinking signatures, prompt caching, `anthropic-beta` features, exact token usage, and Anthropic's own `web_search`/`web_fetch` server tools work just as they do when calling Anthropic directly. Requests the API rejects (thinking type, effort, beta flags) are corrected and retried automatically. +- **OpenAI** (`openai_api/...`, key `OPENAI_API_KEY`): GPT models over Chat Completions with named reasoning effort. Parameters a specific model rejects (for example `reasoning_effort` or `temperature`) are detected from the API error and dropped automatically, and non-chat models are hidden from model pickers. + +Both support a per-provider HTTP proxy (`ANTHROPIC_PROXY`, `OPENAI_PROXY`) for regions where the APIs are not directly reachable. + --- ## 🎨 Admin UI & Control Center diff --git a/pyproject.toml b/pyproject.toml index 3b999b2..700314e 100755 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "codefa" -version = "1.2.52" +version = "1.3.0" description = "Local proxy connecting coding agents to OpenAI-compatible AI providers" readme = "README.md" requires-python = ">=3.14.0" diff --git a/scripts/install.sh b/scripts/install.sh index f49669d..bf89237 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -67,6 +67,9 @@ prompt_confirm() { if [ "$auto_yes" -eq 1 ]; then return 0 fi + if [ ! -t 1 ]; then + return 0 + fi tty_path="" if [ -c /dev/tty ]; then tty_path="/dev/tty" diff --git a/src/codefa/api/admin_static/admin.css b/src/codefa/api/admin_static/admin.css index 9608809..3f9ef3b 100755 --- a/src/codefa/api/admin_static/admin.css +++ b/src/codefa/api/admin_static/admin.css @@ -1,126 +1,229 @@ +/* ========================================================================== + Design tokens + ========================================================================== */ + :root { color-scheme: dark; - - /* Color Palette */ - --bg: #090a0f; - --panel: #11131c; - --panel-strong: #171b26; - --card: #151822; - --card-hover: #1e2230; - --input: #0a0b10; - --input-focus: #0f1118; - --text: #f3f4f6; - --text-strong: #ffffff; - --muted: #9ca3af; - --line: rgba(255, 255, 255, 0.06); - --line-strong: rgba(255, 255, 255, 0.12); - - /* Brand and Accent Colors */ - --accent: #2563eb; - --accent-dark: #1d4ed8; - --accent-muted: rgba(37, 99, 235, 0.08); - --accent-border: rgba(37, 99, 235, 0.3); - - /* Status Colors */ - --ok: #2563eb; - --ok-bg: rgba(37, 99, 235, 0.08); - --ok-border: rgba(37, 99, 235, 0.25); - - --warn: #f59e0b; - --warn-bg: rgba(245, 158, 11, 0.08); - --warn-border: rgba(245, 158, 11, 0.25); - - --error: #ef4444; - --error-bg: rgba(239, 68, 68, 0.08); - --error-border: rgba(239, 68, 68, 0.25); - - --neutral: #6b7280; - --neutral-bg: rgba(107, 114, 128, 0.08); - --neutral-border: rgba(107, 114, 128, 0.25); - - --info: #3b82f6; - - /* Box Shadow & Glows */ - --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.2); - --shadow: 0 12px 34px rgba(0, 0, 0, 0.5); - --glow-accent: 0 0 12px rgba(37, 99, 235, 0.15); - - /* Borders and Radius */ - --radius-sm: 6px; - --radius-md: 10px; - --radius-lg: 14px; - --radius-full: 9999px; - --dropdown-chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%239ca3af' stroke-width='2.5'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5'/%3E%3C/svg%3E"); - + + /* Spacing scale */ + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --space-8: 32px; + --space-10: 40px; + /* Typography */ --font-sans: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; - - /* Transitions */ - --transition-fast: 0.15s ease; - --transition-normal: 0.22s cubic-bezier(0.4, 0, 0.2, 1); + --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; + --text-xs: 11px; + --text-sm: 12px; + --text-base: 13px; + --text-md: 14px; + --text-lg: 16px; + --text-xl: 20px; + --text-2xl: 26px; + --leading-tight: 1.25; + --leading-normal: 1.5; + --weight-medium: 500; + --weight-semibold: 600; + --weight-bold: 700; + + /* Shape */ + --radius-sm: 6px; + --radius-md: 8px; + --radius-lg: 12px; + --radius-full: 9999px; + + /* Layout */ + --sidebar-width: 244px; + --action-bar-height: 72px; + --content-max: 1240px; + --control-height: 38px; + --control-height-sm: 32px; + + /* Motion */ + --transition-fast: 120ms ease; + --transition-normal: 200ms cubic-bezier(0.4, 0, 0.2, 1); + + /* Surfaces */ + --bg: #0b0d12; + --panel: #12151c; + --panel-strong: #191d26; + --card: #151922; + --card-hover: #1a1f2a; + --input: #0d1016; + --input-focus: #0f131a; + + /* Text */ + --text: #d5dae3; + --text-strong: #f5f7fa; + --muted: #8b93a3; + --subtle: #5f6878; + + /* Lines */ + --line: rgba(255, 255, 255, 0.07); + --line-strong: rgba(255, 255, 255, 0.13); + + /* Accent */ + --accent: #6d9bff; + --accent-solid: #2563eb; + --accent-solid-hover: #1d55d6; + --accent-contrast: #ffffff; + --accent-muted: rgba(91, 140, 255, 0.12); + --accent-border: rgba(91, 140, 255, 0.4); + --focus-ring: #7aa2ff; + + /* Status */ + --ok: #34d399; + --ok-bg: rgba(52, 211, 153, 0.1); + --ok-border: rgba(52, 211, 153, 0.3); + --warn: #fbbf24; + --warn-bg: rgba(251, 191, 36, 0.1); + --warn-border: rgba(251, 191, 36, 0.3); + --error: #f87171; + --error-bg: rgba(248, 113, 113, 0.1); + --error-border: rgba(248, 113, 113, 0.3); + --neutral: #9aa3b2; + --neutral-bg: rgba(154, 163, 178, 0.1); + --neutral-border: rgba(154, 163, 178, 0.25); + --info: #60a5fa; + + /* Monochrome brand marks (e.g. white logos) */ + --mono-brand: #f5f7fa; + --mono-brand-bg: rgba(255, 255, 255, 0.09); + + /* Elevation */ + --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.35); + --shadow-md: 0 6px 20px rgba(0, 0, 0, 0.35); + --shadow-lg: 0 28px 70px rgba(0, 0, 0, 0.6); + --backdrop: rgba(4, 6, 10, 0.68); + --action-bar-bg: rgba(18, 21, 28, 0.88); + + --dropdown-chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%238b93a3' stroke-width='2.5'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5'/%3E%3C/svg%3E"); } html[data-theme="light"] { color-scheme: light; - - --bg: #f8fafc; + + --bg: #f5f6f8; --panel: #ffffff; - --panel-strong: #f1f5f9; + --panel-strong: #f1f3f6; --card: #ffffff; - --card-hover: #f1f5f9; + --card-hover: #f8fafc; --input: #ffffff; --input-focus: #ffffff; + --text: #334155; --text-strong: #0f172a; --muted: #64748b; - --line: rgba(0, 0, 0, 0.08); - --line-strong: rgba(0, 0, 0, 0.16); - + --subtle: #94a3b8; + + --line: rgba(15, 23, 42, 0.08); + --line-strong: rgba(15, 23, 42, 0.15); + --accent: #2563eb; - --accent-dark: #1d4ed8; + --accent-solid: #2563eb; + --accent-solid-hover: #1d4ed8; --accent-muted: rgba(37, 99, 235, 0.08); - --accent-border: rgba(37, 99, 235, 0.3); - - --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.05); - --shadow: 0 12px 34px rgba(0, 0, 0, 0.08); - --glow-accent: 0 0 12px rgba(37, 99, 235, 0.15); - + --accent-border: rgba(37, 99, 235, 0.35); + --focus-ring: #2563eb; + + --ok: #047857; + --ok-bg: rgba(16, 185, 129, 0.1); + --ok-border: rgba(4, 120, 87, 0.25); + --warn: #b45309; + --warn-bg: rgba(245, 158, 11, 0.12); + --warn-border: rgba(180, 83, 9, 0.25); + --error: #dc2626; + --error-bg: rgba(239, 68, 68, 0.08); + --error-border: rgba(220, 38, 38, 0.25); + --neutral: #64748b; + --neutral-bg: rgba(100, 116, 139, 0.08); + --neutral-border: rgba(100, 116, 139, 0.22); + --info: #2563eb; + + --mono-brand: #0f172a; + --mono-brand-bg: rgba(15, 23, 42, 0.06); + + --shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.06); + --shadow-md: 0 6px 20px rgba(15, 23, 42, 0.07); + --shadow-lg: 0 28px 70px rgba(15, 23, 42, 0.18); + --backdrop: rgba(15, 23, 42, 0.4); + --action-bar-bg: rgba(255, 255, 255, 0.9); + --dropdown-chevron: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2364748b' stroke-width='2.5'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5'/%3E%3C/svg%3E"); } -body, .sidebar, .topbar, .section-card, .provider-card, .app-shell, .admin-view, .action-bar, input, select, textarea, .logs-container, .modal-container, .modal-backdrop { - transition: background-color 0.25s ease, color 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease; -} +/* ========================================================================== + Base + ========================================================================== */ -* { +*, +*::before, +*::after { box-sizing: border-box; } +html { + -webkit-text-size-adjust: 100%; +} + body { margin: 0; min-width: 320px; background: var(--bg); color: var(--text); font-family: var(--font-sans); - letter-spacing: -0.01em; + font-size: var(--text-md); + line-height: var(--leading-normal); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; + transition: background-color var(--transition-normal), color var(--transition-normal); } -/* Custom Scrollbars */ -::-webkit-scrollbar { - width: 8px; - height: 8px; +body.modal-open { + overflow: hidden; } -::-webkit-scrollbar-track { - background: var(--bg); + +h1, +h2, +h3, +h4, +p { + margin: 0; } -::-webkit-scrollbar-thumb { + +a { + color: var(--accent); + text-underline-offset: 2px; +} + +a:hover { + text-decoration-thickness: 2px; +} + +code { + font-family: var(--font-mono); + font-size: 0.92em; background: var(--panel-strong); - border-radius: var(--radius-full); + border: 1px solid var(--line); + border-radius: 4px; + padding: 0 4px; } -::-webkit-scrollbar-thumb:hover { - background: var(--muted); + +kbd { + font-family: var(--font-mono); + font-size: var(--text-xs); + color: var(--muted); + background: var(--panel-strong); + border: 1px solid var(--line-strong); + border-bottom-width: 2px; + border-radius: 4px; + padding: 0 5px; + line-height: 1.5; } button, @@ -131,107 +234,170 @@ textarea { color: inherit; } -/* App Shell Layout */ +[hidden] { + display: none !important; +} + +::selection { + background: var(--accent-muted); +} + +::-webkit-scrollbar { + width: 10px; + height: 10px; +} + +::-webkit-scrollbar-track { + background: transparent; +} + +::-webkit-scrollbar-thumb { + background: var(--line-strong); + border: 2px solid transparent; + border-radius: var(--radius-full); + background-clip: padding-box; +} + +::-webkit-scrollbar-thumb:hover { + background-color: var(--muted); +} + +/* Accessible focus rings */ +:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: 2px; +} + +:focus:not(:focus-visible) { + outline: none; +} + +.visually-hidden { + position: absolute !important; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.skip-link { + position: fixed; + top: var(--space-3); + left: var(--space-3); + z-index: 2000; + padding: var(--space-2) var(--space-4); + border-radius: var(--radius-md); + background: var(--accent-solid); + color: var(--accent-contrast); + font-weight: var(--weight-semibold); + text-decoration: none; + transform: translateY(-200%); + transition: transform var(--transition-fast); +} + +.skip-link:focus { + transform: translateY(0); +} + +/* ========================================================================== + App shell & sidebar + ========================================================================== */ + .app-shell { display: grid; - grid-template-columns: 260px minmax(0, 1fr); + grid-template-columns: var(--sidebar-width) minmax(0, 1fr); min-height: 100vh; - padding-bottom: 96px; /* Space for action bar */ + padding-bottom: calc(var(--action-bar-height) + var(--space-4)); } -/* Sidebar Navigation */ .sidebar { position: sticky; top: 0; - height: 100vh; - border-right: 1px solid var(--line); - background: var(--bg); - padding: 24px 20px; display: flex; flex-direction: column; - gap: 32px; + gap: var(--space-6); + height: 100vh; + padding: var(--space-6) var(--space-4); + border-right: 1px solid var(--line); + background: var(--panel); } .brand { display: flex; align-items: center; - gap: 12px; - padding: 2px 0; + gap: var(--space-3); + padding: 0 var(--space-2); + min-width: 0; } .brand-mark { display: flex; + flex-shrink: 0; align-items: center; justify-content: center; - width: 40px; - height: 40px; - border-radius: 50%; - background: transparent; - border: none; - box-shadow: none; - padding: 0; - flex-shrink: 0; + width: 36px; + height: 36px; overflow: hidden; - transition: transform var(--transition-fast); -} - -.brand:hover .brand-mark { - transform: scale(1.05); + border-radius: 50%; } .brand-logo-img { + display: block; width: 100%; height: 100%; object-fit: cover; - border-radius: 50%; - display: block; +} + +.brand-text { + display: flex; + flex-direction: column; + min-width: 0; } .brand-title { - font-size: 22px; - font-weight: 800; - line-height: 1.1; - letter-spacing: -0.03em; color: var(--text-strong); - margin: 0; + font-size: var(--text-lg); + font-weight: var(--weight-bold); + letter-spacing: -0.02em; + line-height: var(--leading-tight); +} + +.brand-subtitle { + color: var(--muted); + font-size: var(--text-sm); } .section-nav { display: grid; - gap: 6px; + gap: 2px; } .nav-link { display: flex; align-items: center; - gap: 10px; + gap: var(--space-3); width: 100%; - min-height: 40px; + min-height: 36px; + padding: var(--space-2) var(--space-3); border: 1px solid transparent; border-radius: var(--radius-md); background: transparent; color: var(--muted); - padding: 10px 14px; + font-size: var(--text-md); + font-weight: var(--weight-medium); text-align: left; cursor: pointer; - font-weight: 600; - font-size: 14px; - transition: all var(--transition-fast); + transition: background-color var(--transition-fast), color var(--transition-fast), border-color var(--transition-fast); } .nav-link svg { + flex-shrink: 0; width: 18px; height: 18px; - flex-shrink: 0; - stroke: currentColor; - opacity: 0.85; - transition: transform var(--transition-fast), opacity var(--transition-fast); -} - -.nav-link:hover svg, -.nav-link.active svg { - opacity: 1; - transform: translateX(2px); } .nav-link:hover { @@ -243,336 +409,655 @@ textarea { background: var(--accent-muted); border-color: var(--accent-border); color: var(--accent); - box-shadow: var(--shadow-sm); } -/* Accessible focus outlines */ -button:focus-visible, -input:focus-visible, -select:focus-visible, -textarea:focus-visible, -.nav-link:focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; -} +/* ========================================================================== + Main content + ========================================================================== */ -/* Main Content Area */ .main { min-width: 0; - padding: 40px 48px; + width: 100%; + max-width: calc(var(--content-max) + 2 * var(--space-10)); + padding: var(--space-8) var(--space-10); +} + +.main:focus { + outline: none; } .topbar { - margin-bottom: 32px; + margin-bottom: var(--space-6); } .topbar h2 { - font-size: 30px; - font-weight: 800; - letter-spacing: -0.02em; color: var(--text-strong); - margin: 0; + font-size: var(--text-2xl); + font-weight: var(--weight-bold); + letter-spacing: -0.02em; + line-height: var(--leading-tight); +} + +.page-subtitle { + margin-top: var(--space-1); + color: var(--muted); + font-size: var(--text-md); +} + +.form-sections { + display: flex; + flex-direction: column; + gap: var(--space-6); } -/* Provider Strip & Panels */ +#view-providers.active { + display: flex; + flex-direction: column; + gap: var(--space-6); +} + +/* ========================================================================== + Panels + ========================================================================== */ + +.panel, .provider-strip, .settings-section { border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); - box-shadow: var(--shadow); - margin-bottom: 24px; - transition: border-color var(--transition-normal); -} - -.provider-strip { - padding: 24px; + box-shadow: var(--shadow-sm); + padding: var(--space-6); } +.panel-header, .strip-header, .section-heading { display: flex; + flex-wrap: wrap; align-items: flex-start; justify-content: space-between; - gap: 16px; - margin-bottom: 20px; + gap: var(--space-4); + margin-bottom: var(--space-5); } +.panel-header h3, .strip-header h3, .section-heading h3 { - font-size: 18px; - font-weight: 700; color: var(--text-strong); - margin: 0; + font-size: var(--text-lg); + font-weight: var(--weight-semibold); + letter-spacing: -0.01em; + line-height: var(--leading-tight); } +.panel-subtitle, .section-heading p { + margin-top: var(--space-1); color: var(--muted); - font-size: 13px; - line-height: 1.4; - margin: 4px 0 0 0; + font-size: var(--text-base); } -/* Provider Status Cards */ -.provider-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); - gap: 16px; -} +/* ========================================================================== + Buttons + ========================================================================== */ -.provider-card { - display: flex; - flex-direction: row; +.primary-button, +.secondary-button, +.ghost-button { + display: inline-flex; align-items: center; - gap: 14px; - border: 1px solid var(--line); + justify-content: center; + gap: var(--space-2); + min-height: var(--control-height); + padding: 0 var(--space-4); + border: 1px solid transparent; border-radius: var(--radius-md); - padding: 14px 18px; - background: var(--card); - transition: all var(--transition-normal); - position: relative; - overflow: hidden; -} - -.provider-card:hover { - border-color: var(--accent); - transform: translateY(-2px); - box-shadow: var(--shadow-sm), 0 4px 20px rgba(37, 99, 235, 0.08); - background: var(--card-hover); -} - -.provider-edit-btn { - background: none; - border: none; - color: var(--muted); + font-size: var(--text-base); + font-weight: var(--weight-semibold); + white-space: nowrap; cursor: pointer; - padding: 6px; - border-radius: var(--radius-sm); - display: flex; - align-items: center; - justify-content: center; - transition: all var(--transition-fast); - margin-left: auto; + transition: background-color var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast), box-shadow var(--transition-fast); } -.provider-edit-btn:hover { - color: var(--accent); - background: var(--accent-muted); +.primary-button { + background: var(--accent-solid); + color: var(--accent-contrast); + box-shadow: var(--shadow-sm); } -.provider-title { - display: flex; - align-items: center; - gap: 8px; +.primary-button:hover:not(:disabled) { + background: var(--accent-solid-hover); } -.provider-title strong { - font-size: 14px; - font-weight: 700; +.secondary-button { + background: var(--panel-strong); + border-color: var(--line-strong); color: var(--text-strong); } -/* Modern status pills with color indicators */ -.status-pill { - display: inline-flex; - align-items: center; - min-height: 22px; - border: 1px solid var(--neutral-border); - border-radius: var(--radius-full); - padding: 2px 10px; - background: var(--neutral-bg); +.secondary-button:hover:not(:disabled) { + background: var(--card-hover); + border-color: var(--muted); +} + +.ghost-button { + background: transparent; color: var(--muted); - font-size: 11px; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.05em; - white-space: nowrap; } -.status-pill.ok { - color: var(--ok); - background: var(--ok-bg); - border-color: var(--ok-border); +.ghost-button:hover:not(:disabled) { + background: var(--panel-strong); + color: var(--text-strong); } -.status-pill.warn { - color: var(--warn); - background: var(--warn-bg); - border-color: var(--warn-border); +.primary-button:disabled, +.secondary-button:disabled, +.ghost-button:disabled { + opacity: 0.5; + cursor: not-allowed; + box-shadow: none; } -.status-pill.error { - color: var(--error); - background: var(--error-bg); - border-color: var(--error-border); +.button-sm { + min-height: var(--control-height-sm); + padding: 0 var(--space-3); + font-size: var(--text-sm); } -.provider-meta { - color: var(--muted); - font-size: 12px; - line-height: 1.4; - word-break: break-all; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; +[aria-busy="true"] { + cursor: progress; } -/* Button & Form Controls styling */ -.test-button, -.ghost-button, -.secondary-button, -.primary-button { - display: inline-flex; - align-items: center; - justify-content: center; - min-height: 36px; - border-radius: var(--radius-md); +/* ========================================================================== + Toggle switches (checkbox inputs) + ========================================================================== */ + +.toggle, +.field input[type="checkbox"] { + appearance: none; + -webkit-appearance: none; + position: relative; + flex-shrink: 0; + align-self: flex-start; + width: 34px; + height: 20px; + margin: 0; border: 1px solid var(--line-strong); - padding: 6px 14px; - font-weight: 600; - font-size: 13px; + border-radius: var(--radius-full); + /* The knob is a gradient (pseudo-elements on are not portable). */ + background-color: var(--panel-strong); + background-image: radial-gradient(circle, var(--muted) 0 6px, transparent 7px); + background-position: 0 50%; + background-repeat: no-repeat; + background-size: 18px 18px; cursor: pointer; - transition: all var(--transition-fast); - text-decoration: none; + transition: background-color var(--transition-fast), background-position var(--transition-fast), border-color var(--transition-fast); } -.test-button { - background: var(--panel-strong); - color: var(--text); - border-color: var(--line); - margin-top: auto; - align-self: flex-start; +.toggle:checked, +.field input[type="checkbox"]:checked { + background-color: var(--accent-solid); + background-image: radial-gradient(circle, #ffffff 0 6px, transparent 7px); + background-position: 100% 50%; + border-color: var(--accent-solid); } -.test-button:hover:not(:disabled) { - background: var(--card-hover); - border-color: var(--accent); - color: var(--accent); +.toggle:disabled, +.field input[type="checkbox"]:disabled { + opacity: 0.5; + cursor: not-allowed; } -.test-button:disabled { - opacity: 0.6; - cursor: not-allowed; +.toggle-label .toggle { + align-self: center; } -.secondary-button { - background: transparent; +.toggle-label { + display: inline-flex; + align-items: center; + gap: var(--space-2); color: var(--text); - border-color: var(--line-strong); + font-size: var(--text-base); + font-weight: var(--weight-medium); + white-space: nowrap; + cursor: pointer; + user-select: none; } -.secondary-button:hover:not(:disabled) { - background: var(--panel-strong); - border-color: var(--text); +/* ========================================================================== + Search fields + ========================================================================== */ + +.search-field { + position: relative; + display: flex; + flex: 1 1 220px; + align-items: center; + min-width: 0; } -.primary-button { +.search-field > svg { + position: absolute; + left: 11px; + width: 15px; + height: 15px; + color: var(--muted); + pointer-events: none; +} + +.search-field input { + width: 100%; + height: var(--control-height-sm); + padding: 0 36px 0 33px; + border: 1px solid var(--line-strong); + border-radius: var(--radius-md); + background: var(--input); + color: var(--text-strong); + font-size: var(--text-base); + transition: border-color var(--transition-fast), box-shadow var(--transition-fast); +} + +.search-field input::placeholder { + color: var(--subtle); +} + +.search-field input:focus { border-color: var(--accent); - background: var(--accent); - color: #06100b; + box-shadow: 0 0 0 3px var(--accent-muted); + outline: none; } -.primary-button:hover:not(:disabled) { - background: var(--accent-dark); +.search-field kbd { + position: absolute; + right: 9px; + pointer-events: none; } -.primary-button:disabled { - cursor: not-allowed; - border-color: var(--line); - background: var(--panel-strong); +.search-field input:focus ~ kbd, +.search-field input:not(:placeholder-shown) ~ kbd { + display: none; +} + +/* ========================================================================== + Providers + ========================================================================== */ + +.provider-toolbar { + display: flex; + flex: 1 1 360px; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: var(--space-3) var(--space-4); + max-width: 520px; +} + +.provider-groups { + display: flex; + flex-direction: column; + gap: var(--space-6); +} + +.provider-group-header { + display: flex; + align-items: baseline; + gap: var(--space-2); + margin-bottom: var(--space-3); +} + +.provider-group-header h4 { color: var(--muted); + font-size: var(--text-sm); + font-weight: var(--weight-semibold); + letter-spacing: 0.06em; + text-transform: uppercase; } -.ghost-button { +.provider-group-count { + color: var(--subtle); + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; +} + +.provider-group-description { + margin-left: auto; + color: var(--subtle); + font-size: var(--text-sm); +} + +.provider-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(270px, 1fr)); + gap: var(--space-3); +} + +.provider-card { + position: relative; + display: flex; + align-items: flex-start; + gap: var(--space-3); + min-width: 0; + padding: var(--space-4); + border: 1px solid var(--line); + border-radius: var(--radius-lg); + background: var(--card); + cursor: pointer; + transition: border-color var(--transition-fast), background-color var(--transition-fast), box-shadow var(--transition-fast), transform var(--transition-fast); +} + +.provider-card:hover { + border-color: var(--line-strong); + background: var(--card-hover); + box-shadow: var(--shadow-md); + transform: translateY(-1px); +} + +.provider-card:focus-within { + border-color: var(--accent-border); +} + +.provider-card[data-tone="ok"] { + border-color: var(--ok-border); +} + +.provider-card-body { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--space-1); + min-width: 0; +} + +.provider-title { + display: flex; + align-items: center; + gap: var(--space-2); + min-width: 0; +} + +.provider-title strong { + overflow: hidden; + color: var(--text-strong); + font-size: var(--text-md); + font-weight: var(--weight-semibold); + text-overflow: ellipsis; + white-space: nowrap; +} + +.provider-meta { + overflow: hidden; + color: var(--muted); + font-family: var(--font-mono); + font-size: var(--text-xs); + text-overflow: ellipsis; + white-space: nowrap; +} + +.provider-badges { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); + margin-top: var(--space-2); +} + +.provider-edit-btn { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + border: 1px solid transparent; + border-radius: var(--radius-md); background: transparent; color: var(--muted); - border-color: transparent; + cursor: pointer; + transition: background-color var(--transition-fast), color var(--transition-fast), border-color var(--transition-fast); } -.ghost-button:hover:not(:disabled) { +.provider-edit-btn svg { + transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1); +} + +.provider-card:hover .provider-edit-btn, +.provider-edit-btn:focus-visible { + border-color: var(--line-strong); + background: var(--panel-strong); color: var(--text-strong); +} + +.provider-card:hover .provider-edit-btn svg { + transform: rotate(45deg); +} + +/* Provider brand avatars: per-provider colors arrive via --brand / --brand-bg. */ +.provider-avatar { + --brand: var(--accent); + --brand-bg: var(--accent-muted); + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: 38px; + height: 38px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: var(--brand-bg); + color: var(--brand); +} + +html[data-theme="light"] .provider-avatar:not(.is-mono):not(.is-initials) { + /* Darken bright brand colors so marks keep contrast on light surfaces. */ + color: color-mix(in srgb, var(--brand) 80%, #000000); +} + +.provider-avatar.is-mono { + --brand: var(--mono-brand); + --brand-bg: var(--mono-brand-bg); + color: var(--mono-brand); +} + +.provider-avatar.is-initials { + background: linear-gradient(135deg, var(--accent-solid), #7c3aed); + border-color: transparent; + color: #ffffff; + font-size: var(--text-base); + font-weight: var(--weight-bold); +} + +.provider-avatar svg { + display: block; + width: 20px; + height: 20px; +} + +/* Status pills */ +.status-pill { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 20px; + padding: 0 var(--space-2); + border: 1px solid var(--neutral-border); + border-radius: var(--radius-full); + background: var(--neutral-bg); + color: var(--neutral); + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + line-height: 1; + white-space: nowrap; +} + +.status-pill::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} + +.status-pill:empty { + display: none; +} + +.status-pill.ok { + border-color: var(--ok-border); + background: var(--ok-bg); + color: var(--ok); +} + +.status-pill.warn { + border-color: var(--warn-border); + background: var(--warn-bg); + color: var(--warn); +} + +.status-pill.error { + border-color: var(--error-border); + background: var(--error-bg); + color: var(--error); +} + +.kind-tag { + display: inline-flex; + align-items: center; + min-height: 20px; + padding: 0 var(--space-2); + border-radius: var(--radius-sm); background: var(--panel-strong); + color: var(--muted); + font-size: var(--text-xs); + font-weight: var(--weight-medium); + white-space: nowrap; } -/* Forms layout */ -.form-sections { - display: grid; - gap: 24px; +.kind-tag:empty { + display: none; } -.settings-section { - padding: 24px; - scroll-margin-top: 24px; +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + padding: var(--space-10) var(--space-4); + border: 1px dashed var(--line-strong); + border-radius: var(--radius-lg); + color: var(--muted); + font-size: var(--text-base); + text-align: center; } -.section-heading { - border-bottom: 1px solid var(--line); - padding-bottom: 16px; - margin-bottom: 24px; +.empty-state strong { + color: var(--text-strong); + font-size: var(--text-md); } +/* ========================================================================== + Form fields + ========================================================================== */ + .field-grid { display: grid; - grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); - gap: 20px; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: var(--space-5) var(--space-6); } -/* Field Grouping */ .field { display: flex; flex-direction: column; - gap: 8px; - align-content: start; + gap: 6px; + min-width: 0; } .field label { display: flex; align-items: center; justify-content: space-between; - gap: 8px; - font-size: 13px; - font-weight: 700; + gap: var(--space-2); color: var(--text-strong); + font-size: var(--text-base); + font-weight: var(--weight-semibold); } .field-source { - color: var(--accent); - font-size: 11px; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.05em; - background: var(--accent-muted); + flex-shrink: 0; padding: 1px 6px; border-radius: var(--radius-sm); + background: var(--accent-muted); + color: var(--accent); + font-size: 10px; + font-weight: var(--weight-semibold); + letter-spacing: 0.05em; + text-transform: uppercase; } -/* Form Inputs, Select, Textareas */ .field input[type="text"], .field input[type="number"], .field input[type="password"], .field select, .field textarea { width: 100%; - min-height: 40px; + min-height: var(--control-height); + padding: 8px 12px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--input); color: var(--text-strong); - padding: 10px 14px; - font-size: 14px; - transition: all var(--transition-fast); + font-size: var(--text-base); + transition: border-color var(--transition-fast), box-shadow var(--transition-fast), background-color var(--transition-fast); +} + +.field input::placeholder, +.field textarea::placeholder { + color: var(--subtle); } -/* Custom Dropdown Styling for Select Elements */ .field select { appearance: none; -webkit-appearance: none; -moz-appearance: none; background-image: var(--dropdown-chevron); background-repeat: no-repeat; - background-position: right 14px center; + background-position: right 12px center; background-size: 14px; padding-right: 36px; } +.field input:focus, +.field select:focus, +.field textarea:focus { + border-color: var(--accent); + background-color: var(--input-focus); + box-shadow: 0 0 0 3px var(--accent-muted); + outline: none; +} + +.field textarea { + min-height: 100px; + resize: vertical; + line-height: var(--leading-normal); +} + +.field input:disabled, +.field select:disabled, +.field textarea:disabled { + border-color: var(--line); + background-color: var(--panel-strong); + color: var(--muted); + cursor: not-allowed; +} + +.field-description { + color: var(--muted); + font-size: var(--text-sm); + line-height: var(--leading-normal); + overflow-wrap: anywhere; +} + +/* Model combobox */ .model-combobox { position: relative; width: 100%; @@ -583,7 +1068,7 @@ textarea:focus-visible, } .field .model-combobox input[type="text"] { - padding-right: 44px; + padding-right: 42px; } .model-combobox-toggle { @@ -591,22 +1076,23 @@ textarea:focus-visible, top: 0; right: 0; display: grid; - width: 42px; - height: 40px; place-items: center; + width: 40px; + height: var(--control-height); border: 0; + border-radius: 0 var(--radius-md) var(--radius-md) 0; background: transparent; cursor: pointer; } .model-combobox-toggle::before { + content: ""; width: 14px; height: 14px; background-image: var(--dropdown-chevron); background-position: center; background-repeat: no-repeat; background-size: 14px; - content: ""; transition: transform var(--transition-fast); } @@ -615,8 +1101,8 @@ textarea:focus-visible, } .model-combobox-toggle:disabled { - cursor: not-allowed; opacity: 0.5; + cursor: not-allowed; } .model-combobox-list { @@ -626,13 +1112,13 @@ textarea:focus-visible, left: 0; z-index: 120; max-height: 280px; + padding: var(--space-1); overflow-y: auto; overscroll-behavior: contain; border: 1px solid var(--line-strong); border-radius: var(--radius-md); - background: var(--panel-strong); - box-shadow: var(--shadow); - padding: 6px; + background: var(--panel); + box-shadow: var(--shadow-lg); } .model-combobox-list[hidden] { @@ -640,11 +1126,11 @@ textarea:focus-visible, } .model-combobox-option { + padding: 7px 10px; border-radius: var(--radius-sm); - padding: 9px 10px; color: var(--text); - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 12px; + font-family: var(--font-mono); + font-size: var(--text-sm); line-height: 1.35; overflow-wrap: anywhere; cursor: pointer; @@ -659,732 +1145,883 @@ textarea:focus-visible, .model-combobox-empty { padding: 10px; color: var(--muted); - font-size: 12px; + font-size: var(--text-sm); line-height: 1.4; } -.field input:focus, -.field select:focus, -.field textarea:focus { - border-color: var(--accent); - background: var(--input-focus); - box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15); - outline: none; -} - -/* Checkbox specific layout styling */ -.field input[type="checkbox"] { - align-self: flex-start; - width: 20px; - height: 20px; - accent-color: var(--accent); - cursor: pointer; - margin: 4px 0; -} - -.field textarea { - min-height: 100px; - resize: vertical; - line-height: 1.5; +/* Advanced fields */ +.field.advanced-field { + display: none; } -.field input:disabled, -.field select:disabled, -.field textarea:disabled { - background: rgba(255, 255, 255, 0.02); - border-color: var(--line); - color: var(--muted); - cursor: not-allowed; +.settings-section.show-advanced .advanced-field, +.modal-fields.show-advanced .advanced-field { + display: flex; } -.field-description { - color: var(--muted); - font-size: 12px; - line-height: 1.4; - margin-top: 2px; +.advanced-toggle { + margin-top: var(--space-5); + border-color: var(--line-strong); } -/* Show/Hide Advanced fields */ -.field.advanced-field { - display: none; +.advanced-toggle::after { + content: ""; + width: 12px; + height: 12px; + background: var(--dropdown-chevron) center / 12px no-repeat; + transition: transform var(--transition-fast); } -.settings-section.show-advanced .advanced-field { - display: flex; +.advanced-toggle[aria-expanded="true"]::after { + transform: rotate(180deg); } -.advanced-toggle { - margin-top: 20px; - font-size: 12px; - border: 1px solid var(--line-strong); -} +/* ========================================================================== + Action bar + ========================================================================== */ -/* Fixed Bottom Action Bar */ .action-bar { position: fixed; right: 0; bottom: 0; - left: 260px; + left: var(--sidebar-width); z-index: 100; display: grid; - grid-template-columns: minmax(0, 1.2fr) minmax(200px, 1fr) auto; - gap: 20px; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr) auto; align-items: center; - min-height: 80px; + gap: var(--space-5); + min-height: var(--action-bar-height); + padding: var(--space-3) var(--space-10); border-top: 1px solid var(--line); - background: var(--panel); - padding: 16px 40px; - backdrop-filter: blur(20px); - -webkit-backdrop-filter: blur(20px); - box-shadow: 0 -8px 30px rgba(0, 0, 0, 0.2); -} - -html[data-theme="light"] .action-bar { - background: rgba(255, 255, 255, 0.95); - border-top: 1px solid rgba(0, 0, 0, 0.08); - box-shadow: 0 -8px 30px rgba(0, 0, 0, 0.06); + background: var(--action-bar-bg); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); } .action-meta { display: flex; flex-direction: column; - gap: 4px; + gap: 2px; min-width: 0; } .action-meta strong { - font-size: 14px; - font-weight: 700; - color: var(--text-strong); - white-space: nowrap; + display: inline-flex; + align-items: center; + gap: var(--space-2); overflow: hidden; + color: var(--text-strong); + font-size: var(--text-md); + font-weight: var(--weight-semibold); text-overflow: ellipsis; + white-space: nowrap; +} + +.action-meta strong::before { + content: ""; + flex-shrink: 0; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--ok); +} + +.action-bar.is-dirty .action-meta strong::before { + background: var(--warn); + box-shadow: 0 0 0 3px var(--warn-bg); } .action-meta span { - color: var(--muted); - font-size: 11px; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - white-space: nowrap; overflow: hidden; + color: var(--muted); + font-family: var(--font-mono); + font-size: var(--text-xs); text-overflow: ellipsis; + white-space: nowrap; } .message-area { min-width: 0; color: var(--muted); - font-size: 13px; - font-weight: 500; + font-size: var(--text-base); + font-weight: var(--weight-medium); line-height: 1.4; -} - -.message-area.error { - color: var(--error); - font-weight: 600; + overflow-wrap: anywhere; } .message-area.ok { color: var(--ok); - font-weight: 600; } .message-area.warn { color: var(--warn); - font-weight: 600; +} + +.message-area.error { + color: var(--error); } .action-buttons { display: flex; - gap: 12px; + gap: var(--space-3); } .action-buttons button { - min-width: 100px; + min-width: 96px; } -/* Logs View Custom Styles & Toolbar */ -.logs-header { +/* ========================================================================== + Logs + ========================================================================== */ + +.logs-panel { display: flex; - justify-content: space-between; - align-items: center; - border-bottom: 1px solid var(--line); - padding-bottom: 12px; + flex-direction: column; + gap: var(--space-4); +} + +.logs-header { margin-bottom: 0; } .logs-controls { display: flex; + flex-wrap: wrap; align-items: center; - gap: 16px; + gap: var(--space-4); } -.log-toolbar { - display: flex; - gap: 12px; +.live-indicator { + display: inline-flex; align-items: center; - background-color: var(--panel-strong); - padding: 10px 14px; - border-radius: var(--radius-sm); - border: 1px solid var(--line); + gap: 6px; + color: var(--muted); + font-size: var(--text-sm); + font-weight: var(--weight-semibold); } -.log-toolbar input { - flex: 1; - height: 36px; - font-size: 13px; - padding: 0 12px; - border-radius: var(--radius-sm); - border: 1px solid var(--line); - background-color: var(--input); - color: var(--text); - outline: none; - min-width: 0; +.live-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--subtle); } -.log-level-group { - display: flex; - gap: 6px; +.live-indicator.is-live { + color: var(--ok); } -.log-level-btn { - height: 32px; - font-size: 12px; - padding: 0 12px; - border-radius: var(--radius-sm); - border: 1px solid var(--line); - background-color: var(--input); - color: var(--text); - cursor: pointer; - font-weight: 600; - transition: all var(--transition-fast); +.live-indicator.is-live .live-dot { + background: var(--ok); + animation: live-pulse 2s ease-in-out infinite; } -.log-level-btn.active { - background-color: var(--accent); - border-color: var(--accent); - color: #ffffff; +@keyframes live-pulse { + 0%, + 100% { + box-shadow: 0 0 0 0 var(--ok-border); + } + 50% { + box-shadow: 0 0 0 4px transparent; + } } -.clear-logs-btn { - height: 32px; - font-size: 12px; - padding: 0 14px; +.log-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); +} + +.segmented { + display: inline-flex; + padding: 2px; + border: 1px solid var(--line-strong); + border-radius: var(--radius-md); + background: var(--panel-strong); +} + +.log-level-btn { + min-height: 26px; + padding: 0 var(--space-3); + border: 0; border-radius: var(--radius-sm); - border: 1px solid var(--line); - background-color: var(--input); - color: var(--text); + background: transparent; + color: var(--muted); + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + letter-spacing: 0.03em; cursor: pointer; - font-weight: 600; - white-space: nowrap; + transition: background-color var(--transition-fast), color var(--transition-fast); } -.clear-logs-btn:hover { - background-color: var(--panel-strong); - border-color: var(--text); +.log-level-btn:hover { + color: var(--text-strong); +} + +.log-level-btn.active { + background: var(--panel); + color: var(--text-strong); + box-shadow: var(--shadow-sm); } .logs-container { - background-color: var(--input); + height: min(60vh, 560px); + min-height: 260px; + overflow: auto; + padding: var(--space-2) 0; border: 1px solid var(--line); border-radius: var(--radius-md); - padding: 16px; - height: 500px; - overflow-y: auto; - overflow-x: auto; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 12px; - white-space: pre-wrap; - word-break: break-word; + background: var(--input); color: var(--text); - display: flex; - flex-direction: column; - gap: 6px; - scrollbar-color: var(--panel-strong) var(--bg); + font-family: var(--font-mono); + font-size: var(--text-sm); + line-height: 1.55; } -.logs-container::-webkit-scrollbar { - width: 8px; - height: 8px; -} -.logs-container::-webkit-scrollbar-track { - background: var(--input); +.log-row { + display: grid; + grid-template-columns: 64px 64px minmax(0, 1fr); + gap: var(--space-3); + padding: 2px var(--space-4); + border-left: 2px solid transparent; } -.logs-container::-webkit-scrollbar-thumb { + +.log-row:hover { background: var(--panel-strong); - border-radius: var(--radius-full); -} -.logs-container::-webkit-scrollbar-thumb:hover { - background: var(--muted); } -/* Modern Responsive Media Queries */ - -@media (max-width: 1024px) { - .sidebar { - width: 220px; - padding: 24px 16px; - } +.log-row.level-error { + border-left-color: var(--error); + background: var(--error-bg); +} - .main { - padding: 32px 24px; - } +.log-row.level-warning { + border-left-color: var(--warn); +} - .action-bar { - left: 220px; - padding: 16px 24px; - } +.log-time { + color: var(--subtle); + font-variant-numeric: tabular-nums; +} - .provider-grid { - grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); - } +.log-level { + color: var(--neutral); + font-weight: var(--weight-bold); } -@media (max-width: 768px) { - .app-shell { - display: flex; - flex-direction: column; - padding-bottom: 160px; - } +.level-info .log-level { + color: var(--info); +} - .sidebar { - position: sticky; - top: 0; - z-index: 90; - width: 100%; - height: auto; - border-right: 0; - border-bottom: 1px solid var(--line); - padding: 14px 16px; - gap: 14px; - background: var(--panel); - backdrop-filter: blur(20px); - -webkit-backdrop-filter: blur(20px); - } +.level-success .log-level { + color: var(--ok); +} - .brand { - justify-content: flex-start; - } +.level-warning .log-level { + color: var(--warn); +} - .section-nav { - display: flex; - gap: 8px; - overflow-x: auto; - padding-bottom: 4px; - scrollbar-width: none; - -ms-overflow-style: none; - } +.level-error .log-level { + color: var(--error); +} - .section-nav::-webkit-scrollbar { - display: none; - } +.log-message { + white-space: pre-wrap; + overflow-wrap: anywhere; +} - .nav-link { - white-space: nowrap; - flex-shrink: 0; - width: auto; - padding: 8px 14px; - } +.log-extra { + margin-left: var(--space-2); + color: var(--muted); + font-size: var(--text-xs); +} - .main { - padding: 20px 16px; - } +.logs-notice { + padding: var(--space-6) var(--space-4); + color: var(--muted); + font-family: var(--font-sans); + text-align: center; +} - .topbar { - margin-bottom: 24px; - } +.logs-notice.error { + color: var(--error); +} - .topbar h2 { - font-size: 22px; - } +.logs-footer { + color: var(--subtle); + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; +} - .provider-grid { - grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); - gap: 12px; - } +/* ========================================================================== + Settings: theme picker + ========================================================================== */ - .provider-card { - padding: 16px; - } +.theme-options-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: var(--space-4); +} - .field-grid { - grid-template-columns: 1fr; - gap: 16px; - } +.theme-card { + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-3); + border: 1px solid var(--line-strong); + border-radius: var(--radius-lg); + background: var(--card); + color: var(--text); + text-align: left; + cursor: pointer; + transition: border-color var(--transition-fast), background-color var(--transition-fast), box-shadow var(--transition-fast); +} - .section-card { - padding: 18px 16px; - } +.theme-card:hover { + border-color: var(--muted); + background: var(--card-hover); +} - .logs-header { - flex-direction: column; - align-items: flex-start; - gap: 10px; - } +.theme-card.active { + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-muted); +} - .log-toolbar { - flex-direction: column; - align-items: stretch; - gap: 10px; - } +.theme-card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding: 0 var(--space-1); +} - .log-level-group { - display: flex; - width: 100%; - gap: 6px; - } +.theme-card-title { + display: inline-flex; + align-items: center; + gap: var(--space-2); + color: var(--text-strong); + font-size: var(--text-md); + font-weight: var(--weight-semibold); +} - .log-level-btn { - flex: 1; - text-align: center; - padding: 0 4px; - } +.theme-check { + display: inline-grid; + place-items: center; + width: 20px; + height: 20px; + border-radius: 50%; + background: var(--accent-solid); + color: var(--accent-contrast); + font-size: var(--text-xs); + font-weight: var(--weight-bold); + opacity: 0; + transition: opacity var(--transition-fast); +} - .clear-logs-btn { - width: 100%; - } +.theme-card.active .theme-check { + opacity: 1; +} - .action-bar { - left: 0; - right: 0; - bottom: 0; - grid-template-columns: 1fr; - gap: 12px; - padding: 14px 16px; - min-height: auto; - } +.theme-card-desc { + padding: 0 var(--space-1) var(--space-1); + color: var(--muted); + font-size: var(--text-sm); + line-height: 1.4; +} - html[data-theme="dark"] .action-bar { - background: rgba(17, 19, 28, 0.95); - } +/* Miniature theme previews */ +.theme-preview { + display: grid; + grid-template-columns: 28% 1fr; + height: 72px; + overflow: hidden; + border: 1px solid var(--line); + border-radius: var(--radius-md); +} - html[data-theme="light"] .action-bar { - background: rgba(255, 255, 255, 0.95); - } +.theme-preview-pane { + display: flex; + flex-direction: column; + gap: 5px; + padding: 8px; +} - .action-meta { - flex-direction: row; - justify-content: space-between; - align-items: center; - } +.theme-preview-pane span { + display: block; + height: 6px; + border-radius: 3px; +} - .action-meta span { - text-align: right; - } +.theme-preview-pane span:nth-child(2) { + width: 70%; +} - .action-buttons { - width: 100%; - gap: 10px; - } +.theme-preview-pane span:nth-child(3) { + width: 45%; +} - .action-buttons button { - flex: 1; - min-height: 42px; - } +.theme-preview.is-dark .theme-preview-side { + background: #12151c; } -@media (max-width: 480px) { - .sidebar { - padding: 12px; - } +.theme-preview.is-dark .theme-preview-main { + background: #0b0d12; +} - .brand-title { - font-size: 20px; - } +.theme-preview.is-dark span { + background: #2a303c; +} - .brand-mark { - width: 36px; - height: 36px; - } +.theme-preview.is-dark .theme-preview-main span:first-child { + background: #2563eb; +} - .main { - padding: 16px 12px; - } +.theme-preview.is-light .theme-preview-side { + background: #ffffff; +} - .provider-grid { - grid-template-columns: 1fr; - } +.theme-preview.is-light .theme-preview-main { + background: #f1f3f6; +} - .action-meta { - flex-direction: column; - align-items: flex-start; - gap: 2px; - } +.theme-preview.is-light span { + background: #d7dce4; +} - .action-meta span { - text-align: left; - } +.theme-preview.is-light .theme-preview-main span:first-child { + background: #2563eb; +} - .action-buttons { - flex-direction: column; - } +.theme-preview.is-system { + grid-template-columns: 1fr 1fr; +} - .action-buttons button { - width: 100%; - } +.theme-preview-half-dark { + background: #0b0d12; +} - .logs-container { - height: 400px; - font-size: 11px; - padding: 12px; - } +.theme-preview-half-dark span { + background: #2a303c; +} - .modal-container { - width: calc(100vw - 24px); - max-height: 90vh; - padding: 16px; - } +.theme-preview-half-light { + background: #f1f3f6; +} - .modal-footer { - flex-direction: column-reverse; - gap: 8px; - } +.theme-preview-half-light span { + background: #d7dce4; +} - .modal-footer button { - width: 100%; - } +.theme-preview-pane span:first-child { + width: 55%; } -/* Modal Backdrop Overlay */ +/* ========================================================================== + Modal + ========================================================================== */ + .modal-backdrop { position: fixed; - top: 0; - left: 0; - width: 100vw; - height: 100vh; - background-color: rgba(10, 10, 12, 0.7); - backdrop-filter: blur(14px); - -webkit-backdrop-filter: blur(14px); + inset: 0; + z-index: 1000; display: flex; align-items: center; justify-content: center; - z-index: 1000; + padding: var(--space-4); + background: var(--backdrop); + backdrop-filter: blur(6px); + -webkit-backdrop-filter: blur(6px); opacity: 0; visibility: hidden; pointer-events: none; - transition: opacity 0.3s ease, visibility 0.3s ease; + transition: opacity var(--transition-normal), visibility var(--transition-normal); } .modal-backdrop.active { opacity: 1; visibility: visible; pointer-events: auto; + /* Become visible immediately so the dialog can receive focus on open. */ + transition: opacity var(--transition-normal), visibility 0s; } -/* Modal Content Box */ .modal-container { - background: var(--panel); - border: 1px solid var(--line-strong); - border-radius: var(--radius-lg); - width: 580px; - max-width: 95%; - max-height: 90vh; display: flex; flex-direction: column; - box-shadow: 0 30px 60px rgba(0, 0, 0, 0.45), 0 0 0 1px rgba(255, 255, 255, 0.05); - transform: translateY(24px) scale(0.97); - transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); + width: 600px; + max-width: 100%; + max-height: min(88vh, 860px); overflow: hidden; + border: 1px solid var(--line-strong); + border-radius: var(--radius-lg); + background: var(--panel); + box-shadow: var(--shadow-lg); + transform: translateY(12px) scale(0.98); + transition: transform var(--transition-normal); } .modal-backdrop.active .modal-container { - transform: translateY(0) scale(1); + transform: none; } -/* Modal Header */ .modal-head { display: flex; align-items: center; justify-content: space-between; - padding: 20px 24px; + gap: var(--space-4); + padding: var(--space-5) var(--space-6); border-bottom: 1px solid var(--line); - background: var(--panel); } .modal-head-title { display: flex; align-items: center; - gap: 12px; + gap: var(--space-3); + min-width: 0; } .modal-head-title h3 { - margin: 0; - font-size: 18px; - font-weight: 700; + overflow: hidden; color: var(--text-strong); - letter-spacing: -0.02em; + font-size: var(--text-lg); + font-weight: var(--weight-semibold); + letter-spacing: -0.01em; + text-overflow: ellipsis; + white-space: nowrap; } -.modal-close-icon { - background: none; - border: none; - color: var(--muted); - cursor: pointer; - padding: 6px; - border-radius: var(--radius-full); +.modal-head-meta { display: flex; + flex-wrap: wrap; + gap: var(--space-2); + margin-top: var(--space-1); +} + +.modal-close-icon { + display: inline-flex; + flex-shrink: 0; align-items: center; justify-content: center; - transition: all var(--transition-fast); + width: 32px; + height: 32px; + border: 0; + border-radius: var(--radius-md); + background: transparent; + color: var(--muted); + cursor: pointer; + transition: background-color var(--transition-fast), color var(--transition-fast); } .modal-close-icon:hover { - color: var(--text-strong); background: var(--panel-strong); + color: var(--text-strong); } -/* Modal Body */ .modal-content-body { - padding: 24px; - overflow-y: auto; - flex: 1; display: flex; + flex: 1; flex-direction: column; - gap: 20px; + gap: var(--space-4); + padding: var(--space-6); + overflow-y: auto; } -/* Modal Field Container Cards */ -.modal-content-body .field { - background: var(--panel-strong); +.modal-description { + padding: var(--space-3) var(--space-4); border: 1px solid var(--line); + border-left: 3px solid var(--accent); border-radius: var(--radius-md); - padding: 16px; + background: var(--panel-strong); + color: var(--muted); + font-size: var(--text-base); + line-height: var(--leading-normal); + overflow-wrap: anywhere; +} + +.modal-fields { display: flex; flex-direction: column; - gap: 10px; + gap: var(--space-3); +} + +.modal-fields .field { + gap: var(--space-2); + padding: var(--space-4); + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: var(--card); transition: border-color var(--transition-fast), box-shadow var(--transition-fast); } -.modal-content-body .field:focus-within { - border-color: var(--accent); - box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12); +.modal-fields .field:focus-within { + border-color: var(--accent-border); } -.modal-content-body .field label { - display: flex; - align-items: center; - justify-content: space-between; - font-size: 13px; - font-weight: 600; - color: var(--text-strong); - margin-bottom: 0; +.modal-content-body .advanced-toggle { + align-self: flex-start; + margin-top: 0; } -.modal-content-body .field input[type="text"], -.modal-content-body .field input[type="password"], -.modal-content-body .field select, -.modal-content-body .field textarea { - width: 100%; - background: var(--input); - border: 1px solid var(--line); - border-radius: var(--radius-sm); - padding: 10px 14px; +.modal-message { + padding: var(--space-3) var(--space-4); + border: 1px solid var(--neutral-border); + border-radius: var(--radius-md); + background: var(--neutral-bg); color: var(--text); - font-size: 13px; - outline: none; - transition: border-color var(--transition-fast); + font-size: var(--text-base); + overflow-wrap: anywhere; } -.modal-content-body .field input:focus, -.modal-content-body .field select:focus, -.modal-content-body .field textarea:focus { - border-color: var(--accent) !important; +.modal-message:empty { + display: none; } -.modal-content-body .field-description { - font-size: 12px; - color: var(--muted); - line-height: 1.5; - margin-top: 2px; +.modal-message.ok { + border-color: var(--ok-border); + background: var(--ok-bg); + color: var(--ok); +} + +.modal-message.warn { + border-color: var(--warn-border); + background: var(--warn-bg); + color: var(--warn); +} + +.modal-message.error { + border-color: var(--error-border); + background: var(--error-bg); + color: var(--error); } -/* Modal Footer */ .modal-foot { display: flex; - justify-content: space-between; + flex-wrap: wrap; align-items: center; - padding: 16px 24px; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-4) var(--space-6); border-top: 1px solid var(--line); background: var(--panel-strong); } -/* Provider Gear Icon Rotate Animation on Hover */ -.provider-edit-btn svg { - transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1); +.modal-foot-actions { + display: flex; + gap: var(--space-2); } -.provider-card:hover .provider-edit-btn svg { - transform: rotate(45deg); -} +/* ========================================================================== + Responsive layout + ========================================================================== */ -.provider-edit-btn:hover svg { - transform: rotate(90deg); -} +/* Medium widths: collapse the sidebar into an icon rail. */ +@media (max-width: 1100px) { + :root { + --sidebar-width: 68px; + } -/* Slide up scale keyframes (fallback for older engines) */ -@keyframes modalFadeIn { - from { - opacity: 0; - transform: translateY(20px) scale(0.96); + .sidebar { + align-items: center; + padding: var(--space-5) var(--space-2); } - to { - opacity: 1; - transform: translateY(0) scale(1); + + .brand { + padding: 0; } -} -/* Theme Toggle Button & Settings Options */ -.theme-toggle-btn { - background: var(--card); - border: 1px solid var(--line); - color: var(--text); - width: 36px; - height: 36px; - border-radius: var(--radius-md); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: all var(--transition-fast); -} + .brand-text, + .nav-link span { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + } -.theme-toggle-btn:hover { - background: var(--card-hover); - border-color: var(--line-strong); - color: var(--text-strong); -} + .nav-link { + justify-content: center; + width: 44px; + height: 40px; + padding: 0; + } -html[data-theme="light"] .theme-toggle-btn .sun-icon { - display: none; -} -html[data-theme="light"] .theme-toggle-btn .moon-icon { - display: block; -} + .main { + padding: var(--space-6); + } -html:not([data-theme="light"]) .theme-toggle-btn .sun-icon { - display: block; -} -html:not([data-theme="light"]) .theme-toggle-btn .moon-icon { - display: none; + .action-bar { + padding: var(--space-3) var(--space-6); + } } -.theme-card { - background: var(--card); - border: 2px solid var(--line); - border-radius: var(--radius-md); - padding: 16px; - cursor: pointer; - transition: all var(--transition-fast); - display: flex; - flex-direction: column; - gap: 10px; -} +/* Narrow widths: sidebar becomes a top bar with horizontal navigation. */ +@media (max-width: 720px) { + :root { + --sidebar-width: 0px; + } -.theme-card:hover { - border-color: var(--line-strong); - background: var(--card-hover); + .app-shell { + display: flex; + flex-direction: column; + padding-bottom: 176px; + } + + .sidebar { + position: sticky; + top: 0; + z-index: 90; + flex-direction: row; + align-items: center; + gap: var(--space-3); + height: auto; + padding: var(--space-2) var(--space-3); + border-right: 0; + border-bottom: 1px solid var(--line); + background: var(--action-bar-bg); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + } + + .brand-mark { + width: 30px; + height: 30px; + } + + .section-nav { + display: flex; + flex: 1; + gap: var(--space-1); + overflow-x: auto; + scrollbar-width: none; + } + + .section-nav::-webkit-scrollbar { + display: none; + } + + .nav-link { + flex-shrink: 0; + width: auto; + height: 34px; + padding: 0 var(--space-3); + white-space: nowrap; + } + + .nav-link span { + position: static; + width: auto; + height: auto; + overflow: visible; + clip: auto; + } + + .nav-link svg { + width: 16px; + height: 16px; + } + + .main { + padding: var(--space-5) var(--space-4); + } + + .topbar h2 { + font-size: var(--text-xl); + } + + .panel, + .provider-strip, + .settings-section { + padding: var(--space-4); + } + + .provider-toolbar { + flex-basis: 100%; + justify-content: flex-start; + max-width: none; + } + + .provider-group-description { + display: none; + } + + .provider-grid, + .field-grid { + grid-template-columns: 1fr; + } + + .log-row { + grid-template-columns: auto auto; + gap: 0 var(--space-3); + } + + .log-message { + grid-column: 1 / -1; + } + + .action-bar { + left: 0; + grid-template-columns: 1fr; + gap: var(--space-2); + padding: var(--space-3) var(--space-4); + } + + .action-meta { + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + } + + .action-buttons button { + flex: 1; + } + + .modal-backdrop { + align-items: flex-end; + padding: 0; + } + + .modal-container { + width: 100%; + max-height: 92vh; + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + } + + .modal-head, + .modal-content-body, + .modal-foot { + padding-right: var(--space-4); + padding-left: var(--space-4); + } + + .modal-foot, + .modal-foot-actions { + flex-direction: column-reverse; + align-items: stretch; + } + + .modal-foot button { + width: 100%; + } } -.theme-card.active { - border-color: var(--accent); - background: var(--accent-muted); +/* ========================================================================== + Reduced motion + ========================================================================== */ + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } + + .provider-card:hover { + transform: none; + } } diff --git a/src/codefa/api/admin_static/admin.js b/src/codefa/api/admin_static/admin.js old mode 100755 new mode 100644 index f67bd85..21c8f19 --- a/src/codefa/api/admin_static/admin.js +++ b/src/codefa/api/admin_static/admin.js @@ -5,6 +5,9 @@ const state = { modelOptions: [], modelComboboxes: new Set(), activeView: "providers", + providerFilter: { query: "", configuredOnly: false }, + busy: false, + restarting: false, }; const MASKED_SECRET = "********"; @@ -13,6 +16,7 @@ const VIEW_GROUPS = [ id: "providers", label: "Providers", title: "Providers", + subtitle: "Connect cloud APIs and local model servers.", sections: ["providers", "runtime"], containerId: "providersSections", }, @@ -20,6 +24,7 @@ const VIEW_GROUPS = [ id: "model_config", label: "Model Config", title: "Model Config", + subtitle: "Route Claude Code / Codex model slots to provider models.", sections: ["models", "reasoning", "web_tools"], containerId: "modelConfigSections", }, @@ -27,6 +32,7 @@ const VIEW_GROUPS = [ id: "messaging", label: "Messaging", title: "Messaging", + subtitle: "Chat platform bots, sessions, and voice notes.", sections: ["messaging", "voice"], containerId: "messagingSections", }, @@ -34,6 +40,7 @@ const VIEW_GROUPS = [ id: "logs", label: "Logs", title: "Server Logs", + subtitle: "Inspect recent server activity.", sections: [], containerId: "logsSections", }, @@ -41,12 +48,75 @@ const VIEW_GROUPS = [ id: "settings", label: "Settings", title: "Settings", + subtitle: "Preferences for this admin dashboard.", sections: [], containerId: "settingsSections", }, ]; +const PROVIDER_GROUPS = [ + { + kind: "remote", + title: "Cloud", + description: "Hosted APIs authenticated with a key or token", + }, + { + kind: "local", + title: "Local", + description: "Model servers running on this machine", + }, +]; + +const THEME_STORAGE_KEY = "codefa_theme"; +const THEME_MODES = ["dark", "light", "system"]; +const SVG_NS = "http://www.w3.org/2000/svg"; +const LOGS_POLL_MS = 3000; + const byId = (id) => document.getElementById(id); +const prefersReducedMotion = () => + window.matchMedia("(prefers-reduced-motion: reduce)").matches; + +function escapeHtml(value) { + return String(value ?? "").replace( + /[&<>"']/g, + (char) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char], + ); +} + +// Renders server-provided description text without innerHTML. Supports the two +// markup forms used in field descriptions: [label](https://url) and `code`. +// Links are only created for http(s) URLs; anything else stays plain text. +function renderRichText(target, text) { + target.replaceChildren(); + const source = String(text ?? ""); + const pattern = /\[([^\]]+)\]\(([^)\s]+)\)|`{1,2}([^`]+)`{1,2}/g; + let cursor = 0; + for (const match of source.matchAll(pattern)) { + if (match.index > cursor) { + target.append(source.slice(cursor, match.index)); + } + const [raw, linkText, url, code] = match; + if (code !== undefined) { + const codeEl = document.createElement("code"); + codeEl.textContent = code; + target.append(codeEl); + } else if (/^https?:\/\//i.test(url)) { + const link = document.createElement("a"); + link.href = url; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.textContent = linkText; + target.append(link); + } else { + target.append(raw); + } + cursor = match.index + raw.length; + } + if (cursor < source.length) { + target.append(source.slice(cursor)); + } +} function sourceLabel(source) { const labels = { @@ -74,23 +144,50 @@ function sourceText(field) { function statusClass(status) { if (["configured", "reachable", "running"].includes(status)) return "ok"; - if (["missing_key", "missing_config", "missing_url", "unknown"].includes(status)) return "warn"; + if (["missing_key", "missing_config", "missing_url", "invalid_url", "unknown"].includes(status)) + return "warn"; if (["offline", "error"].includes(status)) return "error"; return "neutral"; } async function api(path, options = {}) { const response = await fetch(path, { - headers: { "Content-Type": "application/json", ...(options.headers || {}) }, ...options, + headers: { "Content-Type": "application/json", ...(options.headers || {}) }, cache: "no-store", }); if (!response.ok) { - throw new Error(`${response.status} ${response.statusText}`); + throw new Error(await responseErrorMessage(response)); } return response.json(); } +async function responseErrorMessage(response) { + const status = `${response.status} ${response.statusText}`.trim(); + try { + const body = await response.json(); + if (typeof body?.detail === "string" && body.detail) { + return `${status}: ${body.detail}`; + } + } catch { + // Non-JSON error bodies fall back to the HTTP status line. + } + return status; +} + +// --------------------------------------------------------------------------- +// Theme +// --------------------------------------------------------------------------- + +function readThemeMode() { + try { + const mode = localStorage.getItem(THEME_STORAGE_KEY); + return THEME_MODES.includes(mode) ? mode : "dark"; + } catch { + return "dark"; + } +} + function getEffectiveTheme(mode) { if (mode === "system") { return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"; @@ -99,90 +196,90 @@ function getEffectiveTheme(mode) { } function setTheme(mode) { - const effective = getEffectiveTheme(mode); - document.documentElement.setAttribute("data-theme", effective); - localStorage.setItem("codefa_theme", mode); + document.documentElement.setAttribute("data-theme", getEffectiveTheme(mode)); + try { + localStorage.setItem(THEME_STORAGE_KEY, mode); + } catch { + // Storage can be unavailable (e.g. privacy mode); the theme still applies. + } document.querySelectorAll(".theme-card").forEach((card) => { - const cardMode = card.dataset.themeMode; - const check = card.querySelector(".theme-check"); - if (cardMode === mode) { - card.classList.add("active"); - if (check) check.style.opacity = "1"; - } else { - card.classList.remove("active"); - if (check) check.style.opacity = "0"; - } + const selected = card.dataset.themeMode === mode; + card.classList.toggle("active", selected); + card.setAttribute("aria-pressed", String(selected)); }); - - if (state.config && state.config.provider_status) { - renderProviders(state.config.provider_status); - } } function initTheme() { - const savedMode = localStorage.getItem("codefa_theme") || "dark"; - setTheme(savedMode); - - byId("themeToggleBtn")?.addEventListener("click", () => { - const currentTheme = document.documentElement.getAttribute("data-theme") || "dark"; - const newMode = currentTheme === "dark" ? "light" : "dark"; - setTheme(newMode); - }); + setTheme(readThemeMode()); document.querySelectorAll(".theme-card").forEach((card) => { - card.addEventListener("click", () => { - const mode = card.dataset.themeMode; - setTheme(mode); - }); + card.addEventListener("click", () => setTheme(card.dataset.themeMode)); }); window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { - const savedMode = localStorage.getItem("codefa_theme") || "dark"; - if (savedMode === "system") { + if (readThemeMode() === "system") { setTheme("system"); } }); } +// --------------------------------------------------------------------------- +// Loading & navigation +// --------------------------------------------------------------------------- + async function load() { - initTheme(); showMessage("Loading admin config"); const config = await api("/admin/api/config"); state.config = config; state.fields = new Map(config.fields.map((field) => [field.key, field])); + state.localStatus.clear(); renderNav(); renderProviders(config.provider_status); renderSections(config.sections, config.fields); - byId("configPath").textContent = config.paths.managed; + const configPath = byId("configPath"); + configPath.textContent = config.paths.managed; + configPath.title = config.paths.managed; await hydrateModelOptions(); await validate(false); - await refreshLocalStatus(); + let localStatusError = null; + try { + await refreshLocalStatus(); + } catch (error) { + // Local probes are informational; they must not block the rest of the UI. + localStatusError = error; + } updateDirtyState(); - showMessage(""); + if (localStatusError) { + showMessage(`Could not check local providers: ${localStatusError.message}`, "warn"); + } else { + showMessage(""); + } } const NAV_ICONS = { - providers: ``, - model_config: ``, - messaging: ``, - logs: ``, - settings: ``, + providers: ``, + model_config: ``, + messaging: ``, + logs: ``, + settings: ``, }; +const GEAR_ICON = NAV_ICONS.settings; + function renderNav() { const nav = byId("sectionNav"); - nav.innerHTML = ""; - VIEW_GROUPS.forEach((view, index) => { + nav.replaceChildren(); + VIEW_GROUPS.forEach((view) => { const button = document.createElement("button"); button.type = "button"; - button.className = `nav-link${index === 0 ? " active" : ""}`; + button.className = "nav-link"; button.dataset.view = view.id; - const icon = NAV_ICONS[view.id] || ""; - button.innerHTML = `${icon} ${view.label}`; - if (index === 0) { - button.setAttribute("aria-current", "page"); - } + button.title = view.label; + button.innerHTML = NAV_ICONS[view.id] || ""; + const label = document.createElement("span"); + label.textContent = view.label; + button.appendChild(label); button.addEventListener("click", () => { setActiveView(view.id, { scroll: true }); }); @@ -196,6 +293,7 @@ function setActiveView(viewId, { scroll = false } = {}) { VIEW_GROUPS.find((view) => view.id === viewId) || VIEW_GROUPS[0]; state.activeView = activeView.id; byId("pageTitle").textContent = activeView.title; + byId("pageSubtitle").textContent = activeView.subtitle || ""; document.querySelectorAll(".nav-link").forEach((link) => { const selected = link.dataset.view === activeView.id; @@ -214,7 +312,7 @@ function setActiveView(viewId, { scroll = false } = {}) { }); if (scroll) { - window.scrollTo({ top: 0, behavior: "smooth" }); + window.scrollTo({ top: 0, behavior: prefersReducedMotion() ? "auto" : "smooth" }); } if (activeView.id === "logs") { @@ -225,78 +323,168 @@ function setActiveView(viewId, { scroll = false } = {}) { } } +// --------------------------------------------------------------------------- +// Provider cards +// --------------------------------------------------------------------------- + function renderProviders(providerStatus) { - const grid = byId("providerGrid"); - grid.innerHTML = ""; - providerStatus.forEach((provider) => { - const card = document.createElement("article"); - card.className = "provider-card"; - card.dataset.provider = provider.provider_id; - card.style.cursor = "pointer"; - - const iconDiv = document.createElement("div"); - iconDiv.innerHTML = getProviderIcon(provider.provider_id, provider.display_name); - - const contentDiv = document.createElement("div"); - contentDiv.style.flex = "1"; - contentDiv.style.display = "flex"; - contentDiv.style.flexDirection = "column"; - contentDiv.style.gap = "4px"; - - const title = document.createElement("div"); - title.className = "provider-title"; - title.style.display = "flex"; - title.style.alignItems = "center"; - title.style.gap = "8px"; - title.style.margin = "0"; - title.innerHTML = `${provider.display_name || provider.provider_id}`; - - const pill = document.createElement("span"); - pill.className = `status-pill ${statusClass(provider.status)}`; - pill.textContent = provider.label; - title.appendChild(pill); - - const meta = document.createElement("div"); - meta.className = "provider-meta"; - meta.textContent = - provider.kind === "local" - ? provider.base_url || "No local URL configured" - : provider.configuration; - - contentDiv.append(title, meta); - - const editBtn = document.createElement("button"); - editBtn.type = "button"; - editBtn.className = "provider-edit-btn"; - editBtn.ariaLabel = `Configure ${provider.display_name}`; - editBtn.innerHTML = ``; - - card.append(iconDiv, contentDiv, editBtn); - - card.addEventListener("click", () => { - openProviderModal(provider.provider_id); - }); + const container = byId("providerGrid"); + container.replaceChildren(); + PROVIDER_GROUPS.forEach((group) => { + const providers = providerStatus.filter( + (provider) => (provider.kind === "local" ? "local" : "remote") === group.kind, + ); + if (providers.length === 0) return; + + const section = document.createElement("section"); + section.className = "provider-group"; + section.dataset.kind = group.kind; + const headingId = `provider-group-${group.kind}`; + section.setAttribute("aria-labelledby", headingId); + + const header = document.createElement("div"); + header.className = "provider-group-header"; + const heading = document.createElement("h4"); + heading.id = headingId; + heading.textContent = group.title; + const count = document.createElement("span"); + count.className = "provider-group-count"; + const description = document.createElement("span"); + description.className = "provider-group-description"; + description.textContent = group.description; + header.append(heading, count, description); + + const grid = document.createElement("div"); + grid.className = "provider-grid"; + grid.setAttribute("role", "list"); + providers.forEach((provider) => grid.appendChild(renderProviderCard(provider))); + + section.append(header, grid); + container.appendChild(section); + }); + applyProviderFilter(); +} - grid.appendChild(card); +function renderProviderCard(provider) { + const name = provider.display_name || provider.provider_id; + const card = document.createElement("article"); + card.className = "provider-card"; + card.dataset.provider = provider.provider_id; + card.dataset.kind = provider.kind; + card.setAttribute("role", "listitem"); + + const body = document.createElement("div"); + body.className = "provider-card-body"; + + const title = document.createElement("div"); + title.className = "provider-title"; + const titleText = document.createElement("strong"); + titleText.textContent = name; + titleText.title = name; + title.appendChild(titleText); + + const meta = document.createElement("div"); + meta.className = "provider-meta"; + meta.textContent = + provider.kind === "local" + ? provider.base_url || "No local URL configured" + : provider.configuration; + meta.title = meta.textContent; + + const badges = document.createElement("div"); + badges.className = "provider-badges"; + const pill = document.createElement("span"); + pill.className = "status-pill"; + const kindTag = document.createElement("span"); + kindTag.className = "kind-tag"; + kindTag.textContent = provider.kind === "local" ? "Local" : "Cloud"; + badges.append(pill, kindTag); + + body.append(title, meta, badges); + + const editBtn = document.createElement("button"); + editBtn.type = "button"; + editBtn.className = "provider-edit-btn"; + editBtn.setAttribute("aria-label", `Configure ${name}`); + editBtn.title = `Configure ${name}`; + editBtn.innerHTML = GEAR_ICON; + + card.append(getProviderIcon(provider.provider_id, provider.display_name), body, editBtn); + setCardStatus(card, provider.status, provider.label); + + card.addEventListener("click", () => { + openProviderModal(provider.provider_id, editBtn); }); + return card; +} + +function findProviderCard(providerId) { + return document.querySelector( + `#providerGrid .provider-card[data-provider="${CSS.escape(providerId)}"]`, + ); +} + +function setCardStatus(card, status, label) { + const tone = statusClass(status); + const pill = card.querySelector(".status-pill"); + pill.className = `status-pill ${tone}`; + pill.textContent = label || ""; + card.dataset.status = status || ""; + card.dataset.tone = tone; } function updateProviderCard(providerId, status, label, metaText) { - const card = document.querySelector(`[data-provider="${providerId}"]`); + const card = findProviderCard(providerId); if (!card) return; - const pill = card.querySelector(".status-pill"); - pill.className = `status-pill ${statusClass(status)}`; - pill.textContent = label; + setCardStatus(card, status, label); if (metaText) { - card.querySelector(".provider-meta").textContent = metaText; + const meta = card.querySelector(".provider-meta"); + meta.textContent = metaText; + meta.title = metaText; } + applyProviderFilter(); +} + +function applyProviderFilter() { + const query = state.providerFilter.query.trim().toLocaleLowerCase(); + const { configuredOnly } = state.providerFilter; + let total = 0; + let visible = 0; + let ready = 0; + + document.querySelectorAll("#providerGrid .provider-group").forEach((group) => { + const cards = Array.from(group.querySelectorAll(".provider-card")); + let groupVisible = 0; + cards.forEach((card) => { + const isReady = card.dataset.tone === "ok"; + const haystack = `${card.dataset.provider} ${card.textContent}`.toLocaleLowerCase(); + const matches = (!query || haystack.includes(query)) && (!configuredOnly || isReady); + card.hidden = !matches; + if (matches) groupVisible += 1; + if (isReady) ready += 1; + }); + group.hidden = groupVisible === 0; + group.querySelector(".provider-group-count").textContent = + groupVisible === cards.length ? String(cards.length) : `${groupVisible} of ${cards.length}`; + total += cards.length; + visible += groupVisible; + }); + + byId("providerEmpty").hidden = total === 0 || visible > 0; + byId("providerSummary").textContent = total + ? `${ready} of ${total} provider${total === 1 ? "" : "s"} configured or reachable` + : ""; } +// --------------------------------------------------------------------------- +// Config sections & fields +// --------------------------------------------------------------------------- + function renderSections(sections, fields) { state.modelComboboxes.clear(); VIEW_GROUPS.forEach((view) => { if (view.id !== "logs" && view.id !== "settings") { - byId(view.containerId).innerHTML = ""; + byId(view.containerId).replaceChildren(); } }); @@ -317,7 +505,7 @@ function renderSections(sections, fields) { if (sectionId === "providers") { const hiddenContainer = byId("hiddenFieldsContainer"); - hiddenContainer.innerHTML = ""; + hiddenContainer.replaceChildren(); sectionFields.forEach((field) => { hiddenContainer.appendChild(renderField(field)); }); @@ -330,11 +518,17 @@ function renderSections(sections, fields) { const heading = document.createElement("div"); heading.className = "section-heading"; - heading.innerHTML = `

${section.label}

${section.description}

`; + const headingText = document.createElement("div"); + const title = document.createElement("h3"); + title.textContent = section.label; + const description = document.createElement("p"); + description.textContent = section.description; + headingText.append(title, description); + heading.appendChild(headingText); if (section.id === "models") { const refreshButton = document.createElement("button"); refreshButton.type = "button"; - refreshButton.className = "secondary-button"; + refreshButton.className = "secondary-button button-sm"; refreshButton.textContent = "Refresh models"; refreshButton.addEventListener("click", () => refreshModelOptions(refreshButton)); heading.appendChild(refreshButton); @@ -343,6 +537,7 @@ function renderSections(sections, fields) { const grid = document.createElement("div"); grid.className = "field-grid"; + grid.id = `section-${section.id}-fields`; sectionFields.forEach((field) => { grid.appendChild(renderField(field)); }); @@ -351,11 +546,14 @@ function renderSections(sections, fields) { if (sectionFields.some((field) => field.advanced)) { const toggle = document.createElement("button"); toggle.type = "button"; - toggle.className = "ghost-button advanced-toggle"; + toggle.className = "ghost-button button-sm advanced-toggle"; toggle.textContent = "Show advanced"; + toggle.setAttribute("aria-expanded", "false"); + toggle.setAttribute("aria-controls", grid.id); toggle.addEventListener("click", () => { const showing = sectionEl.classList.toggle("show-advanced"); toggle.textContent = showing ? "Hide advanced" : "Show advanced"; + toggle.setAttribute("aria-expanded", String(showing)); }); sectionEl.appendChild(toggle); } @@ -387,7 +585,11 @@ function renderField(field) { const input = inputForField(field); input.id = `field-${field.key}`; input.dataset.key = field.key; - input.dataset.original = field.value || ""; + // Checkboxes normalize their own original value ("true"/"false"); using the raw + // env value (e.g. "True", "1", "") would report a phantom unsaved change. + if (input.dataset.original === undefined) { + input.dataset.original = field.value || ""; + } input.dataset.secret = field.secret ? "true" : "false"; input.dataset.configured = field.configured ? "true" : "false"; input.dataset.fieldType = field.type; @@ -411,7 +613,9 @@ function renderField(field) { if (field.description) { const description = document.createElement("div"); description.className = "field-description"; - description.textContent = field.description; + description.id = `field-${field.key}-description`; + renderRichText(description, field.description); + input.setAttribute("aria-describedby", description.id); wrapper.appendChild(description); } return wrapper; @@ -446,6 +650,7 @@ function inputForField(field) { input.type = "text"; input.value = field.value || (field.type === "optional_model" ? "None" : ""); input.autocomplete = "off"; + input.spellcheck = false; return input; } @@ -562,7 +767,7 @@ class ModelCombobox { value.toLocaleLowerCase().includes(normalizedQuery), ) : this.values; - this.listbox.innerHTML = ""; + this.listbox.replaceChildren(); if (values.length === 0) { const empty = document.createElement("div"); @@ -651,6 +856,10 @@ function option(value, label) { return optionEl; } +// --------------------------------------------------------------------------- +// Dirty state, validate & apply +// --------------------------------------------------------------------------- + function readFieldValue(input) { if (input.type === "checkbox") return input.checked ? "true" : "false"; if ( @@ -681,7 +890,32 @@ function updateDirtyState() { const count = Object.keys(changedValues()).length; byId("dirtyState").textContent = count === 0 ? "No changes" : `${count} unsaved change${count === 1 ? "" : "s"}`; - byId("applyButton").disabled = count === 0; + document.querySelector(".action-bar").classList.toggle("is-dirty", count > 0); + byId("applyButton").disabled = count === 0 || state.busy || state.restarting; + return count; +} + +// Serializes validate/apply so double clicks cannot submit overlapping requests, +// and surfaces failures instead of leaving unhandled promise rejections. +async function runAction(action) { + if (state.busy) return undefined; + setBusy(true); + try { + return await action(); + } catch (error) { + showMessage(error.message || String(error), "error"); + return undefined; + } finally { + setBusy(false); + } +} + +function setBusy(busy) { + state.busy = busy; + byId("validateButton").disabled = busy; + byId("modalSaveBtn").disabled = busy; + document.querySelector(".action-bar").setAttribute("aria-busy", String(busy)); + updateDirtyState(); } async function validate(showResult = true) { @@ -695,11 +929,15 @@ async function validate(showResult = true) { return result; } +function validationErrorText(result) { + return (result.errors || []).join("; ") || "Configuration is invalid"; +} + function showValidationResult(result) { if (result.valid) { showMessage("Config shape is valid", "ok"); } else { - showMessage(result.errors.join("; "), "error"); + showMessage(validationErrorText(result), "error"); } } @@ -710,16 +948,17 @@ async function apply() { }); if (!result.applied) { showValidationResult(result); - return; + return result; } const restart = result.restart || {}; if (restart.required && restart.automatic) { + state.restarting = true; showMessage("Applied. Restarting server...", "ok"); byId("applyButton").disabled = true; setTimeout(() => { window.location.href = restart.admin_url || "/admin"; }, 1600); - return; + return result; } const pending = restart.required ? restart.fields || [] : result.pending_fields || []; await load(); @@ -729,6 +968,7 @@ async function apply() { : "Applied", "ok", ); + return result; } async function refreshLocalStatus() { @@ -742,34 +982,9 @@ async function refreshLocalStatus() { }); } -async function testProvider(providerId, button) { - const original = button.textContent; - button.disabled = true; - button.textContent = "Testing"; - try { - const result = await api(`/admin/api/providers/${providerId}/test`, { - method: "POST", - body: "{}", - }); - if (result.ok) { - updateProviderCard( - providerId, - "reachable", - `${result.models.length} models`, - result.models.slice(0, 3).join(", ") || "No models returned", - ); - setModelOptions([ - ...state.modelOptions, - ...result.models.map((model) => `${providerId}/${model}`), - ]); - } else { - updateProviderCard(providerId, "offline", result.error_type, result.error_type); - } - } finally { - button.disabled = false; - button.textContent = original; - } -} +// --------------------------------------------------------------------------- +// Model options +// --------------------------------------------------------------------------- async function hydrateModelOptions() { try { @@ -790,7 +1005,8 @@ async function loadModelOptions(refresh = false) { async function refreshModelOptions(button) { const original = button.textContent; button.disabled = true; - button.textContent = "Refreshing"; + button.setAttribute("aria-busy", "true"); + button.textContent = "Refreshing..."; try { const result = await loadModelOptions(true); const failedProviders = result.failed_providers || []; @@ -807,6 +1023,7 @@ async function refreshModelOptions(button) { showMessage(`Could not refresh models: ${error.message}`, "error"); } finally { button.disabled = false; + button.removeAttribute("aria-busy"); button.textContent = original; } } @@ -820,7 +1037,7 @@ function providerDisplayName(providerId) { function setModelOptions(models) { state.modelOptions = Array.from( - new Set(models.filter((model) => typeof model === "string" && model.trim())), + new Set((models || []).filter((model) => typeof model === "string" && model.trim())), ).sort((left, right) => left.localeCompare(right)); state.modelComboboxes.forEach((combobox) => { if (combobox.isOpen) combobox.render(combobox.query); @@ -833,137 +1050,175 @@ function showMessage(message, kind = "") { area.className = `message-area ${kind}`.trim(); } -byId("validateButton").addEventListener("click", () => validate(true)); -byId("applyButton").addEventListener("click", apply); -document.addEventListener("pointerdown", (event) => { - state.modelComboboxes.forEach((combobox) => { - if (combobox.isOpen && !combobox.element.contains(event.target)) combobox.close(); - }); -}); +// --------------------------------------------------------------------------- +// Logs +// --------------------------------------------------------------------------- + +const LOG_SKIP_KEYS = new Set(["time", "level", "message", "module", "function", "line"]); + +const logs = { + intervalId: null, + entries: [], + levelFilter: "ALL", + query: "", + // Last entry visible when "Clear View" was pressed. The server returns a sliding + // window of recent lines, so clearing must be anchored to an entry, not an index. + clearMarker: null, + renderedHtml: null, + requestSeq: 0, +}; -let logsIntervalId = null; -let currentLogLevelFilter = "ALL"; -let currentLogSearchQuery = ""; -let clearedLogsCount = 0; -let lastLogsLength = 0; +const logEntryKey = (entry) => JSON.stringify(entry); async function loadLogs() { - const container = byId("logsContainer"); - if (!container) return; + const seq = ++logs.requestSeq; try { const data = await api("/admin/api/logs"); - if (!data.logs) { - container.innerHTML = `No logs available.`; - return; - } + // Ignore responses that were overtaken by a newer request. + if (seq !== logs.requestSeq) return; + logs.entries = Array.isArray(data.logs) ? data.logs : []; + renderLogs(); + } catch (error) { + if (seq !== logs.requestSeq) return; + showLogsNotice(`Error loading logs: ${error.message}`, true); + } +} - lastLogsLength = data.logs.length; - if (clearedLogsCount > lastLogsLength) { - clearedLogsCount = 0; - } +function visibleLogEntries() { + let entries = logs.entries; + if (logs.clearMarker !== null) { + const markerIndex = entries.map(logEntryKey).lastIndexOf(logs.clearMarker); + // When the marker has scrolled out of the server window, every entry is newer. + if (markerIndex >= 0) entries = entries.slice(markerIndex + 1); + } - let logsToRender = data.logs; - if (clearedLogsCount > 0) { - logsToRender = logsToRender.slice(clearedLogsCount); - } + if (logs.levelFilter !== "ALL") { + entries = entries.filter( + (log) => String(log.level || "INFO").toUpperCase() === logs.levelFilter, + ); + } - if (currentLogLevelFilter !== "ALL") { - logsToRender = logsToRender.filter(log => (log.level || "INFO").toUpperCase() === currentLogLevelFilter); - } + const query = logs.query.trim().toLowerCase(); + if (query) { + entries = entries.filter((log) => + [log.message, log.level, log.module].some((value) => + String(value || "").toLowerCase().includes(query), + ), + ); + } + return entries; +} - if (currentLogSearchQuery) { - const q = currentLogSearchQuery.toLowerCase(); - logsToRender = logsToRender.filter(log => { - const msg = (log.message || "").toLowerCase(); - const level = (log.level || "").toLowerCase(); - const module = (log.module || "").toLowerCase(); - return msg.includes(q) || level.includes(q) || module.includes(q); - }); - } +function formatLogTime(time) { + const text = String(time || ""); + return text.match(/\d{2}:\d{2}:\d{2}/)?.[0] || text; +} - if (logsToRender.length === 0) { - container.innerHTML = `No matching logs found.`; - return; - } +function logRowHtml(log) { + const level = String(log.level || "INFO").toUpperCase(); + const levelClass = level.toLowerCase().replace(/[^a-z]/g, ""); + const extras = Object.entries(log) + .filter(([key, value]) => !LOG_SKIP_KEYS.has(key) && value !== null && value !== undefined) + .map(([key, value]) => `${key}=${typeof value === "object" ? JSON.stringify(value) : value}`); + const extra = extras.length + ? `[${escapeHtml(extras.join(" "))}]` + : ""; + return ( + `
` + + `${escapeHtml(formatLogTime(log.time))}` + + `${escapeHtml(level)}` + + `${escapeHtml(log.message || "")}${extra}` + + `
` + ); +} - const htmlLines = logsToRender.map((log) => { - let time = log.time || ""; - if (time) { - const tMatch = time.match(/\d{2}:\d{2}:\d{2}/); - if (tMatch) time = tMatch[0]; - } - const level = (log.level || "INFO").toUpperCase(); - let lvlColor = "var(--neutral)"; - if (level === "ERROR") lvlColor = "var(--error)"; - else if (level === "WARNING") lvlColor = "var(--warn)"; - else if (level === "SUCCESS") lvlColor = "var(--ok)"; - else if (level === "INFO") lvlColor = "var(--info)"; - - let message = log.message || ""; - const extraFields = []; - const skipKeys = ["time", "level", "message", "module", "function", "line"]; - Object.keys(log).forEach((k) => { - if (!skipKeys.includes(k) && log[k] !== null && log[k] !== undefined) { - extraFields.push(`${k}=${log[k]}`); - } - }); - const extraStr = extraFields.length > 0 ? ` [${extraFields.join(" ")}]` : ""; +function renderLogs() { + const container = byId("logsContainer"); + const entries = visibleLogEntries(); + updateLogsFooter(entries.length); + + if (entries.length === 0) { + const filtered = logs.query.trim() || logs.levelFilter !== "ALL"; + showLogsNotice( + logs.entries.length === 0 + ? "No logs available." + : filtered + ? "No matching logs found." + : "View cleared. New log entries will appear here.", + ); + return; + } - return `
[${time}]${level}${message}${extraStr}
`; - }); + const html = entries.map(logRowHtml).join(""); + // Skip identical re-renders so polling does not reset text selection or scroll. + if (html === logs.renderedHtml) return; + const previousScrollTop = container.scrollTop; + container.innerHTML = html; + logs.renderedHtml = html; - container.innerHTML = htmlLines.join(""); - - const autoScroll = byId("autoScrollLogs"); - if (autoScroll && autoScroll.checked) { - container.scrollTop = container.scrollHeight; - } - } catch (err) { - container.innerHTML = `Error loading logs: ${err.message}`; + const autoScroll = byId("autoScrollLogs"); + container.scrollTop = autoScroll && autoScroll.checked ? container.scrollHeight : previousScrollTop; +} + +function showLogsNotice(message, isError = false) { + const notice = document.createElement("div"); + notice.className = `logs-notice${isError ? " error" : ""}`; + notice.textContent = message; + byId("logsContainer").replaceChildren(notice); + logs.renderedHtml = null; + if (isError) updateLogsFooter(null); +} + +function updateLogsFooter(visibleCount) { + const footer = byId("logsFooter"); + if (visibleCount === null) { + footer.textContent = ""; + return; } + const total = logs.entries.length; + footer.textContent = `Showing ${visibleCount} of ${total} recent entr${total === 1 ? "y" : "ies"}`; +} + +function setLogsLive(live) { + const indicator = byId("logsLiveIndicator"); + indicator.classList.toggle("is-live", live); + indicator.querySelector(".live-text").textContent = live ? "Live" : "Paused"; } function startLogsInterval() { - if (logsIntervalId) return; - logsIntervalId = setInterval(loadLogs, 3000); + if (logs.intervalId || document.hidden) return; + logs.intervalId = setInterval(loadLogs, LOGS_POLL_MS); + setLogsLive(true); } function stopLogsInterval() { - if (logsIntervalId) { - clearInterval(logsIntervalId); - logsIntervalId = null; + if (logs.intervalId) { + clearInterval(logs.intervalId); + logs.intervalId = null; } + setLogsLive(false); } -// Bind log viewer controls -byId("refreshLogsButton")?.addEventListener("click", loadLogs); -byId("logSearchInput")?.addEventListener("input", (e) => { - currentLogSearchQuery = e.target.value; - loadLogs(); -}); -byId("clearLogsBtn")?.addEventListener("click", () => { - clearedLogsCount = lastLogsLength; - loadLogs(); -}); -document.querySelectorAll(".log-level-btn").forEach(btn => { - btn.addEventListener("click", () => { - document.querySelectorAll(".log-level-btn").forEach(b => { - b.classList.remove("active"); - b.style.backgroundColor = "var(--input)"; - b.style.color = "var(--text)"; - }); - btn.classList.add("active"); - btn.style.backgroundColor = "var(--accent)"; - btn.style.color = "white"; - currentLogLevelFilter = btn.dataset.level; - loadLogs(); - }); -}); +// --------------------------------------------------------------------------- +// Provider icons & fields +// --------------------------------------------------------------------------- let currentProviderId = null; +let modalReturnFocus = null; +let backdropPointerDown = false; function getProviderIcon(providerId, displayName) { const iconsData = { + "anthropic_api": { + "path": "M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z", + "color": "#D97757", + "bg": "rgba(217, 119, 87, 0.15)" + }, + "openai_api": { + "path": "M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z", + "color": "#FFFFFF", + "bg": "rgba(255, 255, 255, 0.15)" + }, "nvidia_nim": { "path": "M8.948 8.798v-1.43a6.7 6.7 0 0 1 .424-.018c3.922-.124 6.493 3.374 6.493 3.374s-2.774 3.851-5.75 3.851c-.398 0-.787-.062-1.158-.185v-4.346c1.528.185 1.837.857 2.747 2.385l2.04-1.714s-1.492-1.952-4-1.952a6.016 6.016 0 0 0-.796.035m0-4.735v2.138l.424-.027c5.45-.185 9.01 4.47 9.01 4.47s-4.08 4.964-8.33 4.964c-.37 0-.733-.035-1.095-.097v1.325c.3.035.61.062.91.062 3.957 0 6.82-2.023 9.593-4.408.459.371 2.34 1.263 2.73 1.652-2.633 2.208-8.772 3.984-12.253 3.984-.335 0-.653-.018-.971-.053v1.864H24V4.063zm0 10.326v1.131c-3.657-.654-4.673-4.46-4.673-4.46s1.758-1.944 4.673-2.262v1.237H8.94c-1.528-.186-2.73 1.245-2.73 1.245s.68 2.412 2.739 3.11M2.456 10.9s2.164-3.197 6.5-3.533V6.201C4.153 6.59 0 10.653 0 10.653s2.35 6.802 8.948 7.42v-1.237c-4.84-.6-6.492-5.936-6.492-5.936z", "color": "#76B900", @@ -1113,224 +1368,447 @@ function getProviderIcon(providerId, displayName) { "bg": "rgba(4, 103, 223, 0.15)" } }; - const p = iconsData[providerId]; - if (p) { - const isLight = document.documentElement.getAttribute("data-theme") === "light"; - let color = p.color; - let bg = p.bg; - if (color === "#FFFFFF") { - color = isLight ? "#0f172a" : "#FFFFFF"; - bg = isLight ? "rgba(15, 23, 42, 0.08)" : "rgba(255, 255, 255, 0.15)"; - } else if (p.stroke && isLight && color === "#00F0FF") { - color = "#0284c7"; - bg = "rgba(2, 132, 199, 0.12)"; - } - const border = isLight ? "1px solid rgba(0,0,0,0.08)" : "1px solid rgba(255,255,255,0.08)"; - const svgInner = p.stroke - ? `` - : ``; - return `
${svgInner}
`; + const icon = iconsData[providerId]; + const avatar = document.createElement("div"); + avatar.className = "provider-avatar"; + avatar.setAttribute("aria-hidden", "true"); + + if (!icon) { + avatar.classList.add("is-initials"); + avatar.textContent = (displayName || providerId) + .split(/[\s_-]+/) + .filter(Boolean) + .map((word) => word[0]) + .join("") + .substring(0, 2) + .toUpperCase(); + return avatar; + } + + // Colors flow through CSS custom properties so theme switches restyle icons + // without re-rendering cards (which used to discard live status updates). + if (icon.color.toUpperCase() === "#FFFFFF") { + avatar.classList.add("is-mono"); + } else { + avatar.style.setProperty("--brand", icon.color); + avatar.style.setProperty("--brand-bg", icon.bg); + } + + const svg = document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("width", "20"); + svg.setAttribute("height", "20"); + const path = document.createElementNS(SVG_NS, "path"); + path.setAttribute("d", icon.path); + if (icon.stroke) { + path.setAttribute("fill", "none"); + path.setAttribute("stroke", "currentColor"); + path.setAttribute("stroke-width", "2"); + path.setAttribute("stroke-linecap", "round"); + path.setAttribute("stroke-linejoin", "round"); + } else { + path.setAttribute("fill", "currentColor"); } - const initials = (displayName || providerId).split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase(); - return `
${initials}
`; + svg.appendChild(path); + avatar.appendChild(svg); + return avatar; } +// Explicit env-key ownership per provider. Providers listed here never fall +// through to the generic prefix/attribute heuristic below, which could otherwise +// capture unrelated fields (e.g. "openai" matching other settings attributes, or +// "anthropic" matching ANTHROPIC_AUTH_TOKEN, the proxy's own server token). +const PROVIDER_FIELD_MATCHERS = { + anthropic_api: (key) => key === "ANTHROPIC_API_KEY" || key === "ANTHROPIC_PROXY", + openai_api: (key) => key === "OPENAI_API_KEY" || key === "OPENAI_PROXY", + nvidia_nim: (key) => key.startsWith("NVIDIA_NIM_"), + open_router: (key) => key.startsWith("OPENROUTER_"), + gemini: (key) => key.startsWith("GEMINI_"), + vertex: (key) => key.startsWith("VERTEX_"), + deepseek: (key) => key.startsWith("DEEPSEEK_"), + mistral: (key) => key.startsWith("MISTRAL_") && !key.startsWith("MISTRAL_CODESTRAL_"), + mistral_codestral: (key) => key.startsWith("CODESTRAL_") || key.startsWith("MISTRAL_CODESTRAL_"), + opencode: (key) => key === "OPENCODE_API_KEY" || key.startsWith("OPENCODE_PROXY"), + opencode_go: (key) => key === "OPENCODE_API_KEY" || key.startsWith("OPENCODE_GO_PROXY"), + vercel: (key) => key.startsWith("AI_GATEWAY_") || key.startsWith("VERCEL_"), + bedrock: (key) => key.startsWith("BEDROCK_") || key === "AWS_BEARER_TOKEN_BEDROCK", + huggingface: (key) => key.startsWith("HUGGINGFACE_"), + cohere: (key) => key.startsWith("COHERE_"), + github_models: (key) => key.startsWith("GITHUB_MODELS_"), + wafer: (key) => key.startsWith("WAFER_"), + kimi: (key) => key.startsWith("KIMI_") && !key.startsWith("KIMI_CODE_"), + kimi_code: (key) => key.startsWith("KIMI_CODE_"), + minimax: (key) => key.startsWith("MINIMAX_"), + cerebras: (key) => key.startsWith("CEREBRAS_"), + groq: (key) => key.startsWith("GROQ_"), + sambanova: (key) => key.startsWith("SAMBANOVA_"), + fireworks: (key) => key.startsWith("FIREWORKS_"), + cloudflare: (key) => key.startsWith("CLOUDFLARE_"), + zai: (key) => key.startsWith("ZAI_"), + ollama_cloud: (key) => key === "OLLAMA_API_KEY" || key.startsWith("OLLAMA_CLOUD_"), + tokenrouter: (key) => key.startsWith("TOKENROUTER_"), + ollama: (key) => key.startsWith("OLLAMA_") && key !== "OLLAMA_API_KEY", + lmstudio: (key) => key.startsWith("LMSTUDIO_") || key.startsWith("LM_STUDIO_"), + llamacpp: (key) => key.startsWith("LLAMACPP_") || key.startsWith("LLAMA_CPP_"), +}; + function getProviderFields(providerId) { - const cleanId = providerId.toLowerCase().replace(/[^a-z0-9]/g, '_'); + const cleanId = providerId.toLowerCase().replace(/[^a-z0-9]/g, "_"); const screamingId = cleanId.toUpperCase(); - - return Array.from(state.fields.values()).filter(field => { + const explicitMatcher = Object.prototype.hasOwnProperty.call(PROVIDER_FIELD_MATCHERS, cleanId) + ? PROVIDER_FIELD_MATCHERS[cleanId] + : null; + + return Array.from(state.fields.values()).filter((field) => { + if (field.section !== "providers") return false; const key = field.key.toUpperCase(); - const attr = (field.settings_attr || "").toLowerCase(); - - if (cleanId === 'nvidia_nim') { - return key.startsWith('NVIDIA_NIM_'); - } - if (cleanId === 'open_router') { - return key.startsWith('OPENROUTER_'); - } - if (cleanId === 'gemini') { - return key.startsWith('GEMINI_'); - } - if (cleanId === 'vertex') { - return key.startsWith('VERTEX_'); - } - if (cleanId === 'deepseek') { - return key.startsWith('DEEPSEEK_'); - } - if (cleanId === 'mistral') { - return key.startsWith('MISTRAL_') && !key.startsWith('MISTRAL_CODESTRAL_'); - } - if (cleanId === 'mistral_codestral') { - return key.startsWith('CODESTRAL_') || key.startsWith('MISTRAL_CODESTRAL_'); - } - if (cleanId === 'opencode') { - return key === 'OPENCODE_API_KEY' || key.startsWith('OPENCODE_PROXY'); - } - if (cleanId === 'opencode_go') { - return key === 'OPENCODE_API_KEY' || key.startsWith('OPENCODE_GO_PROXY'); - } - if (cleanId === 'vercel') { - return key.startsWith('AI_GATEWAY_') || key.startsWith('VERCEL_'); - } - if (cleanId === 'bedrock') { - return key.startsWith('BEDROCK_') || key === 'AWS_BEARER_TOKEN_BEDROCK'; - } - if (cleanId === 'huggingface') { - return key.startsWith('HUGGINGFACE_'); - } - if (cleanId === 'cohere') { - return key.startsWith('COHERE_'); - } - if (cleanId === 'github_models') { - return key.startsWith('GITHUB_MODELS_'); - } - if (cleanId === 'wafer') { - return key.startsWith('WAFER_'); + if (explicitMatcher) { + return explicitMatcher(key); } - if (cleanId === 'kimi') { - return key.startsWith('KIMI_') && !key.startsWith('KIMI_CODE_'); - } - if (cleanId === 'kimi_code') { - return key.startsWith('KIMI_CODE_'); - } - if (cleanId === 'minimax') { - return key.startsWith('MINIMAX_'); - } - if (cleanId === 'cerebras') { - return key.startsWith('CEREBRAS_'); - } - if (cleanId === 'groq') { - return key.startsWith('GROQ_'); - } - if (cleanId === 'sambanova') { - return key.startsWith('SAMBANOVA_'); - } - if (cleanId === 'fireworks') { - return key.startsWith('FIREWORKS_'); - } - if (cleanId === 'cloudflare') { - return key.startsWith('CLOUDFLARE_'); - } - if (cleanId === 'zai') { - return key.startsWith('ZAI_'); - } - if (cleanId === 'ollama_cloud') { - return key === 'OLLAMA_API_KEY' || key.startsWith('OLLAMA_CLOUD_'); - } - if (cleanId === 'tokenrouter') { - return key.startsWith('TOKENROUTER_'); - } - if (cleanId === 'ollama') { - return key.startsWith('OLLAMA_') && key !== 'OLLAMA_API_KEY'; - } - if (cleanId === 'lmstudio') { - return key.startsWith('LMSTUDIO_') || key.startsWith('LM_STUDIO_'); - } - if (cleanId === 'llamacpp') { - return key.startsWith('LLAMACPP_') || key.startsWith('LLAMA_CPP_'); - } - + const attr = (field.settings_attr || "").toLowerCase(); return key.startsWith(screamingId) || attr.includes(cleanId); }); } -function openProviderModal(providerId) { - currentProviderId = providerId; - const provider = state.config.provider_status.find(p => p.provider_id === providerId); +// --------------------------------------------------------------------------- +// Provider modal +// --------------------------------------------------------------------------- + +const FOCUSABLE_SELECTOR = + 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; +const providerTestsInFlight = new Set(); + +function findProviderStatus(providerId) { + return state.config?.provider_status?.find((p) => p.provider_id === providerId) || null; +} + +function isModalOpen() { + return currentProviderId !== null; +} + +function modalContainer() { + return document.querySelector("#providerModal .modal-container"); +} + +function setModalMessage(message, kind = "") { + const area = byId("modalMessage"); + area.textContent = message; + area.className = `modal-message ${kind}`.trim(); +} + +function syncModalTestButton() { + const button = byId("modalTestBtn"); + const provider = currentProviderId ? findProviderStatus(currentProviderId) : null; + const busy = currentProviderId !== null && providerTestsInFlight.has(currentProviderId); + button.disabled = busy; + if (busy) { + button.setAttribute("aria-busy", "true"); + button.textContent = "Testing..."; + } else { + button.removeAttribute("aria-busy"); + button.textContent = provider?.kind === "local" ? "Test" : "Refresh models"; + } +} + +function renderModalMeta(providerId, provider) { + const meta = byId("modalProviderMeta"); + meta.replaceChildren(); + const card = findProviderCard(providerId); + const pill = card?.querySelector(".status-pill"); + if (pill?.textContent) { + meta.appendChild(pill.cloneNode(true)); + } + const kindTag = document.createElement("span"); + kindTag.className = "kind-tag"; + kindTag.textContent = provider.kind === "local" ? "Local" : "Cloud"; + meta.appendChild(kindTag); +} + +function setModalAdvanced(showing) { + const fieldsContainer = byId("modalProviderFields"); + const toggle = byId("modalAdvancedToggle"); + fieldsContainer.classList.toggle("show-advanced", showing); + toggle.textContent = showing ? "Hide advanced" : "Show advanced"; + toggle.setAttribute("aria-expanded", String(showing)); +} + +function openProviderModal(providerId, returnFocusTo = null) { + const provider = findProviderStatus(providerId); if (!provider) return; + if (isModalOpen()) { + closeProviderModal({ restoreFocus: false }); + } - const modal = byId("providerModal"); - byId("modalProviderTitle").textContent = provider.display_name || providerId; - byId("modalProviderIcon").innerHTML = getProviderIcon(providerId, provider.display_name); + currentProviderId = providerId; + modalReturnFocus = returnFocusTo || document.activeElement; + const name = provider.display_name || providerId; + + byId("modalProviderTitle").textContent = name; + byId("modalProviderIcon").replaceChildren(getProviderIcon(providerId, provider.display_name)); + renderModalMeta(providerId, provider); const pFields = getProviderFields(providerId); - const credField = pFields.find(f => f.key.includes("API_KEY") || f.key.includes("TOKEN") || f.key.includes("SECRET") || f.key.includes("PROJECT_ID")); - const desc = credField ? credField.description : `Configure settings and endpoints for ${provider.display_name}.`; - byId("modalProviderDesc").innerHTML = desc || `Configure settings and endpoints for ${provider.display_name}.`; + const credField = pFields.find( + (f) => + f.key.includes("API_KEY") || + f.key.includes("TOKEN") || + f.key.includes("SECRET") || + f.key.includes("PROJECT_ID"), + ); + renderRichText( + byId("modalProviderDesc"), + credField?.description || `Configure settings and endpoints for ${name}.`, + ); const fieldsContainer = byId("modalProviderFields"); - fieldsContainer.innerHTML = ""; - - pFields.forEach(field => { - const fieldEl = document.querySelector(`#hiddenFieldsContainer .field[data-key="${field.key}"]`); + fieldsContainer.replaceChildren(); + pFields.forEach((field) => { + const fieldEl = document.querySelector( + `#hiddenFieldsContainer .field[data-key="${CSS.escape(field.key)}"]`, + ); if (fieldEl) { fieldsContainer.appendChild(fieldEl); } }); - const testBtn = byId("modalTestBtn"); - testBtn.textContent = "Test Provider"; - const newTestBtn = testBtn.cloneNode(true); - testBtn.parentNode.replaceChild(newTestBtn, testBtn); - newTestBtn.addEventListener("click", () => { - testProviderInModal(providerId, newTestBtn); - }); + const advancedToggle = byId("modalAdvancedToggle"); + advancedToggle.hidden = !fieldsContainer.querySelector(".advanced-field"); + setModalAdvanced(false); + setModalMessage( + fieldsContainer.children.length ? "" : `${name} has no editable settings here.`, + ); + syncModalTestButton(); + + byId("providerModal").classList.add("active"); + document.querySelector(".app-shell").inert = true; + document.body.classList.add("modal-open"); - modal.classList.add("active"); + const firstInput = fieldsContainer.querySelector( + "input:not([disabled]), select:not([disabled]), textarea:not([disabled])", + ); + (firstInput || byId("closeModalBtn")).focus({ preventScroll: true }); } -function closeProviderModal() { +function closeProviderModal({ restoreFocus = true } = {}) { + if (!isModalOpen()) return; const fieldsContainer = byId("modalProviderFields"); const hiddenContainer = byId("hiddenFieldsContainer"); - - const fields = Array.from(fieldsContainer.children); - fields.forEach(fieldEl => { + + state.modelComboboxes.forEach((combobox) => combobox.close()); + Array.from(fieldsContainer.children).forEach((fieldEl) => { hiddenContainer.appendChild(fieldEl); }); byId("providerModal").classList.remove("active"); + document.querySelector(".app-shell").inert = false; + document.body.classList.remove("modal-open"); currentProviderId = null; + setModalMessage(""); + + const returnTo = modalReturnFocus; + modalReturnFocus = null; + if (restoreFocus && returnTo?.isConnected) { + returnTo.focus({ preventScroll: true }); + } } -async function testProviderInModal(providerId, button) { - const original = button.textContent; - button.disabled = true; - button.textContent = "Testing..."; +function trapModalFocus(event) { + const container = modalContainer(); + const focusables = Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR)).filter( + (el) => el.getClientRects().length > 0, + ); + if (focusables.length === 0) { + event.preventDefault(); + container.focus(); + return; + } + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + const active = document.activeElement; + if (event.shiftKey && (active === first || !container.contains(active))) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && (active === last || !container.contains(active))) { + event.preventDefault(); + first.focus(); + } +} + +async function testProviderInModal(providerId) { + const name = providerDisplayName(providerId); + providerTestsInFlight.add(providerId); + syncModalTestButton(); + setModalMessage(""); + let message = ""; + let kind = ""; try { - const result = await api(`/admin/api/providers/${providerId}/test`, { + const result = await api(`/admin/api/providers/${encodeURIComponent(providerId)}/test`, { method: "POST", body: "{}", }); if (result.ok) { + const models = result.models || []; updateProviderCard( providerId, "reachable", - `${result.models.length} models`, - result.models.slice(0, 3).join(", ") || "No models returned", + `${models.length} models`, + models.slice(0, 3).join(", ") || "No models returned", ); - showMessage(`Success: Connected to ${providerId}. Found ${result.models.length} models.`, "ok"); - await loadModels(); + message = `Success: Connected to ${name}. Found ${models.length} models.`; + kind = "ok"; + await loadModelOptions(true); } else { updateProviderCard(providerId, "offline", result.error_type, result.error_type); - showMessage(`Connection failed: ${result.error_type}`, "error"); + message = `Connection failed: ${result.error_type || "unknown error"}`; + kind = "error"; } } catch (err) { - showMessage(`Error: ${err.message}`, "error"); + message = `Error: ${err.message}`; + kind = "error"; } finally { - button.disabled = false; - button.textContent = original; + providerTestsInFlight.delete(providerId); + } + + showMessage(message, kind); + // The user may have closed the modal or opened another provider meanwhile. + if (currentProviderId === providerId) { + setModalMessage(message, kind); + renderModalMeta(providerId, findProviderStatus(providerId)); + syncModalTestButton(); } } -// Bind modal controls -byId("closeModalBtn")?.addEventListener("click", closeProviderModal); -byId("modalCancelBtn")?.addEventListener("click", closeProviderModal); -byId("modalSaveBtn")?.addEventListener("click", async () => { - closeProviderModal(); - await apply(); -}); -byId("providerModal")?.addEventListener("click", (e) => { - if (e.target === byId("providerModal")) { +async function saveProviderModal() { + if (state.busy || state.restarting) return; + await runAction(async () => { + try { + const check = await validate(false); + if (!check.valid) { + setModalMessage(validationErrorText(check), "error"); + return; + } + } catch (error) { + setModalMessage(`Could not validate: ${error.message}`, "error"); + return; + } + // Fields must return to the hidden container before apply() reloads and + // re-renders them; otherwise stale nodes would be duplicated on close. closeProviderModal(); + await apply(); + }); +} + +// --------------------------------------------------------------------------- +// Event bindings +// --------------------------------------------------------------------------- + +byId("validateButton").addEventListener("click", () => runAction(() => validate(true))); +byId("applyButton").addEventListener("click", () => runAction(apply)); + +document.addEventListener("pointerdown", (event) => { + state.modelComboboxes.forEach((combobox) => { + if (combobox.isOpen && !combobox.element.contains(event.target)) combobox.close(); + }); +}); + +byId("providerSearch").addEventListener("input", (event) => { + state.providerFilter.query = event.target.value; + applyProviderFilter(); +}); +byId("providerConfiguredOnly").addEventListener("change", (event) => { + state.providerFilter.configuredOnly = event.target.checked; + applyProviderFilter(); +}); + +byId("refreshLogsButton").addEventListener("click", () => loadLogs()); +byId("logSearchInput").addEventListener("input", (event) => { + logs.query = event.target.value; + renderLogs(); +}); +byId("clearLogsBtn").addEventListener("click", () => { + const last = logs.entries[logs.entries.length - 1]; + logs.clearMarker = last === undefined ? null : logEntryKey(last); + renderLogs(); +}); +byId("autoScrollLogs").addEventListener("change", (event) => { + if (event.target.checked) { + const container = byId("logsContainer"); + container.scrollTop = container.scrollHeight; + } +}); +document.querySelectorAll(".log-level-btn").forEach((btn) => { + btn.addEventListener("click", () => { + document.querySelectorAll(".log-level-btn").forEach((other) => { + const selected = other === btn; + other.classList.toggle("active", selected); + other.setAttribute("aria-pressed", String(selected)); + }); + logs.levelFilter = btn.dataset.level; + renderLogs(); + }); +}); + +// Pause log polling while the tab is hidden; resume when it becomes visible. +document.addEventListener("visibilitychange", () => { + if (state.activeView !== "logs") return; + if (document.hidden) { + stopLogsInterval(); + } else { + loadLogs(); + startLogsInterval(); } }); -document.addEventListener("keydown", (e) => { - if (e.key === "Escape" && byId("providerModal") && byId("providerModal").classList.contains("active")) { + +byId("modalTestBtn").addEventListener("click", () => { + if (currentProviderId !== null) testProviderInModal(currentProviderId); +}); +byId("closeModalBtn").addEventListener("click", () => closeProviderModal()); +byId("modalCancelBtn").addEventListener("click", () => closeProviderModal()); +byId("modalSaveBtn").addEventListener("click", saveProviderModal); +byId("modalAdvancedToggle").addEventListener("click", () => { + setModalAdvanced(!byId("modalProviderFields").classList.contains("show-advanced")); +}); + +// Only close on a click that both starts and ends on the backdrop, so a text +// selection drag that ends outside the dialog does not discard the modal. +byId("providerModal").addEventListener("pointerdown", (event) => { + backdropPointerDown = event.target === event.currentTarget; +}); +byId("providerModal").addEventListener("click", (event) => { + if (backdropPointerDown && event.target === event.currentTarget) { closeProviderModal(); } + backdropPointerDown = false; +}); + +document.addEventListener("keydown", (event) => { + if (isModalOpen()) { + // Comboboxes call preventDefault() when Escape closes their listbox. + if (event.key === "Escape" && !event.defaultPrevented) { + event.preventDefault(); + closeProviderModal(); + } else if (event.key === "Tab") { + trapModalFocus(event); + } + return; + } + + if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey) { + if (event.target.closest?.("input, textarea, select, [contenteditable='true']")) return; + const searchId = + state.activeView === "providers" + ? "providerSearch" + : state.activeView === "logs" + ? "logSearchInput" + : null; + if (searchId) { + event.preventDefault(); + byId(searchId).focus(); + } + } }); +initTheme(); load().catch((error) => { showMessage(error.message, "error"); }); diff --git a/src/codefa/api/admin_static/index.html b/src/codefa/api/admin_static/index.html index fa5beca..095ff64 100755 --- a/src/codefa/api/admin_static/index.html +++ b/src/codefa/api/admin_static/index.html @@ -3,36 +3,59 @@ + codefa Admin +
-
+
-
-

Providers

-
+

Providers

+

-
+
-

Providers

+
+

Providers

+

+
+
+
+ + + + +
+ +
+
+
+ -
Providers