Skip to content

Phase 3: Widget model menu, BYOK key field, deployment configuration - #381

Merged
neuromechanist merged 16 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-363-phase3-widget-deploy
Sep 17, 2026
Merged

neuromechanist merged 16 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-363-phase3-widget-deploy

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

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 thinking event the backend already emits. The Cloudflare Worker never allowed or forwarded X-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

  • The model menu is served, not hard-coded. The community config endpoint gained offered_models, populated from OFFERED_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.
  • One shared isValidModelId() replaces two regexes that required a slash. Both would have silently dropped claude-haiku-4-5 from localStorage on every load.
  • The key field takes either credential. The provider is inferred from the key's own prefix rather than stored as a separate choice, so settings saved before this phase keep working, and the request goes out on X-Anthropic-API-Key or X-OpenRouter-Key to match. The accepted formats mirror the server's own redaction patterns in src/core/logging.py.
  • The thinking indicator reuses the existing loading element: the label reads "Thinking..." until the first token, then the community title. Scoped to before the first content chunk so a thinking event between tool calls does not make the label flicker under text already on screen. Reasoning text is never rendered.

Worker

X-Anthropic-API-Key added 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 dead X-OpenRouter-Model/-Provider/-Temperature headers are gone, since Phase 2 deleted the extractor that read them.

Configuration and deployment

  • Dropped openrouter_api_key_env_var from the four community configs that still named it. Those env vars are not set on the server, so _resolve_provider was 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.example rewritten around the Anthropic platform, with every variable that nothing reads removed, and OpenRouter documented as the BYOK-only path.
  • deploy/docker-compose.yml: the environment: block was overriding env_file with compose-time values. DEFAULT_MODEL was pinned to openai/gpt-oss-120b that way, and every credential in the block was being blanked to "". Verified with docker compose config. The block now leaves those to env_file.
  • deploy/Dockerfile installs from uv.lock instead of resolving against PyPI on build day. That divergence is how Phase 1 shipped a different langchain-anthropic than it was developed against.
  • CI: the integration job now carries the Anthropic credentials. It was running the whole integration or llm suite with only an OpenRouter key, which stops making sense once those tests target the platform.

Fixes found along the way

compute_community_health only consulted openrouter_api_key_env_var, so a community funded by the anthropic_api_key_env_var that Phase 2 added, the one _resolve_provider checks first, reported using_platform/degraded and publicly warned its maintainer to configure a key they had already configured. Health now mirrors the resolution order.

Test plan

  • Full unit suite green.
  • New drift tests: offered_models matches OFFERED_MODELS and every id survives normalize_model; no shipped community config sets openrouter_api_key_env_var; the compose environment: block uses no ${VAR:-...} form; every anthropic_* Settings field is documented in .env.example; DEFAULT_MODEL/TEST_MODEL there are real offered ids.
  • Five tests that had started skipping (the community-key resolution and health-warning paths) now configure the field on a real registered config instead of scanning for a community that sets it, so they exercise the real code path again.
  • New health coverage for the Anthropic community-key case, confirmed failing before the fix.
  • docker build from the worktree succeeds with the locked install, and the container answers /health.
  • Server .env on hedtools already carries the six ANTHROPIC_* variables, appended additively and verified byte-identical for the prior 157 lines. The DEFAULT_MODEL flip 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:

  • loadUserSettings had four failure branches that could never reach the user: init() calls it before createWidget(), so the container they 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_key claimed 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 in compute_community_health is covered. Both were confirmed to fail against a deliberately reversed implementation.
  • Cross-language drift tests. The widget's 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 from ByokCredential.provider's Literal values rather than hardcoded, so adding a provider forces the worker to keep up.
  • deploy/deploy.sh and both auto-update scripts omitted --env-file silently when .env was missing, and /health reports 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.
  • The BYOK header branch no longer treats an unrecognized provider as OpenRouter, and a missing offered_models on an otherwise successful response now warns instead of falling back silently.

Considered and declined, with reasons: isValidModelId accepts 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).

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.
@github-actions

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-363-phase3-wid-demo.osc.earth
Branch feature/issue-363-phase3-widget-deploy
Commit 2ac7d88

This preview will be updated automatically when you push new commits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant