Pokazówka: merge #33 (dostawcy: wklej klucz) na main + #39

Konflikty: stałe kluczy osobistych zostają obok KEY_UNREADABLE przeniesionego przez #33; tabela i formularz dostawcy z #33 z kolumną i wyborem „Czyj klucz” z main.
This commit is contained in:
tobayah
2026-11-17 21:17:17 +01:00
15 changed files with 1173 additions and 168 deletions
+1
View File
@@ -25,6 +25,7 @@ gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
|---|---|---|
| [Open Color](https://yeun.github.io/open-color/) | MIT | the colour palette, light and dark |
| [Tabler Icons](https://tabler.io/icons) | MIT | outline icon set — path data is **vendored** into `frontend/app.js`'s `ICN` map, never loaded from a CDN, because the console's CSP allows no third-party origins |
| [Simple Icons](https://simpleicons.org) | CC0-1.0 | brand logotypes for model families and providers — path data **vendored** into `frontend/app.js`'s `BRAND` map at commit `e451c581` (no per-icon licence in the set's data): `anthropic`, `google` (Google Gemini), `qwen`, `meta`, `mistral` (Mistral AI), `openrouter`. OpenAI is not in the set, Bielik neither — those keep a monogram. The marks remain their owners' trademarks; they only name the vendor a model comes from |
| [Inter](https://rsms.me/inter/) | SIL OFL 1.1 | the console font, `frontend/ui/v1/InterVariable.woff2` beside its licence (`LICENSE-Inter.txt`), served from this origin |
| [legalwork](https://github.com/eigenweltlabs/legalwork) | MIT | the look: colour, shape, type and motion values read from its code (HEAD `8255eba9`) into `frontend/ui/v1/tokens.css`; no legalwork code is included |
+144 -2
View File
@@ -24,10 +24,14 @@ with no chat type in `/api/v0` is left alone.
from __future__ import annotations
import asyncio
import json
import re
from collections.abc import AsyncIterator
import httpx
from app.errors import ValidationError
#: Loading an 11B model from disk took about a minute on the reference machine.
LOAD_TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=30.0, pool=10.0)
LIST_TIMEOUT = httpx.Timeout(5.0)
@@ -123,11 +127,149 @@ async def stream_chat(root: str, key: str | None, model: str, messages: list[dic
body = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True, **extra}
async with httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
try:
# Identity: the raw bytes pass through to the browser with no Content-Encoding of ours, and a
# cloud API gzips by default (api.anthropic.com did, 2026-11-06) — the chat read garbage.
async with client.stream("POST", f"{root}/v1/chat/completions",
headers=_headers(key), json=body) as resp:
headers={**_headers(key), "Accept-Encoding": "identity"},
json=body) as resp:
if resp.status_code != 200:
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}.")
# The server's own reason (OpenAI-shaped `error.message`), capped: a bare "HTTP 400"
# left a refused parameter invisible. The key travels in a header, never echoed here.
raw = b""
async for chunk in resp.aiter_raw():
raw += chunk
if len(raw) > 4096:
break
try:
why = json.loads(raw)["error"]["message"]
except (ValueError, KeyError, TypeError):
why = ""
why = f": {str(why)[:300]}" if why else ""
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}{why}")
async for chunk in resp.aiter_raw():
yield chunk
except httpx.HTTPError as exc:
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
# ── listing what a provider offers (the administrator's "discover" / "refresh") ──────────────────
# An administrator-steered outbound call, SSRF-shaped like the module probe: no redirects, one
# deadline for the whole exchange, and a capped body. The key travels only in a header and never
# appears in an error.
LIST_DEADLINE = 10.0
LIST_MAX_BYTES = 2 * 1024 * 1024
#: Vendors whose address is a cloud API, not somebody's own server: no LM Studio listing to ask.
CLOUD_VENDORS = frozenset({"openai", "openrouter", "anthropic"})
# ponytail: a pattern, not a catalogue of model ids — extend it when a non-chat model leaks through.
NON_CHAT = re.compile(r"embed|tts|whisper|dall-e|image|moderation|audio|transcribe|realtime|rerank", re.I)
def _refusal(code: str, pl: str, en: str) -> ValidationError:
return ValidationError(pl, {"code": code, "en": en})
def _unreachable(why_pl: str, why_en: str) -> ValidationError:
return _refusal("provider_unreachable", f"Serwer modeli nie odpowiada: {why_pl}.",
f"The model server does not answer: {why_en}.")
class _NotFound(Exception):
"""A non-200 answer that is not a refusal of the key — for an optional listing, just absent."""
async def _capped_json(client: httpx.AsyncClient, url: str, headers: dict[str, str]):
# Raw bytes, identity only: a decoded read is a decompression bomb (one gzip chunk → many MB).
async with client.stream("GET", url, headers={**headers, "Accept-Encoding": "identity"}) as resp:
if resp.is_redirect:
raise _unreachable("przekierowanie odrzucone", "redirect refused")
if resp.status_code in (401, 403):
raise _refusal("provider_key_refused", "Serwer modeli odrzucił klucz.",
"The model server refused the key.")
if resp.status_code != 200:
raise _NotFound(resp.status_code)
if resp.headers.get("content-encoding", "identity").lower() != "identity":
raise _unreachable("odpowiedź jest skompresowana", "the answer is compressed")
body = bytearray()
async for chunk in resp.aiter_raw():
body += chunk
if len(body) > LIST_MAX_BYTES:
raise _unreachable("odpowiedź jest za duża", "the answer is too large")
try:
return json.loads(body)
except (ValueError, RecursionError): # 2 MB of `[` nests deeper than the decoder recurses
raise _unreachable("odpowiedź nie jest JSON-em", "the answer is not JSON") from None
def _data(listing) -> list:
"""`listing["data"]` when somebody else's server answered the documented shape; anything else
is a 422, never an AttributeError (a 500) on untrusted input."""
data = listing.get("data") if isinstance(listing, dict) else None
if not isinstance(data, list):
raise _unreachable("nieoczekiwany kształt odpowiedzi", "unexpected answer shape")
return data
async def _openai_models(client: httpx.AsyncClient, base_url: str, key: str | None,
vendor: str | None) -> list[dict]:
root, headers = server_root(base_url), _headers(key)
try:
listing = await _capped_json(client, f"{root}/v1/models", headers)
except _NotFound as exc:
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
models = [{"id": m["id"], "dialect": "openai",
**({"context_window": m["max_model_len"]}
if isinstance(m.get("max_model_len"), int) and m["max_model_len"] > 0 else {})}
for m in _data(listing) if isinstance(m, dict) and isinstance(m.get("id"), str)]
if vendor not in CLOUD_VENDORS:
# LM Studio's own listing says which models chat; `/v1/models` lists embeddings too. Same
# reading as `loaded_models`, but through the capped reader. Not LM Studio → no listing.
# Optional: a server behind a login page answers this path with a 302, HTML or a 401, and
# that says nothing about `/v1/models`, which already answered — any refusal = no listing.
try:
lm_data = _data(await _capped_json(client, f"{root}/api/v0/models", headers))
except (_NotFound, ValidationError):
lm_data = []
types = {m.get("id"): m.get("type") for m in lm_data if isinstance(m, dict)}
models = [m for m in models if types.get(m["id"], "llm") in CHAT_TYPES]
return models
#: https://platform.claude.com/docs/en/api/versioning (latest on 2026-11-06); the listing itself is
#: https://platform.claude.com/docs/en/api/models-list — `lifecycle`, `max_input_tokens`.
ANTHROPIC_VERSION = "2026-10-21"
async def _anthropic_models(client: httpx.AsyncClient, base_url: str, key: str | None) -> list[dict]:
headers = {"anthropic-version": ANTHROPIC_VERSION, **({"x-api-key": key} if key else {})}
# ponytail: one page of 1000 (the maximum), no `after_id` paging — the catalogue is far smaller.
try:
listing = await _capped_json(client, f"{base_url.rstrip('/')}/models?limit=1000", headers)
except _NotFound as exc:
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
# The default listing includes `deprecated` models, closed to new adopters: offer active only.
return [{"id": m["id"], "dialect": "openai",
**({"context_window": m["max_input_tokens"]}
if isinstance(m.get("max_input_tokens"), int) and m["max_input_tokens"] > 0 else {})}
for m in _data(listing)
if isinstance(m, dict) and isinstance(m.get("id"), str) and m.get("lifecycle") == "active"]
async def list_models(base_url: str, key: str | None, vendor: str | None, *,
transport: httpx.AsyncBaseTransport | None = None) -> list[dict]:
"""The chat models a provider offers under this key, as `{id, context_window?, dialect}`.
Refusals are 422 Problem Details with `code` `provider_key_refused` / `provider_unreachable` /
`provider_no_models`. `transport` exists for tests."""
try:
async with httpx.AsyncClient(timeout=LIST_DEADLINE, follow_redirects=False,
transport=transport) as client:
listing = (_anthropic_models(client, base_url, key) if vendor == "anthropic"
else _openai_models(client, base_url, key, vendor))
models = await asyncio.wait_for(listing, LIST_DEADLINE)
except (httpx.HTTPError, TimeoutError) as exc:
raise _unreachable(type(exc).__name__, type(exc).__name__) from None
models = [m for m in models if not NON_CHAT.search(m["id"])]
if not models:
raise _refusal("provider_no_models", "Pod tym kluczem/adresem nie ma żadnego modelu czatu.",
"There is no chat model under this key/address.")
return models
+27 -4
View File
@@ -5,8 +5,8 @@ sent for every module at once, so the platform-wide tier is the only one that ma
module's moderator sees them read-only in that module, and its writes are 409s there).
Never returns a key: a key is write-only, set or replaced through `api_key`, removed with
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Nothing here calls a provider
(`services/providers.py` says why there is no "test connection").
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Only `discover` and `refresh`
call a provider — to list its models — and both end the DB transaction before they do.
"""
from __future__ import annotations
@@ -18,13 +18,19 @@ from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, require_administrator
from ..models import AppUser
from ..schemas import ProviderCreateIn, ProviderPolicyIn, ProviderUpdateIn
from ..schemas import (
ProviderCreateIn,
ProviderDiscoverIn,
ProviderDiscoverOut,
ProviderPolicyIn,
ProviderUpdateIn,
)
from ..services import providers as service
router = APIRouter(prefix="/admin/model-providers", tags=["admin: model providers"])
# The policy routes come before `/{provider_id}`, so "policy" is never parsed as an id.
# The policy and discover routes come before `/{provider_id}`, so neither word is parsed as an id.
@router.get("/policy")
def read_policy(db: Session = Depends(get_db),
_: AppUser = Depends(require_administrator)) -> dict:
@@ -40,6 +46,15 @@ def update_policy(body: ProviderPolicyIn, request: Request, db: Session = Depend
return out
@router.post("/discover", response_model=ProviderDiscoverOut)
async def discover_provider(body: ProviderDiscoverIn, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_administrator)) -> dict:
db.commit() # no transaction held across the outbound call (up to model_server.LIST_DEADLINE)
out = await service.discover(db, admin, body.input, body.key, ip=client_ip(request))
db.commit() # the audit row
return out
@router.get("")
def list_providers(db: Session = Depends(get_db),
_: AppUser = Depends(require_administrator)) -> list[dict]:
@@ -76,3 +91,11 @@ def disable_provider(provider_id: uuid.UUID, request: Request, db: Session = Dep
out = service.disable(db, admin, provider_id, ip=client_ip(request))
db.commit()
return out
@router.post("/{provider_id}/refresh")
async def refresh_provider(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_administrator)) -> dict:
out = await service.refresh(db, admin, provider_id, ip=client_ip(request))
db.commit()
return out
+7 -2
View File
@@ -116,7 +116,7 @@ def prompt_size(body: AskIn) -> int:
ensure_ascii=False))
def _sampling(body: AskIn) -> dict:
def _sampling(body: AskIn, vendor: str | None = None) -> dict:
"""The person's sampling knobs, only those they set; the model's defaults otherwise.
`thinking=False` is `reasoning_effort: "none"`: against LM Studio with qwen/qwen3.5-9b (2026-10-29)
@@ -130,6 +130,11 @@ def _sampling(body: AskIn) -> dict:
exclude_none=True)
if body.thinking is False:
out["reasoning_effort"] = "none"
if vendor == "anthropic":
# Newer Claude models refuse `temperature` outright (400 "deprecated for this model",
# claude-opus-5-5, 2026-11-06); the knobs were tuned for small local models anyway.
for k in ("temperature", "top_p", "top_k"):
out.pop(k, None)
return out
@@ -176,7 +181,7 @@ async def ask(body: AskIn, request: Request, db: Session = Depends(get_db),
messages = [{"role": "system", "content": SYSTEM.format(today=date.today())},
*(m.model_dump(exclude_none=True) for m in body.messages)]
tools = {"tools": body.tools, "tool_choice": body.tool_choice} if body.tools else {}
extra = {**tools, **_sampling(body)}
extra = {**tools, **_sampling(body, providers.vendor_of(target["base_url"]))}
max_tokens = body.max_tokens or MAX_ANSWER_TOKENS
async def events():
+17 -2
View File
@@ -240,7 +240,7 @@ class ProviderUpdateIn(BaseModel):
name: str | None = Field(default=None, max_length=120)
kind: str | None = Field(default=None, max_length=20)
base_url: str | None = Field(default=None, max_length=2000)
models: list[Any] | None = Field(default=None, max_length=100)
models: list[Any] | None = Field(default=None, max_length=1000) # OpenRouter lists hundreds; the 2 MB listing cap bounds the rest
trains_on_data: bool | None = None
api_key: str | None = Field(default=None, max_length=4096, repr=False)
region: str | None = Field(default=None, max_length=8)
@@ -258,7 +258,7 @@ class ProviderCreateIn(BaseModel):
name: str = Field(max_length=120)
kind: str = Field(max_length=20)
base_url: str = Field(max_length=2000)
models: list[Any] = Field(max_length=100)
models: list[Any] = Field(max_length=1000)
trains_on_data: bool
api_key: str | None = Field(default=None, max_length=4096, repr=False)
region: str | None = Field(default=None, max_length=8)
@@ -268,6 +268,21 @@ class ProviderCreateIn(BaseModel):
key_mode: str = Field(default="firm", max_length=20)
class ProviderDiscoverIn(BaseModel):
"""What the administrator pasted: an API key, or a server's address (with its key if it needs one)."""
input: str = Field(min_length=1, max_length=4096, repr=False)
key: str | None = Field(default=None, max_length=4096, repr=False)
class ProviderDiscoverOut(BaseModel):
"""What `discover` recognised. Nothing is stored; the console sends it back through `POST ""`."""
vendor: str | None
name: str
kind: str
base_url: str
models: list[Any]
class ProviderPolicyIn(BaseModel):
"""`None` = leave as it is."""
level: str | None = Field(default=None, max_length=20)
+74 -5
View File
@@ -20,24 +20,29 @@ Three things this file adds, and only these:
* **The shape out.** A key never leaves: not to the administrator, not in a list, not in a diff.
The card says `has_key` and `key_prefix` (core's six-character, non-secret prefix) and nothing else.
**Nothing here calls a provider.** These endpoints store configuration; there is deliberately no
"test connection", because a hub that fetches an administrator-typed URL is an SSRF primitive with
an administrator's reach.
**One thing here calls a provider: `discover`**, which lists the models under a pasted key or address.
It is an administrator-typed outbound request (SSRF by nature), so it is held like the module probe:
administrator only, the address through core's `check_base_url`, the limits in
`integrations/model_server.list_models`, and an audit row naming the host — never the key.
"""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import urlsplit
from dredd_core import model_providers as core
from sqlalchemy.orm import Session as DbSession
from .. import provider_keys
from ..config import get_settings
from ..errors import ConflictError, NotFoundError
from ..errors import ConflictError, NotFoundError, ValidationError
from ..integrations import model_server
from ..models import AppUser, ModelProvider
from . import audit
KEY_SECRET_MISSING = "model_provider_secret_missing"
KEY_UNREADABLE = "model_provider_key_unreadable"
def _secret() -> str:
@@ -126,12 +131,76 @@ def set_policy(db: DbSession, actor: AppUser, *, level: str | None, eu_only: boo
return policy_out(db)
# ── discovering a provider: paste a key or an address, get its models ────────
# Longest prefix first: `sk-` would swallow the other two. The console does not repeat this table.
KEY_PREFIXES: tuple[tuple[str, str, str, str], ...] = (
# prefix, vendor, name, base_url
("sk-ant-", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
("sk-or-", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
("sk-", "openai", "OpenAI", "https://api.openai.com/v1"),
)
def recognise(text: str, key: str | None) -> tuple[str | None, str, str, str, str | None]:
"""`(vendor, name, kind, base_url, key)` for what the administrator pasted. Anything with `://`
is an address and goes through core's `check_base_url` (http(s) only, no credentials, a sane
host); a local host is `kind=local` by core's own `LOCAL_HOSTS`."""
text = (text or "").strip()
if "://" in text:
host = (urlsplit(text).hostname or "").lower() if text.lower().startswith(("http://", "https://")) else ""
kind = "local" if host in core.LOCAL_HOSTS else "api"
base_url = core.check_base_url(text, kind)
# A pasted cloud address is asked the way its vendor answers (Anthropic is not Bearer).
return vendor_of(base_url), host, kind, base_url, (key or "").strip() or None
for prefix, vendor, name, base_url in KEY_PREFIXES:
if text.startswith(prefix):
return vendor, name, "api", base_url, text
raise ValidationError("Nie rozpoznaję tego klucza — wklej adres serwera.",
{"code": "provider_unknown_key",
"en": "I don't recognise this key — paste the server's address."})
async def discover(db: DbSession, actor: AppUser, text: str, key: str | None, *,
ip: str | None) -> dict:
"""The provider a pasted key or address names, with its chat models. Stores no provider; the
audit row (host only) is the caller's to commit. Call it with no transaction open — the
outbound request can take up to `model_server.LIST_DEADLINE`."""
vendor, name, kind, base_url, key = recognise(text, key)
# ponytail: a refused discovery is not audited — the 422 rolls the row back; record it in its
# own transaction if failed attempts need to be answerable.
models = await model_server.list_models(base_url, key, vendor)
audit.record(db, action="model_provider.discover", entity_type="model_provider",
actor_id=actor.id, detail=urlsplit(base_url).hostname, ip=ip)
return {"vendor": vendor, "name": name, "kind": kind, "base_url": base_url, "models": models}
def vendor_of(base_url: str) -> str | None:
"""The vendor whose address this row has (`list_models` asks Anthropic differently)."""
host = urlsplit(base_url).hostname
return next((v for _p, v, _n, url in KEY_PREFIXES if urlsplit(url).hostname == host), None)
async def refresh(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> dict:
"""Re-read a stored provider's models from the provider itself and store them through `update`
(audited like any change). A refused listing — empty included — raises before anything is
written, so the old list stays. Ends the read transaction before the outbound call."""
provider = core.get_or_404(db, provider_id)
base_url, name = provider.base_url, provider.name
key = core.api_key(db, provider, decrypt) if provider.key_prefix is not None else None
if provider.key_prefix is not None and key is None:
raise ConflictError(
f"Klucza API dostawcy {name} nie da się odczytać. Zapisz go ponownie.",
{"code": KEY_UNREADABLE, "en": f"The API key of {name} cannot be read. Store it again."})
db.commit() # nothing written yet: only closes the transaction the outbound call must not hold
models = await model_server.list_models(base_url, key, vendor_of(base_url))
return update(db, actor, provider_id, {"models": models}, ip=ip)
# ── using a provider: Home's "ask the model" ─────────────────────────────────
# Who may use what is core's `_use_filter` (policy, `allowed_for`, `eu_only`); the hub passes the
# platform administrator as `is_admin`. Only `openai`-dialect models: Home speaks chat completions.
CHAT_DIALECT = "openai"
KEY_UNREADABLE = "model_provider_key_unreadable"
USER_KEY_MISSING = "model_provider_user_key_missing"
USER_KEY_UNREADABLE = "model_provider_user_key_unreadable"
@@ -0,0 +1,94 @@
"""Home's model picker: how a model id is shown and which family's mark it wears.
`prettyModel` and `modelFamily` are lifted out of `frontend/app.js` and run under Node, so the
behaviour is asserted, not the source text. DB-free; skipped only where no `node` binary exists.
"""
from __future__ import annotations
import json
import pathlib
import shutil
import subprocess
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
NODE = shutil.which("node")
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
def _fn(head: str) -> str:
i = SRC.index(head)
return SRC[i:SRC.index("\n}\n", i) + 3]
def _run(fn: str, args: list[str]) -> list[str]:
script = _fn(f"function {fn}(") + f"\nconsole.log(JSON.stringify({json.dumps(args)}.map({fn})));"
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_pretty_model_reads_like_a_name() -> None:
assert _run("prettyModel", ["claude-opus-5-5", "qwen/qwen3.5-9b", "claude-sonnet-4-5-20250929"]) == [
"Claude Opus 5.5", "Qwen3.5 9B", "Claude Sonnet 4.5 20250929"]
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_model_family_by_id() -> None:
cases = {
"claude-opus-5-5": "anthropic", "anthropic/claude-haiku-5-5": "anthropic",
"gpt-5": "openai", "o3-mini": "openai", "openai/o4": "openai",
"gemini-2.5-pro": "google", "google/gemma-3-27b": "google",
"qwen/qwen3.5-9b": "qwen", "speakleash/bielik-11b-v2.6": "bielik",
"meta-llama/llama-3.3-70b": "meta", "mistral-large": "mistral", "mixtral-8x7b": "mistral",
"deepseek-r1": "D", "phi-4": "P",
}
assert _run("modelFamily", list(cases)) == list(cases.values())
def test_picker_groups_by_provider_and_escapes() -> None:
body = _fn("function modelOptions(")
assert "<optgroup label=\"${esc(g.provider)}\" data-no-i18n>" in body
assert "${esc(prettyModel(m.id))}" in body and 'title="${esc(m.id)}"' in body
assert "modelLabel" not in SRC
def test_pick_is_remembered_and_the_icon_follows_it() -> None:
change = _fn("function homeModelChange(")
assert "saveModelPick(sel.value)" in change
assert "$('homeModelIcon').innerHTML = familyIcon(sel.value)" in change
assert "savedModelPick()" in SRC and "localStorage.setItem(modelPickKey()" in SRC
assert '<span id="homeModelIcon">${familyIcon(picked)}</span>' in SRC
assert "markSvg(fam, letter)" in _fn("function familyIcon(")
assert "${esc(letter)}" in _fn("function markSvg(")
def test_every_vendored_logotype_is_credited() -> None:
import re
brand = SRC[SRC.index("const BRAND = {"):]
brand = brand[:brand.index("\n};")]
keys = re.findall(r"^ (\w+): '", brand, re.M)
assert keys, "BRAND map is empty"
credits = (ROOT / "CREDITS.md").read_text(encoding="utf-8")
assert "Simple Icons" in credits and "CC0" in credits
for key in keys:
assert f"`{key}`" in credits, key
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_model_two_providers_offer_is_listed_once_under_the_one_that_answers() -> None:
# The server routes an id to the FIRST provider offering it; a second option for the same id
# would show one provider and send the question to another.
start = SRC.index("const esc = ")
esc = SRC[start:SRC.index("}[c]));", start) + len("}[c]));")]
script = "\n".join([esc, _fn("function prettyModel("), _fn("function modelOptions(")]) + (
"\nconsole.log(modelOptions([{id:'qwen3',provider:'Lokalny'},{id:'qwen3',provider:'OpenRouter'},"
"{id:'gpt-5',provider:'OpenRouter'}], 'qwen3', 'Tylko szukaj'));")
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
assert r.returncode == 0, r.stderr
html = r.stdout
assert html.count('value="qwen3"') == 1 and html.count(" selected") == 1
assert html.index('value="qwen3"') < html.index('label="OpenRouter"')
@@ -0,0 +1,183 @@
"""`model_server.list_models` on a mocked transport: what counts as a chat model, the outbound limits
(no redirects, 2 MB), the refusal codes, and that the key never appears in an error."""
from __future__ import annotations
import asyncio
import json
import httpx
import pytest
from app.errors import ValidationError
from app.integrations import model_server
KEY = "sk-secret-value-123"
def _resp(status, json_=None, content=b"", headers=None):
"""A STREAMED response, as the network gives one (`content=` would arrive already read)."""
body = json.dumps(json_).encode() if json_ is not None else content
return httpx.Response(status, headers=headers, stream=httpx.ByteStream(body))
def _run(handler, base="http://gpu.example:8000/v1", key=KEY, vendor=None):
return asyncio.run(model_server.list_models(base, key, vendor, transport=httpx.MockTransport(handler)))
def _refused(handler, code, **kw):
with pytest.raises(ValidationError) as exc:
_run(handler, **kw)
assert exc.value.extra["code"] == code
assert KEY not in exc.value.detail and KEY not in json.dumps(exc.value.extra)
return exc.value
def test_vllm_max_model_len_becomes_the_context_window_and_the_key_is_a_bearer():
seen = []
def handler(req):
seen.append(req)
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen/qwen3.5-9b", "max_model_len": 32768},
{"id": "bielik-11b"}]})
return _resp(404)
assert _run(handler) == [{"id": "qwen/qwen3.5-9b", "dialect": "openai", "context_window": 32768},
{"id": "bielik-11b", "dialect": "openai"}]
assert seen[0].headers["authorization"] == f"Bearer {KEY}"
def test_lm_studio_drops_embeddings_and_keeps_models_not_loaded():
def handler(req):
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen3"}, {"id": "nomic-text-v1"}, {"id": "gemma"}]})
return _resp(200, json_={"data": [
{"id": "qwen3", "type": "llm", "state": "loaded"},
{"id": "nomic-text-v1", "type": "embeddings", "state": "not-loaded"},
{"id": "gemma", "type": "vlm", "state": "not-loaded"}]})
assert [m["id"] for m in _run(handler, base="http://localhost:1234", key=None)] == ["qwen3", "gemma"]
def test_non_chat_ids_are_dropped_by_pattern():
def handler(req):
return _resp(200, json_={"data": [{"id": "gpt-5"}, {"id": "text-embedding-3-large"},
{"id": "whisper-1"}, {"id": "gpt-image-1"}]})
assert [m["id"] for m in _run(handler, vendor="openai")] == ["gpt-5"]
def test_a_redirect_is_refused():
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
"provider_unreachable")
def test_an_answer_over_2_mb_is_cut_and_refused():
big = b'{"data": [' + b" " * (model_server.LIST_MAX_BYTES + 1) + b"]}"
_refused(lambda req: _resp(200, content=big), "provider_unreachable")
def test_401_is_a_refused_key():
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused")
def test_no_answer_is_unreachable():
def handler(req):
raise httpx.ConnectError(f"cannot connect with {KEY}")
_refused(handler, "provider_unreachable")
def test_an_empty_list_after_the_filter_is_no_models():
_refused(lambda req: _resp(200, json_={"data": [{"id": "text-embedding-3-small"}]}),
"provider_no_models", vendor="openai")
def test_a_compressed_answer_is_refused_and_identity_is_asked_for():
seen = []
def handler(req):
seen.append(req.headers["accept-encoding"])
return _resp(200, headers={"Content-Encoding": "gzip"}, content=b"\x1f\x8b")
_refused(handler, "provider_unreachable")
assert seen == ["identity"]
ANTHROPIC = "https://api.anthropic.com/v1"
def _anthropic(handler):
return _run(handler, base=ANTHROPIC, vendor="anthropic")
def test_anthropic_keeps_active_models_and_sends_its_own_headers():
seen = []
def handler(req):
seen.append(req)
return _resp(200, json_={"data": [
{"id": "claude-opus-5-5", "lifecycle": "active", "max_input_tokens": 1000000},
{"id": "claude-old-3", "lifecycle": "deprecated", "max_input_tokens": 200000},
{"id": "claude-haiku-5-5", "lifecycle": "active", "max_input_tokens": 0}]})
assert _anthropic(handler) == [
{"id": "claude-opus-5-5", "dialect": "openai", "context_window": 1000000},
{"id": "claude-haiku-5-5", "dialect": "openai"}]
req, = seen
assert req.url.path == "/v1/models" and req.url.params["limit"] == "1000"
assert req.headers["x-api-key"] == KEY
assert req.headers["anthropic-version"] == model_server.ANTHROPIC_VERSION
assert "authorization" not in req.headers
def test_anthropic_refusals_never_carry_the_key():
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused",
base=ANTHROPIC, vendor="anthropic")
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
"provider_unreachable", base=ANTHROPIC, vendor="anthropic")
_refused(lambda req: _resp(200, json_={"data": [{"id": "claude-old-3", "lifecycle": "deprecated"}]}),
"provider_no_models", base=ANTHROPIC, vendor="anthropic")
def test_a_redirect_is_not_followed_one_request_and_no_second_host():
seen = []
def handler(req):
seen.append(str(req.url))
return _resp(302, headers={"Location": "http://169.254.169.254/latest/meta-data/"})
_refused(handler, "provider_unreachable")
assert len(seen) == 1 and "169.254" not in seen[0]
def test_one_deadline_covers_the_whole_exchange_not_each_read(monkeypatch):
"""A body trickled slower than the deadline in total, but each chunk fast enough for a per-read
timeout, must still end at the deadline."""
import time
class Trickle(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'{"data": ['
for _ in range(50):
await asyncio.sleep(0.05)
yield b" "
yield b"]}"
monkeypatch.setattr(model_server, "LIST_DEADLINE", 0.5)
started = time.monotonic()
_refused(lambda req: httpx.Response(200, stream=Trickle()), "provider_unreachable")
assert time.monotonic() - started < 2
@pytest.mark.parametrize("answer", [
lambda: _resp(302, headers={"Location": "/login"}),
lambda: _resp(200, content=b"<html>login</html>"),
lambda: _resp(401),
], ids=["redirect", "html", "401"])
def test_a_broken_optional_lm_studio_listing_does_not_sink_the_discovery(answer):
def handler(req):
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen3"}]})
return answer()
assert [m["id"] for m in _run(handler, key=None)] == ["qwen3"]
@pytest.mark.parametrize("body", [b"[]", b"null", b'"x"', b'{"data": null}', b'{"data": "x"}',
b"[" * 100_000 + b"]" * 100_000],
ids=["list", "null", "string", "data-null", "data-string", "deep-nesting"])
@pytest.mark.parametrize("vendor", [None, "anthropic"])
def test_an_unexpected_json_shape_is_a_422_not_a_500(body, vendor):
_refused(lambda req: _resp(200, content=body), "provider_unreachable", vendor=vendor)
+42
View File
@@ -349,3 +349,45 @@ def test_there_is_no_door_for_modules_and_no_stored_choice():
paths = {getattr(r, "path", "") for _, r in iter_routes(app.routes)}
assert "/api/v1/models" in paths and "/api/v1/models/ask" in paths
assert not any(p.startswith("/api/v1/gateway") or p == "/api/v1/models/choice" for p in paths)
def test_claude_is_not_sent_the_knobs_it_refuses():
# claude-opus-5-5 answered 400 "`temperature` is deprecated for this model" (2026-11-06).
sent = models._sampling(_ask(temperature=0.2, top_p=0.9, top_k=40, presence_penalty=1.5, thinking=False),
"anthropic")
assert sent == {"presence_penalty": 1.5, "reasoning_effort": "none"}
def test_a_refused_call_says_why(monkeypatch):
import httpx
def handler(req):
body = b'{"error": {"message": "`temperature` is deprecated for this model."}}'
return httpx.Response(400, stream=httpx.ByteStream(body)) # streamed, as the network gives it
real = httpx.AsyncClient
monkeypatch.setattr(model_server.httpx, "AsyncClient",
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
async def run():
async for _ in model_server.stream_chat("http://h", "k", "m", [], 64):
pass
with pytest.raises(model_server.GatewayError, match="temperature"):
asyncio.run(run())
def test_the_answer_is_asked_for_uncompressed(monkeypatch):
# The bytes are passed through raw with no Content-Encoding: a gzipped stream reached the chat
# as garbage (api.anthropic.com, 2026-11-06).
import httpx
seen = []
def handler(req):
seen.append(req.headers.get("accept-encoding"))
return httpx.Response(200, stream=httpx.ByteStream(b"data: [DONE]\n\n"))
real = httpx.AsyncClient
monkeypatch.setattr(model_server.httpx, "AsyncClient",
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
async def run():
return [c async for c in model_server.stream_chat("http://h", "k", "m", [], 64)]
assert asyncio.run(run()) == [b"data: [DONE]\n\n"] and seen == ["identity"]
+72 -13
View File
@@ -1,8 +1,8 @@
"""The model-provider screen in the console (Platforma → Dostawcy modeli). DB-free.
Source-reading, like `test_app_token_console.py`, and honest about what that proves: the screen
exists, calls only routes that exist, never renders or stores a key, offers nothing that fetches a
provider, and is in both languages. That the routes really behave is
exists, calls only routes that exist, never renders or stores a key, never reaches a provider
itself (the model list comes through the hub's `discover`/`refresh`), and is in both languages. That the routes really behave is
`test_providers_integration.py`'s job.
"""
from __future__ import annotations
@@ -66,23 +66,61 @@ def test_the_key_is_write_only_in_the_console_too(screen):
assert "{ clear: ['api_key'] }" in screen
def test_nothing_on_it_reaches_a_provider(screen):
"""These endpoints store configuration; a "test connection" would make the hub fetch an
administrator-typed URL."""
def test_only_the_hub_reaches_a_provider(screen):
"""The list of models is read by the hub, under its outbound limits; the console only asks for
it through `discover`/`refresh` and never opens a connection of its own."""
assert "fetch(" not in screen
assert "XMLHttpRequest" not in screen
# The header comment says why there is none; no control may offer one.
assert "`/admin/model-providers/${enc(id)}/refresh`" in screen
code = re.sub(r"/\*.*?\*/", "", screen, flags=re.S)
assert not re.search(r"test.?connection|probe|połącz", code, re.I)
def test_each_row_offers_refresh_details_and_disable(screen):
rows = screen.split("rows.map((p) =>", 1)[1].split(".join('')", 1)[0]
assert "providerIcon(p)" in rows
assert "(p.models || []).length" in rows
for action in ("refreshProvider(", "openProviderForm(", "disableProvider("):
assert action in rows, action
def test_details_have_no_models_field(screen):
"""A provider's models are its own list (`discover`/`refresh`), never typed."""
form = screen.split("function openProviderForm(", 1)[1].split("\n}\n", 1)[0]
assert "Modele" not in form and "textarea" not in form
edit = screen.split("function readProviderForm(", 1)[1].split("\n}\n", 1)[0]
assert "models" not in edit
def test_adding_goes_through_discover(console, screen):
"""One field; the hub recognises it (`discover`), the console adds what was checked."""
assert 'onclick="openAddProvider()"' in screen
assert "'/admin/model-providers/discover'" in screen
assert "reopen: showDiscovered" in screen
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
assert "mutate('POST', '/admin/model-providers', body)" in add
assert "models: r.models" in add and "kind: r.kind" in add and "base_url: r.base_url" in add
# The second field shows only for an address.
assert 'id="apKeyRow"' in screen and 'id="apKey" type="password"' in screen
# The prefix catalogue is the backend's alone.
assert "sk-ant-" not in console and "sk-or-" not in console
def test_the_pasted_key_is_never_rendered_or_kept(screen):
preview = screen.split("function showDiscovered(", 1)[1].split("\n}\n", 1)[0]
assert "apInput" not in preview and "apKey" not in preview and "key" not in preview.lower()
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
assert "state." not in add.split("const r = state._discovered;", 1)[1]
assert not re.search(r"state[.]\w+\s*=\s*(?:key|input)", screen)
def test_dynamic_values_are_escaped(screen):
# Every interpolation goes through esc()/dat()/enc() or is markup built here.
for expr in re.findall(r"\$\{([^}]*)\}", screen):
if expr.strip().startswith(("esc(", "dat(", "enc(", "svg(", "lbl(", "choice(", "kindChip",
"euChip", "keyCell", "p ?", "p &&", "writable", "rows.map",
"p.is_active", "v.trains_on_data", "v.is_active",
"policy.eu_only", "esc(")):
if expr.strip().startswith(("esc(", "dat(", "enc(", "svg(", "lbl(", "choice(", "providerIcon(", "markSvg(",
"hue", "writable", "rows.map",
"p.is_active", "p.trains_on_data", "p.has_key",
"policy.eu_only", "r.models.map", "esc(")):
continue
pytest.fail(f"unescaped interpolation: ${{{expr}}}")
@@ -92,16 +130,17 @@ def test_the_look_is_marked_as_replaceable(screen):
@pytest.mark.parametrize("phrase", [
"Dostawcy modeli", "Nowy dostawca", "Edytuj dostawcę", "Polityka użycia", "Kto może używać modeli",
"Dostawcy modeli", "Szczegóły", "Polityka użycia", "Kto może używać modeli",
"Tylko dostawcy z UE/EOG (lub lokalni)", "Zapisz politykę", "Brak dostawców modeli.",
"Pozostaw puste, aby zachować obecny klucz", "Usuń klucz", "Wyłącz", "Włącz", "Nikt",
"Tylko administratorzy", "Każdy", "Zgodnie z polityką", "Dostawca trenuje modele na przesłanych danych",
"Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.",
"Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.",
"Jeden model w wierszu: identyfikator | okno kontekstu | dialekt (openai albo chatml).",
"Usunąć zapisany klucz API tego dostawcy?",
"Wyłączyć tego dostawcę? Moduły przestaną go oferować.",
"API (zewnętrzny)", "lokalny", "Podmiot przetwarzający", "Adres umowy powierzenia (DPA)",
"Dodaj dostawcę", "Wklej klucz API albo adres serwera", "Klucz (jeśli serwer go wymaga)", "Sprawdź",
"Dodaj", "Znaleziono modele.", "Odśwież modele", "Odświeżono modele.",
])
def test_it_is_in_both_languages(console, screen, phrase):
assert phrase in screen
@@ -128,7 +167,7 @@ def my_keys(console) -> str:
def test_the_admin_card_shows_and_edits_key_mode(screen):
assert "const KEY_MODE = { firm:" in screen and "user:" in screen and "none:" in screen
assert "choice('pfKeyMode', KEY_MODE, v.key_mode || 'firm')" in screen
assert "choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')" in screen
assert "key_mode: $('pfKeyMode').value" in screen
assert "KEY_MODE[p.key_mode]" in screen
@@ -171,3 +210,23 @@ def test_home_points_at_my_keys_when_a_personal_key_is_missing(console):
assert 'href="#/my-keys"' in hint and "esc(p.name)" in hint
# The chat says where to add the key instead of a bare "Nie udało się".
assert "'model_provider_user_key_missing'" in console.split("const CHAT_REFUSALS", 1)[1].split(";", 1)[0]
@pytest.mark.parametrize("code", [
"provider_key_refused", "provider_unreachable", "provider_no_models", "provider_unknown_key",
])
def test_discover_refusals_carry_their_english(code):
"""These refusals are worded by `coreRefusal` from the Problem Details `code` + `en`, not by a
dictionary entry: `provider_unreachable` carries the reason inside its sentence."""
backend = ROOT / "backend" / "app"
src = ((backend / "integrations" / "model_server.py").read_text(encoding="utf-8")
+ (backend / "services" / "providers.py").read_text(encoding="utf-8"))
assert "def _refusal(code: str, pl: str, en: str)" in src and '{"code": code, "en": en}' in src
assert re.search(rf'_refusal\(\s*"{code}"|"code": "{code}",\s*"en": ', src), code
def test_a_provider_the_eu_only_policy_hides_says_so_in_the_list() -> None:
# Core drops a non-EU provider from every model list while `eu_only` is on; the list must not
# call it plainly "aktywny" then, or its models vanish from the chat with no visible reason.
src = (pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js").read_text(encoding="utf-8")
assert "policy.eu_only && !p.stays_in_the_eu" in src and "ukryty: tylko UE" in src
@@ -0,0 +1,183 @@
"""`providers.discover` with `list_models` replaced: the key-prefix table, address vs key, local vs
external host, a non-http scheme refused, and an audit row that names the host and never the key."""
from __future__ import annotations
import asyncio
import json
import types
import uuid
import pytest
from app.errors import ValidationError
from app.services import providers
MODELS = [{"id": "m-1", "dialect": "openai"}]
@pytest.fixture
def calls(monkeypatch):
seen = {"list": [], "audit": []}
async def fake_list(base_url, key, vendor):
seen["list"].append((base_url, key, vendor))
return MODELS
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
monkeypatch.setattr(providers.audit, "record", lambda db, **kw: seen["audit"].append(kw))
return seen
def _discover(text, key=None):
actor = types.SimpleNamespace(id=uuid.uuid4())
return asyncio.run(providers.discover(object(), actor, text, key, ip="10.0.0.1"))
@pytest.mark.parametrize("key, vendor, name, base", [
("sk-ant-api03-abc", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
("sk-or-v1-abc", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
("sk-proj-abc", "openai", "OpenAI", "https://api.openai.com/v1"),
])
def test_each_key_prefix_names_its_vendor(calls, key, vendor, name, base):
out = _discover(f" {key} ")
assert out == {"vendor": vendor, "name": name, "kind": "api", "base_url": base, "models": MODELS}
assert calls["list"] == [(base, key, vendor)]
def test_an_unknown_key_asks_for_an_address(calls):
with pytest.raises(ValidationError) as exc:
_discover("xai-abcdef")
assert exc.value.extra["code"] == "provider_unknown_key"
assert calls["list"] == [] and calls["audit"] == []
@pytest.mark.parametrize("url, kind, host", [
("http://localhost:1234/v1", "local", "localhost"),
("http://127.0.0.1:1234", "local", "127.0.0.1"),
("http://[::1]:8080", "local", "::1"),
("http://host.docker.internal:1234/", "local", "host.docker.internal"),
("https://gpu.example.com:8000/v1", "api", "gpu.example.com"),
("http://localhost.evil.example", "api", "localhost.evil.example"),
])
def test_an_address_is_local_only_on_this_machine(calls, url, kind, host):
out = _discover(url, key=" srv-key ")
assert (out["vendor"], out["name"], out["kind"]) == (None, host, kind)
assert out["base_url"] == url.rstrip("/")
assert calls["list"] == [(url.rstrip("/"), "srv-key", None)]
def test_an_address_without_a_key_sends_none(calls):
_discover("http://localhost:1234")
assert calls["list"][0][1] is None
@pytest.mark.parametrize("url", ["ftp://gpu.example.com", "file:///etc/passwd",
"http://user:pw@gpu.example.com"])
def test_a_non_http_address_or_one_with_credentials_is_refused(calls, url):
with pytest.raises(ValidationError):
_discover(url)
assert calls["list"] == []
def test_the_audit_names_the_host_and_never_the_key(calls):
key = "sk-ant-api03-very-secret"
_discover(key)
(row,) = calls["audit"]
assert row["action"] == "model_provider.discover"
assert row["detail"] == "api.anthropic.com"
assert key not in json.dumps(row, default=str)
def test_a_refused_listing_propagates_and_writes_no_audit(monkeypatch, calls):
async def refuse(*_a):
raise ValidationError("x", {"code": "provider_key_refused"})
monkeypatch.setattr(providers.model_server, "list_models", refuse)
with pytest.raises(ValidationError):
_discover("sk-proj-abc")
assert calls["audit"] == []
# ── refresh: a stored provider's models re-read, through `update` ────────────
KEY = "sk-ant-api03-SECRETVALUE"
@pytest.fixture
def stored(monkeypatch):
row = types.SimpleNamespace(id=uuid.uuid4(), name="Anthropic", base_url="https://api.anthropic.com/v1",
key_prefix="sk-ant-a", models=[{"id": "old", "dialect": "openai"}])
seen = {"list": [], "update": [], "commits": 0, "listing": MODELS}
async def fake_list(base_url, key, vendor):
seen["list"].append((base_url, key, vendor))
if isinstance(seen["listing"], Exception):
raise seen["listing"]
return seen["listing"]
def fake_update(db, actor, provider_id, fields, *, ip):
seen["update"].append(fields)
row.models = fields["models"]
return {"id": str(provider_id), "models": row.models}
db = types.SimpleNamespace(commit=lambda: seen.__setitem__("commits", seen["commits"] + 1))
monkeypatch.setattr(providers.core, "get_or_404", lambda _db, _id: row)
monkeypatch.setattr(providers.core, "api_key", lambda _db, _p, _decrypt: KEY)
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
monkeypatch.setattr(providers, "update", fake_update)
return row, seen, db
def _refresh(row, db):
actor = types.SimpleNamespace(id=uuid.uuid4())
return asyncio.run(providers.refresh(db, actor, row.id, ip="10.0.0.1"))
def test_refresh_replaces_the_models_and_ends_the_read_first(stored):
row, seen, db = stored
out = _refresh(row, db)
assert out["models"] == MODELS and row.models == MODELS
assert seen["list"] == [("https://api.anthropic.com/v1", KEY, "anthropic")]
assert seen["commits"] == 1
# Only the models go to `update`: its audit diff can never carry the key.
assert seen["update"] == [{"models": MODELS}]
assert KEY not in json.dumps(seen["update"])
def test_a_refused_listing_keeps_the_old_models(stored):
row, seen, db = stored
seen["listing"] = ValidationError("Brak modeli.", {"code": "provider_no_models", "en": "No models."})
with pytest.raises(ValidationError) as exc:
_refresh(row, db)
assert exc.value.extra["code"] == "provider_no_models"
assert seen["update"] == [] and row.models == [{"id": "old", "dialect": "openai"}]
def test_refresh_of_a_keyless_local_server_sends_no_key(stored):
row, seen, db = stored
row.base_url, row.key_prefix = "http://localhost:1234", None
_refresh(row, db)
assert seen["list"] == [("http://localhost:1234", None, None)]
def test_an_unreadable_key_refuses_before_calling(stored, monkeypatch):
row, seen, db = stored
monkeypatch.setattr(providers.core, "api_key", lambda *_: None)
with pytest.raises(providers.ConflictError) as exc:
_refresh(row, db)
assert exc.value.extra["code"] == providers.KEY_UNREADABLE
assert seen["list"] == [] and seen["update"] == []
@pytest.mark.parametrize("url, vendor", [("https://api.anthropic.com/v1", "anthropic"),
("https://api.openai.com/v1/", "openai")])
def test_a_pasted_cloud_address_is_asked_the_way_its_vendor_answers(calls, url, vendor):
out = _discover(url, key="k")
assert out["vendor"] == vendor and calls["list"][0][2] == vendor
def test_a_provider_with_hundreds_of_models_can_be_added():
from app.schemas import ProviderCreateIn, ProviderUpdateIn
models = [{"id": f"m-{i}", "dialect": "openai"} for i in range(400)]
ProviderCreateIn(name="OpenRouter", kind="api", base_url="https://openrouter.ai/api/v1",
models=models, trains_on_data=False)
ProviderUpdateIn(models=models)
@@ -0,0 +1,53 @@
"""The two routes that call a provider: administrator-only, routed before `/{provider_id}`, and
SQL-free (the router validates and calls the service, nothing else)."""
from __future__ import annotations
import pathlib
import re
import uuid
import pytest
from app.services import providers
from tests.test_hub_gates_unit import _person, api # noqa: F401 (fixture)
ROUTER = pathlib.Path(__file__).resolve().parents[1] / "app" / "routers" / "admin_providers.py"
BASE = "/api/v1/admin/model-providers"
def test_both_routes_are_in_the_openapi_document():
from app.main import app
paths = app.openapi()["paths"]
assert "post" in paths[f"{BASE}/discover"]
assert "post" in paths[f"{BASE}/{{provider_id}}/refresh"]
def test_the_router_holds_no_sql():
assert not re.search(r"select\(|db\.execute|db\.add", ROUTER.read_text(encoding="utf-8"))
@pytest.mark.parametrize("path, body", [
(f"{BASE}/discover", {"input": "sk-ant-secret"}),
(f"{BASE}/{uuid.uuid4()}/refresh", None),
])
def test_a_plain_user_gets_what_other_admin_routes_answer(api, monkeypatch, path, body): # noqa: F811
called = []
monkeypatch.setattr(providers, "discover", lambda *a, **k: called.append(a))
monkeypatch.setattr(providers, "refresh", lambda *a, **k: called.append(a))
api.who(_person())
reference = api.client.get(f"{BASE}/policy")
r = api.client.post(path, json=body)
assert r.status_code == reference.status_code and r.status_code in (403, 404)
assert not called
def test_discover_is_not_parsed_as_an_id(api, monkeypatch): # noqa: F811
async def fake(db, actor, text, key, *, ip):
return {"vendor": "anthropic", "name": "Anthropic", "kind": "api",
"base_url": "https://api.anthropic.com/v1", "models": [{"id": "claude-x"}]}
monkeypatch.setattr(providers, "discover", fake)
api.who(_person(admin=True))
r = api.client.post(f"{BASE}/discover", json={"input": "sk-ant-secret"})
assert r.status_code == 200, r.text
assert r.json()["vendor"] == "anthropic"
assert api.db.calls == ["commit", "commit"]
+74 -74
View File
@@ -1,74 +1,74 @@
# Przegląd QA platformy Atrium - 2026-10-07 (noc)
Zakres: Compass (gałąź `rejestr/fundament`, przed PR), Atrium, Galena, Sygna, Counsel Scorecard + wspólne logowanie platformy. Infrastruktura: skill `atrium-qa-kontrakt`, agenci auditor / test-runner / e2e, kopia `C:/Users/badur/projects/atrium-qa`. Zero zmian i pushy w repo rodziny. Szczegóły i dowody per moduł: [2026-10-07/](2026-10-07/). Zrzuty ekranu, skrypty sond i specy Playwright (`platform-sso.spec.ts`, `rejestr-e2e.spec.ts`) zostały w kopii QA u Tobiasza - na prośbę dołożymy.
| moduł | SHA | stan |
|---|---|---|
| atrium | 0b09f50 | origin/main |
| galena | 40f78a8 | pin == HEAD |
| sygna | 41ab5f9 | pin == HEAD |
| counsel | 5ad8476 | pin == HEAD |
| dredd-core | v0.12.0 | pin z atrium/backend/requirements.txt (w kontenerach potwierdzone przez e2e) |
| compass | 1d7593d | gałąź rejestr/fundament (poza platformą - raport gotowości) |
## 1. Wady w stronę ZGODY (wpuszczają za dużo) - od najpoważniejszej
1. **Galena - użytkownik z samym odczytem może obciąć albo nadpisać dowolny plik na serwerze.** Parametry `ref`, `a`, `b` w trasach historii (`app/routers/history.py:30, :48`) idą prosto do gita, więc `--output=<ścieżka>` jest opcją, nie nazwą wersji. Potwierdzone wywołaniem funkcji (pliki obcięte do 0 B); żądania HTTP nikt nie wysłał, dojście wynika z kodu. **Galena działa na żywym Contabo.** Poprawka: odrzucać ref zaczynający się od `-` (albo `--end-of-options`) w `changes.resolve_ref`, `git_facade.log`, `changed_files`, `blame`. → [2026-10-07/galena-audyt.md](2026-10-07/galena-audyt.md)
2. **Sygna - prawnik, który założył sprawę, może zdjąć chiński mur postawiony przez partnera nadzorującego.** Przenosi sprawę do swojej przestrzeni osobistej (albo na najwyższy poziom drzewa), staje się administratorem murów, zdejmuje mur i wpuszcza osobę z konfliktem; partner traci wgląd. `routers/nodes.py:98-110` nie sprawdza uprawnień na starym rodzicu. Potwierdzone dwa razy na prawdziwej bazie. Poprawka: kilka linii (diff w raporcie modułu). → [2026-10-07/sygna-audyt.md](2026-10-07/sygna-audyt.md)
3. **Atrium - wyciekły token aplikacji wybija sobie kolejne tokeny, które działają po odwołaniu pierwszego.** `routers/users.py:308-352` bez bramki „tylko z sesji”; Compass taką ma. Poprawka: przenieść `require_session_credential` z Compassu. → [2026-10-07/atrium-audyt.md](2026-10-07/atrium-audyt.md)
4. **Atrium - przywrócenie konta oddaje dostęp do modułów, który w międzyczasie odebrano** (usunięcie z jednostki albo wyłączenie modułu). Poprawka sprawdzona sondą: `sync_members` w `reactivate`.
5. **Atrium - kierownik jednostki (nie admin, nie moderator) wpuszcza ludzi do modułów** przez dodanie ich do folderu. Wada albo nieopisana decyzja; łamie obietnicę z ONBOARDING-compass §3. Do rozstrzygnięcia Roman/Tobiasz.
6. **Compass (rejestr) - „Przyjmij z karty” przy walucie robi z ręcznych „5 EUR” kwotę „5 PLN” oznaczoną jako „z karty”.** Poprawka: kwota i waluta przyjmowane razem. → [2026-10-07/compass-audyt.md](2026-10-07/compass-audyt.md)
7. **Compass (rejestr) - dziennik zmian zapisuje „z karty”, ale nie z której analizy** (spec R3).
8. **Atrium - logowanie w hubie zwraca sekret sesji także w treści odpowiedzi** (poza ciasteczkiem HttpOnly), więc kod w stronie może go odczytać. Do potwierdzenia z autorem (klient desktopowy?). (e2e platformy)
9. **Galena, Sygna, Counsel, Atrium - domyślna instalacja z `init.sh` stawia moduły jako osobne aplikacje z własnymi kontami** (znana luka #6, potwierdzona na wszystkich): bez dopisania dwóch linii do env każdy z kontem w module wchodzi bez zgody z Atrium. Komentarze w env („until its cutover revision lands”) są nieaktualne.
10. **Strażnik „jedno konto” (`assert_identity_schema`) bez testu we wszystkich czterech modułach platformy** - działa na żywej bazie, ale usunięcie nie czerwieni niczego. W Atrium bez testu zachowania są też: awans na administratora, odwołanie sesji przy dezaktywacji, sprawdzenie kierownika przy zakładaniu folderu (mutacje przechodzą na zielono).
11. Drobniejsze: Compass - `CLEARABLE_FIELDS` nikt nie czyta; ochrona przed wstrzyknięciem w nowych miejscach konsoli bez testu (kod dziś poprawny); waluta „ZZZ” przyjmowana; wyczyszczenie kwoty zostawia walutę. Atrium - dwa testy kitu zawsze pomijają Compass (zła ścieżka). OpenAPI i `/docs` publiczne bez sesji we wszystkich modułach.
## 2. Wady w stronę ODMOWY
- **Świeże `init.sh` + `push.sh` pada w kroku 1/5** (`provision.sql` platformowy vs zakomentowane `PLATFORM_IDENTITY_SCHEMA`) - instalacja „z pudełka” opisana w README nie działa bez ręcznych zmian z RUNBOOK §4. `push.sh` woła compose bez `-p`.
- Counsel (i najpewniej Sygna) przyjmuje połowiczną konfigurację tożsamości: moduł martwy albo wylogowuje ludzi z Atrium.
- Sygna, Counsel: zalogowany bez uprawnienia widzi „Zaloguj się w Atrium” zamiast „nie masz dostępu” (pętla); login w module 409 zamiast 404.
- Compass (rejestr): pusty tekst z API blokuje wypełnienie z karty; na telefonie lista szersza niż ekran; komunikaty serwera po angielsku; kwoty w wersji EN w formacie polskim.
## 3. Kontrakt K1-K7
| | Atrium | Galena | Sygna | Counsel | Compass (gałąź) |
|---|---|---|---|---|---|
| K1 jedno konto | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak |
| K2 `dredd_session` | kod tak, wdrożenie `atrium_session` | trzyma | kod tak, wdrożenie nie | kod tak, wdrożenie nie | kod tak |
| K3 `assert_may_use` | nie dotyczy | trzyma | trzyma | trzyma (test tekstowy) | trzyma |
| K4 schemat + role | trzyma (managed check) | trzyma (managed check) | częściowo | statycznie | managed-db OK |
| K5 prefiks | trzyma (e2e S7) | trzyma (e2e) | trzyma (e2e) | trzyma (e2e) | nieznane |
| K6 licencje | trzyma | backend tak | trzyma | trzyma | trzyma |
| K7 dwa obrazy | trzyma | trzyma | trzyma | trzyma | nieznane |
| K-A strażnik | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak |
| K-B v0.12.0 | tak (kontener) | tak (kontener) | tak (kontener) | tak (kontener) | tak |
Referencja skilla (`references/kontrakt.md`) podaje v0.11.0 - nieaktualna. `CLAUDE.md` Atrium podaje v0.9.0.
## 4. Testy (pominięte = NIEZNANE)
| moduł | standalone z integracją | tryb platformy | bramki |
|---|---|---|---|
| Compass 1d7593d | 4939 / 70 / 82 - **64 porażki to artefakt** (kopię QA przełączył w trakcie inny agent); powtórka 8 plików: 206 / 0 / 7; wcześniejsza bramka pętli na tym SHA: 5009 / 0 | managed-db: migracje 0001-0010 OK; job platform NIEZNANY (14 pominiętych) | license OK, deploy_check OK, node OK |
| Atrium | 364 / 0 / 2 (2 = martwe testy Compassu) | managed check OK, odmowa migracji jako superuser OK; pytest managed-db przerwany = NIEZNANY | license OK, deploy_check OK |
| Galena | 288 / 0 / 14 | provisioning + managed check OK; `test_platform_live` (13) NIEZNANY | - |
| Sygna | 569 / 0 / 17 | NIEZNANY (seed platformy padł na granty - kolejność kroków) | license OK, deploy_check OK |
| Counsel | 178 / 0 / 11 | NIEZNANY (11 pominiętych) | license OK |
ruff we wszystkich modułach zgłasza I001/B008 - do sprawdzenia, czy CI w ogóle go odpala. Python 3.13 lokalnie, CI 3.12.
## 5. E2E
- **Platforma (S1-S9), cały stos:** 50 testów, 45 zielonych, 5 czerwonych (każdy to znalezisko wyżej). Wspólne logowanie, wylogowanie we wszystkich modułach, odmowa bez uprawnienia, 403 dla zwykłej roli, prefiksy, odporność na podrobione nagłówki i powtórkę ciasteczka - OK. Dwa testy zweryfikowane mutacją. Spec: `2026-10-07-platforma-e2e/platform-sso.spec.ts`. Compass poza zakresem (na platformie stoi `main`).
- **Compass, ekrany rejestru:** wszystko z §5 specu działa; wstrzyknięcie skryptu renderuje się jako tekst; viewer bez edycji (403). Rozjazd z prawdziwą kartą NIE URUCHOMIONY (brak modelu). Spec: `2026-10-07-rejestr-e2e/rejestr-e2e.spec.ts`.
## 6. Hipotezy niepotwierdzone
- Counsel: `GET /users` pokazuje moderatorowi cały katalog kont platformy.
- Sygna: rola aplikacji ma UPDATE na `conflict_check` i `aml_assessment` (niezmienność trzyma tylko kod).
- Galena: `blame` i `git diff --output` z treścią - do dobicia.
- Compass: źródło „karta” liczone od dzisiejszej nazwy firmy; rejestr a maskowanie PESEL w nazwie strony.
- `deploy/README.md:1193` vs ONBOARDING §2.1 - jeden z dokumentów nieaktualny.
## 7. Czego nie uruchomiono
Joby platformowe pytest w Galenie, Sygnie, Counselu i Compassie; PG17 w backendach; obrazów pojedynczych modułów poza e2e; compose-smoke; regresji option injection przez HTTP w Galenie; rozjazdu rejestru z prawdziwą kartą; Compassu na platformie.
# Przegląd QA platformy Atrium - 2026-10-07 (noc)
Zakres: Compass (gałąź `rejestr/fundament`, przed PR), Atrium, Galena, Sygna, Counsel Scorecard + wspólne logowanie platformy. Infrastruktura: skill `atrium-qa-kontrakt`, agenci auditor / test-runner / e2e, kopia `C:/Users/badur/projects/atrium-qa`. Zero zmian i pushy w repo rodziny. Szczegóły i dowody per moduł: [2026-10-07/](2026-10-07/). Zrzuty ekranu, skrypty sond i specy Playwright (`platform-sso.spec.ts`, `rejestr-e2e.spec.ts`) zostały w kopii QA u Tobiasza - na prośbę dołożymy.
| moduł | SHA | stan |
|---|---|---|
| atrium | 0b09f50 | origin/main |
| galena | 40f78a8 | pin == HEAD |
| sygna | 41ab5f9 | pin == HEAD |
| counsel | 5ad8476 | pin == HEAD |
| dredd-core | v0.12.0 | pin z atrium/backend/requirements.txt (w kontenerach potwierdzone przez e2e) |
| compass | 1d7593d | gałąź rejestr/fundament (poza platformą - raport gotowości) |
## 1. Wady w stronę ZGODY (wpuszczają za dużo) - od najpoważniejszej
1. **Galena - użytkownik z samym odczytem może obciąć albo nadpisać dowolny plik na serwerze.** Parametry `ref`, `a`, `b` w trasach historii (`app/routers/history.py:30, :48`) idą prosto do gita, więc `--output=<ścieżka>` jest opcją, nie nazwą wersji. Potwierdzone wywołaniem funkcji (pliki obcięte do 0 B); żądania HTTP nikt nie wysłał, dojście wynika z kodu. **Galena działa na żywym Contabo.** Poprawka: odrzucać ref zaczynający się od `-` (albo `--end-of-options`) w `changes.resolve_ref`, `git_facade.log`, `changed_files`, `blame`. → [2026-10-07/galena-audyt.md](2026-10-07/galena-audyt.md)
2. **Sygna - prawnik, który założył sprawę, może zdjąć chiński mur postawiony przez partnera nadzorującego.** Przenosi sprawę do swojej przestrzeni osobistej (albo na najwyższy poziom drzewa), staje się administratorem murów, zdejmuje mur i wpuszcza osobę z konfliktem; partner traci wgląd. `routers/nodes.py:98-110` nie sprawdza uprawnień na starym rodzicu. Potwierdzone dwa razy na prawdziwej bazie. Poprawka: kilka linii (diff w raporcie modułu). → [2026-10-07/sygna-audyt.md](2026-10-07/sygna-audyt.md)
3. **Atrium - wyciekły token aplikacji wybija sobie kolejne tokeny, które działają po odwołaniu pierwszego.** `routers/users.py:308-352` bez bramki „tylko z sesji”; Compass taką ma. Poprawka: przenieść `require_session_credential` z Compassu. → [2026-10-07/atrium-audyt.md](2026-10-07/atrium-audyt.md)
4. **Atrium - przywrócenie konta oddaje dostęp do modułów, który w międzyczasie odebrano** (usunięcie z jednostki albo wyłączenie modułu). Poprawka sprawdzona sondą: `sync_members` w `reactivate`.
5. **Atrium - kierownik jednostki (nie admin, nie moderator) wpuszcza ludzi do modułów** przez dodanie ich do folderu. Wada albo nieopisana decyzja; łamie obietnicę z ONBOARDING-compass §3. Do rozstrzygnięcia Roman/Tobiasz.
6. **Compass (rejestr) - „Przyjmij z karty” przy walucie robi z ręcznych „5 EUR” kwotę „5 PLN” oznaczoną jako „z karty”.** Poprawka: kwota i waluta przyjmowane razem. → [2026-10-07/compass-audyt.md](2026-10-07/compass-audyt.md)
7. **Compass (rejestr) - dziennik zmian zapisuje „z karty”, ale nie z której analizy** (spec R3).
8. **Atrium - logowanie w hubie zwraca sekret sesji także w treści odpowiedzi** (poza ciasteczkiem HttpOnly), więc kod w stronie może go odczytać. Do potwierdzenia z autorem (klient desktopowy?). (e2e platformy)
9. **Galena, Sygna, Counsel, Atrium - domyślna instalacja z `init.sh` stawia moduły jako osobne aplikacje z własnymi kontami** (znana luka #6, potwierdzona na wszystkich): bez dopisania dwóch linii do env każdy z kontem w module wchodzi bez zgody z Atrium. Komentarze w env („until its cutover revision lands”) są nieaktualne.
10. **Strażnik „jedno konto” (`assert_identity_schema`) bez testu we wszystkich czterech modułach platformy** - działa na żywej bazie, ale usunięcie nie czerwieni niczego. W Atrium bez testu zachowania są też: awans na administratora, odwołanie sesji przy dezaktywacji, sprawdzenie kierownika przy zakładaniu folderu (mutacje przechodzą na zielono).
11. Drobniejsze: Compass - `CLEARABLE_FIELDS` nikt nie czyta; ochrona przed wstrzyknięciem w nowych miejscach konsoli bez testu (kod dziś poprawny); waluta „ZZZ” przyjmowana; wyczyszczenie kwoty zostawia walutę. Atrium - dwa testy kitu zawsze pomijają Compass (zła ścieżka). OpenAPI i `/docs` publiczne bez sesji we wszystkich modułach.
## 2. Wady w stronę ODMOWY
- **Świeże `init.sh` + `push.sh` pada w kroku 1/5** (`provision.sql` platformowy vs zakomentowane `PLATFORM_IDENTITY_SCHEMA`) - instalacja „z pudełka” opisana w README nie działa bez ręcznych zmian z RUNBOOK §4. `push.sh` woła compose bez `-p`.
- Counsel (i najpewniej Sygna) przyjmuje połowiczną konfigurację tożsamości: moduł martwy albo wylogowuje ludzi z Atrium.
- Sygna, Counsel: zalogowany bez uprawnienia widzi „Zaloguj się w Atrium” zamiast „nie masz dostępu” (pętla); login w module 409 zamiast 404.
- Compass (rejestr): pusty tekst z API blokuje wypełnienie z karty; na telefonie lista szersza niż ekran; komunikaty serwera po angielsku; kwoty w wersji EN w formacie polskim.
## 3. Kontrakt K1-K7
| | Atrium | Galena | Sygna | Counsel | Compass (gałąź) |
|---|---|---|---|---|---|
| K1 jedno konto | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak, wdrożenie standalone | kod tak |
| K2 `dredd_session` | kod tak, wdrożenie `atrium_session` | trzyma | kod tak, wdrożenie nie | kod tak, wdrożenie nie | kod tak |
| K3 `assert_may_use` | nie dotyczy | trzyma | trzyma | trzyma (test tekstowy) | trzyma |
| K4 schemat + role | trzyma (managed check) | trzyma (managed check) | częściowo | statycznie | managed-db OK |
| K5 prefiks | trzyma (e2e S7) | trzyma (e2e) | trzyma (e2e) | trzyma (e2e) | nieznane |
| K6 licencje | trzyma | backend tak | trzyma | trzyma | trzyma |
| K7 dwa obrazy | trzyma | trzyma | trzyma | trzyma | nieznane |
| K-A strażnik | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak, bez testu | kod tak |
| K-B v0.12.0 | tak (kontener) | tak (kontener) | tak (kontener) | tak (kontener) | tak |
Referencja skilla (`references/kontrakt.md`) podaje v0.11.0 - nieaktualna. `CLAUDE.md` Atrium podaje v0.9.0.
## 4. Testy (pominięte = NIEZNANE)
| moduł | standalone z integracją | tryb platformy | bramki |
|---|---|---|---|
| Compass 1d7593d | 4939 / 70 / 82 - **64 porażki to artefakt** (kopię QA przełączył w trakcie inny agent); powtórka 8 plików: 206 / 0 / 7; wcześniejsza bramka pętli na tym SHA: 5009 / 0 | managed-db: migracje 0001-0010 OK; job platform NIEZNANY (14 pominiętych) | license OK, deploy_check OK, node OK |
| Atrium | 364 / 0 / 2 (2 = martwe testy Compassu) | managed check OK, odmowa migracji jako superuser OK; pytest managed-db przerwany = NIEZNANY | license OK, deploy_check OK |
| Galena | 288 / 0 / 14 | provisioning + managed check OK; `test_platform_live` (13) NIEZNANY | - |
| Sygna | 569 / 0 / 17 | NIEZNANY (seed platformy padł na granty - kolejność kroków) | license OK, deploy_check OK |
| Counsel | 178 / 0 / 11 | NIEZNANY (11 pominiętych) | license OK |
ruff we wszystkich modułach zgłasza I001/B008 - do sprawdzenia, czy CI w ogóle go odpala. Python 3.13 lokalnie, CI 3.12.
## 5. E2E
- **Platforma (S1-S9), cały stos:** 50 testów, 45 zielonych, 5 czerwonych (każdy to znalezisko wyżej). Wspólne logowanie, wylogowanie we wszystkich modułach, odmowa bez uprawnienia, 403 dla zwykłej roli, prefiksy, odporność na podrobione nagłówki i powtórkę ciasteczka - OK. Dwa testy zweryfikowane mutacją. Spec: `2026-10-07-platforma-e2e/platform-sso.spec.ts`. Compass poza zakresem (na platformie stoi `main`).
- **Compass, ekrany rejestru:** wszystko z §5 specu działa; wstrzyknięcie skryptu renderuje się jako tekst; viewer bez edycji (403). Rozjazd z prawdziwą kartą NIE URUCHOMIONY (brak modelu). Spec: `2026-10-07-rejestr-e2e/rejestr-e2e.spec.ts`.
## 6. Hipotezy niepotwierdzone
- Counsel: `GET /users` pokazuje moderatorowi cały katalog kont platformy.
- Sygna: rola aplikacji ma UPDATE na `conflict_check` i `aml_assessment` (niezmienność trzyma tylko kod).
- Galena: `blame` i `git diff --output` z treścią - do dobicia.
- Compass: źródło „karta” liczone od dzisiejszej nazwy firmy; rejestr a maskowanie PESEL w nazwie strony.
- `deploy/README.md:1193` vs ONBOARDING §2.1 - jeden z dokumentów nieaktualny.
## 7. Czego nie uruchomiono
Joby platformowe pytest w Galenie, Sygnie, Counselu i Compassie; PG17 w backendach; obrazów pojedynczych modułów poza e2e; compose-smoke; regresji option injection przez HTTP w Galenie; rozjazdu rejestru z prawdziwą kartą; Compassu na platformie.
+1
View File
@@ -118,6 +118,7 @@
/* The model picker sits at the end of the scope bar; the answer is a quiet card, plain text only. */
.home-model { display: inline-flex; align-items: center; gap: 8px; }
.home-model select { min-height: 32px; padding: 2px 8px; font-size: 12px; max-width: 260px; }
.home-model > span:empty { display: none; }
.home-answer {
margin-top: 20px; padding: 14px 16px; border: 1px solid var(--at-border); border-radius: var(--at-radius-2xl);
background: var(--at-surface);
+201 -66
View File
@@ -640,7 +640,6 @@ const I18N = {
'Najnowsze': 'Newest',
// model providers
'Dostawcy modeli': 'Model providers',
'Nowy dostawca': 'New provider',
'Edytuj dostawcę': 'Edit provider',
'Dostawca': 'Provider',
'Modele': 'Models',
@@ -672,7 +671,6 @@ const I18N = {
'Pozostaw puste, aby zachować obecny klucz': 'Leave empty to keep the current key',
'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.': 'The key is write-only: nobody, the administrator included, sees it again.',
'Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.': 'This server has no MODEL_PROVIDER_SECRET, so it cannot store an API key.',
'Jeden model w wierszu: identyfikator | okno kontekstu | dialekt (openai albo chatml).': 'One model per line: id | context window | dialect (openai or chatml).',
'Obowiązuje we wszystkich modułach. Dostawcę można tylko wyłączyć, nie usunąć: przebiegi pamiętają, kto je policzył.': 'Applies in every module. A provider can only be disabled, never deleted: runs remember which one computed them.',
'Wyłączyć tego dostawcę? Moduły przestaną go oferować.': 'Disable this provider? Modules stop offering it.',
'Usunąć zapisany klucz API tego dostawcy?': 'Remove the stored API key of this provider?',
@@ -688,6 +686,14 @@ const I18N = {
'Twój własny klucz API jest potrzebny dla:': 'Your own API key is needed for:',
'Zmień klucz': 'Change key',
'Usunąć twój zapisany klucz API tego dostawcy?': 'Remove your stored API key for this provider?',
'Dodaj dostawcę': 'Add provider',
'Wklej klucz API albo adres serwera': 'Paste an API key or a server’s address',
'Klucz (jeśli serwer go wymaga)': 'Key (if the server needs one)',
'Znaleziono modele.': 'Models found.',
'Odśwież modele': 'Refresh models',
'Odświeżono modele.': 'Models refreshed.',
// discover/refresh refusals (provider_key_refused, provider_unreachable, provider_no_models,
// provider_unknown_key) carry their own `en` and are worded by coreRefusal(), not here
};
let LANG = (function () {
@@ -1241,7 +1247,34 @@ function homeSubmit(ev) {
written with textContent and nothing else, so a model cannot put markup, a link or an image on
the platform's one origin. The conversation lives in this tab (sessionStorage, see chatSave). */
const chat = { model: '', turns: [], ctl: null };
const modelLabel = (m) => m.id;
/* A model id as a person reads it: `claude-opus-5-5` → "Claude Opus 5.5", `qwen/qwen3.5-9b` →
"Qwen3.5 9B". Only short all-digit parts join with a dot, so a date suffix stays a word.
ponytail: a heuristic over the id; a display name from the provider when one is offered. */
function prettyModel(id) {
const parts = String(id).split('/').pop().split('-').filter(Boolean);
const words = [];
for (const p of parts) {
const prev = words[words.length - 1];
if (/^\d{1,2}$/.test(p) && /^\d{1,2}(\.\d{1,2})*$/.test(prev || '')) words[words.length - 1] = prev + '.' + p;
else words.push(p);
}
return words.map((w) => w.replace(/[a-z]/, (c) => c.toUpperCase())).join(' ');
}
/* Which family a model belongs to, by its id: a family key (`anthropic`, `openai`, …), or for any
other model the first letter of its name as a one-character monogram. */
function modelFamily(id) {
const name = String(id).split('/').pop().toLowerCase();
if (/claude/.test(name)) return 'anthropic';
if (/^(gpt|o\d)/.test(name)) return 'openai';
if (/gemini|gemma/.test(name)) return 'google';
if (/qwen/.test(name)) return 'qwen';
if (/bielik/.test(name)) return 'bielik';
if (/llama/.test(name)) return 'meta';
if (/mistral|mixtral/.test(name)) return 'mistral';
return ((name.match(/[a-z0-9]/) || ['?'])[0]).toUpperCase();
}
async function loadModels() {
/* 502 = configured, but the model server does not answer (the pod is stopped). */
@@ -1250,9 +1283,60 @@ async function loadModels() {
return state._models;
}
/* The picker groups by provider; /models already lists them in provider order. */
function modelOptions(models, selected, none) {
return `<option value="">${esc(none)}</option>` + models.map((m) =>
`<option value="${esc(m.id)}"${m.id === selected ? ' selected' : ''} data-no-i18n>${esc(modelLabel(m))}</option>`).join('');
const groups = [];
// The ask names a model id and the server takes the FIRST provider offering it (core `offering`),
// so an id a later provider repeats is shown once, under the provider that will answer.
// ponytail: pass a provider id with the ask if two providers of one model must both be choosable.
const seen = new Set();
for (const m of models) {
if (seen.has(m.id)) continue;
seen.add(m.id);
if (!groups.length || groups[groups.length - 1].provider !== m.provider) groups.push({ provider: m.provider, models: [] });
groups[groups.length - 1].models.push(m);
}
return `<option value="">${esc(none)}</option>` + groups.map((g) =>
`<optgroup label="${esc(g.provider)}" data-no-i18n>` + g.models.map((m) =>
`<option value="${esc(m.id)}" title="${esc(m.id)}"${m.id === selected ? ' selected' : ''} data-no-i18n>${esc(prettyModel(m.id))}</option>`).join('')
+ '</optgroup>').join('');
}
/* Brand logotypes for model families and providers: Simple Icons (CC0-1.0, no per-icon licence
in its data), path data vendored at commit e451c581, never from a CDN. Decided per brand
(plan 5.2): anthropic, google (Gemini), qwen, meta, mistral, openrouter → logotype; openai →
monogram (not in Simple Icons), bielik and the rest → monogram (not in the set). */
const BRAND = {
// simple-icons: anthropic
anthropic: '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',
// simple-icons: googlegemini
google: 'M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81',
// simple-icons: qwen
qwen: 'M23.919 14.545 20.817 9.17l1.47-2.544a.56.56 0 0 0 0-.566l-1.633-2.83a.57.57 0 0 0-.49-.283h-6.207L12.487.402a.57.57 0 0 0-.49-.284H8.732a.56.56 0 0 0-.49.284L5.139 5.775h-2.94a.56.56 0 0 0-.49.284L.077 8.887a.56.56 0 0 0 0 .567L3.18 14.83l-1.47 2.545a.56.56 0 0 0 0 .566l1.634 2.83a.57.57 0 0 0 .49.283h6.205l1.47 2.545a.57.57 0 0 0 .49.284h3.266a.57.57 0 0 0 .49-.284l3.104-5.375h2.94a.57.57 0 0 0 .49-.283l1.634-2.828a.55.55 0 0 0-.004-.568M8.733.686l1.634 2.828-1.634 2.828H21.8L20.164 9.17H7.425L5.63 6.06Zm1.306 19.801-6.205-.002 1.634-2.83h3.265L2.201 6.344h3.267q3.182 5.517 6.367 11.032zm10.124-5.66L18.53 12l-6.532 11.315-1.634-2.83c2.129-3.673 4.25-7.351 6.373-11.028h3.592l3.102 5.374z',
// simple-icons: meta
meta: 'M6.915 4.03c-1.968 0-3.683 1.28-4.871 3.113C.704 9.208 0 11.883 0 14.449c0 .706.07 1.369.21 1.973a6.624 6.624 0 0 0 .265.86 5.297 5.297 0 0 0 .371.761c.696 1.159 1.818 1.927 3.593 1.927 1.497 0 2.633-.671 3.965-2.444.76-1.012 1.144-1.626 2.663-4.32l.756-1.339.186-.325c.061.1.121.196.183.3l2.152 3.595c.724 1.21 1.665 2.556 2.47 3.314 1.046.987 1.992 1.22 3.06 1.22 1.075 0 1.876-.355 2.455-.843a3.743 3.743 0 0 0 .81-.973c.542-.939.861-2.127.861-3.745 0-2.72-.681-5.357-2.084-7.45-1.282-1.912-2.957-2.93-4.716-2.93-1.047 0-2.088.467-3.053 1.308-.652.57-1.257 1.29-1.82 2.05-.69-.875-1.335-1.547-1.958-2.056-1.182-.966-2.315-1.303-3.454-1.303zm10.16 2.053c1.147 0 2.188.758 2.992 1.999 1.132 1.748 1.647 4.195 1.647 6.4 0 1.548-.368 2.9-1.839 2.9-.58 0-1.027-.23-1.664-1.004-.496-.601-1.343-1.878-2.832-4.358l-.617-1.028a44.908 44.908 0 0 0-1.255-1.98c.07-.109.141-.224.211-.327 1.12-1.667 2.118-2.602 3.358-2.602zm-10.201.553c1.265 0 2.058.791 2.675 1.446.307.327.737.871 1.234 1.579l-1.02 1.566c-.757 1.163-1.882 3.017-2.837 4.338-1.191 1.649-1.81 1.817-2.486 1.817-.524 0-1.038-.237-1.383-.794-.263-.426-.464-1.13-.464-2.046 0-2.221.63-4.535 1.66-6.088.454-.687.964-1.226 1.533-1.533a2.264 2.264 0 0 1 1.088-.285z',
// simple-icons: mistralai
mistral: 'M17.143 3.429v3.428h-3.429v3.429h-3.428V6.857H6.857V3.43H3.43v13.714H0v3.428h10.286v-3.428H6.857v-3.429h3.429v3.429h3.429v-3.429h3.428v3.429h-3.428v3.428H24v-3.428h-3.43V3.429z',
// simple-icons: openrouter
openrouter: 'M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.396.223-1.342.574-2.185.798-.841.225-1.753.333-1.751.333v4.229s.768.108 1.61.333c.842.224 1.789.575 2.185.799 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918l7.222-4.168-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z',
};
// A brand's logotype scaled into the tile, else a one-letter monogram.
function markSvg(brand, letter) {
const glyph = BRAND[brand]
? `<g transform="translate(5 5) scale(.5833)"><path d="${BRAND[brand]}" fill="currentColor"/></g>`
: `<text x="12" y="16.5" text-anchor="middle" font-size="13" font-weight="600" fill="currentColor">${esc(letter)}</text>`;
return `<svg viewBox="0 0 24 24" aria-hidden="true">${glyph}</svg>`;
}
/* A family's mark beside the picker, in the family's colour (a one-letter family is "other", in
gray): its logotype where BRAND has one, else a monogram. */
const FAMILY_MARK = { anthropic: ['A', 'orange'], openai: ['O', 'teal'], google: ['G', 'blue'], qwen: ['Q', 'violet'],
bielik: ['B', 'red'], meta: ['M', 'indigo'], mistral: ['M', 'pink'] };
function familyIcon(id) {
if (!id) return '';
const fam = modelFamily(id);
const [letter, hue] = FAMILY_MARK[fam] || [fam, 'gray'];
return `<span class="mi h-${hue}" style="--mi:22px">${markSvg(fam, letter)}</span>`;
}
// ponytail: per browser; a server-side preference when a pick has to follow a person across devices.
@@ -1270,6 +1354,7 @@ function homeModelChange(sel) {
$('homeQ').setAttribute('aria-label', _tr(ask ? 'Zapytaj asystenta' : 'Szukaj we wszystkich modułach'));
document.querySelector('.home-send').setAttribute('aria-label', _tr(ask ? 'Wyślij' : 'Szukaj'));
document.querySelectorAll('[data-chat-only]').forEach((e) => e.classList.toggle('hidden', !ask));
$('homeModelIcon').innerHTML = familyIcon(sel.value);
saveModelPick(sel.value);
}
@@ -4146,6 +4231,7 @@ async function viewHome(C) {
const picked = models.some((m) => m.id === saved) ? saved : '';
/* Model server off: say so instead of dropping the picker, or the feature looks gone. */
const picker = models.length ? `<label class="home-model"><span>Model AI</span>
<span id="homeModelIcon">${familyIcon(picked)}</span>
<select id="homeModel" onchange="homeModelChange(this)">${modelOptions(models, picked, 'Tylko szukaj')}</select></label>`
: gw && gw.configured ? `<label class="home-model"><span>Model AI</span>
<select id="homeModel" disabled><option value="">Serwer modeli wyłączony</option></select></label>` : '';
@@ -5331,9 +5417,22 @@ function saveSettings() {
writer, every module reads them). Deliberately plain: functional and minimal, built from the same
pieces as the other admin screens — the look is Tobiasz's to replace.
The key is WRITE-ONLY: the API never returns it (only has_key / key_prefix), so the field is
always empty, "leave empty to keep", and removing it is its own action. Nothing here calls a
provider: there is no "test connection" (an admin-typed URL fetched by the hub is an SSRF door). */
always empty, "leave empty to keep", and removing it is its own action. The console never calls
a provider itself: "Odśwież modele" asks the hub (`/refresh`), which reads the provider's list
under the outbound limits of integrations/model_server.py. */
const PROVIDER_KIND = { api: 'API (zewnętrzny)', local: 'lokalny' };
/* A provider's mark in its colour, recognised by the host it answers on (the console holds no
key-prefix catalogue — that is services/providers.py's): its logotype where BRAND has one
(PROVIDER_BRAND), else a monogram. */
const PROVIDER_HUE = { 'api.anthropic.com': 'orange', 'api.openai.com': 'teal', 'openrouter.ai': 'indigo' };
const PROVIDER_BRAND = { 'api.anthropic.com': 'anthropic', 'openrouter.ai': 'openrouter' };
function providerIcon(p) {
let host = '';
try { host = new URL(p.base_url).hostname; } catch { /* the row is shown anyway, in gray */ }
const hue = PROVIDER_HUE[host] || (p.kind === 'local' ? 'gray' : 'blue');
const letter = ((p.name || host || '?').trim()[0] || '?').toUpperCase();
return `<span class="mi h-${hue}" style="--mi:28px">${markSvg(PROVIDER_BRAND[host], letter)}</span>`;
}
const PROVIDER_LEVEL = { nobody: 'Nikt', admins_only: 'Tylko administratorzy', everyone: 'Każdy' };
/* dredd-core 0.18.0: whose key a call carries — one source per provider, never a fallback. */
const KEY_MODE = { firm: 'Klucz firmy', user: 'Własny klucz użytkownika', none: 'Bez klucza' };
@@ -5344,30 +5443,26 @@ async function viewAdminProviders(C) {
state._providers = rows;
state._providerPolicy = policy;
setCrumb([{ label: 'Ustawienia' }, { label: 'Dostawcy modeli' }]);
const kindChip = (p) => `<span class="chip">${esc(PROVIDER_KIND[p.kind] || p.kind)}</span>`;
const euChip = (p) => (p.stays_in_the_eu ? '<span class="chip ok">UE/EOG</span>' : '<span class="chip warn">poza UE</span>');
const keyCell = (p) => (p.has_key
? `<span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(p.key_prefix || '')}…</span>`
: '<span class="faint">brak</span>');
C.innerHTML = pageHead('Dostawcy modeli', '',
`<button class="btn primary" onclick="openProviderForm()">${svg(ICN.plus)}<span>Nowy dostawca</span></button>`)
`<button class="btn primary" onclick="openAddProvider()">${svg(ICN.plus)}<span>Dodaj dostawcę</span></button>`)
+ `<div class="faint tiny" style="margin-bottom:10px">Obowiązuje we wszystkich modułach. Dostawcę można tylko wyłączyć, nie usunąć: przebiegi pamiętają, kto je policzył.</div>`
+ `<div class="card"><h3>Polityka użycia</h3><div class="stack">
<label class="field">Kto może używać modeli${choice('ppLevel', PROVIDER_LEVEL, policy.level)}</label>
<label class="check"><input type="checkbox" id="ppEu" ${policy.eu_only ? 'checked' : ''} /> <span>Tylko dostawcy z UE/EOG (lub lokalni)</span></label>
</div><div class="acts-row"><button class="btn primary" onclick="saveProviderPolicy()">${svg(ICN.check)}<span>Zapisz politykę</span></button></div></div>`
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
<th>Dostawca</th><th>Rodzaj</th><th>Region</th><th>Modele</th><th>Czyj klucz</th><th>Klucz API</th><th>Status</th><th></th>
<th>Dostawca</th><th>Modele</th><th>Czyj klucz</th><th>Status</th><th></th>
</tr></thead><tbody>${rows.map((p) => `<tr>
<td><div>${dat(p.name)}</div><div class="mono tiny faint wrap" data-no-i18n>${esc(p.base_url)}</div></td>
<td${lbl('Rodzaj')}>${kindChip(p)}</td>
<td${lbl('Region')}><span data-no-i18n>${esc(p.region || '—')}</span> ${euChip(p)}</td>
<td class="mono tiny"${lbl('Modele')} data-no-i18n>${esc((p.models || []).map((m) => m.id).join(', '))}</td>
<td><div class="row">${providerIcon(p)}<div><div>${dat(p.name)}</div><div class="mono tiny faint wrap" data-no-i18n>${esc(p.base_url)}</div></div></div></td>
<td class="mono"${lbl('Modele')} data-no-i18n>${esc(String((p.models || []).length))}</td>
<td${lbl('Czyj klucz')}><span class="chip">${esc(KEY_MODE[p.key_mode] || p.key_mode)}</span></td>
<td${lbl('Klucz API')}>${keyCell(p)}</td>
<td${lbl('Status')}>${p.is_active ? '<span class="chip ok">aktywny</span>' : '<span class="chip err">wyłączony</span>'}</td>
<td${lbl('Status')}>${p.is_active === false ? '<span class="chip err">wyłączony</span>'
: policy.eu_only && !p.stays_in_the_eu
? '<span class="chip warn" title="Polityka „Tylko dostawcy z UE/EOG” ukrywa jego modele. Odznacz ją albo podaj region w Szczegółach.">ukryty: tylko UE</span>'
: '<span class="chip ok">aktywny</span>'}</td>
<td class="acts-cell shrink"><div class="row">
<button class="btn sm" data-pid="${esc(p.id)}" onclick="openProviderForm(this.dataset.pid)">Edytuj</button>
<button class="btn sm" data-pid="${esc(p.id)}" onclick="refreshProvider(this.dataset.pid)">${svg(ICN.refresh)}<span>Odśwież modele</span></button>
<button class="btn sm" data-pid="${esc(p.id)}" onclick="openProviderForm(this.dataset.pid)">Szczegóły</button>
${p.is_active
? `<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="disableProvider(this.dataset.pid)">Wyłącz</button>`
: `<button class="btn sm" data-pid="${esc(p.id)}" onclick="enableProvider(this.dataset.pid)">Włącz</button>`}
@@ -5375,85 +5470,121 @@ async function viewAdminProviders(C) {
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak dostawców modeli.</div>');
}
/* `id | context window | dialect`, one model per line — the smallest editor that covers the shape. */
const modelsText = (models) => (models || []).map((m) =>
[m.id, m.context_window == null ? '' : m.context_window, m.dialect || 'openai'].join(' | ')).join('\n');
/* "Dodaj dostawcę": one field. The hub recognises what was pasted and lists its models (`discover`,
which holds the key-prefix catalogue — the console does not copy it); the preview is read-only
but the name. The key is never rendered or kept: it stays in its input until "Dodaj" sends it once,
and any edit drops the preview, so what is added is always what was checked. */
const isAddress = (text) => /^https?:\/\//i.test(text.trim());
function readModels(text) {
return text.split('\n').map((l) => l.trim()).filter(Boolean).map((line) => {
const [id, win, dialect] = line.split('|').map((x) => x.trim());
const out = { id: id || '' };
// A whole number goes as a number; anything else goes as typed, so core refuses it by name.
if (win) out.context_window = /^\d+$/.test(win) ? parseInt(win, 10) : win;
if (dialect) out.dialect = dialect;
return out;
});
function openAddProvider() {
state._discovered = null;
modal('Dodaj dostawcę', '', `<label class="field">Wklej klucz API albo adres serwera<input id="apInput"
autocomplete="off" spellcheck="false" maxlength="4096" oninput="addProviderInput()" /></label>
<label class="field hidden" id="apKeyRow">Klucz (jeśli serwer go wymaga)<input id="apKey" type="password"
autocomplete="new-password" maxlength="4096" oninput="addProviderInput()" /></label>
<div id="apPreview" class="stack"></div>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn" onclick="discoverProvider()">Sprawdź</button>
<button class="btn primary hidden" id="apAdd" onclick="addProvider()">Dodaj</button>`,
{ wide: true });
}
function addProviderInput() {
$('apKeyRow').classList.toggle('hidden', !isAddress($('apInput').value));
state._discovered = null;
$('apPreview').innerHTML = '';
$('apAdd').classList.add('hidden');
}
function discoverProvider() {
const input = $('apInput').value.trim();
const key = isAddress(input) ? $('apKey').value.trim() : '';
mutate('POST', '/admin/model-providers/discover', key ? { input, key } : { input },
{ reopen: showDiscovered, done: 'Znaleziono modele.' });
}
function showDiscovered(r) {
state._discovered = r;
const stale = $('modalBody').querySelector('.banner.err');
if (stale) stale.remove();
$('apPreview').innerHTML = `<div class="row">${providerIcon(r)}
<label class="field">Nazwa<input id="apName" maxlength="120" value="${esc(r.name)}" /></label></div>
<div class="faint tiny">${esc(PROVIDER_KIND[r.kind] || r.kind)} · <span class="mono" data-no-i18n>${esc(r.base_url)}</span></div>
<ul class="mono tiny" data-no-i18n>${r.models.map((m) => `<li>${esc(m.id)}</li>`).join('')}</ul>`;
localize($('apPreview'));
$('apAdd').classList.remove('hidden');
}
/* A recognised vendor (a key) also suggests the processor's name; region and DPA are the
administrator's to fill in under "Szczegóły" — nothing about a vendor is asserted here. */
function addProvider() {
const r = state._discovered;
if (!r) return;
const input = $('apInput').value.trim();
const key = isAddress(input) ? $('apKey').value.trim() : input;
const body = { name: $('apName').value.trim(), kind: r.kind, base_url: r.base_url, models: r.models,
trains_on_data: false };
if (r.vendor) body.processor_name = r.name;
if (key) body.api_key = key;
mutate('POST', '/admin/model-providers', body);
}
function openProviderForm(id) {
const p = id ? (state._providers || []).find((x) => x.id === id) : null;
if (id && !p) { toast('Nie znaleziono strony.'); return; }
const v = p || { kind: 'api', models: [], trains_on_data: false, is_active: true };
const p = (state._providers || []).find((x) => x.id === id);
if (!p) { toast('Nie znaleziono strony.'); return; }
const writable = !!(state._providerPolicy && state._providerPolicy.keys_writable);
const allowed = { '': 'Zgodnie z polityką', ...PROVIDER_LEVEL };
const body = `<div class="grid2">
<label class="field">Nazwa<input id="pfName" maxlength="120" value="${esc(v.name || '')}" /></label>
<label class="field">Rodzaj${p ? `<input value="${esc(PROVIDER_KIND[v.kind] || v.kind)}" disabled />` : choice('pfKind', PROVIDER_KIND, v.kind)}</label>
<label class="field">Nazwa<input id="pfName" maxlength="120" value="${esc(p.name || '')}" /></label>
<label class="field">Rodzaj<input value="${esc(PROVIDER_KIND[p.kind] || p.kind)}" disabled /></label>
</div>
<label class="field">Adres<input id="pfUrl" type="url" inputmode="url" autocomplete="off" spellcheck="false" maxlength="2000" placeholder="https://api.example.eu/v1" value="${esc(v.base_url || '')}" /></label>
<label class="field">Modele<textarea id="pfModels" rows="4" data-no-i18n>${esc(modelsText(v.models))}</textarea></label>
<div class="faint tiny">Jeden model w wierszu: identyfikator | okno kontekstu | dialekt (openai albo chatml).</div>
<label class="field">Adres<input id="pfUrl" type="url" inputmode="url" autocomplete="off" spellcheck="false" maxlength="2000" placeholder="https://api.example.eu/v1" value="${esc(p.base_url || '')}" /></label>
<div class="grid3">
<label class="field">Region<input id="pfRegion" autocomplete="off" spellcheck="false" maxlength="8" placeholder="DE" value="${esc(v.region || '')}" /></label>
<label class="field">Podmiot przetwarzający<input id="pfProcessor" maxlength="200" value="${esc(v.processor_name || '')}" /></label>
<label class="field">Dla kogo${choice('pfAllowed', allowed, v.allowed_for || '')}</label>
<label class="field">Region<input id="pfRegion" autocomplete="off" spellcheck="false" maxlength="8" placeholder="DE" value="${esc(p.region || '')}" /></label>
<label class="field">Podmiot przetwarzający<input id="pfProcessor" maxlength="200" value="${esc(p.processor_name || '')}" /></label>
<label class="field">Dla kogo${choice('pfAllowed', allowed, p.allowed_for || '')}</label>
</div>
<label class="field">Adres umowy powierzenia (DPA)<input id="pfDpa" maxlength="2000" value="${esc(v.dpa_url || '')}" /></label>
<label class="check"><input type="checkbox" id="pfTrains" ${v.trains_on_data ? 'checked' : ''} /> <span>Dostawca trenuje modele na przesłanych danych</span></label>
${p ? `<label class="check"><input type="checkbox" id="pfActive" ${v.is_active ? 'checked' : ''} /> <span>Aktywny</span></label>` : ''}
<label class="field">Czyj klucz${choice('pfKeyMode', KEY_MODE, v.key_mode || 'firm')}</label>
${p ? '<div class="faint tiny">Zmiana adresu albo odejście od własnych kluczy użytkowników usuwa wszystkie zapisane klucze użytkowników tego dostawcy.</div>' : ''}
<label class="field">Adres umowy powierzenia (DPA)<input id="pfDpa" maxlength="2000" value="${esc(p.dpa_url || '')}" /></label>
<label class="check"><input type="checkbox" id="pfTrains" ${p.trains_on_data ? 'checked' : ''} /> <span>Dostawca trenuje modele na przesłanych danych</span></label>
<label class="check"><input type="checkbox" id="pfActive" ${p.is_active ? 'checked' : ''} /> <span>Aktywny</span></label>
<label class="field">Czyj klucz${choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')}</label>
<div class="faint tiny">Zmiana adresu albo odejście od własnych kluczy użytkowników usuwa wszystkie zapisane klucze użytkowników tego dostawcy.</div>
<label class="field">Klucz API<input id="pfKey" type="password" autocomplete="new-password" maxlength="4096"
placeholder="Pozostaw puste, aby zachować obecny klucz" ${writable ? '' : 'disabled'} /></label>
<div class="faint tiny">${writable ? 'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.'
: 'Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.'}</div>
${p && p.has_key ? `<div class="row"><span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(p.key_prefix || '')}…</span>
${p.has_key ? `<div class="row"><span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(p.key_prefix || '')}…</span>
<button type="button" class="btn sm danger" data-pid="${esc(p.id)}" onclick="removeProviderKey(this.dataset.pid)">Usuń klucz</button></div>` : ''}`;
modal(p ? 'Edytuj dostawcę' : 'Nowy dostawca', '', body,
modal('Szczegóły', '', body,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" data-pid="${esc(p ? p.id : '')}" onclick="saveProvider(this.dataset.pid)">Zapisz</button>`,
<button class="btn primary" data-pid="${esc(p.id)}" onclick="saveProvider(this.dataset.pid)">Zapisz</button>`,
{ wide: true });
}
/* Create sends the whole card; edit sends it too, with emptied optional fields asked for by name in
`clear` (absent means "leave it" on the server) — and never a key unless one was typed. */
function readProviderForm(editing) {
/* Sends the whole card, with emptied optional fields asked for by name in `clear` (absent means
"leave it" on the server) — and never a key unless one was typed. The models are the provider's
own list (`/refresh`), never typed. */
function readProviderForm() {
const text = (id) => $(id).value.trim();
const body = {
name: text('pfName'), base_url: text('pfUrl'), models: readModels($('pfModels').value),
trains_on_data: $('pfTrains').checked, key_mode: $('pfKeyMode').value,
name: text('pfName'), base_url: text('pfUrl'), trains_on_data: $('pfTrains').checked,
is_active: $('pfActive').checked, key_mode: $('pfKeyMode').value,
};
const clear = [];
[['region', 'pfRegion'], ['processor_name', 'pfProcessor'], ['dpa_url', 'pfDpa'], ['allowed_for', 'pfAllowed']]
.forEach(([field, id]) => {
const value = text(id);
if (value) body[field] = value;
else if (editing) clear.push(field);
else clear.push(field);
});
if (editing) {
body.is_active = $('pfActive').checked;
body.clear = clear;
} else {
body.kind = $('pfKind').value;
}
body.clear = clear;
const key = $('pfKey').value;
if (key) body.api_key = key;
return body;
}
function saveProvider(id) {
if (id) mutate('PATCH', '/admin/model-providers/' + enc(id), () => readProviderForm(true));
else mutate('POST', '/admin/model-providers', () => readProviderForm(false));
mutate('PATCH', '/admin/model-providers/' + enc(id), readProviderForm);
}
function removeProviderKey(id) {
@@ -5476,6 +5607,10 @@ function confirmDisableProvider(id) {
mutate('POST', `/admin/model-providers/${enc(id)}/disable`);
}
function refreshProvider(id) {
mutate('POST', `/admin/model-providers/${enc(id)}/refresh`, undefined, { done: 'Odświeżono modele.' });
}
function enableProvider(id) {
mutate('PATCH', '/admin/model-providers/' + enc(id), { is_active: true });
}