Repository navigation
Phase 3: Widget model menu, BYOK key field, deployment configuration - #381
Merged
neuromechanist merged 16 commits intoSep 17, 2026
Conversation
Add OfferedModelResponse and an offered_models field to CommunityConfigResponse, populated from OFFERED_MODELS in anthropic_llm.py, so the widget can build its model menu from the backend's real offer list instead of a hand-maintained copy. Drop the "(default)" suffix from the Haiku label: which model is default is already carried by default_model in the same response, and baking it into the label creates a second source of truth. Add a drift test asserting offered_models matches OFFERED_MODELS, each id resolves through normalize_model, and default_model is one of the offered ids; and a test guarding the labels against policy words creeping back in.
… BYOK key Model menu: DEFAULT_MODELS becomes a two-entry fallback (claude-haiku-4-5, claude-sonnet-5) used only until fetchCommunityConfig's offered_models response arrives; the live list now drives the settings dropdown and getModelLabel. The saved-settings and custom-model regexes, which rejected every first-party id the backend now returns, are replaced by a shared isValidModelId() that accepts both a bare first-party id and the legacy provider/model form. The custom-model field label now says it needs a caller's own OpenRouter key, matching what the backend enforces. BYOK key: userSettings gains keyProvider, derived from the key's own prefix (sk-ant- -> anthropic, sk-or-v1- -> openrouter) rather than stored as a separate choice, so settings saved before this change keep working without re-entering a key. Validation on load and save accepts either key shape. The request now sends X-Anthropic-API-Key or X-OpenRouter-Key depending on which key was entered.
The backend already emits a thinking SSE event carrying no reasoning text. The widget used to log it as an unknown event; it now sets an isThinking flag while the model is reasoning, before the first content chunk arrives, and reuses the existing loading label (no new UI) to show "Thinking..." instead of the community title. The flag is cleared on the first content chunk and at the end of every send, and scoped to before the first content chunk on purpose so a thinking event arriving between tool calls mid-answer cannot make the label flicker under already-rendered text. Reasoning text itself is never rendered.
Add X-Anthropic-API-Key to the CORS allow-list, the forwarded BYOK header set, and the Turnstile-bypass check, so an Anthropic BYOK key can reach the backend from a browser: previously the preflight rejected it, the header was never forwarded even if it passed, and a caller providing only that key was still forced through Turnstile. Drop X-OpenRouter-Model, X-OpenRouter-Provider, and X-OpenRouter-Temperature from the allow-list and forwarding list. Phase 2 deleted the backend extractor that read them, so the backend has ignored them for a while now. Update the README's architecture diagram and BYOK section to document both key types.
Remove openrouter_api_key_env_var from hed, bids, fieldtrip, and openneuropet's config.yaml. None of the four named env vars is set on the server, so every request for these communities logged an ERROR in _resolve_provider and silently fell back to the platform key; if anyone ever set one, that community would silently leave the Claude Platform. The schema field stays supported for a community that genuinely funds itself through OpenRouter. Add a test asserting no shipped config.yaml sets the field (dynamic over the registry, not hardcoded ids) alongside one confirming a synthetic config that does set it still validates. Several existing dynamic tests that looked for a community with the field configured now skip gracefully, which is the intended behavior of their existing pytest.skip fallback.
…Anthropic platform
.env.example was still documenting the pre-migration world (LLM_PROVIDER,
Ollama, an OpenRouter-format DEFAULT_MODEL, and a long tail of variables
no Settings field, deploy script, or workflow reads any more: ALLOW_BYOK,
DATABASE_URL, ENABLE_TELEMETRY, FEEDBACK_DIR, LOG_LEVEL, GITHUB_REPO,
SYNC_*_CRON, API_HOST/API_PORT/API_WORKERS, EXTRA_CORS_ORIGINS,
ALLOW_LOCALHOST_CORS, LANGFUSE_ENVIRONMENT). Rewrite it around the three
ANTHROPIC_* credentials plus the thinking/output/cache-ttl tuning
variables, DEFAULT_MODEL/TEST_MODEL on claude-haiku-4-5, and HOST/PORT
under the names Settings actually reads, with OpenRouter documented as
the BYOK-only path.
deploy/docker-compose.yml: add the ANTHROPIC_* variables to the
environment block and delete the DEFAULT_MODEL / DEFAULT_MODEL_PROVIDER
lines. Those two were a live bug: the block overrides env_file, and
compose interpolates ${DEFAULT_MODEL} from deploy/.env (which does not
exist), so the stale openai/gpt-oss-120b default always won over
whatever the real .env said. env_file already supplies both from ../.env.
Update deploy/DEPLOYMENT_ARCHITECTURE.md and README.md's docker run
examples and community-key section to lead with the Anthropic platform,
with OpenRouter kept as the BYOK alternative. Update the pyproject.toml
llm marker description, which still named OPENROUTER_API_KEY_FOR_TESTING
as the credential every llm-marked test needs; most of them exercise the
Anthropic path now.
Add tests/test_deploy/test_deploy_config.py: parses docker-compose.yml
to assert no DEFAULT_MODEL/DEFAULT_MODEL_PROVIDER leak into the
environment block, and parses .env.example to assert every anthropic_*
Settings field is documented and DEFAULT_MODEL/TEST_MODEL are real
offered model ids (dynamic over Settings.model_fields and OFFERED_MODELS,
not hardcoded).
deploy/Dockerfile installed with `uv pip install --system ".[server]"`, which ignores uv.lock: the image ships whatever PyPI resolves on build day, which is how Phase 1 shipped a different langchain-anthropic than it was developed against. Switch to a frozen `uv sync` against the lockfile instead. UV_PROJECT_ENVIRONMENT=/usr/local keeps packages where the existing CMD already finds them, and --no-install-project is correct because the container runs from /app/src on sys.path, never from the installed distribution. uv.lock is already in the build context since there is no .dockerignore. CI keeps `uv pip install --system` for now (resolves forward, the safe direction); that's a separate follow-up.
.github/workflows/test.yml ran the whole "integration or llm" suite with only OPENROUTER_API_KEY in the environment, then ran one Anthropic-only file in a second step gated on ANTHROPIC_API_KEY. After the platform migration most of the integration/llm suite targets Anthropic, so the broad step would fail on main with only an OpenRouter key. Fold the two steps into one: run the full suite gated on the Anthropic key being present, with both the Anthropic credentials and OPENROUTER_API_KEY available in the environment (some tests still need the OpenRouter key for OpenRouter-specific coverage). .github/workflows/docker-build.yml's smoke test passed OPENROUTER_API_KEY=test-key-for-ci to a container that only answers /health; use ANTHROPIC_API_KEY instead so the smoke test documents what the image actually expects.
compute_community_health read only config.openrouter_api_key_env_var, but _resolve_provider (src/api/routers/community.py) checks the Anthropic env var first. A community that correctly funds itself with an Anthropic key was reporting api_key="using_platform", status="degraded", and a public warning telling its maintainer to configure a key they had already configured. Mirror _resolve_provider's precedence exactly: the Anthropic env var decides configured/missing when set, falling back to the OpenRouter one, then the platform. Warning wording, status mapping, and the public-endpoint redaction (env var names never leak into public warnings) are unchanged; only which field is consulted. Add regression coverage in tests/test_api/test_health.py: a community configured with anthropic_api_key_env_var reports configured/healthy when that env var is set, and missing/error naming that env var when it is not. Confirmed both new tests fail against the pre-fix compute_community_health (git stash of the health.py change) before trusting them.
Five tests dynamically searched the registry for a community with openrouter_api_key_env_var configured; since #363 removed that field from every shipped config.yaml, they silently skipped instead of exercising the code path. The field is still supported for a community that funds its own OpenRouter usage, so the path still needs coverage. Replace the search with monkeypatch.setattr on a real, registered CommunityConfig object (the pattern already used for the equivalent Anthropic-key tests in test_authorization.py), clearing anthropic_api_key_env_var on the same config so the OpenRouter branch under test is the one actually reached (both _resolve_provider and compute_community_health check it first). - test_authorization.py: _community_with_openrouter_env_var() now takes monkeypatch and configures "hed" directly instead of searching; both call sites updated. - test_health.py: converts the two compute_community_health tests from bare os.environ manipulation to monkeypatch, alongside the anthropic-path tests added in the prior commit. - test_community_router.py: the public-metrics test builds a fresh router via create_community_router("hed") bound to the just-patched config, rather than reusing the module-level app fixture. That app's community routes close over whatever registry snapshot existed the first time src.api.main was imported in the test session; other test modules' own discover_assistants() calls run later and replace the registry's CommunityConfig objects with new ones carrying the same values but a different identity, so a freshly-fetched object is not reliably the one an already-built route reads. Building an isolated router right after the monkeypatch sidesteps that. Skip count drops from 18 to 13; none of the remaining skips mention openrouter_api_key_env_var.
…e values
deploy/docker-compose.yml's environment: block used the
`- FOO=${FOO:-default}` interpolation form for every entry. That form
resolves at compose time from the shell (or deploy/.env, which does
not exist), NOT from env_file, and silently overrides whatever
env_file provides -- verified with `docker compose config`: with
env_file providing REAL_SECRET=value-from-env-file, an environment:
entry of `- REAL_SECRET=${REAL_SECRET:-}` renders as REAL_SECRET: ""
regardless.
This is the same defect the prior commit removed for DEFAULT_MODEL,
just not limited to it: every entry in the block had it, including
API_KEYS, OPENROUTER_API_KEY, OPENAI_API_KEY, the ANTHROPIC_* set,
GITHUB_TOKEN, SEMANTIC_SCHOLAR_API_KEY, PUBMED_API_KEY, and both
LangFuse keys. Anyone following this file's own header instructions
(copy ../.env.example to ../.env, docker-compose up -d) got a
container with every secret blanked and every tuning default pinned,
which sends the platform straight down _platform_choice's OpenRouter
fallback -- the precise failure this epic exists to eliminate.
Production is unaffected because deploy/deploy.sh uses
`docker run --env-file` and never touches compose.
Every variable that was in the block has a genuine default on Settings
(src/api/config.py), so the fix is to delete the block entirely rather
than add more entries to it: env_file already supplies every one of
them, and letting Settings' own defaults apply when a variable is
absent is correct. Replaced with a comment explaining why the block is
empty and what to check before adding an entry back.
Extend tests/test_deploy/test_deploy_config.py with
test_environment_block_never_uses_var_default_interpolation, which
asserts no entry in the environment: block (if any exist at all) uses
the ${VAR:-...} form, checked dynamically over the block's actual
contents rather than a hardcoded list of names. Confirmed it fails
against the pre-fix file before trusting it.
Three documentation fixes in files this phase already touches: - The widget's custom-model label used an em dash. - deploy/DEPLOYMENT_ARCHITECTURE.md's docker run and .env examples named API_KEY, but the Settings field and env var are API_KEYS (plural, comma-separated), so following either example verbatim left the server with no configured key. - deploy/Dockerfile's trailing reference block listed SYNC_GITHUB_CRON and SYNC_PAPERS_CRON, which nothing reads, and did not mention the three ANTHROPIC_ variables the image now needs to answer a request at all.
loadUserSettings had four failure branches (corrupted JSON, localStorage access error, invalid saved key, invalid saved model); each either tried to call showError guarded by "container && isOpen" or only logged to console. init() calls loadUserSettings/loadHistory before createWidget, so the container query always returned null and isOpen was still false: none of the four branches could ever reach the user. A saved BYOK key that failed validation was dropped with no explanation, and every later request silently billed the platform key instead. Queue the failure reason in a module-level pending notice and flush it through the existing showError presentation the first time the widget is actually opened (toggleChat and the fullscreen init path), instead of trying to render at init time. Routes loadHistory's corrupted-history case through the same mechanism; its return value was already discarded at the call site, so a load failure was previously invisible. Also: - offered_models: warn when a config response omits it (or ships it empty) and the widget falls back to DEFAULT_MODELS, matching the default_model check just above it, without disabling the widget. - BYOK header selection: make the anthropic/openrouter branch explicit instead of treating "not anthropic" as "openrouter", so an unrecognized keyProvider can never send the wrong header; log and drop the key instead.
Three constants are hand-duplicated across Python, the widget JS, and the Cloudflare Worker JS with nothing keeping them in sync: DEFAULT_MODELS vs OFFERED_MODELS, the widget's BYOK key regexes vs the backend's log redaction pattern, and the worker's CORS/byokHeaders lists vs the BYOK headers security.py actually resolves into a credential. Each is correct today; each can drift silently, and the worker case would only surface as a real browser's CORS preflight rejecting a request, with every Python test staying green. Parses the JS files as text (no JS test harness in this project) and derives expected values from the real Python source at test time, the same way tests/test_deploy/test_deploy_config.py parses deployment files. Verified each test actually fails by perturbing the corresponding JS constant before trusting it.
test_authorized_origin_uses_community_anthropic_key claimed Anthropic wins over OpenRouter but only ever set the Anthropic field; since hed no longer ships an openrouter_api_key_env_var, an implementation that checked OpenRouter first would find it unset, fall through to Anthropic anyway, and still pass. Set both fields, with OpenRouter pointing at a populated, distinct env var, so a reversed-precedence implementation actually fails the assertion (verified by temporarily reversing the precedence check and confirming the test catches it, then reverting). compute_community_health had the identical untested precedence gap. Added a test that leaves the Anthropic env var unset and the OpenRouter one populated: correct precedence still reports "missing" (it commits to whichever env var name it selects, regardless of whether that one is actually set), while a reversed implementation would find OpenRouter's populated value and incorrectly report "configured". Also verified by reversing the precedence check and confirming the test fails. _community_without_configured_keys() searched the registry for a community with neither key env var configured, and skipped (taking six tests with it) once every shipped community had one -- an easier way to lose coverage than the single-community helper beside it. Hardened it the same way: monkeypatch a real, registered CommunityConfig directly instead of searching for one that qualifies. Added a test for get_community_config's platform-default branch (default_model = settings.default_model when the community config has none), previously exercised by no test since every shipped community sets its own default_model.
…gured deploy.sh only set --env-file when deploy/.env existed, with no else: a missing .env meant the container started with no environment at all, /health returned healthy regardless (it checks nothing), and the script printed "Deployment complete!" and exited 0. This is the mechanism CLAUDE.md documents as the real deploy path, and it now stands between a deploy and the Anthropic credentials. auto-update.sh and auto-update-dev.sh run unattended from cron and had the same shape (a logged warning, then deploy anyway). Made all three fail loudly and exit non-zero instead: deploy.sh via its existing error_exit, naming the expected path; the two auto-update scripts to their own log output, since a cron job's only visibility is its log file. Verified by running each script with stubbed docker/curl against a directory with and without .env: all three now exit 1 with a clear message when it is missing, and behave as before when it is present.
Contributor
Preview Deployment
This preview will be updated automatically when you push new commits. |
neuromechanist
merged commit Sep 17, 2026
84a6854
into
feature/issue-360-epic-anthropic-platform
5 checks passed
This was referenced Sep 17, 2026
Merged
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Makes the Claude Platform migration reachable from a browser and brings the deployment configuration in line with it. Phases 1 (#365) and 2 (#368) moved the server to the Claude Platform on AWS but changed nothing a user can see: the widget still offered eight OpenRouter models, discarded every model id the backend now returns, accepted only an OpenRouter-shaped key, and ignored the
thinkingevent the backend already emits. The Cloudflare Worker never allowed or forwardedX-Anthropic-API-Key, so Anthropic BYOK could not have worked from a browser even once the widget sent it.Closes #363
Part of epic #360
Widget
offered_models, populated fromOFFERED_MODELS, so the menu cannot advertise a model the backend would reject. The old list carried a "Last updated: 2026-03" comment and had already drifted; narrowing it by hand would only have reset that clock. A two-entry fallback covers an older backend.isValidModelId()replaces two regexes that required a slash. Both would have silently droppedclaude-haiku-4-5from localStorage on every load.X-Anthropic-API-KeyorX-OpenRouter-Keyto match. The accepted formats mirror the server's own redaction patterns insrc/core/logging.py.Worker
X-Anthropic-API-Keyadded to the CORS allow-list, the forwarded header list, and the Turnstile BYOK bypass. All three were needed, and each failed differently on its own: preflight rejection, a key that never reaches the backend while the platform quietly pays, and a BYOK caller still forced through Turnstile. The three deadX-OpenRouter-Model/-Provider/-Temperatureheaders are gone, since Phase 2 deleted the extractor that read them.Configuration and deployment
openrouter_api_key_env_varfrom the four community configs that still named it. Those env vars are not set on the server, so_resolve_providerwas logging an ERROR and falling back to the platform key on every request for hed, bids, fieldtrip and openneuropet. The schema field stays supported..env.examplerewritten around the Anthropic platform, with every variable that nothing reads removed, and OpenRouter documented as the BYOK-only path.deploy/docker-compose.yml: theenvironment:block was overridingenv_filewith compose-time values.DEFAULT_MODELwas pinned toopenai/gpt-oss-120bthat way, and every credential in the block was being blanked to"". Verified withdocker compose config. The block now leaves those toenv_file.deploy/Dockerfileinstalls fromuv.lockinstead of resolving against PyPI on build day. That divergence is how Phase 1 shipped a differentlangchain-anthropicthan it was developed against.integration or llmsuite with only an OpenRouter key, which stops making sense once those tests target the platform.Fixes found along the way
compute_community_healthonly consultedopenrouter_api_key_env_var, so a community funded by theanthropic_api_key_env_varthat Phase 2 added, the one_resolve_providerchecks first, reportedusing_platform/degradedand publicly warned its maintainer to configure a key they had already configured. Health now mirrors the resolution order.Test plan
offered_modelsmatchesOFFERED_MODELSand every id survivesnormalize_model; no shipped community config setsopenrouter_api_key_env_var; the composeenvironment:block uses no${VAR:-...}form; everyanthropic_*Settings field is documented in.env.example;DEFAULT_MODEL/TEST_MODELthere are real offered ids.docker buildfrom the worktree succeeds with the locked install, and the container answers/health..envon hedtools already carries the sixANTHROPIC_*variables, appended additively and verified byte-identical for the prior 157 lines. TheDEFAULT_MODELflip and the pruning of dead variables happen at epic-merge time with the deploy.Review round
Three reviewers ran over the full diff. No critical findings in the implementation itself. Everything substantive was either a pre-existing issue this phase made newly load-bearing, or a test that proved less than its docstring claimed. Fixed here:
loadUserSettingshad four failure branches that could never reach the user:init()calls it beforecreateWidget(), so thecontainerthey check is always null. A user whose saved BYOK key failed validation lost it silently and every later request billed the platform key instead. Notices are now queued and shown when the widget opens.test_authorized_origin_uses_community_anthropic_keyclaimed Anthropic wins over OpenRouter but never set the OpenRouter field, so a reversed implementation would have passed. It now sets both, and the same gap incompute_community_healthis covered. Both were confirmed to fail against a deliberately reversed implementation.DEFAULT_MODELS, its two key-format regexes, and the worker's two header lists were hand-duplicated from Python with nothing keeping them in sync; the worker case would have failed only in a real browser's CORS preflight while every Python test stayed green. The worker's expected headers are derived fromByokCredential.provider'sLiteralvalues rather than hardcoded, so adding a provider forces the worker to keep up.deploy/deploy.shand both auto-update scripts omitted--env-filesilently when.envwas missing, and/healthreports healthy regardless of configuration, so an unconfigured container deployed and reported success. Now a hard failure. The cron scripts exit non-zero to their log.offered_modelson an otherwise successful response now warns instead of falling back silently.Considered and declined, with reasons:
isValidModelIdaccepts the literal strings "default" and "custom", which requires deliberately typing a sentinel value into the custom-model field and yields a clean 400 listing the offered models; and the custom-model label points at OpenRouter while the validator also accepts bare ids, an advanced-user edge case with a clear backend error.Filed as follow-ups rather than widened into this phase: #374 (CI installs without the lockfile), #376 (tests that skip themselves when shipped config changes), #377 (the widget's JS test harness is not wired into CI and re-implements what it tests), #378 (a misconfigured community key is only discoverable by polling an auth-gated endpoint).