Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(llm): add QwenCloud as an OpenAI-compatible provider (#6578)

LearningCircuitec977faa1193
diff --git a/changelog.d/+error-rewrite-deepseek-requesty.bugfix.md b/changelog.d/+error-rewrite-deepseek-requesty.bugfix.md
new file mode 100644
index 0000000000..5e1304986c
--- /dev/null
+++ b/changelog.d/+error-rewrite-deepseek-requesty.bugfix.md
@@ -0,0 +1 @@
+When research with the DeepSeek or Requesty LLM providers fails with an OpenAI-compatible runtime error (connection refused, timeout, authentication, ...), the server log now names the provider and its real endpoint (and the model, where the error identifies one), like every other OpenAI-compatible cloud provider, instead of a generic status-code message; the research page shows the matching category message and hint. The context-overflow dashboard likewise now shows their proper provider names instead of raw ids. In addition, these logged errors no longer name the unrelated `llm.openai_endpoint.url` value as the endpoint for providers other than the custom OpenAI endpoint when research is started from chat or a follow-up, and the research page's messages and hints for OpenAI-compatible errors no longer assume a local LLM server (they also apply to cloud providers).
diff --git a/changelog.d/+mask-api-key-toast-research-page.security.md b/changelog.d/+mask-api-key-toast-research-page.security.md
new file mode 100644
index 0000000000..d9940c873a
--- /dev/null
+++ b/changelog.d/+mask-api-key-toast-research-page.security.md
@@ -0,0 +1 @@
+Saving an LLM provider API key from the research page no longer echoes the secret value in the success toast; the confirmation now names the provider (for example "qwen api_key updated") without displaying the key. Saved endpoint URLs, which can embed credentials, are confirmed the same way (for example "ollama url updated").
diff --git a/changelog.d/+model-refresh-after-api-key-save.feature.md b/changelog.d/+model-refresh-after-api-key-save.feature.md
new file mode 100644
index 0000000000..5f34cd1c39
--- /dev/null
+++ b/changelog.d/+model-refresh-after-api-key-save.feature.md
@@ -0,0 +1,3 @@
+Saving an LLM provider API key on the research page now refreshes just that provider's model catalog immediately (merged into the cached catalog, with stale in-flight responses discarded; the refreshed models expire from the 24h cache together with the other providers' cached models, so the other providers' models are never hidden while only the refreshed provider's models remain cached) instead of leaving its models hidden behind the 24h model cache until a manual refresh. Pasted API keys with surrounding whitespace no longer fail model discovery while working for research. The targeted refresh is a CSRF-protected `POST /settings/api/available-models?refresh_provider=<provider>` (a POST without `refresh_provider` re-discovers every provider); a `GET` carrying `refresh_provider` or `force_refresh=true` returns 405 and never contacts a provider or rewrites the model cache.
+
+On the research page, overlapping refreshes preserve successful updates for each provider, including when a full catalog reload overlaps a provider refresh, and policy reloads prevent older responses from restoring disabled cloud providers. On the server, refreshes using an API key or endpoint that has since changed cannot overwrite newer cached models.
diff --git a/changelog.d/+redact-base-url-query-credentials.security.md b/changelog.d/+redact-base-url-query-credentials.security.md
new file mode 100644
index 0000000000..20de0f7af2
--- /dev/null
+++ b/changelog.d/+redact-base-url-query-credentials.security.md
@@ -0,0 +1 @@
+Credentials embedded in a configured LLM or embeddings base URL are now redacted in these log lines: the OpenAI-compatible provider's LLM-creation (INFO) and model-listing (DEBUG) messages; the Ollama provider's LLM-creation (INFO) and client (DEBUG) messages and the "Checking Ollama availability at ..." (INFO) line of its availability check (when that check's request fails or times out, the shared request helper's warning already shows no more than the URL's scheme, host and port); the OpenAI embeddings provider's keyless-endpoint and model-listing (INFO) messages; the research start route's endpoint and Ollama-URL fallback messages; the research worker's "Research parameters" line (which retains main's stricter origin-only redaction); the friendly error message for OpenAI-compatible LLM failures; and URL-valued settings in the `LDR_LOG_SETTINGS=debug` settings dump, for dict and non-dict settings alike: values containing `://`, scheme-less `user:password@host` values with any host (the user may be empty, as in `:password@host`; surrounding whitespace ignored; the password may contain whitespace, a newline included, but not start with it), and whitespace-free scheme-less values with a query or fragment such as `localhost:1234/v1?api_key=...`; a scheme-less `name@host` value without a password is not treated as a URL. Redaction removes `user:password@` userinfo (also without a scheme); replaces the values of credential-named parameters in the query string, the fragment and `;` path parameters (a name is split into words at camelCase boundaries and at every character other than an ASCII letter or digit, so `accessToken`, `XAPIKey`, `x-api-key`, `api+key` and `key%00` are all split; it matches when its last word is `key`, `apikey`, `token`, `secret`, `password`, `passwd`, `pwd`, `pass`, `passphrase`, `signature`, `sig`, `credential`, `credentials`, `jwt`, `session`, `assertion` or `verifier` (so the OAuth grant secrets `assertion`, `client_assertion`, `code_verifier` and `oauth_verifier` match); when its last word ends in `token`, `secret`, `password`, `passwd`, `passphrase`, `assertion` or `verifier` (run-together names such as `authtoken`, `APITOKEN`, `clientsecret` and `clientassertion`); when its last word ends in one of the compounds `apikey`, `appkey`, `accesskey`, `authkey`, `clientkey`, `encryptionkey`, `licensekey`, `masterkey`, `passkey`, `privatekey`, `secretkey`, `sessionkey`, `signingkey` or `subscriptionkey` -- other words ending in `key`, such as `monkey`, do not match; or when the whole name, ignoring letter case and every character other than an ASCII letter or digit, is `auth`, `authorization`, `bearer`, `code`, `sas`, `refresh`, `device_code`, `id_token_hint`, `auth_code` or `authorization_code` (so `deviceCode`, `devicecode`, `IDTOKENHINT` and `authCode` match, while `force_refresh` and `login_hint` do not). Each of these tests is also run with a trailing number or version taken off the name (final words that are digits or `v` plus digits are dropped, then trailing digits, and a `v` just before them, come off the last word) and once more with a plural `s` also taken off the last word unless it ends in `ss`, so `api_key_2`, `apiKey2`, `key1`, `token2`, `access_token_v2`, `x-api-key-v2` and `api_keys` match while `page2`, `items` and `v2` do not; non-secret names such as `sort_keys` and `max_tokens` are redacted too. For an array-style name, the text before and inside each bracket is checked on its own and all-digit or empty indexes are ignored, so `api_key[0]`, `key[]`, `auth[token]`, `api_key[prod]` and `api_key[a][b]` all match, while `items[0]` and `data[name]` do not. A name longer than 256 characters is treated as a credential name without being inspected); replaces any value-less query or fragment item of 17 or more characters; and replaces path segments shaped like a provider key (`sk-`/`key-` in any letter case plus 16 or more characters, or 32 or more letters, digits and underscores containing both a letter and a digit and no `-`). When the userinfo cannot be isolated reliably the whole URL is logged as `<unknown>`: that is the case for any `@` in the path, query or fragment, with or without a scheme (including a harmless `[email protected]`); for a non-numeric port, as happens when a password contains an unencoded `/`, `?` or `#`, or an `@` followed by one of those; and for an authority containing `;`, `&` or `=` (`https://host;api_key=...`). Any value longer than 4096 characters is also logged as `<unknown>` without being parsed, which bounds the work redaction does on a user-supplied endpoint. Other log lines that print URLs are unchanged, as is third-party libraries' own debug logging (such as the openai SDK's request log), which can still print the full URL.
diff --git a/changelog.d/6578.breaking.md b/changelog.d/6578.breaking.md
new file mode 100644
index 0000000000..86973c3600
--- /dev/null
+++ b/changelog.d/6578.breaking.md
@@ -0,0 +1 @@
+Refreshing the model list now requires a CSRF-protected `POST /settings/api/available-models`. `GET /settings/api/available-models?force_refresh=true`, which cleared and re-discovered the whole model cache without a CSRF check, now returns 405 (`Allow: POST`) and changes nothing; send a `POST` with the session's CSRF token instead (add `?refresh_provider=<provider>` to refresh a single provider). The research, settings and benchmark pages already refresh this way; plain `GET` model-list reads are unchanged.
diff --git a/changelog.d/6578.bugfix.md b/changelog.d/6578.bugfix.md
new file mode 100644
index 0000000000..c769e739f0
--- /dev/null
+++ b/changelog.d/6578.bugfix.md
@@ -0,0 +1 @@
+Preserve provider-neutral LLM error guidance in saved research reports and status responses, while retaining safe messages from older runs and rejecting appended provider details.
diff --git a/changelog.d/6578.feature.md b/changelog.d/6578.feature.md
new file mode 100644
index 0000000000..bb1d45edf8
--- /dev/null
+++ b/changelog.d/6578.feature.md
@@ -0,0 +1 @@
+Add QwenCloud as a built-in OpenAI-compatible LLM provider, using its pay-as-you-go endpoint (`https://maas.qwencloudapi.com/compatible-mode/v1`). Enter a pay-as-you-go API key from home.qwencloud.com in the research page's advanced options or in settings, pick QwenCloud as the LLM provider, and choose one of its chat models for research. Token Plan subscription keys (`sk-sp-`) use a different endpoint and are not supported by this provider.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 8be0ec683b..f06fc08079 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -134,8 +134,8 @@ They are not available in the Web UI because they are needed to start the applic
| `llm.context_window_size` | `LDR_LLM_CONTEXT_WINDOW_SIZE` | `128000` | Maximum context window size in tokens for cloud LLMs. Only used when unrestricted context is disabled. | LLM |
| `llm.context_window_unrestricted` | `LDR_LLM_CONTEXT_WINDOW_UNRESTRICTED` | `true` | Let cloud provider APIs manage their own token limits without a hard cap (recommended). Uncheck to enforce a specific limit via the Context Window Size setting. | LLM |
| `llm.deepseek.api_key` | `LDR_LLM_DEEPSEEK_API_KEY` | `null` | API key to use for the DeepSeek provider. | LLM |
-| `llm.google.api_key` | `LDR_LLM_GOOGLE_API_KEY` | `null` | API key to use for the Google Gemini provider. | SEARCH |
-| `llm.ionos.api_key` | `LDR_LLM_IONOS_API_KEY` | `null` | API key to use for the IONOS AI Model Hub provider. | SEARCH |
+| `llm.google.api_key` | `LDR_LLM_GOOGLE_API_KEY` | `null` | API key to use for the Google Gemini provider. | LLM |
+| `llm.ionos.api_key` | `LDR_LLM_IONOS_API_KEY` | `null` | API key to use for the IONOS AI Model Hub provider. | LLM |
| `llm.llamacpp.api_key` | `LDR_LLM_LLAMACPP_API_KEY` | `` | Optional API key for `llama-server` if it's behind an auth proxy. Leave empty if your llama-server has no authentication. | LLM |
| `llm.llamacpp.url` | `LDR_LLM_LLAMACPP_URL` | `http://localhost:8080/v1` | HTTP endpoint URL where llama.cpp's `llama-server` is running. Include the full path with /v1 (default: http://localhost:8080/v1). Run `llama-server -m <model.gguf>` to start it. | LLM |
| `llm.lmstudio.api_key` | `LDR_LLM_LMSTUDIO_API_KEY` | `` | Optional API key for LM Studio if you've enabled authentication. Leave empty for the default no-auth setup. | LLM |
@@ -151,11 +151,12 @@ They are not available in the Web UI because they are needed to start the applic
| `llm.openai_endpoint.api_key` | `LDR_LLM_OPENAI_ENDPOINT_API_KEY` | `` | API key for your custom OpenAI-compatible endpoint. For cloud services (OpenRouter, Groq), use your actual API key. For local servers (llama.cpp, vLLM), you can leave this blank — LDR will substitute a placeholder automatically. | LLM |
| `llm.openai_endpoint.stream_usage` | `LDR_LLM_OPENAI_ENDPOINT_STREAM_USAGE` | `false` | Request token usage statistics on streamed responses (sends stream_options.include_usage). Enable this if the token metrics dashboard shows zero token counts for streamed calls. Supported by LM Studio (0.3.18+), llama.cpp server, vLLM, and OpenRouter. Leave disabled if your endpoint rejects requests with a 'stream_options' error (e.g. some API gateways). | LLM |
| `llm.openai_endpoint.url` | `LDR_LLM_OPENAI_ENDPOINT_URL` | `https://openrouter.ai/api/v1` | URL of a custom OpenAI-compatible API endpoint. Use for llama.cpp server, vLLM, Ollama, OpenRouter, Groq, Together, or any service that implements the OpenAI API format. Example for local llama.cpp: http://localhost:8000/v1 | LLM |
-| `llm.openrouter.api_key` | `LDR_LLM_OPENROUTER_API_KEY` | `null` | API key to use for the OpenRouter provider. | SEARCH |
-| `llm.orcarouter.api_key` | `LDR_LLM_ORCAROUTER_API_KEY` | `null` | API key to use for the OrcaRouter provider. | SEARCH |
+| `llm.openrouter.api_key` | `LDR_LLM_OPENROUTER_API_KEY` | `null` | API key to use for the OpenRouter provider. | LLM |
+| `llm.orcarouter.api_key` | `LDR_LLM_ORCAROUTER_API_KEY` | `null` | API key to use for the OrcaRouter provider. | LLM |
| `llm.provider` | `LDR_LLM_PROVIDER` | `ollama` | The LLM service provider. Choose local providers (Ollama, LM Studio, LlamaCpp) for free on-device inference, or cloud APIs (OpenAI, Anthropic, Google, OpenRouter) for hosted models. | LLM |
+| `llm.qwen.api_key` | `LDR_LLM_QWEN_API_KEY` | `null` | API key to use for the QwenCloud provider. | LLM |
| `llm.request_timeout` | `LDR_LLM_REQUEST_TIMEOUT` | `1800` | Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit; values below 1 second are clamped to 1, and non-numeric or non-finite values use the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively. | LLM |
-| `llm.requesty.api_key` | `LDR_LLM_REQUESTY_API_KEY` | `null` | API key to use for the Requesty provider. | SEARCH |
+| `llm.requesty.api_key` | `LDR_LLM_REQUESTY_API_KEY` | `null` | API key to use for the Requesty provider. | LLM |
| `llm.require_local_endpoint` | `LDR_LLM_REQUIRE_LOCAL_ENDPOINT` | `false` | When enabled, the LLM provider's resolved endpoint must be on a local network (loopback, RFC1918, link-local). Cloud-only providers (OpenAI, Anthropic, Google, OpenRouter) are blocked. Independent of egress_scope. | LLM |
| `llm.supports_max_tokens` | `LDR_LLM_SUPPORTS_MAX_TOKENS` | `true` | Feature flag for max_tokens parameter. Disable if your LLM API returns errors when max_tokens is set. When disabled, the parameter is not passed to the API. | LLM |
| `llm.temperature` | `LDR_LLM_TEMPERATURE` | `0.7` | Controls randomness in model outputs. Lower values (0.0-0.3) produce deterministic, factual responses; higher values (0.7-1.0) produce more creative and varied outputs. | LLM |
diff --git a/docs/api-quickstart.md b/docs/api-quickstart.md
index 676f64131a..a2425becbf 100644
--- a/docs/api-quickstart.md
+++ b/docs/api-quickstart.md
@@ -139,6 +139,7 @@ Settings endpoints are under `/settings/api/`:
- `GET /settings/api/{key}` - Get specific setting
- `PUT /settings/api/{key}` - Update setting
- `GET /settings/api/available-models` - Get available LLM providers
+- `POST /settings/api/available-models?refresh_provider=<provider>` - Re-discover one provider's models (CSRF token required; a POST without `refresh_provider` refreshes every provider, and a `GET` with `refresh_provider` or `force_refresh=true` returns 405)
- `GET /settings/api/available-search-engines` - Get search engines
### History Endpoints
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 080418af36..77ae7558a7 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -742,6 +742,10 @@
"label": "OrcaRouter API",
"value": "orcarouter"
},
+ {
+ "label": "QwenCloud API",
+ "value": "qwen"
+ },
{
"label": "xAI Grok API",
"value": "xai"
diff --git a/src/local_deep_research/defaults/llm_providers/google_settings.json b/src/local_deep_research/defaults/llm_providers/google_settings.json
index 02ab14f1f4..b6168affb1 100644
--- a/src/local_deep_research/defaults/llm_providers/google_settings.json
+++ b/src/local_deep_research/defaults/llm_providers/google_settings.json
@@ -8,7 +8,7 @@
"name": "Google API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/src/local_deep_research/defaults/llm_providers/ionos_settings.json b/src/local_deep_research/defaults/llm_providers/ionos_settings.json
index 93b28da976..a0f6c6ce28 100644
--- a/src/local_deep_research/defaults/llm_providers/ionos_settings.json
+++ b/src/local_deep_research/defaults/llm_providers/ionos_settings.json
@@ -8,7 +8,7 @@
"name": "IONOS API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/src/local_deep_research/defaults/llm_providers/openrouter_settings.json b/src/local_deep_research/defaults/llm_providers/openrouter_settings.json
index 4828e4397e..33470d6925 100644
--- a/src/local_deep_research/defaults/llm_providers/openrouter_settings.json
+++ b/src/local_deep_research/defaults/llm_providers/openrouter_settings.json
@@ -8,7 +8,7 @@
"name": "OpenRouter API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/src/local_deep_research/defaults/llm_providers/orcarouter_settings.json b/src/local_deep_research/defaults/llm_providers/orcarouter_settings.json
index f6f58e6888..17a3f59bd2 100644
--- a/src/local_deep_research/defaults/llm_providers/orcarouter_settings.json
+++ b/src/local_deep_research/defaults/llm_providers/orcarouter_settings.json
@@ -8,7 +8,7 @@
"name": "OrcaRouter API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/src/local_deep_research/defaults/llm_providers/qwen_settings.json b/src/local_deep_research/defaults/llm_providers/qwen_settings.json
new file mode 100644
index 0000000000..6b1108fb9c
--- /dev/null
+++ b/src/local_deep_research/defaults/llm_providers/qwen_settings.json
@@ -0,0 +1,16 @@
+{
+ "llm.qwen.api_key": {
+ "category": "llm_general",
+ "description": "API key to use for the QwenCloud provider.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "QwenCloud API Key",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "password",
+ "value": null,
+ "visible": true
+ }
+}
diff --git a/src/local_deep_research/defaults/llm_providers/requesty_settings.json b/src/local_deep_research/defaults/llm_providers/requesty_settings.json
index 969b464ce5..6a56e77e69 100644
--- a/src/local_deep_research/defaults/llm_providers/requesty_settings.json
+++ b/src/local_deep_research/defaults/llm_providers/requesty_settings.json
@@ -8,7 +8,7 @@
"name": "Requesty API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/src/local_deep_research/embeddings/providers/implementations/openai.py b/src/local_deep_research/embeddings/providers/implementations/openai.py
index 5d0aae1398..64ae0339d4 100644
--- a/src/local_deep_research/embeddings/providers/implementations/openai.py
+++ b/src/local_deep_research/embeddings/providers/implementations/openai.py
@@ -10,6 +10,7 @@ from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
from ....security.ssrf_validator import assert_base_url_safe
+from ....security.url_redaction import redact_url_credentials
from ....utilities.url_utils import normalize_url
from ..base import BaseEmbeddingProvider, Exposure
@@ -107,7 +108,7 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
"OpenAI embeddings: no API key set but base_url={} "
"is configured — using placeholder key for the "
"OpenAI-compatible endpoint.",
- base_url,
+ redact_url_credentials(base_url),
)
api_key = cls._PLACEHOLDER_API_KEY
else:
@@ -423,7 +424,7 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
logger.info(
"Fetched {} models from OpenAI endpoint{}",
len(models),
- f" at {base_url}" if base_url else "",
+ f" at {redact_url_credentials(base_url)}" if base_url else "",
)
return models
diff --git a/src/local_deep_research/error_handling/error_messages.py b/src/local_deep_research/error_handling/error_messages.py
index e797e19fac..20842794d3 100644
--- a/src/local_deep_research/error_handling/error_messages.py
+++ b/src/local_deep_research/error_handling/error_messages.py
@@ -10,17 +10,20 @@ TYPED_RESEARCH_ERROR_MESSAGES = {
"model_not_found": "The configured LLM model was not found.",
"connection_error": "Could not connect to the configured LLM server.",
"api_error": "The language model API rejected the request.",
- "openai_connection_refused": "Could not connect to the configured LLM server.",
- "openai_timeout": "The configured LLM server timed out.",
+ "openai_connection_refused": "Could not connect to the configured LLM endpoint.",
+ "openai_timeout": "The configured LLM endpoint timed out.",
"openai_auth": "Authentication with the LLM provider failed.",
"openai_permission_denied": "The LLM provider denied access to the model.",
- "openai_model_not_found": "The configured LLM model was not found.",
- "openai_bad_request": "The LLM server rejected the request.",
+ "openai_model_not_found": "The configured model was not found at the LLM endpoint.",
+ "openai_bad_request": "The LLM endpoint rejected the request.",
"openai_unknown": "The configured LLM provider returned an error.",
"openai_rate_limit": "The LLM provider rate-limited the request.",
}
_SAFE_WORKER_MESSAGES = frozenset(TYPED_RESEARCH_ERROR_MESSAGES.values()) | {
+ # Keep authored messages from older saved reports recognizable.
+ "The configured LLM server timed out.",
+ "The LLM server rejected the request.",
"Ollama AI service is unavailable. Please check that Ollama is running properly on your system.",
"Required Ollama model not found. Please pull the model first.",
"Connection error with LLM service. Please check that your AI service is running.",
diff --git a/src/local_deep_research/error_handling/openai_compat_errors.py b/src/local_deep_research/error_handling/openai_compat_errors.py
index 97b68685c7..32d81d58e4 100644
--- a/src/local_deep_research/error_handling/openai_compat_errors.py
+++ b/src/local_deep_research/error_handling/openai_compat_errors.py
@@ -16,12 +16,12 @@ communicate.
from __future__ import annotations
from types import ModuleType
-from urllib.parse import urlparse, urlunparse
import httpx
import openai
from ..security.log_sanitizer import sanitize_error_message
+from ..security.url_redaction import redact_url_credentials
# openai 3.x makes its requests through httpx2, so its transport errors are
# httpx2 classes and are unrelated to the httpx ones imported above. openai 2.x
@@ -37,32 +37,10 @@ _CONNECT_ERRORS = tuple(m.ConnectError for m in _TRANSPORT_MODULES)
_READ_TIMEOUTS = tuple(m.ReadTimeout for m in _TRANSPORT_MODULES)
-def _strip_credentials(base_url: str | None) -> str:
- """Return ``base_url`` with any userinfo (``user:password@``) removed.
-
- Users sometimes embed an API key directly in the base URL (e.g.
- ``https://user:key@host/v1``). We must never echo that back to the UI or
- logs. Falsy / unparseable inputs are returned as ``"<unknown>"``.
- """
- if not base_url:
- return "<unknown>"
- try:
- parsed = urlparse(base_url)
- except Exception:
- return "<unknown>"
- if not parsed.netloc:
- return base_url
- host = parsed.hostname or ""
- # urlparse exposes IPv6 hostnames without their surrounding brackets;
- # re-add them when reassembling the netloc, or the rebuilt URL is
- # not parseable by downstream HTTP libraries (e.g. ``http://::1:8080/``
- # is ambiguous: is the host ``::`` and the port ``1:8080``?). IPv4
- # never contains ``:`` so this heuristic is safe.
- if ":" in host:
- host = f"[{host}]"
- if parsed.port:
- host = f"{host}:{parsed.port}"
- return urlunparse(parsed._replace(netloc=host)) or "<unknown>"
+# Base-URL credential redaction lives in ``security.url_redaction`` so the
+# provider and router modules that log a base URL can share it without an
+# import cycle; the private alias keeps this module's historical name.
+_strip_credentials = redact_url_credentials
def _is_dispatchable(exc: BaseException) -> bool:
diff --git a/src/local_deep_research/llm/providers/base.py b/src/local_deep_research/llm/providers/base.py
index 5b3f211545..483deafe17 100644
--- a/src/local_deep_research/llm/providers/base.py
+++ b/src/local_deep_research/llm/providers/base.py
@@ -13,9 +13,21 @@ def normalize_provider(provider):
"""Normalize provider name to lowercase canonical form.
All provider comparisons in route/service code should use
- this function to ensure consistent casing.
+ this function to ensure consistent casing. Surrounding whitespace is
+ stripped too (a hand-edited or env-supplied ``" qwen "``); a
+ whitespace-only value normalises to None like any other empty value.
+
+ Only ``str`` input is stripped. Any other truthy value keeps the
+ pre-strip contract exactly: it is duck-typed through ``.lower()``, so a
+ list/int still raises ``AttributeError`` (callers and the contract
+ tests rely on that), and an object that only implements ``lower()``
+ passes through as before instead of failing on a missing ``strip()``.
"""
- return provider.lower() if provider else None
+ if not provider:
+ return None
+ if isinstance(provider, str):
+ return provider.strip().lower() or None
+ return provider.lower()
class BaseLLMProvider:
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index dbf54bc1f5..c29ede5f70 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -9,6 +9,7 @@ from ....security import safe_get
from ....security.secure_logging import logger
from ....security.log_sanitizer import scrub_error
from ....security.ssrf_validator import assert_base_url_safe
+from ....security.url_redaction import redact_url_credentials
from ....utilities.url_utils import normalize_url
from ..base import BaseLLMProvider, Exposure
@@ -148,7 +149,8 @@ class OllamaProvider(BaseLLMProvider):
base_url = assert_base_url_safe(base_url, setting_key="llm.ollama.url")
logger.info(
- f"Creating ChatOllama with model={model_name}, base_url={base_url}"
+ f"Creating ChatOllama with model={model_name}, "
+ f"base_url={redact_url_credentials(base_url)}"
)
# Build Ollama parameters
@@ -215,7 +217,8 @@ class OllamaProvider(BaseLLMProvider):
# Log the actual client configuration after creation
logger.debug(
- f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}"
+ "ChatOllama created - base_url attribute: "
+ f"{redact_url_credentials(getattr(llm, 'base_url', None))}"
)
return llm
@@ -251,7 +254,10 @@ class OllamaProvider(BaseLLMProvider):
safe_msg = scrub_error(e)
logger.warning("Ollama {}", safe_msg)
return False
- logger.info(f"Checking Ollama availability at {base_url}/api/tags")
+ logger.info(
+ "Checking Ollama availability at "
+ f"{redact_url_credentials(base_url)}/api/tags"
+ )
# Get authentication headers
headers = cls._get_auth_headers(settings_snapshot=settings_snapshot)
diff --git a/src/local_deep_research/llm/providers/implementations/qwen.py b/src/local_deep_research/llm/providers/implementations/qwen.py
new file mode 100644
index 0000000000..92a48f8662
--- /dev/null
+++ b/src/local_deep_research/llm/providers/implementations/qwen.py
@@ -0,0 +1,39 @@
+"""QwenCloud LLM provider for Local Deep Research."""
+
+from ..base import Exposure
+from ..openai_base import OpenAICompatibleProvider
+
+
+class QwenCloudProvider(OpenAICompatibleProvider):
+ """QwenCloud provider using its OpenAI-compatible endpoint.
+
+ QwenCloud (Alibaba's Qwen cloud platform) exposes an OpenAI-compatible
+ API through its pay-as-you-go compatible-mode endpoint. API keys
+ are issued at home.qwencloud.com/api-keys.
+ """
+
+ provider_name = "QwenCloud"
+ api_key_setting = "llm.qwen.api_key"
+ default_base_url = "https://maas.qwencloudapi.com/compatible-mode/v1"
+ # Informational only (create_llm requires an explicit llm.model): the
+ # flagship model from QwenCloud's own first-API-call quickstart, kept
+ # concrete like deepseek/atlascloud rather than the "" no-fallback
+ # convention used by providers without an obvious default.
+ default_model = "qwen3.8-max"
+
+ # Metadata for auto-discovery
+ provider_key = "QWEN"
+ company_name = "QwenCloud"
+ is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
+
+ @classmethod
+ def requires_auth_for_models(cls):
+ """QwenCloud requires authentication for listing models.
+
+ ``GET /compatible-mode/v1/models`` returns 401 without a valid
+ Bearer key (verified live), so model discovery only runs once the
+ API key is configured.
+ """
+ return True
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 25c0119349..e8ec40f211 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -11,6 +11,7 @@ from ...security.secure_logging import logger
# be unaffected by patching the source module.
from ...security.log_sanitizer import redact_secrets, scrub_error
from ...security.ssrf_validator import assert_base_url_safe
+from ...security.url_redaction import redact_url_credentials
from ...utilities.url_utils import normalize_url
from ._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
@@ -146,7 +147,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
logger.info(
f"Creating {cls.provider_name} LLM with model: {model_name}, "
- f"temperature: {temperature}, endpoint: {base_url}"
+ f"temperature: {temperature}, "
+ f"endpoint: {redact_url_credentials(base_url) if base_url else None}"
)
return ChatOpenAI(**llm_params)
@@ -313,6 +315,12 @@ class OpenAICompatibleProvider(BaseLLMProvider):
)
return []
+ # Trim a pasted key the same way create_llm's resolve_api_key
+ # does — otherwise a key with surrounding whitespace works for
+ # research but fails model discovery with a bare auth error.
+ if isinstance(api_key, str):
+ api_key = api_key.strip()
+
# Check if auth is required
if cls.requires_auth_for_models():
if not api_key:
@@ -368,7 +376,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
# Fetch models
logger.debug(
- f"Fetching models from {cls.provider_name} at {base_url}"
+ f"Fetching models from {cls.provider_name} at "
+ f"{redact_url_credentials(base_url) if base_url else None}"
)
models_response = client.models.list()
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index 2635321621..71397f88af 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -1495,6 +1495,7 @@ _CLOUD_LLM_PROVIDERS = frozenset(
"requesty",
"orcarouter",
"atlascloud",
+ "qwen",
"deepseek",
"xai",
"ionos",
diff --git a/src/local_deep_research/security/url_redaction.py b/src/local_deep_research/security/url_redaction.py
new file mode 100644
index 0000000000..54acf8a6cc
--- /dev/null
+++ b/src/local_deep_research/security/url_redaction.py
@@ -0,0 +1,381 @@
+"""Redact credentials embedded in a configured URL before it is logged.
+
+Operators sometimes put an API key straight into an LLM base URL -- as
+userinfo (``https://user:key@host/v1``), as a query or fragment parameter
+(``?api_key=...``, ``#access_token=...``), as a ``;`` path parameter
+(``/v1;api_key=...``), or as a bare path segment (``/sk-.../v1``).
+:func:`redact_url_credentials` removes or masks those while keeping the URL
+legible for troubleshooting.
+
+Dependency-free on purpose (``re`` / ``urllib`` only), so provider, router
+and error-handling modules can all import it without an import cycle.
+"""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import unquote_plus, urlsplit, urlunsplit
+
+REDACTED = "REDACTED"
+
+# A parameter NAME is a credential name when any of its PARTS is. The
+# parts of a PHP/Rails-style array name are the text around its ``[`` /
+# ``]`` brackets (``api_key[0]`` -> ``api_key``; ``auth[token]`` ->
+# ``auth``, ``token``; ``api_key[prod]`` -> ``api_key``, ``prod``); an
+# all-digit or empty part (an index) is ignored, and a stray bracket
+# (``api_key]``) simply ends a part. A part is normalised by splitting
+# camelCase (``accessToken`` -> ``access_token``, ``XAPIKey`` ->
+# ``XAPI_Key``), lower-casing, and splitting into words on every character
+# that is not an ASCII letter or digit (``_``, ``-``, ``.``, whitespace --
+# ``api+key`` decodes to ``api key`` -- and also ``%00``, ``:`` and the
+# like). A part is a credential name when EITHER
+# * its last word is in ``_CREDENTIAL_SUFFIX_WORDS`` (so ``api_key``,
+# ``x-api-key``, ``subscription-key``, ``access_token``, ``authToken``,
+# ``clientSecret``, ``x-amz-signature``, ``db.password``,
+# ``passphrase``, and the OAuth grant secrets ``assertion``,
+# ``client_assertion`` (RFC 7521/7523), ``code_verifier`` (RFC 7636)
+# and ``oauth_verifier`` (RFC 5849) all match), OR
+# * its last word is a run-together compound: it ends in one of
+# ``_RUN_TOGETHER_SUFFIXES`` (``authtoken``, ``APITOKEN``,
+# ``clientsecret``, ``clientassertion``, ``dbpassword``,
+# ``keypassphrase``) or in one of the ``...key`` words of
+# ``_RUN_TOGETHER_KEY_NAMES`` (``apikey``, ``xapikey``, ``secretkey``,
+# ``privatekey``). ``key`` itself is NOT a run-together suffix, because
+# ordinary words end in it (``monkey``, ``turkey``, ``hockey``); a
+# ``...key`` compound outside that list (``fookey``) is not matched, OR
+# * its words, joined without separators, are one of
+# ``_CREDENTIAL_EXACT_NAMES`` -- credential names that cannot be
+# matched by their ending without also matching ordinary names:
+# ``code`` (``error_code``), ``auth`` (``oauth``), ``refresh``
+# (``force_refresh``), ``device_code`` (RFC 8628; ``country_code``),
+# ``id_token_hint`` (it carries an OpenID Connect ID token;
+# ``login_hint``) and the OAuth authorization code ``auth_code`` /
+# ``authorization_code`` (RFC 6749). Joining makes ``device_code``,
+# ``deviceCode`` and the run-together ``devicecode`` / ``DEVICECODE``
+# one name.
+# Each of these tests is also run with a trailing number or version taken
+# off the part -- final words that are digits or ``v`` + digits are
+# dropped, then trailing digits (and a ``v`` just before them) come off the
+# last word -- and once more with a plural ``s`` also taken off the last
+# word (not when it ends in ``ss``). So ``api_key_2``, ``apiKey2``,
+# ``key1``, ``token2``, ``access_token_v2``, ``x-api-key-v2`` and
+# ``api_keys`` match, while ``page2``, ``items`` and ``v2`` do not; this
+# only ever adds matches.
+# Other words match only as a whole word, so ``tokenizer``, ``passthrough``,
+# ``monkey`` and ``keyboard`` never match. Errs towards over-redaction: a
+# non-secret ``sort_key``, ``sort_keys``, ``max_tokens`` or
+# ``api_key[prod]`` is redacted too, and a name longer than
+# ``_MAX_PARAM_NAME_LEN`` is treated as a credential name without being
+# inspected (fail closed, and bounded work).
+_CREDENTIAL_SUFFIX_WORDS = frozenset(
+ {
+ "key",
+ "apikey",
+ "token",
+ "secret",
+ "password",
+ "passwd",
+ "pwd",
+ "pass",
+ "passphrase",
+ "signature",
+ "sig",
+ "credential",
+ "credentials",
+ "jwt",
+ "session",
+ "assertion",
+ "verifier",
+ }
+)
+_RUN_TOGETHER_SUFFIXES = (
+ "token",
+ "secret",
+ "password",
+ "passwd",
+ "passphrase",
+ "assertion",
+ "verifier",
+)
+_RUN_TOGETHER_KEY_NAMES = (
+ "apikey",
+ "appkey",
+ "accesskey",
+ "authkey",
+ "clientkey",
+ "encryptionkey",
+ "licensekey",
+ "masterkey",
+ "passkey",
+ "privatekey",
+ "secretkey",
+ "sessionkey",
+ "signingkey",
+ "subscriptionkey",
+)
+# Stored without separators: compared with a part's words joined by "".
+_CREDENTIAL_EXACT_NAMES = frozenset(
+ name.replace("_", "")
+ for name in (
+ "sas",
+ "auth",
+ "authorization",
+ "bearer",
+ "code",
+ "refresh",
+ "device_code",
+ "id_token_hint",
+ "auth_code",
+ "authorization_code",
+ )
+)
+# A final name word that is a number or a version (``2``, ``v2``).
+_NUMBER_OR_VERSION_WORD_RE = re.compile(r"v?[0-9]+")
+# Longest parameter name inspected word by word; a longer one is treated
+# as a credential name. Real parameter names are far shorter.
+_MAX_PARAM_NAME_LEN = 256
+# Longest value :func:`redact_url_credentials` parses; a longer one is
+# logged as ``<unknown>``. A configured base URL is far shorter; the cap
+# bounds the work done in (often unconditional) log lines on a value a
+# user can supply.
+MAX_REDACTABLE_URL_LEN = 4096
+_CAMEL_BOUNDARY_RE = re.compile(
+ r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])"
+)
+_NAME_WORD_SEPARATOR_RE = re.compile(r"[^a-z0-9]+")
+_ARRAY_BRACKET_RE = re.compile(r"[\[\]]")
+# ``?`` is a separator too: ``?x=1?api_key=...`` (a repeated ``?``) and a
+# value that embeds a URL (``next=https://h/p?token=...``) both carry their
+# credential after a ``?`` that ``urlsplit`` leaves inside the query.
+_PARAM_SEPARATORS_RE = re.compile(r"([&;?])")
+# A value-less query/fragment item at least this long (``?sk-...``) is
+# assumed to be a bare credential.
+_BARE_ITEM_REDACT_MIN_LEN = 17
+# Path segments shaped like a provider key:
+# * ``sk-`` / ``key-`` in any letter case (``SK-``, ``Key-``) + 16 or
+# more base64url characters, or
+# * 32+ characters of ``[A-Za-z0-9_]`` -- NO ``-`` -- containing both a
+# letter and a digit.
+# Excluding ``-`` keeps hyphenated model and deployment names
+# (``text-embedding-3-large-2024-preview-model``, UUIDs) legible. The
+# trade-offs: a dash-bearing key without an ``sk-``/``key-`` prefix (some
+# Google keys) is not caught, and a 32-hex id such as a Cloudflare account
+# id IS redacted (over-redaction, the safe direction).
+_KEY_LIKE_SEGMENT_RE = re.compile(
+ r"^(?:(?:sk|key)-[A-Za-z0-9_\-]{16,}"
+ r"|(?=[A-Za-z0-9_]*[A-Za-z])(?=[A-Za-z0-9_]*[0-9])[A-Za-z0-9_]{32,})$",
+ # ASCII: without it, IGNORECASE lets the classes match four non-ASCII
+ # letters too (U+0130, U+0131, U+017F, U+212A).
+ re.IGNORECASE | re.ASCII,
+)
+_PORT_RE = re.compile(r"[0-9]+")
+# Characters that never belong in a host we log: a ``;`` / ``&`` / ``=``
+# after the host means parameters (``https://host;api_key=...``) ended up
+# inside the parsed authority, where they would not be redacted.
+_AUTHORITY_PARAM_CHARS_RE = re.compile(r"[;&=]")
+# End of a scheme-less value's leading authority-like part.
+_AUTHORITY_END_RE = re.compile(r"[/?#]")
+_HTTP_SCHEMES = frozenset({"http", "https"})
+
+
+def _name_variants(words: list[str]) -> list[list[str]]:
+ """``words`` as given, without a trailing number or version, and
+ without that and a plural ``s`` (see the rule above). A last word that
+ the stripping would leave empty (``v2``, ``s``) is kept as it was."""
+ trimmed = list(words)
+ while len(trimmed) > 1 and _NUMBER_OR_VERSION_WORD_RE.fullmatch(
+ trimmed[-1]
+ ):
+ trimmed.pop()
+ last = trimmed[-1]
+ stem = last.rstrip("0123456789")
+ if stem != last and stem.endswith("v"):
+ stem = stem[:-1]
+ if stem:
+ trimmed[-1] = stem
+ variants = [words, trimmed]
+ last = trimmed[-1]
+ if len(last) > 1 and last.endswith("s") and not last.endswith("ss"):
+ variants.append([*trimmed[:-1], last[:-1]])
+ return variants
+
+
+def _words_name_a_credential(words: list[str]) -> bool:
+ """The three tests of the rule above, for one spelling of a part."""
+ if "".join(words) in _CREDENTIAL_EXACT_NAMES:
+ return True
+ last = words[-1]
+ return (
+ last in _CREDENTIAL_SUFFIX_WORDS
+ or last.endswith(_RUN_TOGETHER_SUFFIXES)
+ or last.endswith(_RUN_TOGETHER_KEY_NAMES)
+ )
+
+
+def _is_credential_name_part(part: str) -> bool:
+ """The rule above for one bracket-free part of a parameter name."""
+ words = [
+ w
+ for w in _NAME_WORD_SEPARATOR_RE.split(
+ _CAMEL_BOUNDARY_RE.sub("_", part).lower()
+ )
+ if w
+ ]
+ if not words:
+ return False
+ return any(_words_name_a_credential(v) for v in _name_variants(words))
+
+
+def is_credential_param_name(raw_name: str) -> bool:
+ """Return True when a URL parameter name names a credential.
+
+ Linear in the length of the name, and a name longer than
+ ``_MAX_PARAM_NAME_LEN`` is reported
+ as a credential name without further inspection."""
+ if len(raw_name) > _MAX_PARAM_NAME_LEN:
+ return True
+ return any(
+ _is_credential_name_part(part)
+ for part in _ARRAY_BRACKET_RE.split(unquote_plus(raw_name))
+ if part.strip() and not part.strip().isdigit()
+ )
+
+
+def _redact_param_list(params: str, *, redact_bare: bool) -> str:
+ """Redact credential values in a ``&`` / ``;`` / ``?`` separated list,
+ keeping every other parameter and separator unchanged."""
+ if not params:
+ return params
+ out = []
+ for piece in _PARAM_SEPARATORS_RE.split(params):
+ if piece in ("&", ";", "?"):
+ out.append(piece)
+ continue
+ name, sep, _value = piece.partition("=")
+ if sep and is_credential_param_name(name):
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: URL parameter text
+ piece = f"{name}={REDACTED}"
+ elif (
+ not sep and redact_bare and len(piece) >= _BARE_ITEM_REDACT_MIN_LEN
+ ):
+ piece = REDACTED
+ out.append(piece)
+ return "".join(out)
+
+
+def _redact_path(path: str) -> str:
+ """Redact ``;name=value`` path parameters and key-shaped segments."""
+ segments = []
+ for segment in path.split("/"):
+ head, sep, params = segment.partition(";")
+ if _KEY_LIKE_SEGMENT_RE.match(head):
+ head = REDACTED
+ if sep:
+ params = _redact_param_list(params, redact_bare=False)
+ segments.append(f"{head}{sep}{params}")
+ return "/".join(segments)
+
+
+def _drop_schemeless_userinfo(url: str) -> str:
+ """``user:secret@host/v1`` (no ``//``) parses with ``user`` as the
+ scheme and the secret in the path; drop everything up to the ``@`` of
+ the leading authority-like part, which ends at the first ``/``, ``?``
+ or ``#``. An ``@`` only later in the value (a password containing one
+ of those such as ``user:Abc/123@host``, or an ``@`` in the query or
+ fragment such as ``host?x=a@b``) is left for the caller's fail-closed
+ ``@`` check."""
+ head = _AUTHORITY_END_RE.split(url, maxsplit=1)[0]
+ if "@" in head:
+ return url[head.rindex("@") + 1 :]
+ return url
+
+
+def _authority_is_well_formed(authority: str) -> bool:
+ """True when ``host[:port]`` (or ``[v6][:port]``) has an empty or
+ all-digit port. A non-digit "port" means ``urlsplit`` cut the
+ authority short -- typically at a ``/``, ``?`` or ``#`` inside an
+ unencoded password -- so the real userinfo was never isolated. Also
+ False when the authority holds a ``;``, ``&`` or ``=``
+ (``host;api_key=...``): parameters there are not redacted."""
+ if _AUTHORITY_PARAM_CHARS_RE.search(authority):
+ return False
+ if authority.startswith("["):
+ close = authority.find("]")
+ if close == -1:
+ return False
+ rest = authority[close + 1 :]
+ if not rest:
+ return True
+ if not rest.startswith(":"):
+ return False
+ port = rest[1:]
+ else:
+ port = authority.rpartition(":")[2] if ":" in authority else ""
+ return not port or bool(_PORT_RE.fullmatch(port))
+
+
+def redact_url_credentials(url: object) -> str:
+ """Return ``url`` with embedded credentials removed, for logging.
+
+ * userinfo (``user:pass@``) is dropped -- also for a scheme-less
+ ``user:pass@host/v1``;
+ * in the query string, the fragment, and ``;`` path parameters, the
+ value of every credential-named parameter (see the name rule above;
+ ``&``, ``;`` and ``?`` all separate parameters) becomes ``REDACTED``;
+ * a value-less query or fragment item of 17+ characters (``?sk-...``)
+ becomes ``REDACTED``;
+ * a path segment shaped like a provider key (see
+ ``_KEY_LIKE_SEGMENT_RE``) becomes ``REDACTED``.
+
+ Fails closed -- returns ``"<unknown>"`` -- when the userinfo cannot be
+ isolated reliably: any ``@`` in the path, query or fragment (so the
+ count of ``@`` in the value differs from the count in the parsed
+ authority -- this includes a harmless ``[email protected]``), or an
+ authority whose port is not all digits (an unencoded ``/``, ``?`` or
+ ``#`` in a password ends the authority early), or an authority that
+ contains ``;``, ``&`` or ``=`` (``https://host;api_key=...``).
+ Non-string and empty inputs, and any value longer than
+ ``MAX_REDACTABLE_URL_LEN`` characters, also return ``"<unknown>"``;
+ the function never raises, and its work is linear in the input.
+
+ The scheme is lower-cased (``urlsplit`` does that); the host (with its
+ original case) and the port are kept as given; the rest of the URL is
+ kept unchanged except for the replacements above (``urlsplit`` also
+ drops an empty trailing ``?`` or ``#``).
+
+ Limits: a credential under a name the rule does not recognise, a short
+ or non key-shaped path segment, and percent-encoded separators inside a
+ value are not detected.
+ """
+ if not isinstance(url, str) or not url or len(url) > MAX_REDACTABLE_URL_LEN:
+ return "<unknown>"
+ try:
+ parsed = urlsplit(url)
+ if not parsed.netloc and parsed.scheme.lower() not in _HTTP_SCHEMES:
+ stripped = _drop_schemeless_userinfo(url)
+ if stripped != url:
+ url = stripped
+ parsed = urlsplit(url)
+ except ValueError:
+ return "<unknown>"
+ if url.count("@") != parsed.netloc.count("@"):
+ # An @ outside the authority (path, query or fragment): either the
+ # userinfo was not isolated -- a password containing ``@`` and then
+ # ``/``, ``?`` or ``#`` splits across the authority boundary -- or a
+ # scheme-less value still carries one after stripping. Also covers
+ # an innocent ``[email protected]``: withheld rather than guessed.
+ return "<unknown>"
+ redacted = parsed._replace(
+ path=_redact_path(parsed.path),
+ query=_redact_param_list(parsed.query, redact_bare=True),
+ fragment=_redact_param_list(parsed.fragment, redact_bare=True),
+ )
+ if parsed.netloc:
+ authority = parsed.netloc.rpartition("@")[2]
+ if not _authority_is_well_formed(authority):
+ return "<unknown>"
+ redacted = redacted._replace(netloc=authority)
+ elif redacted == parsed:
+ # Nothing to redact: pass a scheme-less value through as given.
+ return url or "<unknown>"
+ return urlunsplit(redacted) or "<unknown>"
diff --git a/src/local_deep_research/settings/logger.py b/src/local_deep_research/settings/logger.py
index 8fbd2cd5a0..279e5b6b81 100644
--- a/src/local_deep_research/settings/logger.py
+++ b/src/local_deep_research/settings/logger.py
@@ -10,6 +10,7 @@ Environment variable LDR_LOG_SETTINGS controls the verbosity:
"""
import os
+import re
from collections.abc import Mapping
from typing import Any, Dict, Optional
from loguru import logger
@@ -83,7 +84,7 @@ def log_settings(
elif log_level == "debug":
# Log full settings at DEBUG level with redaction
if isinstance(settings, dict):
- safe_settings = redact_sensitive_keys(settings)
+ safe_settings = _redact_url_values(redact_sensitive_keys(settings))
logger.debug(f"{message} (redacted): {safe_settings}")
else:
# Non-dict settings get the same redaction: coerce to a dict
@@ -115,9 +116,10 @@ def log_settings(
elif hasattr(settings, "__dict__"):
coerced = dict(vars(settings))
if coerced is not None:
- logger.debug(
- f"{message} (redacted): {redact_sensitive_keys(coerced)}"
+ safe_coerced = _redact_url_values(
+ redact_sensitive_keys(coerced)
)
+ logger.debug(f"{message} (redacted): {safe_coerced}")
else:
logger.debug(_unredactable_shape_message())
except Exception:
@@ -143,6 +145,57 @@ _SENSITIVE_KEY_PATTERNS = (
)
+# ``user:password@host...`` without a scheme (matched after leading
+# whitespace is stripped). The user part -- possibly empty, as in
+# ``:TOKEN@host/v1`` -- has no whitespace, ``@``, ``:`` or ``/``. Two
+# forms:
+# * a password with no whitespace or ``@`` up to the first ``@`` -- any
+# host may follow (``ollama_server``, an IDN, ``[fe80::1%eth0]``);
+# * a password that contains whitespace (a newline too) or ``@`` but does
+# not START with whitespace, followed by a host-like part (no
+# whitespace, ``@``, ``/``, ``?`` or ``#``) and then ``/``, ``?``,
+# ``#``, whitespace or the end.
+# A password must not start with whitespace, so prose such as
+# ``"Note: mail [email protected]"`` is not mistaken for userinfo. Known
+# limits: a password that begins with whitespace is not recognised, and
+# neither is a token-only ``TOKEN@host`` (no ``:``). The pattern is
+# anchored and its backtracking is linear in the value's length.
+_SCHEMELESS_USERINFO_RE = re.compile(
+ r"^[^\s@:/]*:(?:[^\s@]*@|[^\s@][\s\S]*@[^\s@/?#]+(?:[/?#\s]|$))"
+)
+
+
+def _looks_like_url(value: str) -> bool:
+ """Whether a setting value should go through the URL redactor: it
+ contains ``://``, starts with scheme-less userinfo, or is a single
+ whitespace-free token (surrounding whitespace ignored) with a query or
+ fragment (a scheme-less ``localhost:1234/v1?api_key=...``)."""
+ token = value.strip()
+ if "://" in token or _SCHEMELESS_USERINFO_RE.match(token):
+ return True
+ return ("?" in token or "#" in token) and not any(
+ c.isspace() for c in token
+ )
+
+
+def _redact_url_values(value: Any) -> Any:
+ """Redact credentials embedded in URL-valued settings (e.g. an
+ ``llm.openai_endpoint.url`` of ``https://host/v1?api_key=...``) for the
+ debug settings log. Key-name redaction alone misses them because the
+ setting's key (``*.url``) is not sensitive. See ``_looks_like_url``
+ for which strings are treated as URLs."""
+ if isinstance(value, dict):
+ return {k: _redact_url_values(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_redact_url_values(v) for v in value]
+ if isinstance(value, str) and _looks_like_url(value):
+ # Lazy import: the security package imports settings modules.
+ from ..security.url_redaction import redact_url_credentials
+
+ return redact_url_credentials(value)
+ return value
+
+
def is_sensitive_setting_key(key: str) -> bool:
"""Return True if the setting key should be redacted in responses."""
key_lower = key.lower()
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index d46fef307a..803204321b 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -448,8 +448,8 @@ def _perform_post_login_tasks_body(
"step 3 (auth DB + scheduler notify)", step_start, username
)
- # Model cache refresh is handled by /api/settings/available-models
- # via its 24h TTL and explicit force_refresh=true flag.
+ # Model cache refresh is handled by POST /settings/api/available-models;
+ # ordinary GET reads use its 24h TTL.
# 4. Schedule background database backup if enabled
step_start = time.perf_counter()
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 07d0368b0c..e03c0ff62d 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -47,6 +47,7 @@ from ...database.models import (
)
from ...database.session_context import get_user_db_session
from ...exceptions import DuplicateResearchError, SystemAtCapacityError
+from ...llm.providers.base import normalize_provider
from ...settings.manager import SettingsManager
from ...utilities.formatting import short_id
from ..auth.password_utils import get_user_password, resolve_user_password
@@ -1155,9 +1156,16 @@ async def send_message(
search_engine = settings_snapshot.get("search.tool", {}).get(
"value", ""
)
- custom_endpoint = settings_snapshot.get(
- "llm.openai_endpoint.url", {}
- ).get("value")
+ # llm.openai_endpoint.url is only the client's base URL for
+ # the openai_endpoint provider; passing it for any other
+ # provider mislabels that provider's endpoint downstream.
+ custom_endpoint = (
+ settings_snapshot.get("llm.openai_endpoint.url", {}).get(
+ "value"
+ )
+ if normalize_provider(model_provider) == "openai_endpoint"
+ else None
+ )
# Defensive fallbacks kept in sync with default_settings.json.
user_strategy = settings_snapshot.get(
"search.search_strategy", {}
@@ -1710,9 +1718,14 @@ async def retry_attempt(
search_engine = settings_snapshot.get("search.tool", {}).get(
"value", ""
)
- custom_endpoint = settings_snapshot.get(
- "llm.openai_endpoint.url", {}
- ).get("value")
+ # Only meaningful for the openai_endpoint provider (see above).
+ custom_endpoint = (
+ settings_snapshot.get("llm.openai_endpoint.url", {}).get(
+ "value"
+ )
+ if normalize_provider(model_provider) == "openai_endpoint"
+ else None
+ )
user_strategy = settings_snapshot.get(
"search.search_strategy", {}
).get("value", "langgraph-agent")
diff --git a/src/local_deep_research/web/routers/followup.py b/src/local_deep_research/web/routers/followup.py
index fc1316ff32..dc1735d5db 100644
--- a/src/local_deep_research/web/routers/followup.py
+++ b/src/local_deep_research/web/routers/followup.py
@@ -532,7 +532,14 @@ def _start_followup_sync(data, username):
model_provider=model_provider, # Pass model provider
model=model, # Pass model name
search_engine=search_engine, # Pass search engine
- custom_endpoint=custom_endpoint, # Pass custom endpoint if any
+ # llm.openai_endpoint.url is only the client's base URL for
+ # the openai_endpoint provider; don't label other providers
+ # with it.
+ custom_endpoint=(
+ custom_endpoint
+ if model_provider == "openai_endpoint"
+ else None
+ ),
strategy="enhanced-contextual-followup", # Use enhanced contextual follow-up strategy
iterations=research_params["max_iterations"],
questions_per_iteration=research_params[
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index f1431ab09f..79a64b4e81 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -48,6 +48,7 @@ from ...security import (
strip_settings_snapshot,
)
from ...security.log_sanitizer import redact_and_bound_for_log
+from ...security.url_redaction import redact_url_credentials
from ...utilities.type_utils import overlay_runtime_settings, to_bool
from ...utilities.url_utils import is_safe_custom_llm_endpoint
@@ -297,7 +298,8 @@ def _extract_research_params(data, settings_manager):
"llm.openai_endpoint.url", None
)
logger.debug(
- f"No custom_endpoint in request, using database setting: {custom_endpoint}"
+ "No custom_endpoint in request, using database setting: "
+ f"{redact_url_credentials(custom_endpoint) if custom_endpoint else None}"
)
# SSRF guard: a user-supplied custom_endpoint goes straight to the
@@ -319,7 +321,8 @@ def _extract_research_params(data, settings_manager):
"llm.ollama.url", DEFAULT_OLLAMA_URL
)
logger.debug(
- f"No ollama_url in request, using database setting: {ollama_url}"
+ "No ollama_url in request, using database setting: "
+ f"{redact_url_credentials(ollama_url) if ollama_url else None}"
)
search_engine = data.get("search_engine") or data.get("search_tool")
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index a464c6033e..0919495165 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -38,7 +38,7 @@ This dual-mode approach ensures the app works for all users while providing
optimal experience when JavaScript is available.
"""
-from fastapi import APIRouter, Depends, Request
+from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from ..dependencies.auth import (
require_auth,
@@ -538,6 +538,31 @@ def _get_setting_from_session(key: str | None, username: str, default=None):
return default
+def _model_discovery_settings_unchanged(db_session, fetched_settings):
+ """Compare discovery inputs with fresh rows in the cache write transaction."""
+ if not fetched_settings:
+ return True
+ rows = (
+ db_session.query(Setting)
+ .filter(Setting.key.in_(fetched_settings))
+ .populate_existing()
+ .all()
+ )
+ settings = {row.key: row for row in rows}
+ for key, fetched_value in fetched_settings.items():
+ row = settings.get(key)
+ current_value = get_typed_setting_value(
+ key,
+ row.value if row is not None else None,
+ str(row.ui_element) if row is not None else "text",
+ default="",
+ check_env=True,
+ )
+ if current_value != fetched_value:
+ return False
+ return True
+
+
def validate_setting(
setting: Setting, value: Any
) -> Tuple[bool, Optional[str]]:
@@ -2973,10 +2998,44 @@ def api_get_ui_elements(
@router.get("/api/available-models")
[email protected]("/api/available-models")
async def api_get_available_models(
request: Request, username: Annotated[str, Depends(require_auth)]
):
- """Discover models without continuing the provider loop after cancellation."""
+ """Get available LLM models from various providers.
+
+ ``GET`` returns the cached catalog; only when the cache yields no
+ usable rows from the last 24 hours does it discover the providers and
+ cache the result. A refresh calls providers with the user's stored API
+ keys and rewrites their cached ``ProviderModel`` rows, so it is a
+ state change accepted only on the CSRF-protected ``POST``:
+ ``?refresh_provider=<p>`` re-discovers that provider (or every
+ provider, when the cache has no usable rows), and a ``POST`` without a
+ target re-discovers every provider. A ``GET`` carrying
+ ``refresh_provider`` or ``force_refresh=true`` answers 405
+ (``Allow: POST``) without touching the cache or any provider; on a
+ ``POST`` the legacy ``force_refresh`` flag is ignored, so it never
+ widens a targeted refresh.
+
+ Discovery runs on its own executor and does not continue the provider
+ loop after cancellation.
+ """
+ # Parse as bool — a raw string (non-empty) is always truthy, so the old
+ # code always took the force-refresh path, deleting every cached model
+ # on every request.
+ force_refresh_requested = (
+ request.query_params.get("force_refresh", "false").lower() == "true"
+ )
+ # Refused here, on the event loop, so a 405 never waits for a discovery
+ # worker.
+ if request.method != "POST" and (
+ force_refresh_requested or request.query_params.get("refresh_provider")
+ ):
+ raise HTTPException(
+ status_code=405,
+ detail="Use POST to refresh models",
+ headers={"Allow": "POST"},
+ )
cancelled = threading.Event()
try:
# Not run_db_sync: discovery can wait out one provider timeout after
@@ -3003,18 +3062,32 @@ def _get_available_models(
raise asyncio.CancelledError
check_cancelled()
+ is_refresh_request = request.method == "POST"
endpoint_start = time.perf_counter()
try:
# request comes from FastAPI parameter
from ...database.models.providers import ProviderModel
- # Parse as bool — a raw string (non-empty) is always truthy, so
- # the old code always took the force-refresh path, deleting
- # every cached model on every request.
- force_refresh = (
- request.query_params.get("force_refresh", "false").lower() == "true"
+ # Optional targeted refresh: re-discover ONLY this provider and
+ # merge the result into the cached catalog (used after a provider
+ # API key is saved — the plain cache read would keep that
+ # provider's stale/empty list for up to 24h, and a full refresh
+ # re-probes every provider serially). POST-only: a GET carrying it
+ # was refused with 405 above.
+ refresh_provider = (
+ normalize_provider(
+ request.query_params.get("refresh_provider", "") or ""
+ )
+ if is_refresh_request
+ else None
)
+ # The forced (full) refresh: a POST without a target. The legacy
+ # force_refresh flag only matters on GET, where it was refused
+ # above; on a POST it neither selects nor widens anything, so a
+ # targeted POST stays targeted.
+ force_refresh = is_refresh_request and not refresh_provider
+
# Resolve the egress policy BEFORE the model cache is read or any
# provider is discovered/contacted. Fails closed (PolicyDeniedError).
policy_context, policy_snapshot = _resolve_model_discovery_policy(
@@ -3071,6 +3144,17 @@ def _get_available_models(
# Available models by provider
providers: dict[str, Any] = {}
+ # Cached rows of a targeted refresh's provider, set aside when the
+ # target's cache entries are dropped for re-fetch. Restored to the
+ # response if the re-fetch fails, so a transient upstream error
+ # can't blank the provider's catalog.
+ stale_target_rows: list | None = None
+ # Whether the cache read produced ANY rows (before the targeted
+ # refresh pops its provider). Distinct from a post-pop empty
+ # ``providers`` dict, which just means the cache held only the
+ # target — not that it is cold.
+ cache_had_rows = False
+
# Check database cache first (unless force_refresh is True)
if not force_refresh:
try:
@@ -3113,8 +3197,20 @@ def _get_available_models(
}
)
- # If we have cached data for all providers, return it
- if providers:
+ # If we have cached data for all providers, return it —
+ # unless a targeted refresh was requested for a provider
+ # whose rows are stale or absent (e.g. right after its
+ # API key was saved): drop just that provider's cached
+ # entries and fall through to a single-provider fetch.
+ cache_had_rows = bool(providers)
+ if providers and refresh_provider:
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Dictionary key only
+ stale_key = f"{refresh_provider}_models"
+ # Drop the target's cached entries (if any) and
+ # fall through to a single-provider re-fetch. Keep
+ # them aside for restoration if the re-fetch fails.
+ stale_target_rows = providers.pop(stale_key, None)
+ elif providers:
_log_available_models_duration(
endpoint_start, cache_hit=True
)
@@ -3131,6 +3227,17 @@ def _get_available_models(
logger.warning("Error reading cached models from database")
# Continue to fetch fresh data
+ if refresh_provider and not cache_had_rows:
+ # Cold cache (fresh install, or every row older than 24h): a
+ # targeted refresh would return a one-provider catalog that
+ # the client would cache as the whole world. Fall back to a
+ # full discovery — the plain cold-cache path does exactly that.
+ logger.info(
+ "Targeted refresh with an empty model cache: "
+ "falling back to full discovery"
+ )
+ refresh_provider = None
+
# Ollama / OpenAI / Anthropic model listing is handled by the
# auto-discovery loop below (their provider classes' list_models_for_api),
# leaving one provider-class fetch path. Those classes own base-URL
@@ -3172,6 +3279,20 @@ def _get_available_models(
],
)
+ if refresh_provider and not force_refresh:
+ # Targeted refresh: only the named provider is re-fetched (and
+ # only if it survived the policy filter above). Unknown
+ # provider names degrade to a plain cache read (nothing to
+ # re-fetch) — the merged `providers` dict below still returns
+ # the other providers' cached rows.
+ discovered_providers = {
+ key: info
+ for key, info in discovered_providers.items()
+ if key.lower() == refresh_provider
+ }
+
+ targeted_fetch_failed = False
+ fetched_provider_settings = {}
for provider_key, provider_info in discovered_providers.items():
check_cancelled()
provider_models = []
@@ -3196,6 +3317,15 @@ def _get_available_models(
url_setting, username, ""
)
+ fetched_settings = {}
+ if provider_class.api_key_setting is not None:
+ fetched_settings[provider_class.api_key_setting] = api_key
+ if url_setting:
+ fetched_settings[url_setting] = provider_base_url
+ fetched_provider_settings[
+ f"{normalize_provider(provider_key)}_models"
+ ] = fetched_settings
+
if policy_context.require_local_llm:
provider_snapshot = dict(policy_snapshot)
if url_setting:
@@ -3248,6 +3378,15 @@ def _get_available_models(
logger.exception(
f"Error getting {provider_info.provider_name} models"
)
+ if (
+ refresh_provider
+ and provider_key.lower() == refresh_provider
+ ):
+ # The targeted provider's re-fetch failed: don't let a
+ # transient upstream error blank its catalog — the
+ # cached rows set aside earlier are restored below and
+ # the DB rows are left untouched.
+ targeted_fetch_failed = True
# Set models in providers dict using lowercase key
providers[f"{normalize_provider(provider_key)}_models"] = (
@@ -3260,12 +3399,67 @@ def _get_available_models(
# Also check after the final provider, including failed fetches.
check_cancelled()
- # Save fetched models to database cache
- if force_refresh or providers:
+ # Restore the targeted provider's cached rows when its re-fetch
+ # failed (response keeps the last-known-good catalog).
+ if targeted_fetch_failed and stale_target_rows is not None:
+ providers[f"{refresh_provider}_models"] = stale_target_rows
+
+ # ``list_models_for_api`` converts every upstream failure into an
+ # empty list (its catch-all never raises), so the exception path
+ # above cannot fire for real network errors. Treat "targeted
+ # refresh produced zero models while non-empty cached rows were
+ # set aside" as a failed probe too: keep the last-known-good
+ # catalog and skip the cache write, so a transient outage during
+ # a key re-save cannot blank the provider's cached models.
+ if (
+ refresh_provider
+ and not force_refresh
+ and stale_target_rows
+ and not providers.get(f"{refresh_provider}_models")
+ ):
+ targeted_fetch_failed = True
+ providers[f"{refresh_provider}_models"] = stale_target_rows
+
+ # Save fetched models to database cache. A targeted refresh only
+ # persists the refreshed provider's rows — other providers keep
+ # their cached rows and TTLs untouched. A failed targeted re-fetch
+ # persists nothing (the cached rows stay valid).
+ providers_to_save = providers
+ if refresh_provider and not force_refresh:
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Dictionary key only
+ target_key = f"{refresh_provider}_models"
+ providers_to_save = (
+ {}
+ if targeted_fetch_failed
+ else {
+ key: models
+ for key, models in providers.items()
+ if key == target_key
+ }
+ )
+ if force_refresh or providers_to_save:
# We fetched fresh data, save it to database
with get_user_db_session(username) as db_session:
try:
- if force_refresh:
+ # Take SQLite's writer lock only AFTER all network calls.
+ # Checking settings and writing models under the same lock
+ # prevents a key/URL change (including in another worker)
+ # from racing between the check and the cache replacement.
+ db_session.connection().exec_driver_sql("BEGIN IMMEDIATE")
+ current_providers_to_save = {
+ key: models
+ for key, models in providers_to_save.items()
+ if _model_discovery_settings_unchanged(
+ db_session, fetched_provider_settings.get(key, {})
+ )
+ }
+ superseded = len(current_providers_to_save) != len(
+ providers_to_save
+ )
+ providers_to_save = current_providers_to_save
+ # A superseded full refresh must also leave the newer
+ # provider's rows intact instead of clearing the catalog.
+ if force_refresh and not superseded:
# When force refresh, clear ALL cached models to remove any stale data
# from old code versions or deleted providers
deleted_count = db_session.query(ProviderModel).delete()
@@ -3274,7 +3468,7 @@ def _get_available_models(
)
else:
# Clear old cache entries only for providers we're updating
- for provider_key in providers:
+ for provider_key in providers_to_save:
provider_name = provider_key.replace(
"_models", ""
).upper()
@@ -3282,8 +3476,39 @@ def _get_available_models(
ProviderModel.provider == provider_name
).delete()
- # Insert new models
- for provider_key, models in providers.items():
+ # Insert new models. A targeted refresh stamps its
+ # rows with the oldest ``last_updated`` among the other
+ # providers' fresh cached rows so the whole catalog
+ # still expires at once: the cache read returns any
+ # fresh rows as the complete catalog, so rows that
+ # outlived the others would hide every other
+ # provider's models until they expired too. Read under
+ # the writer lock, so a full refresh that committed
+ # after this request's cache read is taken into
+ # account.
+ row_time = datetime.now(UTC)
+ if refresh_provider and not force_refresh:
+ other_row_times = [
+ model.last_updated
+ for model in db_session.query(ProviderModel)
+ .filter(
+ ProviderModel.last_updated
+ > row_time - timedelta(hours=24)
+ )
+ .all()
+ if normalize_provider(model.provider)
+ != refresh_provider
+ and isinstance(model.last_updated, datetime)
+ ]
+ if other_row_times:
+ row_time = min(
+ row_time,
+ *(
+ t if t.tzinfo else t.replace(tzinfo=UTC)
+ for t in other_row_times
+ ),
+ )
+ for provider_key, models in providers_to_save.items():
provider_name = provider_key.replace(
"_models", ""
).upper()
@@ -3297,7 +3522,7 @@ def _get_available_models(
provider=provider_name,
model_key=model["value"],
model_label=model["label"],
- last_updated=datetime.now(UTC),
+ last_updated=row_time,
)
db_session.add(new_model)
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 34d39dc04a..17d846c4cb 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -25,11 +25,13 @@ from ...constants import ResearchStatus
from ...database.models import ResearchHistory, ResearchStrategy
from ...database.session_context import get_user_db_session
from ...database.thread_local_session import thread_cleanup
+from ...error_handling.error_messages import TYPED_RESEARCH_ERROR_MESSAGES
from ...error_handling.openai_compat_errors import (
friendly_openai_compatible_error,
is_openai_compat_runtime_error,
)
from ...error_handling.report_generator import ErrorReportGenerator
+from ...llm.providers.base import normalize_provider
from ...utilities.thread_context import set_search_context
from ...report_generator import IntegratedReportGenerator
from ...search_system import AdvancedSearchSystem
@@ -46,6 +48,76 @@ from .socketio_asgi import (
OUTPUT_DIR = get_research_outputs_directory()
+# Providers whose runtime failures are OpenAI-compatible client errors and
+# get rewritten by ``friendly_openai_compatible_error`` to name the provider,
+# base URL, and model (#3878). Pinned by
+# tests/error_handling/test_openai_compat_errors.py.
+_OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS = frozenset(
+ {
+ "openai_endpoint",
+ "lmstudio",
+ "llamacpp",
+ "openai",
+ "openrouter",
+ "requesty",
+ "orcarouter",
+ "atlascloud",
+ "qwen",
+ "deepseek",
+ "google",
+ "ionos",
+ "xai",
+ }
+)
+
+
+def _resolve_error_rewrite_base_url(
+ provider, custom_endpoint, settings_context=None
+):
+ """Resolve the base URL for the friendly error rewrite.
+
+ ``custom_endpoint`` is the ``llm.openai_endpoint.url`` value and is only
+ the URL the client uses when the provider is ``openai_endpoint``. Some
+ callers pass it for every provider (it defaults to the OpenRouter URL),
+ so it is ignored for any other provider — otherwise QwenCloud, DeepSeek,
+ LM Studio, ... would be reported against a URL they never contacted.
+
+ Providers with a hardcoded endpoint (QwenCloud, DeepSeek, Atlas Cloud,
+ ...) fall back to the provider class default so the rewritten message
+ names the real base URL instead of ``<unknown>``. Providers whose URL is
+ configurable via a settings key (LM Studio, llama.cpp, custom endpoints)
+ resolve their configured URL through the settings context — their class
+ default is just a localhost guess that would misdirect troubleshooting
+ when an operator overrode it.
+ """
+ provider = normalize_provider(provider)
+ if not provider:
+ return None
+ if custom_endpoint and provider == "openai_endpoint":
+ return custom_endpoint
+ from ...llm.providers.auto_discovery import get_provider_class
+
+ provider_cls = get_provider_class(provider)
+ if provider_cls is None:
+ return None
+ url_setting = getattr(provider_cls, "url_setting", None)
+ if url_setting:
+ if settings_context is None:
+ # No context to read the operator's configured URL — the class
+ # default is just a localhost guess; report "<unknown>" rather
+ # than risk naming a URL the client is not using.
+ return None
+ url = settings_context.get_setting(url_setting, None)
+ return url or None
+ if provider == "openai" and settings_context is not None:
+ # OpenAIProvider's create_llm honors an operator-configured
+ # llm.openai.api_base gateway; naming the class default would
+ # misdirect troubleshooting the same way a wrong localhost would.
+ api_base = settings_context.get_setting("llm.openai.api_base", None)
+ if api_base:
+ return api_base
+ return getattr(provider_cls, "default_base_url", None)
+
class _SocketEmitter:
"""Object-style adapter over ``socketio_asgi.emit_to_subscribers``.
@@ -1190,7 +1262,7 @@ def run_research_process(research_id, query, mode, **kwargs):
model = settings_context.get_setting("llm.model")
if (
"custom_endpoint" not in kwargs
- and model_provider == "openai_endpoint"
+ and normalize_provider(model_provider) == "openai_endpoint"
):
custom_endpoint = settings_context.get_setting(
"llm.openai_endpoint.url"
@@ -1915,22 +1987,19 @@ def run_research_process(research_id, query, mode, **kwargs):
# OpenAI-compatible runtime failures (LM Studio / vLLM / llama.cpp
# server / OpenRouter / custom endpoint) -- rewrite to a message
# that names the provider, base URL, and model (#3878).
- if model_provider in {
- "openai_endpoint",
- "lmstudio",
- "llamacpp",
- "openai",
- "openrouter",
- "orcarouter",
- "atlascloud",
- "google",
- "ionos",
- "xai",
- } and is_openai_compat_runtime_error(search_error):
+ # Normalise first: a legacy upper-case stored provider
+ # ("QWEN") must still get the rewrite.
+ rewrite_provider = normalize_provider(model_provider)
+ if (
+ rewrite_provider in _OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS
+ and is_openai_compat_runtime_error(search_error)
+ ):
rewritten = friendly_openai_compatible_error(
search_error,
- provider=model_provider,
- base_url=custom_endpoint,
+ provider=rewrite_provider,
+ base_url=_resolve_error_rewrite_base_url(
+ rewrite_provider, custom_endpoint, settings_context
+ ),
model=model,
)
raise RuntimeError(rewritten) from search_error
@@ -2879,6 +2948,7 @@ def run_research_process(research_id, query, mode, **kwargs):
# Other egress PEPs (scope mismatch, require-local
# inference, etc.) — no "sensitive source" is necessarily
# involved, so don't claim one.
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Client error message
user_friendly_error = (
f"Egress policy refused this run ({_reason})."
)
@@ -2917,42 +2987,46 @@ def run_research_process(research_id, query, mode, **kwargs):
# detail stays in the logs above and the actionable hint is in
# ``solution``.
elif "Error type: openai_connection_refused" in user_friendly_error:
- user_friendly_error = (
- "Could not connect to the configured LLM server."
- )
+ user_friendly_error = TYPED_RESEARCH_ERROR_MESSAGES[
+ "openai_connection_refused"
+ ]
error_context = {
- "solution": "Start your LLM server (LM Studio / vLLM / llama.cpp server) and verify the base URL in Settings -> LLM Providers."
+ "solution": "Check that the configured LLM endpoint is reachable (a local server such as LM Studio, vLLM or llama.cpp must be running) and verify its base URL in Settings -> LLM Providers."
}
elif "Error type: openai_timeout" in user_friendly_error:
- user_friendly_error = "The configured LLM server timed out."
+ user_friendly_error = TYPED_RESEARCH_ERROR_MESSAGES[
+ "openai_timeout"
+ ]
error_context = {
- "solution": "The server is reachable but slow -- it may be loading a model. Retry, or increase the request timeout."
+ "solution": "The endpoint is reachable but slow (the model may still be loading). Retry, or increase the request timeout."
}
elif "Error type: openai_auth" in user_friendly_error:
user_friendly_error = (
"Authentication with the configured LLM provider failed."
)
error_context = {
- "solution": "Set or correct the API key for this provider in Settings -> LLM Providers. Local servers usually accept any non-empty key."
+ "solution": "Check that the API key for this provider is valid and set in Settings -> LLM Providers."
}
elif "Error type: openai_permission_denied" in user_friendly_error:
user_friendly_error = (
"The configured LLM provider denied access to the model."
)
error_context = {
- "solution": "Your API key is valid but lacks access to this model. Pick a model your account/server is permitted to use."
+ "solution": "Your API key is valid but lacks access to this model. Pick a model your account is permitted to use."
}
elif "Error type: openai_model_not_found" in user_friendly_error:
- user_friendly_error = (
- "The configured model was not found on the LLM server."
- )
+ user_friendly_error = TYPED_RESEARCH_ERROR_MESSAGES[
+ "openai_model_not_found"
+ ]
error_context = {
- "solution": "The model id is not loaded on this server. Pick a currently-loaded model in the provider's UI/config."
+ "solution": "The provider does not offer (or has not loaded) this model id. Pick a model from the provider's model list."
}
elif "Error type: openai_bad_request" in user_friendly_error:
- user_friendly_error = "The LLM server rejected the request."
+ user_friendly_error = TYPED_RESEARCH_ERROR_MESSAGES[
+ "openai_bad_request"
+ ]
error_context = {
- "solution": "The server rejected the request. Check the model id and any provider-specific parameters."
+ "solution": "The provider rejected the request. Check the model id and any provider-specific parameters."
}
elif "Error type: openai_unknown" in user_friendly_error:
user_friendly_error = (
diff --git a/src/local_deep_research/web/static/js/components/context-overflow.js b/src/local_deep_research/web/static/js/components/context-overflow.js
index 449025ab28..1dc2e0667d 100644
--- a/src/local_deep_research/web/static/js/components/context-overflow.js
+++ b/src/local_deep_research/web/static/js/components/context-overflow.js
@@ -86,6 +86,9 @@
'openrouter': 'OpenRouter',
'orcarouter': 'OrcaRouter',
'atlascloud': 'Atlas Cloud',
+ 'qwen': 'QwenCloud',
+ 'deepseek': 'DeepSeek',
+ 'requesty': 'Requesty',
'lmstudio': 'LM Studio',
'llamacpp': 'Llama.cpp',
'xai': 'xAI',
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 8fcd2448e7..11a92fbda5 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -77,6 +77,8 @@
let orcarouterApiKeyContainer = null;
let atlascloudApiKeyInput = null;
let atlascloudApiKeyContainer = null;
+ let qwenApiKeyInput = null;
+ let qwenApiKeyContainer = null;
let xaiApiKeyInput = null;
let xaiApiKeyContainer = null;
let ionosApiKeyInput = null;
@@ -333,6 +335,8 @@
orcarouterApiKeyContainer = document.getElementById('orcarouter_api_key_container');
atlascloudApiKeyInput = document.getElementById('atlascloud_api_key');
atlascloudApiKeyContainer = document.getElementById('atlascloud_api_key_container');
+ qwenApiKeyInput = document.getElementById('qwen_api_key');
+ qwenApiKeyContainer = document.getElementById('qwen_api_key_container');
xaiApiKeyInput = document.getElementById('xai_api_key');
xaiApiKeyContainer = document.getElementById('xai_api_key_container');
ionosApiKeyInput = document.getElementById('ionos_api_key');
@@ -908,6 +912,9 @@
if (atlascloudApiKeyContainer) {
atlascloudApiKeyContainer.style.display = provider === 'ATLASCLOUD' ? 'block' : 'none';
}
+ if (qwenApiKeyContainer) {
+ qwenApiKeyContainer.style.display = provider === 'QWEN' ? 'block' : 'none';
+ }
if (xaiApiKeyContainer) {
xaiApiKeyContainer.style.display = provider === 'XAI' ? 'block' : 'none';
}
@@ -1172,6 +1179,11 @@
saveSearchSetting('llm.atlascloud.api_key', this.value);
});
}
+ if (qwenApiKeyInput) {
+ qwenApiKeyInput.addEventListener('change', function() {
+ saveSearchSetting('llm.qwen.api_key', this.value);
+ });
+ }
if (xaiApiKeyInput) {
xaiApiKeyInput.addEventListener('change', function() {
saveSearchSetting('llm.xai.api_key', this.value);
@@ -1382,6 +1394,9 @@
if (atlascloudApiKeyContainer) {
atlascloudApiKeyContainer.style.display = selectedProvider === 'ATLASCLOUD' ? 'block' : 'none';
}
+ if (qwenApiKeyContainer) {
+ qwenApiKeyContainer.style.display = selectedProvider === 'QWEN' ? 'block' : 'none';
+ }
if (xaiApiKeyContainer) {
xaiApiKeyContainer.style.display = selectedProvider === 'XAI' ? 'block' : 'none';
}
@@ -1788,6 +1803,9 @@
if (atlascloudApiKeyContainer) {
atlascloudApiKeyContainer.style.display = activeProvider === 'ATLASCLOUD' ? 'block' : 'none';
}
+ if (qwenApiKeyContainer) {
+ qwenApiKeyContainer.style.display = activeProvider === 'QWEN' ? 'block' : 'none';
+ }
if (xaiApiKeyContainer) {
xaiApiKeyContainer.style.display = activeProvider === 'XAI' ? 'block' : 'none';
}
@@ -1890,6 +1908,12 @@
atlascloudApiKeyInput.disabled = !atlascloudApiKeySetting.editable;
}
+ const qwenApiKeySetting = data.settings['llm.qwen.api_key'];
+ if (qwenApiKeySetting && qwenApiKeyInput) {
+ qwenApiKeyInput.value = '';
+ qwenApiKeyInput.disabled = !qwenApiKeySetting.editable;
+ }
+
const xaiApiKeySetting = data.settings['llm.xai.api_key'];
if (xaiApiKeySetting && xaiApiKeyInput) {
xaiApiKeyInput.value = '';
@@ -2076,6 +2100,9 @@
if (atlascloudApiKeyContainer) {
atlascloudApiKeyContainer.style.display = provider === 'ATLASCLOUD' ? 'block' : 'none';
}
+ if (qwenApiKeyContainer) {
+ qwenApiKeyContainer.style.display = provider === 'QWEN' ? 'block' : 'none';
+ }
if (xaiApiKeyContainer) {
xaiApiKeyContainer.style.display = provider === 'XAI' ? 'block' : 'none';
}
@@ -2133,11 +2160,17 @@
* Load model options from API or cache
*/
let modelOptionsRequestGeneration = 0;
+ let fullModelOptionsRequestGeneration = 0;
+ let modelProviderOptionsGeneration = 0;
+ const providerModelOptionsRequestGenerations = new Map();
- function loadModelOptions(forceRefresh = false) {
+ function loadModelOptions(forceRefresh = false, refreshProvider = null) {
return new Promise((resolve) => {
- // Check in-memory cache first if not forcing refresh (5-minute expiration)
- if (!forceRefresh) {
+ // Check in-memory cache first for plain loads (5-minute
+ // expiration). A targeted refresh explicitly wants fresh
+ // server data, so it bypasses the client cache like a full
+ // force refresh does.
+ if (!forceRefresh && !refreshProvider) {
const cachedData = getCachedData(CACHE_KEYS.MODELS);
if (cachedData) {
SafeLogger.log('Using cached model data');
@@ -2146,7 +2179,28 @@
}
}
+ // Reading the cache above deliberately does NOT advance the
+ // generation: a plain cache hit must not cancel an in-flight
+ // targeted/forced refresh (which owns the loading spinner
+ // until it settles).
const requestGeneration = ++modelOptionsRequestGeneration;
+ const targetedProvider = !forceRefresh && refreshProvider
+ ? refreshProvider.toUpperCase() : null;
+ if (targetedProvider) {
+ providerModelOptionsRequestGenerations.set(targetedProvider, requestGeneration);
+ } else {
+ fullModelOptionsRequestGeneration = requestGeneration;
+ }
+ // Independent targeted refreshes may both contribute models.
+ // A newer request for the same provider, or a full/policy reload,
+ // supersedes this provider's response instead.
+ const isSuperseded = () => {
+ if (targetedProvider) {
+ return providerModelOptionsRequestGenerations.get(targetedProvider) !== requestGeneration
+ || fullModelOptionsRequestGeneration > requestGeneration;
+ }
+ return requestGeneration !== fullModelOptionsRequestGeneration;
+ };
// Add loading class to parent
if (modelInput && modelInput.parentNode) {
@@ -2192,12 +2246,28 @@
resolve([]);
};
- // Fetch from API if cache is invalid or refresh is forced
- const url = forceRefresh
- ? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
+ // Fetch from API if cache is invalid or refresh is forced.
+ // refreshProvider targets a single provider's catalog (used
+ // after its API key was saved); forceRefresh re-discovers
+ // every provider (a POST without a target). Both refreshes
+ // call providers with the user's stored keys and rewrite the
+ // cached rows, so the server accepts them only as a
+ // CSRF-protected POST (a GET with refresh_provider or
+ // force_refresh=true answers 405).
+ const params = new URLSearchParams();
+ if (!forceRefresh && refreshProvider) {
+ params.set('refresh_provider', refreshProvider);
+ }
+ const url = params.toString()
+ ? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?${params.toString()}`
: URLS.SETTINGS_API.AVAILABLE_MODELS;
+ const csrfToken = window.api?.getCsrfToken?.()
+ || document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const modelRequest = (forceRefresh || refreshProvider)
+ ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
+ : fetch(url);
- fetch(url)
+ modelRequest
.then(response => {
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
@@ -2205,7 +2275,7 @@
return response.json();
})
.then(data => {
- if (requestGeneration !== modelOptionsRequestGeneration) {
+ if (isSuperseded()) {
resolveSupersededRequest();
return;
}
@@ -2218,8 +2288,11 @@
SafeLogger.log('Got model data from API:', data);
// Update MODEL_PROVIDERS from API if available
- if (data.provider_options) {
+ const updatesProviderOptions = data.provider_options
+ && requestGeneration > modelProviderOptionsGeneration;
+ if (updatesProviderOptions) {
MODEL_PROVIDERS = data.provider_options;
+ modelProviderOptionsGeneration = requestGeneration;
SafeLogger.log('Updated MODEL_PROVIDERS from API:', MODEL_PROVIDERS);
}
@@ -2232,12 +2305,16 @@
// user toggled a policy, would be the very call we
// just made (waste) or, worse, a fresh force-refresh
// for a cloud provider that just got re-enabled.
- const formattedModels = formatModelsFromAPI(data);
+ const formattedModels = formatModelRefresh(
+ data, targetedProvider, requestGeneration
+ );
cacheData(CACHE_KEYS.MODELS, formattedModels);
// Re-populate the provider dropdown with new options
- if (data.provider_options) {
+ if (updatesProviderOptions) {
populateModelProviders();
+ } else if (modelProviderSelect) {
+ updateModelOptionsForProvider(modelProviderSelect.value, false);
}
resolve(formattedModels);
@@ -2246,7 +2323,7 @@
}
})
.catch(error => {
- if (requestGeneration !== modelOptionsRequestGeneration) {
+ if (isSuperseded()) {
resolveSupersededRequest();
return;
}
@@ -2280,6 +2357,51 @@
});
}
+ function formatModelRefresh(data, provider, requestGeneration) {
+ const cachedModels = getCachedData(CACHE_KEYS.MODELS);
+ const cachedProviders = {};
+ if (cachedModels && cachedModels.length > 0) {
+ // The server takes its other-provider snapshot before fetching the
+ // target. Keep our other providers' models: that snapshot can be
+ // older than a targeted response we have already applied.
+ cachedModels.forEach(model => {
+ if (model.isProvider || !model.provider) return;
+ const key = `${model.provider.toLowerCase()}_models`;
+ if (!cachedProviders[key]) cachedProviders[key] = [];
+ cachedProviders[key].push(model);
+ });
+ }
+ const providers = provider && cachedModels && cachedModels.length > 0
+ ? cachedProviders : {...data.providers};
+ if (provider) {
+ const targetKey = `${provider.toLowerCase()}_models`;
+ providers[targetKey] = data.providers[targetKey] || [];
+ } else {
+ // A full response can still contribute other providers after a
+ // newer targeted request. Preserve that target's current models,
+ // including an empty list, instead of replacing them with the
+ // full request's older credential/configuration snapshot.
+ providerModelOptionsRequestGenerations.forEach((generation, name) => {
+ if (generation > requestGeneration) {
+ const key = `${name.toLowerCase()}_models`;
+ providers[key] = cachedProviders[key] || [];
+ }
+ });
+ }
+
+ // Only the newest response may update provider policy/options. An
+ // older targeted response must never restore a now-disabled provider.
+ const allowedProviders = new Set(MODEL_PROVIDERS
+ .filter(option => !option.disabled)
+ .map(option => option.value.toUpperCase()));
+ Object.keys(providers).forEach(key => {
+ if (!allowedProviders.has(key.replace(/_models$/, '').toUpperCase())) {
+ delete providers[key];
+ }
+ });
+ return formatModelsFromAPI({provider_options: MODEL_PROVIDERS, providers});
+ }
+
// Format models from API response
function formatModelsFromAPI(data) {
const formatted = [];
@@ -3302,6 +3424,13 @@
});
}
+ // Setting keys whose values are secrets and must never be echoed in a
+ // toast (case-insensitive; matches the last key segment's suffix).
+ const SECRET_SETTING_KEY_RE = /(?:api_key|token|secret|password)$/i;
+ // Endpoint URL settings can embed credentials (user:pw@host or
+ // ?api_key=...), so their toasts omit the value too.
+ const URL_SETTING_KEY_RE = /\.url$/i;
+
function saveSearchSetting(settingKey, value, onFailure = null, onSuccess = null) {
return enqueueResearchSettingSave(settingKey, () => fetch(`/settings/api/${settingKey}`, {
method: "PUT",
@@ -3327,8 +3456,32 @@
window.displayWarnings(data.warnings);
}
if (typeof onSuccess === "function") onSuccess(data);
+ const parts = settingKey.split(".");
+ const isApiKey = settingKey.endsWith("api_key");
+ // The PUT response carries no ui_element, so classify secrets
+ // by key name: any *api_key / *token / *secret / *password
+ // setting (the password-typed inputs this page saves).
+ const isSecret = SECRET_SETTING_KEY_RE.test(settingKey);
+ const hideValue = isSecret || URL_SETTING_KEY_RE.test(settingKey);
if (window.ui && window.ui.showMessage) {
- window.ui.showMessage(`${settingKey.split(".").pop()} updated to: ${value}`, "success", 2000);
+ // Never echo secret or endpoint URL values on screen —
+ // show a neutral confirmation instead of the raw value,
+ // keeping the provider segment for identifiability
+ // ("qwen api_key updated", "ollama url updated").
+ const label = hideValue
+ ? `${parts.length > 2 ? `${parts[parts.length - 2]} ` : ""}${parts[parts.length - 1]}`
+ : parts[parts.length - 1];
+ const detail = hideValue ? "updated" : `updated to: ${value}`;
+ window.ui.showMessage(`${label} ${detail}`, "success", 2000);
+ }
+ // A saved provider API key changes what that provider's model
+ // dropdown can offer: a missing or wrong key previously left
+ // it undiscovered, and the server caches model lists for up
+ // to 24h. Refresh just that provider's catalog so its models
+ // appear at once (single-provider fetch, keeps other
+ // providers' caches intact).
+ if (isApiKey && parts.length > 2) {
+ loadModelOptions(false, parts[parts.length - 2]);
}
}))
.catch(error => {
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index b549b3c7da..6d257ce8ef 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -4390,12 +4390,14 @@
SafeLogger.log('Fetching model providers from API');
// Create a promise and store it
- const url = forceRefresh
- ? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
- : URLS.SETTINGS_API.AVAILABLE_MODELS;
+ const url = URLS.SETTINGS_API.AVAILABLE_MODELS;
+ const csrfToken = window.api?.getCsrfToken?.()
+ || document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
const requestGeneration = ++nextModelProvidersRequestGeneration;
- const request = fetch(url)
+ const request = (forceRefresh
+ ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
+ : fetch(url))
.then(response => {
if (!response.ok) {
throw new Error(`API returned status: ${response.status}`);
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index d570221585..8e1b401385 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -585,12 +585,12 @@ function getNewsSubscriptionModelConfig() {
const model = document.getElementById('news-subscription-model')?.value ?? '';
if (!model) return null;
- // Match the built-in provider keys; a native model ID can also contain
- // colons (e.g. llama3.1:8b), so a colon alone is not a provider delimiter.
+ // Every built-in provider key (a test pins it to the registry). A model ID
+ // can contain colons (llama3.1:8b), so a colon alone is not a delimiter.
const knownProviders = new Set([
- 'ANTHROPIC', 'ANTHROPIC_ENDPOINT', 'ATLASCLOUD', 'DEEPSEEK',
- 'GOOGLE', 'IONOS', 'LLAMACPP', 'LMSTUDIO', 'OLLAMA', 'OPENAI',
- 'OPENAI_ENDPOINT', 'OPENROUTER', 'ORCAROUTER', 'REQUESTY', 'XAI',
+ 'ANTHROPIC', 'ANTHROPIC_ENDPOINT', 'ATLASCLOUD', 'DEEPSEEK', 'GOOGLE',
+ 'IONOS', 'LLAMACPP', 'LMSTUDIO', 'OLLAMA', 'OPENAI', 'OPENAI_ENDPOINT',
+ 'OPENROUTER', 'ORCAROUTER', 'QWEN', 'REQUESTY', 'XAI',
]);
const separator = model.indexOf(':');
const provider = model.slice(0, separator).toUpperCase();
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index 619e7c756e..050d123018 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -2165,7 +2165,9 @@ function setupEvaluationModelDropdown() {
window.modelsLoading = true;
const requestVersion = ++evaluationModelsRequestVersion;
- fetch('/settings/api/available-models?force_refresh=true')
+ fetch('/settings/api/available-models', {
+ method: 'POST', headers: { 'X-CSRFToken': csrfToken }
+ })
.then(response => response.json())
.then(data => {
if (requestVersion !== evaluationModelsRequestVersion) return;
@@ -2309,10 +2311,12 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false, refr
window.modelsLoading = true;
const requestVersion = ++evaluationModelsRequestVersion;
- // Use the correct API endpoint with optional force_refresh parameter
- const url = forceRefresh ? '/settings/api/available-models?force_refresh=true' : '/settings/api/available-models';
+ const url = '/settings/api/available-models';
+ const modelRequest = forceRefresh
+ ? fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })
+ : fetch(url);
- fetch(url)
+ modelRequest
.then(response => response.json())
.then(data => {
if (requestVersion !== evaluationModelsRequestVersion) return;
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index ba3bbe5e06..c6874a942c 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -276,6 +276,14 @@
<span class="ldr-input-help">Get your key at atlascloud.ai</span>
</div>
+ <!-- QwenCloud API Key (hidden by default) -->
+ <div class="ldr-form-group ldr-half" id="qwen_api_key_container" style="display: none;">
+ <label for="qwen_api_key">QwenCloud API Key</label>
+ <input type="password" id="qwen_api_key" name="qwen_api_key" class="ldr-form-control"
+ placeholder="sk-ws-..." autocomplete="off">
+ <span class="ldr-input-help">Pay-as-you-go key (sk-ws-…) from home.qwencloud.com; Token Plan keys (sk-sp-…) use a different endpoint and are not supported</span>
+ </div>
+
<!-- xAI API Key (hidden by default) -->
<div class="ldr-form-group ldr-half" id="xai_api_key_container" style="display: none;">
<label for="xai_api_key">xAI API Key</label>
diff --git a/tests/error_handling/test_openai_compat_errors.py b/tests/error_handling/test_openai_compat_errors.py
index 8447d64c50..c1b718eb18 100644
--- a/tests/error_handling/test_openai_compat_errors.py
+++ b/tests/error_handling/test_openai_compat_errors.py
@@ -73,6 +73,133 @@ class TestStripCredentials:
assert _strip_credentials("") == "<unknown>"
assert _strip_credentials(None) == "<unknown>"
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "api_key",
+ "API_KEY",
+ "apikey",
+ "key",
+ "Key",
+ "x-api-key",
+ "subscription-key",
+ "token",
+ "access_token",
+ "refresh_token",
+ "secret",
+ "client_secret",
+ "password",
+ ],
+ )
+ def test_redacts_credential_query_values(self, name):
+ out = _strip_credentials(f"https://gw.example/v1?{name}=sk-leak123")
+ assert "sk-leak123" not in out
+ assert out == f"https://gw.example/v1?{name}=REDACTED"
+
+ def test_query_redaction_keeps_other_params_and_strips_userinfo(self):
+ out = _strip_credentials(
+ "https://u:[email protected]:8443/v1"
+ "?api-version=2024-10-01&api_key=sk-leak123&model=m"
+ )
+ assert out == (
+ "https://gw.example:8443/v1"
+ "?api-version=2024-10-01&api_key=REDACTED&model=m"
+ )
+
+ def test_query_redaction_does_not_touch_lookalike_names(self):
+ """Only whole names / trailing segments match: ``monkey`` and
+ ``keyboard`` are not credentials."""
+ url = "https://gw.example/v1?monkey=a&keyboard=b"
+ assert _strip_credentials(url) == url
+
+ def test_query_redaction_without_netloc(self):
+ """A scheme-less base URL has no parsed netloc; its query is still
+ redacted."""
+ out = _strip_credentials("localhost:1234/v1?key=sk-leak123")
+ assert "sk-leak123" not in out
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "sig",
+ "signature",
+ "sas",
+ "auth",
+ "authorization",
+ "bearer",
+ "pwd",
+ "passwd",
+ "x-amz-signature",
+ "X-Goog-Signature",
+ "code",
+ "my_token",
+ "my_key",
+ "my_secret",
+ "custom-key",
+ ],
+ )
+ def test_redacts_extended_credential_names(self, name):
+ out = _strip_credentials(f"https://gw.example/v1?{name}=sk-leak123")
+ assert out == f"https://gw.example/v1?{name}=REDACTED"
+
+ @pytest.mark.parametrize(
+ "name", ["monkey", "keyboard", "tokenizer", "error_code", "oauth"]
+ )
+ def test_lookalike_names_are_not_redacted(self, name):
+ url = f"https://gw.example/v1?{name}=visible"
+ assert _strip_credentials(url) == url
+
+ def test_semicolon_separates_query_params(self):
+ out = _strip_credentials(
+ "https://gw.example/v1?a=1;api_key=sk-leak123;b=2"
+ )
+ assert out == "https://gw.example/v1?a=1;api_key=REDACTED;b=2"
+
+ def test_fragment_params_are_redacted(self):
+ out = _strip_credentials(
+ "https://gw.example/v1#access_token=sk-leak123&state=x"
+ )
+ assert out == "https://gw.example/v1#access_token=REDACTED&state=x"
+
+ def test_path_params_are_redacted(self):
+ out = _strip_credentials(
+ "https://gw.example/v1;api_key=sk-leak123/chat;v=2"
+ )
+ assert out == "https://gw.example/v1;api_key=REDACTED/chat;v=2"
+
+ def test_long_bare_query_item_is_redacted(self):
+ out = _strip_credentials(
+ "https://gw.example/v1?sk-leak1234567890abcdef&x=1"
+ )
+ assert "sk-leak1234567890abcdef" not in out
+ assert out == "https://gw.example/v1?REDACTED&x=1"
+
+ def test_short_bare_query_item_is_kept(self):
+ """Only value-less items of 17+ characters are treated as bare
+ credentials; a short flag stays legible."""
+ url = "https://gw.example/v1?debug&x=1"
+ assert _strip_credentials(url) == url
+
+ def test_invalid_port_does_not_raise(self):
+ """``SplitResult.port`` raises on an out-of-range port. The helper
+ runs inside an error handler, so it never parses the port: the
+ authority is kept verbatim (minus userinfo) and nothing raises."""
+ assert _strip_credentials("http://u:[email protected]:99999/v1") == (
+ "http://h.example:99999/v1"
+ )
+
+ def test_query_key_redacted_in_friendly_message(self):
+ """End to end: the rewritten message never carries the key."""
+ exc = APIConnectionError(message="conn", request=_req())
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="openai_endpoint",
+ base_url="https://gw.example/v1?api_key=sk-leak123",
+ model="m",
+ )
+ assert "sk-leak123" not in msg
+ assert "https://gw.example/v1?api_key=REDACTED" in msg
+
# ---------------------------------------------------------------------------
# Cause-chain walker
@@ -601,3 +728,281 @@ class TestTransportPackageOfTheInstalledSDK:
model="mistral",
)
assert "Error type: openai_timeout" in msg
+
+
+class TestErrorRewriteProviderSet:
+ """Pin the provider set that opts into the friendly error rewrite.
+
+ research_service rewrites OpenAI-compatible runtime failures only for
+ providers in ``_OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS``; a provider
+ dropped from the set silently falls back to the generic status-code
+ rewrite. Every OpenAI-compatible provider (including newly added ones
+ like QwenCloud) must stay enumerated here.
+ """
+
+ def test_rewrite_set_membership_is_pinned(self):
+ from local_deep_research.web.services.research_service import (
+ _OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS,
+ )
+
+ expected = frozenset(
+ {
+ "openai_endpoint",
+ "lmstudio",
+ "llamacpp",
+ "openai",
+ "openrouter",
+ "requesty",
+ "orcarouter",
+ "atlascloud",
+ "qwen",
+ "deepseek",
+ "google",
+ "ionos",
+ "xai",
+ }
+ )
+ actual = _OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS
+ assert actual == expected, (
+ f"error-rewrite provider set drifted: "
+ f"missing={sorted(expected - actual)} "
+ f"unexpected={sorted(actual - expected)}. Update both the set in "
+ f"research_service.py and this pin (and add a changelog entry if "
+ f"a provider was removed)."
+ )
+
+ def test_every_discovered_openai_compat_provider_is_in_rewrite_set(self):
+ """Stronger contract: no discovered cloud provider that inherits the
+ stock ``OpenAICompatibleProvider.create_llm`` (i.e., talks through
+ ChatOpenAI and raises OpenAI-compatible client errors) may ship
+ without its friendly error rewrite. Providers that override
+ ``create_llm`` with a different client (Anthropic's Messages SDK,
+ Ollama's native client) raise different exception types and are
+ excluded. Guards future provider additions from forgetting this
+ registration point."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+ from local_deep_research.llm.providers.auto_discovery import (
+ discover_providers,
+ )
+ from local_deep_research.web.services.research_service import (
+ _OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS,
+ )
+
+ discovered = discover_providers()
+ assert discovered, "provider auto-discovery returned nothing"
+ missing = []
+ checked = 0
+ for key, info in discovered.items():
+ cls = info.provider_class
+ if not issubclass(cls, OpenAICompatibleProvider):
+ continue
+ if not cls.is_cloud:
+ continue
+ uses_stock_openai_client = (
+ getattr(cls.create_llm, "__func__", None)
+ is OpenAICompatibleProvider.create_llm.__func__
+ )
+ if not uses_stock_openai_client:
+ continue
+ checked += 1
+ if key.lower() not in _OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS:
+ missing.append(key.lower())
+ # Guard against a silent regression that makes the comparator match
+ # nothing (the check would then pass vacuously).
+ assert checked >= 5, (
+ f"only {checked} providers reached the stock-client check; "
+ f"the discriminator is likely broken"
+ )
+ assert not missing, (
+ f"Discovered cloud OpenAI-compatible providers missing from the "
+ f"error-rewrite set: {sorted(missing)}"
+ )
+
+ def test_rewrite_base_url_falls_back_to_provider_default(self):
+ """Hardcoded-endpoint providers must name their real base URL in the
+ rewritten message, not "<unknown>"."""
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ assert _resolve_error_rewrite_base_url("qwen", None) == (
+ "https://maas.qwencloudapi.com/compatible-mode/v1"
+ )
+ assert _resolve_error_rewrite_base_url("deepseek", None) == (
+ "https://api.deepseek.com/v1"
+ )
+
+ def test_rewrite_base_url_ignores_custom_endpoint_for_other_providers(
+ self,
+ ):
+ """``custom_endpoint`` is ``llm.openai_endpoint.url`` (default: the
+ OpenRouter URL), which chat/follow-up callers pass regardless of
+ provider. For a hardcoded-endpoint provider it must not replace the
+ URL the client actually used."""
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ assert _resolve_error_rewrite_base_url(
+ "qwen", "https://openrouter.ai/api/v1"
+ ) == ("https://maas.qwencloudapi.com/compatible-mode/v1")
+ assert _resolve_error_rewrite_base_url(
+ "deepseek", "https://openrouter.ai/api/v1"
+ ) == ("https://api.deepseek.com/v1")
+
+ def test_rewrite_base_url_stale_custom_endpoint_does_not_mask_url_setting(
+ self,
+ ):
+ """LM Studio with its own configured URL plus a stale
+ llm.openai_endpoint.url must report the LM Studio URL."""
+ from local_deep_research.settings.manager import (
+ SnapshotSettingsContext,
+ )
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ ctx = SnapshotSettingsContext(
+ {
+ "llm.lmstudio.url": "http://nas:1234/v1",
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
+ )
+ assert (
+ _resolve_error_rewrite_base_url(
+ "lmstudio", "https://openrouter.ai/api/v1", ctx
+ )
+ == "http://nas:1234/v1"
+ )
+
+ def test_rewrite_base_url_openai_endpoint_uses_custom_endpoint(self):
+ """For the openai_endpoint provider the per-run custom endpoint IS
+ the client's base URL (any casing of the provider id)."""
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ for provider in ("openai_endpoint", "OPENAI_ENDPOINT"):
+ assert (
+ _resolve_error_rewrite_base_url(
+ provider, "http://gateway.example/v1"
+ )
+ == "http://gateway.example/v1"
+ )
+
+ @pytest.mark.parametrize("provider", [None, ""])
+ def test_rewrite_base_url_missing_provider_is_none(self, provider):
+ """No provider to look up: the resolver returns None (which the
+ friendly message renders as ``<unknown>``), even with a custom
+ endpoint, because that only applies to ``openai_endpoint``."""
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ assert (
+ _resolve_error_rewrite_base_url(
+ provider, "https://gateway.example/v1"
+ )
+ is None
+ )
+
+ def test_rewrite_base_url_unknown_provider_degrades_to_none(self):
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ assert _resolve_error_rewrite_base_url("no_such_provider", None) is None
+
+ def test_rewrite_message_names_provider_endpoint_and_model(self):
+ """End-to-end contract of the fallback for a hardcoded provider."""
+ from openai import NotFoundError
+
+ from local_deep_research.error_handling.openai_compat_errors import (
+ friendly_openai_compatible_error,
+ )
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ try:
+ raise NotFoundError(
+ message="The model 'qwen3.8-max' does not exist",
+ response=_resp(404),
+ body=None,
+ )
+ except NotFoundError as exc:
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="qwen",
+ base_url=_resolve_error_rewrite_base_url("qwen", None),
+ model="qwen3.8-max",
+ )
+ assert "qwen" in msg
+ assert "https://maas.qwencloudapi.com/compatible-mode/v1" in msg
+ assert "qwen3.8-max" in msg
+ assert "<unknown>" not in msg
+
+ def test_rewrite_base_url_prefers_configured_url_setting(self):
+ """URL-configurable providers (LM Studio, llama.cpp) must report the
+ operator-configured URL, not the localhost class default."""
+ from local_deep_research.settings.manager import (
+ SnapshotSettingsContext,
+ )
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ ctx = SnapshotSettingsContext(
+ {"llm.lmstudio.url": "http://nas:1234/v1"}
+ )
+ assert (
+ _resolve_error_rewrite_base_url("lmstudio", "", ctx)
+ == "http://nas:1234/v1"
+ )
+
+ def test_rewrite_base_url_url_setting_unset_is_not_guessed(self):
+ """Without a configured URL, a URL-configurable provider falls back
+ to None ("<unknown>") rather than the localhost class default."""
+ from local_deep_research.settings.manager import (
+ SnapshotSettingsContext,
+ )
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ ctx = SnapshotSettingsContext({})
+ assert _resolve_error_rewrite_base_url("lmstudio", "", ctx) is None
+
+ def test_rewrite_base_url_url_setting_without_context_is_none(self):
+ """A URL-configurable provider with no settings context must not
+ fall back to the localhost class default."""
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ assert _resolve_error_rewrite_base_url("lmstudio", "", None) is None
+
+ def test_rewrite_base_url_honors_openai_api_base_override(self):
+ """An operator-configured llm.openai.api_base gateway is the URL the
+ client actually uses — the rewrite must name it, not the class
+ default."""
+ from local_deep_research.settings.manager import (
+ SnapshotSettingsContext,
+ )
+ from local_deep_research.web.services.research_service import (
+ _resolve_error_rewrite_base_url,
+ )
+
+ ctx = SnapshotSettingsContext(
+ {"llm.openai.api_base": "https://gateway.example/v1"}
+ )
+ assert (
+ _resolve_error_rewrite_base_url("openai", "", ctx)
+ == "https://gateway.example/v1"
+ )
+ # Without a context (or override) the class default still applies.
+ assert _resolve_error_rewrite_base_url("openai", "", None) == (
+ "https://api.openai.com/v1"
+ )
diff --git a/tests/error_handling/test_report_generator_behavior.py b/tests/error_handling/test_report_generator_behavior.py
index 5b4c7864c3..11a720d6cd 100644
--- a/tests/error_handling/test_report_generator_behavior.py
+++ b/tests/error_handling/test_report_generator_behavior.py
@@ -253,7 +253,7 @@ class TestErrorTypeTokenShortCircuit:
)
result = gen._make_error_user_friendly(msg)
- assert "Could not connect to the configured LLM server" in result
+ assert "Could not connect to the configured LLM endpoint" in result
assert "http://localhost:1234" not in result
assert "Details:" not in result
assert "Cannot connect to the LLM service" not in result
diff --git a/tests/error_handling/test_report_generator_disclosure.py b/tests/error_handling/test_report_generator_disclosure.py
index 20521747e8..680bc76266 100644
--- a/tests/error_handling/test_report_generator_disclosure.py
+++ b/tests/error_handling/test_report_generator_disclosure.py
@@ -25,7 +25,7 @@ from local_deep_research.error_handling.report_generator import (
pytest.param(
"Cannot reach provider at /srv/private/provider-internals.txt "
"(Error type: openai_connection_refused) | Details: private endpoint",
- "configured LLM server",
+ "configured LLM endpoint",
id="typed",
),
],
@@ -198,7 +198,7 @@ def test_report_gives_safe_recovery_for_quick_mode_failures(
),
pytest.param(
"Error: network unavailable (ERROR TYPE: OPENAI_TIMEOUT)",
- "The configured LLM server timed out.",
+ "The configured LLM endpoint timed out.",
id="known-typed-uppercase",
),
pytest.param(
diff --git a/tests/js/components/research-api-key-wiring.test.js b/tests/js/components/research-api-key-wiring.test.js
new file mode 100644
index 0000000000..ad3baf7cec
--- /dev/null
+++ b/tests/js/components/research-api-key-wiring.test.js
@@ -0,0 +1,150 @@
+/**
+ * Static wiring contract for the research form's per-provider API-key
+ * fields: every provider that ships an API-key input must have the
+ * container and label in research.html AND a change listener in
+ * research.js persisting to the matching llm.<provider>.api_key setting.
+ *
+ * Complements research-api-runtime.test.js (which exercises the openai
+ * listener end-to-end for every provider) by pinning the template itself —
+ * the puppeteer script that drove these fields is not part of CI.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+const RESEARCH_TEMPLATE = readFileSync(resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/research.html',
+), 'utf8');
+
+const RESEARCH_COMPONENT = readFileSync(resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/research.js',
+), 'utf8');
+
+const CONTEXT_OVERFLOW_COMPONENT = readFileSync(resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/context-overflow.js',
+), 'utf8');
+
+// The context-overflow dashboard's provider display names. This map
+// silently rotted once on main (deepseek/requesty were missing until this
+// PR added them) — pin it so the next provider addition cannot forget it.
+const PROVIDER_DISPLAY_NAMES = [
+ ['openai_endpoint', 'OpenAI Endpoint'],
+ ['anthropic_endpoint', 'Anthropic Endpoint'],
+ ['ollama', 'Ollama'],
+ ['openai', 'OpenAI'],
+ ['anthropic', 'Anthropic'],
+ ['google', 'Google'],
+ ['openrouter', 'OpenRouter'],
+ ['orcarouter', 'OrcaRouter'],
+ ['atlascloud', 'Atlas Cloud'],
+ ['qwen', 'QwenCloud'],
+ ['deepseek', 'DeepSeek'],
+ ['requesty', 'Requesty'],
+ ['lmstudio', 'LM Studio'],
+ ['llamacpp', 'Llama.cpp'],
+ ['xai', 'xAI'],
+ ['ionos', 'IONOS'],
+];
+
+// Deliberately NOT imported from helpers/api-key-providers.js: this is a
+// static contract pinning the real template, so it must carry its own
+// literal list — a provider removed from the shared helper must still fail
+// here rather than shrink the contract silently.
+const API_KEY_PROVIDERS = [
+ 'openai',
+ 'anthropic',
+ 'google',
+ 'openrouter',
+ 'orcarouter',
+ 'atlascloud',
+ 'qwen',
+ 'xai',
+ 'ionos',
+ 'openai_endpoint',
+ 'anthropic_endpoint',
+ 'ollama',
+ 'lmstudio',
+];
+
+it.each(API_KEY_PROVIDERS)(
+ 'ships the %s API-key container, input, and label in research.html',
+ (key) => {
+ expect(RESEARCH_TEMPLATE).toContain(`id="${key}_api_key_container"`);
+ expect(RESEARCH_TEMPLATE).toContain(`id="${key}_api_key"`);
+ expect(RESEARCH_TEMPLATE).toContain(`for="${key}_api_key"`);
+ expect(RESEARCH_TEMPLATE).toContain(`name="${key}_api_key"`);
+ },
+);
+
+for (const [key, label] of PROVIDER_DISPLAY_NAMES) {
+ it(`labels the ${key} provider on the context-overflow dashboard`, () => {
+ expect(CONTEXT_OVERFLOW_COMPONENT)
+ .toContain(`'${key}': '${label}'`);
+ });
+}
+
+it.each(API_KEY_PROVIDERS)(
+ 'persists the %s API key through a research.js change listener',
+ (key) => {
+ // Quote-agnostic: matches saveSearchSetting('llm.<key>.api_key'
+ // and saveSearchSetting("llm.<key>.api_key".
+ const listenerPattern = new RegExp(
+ `saveSearchSetting\\(['"]llm\\.${key}\\.api_key`,
+ );
+ expect(RESEARCH_COMPONENT).toMatch(listenerPattern);
+ },
+);
+
+// The success toast masks a setting's value when its key names a secret.
+// The PUT response carries no ui_element, so research.js classifies by key
+// name; pin that classifier against the real source so it cannot narrow
+// back to an ``api_key``-only suffix check.
+const SECRET_KEY_RE_SOURCE = RESEARCH_COMPONENT.match(
+ /const SECRET_SETTING_KEY_RE = \/(.+)\/([a-z]*);/,
+);
+
+it('declares the secret-setting classifier used by the toast', () => {
+ expect(SECRET_KEY_RE_SOURCE).not.toBeNull();
+ // The toast's label/detail must key off it, not the api_key suffix.
+ expect(RESEARCH_COMPONENT).toMatch(
+ /const isSecret = SECRET_SETTING_KEY_RE\.test\(settingKey\);/,
+ );
+ expect(RESEARCH_COMPONENT).toMatch(
+ /const hideValue = isSecret \|\| URL_SETTING_KEY_RE\.test\(settingKey\);/,
+ );
+ expect(RESEARCH_COMPONENT).toMatch(
+ /const detail = hideValue \? "updated" : `updated to: \$\{value\}`;/,
+ );
+});
+
+describe('secret-setting classifier', () => {
+ const secretKeyRe = SECRET_KEY_RE_SOURCE
+ ? new RegExp(SECRET_KEY_RE_SOURCE[1], SECRET_KEY_RE_SOURCE[2])
+ : null;
+
+ it.each([
+ ...API_KEY_PROVIDERS.map(key => `llm.${key}.api_key`),
+ 'llm.example.API_KEY',
+ 'search.engine.web.example.access_token',
+ 'notifications.service_token',
+ 'llm.example.client_secret',
+ 'app.admin_password',
+ ])('masks %s', (settingKey) => {
+ expect(secretKeyRe.test(settingKey)).toBe(true);
+ });
+
+ it.each([
+ 'llm.model',
+ 'llm.provider',
+ 'search.tool',
+ 'search.iterations',
+ 'llm.lmstudio.url',
+ 'llm.local_context_window_size',
+ 'embeddings.require_local',
+ ])('shows the value for %s', (settingKey) => {
+ expect(secretKeyRe.test(settingKey)).toBe(false);
+ });
+});
diff --git a/tests/js/components/research-api-runtime.test.js b/tests/js/components/research-api-runtime.test.js
index a5dc718b0a..1f61a29a42 100644
--- a/tests/js/components/research-api-runtime.test.js
+++ b/tests/js/components/research-api-runtime.test.js
@@ -8,8 +8,11 @@ import '@js/config/urls.js';
import '@js/utils/alert-helpers.js';
import '@js/security/xss-protection.js';
import '@js/utils/form-validation.js';
+import { API_KEY_PROVIDERS } from '../helpers/api-key-providers.js';
const AVAILABLE_MODELS = '/settings/api/available-models';
+// The manual full model refresh: a CSRF-protected POST without a query.
+const FULL_REFRESH_REQUEST = { method: 'POST', headers: { 'X-CSRFToken': 'research-csrf' } };
const AVAILABLE_ENGINES = '/settings/api/available-search-engines';
const SETTINGS = '/settings/api';
const START_RESEARCH = '/api/start_research';
@@ -40,20 +43,7 @@ function deferred() {
}
function buildForm() {
- const apiKeys = [
- 'openai',
- 'anthropic',
- 'google',
- 'openrouter',
- 'orcarouter',
- 'atlascloud',
- 'xai',
- 'ionos',
- 'openai_endpoint',
- 'anthropic_endpoint',
- 'ollama',
- 'lmstudio',
- ];
+ const apiKeys = API_KEY_PROVIDERS;
// eslint-disable-next-line no-unsanitized/property -- static, repository-owned test fixture.
document.body.innerHTML = `
<form id="research-form">
@@ -138,20 +128,7 @@ function initialSettings() {
'llm.local_context_window_size': { value: 16384, editable: true },
'search.tool': { value: 'searxng', editable: true },
};
- for (const key of [
- 'openai',
- 'anthropic',
- 'google',
- 'openrouter',
- 'orcarouter',
- 'atlascloud',
- 'xai',
- 'ionos',
- 'openai_endpoint',
- 'anthropic_endpoint',
- 'ollama',
- 'lmstudio',
- ]) {
+ for (const key of API_KEY_PROVIDERS) {
settings[`llm.${key}.api_key`] = {
value: '[REDACTED]',
editable: key !== 'google',
@@ -164,7 +141,7 @@ function routeFetch(url, init = {}) {
const override = responseOverrides.get(url);
if (override) return response(override.body, override);
- if (url === AVAILABLE_MODELS) {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
return response({
provider_options: [
{ value: 'OLLAMA', label: 'Ollama', is_cloud: false },
@@ -321,13 +298,15 @@ it('hydrates the editable settings envelope and reconciles its provider and mode
googleKeyDisabled: true,
activeProviderContainer: 'block',
});
- expect(initialSnapshot.apiKeyValues).toHaveLength(12);
- expect(initialSnapshot.apiKeyValues).toEqual(Array(12).fill(''));
+ expect(initialSnapshot.apiKeyValues).toHaveLength(API_KEY_PROVIDERS.length);
+ expect(initialSnapshot.apiKeyValues)
+ .toEqual(Array(API_KEY_PROVIDERS.length).fill(''));
});
it('replaces one redacted API key through the canonical FastAPI setting route', async () => {
const input = document.getElementById('openai_api_key');
- expect(initialSnapshot.apiKeyValues).toEqual(Array(12).fill(''));
+ expect(initialSnapshot.apiKeyValues)
+ .toEqual(Array(API_KEY_PROVIDERS.length).fill(''));
input.value = 'replacement-openai-key';
input.dispatchEvent(new Event('change', { bubbles: true }));
@@ -352,6 +331,211 @@ it('replaces one redacted API key through the canonical FastAPI setting route',
);
});
+it('never echoes the API key value in the success toast', async () => {
+ const input = document.getElementById('openai_api_key');
+ input.value = 'sk-ws-super-secret';
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'openai api_key updated',
+ 'success',
+ 2000,
+ );
+ });
+ for (const call of window.ui.showMessage.mock.calls) {
+ expect(String(call[0])).not.toContain('sk-ws-super-secret');
+ }
+});
+
+it('consumes the targeted refresh response after an API-key save', async () => {
+ responseOverrides.set('/settings/api/available-models?refresh_provider=openai', {
+ body: {
+ provider_options: [
+ { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
+ { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
+ ],
+ providers: {
+ ollama_models: [{ value: 'qwen3:4b', provider: 'OLLAMA' }],
+ qwen_models: [{ value: 'qwen3.8-max', provider: 'QWEN' }],
+ },
+ },
+ });
+
+ const input = document.getElementById('openai_api_key');
+ input.value = 'replacement-openai-key';
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ // The targeted response is actually consumed: the provider
+ // dropdown is repopulated from its provider_options.
+ expect(document.querySelector('#model_provider option[value="QWEN"]'))
+ .not.toBeNull();
+ });
+});
+
+it('discards a superseded targeted refresh response', async () => {
+ const startedRefreshes = [];
+ const refreshOptions = [];
+ // Intercept PUTs and targeted model fetches so we control resolution
+ // order: key saves succeed immediately, targeted refreshes pend until
+ // we resolve them explicitly.
+ fetchMock.mockImplementation((url, options = {}) => {
+ if (typeof url === 'string' && url.startsWith('/settings/api/available-models?refresh_provider=')) {
+ const provider = url.split('=')[1];
+ startedRefreshes.push(provider);
+ refreshOptions.push(options);
+ const pending = deferred();
+ refreshResponses.set(provider, pending);
+ return pending.promise;
+ }
+ if (options.method === 'PUT') {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ status: 'ok' }),
+ text: vi.fn().mockResolvedValue(''),
+ });
+ }
+ return routeFetch(url, options);
+ });
+ const refreshResponses = new Map();
+
+ const qwenInput = document.getElementById('qwen_api_key');
+ qwenInput.value = 'replacement-qwen-key';
+ qwenInput.dispatchEvent(new Event('change', { bubbles: true }));
+ const openaiInput = document.getElementById('openai_api_key');
+ openaiInput.value = 'another-openai-key';
+ openaiInput.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ expect(startedRefreshes).toEqual(['qwen', 'openai']);
+ });
+ // Both targeted refreshes are CSRF-protected POSTs.
+ for (const options of refreshOptions) {
+ expect(options).toEqual({
+ method: 'POST',
+ headers: { 'X-CSRFToken': 'research-csrf' },
+ });
+ }
+
+ // The NEWER (openai) refresh settles first with its own catalog...
+ refreshResponses.get('openai').resolve(response({
+ provider_options: [
+ { value: 'XAI', label: 'xAI', is_cloud: true },
+ ],
+ providers: {},
+ }));
+ await vi.waitFor(() => {
+ expect(document.querySelector('#model_provider option[value="XAI"]'))
+ .not.toBeNull();
+ });
+
+ // ...then the STALE (qwen) refresh lands late with a different
+ // catalog. The generation guard must discard it: the provider
+ // dropdown keeps the newer response's options.
+ //
+ // Wait for the stale `.then(data => ...)` handler to have actually
+ // run, not for a fixed number of microtask ticks (the chain from
+ // resolve() to that handler is ~6 ticks deep, so a short tick count
+ // asserts before it runs and passes even with the guard removed).
+ // Both branches of the handler - the superseded unwind and the
+ // normal render - clear the model field's 'ldr-loading' class, and
+ // the render (populateModelProviders) is synchronous inside it, so
+ // re-arming the class and waiting for its removal proves the whole
+ // handler has finished.
+ const modelField = document.getElementById('model').parentNode;
+ modelField.classList.add('ldr-loading');
+ refreshResponses.get('qwen').resolve(response({
+ provider_options: [
+ { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
+ ],
+ providers: {},
+ }));
+ await vi.waitFor(() => {
+ expect(modelField.classList.contains('ldr-loading')).toBe(false);
+ });
+ expect(document.querySelector('#model_provider option[value="XAI"]'))
+ .not.toBeNull();
+ expect(document.querySelector('#model_provider option[value="QWEN"]'))
+ .toBeNull();
+});
+
+it('reveals only the QwenCloud API-key field when QWEN is the provider', async () => {
+ const provider = document.getElementById('model_provider');
+ provider.disabled = false;
+ const qwenOption = document.createElement('option');
+ qwenOption.value = 'QWEN';
+ provider.appendChild(qwenOption);
+ provider.value = 'QWEN';
+ provider.dispatchEvent(new Event('change', { bubbles: true }));
+
+ expect(document.getElementById('qwen_api_key_container').style.display).toBe('block');
+ expect(document.getElementById('atlascloud_api_key_container').style.display).toBe('none');
+ expect(document.getElementById('xai_api_key_container').style.display).toBe('none');
+ expect(document.getElementById('endpoint_container').style.display).toBe('none');
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.provider', expect.objectContaining({
+ method: 'PUT',
+ body: JSON.stringify({ value: 'qwen' }),
+ }));
+ });
+});
+
+it.each(API_KEY_PROVIDERS.filter(key => key !== 'openai'))(
+ 'persists the %s API key through the canonical FastAPI setting route',
+ async (key) => {
+ const input = document.getElementById(`${key}_api_key`);
+ input.value = `replacement-${key}-key`;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ const writes = fetchMock.mock.calls.filter(([url, options]) => (
+ url === `/settings/api/llm.${key}.api_key`
+ && options.method === 'PUT'
+ ));
+ expect(writes).toHaveLength(1);
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ `/settings/api/llm.${key}.api_key`,
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'research-csrf',
+ },
+ body: JSON.stringify({ value: `replacement-${key}-key` }),
+ },
+ );
+ // Saving a provider key must refresh just that provider's model
+ // catalog (bypassing the 24h server cache for it alone).
+ // The targeted refresh is state-changing server-side (it calls the
+ // provider with the stored key and rewrites its cached rows), so
+ // it must be a CSRF-protected POST, never a bare GET.
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ `/settings/api/available-models?refresh_provider=${key}`,
+ { method: 'POST', headers: { 'X-CSRFToken': 'research-csrf' } },
+ );
+ });
+ expect(fetchMock).not.toHaveBeenCalledWith(
+ `/settings/api/available-models?refresh_provider=${key}`,
+ );
+ // ...and must never echo the key in the success toast.
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ `${key} api_key updated`,
+ 'success',
+ 2000,
+ );
+ });
+ for (const call of window.ui.showMessage.mock.calls) {
+ expect(String(call[0])).not.toContain(`replacement-${key}-key`);
+ }
+ },
+);
+
it('reports a rejected custom-model save using FastAPI detail and keeps hidden settings in sync', async () => {
responseOverrides.set('/settings/api/llm.model', {
body: { detail: 'model is blocked by policy' },
@@ -580,6 +764,24 @@ it('assigns one settings writer to every control shared with the base bridge', a
}
});
+it('never echoes an endpoint URL value in the success toast', async () => {
+ const credentialUrl = 'http://user:[email protected]/?api_key=url-secret-key';
+ const ollamaUrl = document.getElementById('ollama_url');
+ ollamaUrl.value = credentialUrl;
+ ollamaUrl.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'ollama url updated',
+ 'success',
+ 2000,
+ );
+ });
+ for (const call of window.ui.showMessage.mock.calls) {
+ expect(String(call[0])).not.toContain('url-secret');
+ }
+});
+
it('does not claim a rejected provider save succeeded', async () => {
responseOverrides.set('/settings/api/llm.provider', {
body: { detail: 'provider is operator locked' },
@@ -710,3 +912,197 @@ it('anchors the custom-model hint under ldr-prefixed research markup', async ()
wrapper.className = 'form-group';
}
});
+
+// These fixtures model the server's early snapshot of the other providers:
+// each targeted response has fresh models for its target and old models for
+// the other provider, even when both requests eventually succeed.
+function concurrentModelCatalog(qwen = ['qwen-before-save'], openai = ['openai-before-save']) {
+ const models = (values, provider) => values.map(value => ({ value, label: value, provider }));
+ return {
+ provider_options: [
+ { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
+ { value: 'OPENAI', label: 'OpenAI', is_cloud: true },
+ { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
+ { value: 'OPENAI_ENDPOINT', label: 'OpenAI-compatible', is_cloud: true },
+ ],
+ providers: {
+ qwen_models: models(qwen, 'QWEN'),
+ openai_models: models(openai, 'OPENAI'),
+ ollama_models: models(['qwen3:4b'], 'OLLAMA'),
+ openai_endpoint_models: models(['gateway-model'], 'OPENAI_ENDPOINT'),
+ },
+ };
+}
+
+async function concurrentModelRequests() {
+ // Seed the private cache through the real refresh handler, so each case
+ // begins with the same catalog even though this runtime is initialized once.
+ const refreshButton = document.getElementById('model-refresh');
+ responseOverrides.set(AVAILABLE_MODELS, {
+ body: concurrentModelCatalog(),
+ });
+ refreshButton.click();
+ await vi.waitFor(() => expect(refreshButton.classList.contains('ldr-loading')).toBe(false));
+ // The manual full refresh is a CSRF-protected POST without a query: a
+ // GET carrying force_refresh=true answers 405.
+ expect(fetchMock).toHaveBeenCalledWith(AVAILABLE_MODELS, FULL_REFRESH_REQUEST);
+
+ const requests = [];
+ fetchMock.mockImplementation((url, options = {}) => {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ const provider = new URL(url, 'http://localhost').searchParams.get('refresh_provider');
+ const pending = deferred();
+ requests.push({ provider, options, pending });
+ return pending.promise;
+ }
+ if (options.method === 'PUT') return response({ status: 'ok' });
+ return routeFetch(url, options);
+ });
+ return {
+ requests,
+ async saveKey(provider, value) {
+ const count = requests.length;
+ const input = document.getElementById(`${provider}_api_key`);
+ input.value = value;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ await vi.waitFor(() => expect(requests).toHaveLength(count + 1));
+ expect(requests[count].provider).toBe(provider);
+ return requests[count];
+ },
+ async refreshAll() {
+ const count = requests.length;
+ refreshButton.click();
+ await vi.waitFor(() => expect(requests).toHaveLength(count + 1));
+ expect(requests[count].provider).toBeNull();
+ expect(requests[count].options).toEqual(FULL_REFRESH_REQUEST);
+ return requests[count];
+ },
+ };
+}
+
+async function settleModelRequest(request, catalog, options) {
+ const field = document.getElementById('model').parentNode;
+ field.classList.add('ldr-loading');
+ request.pending.resolve(response(catalog, options));
+ await vi.waitFor(() => expect(field.classList.contains('ldr-loading')).toBe(false));
+}
+
+function modelValuesForProvider(provider) {
+ const select = document.getElementById('model_provider');
+ // Enable the fixture's controls to exercise an ordinary editable form.
+ select.disabled = false;
+ document.getElementById('model').disabled = false;
+ select.value = provider;
+ expect(select.value).toBe(provider);
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ return dropdowns.get('model').getOptions().map(option => option.value);
+}
+
+it.each([
+ ['qwen', 'openai'],
+ ['openai', 'qwen'],
+])('keeps both targeted updates when %s finishes before %s', async (first, second) => {
+ const harness = await concurrentModelRequests();
+ const requests = {
+ qwen: await harness.saveKey('qwen', 'new-qwen-key'),
+ openai: await harness.saveKey('openai', 'new-openai-key'),
+ };
+ const catalogs = {
+ qwen: concurrentModelCatalog(['qwen-after-save']),
+ openai: concurrentModelCatalog(undefined, ['openai-after-save']),
+ };
+ await settleModelRequest(requests[first], catalogs[first]);
+ await settleModelRequest(requests[second], catalogs[second]);
+ expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
+ expect(modelValuesForProvider('OPENAI')).toEqual(['openai-after-save']);
+});
+
+it('keeps a successful targeted update when the newer other-provider request fails', async () => {
+ const harness = await concurrentModelRequests();
+ const qwen = await harness.saveKey('qwen', 'new-qwen-key');
+ const openai = await harness.saveKey('openai', 'new-openai-key');
+ await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
+ await settleModelRequest(openai, {}, { ok: false, status: 503 });
+ expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
+});
+
+it.each([true, false])('ignores an older same-provider response (success=%s)', async olderSucceeds => {
+ const harness = await concurrentModelRequests();
+ const older = await harness.saveKey('qwen', 'older-qwen-key');
+ const newer = await harness.saveKey('qwen', 'replacement-qwen-key');
+ await settleModelRequest(newer, concurrentModelCatalog(['qwen-new-key-model']));
+ await settleModelRequest(older, concurrentModelCatalog(['qwen-old-key-model']), {
+ ok: olderSucceeds,
+ status: olderSucceeds ? 200 : 503,
+ });
+ expect(modelValuesForProvider('QWEN')).toEqual(['qwen-new-key-model']);
+});
+
+it.each([true, false])('merges a full reload with a newer target (full finishes first=%s)', async fullFirst => {
+ const harness = await concurrentModelRequests();
+ const full = await harness.refreshAll();
+ const qwen = await harness.saveKey('qwen', 'new-qwen-key');
+ const finishFull = () => settleModelRequest(full, concurrentModelCatalog(undefined, ['openai-full-refresh']));
+ const finishTarget = () => settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
+ if (fullFirst) {
+ await finishFull();
+ await finishTarget();
+ } else {
+ await finishTarget();
+ await finishFull();
+ }
+ expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
+ expect(modelValuesForProvider('OPENAI')).toEqual(['openai-full-refresh']);
+});
+
+it('preserves a newer empty target list when an older full reload lands', async () => {
+ const harness = await concurrentModelRequests();
+ const full = await harness.refreshAll();
+ const qwen = await harness.saveKey('qwen', 'new-qwen-key');
+ await settleModelRequest(qwen, concurrentModelCatalog([]));
+ await settleModelRequest(full, concurrentModelCatalog());
+ expect(modelValuesForProvider('QWEN')).not.toContain('qwen-before-save');
+});
+
+it('does not restore cloud models from a target superseded by a policy reload', async () => {
+ const harness = await concurrentModelRequests();
+ const qwen = await harness.saveKey('qwen', 'new-qwen-key');
+ const checkbox = document.getElementById('llm_require_local_endpoint');
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event('change', { bubbles: true }));
+ await vi.waitFor(() => expect(harness.requests).toHaveLength(2));
+ const policyRequest = harness.requests[1];
+ expect(policyRequest.provider).toBeNull();
+ const localCatalog = concurrentModelCatalog([], []);
+ localCatalog.provider_options.forEach(option => {
+ if (option.is_cloud) option.disabled = true;
+ });
+ delete localCatalog.providers.openai_endpoint_models;
+ await settleModelRequest(policyRequest, localCatalog);
+ await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
+ expect(document.querySelector('#model_provider option[value="QWEN"]').disabled).toBe(true);
+ expect(modelValuesForProvider('QWEN')).not.toContain('qwen-after-save');
+ checkbox.checked = false;
+});
+
+it('ignores an older full reload after a newer full reload has completed', async () => {
+ const harness = await concurrentModelRequests();
+ const older = await harness.refreshAll();
+ const newer = await harness.refreshAll();
+ await settleModelRequest(newer, concurrentModelCatalog(['qwen-newer-full']));
+ await settleModelRequest(older, concurrentModelCatalog(['qwen-older-full']));
+ expect(modelValuesForProvider('QWEN')).toEqual(['qwen-newer-full']);
+});
+
+it('keeps current provider restrictions when an independent older target responds', async () => {
+ const harness = await concurrentModelRequests();
+ const qwen = await harness.saveKey('qwen', 'new-qwen-key');
+ const openai = await harness.saveKey('openai', 'new-openai-key');
+ const currentCatalog = concurrentModelCatalog([], ['openai-after-save']);
+ currentCatalog.provider_options.find(option => option.value === 'QWEN').disabled = true;
+ await settleModelRequest(openai, currentCatalog);
+ await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
+ expect(document.querySelector('#model_provider option[value="QWEN"]').disabled).toBe(true);
+ expect(modelValuesForProvider('QWEN')).not.toContain('qwen-after-save');
+ expect(modelValuesForProvider('OPENAI')).toEqual(['openai-after-save']);
+});
diff --git a/tests/js/components/research-model-provider.test.js b/tests/js/components/research-model-provider.test.js
index 5358c9c31c..9970fecf82 100644
--- a/tests/js/components/research-model-provider.test.js
+++ b/tests/js/components/research-model-provider.test.js
@@ -17,7 +17,7 @@
* the client-side 5-minute cache before the re-fetch so it actually
* round-trips the server (the server rebuilds provider_options from the
* current policy on every request, so the bare cached endpoint is enough
- * — the slow force_refresh=true path is reserved for cases where the
+ * — the slow POST refresh path is reserved for cases where the
* model *lists* themselves need to be re-discovered).
*/
@@ -116,7 +116,7 @@ beforeAll(async () => {
await import('@js/components/research.js');
document.dispatchEvent(new Event('DOMContentLoaded'));
// Capture the URL of the synchronous-init /available-models request
- // so we can assert it does NOT use force_refresh=true. beforeEach calls
+ // so we can assert the initial read uses the model-list URL. beforeEach calls
// mockClear() which would wipe this otherwise.
initAvailableModelsUrl =
fetchMock.mock.calls
@@ -240,12 +240,12 @@ describe('research form — model provider dropdown', () => {
// beforeEach clears the mock — so we can assert the exact URL
// the mount-time loadModelOptions used. Using the cached
// endpoint is fine because the server rebuilds provider_options
- // from the current policy on every request; force_refresh=true
+ // from the current policy on every request; POST refresh
// would re-discover every provider's models (~1s+ wall clock)
// for no benefit on mount.
expect(initAvailableModelsUrl).not.toBeNull();
expect(initAvailableModelsUrl.startsWith(AVAILABLE_MODELS)).toBe(true);
- expect(initAvailableModelsUrl).not.toContain('force_refresh=true');
+ expect(initAvailableModelsUrl).toBe(AVAILABLE_MODELS);
});
it('renders disabled <option> with the policy reason appended to the label', async () => {
@@ -306,7 +306,7 @@ describe('research form — model provider dropdown', () => {
// And a re-fetch of the providers list (cache miss because we
// invalidated after the PUT). The URL is the bare cached
// endpoint — the server rebuilds provider_options from the
- // current policy every request, so force_refresh=true is
+ // current policy every request, so POST refresh is
// unnecessary here.
await vi.waitFor(
() => {
@@ -335,13 +335,13 @@ describe('research form — model provider dropdown', () => {
expect(getIndex).toBeGreaterThanOrEqual(0);
expect(putIndex).toBeLessThan(getIndex);
- // And specifically NOT the slow force_refresh=true path —
+ // And specifically NOT the slow POST refresh path —
// its ~1s+ wall-clock cost is what motivated this regression.
const forceRefreshCalls = allCalls.filter(
- ([u]) =>
+ ([u, init]) =>
typeof u === 'string' &&
u.startsWith(AVAILABLE_MODELS) &&
- u.includes('force_refresh=true')
+ init?.method === 'POST'
);
expect(forceRefreshCalls).toHaveLength(0);
});
@@ -393,10 +393,10 @@ describe('research form — model provider dropdown', () => {
expect(putIndex).toBeLessThan(getIndex);
const forceRefreshCalls = allCalls.filter(
- ([u]) =>
+ ([u, init]) =>
typeof u === 'string' &&
u.startsWith(AVAILABLE_MODELS) &&
- u.includes('force_refresh=true')
+ init?.method === 'POST'
);
expect(forceRefreshCalls).toHaveLength(0);
});
@@ -777,9 +777,9 @@ it('ignores an older manual model response after a policy refresh completes', as
{ value: 'OLLAMA', label: 'Ollama', disabled: false },
] }),
});
- fetchMock.mockImplementation((url) => {
+ fetchMock.mockImplementation((url, options) => {
if (url.startsWith(AVAILABLE_MODELS)) {
- if (url.includes('force_refresh=true') && !requestedManual) {
+ if (options?.method === 'POST' && !requestedManual) {
requestedManual = true;
return manual;
}
@@ -839,9 +839,9 @@ it('clears the model loading state when a superseded request rejects', async ()
let resolveNewer;
const newer = new Promise((resolve) => { resolveNewer = resolve; });
let requestedManual = false;
- fetchMock.mockImplementation((url) => {
+ fetchMock.mockImplementation((url, options) => {
if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
- if (url.includes('force_refresh=true') && !requestedManual) {
+ if (options?.method === 'POST' && !requestedManual) {
requestedManual = true;
return manual;
}
@@ -925,9 +925,9 @@ it('keeps the loader bounded when a superseded request succeeds', async () => {
let resolveNewer;
const newer = new Promise((resolve) => { resolveNewer = resolve; });
let requestedManual = false;
- fetchMock.mockImplementation((url) => {
+ fetchMock.mockImplementation((url, options) => {
if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
- if (url.includes('force_refresh=true') && !requestedManual) {
+ if (options?.method === 'POST' && !requestedManual) {
requestedManual = true;
return manual;
}
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index ebd479bd5e..b9d3b63a70 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -124,8 +124,7 @@ beforeAll(async () => {
document.dispatchEvent(new Event('DOMContentLoaded'));
// Capture the model-list request count synchronously, before any async
// reload path can add to it (see initAvailableModelsCalls above).
- // Use startsWith (not ===) so any query parameter variant (e.g.
- // ?force_refresh=true) is counted alongside reads against the bare URL.
+ // Count model-list calls against the shared read/refresh path.
initAvailableModelsCalls = fetchMock.mock.calls.filter(
([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
).length;
diff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.js
index 52f401439a..fb99c2a347 100644
--- a/tests/js/components/settings-fetch-error-handling.test.js
+++ b/tests/js/components/settings-fetch-error-handling.test.js
@@ -55,7 +55,8 @@ describe('settings request error handling', () => {
];
const excludedPatterns = [
'const response = await fetch(URLS.SETTINGS_API.OLLAMA_STATUS, {',
- 'const request = fetch(url)',
+ "fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrfToken } })",
+ ': fetch(url))',
'const request = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)',
];
const handledCalls = SETTINGS_SOURCE.match(
@@ -70,7 +71,7 @@ describe('settings request error handling', () => {
expect(SETTINGS_SOURCE).toContain(pattern);
});
expect(handledCalls).toHaveLength(6);
- expect(rawCalls).toHaveLength(3);
+ expect(rawCalls).toHaveLength(4);
});
it('preserves the settings domain success and failure checks', () => {
diff --git a/tests/js/components/settings-refresh-ownership-runtime.test.js b/tests/js/components/settings-refresh-ownership-runtime.test.js
index fb3919be36..ac15efcf13 100644
--- a/tests/js/components/settings-refresh-ownership-runtime.test.js
+++ b/tests/js/components/settings-refresh-ownership-runtime.test.js
@@ -115,7 +115,7 @@ it('keeps the newest overlapping model and search refresh results', async () =>
let currentModels = baselineModels;
let currentEngines = baselineEngines;
- const fetchMock = vi.fn((url) => {
+ const fetchMock = vi.fn((url, options) => {
if (url === URLS.SETTINGS_API.BASE) {
return Promise.resolve(jsonResponse({ status: 'success', settings }));
}
@@ -128,7 +128,8 @@ it('keeps the newest overlapping model and search refresh results', async () =>
if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
return Promise.resolve(jsonResponse({ enabled: false, count: 0, backups: [] }));
}
- if (url === `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`) {
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS && options?.method === 'POST') {
+ expect(options.headers['X-CSRFToken']).toBe('csrf-refresh-ownership');
const request = deferred();
modelRefreshes.push(request);
return request.promise;
diff --git a/tests/js/helpers/api-key-providers.js b/tests/js/helpers/api-key-providers.js
new file mode 100644
index 0000000000..d11f7ec4c7
--- /dev/null
+++ b/tests/js/helpers/api-key-providers.js
@@ -0,0 +1,22 @@
+/**
+ * Providers whose API-key field the research form ships. Shared by the
+ * research.js runtime and wiring-contract tests so a new provider cannot
+ * land in one fixture but not the other. Keep in sync with research.html
+ * and the change listeners in research.js.
+ */
+
+export const API_KEY_PROVIDERS = [
+ 'openai',
+ 'anthropic',
+ 'google',
+ 'openrouter',
+ 'orcarouter',
+ 'atlascloud',
+ 'qwen',
+ 'xai',
+ 'ionos',
+ 'openai_endpoint',
+ 'anthropic_endpoint',
+ 'ollama',
+ 'lmstudio',
+];
diff --git a/tests/js/pages/benchmark-endpoint-runtime.test.js b/tests/js/pages/benchmark-endpoint-runtime.test.js
index 295eba7f7a..8af00ca8d1 100644
--- a/tests/js/pages/benchmark-endpoint-runtime.test.js
+++ b/tests/js/pages/benchmark-endpoint-runtime.test.js
@@ -319,8 +319,10 @@ it('loads and force-refreshes evaluation providers and model options', async ()
document.querySelector('.refresh-btn').click();
await flushPromises();
- expect(fetchMock.mock.calls[1][0])
- .toBe('/settings/api/available-models?force_refresh=true');
+ expect(fetchMock.mock.calls[1]).toEqual([
+ '/settings/api/available-models',
+ { method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
+ ]);
expect(harness.getProviders()).toEqual([
{ value: 'OPENAI', label: 'OpenAI' },
{ value: 'OLLAMA', label: 'Ollama' },
@@ -386,7 +388,8 @@ it('does not schedule a fallback request while force refresh is in flight', asyn
expect(fetchMock).toHaveBeenCalledOnce();
expect(fetchMock).toHaveBeenCalledWith(
- '/settings/api/available-models?force_refresh=true',
+ '/settings/api/available-models',
+ { method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
);
refreshResponse.resolve({
@@ -422,8 +425,8 @@ it('does not let a deferred initial model response overwrite a force refresh', a
vi.useFakeTimers();
const initialResponse = deferred();
const refreshResponse = deferred();
- const fetchMock = vi.fn((url) => {
- if (url.endsWith('?force_refresh=true')) return refreshResponse.promise;
+ const fetchMock = vi.fn((_url, options) => {
+ if (options?.method === 'POST') return refreshResponse.promise;
return initialResponse.promise;
});
vi.stubGlobal('fetch', fetchMock);
@@ -511,8 +514,10 @@ it('cancels the pending debounced load when refresh is requested immediately', a
await vi.advanceTimersByTimeAsync(500);
expect(fetchMock).toHaveBeenCalledOnce();
- expect(fetchMock.mock.calls[0][0])
- .toBe('/settings/api/available-models?force_refresh=true');
+ expect(fetchMock.mock.calls[0]).toEqual([
+ '/settings/api/available-models',
+ { method: 'POST', headers: { 'X-CSRFToken': 'csrf-benchmark' } },
+ ]);
expect(window.evaluationModels.openai[0].value).toBe('manual-model');
});
diff --git a/tests/js/pages/news-actions-direct-runtime.test.js b/tests/js/pages/news-actions-direct-runtime.test.js
index f249f3126a..4a509e7300 100644
--- a/tests/js/pages/news-actions-direct-runtime.test.js
+++ b/tests/js/pages/news-actions-direct-runtime.test.js
@@ -1175,6 +1175,7 @@ it('refreshes from the real template button without relying on inline JavaScript
it.each([
['OPENAI:gpt-4.1-mini', 'OPENAI', 'gpt-4.1-mini'],
+ ['QWEN:qwen3.8-max', 'QWEN', 'qwen3.8-max'],
['OLLAMA:llama3.1:8b', 'OLLAMA', 'llama3.1:8b'],
['ollama:llama3.1:8b', 'OLLAMA', 'llama3.1:8b'],
['llama3.1:8b', undefined, 'llama3.1:8b'],
diff --git a/tests/llm/test_provider_adapter_contracts.py b/tests/llm/test_provider_adapter_contracts.py
index 01d57e585c..015c8d905a 100644
--- a/tests/llm/test_provider_adapter_contracts.py
+++ b/tests/llm/test_provider_adapter_contracts.py
@@ -661,6 +661,9 @@ class TestNormalizeProvider:
("OpenAI", "openai"),
("OPENAI_ENDPOINT", "openai_endpoint"),
("ollama", "ollama"),
+ (" QWEN ", "qwen"),
+ ("\topenai_endpoint\n", "openai_endpoint"),
+ (" ", None),
],
)
def test_none_safe_and_case_folding(self, raw, expected):
diff --git a/tests/llm_providers/implementations/test_qwen_provider.py b/tests/llm_providers/implementations/test_qwen_provider.py
new file mode 100644
index 0000000000..9e027dc503
--- /dev/null
+++ b/tests/llm_providers/implementations/test_qwen_provider.py
@@ -0,0 +1,140 @@
+"""Tests for the QwenCloud LLM provider."""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.llm.providers.base import Exposure
+from local_deep_research.llm.providers.implementations.qwen import (
+ QwenCloudProvider,
+)
+
+
+class TestQwenCloudProvider:
+ """Tests for QwenCloud metadata and OpenAI-compatible construction."""
+
+ def test_metadata(self):
+ assert QwenCloudProvider.provider_name == "QwenCloud"
+ assert QwenCloudProvider.provider_key == "QWEN"
+ assert QwenCloudProvider.company_name == "QwenCloud"
+ assert QwenCloudProvider.api_key_setting == "llm.qwen.api_key"
+ assert QwenCloudProvider.default_base_url == (
+ "https://maas.qwencloudapi.com/compatible-mode/v1"
+ )
+ assert QwenCloudProvider.default_model == "qwen3.8-max"
+ assert QwenCloudProvider.is_cloud is True
+ assert QwenCloudProvider.egress_exposure is Exposure.EXPOSING
+
+ def test_create_llm_uses_qwencloud_endpoint(self):
+ def get_setting(key, default=None, *args, **kwargs):
+ settings = {
+ "llm.qwen.api_key": "test-qwen-key",
+ "llm.max_tokens": None,
+ "llm.streaming": None,
+ "llm.max_retries": None,
+ "llm.request_timeout": None,
+ }
+ return settings.get(key, default)
+
+ with (
+ patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ side_effect=get_setting,
+ ),
+ patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as chat_openai,
+ ):
+ llm = Mock()
+ chat_openai.return_value = llm
+
+ result = QwenCloudProvider.create_llm(
+ model_name=QwenCloudProvider.default_model,
+ temperature=0.2,
+ )
+
+ assert result is llm
+ chat_openai.assert_called_once()
+ params = chat_openai.call_args.kwargs
+ assert params["model"] == "qwen3.8-max"
+ assert params["base_url"] == (
+ "https://maas.qwencloudapi.com/compatible-mode/v1"
+ )
+ assert params["api_key"] == "test-qwen-key"
+ assert params["temperature"] == 0.2
+
+ def test_model_catalog_requires_authentication(self):
+ assert QwenCloudProvider.requires_auth_for_models() is True
+
+ def test_model_catalog_sends_key_to_qwencloud_endpoint(self):
+ import sys
+
+ from openai import DefaultHttpxClient, OpenAI
+
+ # OpenAI 2.x uses httpx; 3.x uses httpx2. Use the installed
+ # SDK's transport so this covers both supported versions.
+ for base in DefaultHttpxClient.__mro__[1:]:
+ transport = sys.modules.get(base.__module__.split(".")[0])
+ if transport is not None and hasattr(transport, "MockTransport"):
+ break
+ else:
+ pytest.fail("could not identify the OpenAI SDK transport")
+
+ requests = []
+
+ def respond(request):
+ requests.append(request)
+ return transport.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [
+ {
+ "id": "qwen3.8-max",
+ "object": "model",
+ "created": 0,
+ "owned_by": "qwen",
+ }
+ ],
+ },
+ )
+
+ with transport.Client(
+ transport=transport.MockTransport(respond)
+ ) as http_client:
+ with patch(
+ "openai.OpenAI",
+ side_effect=lambda **kwargs: OpenAI(
+ http_client=http_client, **kwargs
+ ),
+ ):
+ models = QwenCloudProvider.list_models_for_api(
+ api_key="test-qwen-key"
+ )
+
+ assert models == [{"value": "qwen3.8-max", "label": "qwen3.8-max"}]
+ assert len(requests) == 1
+ assert requests[0].method == "GET"
+ assert str(requests[0].url) == (
+ "https://maas.qwencloudapi.com/compatible-mode/v1/models"
+ )
+ assert requests[0].headers["Authorization"] == "Bearer test-qwen-key"
+
+ def test_create_llm_raises_without_api_key(self):
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with pytest.raises(ValueError, match="API key not configured"):
+ QwenCloudProvider.create_llm()
+
+ @pytest.mark.parametrize(
+ ("api_key", "expected"),
+ [("test-qwen-key", True), (None, False), ("", False)],
+ )
+ def test_is_available_reflects_api_key(self, api_key, expected):
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ return_value=api_key,
+ ):
+ assert QwenCloudProvider.is_available() is expected
diff --git a/tests/llm_providers/test_openai_base_coverage.py b/tests/llm_providers/test_openai_base_coverage.py
index f87fd3bc12..a16519bcb0 100644
--- a/tests/llm_providers/test_openai_base_coverage.py
+++ b/tests/llm_providers/test_openai_base_coverage.py
@@ -274,6 +274,31 @@ class TestListModelsForApi:
assert result == []
mock_openai.assert_not_called()
+ def test_strips_surrounding_whitespace_from_api_key(self):
+ """A pasted key with surrounding whitespace must reach the SDK
+ trimmed — matching create_llm's resolve_api_key, so research works
+ while model discovery does not silently fail auth.
+ """
+ mock_client = MagicMock()
+ model = MagicMock()
+ model.id = "qwen3.8-max"
+ mock_client.models.list.return_value.data = [model]
+ with patch("openai.OpenAI", return_value=mock_client) as mock_openai:
+ result = _KeyedProvider.list_models_for_api(
+ api_key=" sk-ws-pasted-key "
+ )
+ assert [m["value"] for m in result] == ["qwen3.8-max"]
+ mock_openai.assert_called_once()
+ assert mock_openai.call_args.kwargs["api_key"] == "sk-ws-pasted-key"
+
+ def test_whitespace_only_api_key_treated_as_missing(self):
+ """A whitespace-only key is "no key": auth-required providers return
+ [] instead of sending a guaranteed-401 bearer token."""
+ with patch("openai.OpenAI") as mock_openai:
+ result = _KeyedProvider.list_models_for_api(api_key=" ")
+ assert result == []
+ mock_openai.assert_not_called()
+
# ---------------------------------------------------------------------------
# list_models()
diff --git a/tests/llm_providers/test_openai_base_endpoint_log_redaction.py b/tests/llm_providers/test_openai_base_endpoint_log_redaction.py
new file mode 100644
index 0000000000..30ddf1f549
--- /dev/null
+++ b/tests/llm_providers/test_openai_base_endpoint_log_redaction.py
@@ -0,0 +1,88 @@
+"""The OpenAI-compatible provider never logs a credential embedded in its
+base URL.
+
+``create_llm`` logs ``endpoint: <base_url>`` at INFO on every LLM creation,
+and ``list_models_for_api`` logs the URL at DEBUG. For the custom
+``openai_endpoint`` provider the base URL is operator input returned
+unchanged by ``normalize_url``, so a key placed in it (userinfo or
+``?api_key=``) reached the logs verbatim.
+
+``create_llm`` runs for real (``ChatOpenAI`` construction makes no request).
+The only stubbed seam is ``openai.OpenAI`` for model listing, which would
+otherwise make a network call. The endpoint is a private IP literal, so
+SSRF validation needs no DNS lookup.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from loguru import logger
+
+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+)
+
+KEY = "sk-leakedkey1234567890"
+PASSWORD = "pw-leaked-9876"
+ENDPOINT = f"http://user:{PASSWORD}@192.168.1.50:8000/v1?api_key={KEY}"
+
+
+def _capture():
+ messages = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: messages.append(m.record["message"]), level="DEBUG"
+ )
+ return messages, sink_id
+
+
+def _release(sink_id):
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+
+def _assert_no_credential(messages):
+ for message in messages:
+ assert KEY not in message, message
+ assert PASSWORD not in message, message
+
+
+def test_create_llm_endpoint_log_is_redacted():
+ snapshot = {
+ "llm.openai_endpoint.url": {"value": ENDPOINT},
+ "llm.openai_endpoint.api_key": {"value": "not-the-logged-key"},
+ }
+ messages, sink_id = _capture()
+ try:
+ llm = CustomOpenAIEndpointProvider.create_llm(
+ model_name="some-model", settings_snapshot=snapshot
+ )
+ finally:
+ _release(sink_id)
+
+ assert llm is not None
+ creating = [m for m in messages if "LLM with model: some-model" in m]
+ assert creating, f"create_llm never logged its endpoint: {messages}"
+ assert (
+ "endpoint: http://192.168.1.50:8000/v1?api_key=REDACTED"
+ in (creating[0])
+ ), creating[0]
+ _assert_no_credential(messages)
+
+
+def test_list_models_endpoint_log_is_redacted():
+ client = MagicMock()
+ client.models.list.return_value = MagicMock(data=[])
+ messages, sink_id = _capture()
+ try:
+ with patch("openai.OpenAI", return_value=client) as openai_cls:
+ CustomOpenAIEndpointProvider.list_models_for_api(
+ api_key="not-the-logged-key", base_url=ENDPOINT
+ )
+ finally:
+ _release(sink_id)
+
+ openai_cls.assert_called_once()
+ fetching = [m for m in messages if m.startswith("Fetching models from")]
+ assert fetching, f"list_models_for_api never logged its URL: {messages}"
+ assert "api_key=REDACTED" in fetching[0], fetching[0]
+ _assert_no_credential(messages)
diff --git a/tests/security/test_csrf_coverage.py b/tests/security/test_csrf_coverage.py
index 3b08f1f654..0380c30056 100644
--- a/tests/security/test_csrf_coverage.py
+++ b/tests/security/test_csrf_coverage.py
@@ -48,6 +48,7 @@ import secrets as _secrets_mod
import uuid
from contextlib import contextmanager
from pathlib import Path
+from unittest.mock import patch
import pytest
from local_deep_research.web.dependencies import csrf as csrf_mod
@@ -744,6 +745,56 @@ def test_index_all_post_with_a_valid_token_passes_the_middleware():
)
+ "query",
+ ["?refresh_provider=openai", "?force_refresh=true", ""],
+ ids=["targeted", "force-refresh-flag", "full-without-query"],
+)
+def test_model_refresh_requires_post_and_csrf(authenticated_client, query):
+ """A model refresh calls providers with the user's stored keys and
+ rewrites their cached ``ProviderModel`` rows (``force_refresh=true``
+ used to delete every cached row on a plain GET), so it is a mutation:
+ a GET carrying ``refresh_provider`` or ``force_refresh=true`` answers
+ 405 with ``Allow: POST`` without reaching discovery, a POST with no
+ token is refused by the middleware, and a tokened POST reaches the
+ handler. A plain GET read, and a GET with ``force_refresh=false``,
+ still reach the handler (controls).
+ """
+ client = authenticated_client
+ path = "/settings/api/available-models"
+ with patch(
+ "local_deep_research.web.routers.settings."
+ "_resolve_model_discovery_policy",
+ side_effect=RuntimeError("discovery reached"),
+ ) as discover:
+ if query:
+ legacy = client.get(f"{path}{query}")
+ assert legacy.status_code == 405, legacy.text
+ assert legacy.headers["allow"] == "POST"
+ discover.assert_not_called()
+
+ with _no_token(client):
+ bare = client.post(f"{path}{query}")
+ assert _csrf_refused(bare), bare.text
+ discover.assert_not_called()
+
+ client.post(f"{path}{query}")
+ assert discover.call_count == 1, (
+ "CONTROL FAILED — the tokened POST never reached the handler"
+ )
+
+ client.get(path)
+ assert discover.call_count == 2, (
+ "CONTROL FAILED — a plain GET read no longer reaches the handler"
+ )
+
+ client.get(f"{path}?force_refresh=false")
+ assert discover.call_count == 3, (
+ "CONTROL FAILED — a GET with force_refresh=false is a read and "
+ "must still reach the handler"
+ )
+
+
def test_the_challenge_does_not_depend_on_how_the_path_is_spelled():
"""No path spelling can move a mutation outside the middleware.
diff --git a/tests/security/test_data_sanitizer.py b/tests/security/test_data_sanitizer.py
index 82a81140aa..34c8baa2c3 100644
--- a/tests/security/test_data_sanitizer.py
+++ b/tests/security/test_data_sanitizer.py
@@ -535,7 +535,15 @@ class TestStripSettingsSnapshot:
"message",
[
"Authentication with the configured LLM provider failed.",
+ "Could not connect to the configured LLM endpoint.",
+ "The configured LLM endpoint timed out.",
+ "The configured model was not found at the LLM endpoint.",
+ "The LLM endpoint rejected the request.",
+ "Could not connect to the configured LLM server.",
"The configured LLM server timed out.",
+ "The configured model was not found on the LLM server.",
+ "The configured LLM model was not found.",
+ "The LLM server rejected the request.",
"There was a problem with the search engine configuration.",
],
)
@@ -544,6 +552,28 @@ class TestStripSettingsSnapshot:
assert public["error"] == message
+ @pytest.mark.parametrize("prefix", ["", "Research failed: "])
+ @pytest.mark.parametrize("separator", [" | Details: ", "\n"])
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Could not connect to the configured LLM endpoint.",
+ "The configured LLM endpoint timed out.",
+ "The configured model was not found at the LLM endpoint.",
+ "The LLM endpoint rejected the request.",
+ ],
+ )
+ def test_endpoint_message_with_added_detail_is_not_trusted(
+ self, message, prefix, separator
+ ):
+ public = strip_settings_snapshot(
+ {"error": f"{prefix}{message}{separator}/srv/private/key"}
+ )
+
+ assert public["error"] == (
+ "Research failed. Check the server logs for details."
+ )
+
@pytest.mark.parametrize(
"error",
[
diff --git a/tests/security/test_followup_and_settings_guards_fastapi.py b/tests/security/test_followup_and_settings_guards_fastapi.py
index 80bb54d5fc..d23dae2a38 100644
--- a/tests/security/test_followup_and_settings_guards_fastapi.py
+++ b/tests/security/test_followup_and_settings_guards_fastapi.py
@@ -533,7 +533,10 @@ def _discovery_probe(client, api_key_setting):
stack.enter_context(
patch(f"{PROVIDERS}.discover_providers", return_value=discovered)
)
- response = client.get(f"{AVAILABLE_MODELS_PATH}?force_refresh=true")
+ response = client.post(
+ AVAILABLE_MODELS_PATH,
+ headers={"X-CSRFToken": _csrf(client)},
+ )
return response, list_models
@@ -583,7 +586,7 @@ class TestCrossProviderCredentialLeak:
def test_provider_without_api_key_setting_gets_empty_string_not_settings(
self, live_app
):
- """``GET /settings/api/available-models`` — the consumer-side half.
+ """``POST /settings/api/available-models`` — the consumer-side half.
A provider declaring ``api_key_setting = None`` (LM Studio,
Llama.cpp) must be handed ``""``. Without the short-circuit it is
diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.py
index 47812712b4..345326704b 100644
--- a/tests/security/test_settings_egress_and_secrets_fastapi.py
+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py
@@ -372,9 +372,7 @@ def _discovery_probe(client, ollama_url, resolver=None):
with ExitStack() as stack:
for manager in managers:
stack.enter_context(manager)
- response = client.get(
- "/settings/api/available-models?force_refresh=true"
- )
+ response = client.post("/settings/api/available-models")
return response, credential_reads, list_models
diff --git a/tests/security/test_url_redaction.py b/tests/security/test_url_redaction.py
new file mode 100644
index 0000000000..42f2c19b02
--- /dev/null
+++ b/tests/security/test_url_redaction.py
@@ -0,0 +1,532 @@
+"""``redact_url_credentials``: credentials embedded in a configured URL.
+
+Used by the log lines listed in
+``changelog.d/+redact-base-url-query-credentials.security.md`` (the
+OpenAI-compatible, Ollama and OpenAI-embeddings provider logs, the research
+route fallbacks, the friendly error rewrite and the debug settings dump).
+The worker's parameters line keeps main's stricter origin-only redaction.
+Other URL-printing log lines do not use this helper.
+These tests pin the
+redaction scope; ``tests/error_handling/test_openai_compat_errors.py``
+covers the historical ``_strip_credentials`` alias.
+"""
+
+import time
+
+import pytest
+
+from local_deep_research.security.url_redaction import (
+ MAX_REDACTABLE_URL_LEN,
+ is_credential_param_name,
+ redact_url_credentials,
+)
+
+SECRET = "sk-leak1234567890abcdef"
+
+
+class TestRepeatedQuestionMark:
+ def test_credential_after_a_second_question_mark(self):
+ out = redact_url_credentials(f"https://h/v1?x=1?api_key={SECRET}")
+ assert SECRET not in out
+ assert out == "https://h/v1?x=1?api_key=REDACTED"
+
+ def test_credential_inside_an_embedded_url_value(self):
+ out = redact_url_credentials(
+ f"https://h/v1?next=https://a/b?token={SECRET}&y=1"
+ )
+ assert SECRET not in out
+ assert out == "https://h/v1?next=https://a/b?token=REDACTED&y=1"
+
+
+class TestBareItemBoundary:
+ """A value-less query or fragment item is redacted from 17 characters
+ on; a 16-character one is kept."""
+
+ @pytest.mark.parametrize("separator", ["?", "#"])
+ def test_sixteen_characters_are_kept(self, separator):
+ item = "b" * 16
+ url = f"https://h/v1{separator}{item}"
+ assert redact_url_credentials(url) == url
+
+ @pytest.mark.parametrize("separator", ["?", "#"])
+ def test_seventeen_characters_are_redacted(self, separator):
+ out = redact_url_credentials(f"https://h/v1{separator}{'b' * 17}")
+ assert out == f"https://h/v1{separator}REDACTED"
+
+
+class TestCredentialNames:
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "accessToken",
+ "authToken",
+ "clientSecret",
+ "apiKey",
+ "dbPassword",
+ "sessionToken",
+ "pass",
+ "credential",
+ "credentials",
+ "jwt",
+ "session",
+ "user.password",
+ "X-Api-Key",
+ # Array-style names, a ``+``-encoded space, an acronym prefix.
+ "api_key[0]",
+ "key[]",
+ "auth[token]",
+ "data[api_key]",
+ "api+key",
+ "XAPIKey",
+ # Run-together names: a token/secret/password/passwd ending, or
+ # a listed ``...key`` compound.
+ "authtoken",
+ "accesstoken",
+ "apitoken",
+ "APITOKEN",
+ "refreshtoken",
+ "clientsecret",
+ "dbpassword",
+ "rootpasswd",
+ "secretkey",
+ "privatekey",
+ "xapikey",
+ "APIKEY",
+ "ocpapimsubscriptionkey",
+ # Every bracket part is checked, and a stray bracket or a
+ # non-alphanumeric byte ends a word.
+ "api_key[a][b]",
+ "api_key[prod]",
+ "token[value]",
+ "api_key[a][0]",
+ "api_key]",
+ "api_key[]]",
+ "key%00",
+ "auth%00",
+ # OAuth grant secrets: RFC 7521/7523 assertions, the RFC 7636
+ # PKCE verifier, the RFC 5849 verifier, the RFC 8628 device
+ # code, an OpenID Connect ID token hint, and a bare refresh
+ # token.
+ "assertion",
+ "client_assertion",
+ "clientAssertion",
+ "clientassertion",
+ "code_verifier",
+ "codeVerifier",
+ "oauth_verifier",
+ "device_code",
+ "deviceCode",
+ "id_token_hint",
+ "refresh",
+ # A passphrase, and the RFC 6749 authorization code.
+ "passphrase",
+ "sslPassphrase",
+ "keypassphrase",
+ "auth_code",
+ "authCode",
+ "authorization_code",
+ "AuthorizationCode",
+ # Run-together spellings of the whole-name credentials.
+ "devicecode",
+ "DEVICECODE",
+ "idtokenhint",
+ "IDTOKENHINT",
+ "authcode",
+ "authorizationcode",
+ # A trailing number, version or plural does not change what a
+ # name holds.
+ "api_key_2",
+ "api_key_1",
+ "apiKey2",
+ "APIKEY2",
+ "XAPIKey2",
+ "key1",
+ "key2",
+ "keyv2",
+ "token2",
+ "authtoken2",
+ "access_token_v2",
+ "accessTokenV2",
+ "apiKeyV2",
+ "key_v2",
+ "x-api-key-v2",
+ "api_key_v2_1",
+ "api_keys",
+ "apikeys",
+ "api_keys[0]",
+ "keys",
+ "tokens",
+ "tokensv2",
+ "client_secrets",
+ "passwords",
+ "credentials2",
+ "pass2",
+ "sas2",
+ "device_code_2",
+ "auth_codes",
+ "code2",
+ "refresh_v2",
+ "id_token_hint_2",
+ ],
+ )
+ def test_is_credential(self, name):
+ assert is_credential_param_name(name)
+ out = redact_url_credentials(f"https://h/v1?{name}={SECRET}")
+ assert out == f"https://h/v1?{name}=REDACTED"
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "tokenizer",
+ "passthrough",
+ "monkey",
+ "keyboard",
+ "oauth",
+ "error_code",
+ "sessionId",
+ "passage",
+ "keyword",
+ "items[0]",
+ "data[name]",
+ "OAuth",
+ # Words that merely end in ``key`` / ``token``-like letters.
+ "turkey",
+ "hockey",
+ "whiskey",
+ "fookey",
+ "secretary",
+ "items[0][1]",
+ # Non-secret neighbours of the OAuth grant names: only the
+ # whole names ``refresh``, ``device_code`` and ``id_token_hint``
+ # match, not every name ending in their last word.
+ "client_assertion_type",
+ "code_challenge",
+ "code_challenge_method",
+ "login_hint",
+ "force_refresh",
+ "refresh_interval",
+ "country_code",
+ # Non-secret neighbours of the number / version / plural rule:
+ # taking the suffix off leaves an ordinary word, and a name
+ # that is only a version keeps it.
+ "page2",
+ "page_2",
+ "items",
+ "ids",
+ "v2",
+ "api_v2",
+ "limit_v2",
+ "version2",
+ "refresh_interval_2",
+ "country_codes",
+ "error_codes",
+ "login_hints",
+ "codecs",
+ "monkeys",
+ "hotkeys",
+ "fookeys",
+ "keyboards",
+ "keywords",
+ "tokenizers",
+ "passthrough2",
+ # A plural ``s`` is not taken off after another ``s``, and a
+ # name ending in ``es`` keeps its ``e``.
+ "access",
+ "bypass",
+ "class",
+ "sass",
+ "passes",
+ "status",
+ # Digits that are part of an ordinary word.
+ "oauth2",
+ "s3",
+ "md5",
+ "sha256",
+ "ipv4",
+ ],
+ )
+ def test_lookalike_is_not_credential(self, name):
+ assert not is_credential_param_name(name)
+ url = f"https://h/v1?{name}=visible"
+ assert redact_url_credentials(url) == url
+
+ @pytest.mark.parametrize(
+ "name", ["sort_key", "sort_keys", "max_tokens", "codes", "sessions"]
+ )
+ def test_documented_over_redaction(self, name):
+ """Names that hold no secret but end in a credential word (also
+ after the plural is taken off) are redacted -- the safe direction
+ the rule errs towards, as its comment says."""
+ assert is_credential_param_name(name)
+ out = redact_url_credentials(f"https://h/v1?{name}=visible")
+ assert out == f"https://h/v1?{name}=REDACTED"
+
+ @pytest.mark.parametrize(
+ "url,expected",
+ [
+ (
+ f"https://h/v1?api_key_2={SECRET}&page2=7",
+ "https://h/v1?api_key_2=REDACTED&page2=7",
+ ),
+ (
+ f"https://h/v1#access_token_v2={SECRET}&v2=1",
+ "https://h/v1#access_token_v2=REDACTED&v2=1",
+ ),
+ (
+ f"https://h/v1;passphrase={SECRET}/x",
+ "https://h/v1;passphrase=REDACTED/x",
+ ),
+ (
+ f"https://h/v1?items=3&api_keys%5B%5D={SECRET}",
+ "https://h/v1?items=3&api_keys%5B%5D=REDACTED",
+ ),
+ ],
+ ids=["query", "fragment", "path-parameter", "encoded-array"],
+ )
+ def test_suffixed_names_are_redacted_in_every_position(self, url, expected):
+ out = redact_url_credentials(url)
+ assert SECRET not in out
+ assert out == expected
+
+ def test_overlong_name_is_treated_as_a_credential(self):
+ """A name longer than the inspected limit is not parsed word by
+ word; its value is redacted (fail closed)."""
+ name = "q" * 300
+ assert is_credential_param_name(name)
+ out = redact_url_credentials(f"https://h/v1?{name}={SECRET}")
+ assert out == f"https://h/v1?{name}=REDACTED"
+
+
+# 200 KB inputs shaped to hit the per-name loop that used to be quadratic
+# (one rescan per trailing ``[..]`` group). Explicit ids keep the test node
+# ids short.
+_BIG = 200_000
+_SLOW_NAMES = [
+ pytest.param("k" + "[]" * (_BIG // 2), id="empty-index-groups"),
+ pytest.param("k" + "[0]" * (_BIG // 3), id="digit-index-groups"),
+ pytest.param("k" + "[a]" * (_BIG // 3), id="named-groups"),
+ pytest.param("k" + "%5B%5D" * (_BIG // 6), id="percent-encoded-groups"),
+ pytest.param("aB" * (_BIG // 2), id="camel-case"),
+ pytest.param("a" * _BIG, id="plain"),
+]
+
+
+class TestLargeInputsAreCheap:
+ @pytest.mark.parametrize("name", _SLOW_NAMES)
+ def test_long_name_is_classified_quickly(self, name):
+ start = time.perf_counter()
+ assert is_credential_param_name(name)
+ assert time.perf_counter() - start < 0.5
+
+ @pytest.mark.parametrize("name", _SLOW_NAMES)
+ def test_long_url_is_redacted_quickly(self, name):
+ start = time.perf_counter()
+ out = redact_url_credentials(f"http://localhost:1234/v1?{name}=1")
+ assert time.perf_counter() - start < 0.5
+ assert out == "<unknown>"
+
+ def test_url_over_the_cap_is_withheld(self):
+ url = "https://h/v1?x=" + "a" * MAX_REDACTABLE_URL_LEN
+ assert redact_url_credentials(url) == "<unknown>"
+
+ def test_url_at_the_cap_is_still_redacted(self):
+ prefix = f"https://h/v1?api_key={SECRET}&x="
+ url = prefix + "a" * (MAX_REDACTABLE_URL_LEN - len(prefix))
+ assert len(url) == MAX_REDACTABLE_URL_LEN
+ out = redact_url_credentials(url)
+ assert SECRET not in out
+ assert out.startswith("https://h/v1?api_key=REDACTED&x=aaa")
+
+
+class TestPathSegments:
+ def test_sk_key_segment_is_redacted(self):
+ out = redact_url_credentials(f"https://h/{SECRET}/v1")
+ assert out == "https://h/REDACTED/v1"
+
+ def test_long_dashless_alnum_segment_is_redacted(self):
+ segment = "hf_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"
+ out = redact_url_credentials(f"https://h/{segment}/v1")
+ assert out == "https://h/REDACTED/v1"
+
+ def test_key_prefixed_segment_is_redacted(self):
+ out = redact_url_credentials("https://h/key-abcdefghijklmnopqrst/v1")
+ assert out == "https://h/REDACTED/v1"
+
+ @pytest.mark.parametrize(
+ "segment",
+ [
+ "SK-leak1234567890abcdef",
+ "Sk-leak1234567890abcdef",
+ "KEY-abcdefghijklmnopqrst",
+ "Key-abcdefghijklmnopqrst",
+ ],
+ )
+ def test_key_prefix_matches_in_any_letter_case(self, segment):
+ out = redact_url_credentials(f"https://h/{segment}/v1")
+ assert out == "https://h/REDACTED/v1"
+
+ def test_32_hex_id_is_redacted(self):
+ """Documented over-redaction: a 32-hex account id (e.g. a
+ Cloudflare account id) is indistinguishable from a hex key."""
+ out = redact_url_credentials(
+ "https://h/accounts/0123456789abcdef0123456789abcdef/ai/v1"
+ )
+ assert out == "https://h/accounts/REDACTED/ai/v1"
+
+ @pytest.mark.parametrize(
+ "segment",
+ [
+ "text-embedding-3-large-2024-preview-model",
+ "Qwen2-VL-72B-Instruct-Preview-Model-Extra",
+ "abcdefghijklmnopqrstuvwxyzabcdefghij",
+ ],
+ )
+ def test_hyphenated_or_letter_only_names_are_kept(self, segment):
+ url = f"https://h/models/{segment}/v1"
+ assert redact_url_credentials(url) == url
+
+ def test_uuid_and_short_segments_are_kept(self):
+ url = (
+ "https://h/openai/deployments/"
+ "123e4567-e89b-12d3-a456-426614174000/v1/sk-short"
+ )
+ assert redact_url_credentials(url) == url
+
+
+class TestSchemelessUserinfo:
+ def test_userinfo_without_scheme_is_dropped(self):
+ out = redact_url_credentials("user:[email protected]:8443/v1?x=1")
+ assert "SECRETPW" not in out
+ assert out == "gw.example:8443/v1?x=1"
+
+ def test_host_port_without_userinfo_passes_through(self):
+ assert redact_url_credentials("localhost:1234/v1") == (
+ "localhost:1234/v1"
+ )
+
+
+class TestAuthorityIsKeptExactly:
+ def test_host_case_and_port_spelling_are_preserved(self):
+ out = redact_url_credentials("https://u:[email protected]:0443/v1")
+ assert out == "https://GW.Example.COM:0443/v1"
+
+ def test_ipv6_authority_is_preserved(self):
+ out = redact_url_credentials("http://u:p@[::1]:8080/v1?key=abc")
+ assert out == "http://[::1]:8080/v1?key=REDACTED"
+
+
+class TestNonStringInput:
+ @pytest.mark.parametrize(
+ "value", [None, "", b"https://u:p@h/v1", 12, ["https://h"]]
+ )
+ def test_returns_unknown_marker(self, value):
+ assert redact_url_credentials(value) == "<unknown>"
+
+
+class TestFailsClosedWhenUserinfoIsNotIsolated:
+ """An unencoded ``/``, ``?`` or ``#`` in a password makes ``urlsplit``
+ end the authority early, so ``@`` never reaches the netloc and the
+ password would pass through. Such input is not redacted piecemeal;
+ the whole value is withheld."""
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://user:Abc/[email protected]/v1",
+ "https://user:Abc#[email protected]/v1",
+ "https://user:[email protected]/v1",
+ "user:Abc/[email protected]/v1",
+ "https://user:123/[email protected]/v1",
+ # An ``@`` inside the password followed by ``/``, ``?`` or
+ # ``#`` and another ``@``: the netloc ends at the separator,
+ # so it holds exactly one ``@`` and looked isolated.
+ "https://user:P@ss/[email protected]/v1",
+ "https://user:Abc@12/[email protected]/v1",
+ "https://user:Ab@[email protected]/v1",
+ "https://user:Ab@c#[email protected]/v1",
+ "https://user:Ab@1/[email protected]/v1",
+ "user:Ab@c/Secret99@host/v1",
+ ],
+ )
+ def test_unisolated_userinfo_returns_unknown(self, url):
+ out = redact_url_credentials(url)
+ assert out == "<unknown>"
+ assert "secret" not in out
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://[::1]x/v1",
+ "http://h.example:80a/v1",
+ # Parameters inside the parsed authority are not redacted
+ # there, so the whole value is withheld.
+ f"https://host;api_key={SECRET}",
+ f"https://host:443;api_key={SECRET}",
+ f"//h&sig={SECRET}",
+ f"https://u:p@host&token={SECRET}/v1",
+ f"https://host=x{SECRET}/v1",
+ ],
+ )
+ def test_malformed_authority_returns_unknown(self, url):
+ assert redact_url_credentials(url) == "<unknown>"
+
+ @pytest.mark.parametrize("url", ["user:pw@", "@"])
+ def test_nothing_left_after_userinfo_returns_unknown(self, url):
+ assert redact_url_credentials(url) == "<unknown>"
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://user:pw@host/[email protected]",
+ "https://host/[email protected]",
+ "https://host/v1/users/[email protected]",
+ ],
+ )
+ def test_at_sign_outside_the_authority_returns_unknown(self, url):
+ """Policy: any ``@`` outside the authority is withheld, including
+ a harmless-looking e-mail address."""
+ assert redact_url_credentials(url) == "<unknown>"
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ # Scheme-less, no ``/`` before the query or fragment: the
+ # leading userinfo part ends at ``?`` / ``#``, so an ``@`` in
+ # the query or fragment is not taken as the end of userinfo
+ # (which would drop the host and pass the credentials on).
+ "user:pw@host?x=a@b&api_key=secretKEY123",
+ "user:pw@host#a@b&access_token=secretKEY123",
+ "user:pw@host:[email protected]&api_key=secretKEY123",
+ "host:8080?x=a@b&api_key=secretKEY123",
+ "localhost:1234?note=a@b&token=secretKEY123",
+ "user:secretKEY123@host?x=a@b",
+ "user:secretKEY123@host#a@b",
+ "secretKEY123@host?q=r@s",
+ ],
+ )
+ def test_schemeless_at_sign_in_query_or_fragment_returns_unknown(self, url):
+ assert redact_url_credentials(url) == "<unknown>"
+
+ def test_schemeless_userinfo_before_query_is_stripped(self):
+ assert redact_url_credentials(
+ "user:pw@host:8080?api_key=secretKEY123"
+ ) == ("host:8080?api_key=REDACTED")
+
+ def test_at_sign_inside_a_password_is_still_stripped(self):
+ """``@`` in the password with no later separator stays inside the
+ authority; the last ``@`` ends the userinfo."""
+ assert redact_url_credentials("https://u:p@ss@host/v1") == (
+ "https://host/v1"
+ )
+
+ def test_digit_port_and_empty_port_are_kept(self):
+ assert redact_url_credentials("http://h.example:99999/v1") == (
+ "http://h.example:99999/v1"
+ )
+ assert redact_url_credentials("https://h:/v1") == "https://h:/v1"
+
+
+class TestSchemeIsLowercased:
+ def test_scheme_lowercased_host_case_kept(self):
+ out = redact_url_credentials("HTTPS://u:[email protected]:8443/v1")
+ assert out == "https://GW.Example.COM:8443/v1"
diff --git a/tests/security/test_url_redaction_log_sites.py b/tests/security/test_url_redaction_log_sites.py
new file mode 100644
index 0000000000..d1a634985b
--- /dev/null
+++ b/tests/security/test_url_redaction_log_sites.py
@@ -0,0 +1,196 @@
+"""Log sites that print a configured LLM URL redact its credentials.
+
+Covers the research start route's settings fallback (DEBUG) and the
+``LDR_LOG_SETTINGS=debug`` settings dump. The OpenAI-compatible provider's
+own log lines are covered in
+``tests/llm_providers/test_openai_base_endpoint_log_redaction.py``.
+"""
+
+from unittest.mock import Mock
+
+import pytest
+from loguru import logger
+
+from local_deep_research.settings.logger import log_settings
+from local_deep_research.web.routers.research import _extract_research_params
+
+KEY = "sk-leakedkey1234567890"
+PASSWORD = "pw-leaked-9876"
+ENDPOINT = f"http://user:{PASSWORD}@192.168.1.50:8000/v1?api_key={KEY}"
+
+
+def _captured(fn):
+ messages = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: messages.append(m.record["message"]), level="DEBUG"
+ )
+ try:
+ result = fn()
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+ return result, messages
+
+
+def _assert_no_credential(messages):
+ assert messages, "nothing was logged, so nothing was checked"
+ for message in messages:
+ assert KEY not in message, message
+ assert PASSWORD not in message, message
+
+
+def test_research_route_settings_fallback_log_is_redacted():
+ values = {"llm.openai_endpoint.url": ENDPOINT}
+ settings_manager = Mock()
+ settings_manager.get_setting.side_effect = lambda key, default=None: (
+ values.get(key, default)
+ )
+
+ params, messages = _captured(
+ lambda: _extract_research_params(
+ {"model_provider": "openai_endpoint"}, settings_manager
+ )
+ )
+
+ # The resolved value itself is unchanged -- only the log is redacted.
+ assert params["custom_endpoint"] == ENDPOINT
+ fallback = [m for m in messages if "using database setting" in m]
+ assert "api_key=REDACTED" in " ".join(fallback), messages
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_redacts_url_values():
+ settings = {
+ "llm.openai_endpoint.url": {"value": ENDPOINT},
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.model": {"value": "m"},
+ }
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ dump = " ".join(messages)
+ assert "api_key=REDACTED" in dump, dump
+ assert "http://localhost:11434" in dump
+ _assert_no_credential(messages)
+
+
+def test_research_route_ollama_url_fallback_log_is_redacted():
+ values = {"llm.ollama.url": ENDPOINT}
+ settings_manager = Mock()
+ settings_manager.get_setting.side_effect = lambda key, default=None: (
+ values.get(key, default)
+ )
+
+ params, messages = _captured(
+ lambda: _extract_research_params(
+ {"model_provider": "ollama"}, settings_manager
+ )
+ )
+
+ assert params["ollama_url"] == ENDPOINT
+ fallback = [m for m in messages if "No ollama_url in request" in m]
+ assert "api_key=REDACTED" in " ".join(fallback), messages
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_redacts_schemeless_userinfo():
+ settings = {"custom.proxy": f"user:{PASSWORD}@proxy.example:3128"}
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ assert "proxy.example:3128" in " ".join(messages)
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_redacts_urls_in_non_dict_settings():
+ class _Settings:
+ def __init__(self):
+ self.endpoint = ENDPOINT
+ self.model = "m"
+
+ _result, messages = _captured(
+ lambda: log_settings(_Settings(), "Settings", force_level="debug")
+ )
+
+ dump = " ".join(messages)
+ assert "api_key=REDACTED" in dump, dump
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_redacts_schemeless_password_with_spaces():
+ settings = {"custom.proxy": "user:pa ss [email protected]:3128"}
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ assert "proxy.example:3128" in " ".join(messages)
+ _assert_no_credential(messages)
+
+
+ ("value", "host"),
+ [
+ # Docker/compose service names contain ``_``.
+ (f"user:{PASSWORD}@ollama_server:11434", "ollama_server:11434"),
+ (f"admin:{PASSWORD}@project_ollama_1:11434/api", "project_ollama_1"),
+ (f"user:{PASSWORD}@bücher.example", "bücher.example"),
+ (f"user:{PASSWORD}@host.example;x=1", "host.example"),
+ (f"user:{PASSWORD}@[fe80::1%eth0]:11434", "[fe80::1%eth0]:11434"),
+ (f"user:{PASSWORD}@proxy.example:3128 ", "proxy.example:3128"),
+ (f"user:{PASSWORD}@proxy.example:3128\t", "proxy.example:3128"),
+ (f" user:{PASSWORD}@proxy.example:3128", "proxy.example:3128"),
+ (f"user:@{PASSWORD}@proxy.example:3128", "proxy.example:3128"),
+ # An empty user, and a newline inside the password.
+ (f":{PASSWORD}@proxy.example:3128/v1", "proxy.example:3128/v1"),
+ (f"user:pa\n{PASSWORD}@proxy.example:3128", "proxy.example:3128"),
+ ],
+)
+def test_debug_settings_dump_redacts_schemeless_userinfo_forms(value, host):
+ """Scheme-less userinfo is recognised whatever the host looks like
+ and with surrounding whitespace."""
+ settings = {"custom.proxy": value}
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ assert host in " ".join(messages)
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_redacts_schemeless_query_credentials():
+ settings = {"llm.lmstudio.url": f"localhost:1234/v1?api_key={KEY}"}
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ assert "localhost:1234/v1?api_key=REDACTED" in " ".join(messages)
+ _assert_no_credential(messages)
+
+
+def test_debug_settings_dump_keeps_ordinary_values():
+ """Prose and model ids containing ``:`` (and even an ``@``) are not
+ mistaken for scheme-less userinfo."""
+ settings = {
+ "llm.model": "gemma3:12b",
+ "report.prompt": "Note: mail [email protected] with questions",
+ "search.time": "10:30",
+ "report.title": "Summary: see [email protected].",
+ "report.question": "What changed? Why?",
+ "ui.color": "#ffcc00",
+ }
+
+ _result, messages = _captured(
+ lambda: log_settings(settings, "Settings", force_level="debug")
+ )
+
+ dump = " ".join(messages)
+ for value in settings.values():
+ assert value in dump, dump
diff --git a/tests/security/test_url_redaction_provider_logs.py b/tests/security/test_url_redaction_provider_logs.py
new file mode 100644
index 0000000000..09b8f4f51f
--- /dev/null
+++ b/tests/security/test_url_redaction_provider_logs.py
@@ -0,0 +1,155 @@
+"""Ollama and OpenAI-embeddings provider log lines redact their base URL.
+
+Sibling of ``tests/llm_providers/test_openai_base_endpoint_log_redaction.py``.
+The real provider code runs:
+ * ``OllamaProvider.create_llm`` -- building ``ChatOllama`` makes no request;
+ * ``OpenAIEmbeddingsProvider.create_embeddings`` -- building
+ ``OpenAIEmbeddings`` makes no request;
+ * ``OpenAIEmbeddingsProvider.get_available_models`` -- ``openai.OpenAI`` is
+ stubbed, as it is the only network seam;
+ * ``OllamaProvider.is_available`` -- ``requests.get`` inside ``safe_get``
+ is stubbed to fail, as it is the only network seam.
+Each path runs the SSRF check (``assert_base_url_safe``) on a private IP
+literal, so that check needs no DNS lookup.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+import requests
+from loguru import logger
+
+from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+)
+from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+)
+
+KEY = "sk-leakedkey1234567890"
+PASSWORD = "pw-leaked-9876"
+
+
+def _url(port):
+ return f"http://user:{PASSWORD}@192.168.1.50:{port}/v1?api_key={KEY}"
+
+
+def _captured(fn):
+ messages = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: messages.append(m.record["message"]), level="DEBUG"
+ )
+ try:
+ result = fn()
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+ return result, messages
+
+
+def _assert_no_credential(messages):
+ assert messages, "nothing was logged, so nothing was checked"
+ for message in messages:
+ assert KEY not in message, message
+ assert PASSWORD not in message, message
+
+
+def test_ollama_create_llm_logs_redacted_base_url():
+ snapshot = {"llm.ollama.url": {"value": _url(11434)}}
+
+ llm, messages = _captured(
+ lambda: OllamaProvider.create_llm(
+ model_name="llama3.1:8b", settings_snapshot=snapshot
+ )
+ )
+
+ assert llm is not None
+ creating = [m for m in messages if m.startswith("Creating ChatOllama")]
+ assert creating, messages
+ assert "base_url=http://192.168.1.50:11434" in creating[0], creating[0]
+ assert "api_key=REDACTED" in creating[0], creating[0]
+ _assert_no_credential(messages)
+
+
+ ("error", "warning"),
+ [
+ (requests.Timeout("read timed out"), "Request timeout after 3s: "),
+ (requests.ConnectionError("refused"), "Request failed for "),
+ ],
+ ids=["timeout", "connection-error"],
+)
+def test_ollama_availability_failure_warning_shows_only_the_origin(
+ error, warning
+):
+ """The changelog fragment says the shared request helper's warning for
+ a failed or timed-out availability check shows no more than the URL's
+ scheme, host and port: pin that, alongside the redacted INFO line."""
+ snapshot = {"llm.ollama.url": {"value": _url(11434)}}
+
+ with patch(
+ "local_deep_research.security.safe_requests.requests.get",
+ side_effect=error,
+ ) as get:
+ available, messages = _captured(
+ lambda: OllamaProvider.is_available(settings_snapshot=snapshot)
+ )
+
+ assert available is False
+ get.assert_called_once()
+ checking = [m for m in messages if m.startswith("Checking Ollama")]
+ assert checking, messages
+ assert "api_key=REDACTED" in checking[0], checking[0]
+ helper = [m for m in messages if m.startswith(warning)]
+ assert helper == [f"{warning}http://192.168.1.50:11434"], messages
+ _assert_no_credential(messages)
+
+
+def test_openai_embeddings_keyless_base_url_log_is_redacted():
+ embeddings, messages = _captured(
+ lambda: OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-large-2024-preview-model",
+ settings_snapshot={},
+ base_url=_url(8000),
+ api_key="",
+ )
+ )
+
+ assert embeddings is not None
+ keyless = [m for m in messages if "no API key set but base_url=" in m]
+ assert keyless, messages
+ assert "api_key=REDACTED" in keyless[0], keyless[0]
+ _assert_no_credential(messages)
+
+
+def test_openai_embeddings_model_listing_log_is_redacted():
+ client = MagicMock()
+ # Model discovery opens the client as a context manager.
+ client.__enter__.return_value = client
+ client.models.list.return_value = MagicMock(
+ data=[MagicMock(id="text-embedding-3-large-2024-preview-model")]
+ )
+ snapshot = {
+ "embeddings.openai.api_key": {"value": "not-the-logged-key"},
+ "embeddings.openai.base_url": {"value": _url(8000)},
+ }
+
+ with patch("openai.OpenAI", return_value=client) as openai_cls:
+ models, messages = _captured(
+ lambda: OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot=snapshot
+ )
+ )
+
+ openai_cls.assert_called_once()
+ assert models == [
+ {
+ "value": "text-embedding-3-large-2024-preview-model",
+ "label": "text-embedding-3-large-2024-preview-model",
+ }
+ ]
+ fetched = [m for m in messages if m.startswith("Fetched 1 models")]
+ assert fetched, messages
+ assert "api_key=REDACTED" in fetched[0], fetched[0]
+ _assert_no_credential(messages)
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 8d119e92e7..260a2a6031 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -1325,7 +1325,7 @@
"name": "Google API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
@@ -1339,7 +1339,7 @@
"name": "IONOS API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
@@ -1592,7 +1592,7 @@
"name": "OpenRouter API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
@@ -1606,7 +1606,7 @@
"name": "OrcaRouter API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
@@ -1675,6 +1675,10 @@
"label": "OrcaRouter API",
"value": "orcarouter"
},
+ {
+ "label": "QwenCloud API",
+ "value": "qwen"
+ },
{
"label": "xAI Grok API",
"value": "xai"
@@ -1686,6 +1690,20 @@
"value": "ollama",
"visible": true
},
+ "llm.qwen.api_key": {
+ "category": "llm_general",
+ "description": "API key to use for the QwenCloud provider.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "QwenCloud API Key",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "password",
+ "value": null,
+ "visible": true
+ },
"llm.request_timeout": {
"category": "llm_parameters",
"description": "Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit; values below 1 second are clamped to 1, and non-numeric or non-finite values use the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively.",
@@ -1709,7 +1727,7 @@
"name": "Requesty API Key",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "LLM",
"ui_element": "password",
"value": null,
"visible": true
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index 569ea75b43..2182638e20 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -224,6 +224,7 @@ def _is_dynamic_setting(key: str) -> bool:
"llm.requesty.",
"llm.orcarouter.",
"llm.xai.",
+ "llm.qwen.",
"llm.ollama.",
"llm.lmstudio.",
"llm.openai_endpoint.",
@@ -634,6 +635,21 @@ class TestSettingsDefaultsIntegrity:
f"and re-run."
)
+ def test_llm_settings_are_typed_llm(self, defaults):
+ """Every ``llm.*`` default ships with ``type: LLM``.
+
+ ``SettingsManager.set_setting`` self-heals an ``llm.*`` row's type
+ to LLM on every write, so a shipped ``SEARCH`` (as five provider
+ API keys once had) only made the stored type flip on first edit
+ and mislabelled the key in exports and docs/CONFIGURATION.md.
+ """
+ mistyped = sorted(
+ (key, setting.get("type"))
+ for key, setting in defaults.items()
+ if key.startswith("llm.") and setting.get("type") != "LLM"
+ )
+ assert mistyped == [], f"llm.* settings not typed LLM: {mistyped}"
+
# -- Test 11: Reverse value-type consistency ----------------------------
def test_value_type_implies_ui_element(self, defaults):
diff --git a/tests/test_api_key_frontend_settings.py b/tests/test_api_key_frontend_settings.py
index 682b5bb450..0a4b4428fd 100644
--- a/tests/test_api_key_frontend_settings.py
+++ b/tests/test_api_key_frontend_settings.py
@@ -12,6 +12,7 @@ API_KEY_SETTINGS = {
"OPENROUTER": "llm.openrouter.api_key",
"ORCAROUTER": "llm.orcarouter.api_key",
"ATLASCLOUD": "llm.atlascloud.api_key",
+ "QWEN": "llm.qwen.api_key",
"XAI": "llm.xai.api_key",
"IONOS": "llm.ionos.api_key",
"OPENAI_ENDPOINT": "llm.openai_endpoint.api_key",
@@ -26,6 +27,7 @@ CLOUD_PROVIDERS = [
"OPENROUTER",
"ORCAROUTER",
"ATLASCLOUD",
+ "QWEN",
"XAI",
"IONOS",
]
@@ -88,6 +90,14 @@ class TestAPIKeyProviderMapping:
assert AtlasCloudProvider.api_key_setting == "llm.atlascloud.api_key"
+ def test_qwen_provider_api_key_setting(self):
+ """Test QwenCloud provider uses correct API key setting."""
+ from local_deep_research.llm.providers.implementations.qwen import (
+ QwenCloudProvider,
+ )
+
+ assert QwenCloudProvider.api_key_setting == "llm.qwen.api_key"
+
def test_orcarouter_provider_api_key_setting(self):
"""Test OrcaRouter provider uses correct API key setting."""
from local_deep_research.llm.providers.implementations.orcarouter import (
@@ -345,6 +355,9 @@ class TestFrontendAPIKeyMapping:
from local_deep_research.llm.providers.implementations.atlascloud import (
AtlasCloudProvider,
)
+ from local_deep_research.llm.providers.implementations.qwen import (
+ QwenCloudProvider,
+ )
from local_deep_research.llm.providers.implementations.xai import (
XAIProvider,
)
@@ -365,6 +378,7 @@ class TestFrontendAPIKeyMapping:
"GOOGLE": GoogleProvider,
"OPENROUTER": OpenRouterProvider,
"ATLASCLOUD": AtlasCloudProvider,
+ "QWEN": QwenCloudProvider,
"XAI": XAIProvider,
"IONOS": IONOSProvider,
"OPENAI_ENDPOINT": CustomOpenAIEndpointProvider,
diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.py
index aaa4cfc5d7..479bccbdd1 100644
--- a/tests/theme_tests/test_accent_ink_contrast.py
+++ b/tests/theme_tests/test_accent_ink_contrast.py
@@ -941,26 +941,26 @@ DYNAMIC_INLINE_STYLES = {
("inline", "none"),
None,
),
- # context-overflow.js L517: ``const utilColor = utilPct > 80 ?
+ # context-overflow.js L520: ``const utilColor = utilPct > 80 ?
# 'var(--error-color)' : utilPct > 50 ? 'var(--warning-color)' :
- # 'var(--success-color)'``, assigned once. L516 makes utilPct a number
- # (``Math.round(...)`` or 0); L579's truncationPercent is a number too.
- ("static/js/components/context-overflow.js", 571, "color"): (
+ # 'var(--success-color)'``, assigned once. L519 makes utilPct a number
+ # (``Math.round(...)`` or 0); L582's truncationPercent is a number too.
+ ("static/js/components/context-overflow.js", 574, "color"): (
"utilColor",
("var(--error-color)", "var(--warning-color)", "var(--success-color)"),
None,
),
- ("static/js/components/context-overflow.js", 574, "background"): (
+ ("static/js/components/context-overflow.js", 577, "background"): (
"utilColor",
("var(--error-color)", "var(--warning-color)", "var(--success-color)"),
None,
),
- ("static/js/components/context-overflow.js", 574, "width"): (
+ ("static/js/components/context-overflow.js", 577, "width"): (
"Math.min(utilPct, 100)",
(NUMBER,),
None,
),
- ("static/js/components/context-overflow.js", 579, "width"): (
+ ("static/js/components/context-overflow.js", 582, "width"): (
"Math.min(truncationPercent, 100)",
(NUMBER,),
None,
@@ -1279,7 +1279,7 @@ def test_inline_style_scan_finds_the_known_expressions():
assert {
("templates/pages/journal_quality.html", 723, "background"),
("templates/pages/journal_quality.html", 831, "background"),
- ("static/js/components/context-overflow.js", 574, "background"),
+ ("static/js/components/context-overflow.js", 577, "background"),
("static/js/components/details.js", 712, "color"),
("templates/pages/metrics.html", 975, "color"),
} <= set(found), sorted(found)
@@ -1292,7 +1292,7 @@ def test_inline_style_scan_finds_the_known_expressions():
assert {
("templates/pages/journal_quality.html", "style@L723"),
("templates/pages/journal_quality.html", "style@L831"),
- ("static/js/components/context-overflow.js", "style@L574"),
+ ("static/js/components/context-overflow.js", "style@L577"),
} <= expanded, sorted(expanded)
@@ -1594,7 +1594,7 @@ NON_TEXT_STATUS_FILLS = {
("templates/auth/register.html", ".ldr-strength-medium"): _STRENGTH,
("templates/auth/register.html", ".ldr-strength-strong"): _STRENGTH,
# The utilColor and _stateColor() bars; their figures sit beside them.
- ("static/js/components/context-overflow.js", "style@L574"): _BAR,
+ ("static/js/components/context-overflow.js", "style@L577"): _BAR,
("templates/pages/journal_quality.html", "style@L831"): _BAR,
}
@@ -1686,7 +1686,7 @@ def test_fill_inks_read_on_swapped_fills():
("styles.css", ".ldr-console-log-entry.ldr-log-error .ldr-log-badge"),
("styles.css", ".ldr-badge-danger"),
("templates/pages/journal_quality.html", ".ldr-quality-dangerous"),
- ("static/js/components/context-overflow.js", "style@L250"),
+ ("static/js/components/context-overflow.js", "style@L253"),
} <= found
assert len(pairs) >= 80, "too few fill/ink pairs were found"
palettes = _palettes()
diff --git a/tests/ui_tests/test_api_key_inputs.js b/tests/ui_tests/test_api_key_inputs.js
index 8cce9ed621..b9a17f9e77 100644
--- a/tests/ui_tests/test_api_key_inputs.js
+++ b/tests/ui_tests/test_api_key_inputs.js
@@ -18,6 +18,7 @@ const API_KEY_PROVIDERS = [
{ provider: 'OPENROUTER', containerId: 'openrouter_api_key_container', inputId: 'openrouter_api_key', settingKey: 'llm.openrouter.api_key' },
{ provider: 'ORCAROUTER', containerId: 'orcarouter_api_key_container', inputId: 'orcarouter_api_key', settingKey: 'llm.orcarouter.api_key' },
{ provider: 'ATLASCLOUD', containerId: 'atlascloud_api_key_container', inputId: 'atlascloud_api_key', settingKey: 'llm.atlascloud.api_key' },
+ { provider: 'QWEN', containerId: 'qwen_api_key_container', inputId: 'qwen_api_key', settingKey: 'llm.qwen.api_key' },
{ provider: 'XAI', containerId: 'xai_api_key_container', inputId: 'xai_api_key', settingKey: 'llm.xai.api_key' },
{ provider: 'IONOS', containerId: 'ionos_api_key_container', inputId: 'ionos_api_key', settingKey: 'llm.ionos.api_key' },
{ provider: 'OPENAI_ENDPOINT', containerId: 'openai_endpoint_api_key_container', inputId: 'openai_endpoint_api_key', settingKey: 'llm.openai_endpoint.api_key' },
diff --git a/tests/utilities/test_utilities_layer_contracts.py b/tests/utilities/test_utilities_layer_contracts.py
index 5f81035057..11e011ac44 100644
--- a/tests/utilities/test_utilities_layer_contracts.py
+++ b/tests/utilities/test_utilities_layer_contracts.py
@@ -543,7 +543,7 @@ class TestUrlUtilsUnvalidatedInput:
assert is_safe_custom_llm_endpoint(link_local_endpoint) is False
def test_normalize_provider_raises_on_non_string_input(self):
- """``normalize_provider`` is ``provider.lower() if provider``.
+ """``normalize_provider`` is ``provider.strip().lower()`` (or None).
It is applied directly to ``data.get("model_provider")`` from an
untyped JSON body in ``research.py`` and ``followup.py``, and
diff --git a/tests/web/routers/test_chat_router_error_edges.py b/tests/web/routers/test_chat_router_error_edges.py
index 5fb7c06bc9..c2f0c2ae85 100644
--- a/tests/web/routers/test_chat_router_error_edges.py
+++ b/tests/web/routers/test_chat_router_error_edges.py
@@ -692,3 +692,120 @@ async def test_retry_unmapped_value_error_and_route_exception_return_500(
)
assert response.status_code == expected
assert service.insert_message_in_db.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# custom_endpoint forwarding (PR #6578)
+#
+# ``llm.openai_endpoint.url`` is the client's base URL only for the
+# ``openai_endpoint`` provider. Both chat spawn sites used to forward it
+# for every provider (it defaults to the OpenRouter URL), so a QwenCloud /
+# DeepSeek / LM Studio failure was reported against an endpoint the client
+# never contacted.
+# ---------------------------------------------------------------------------
+
+_STALE_ENDPOINT = "https://openrouter.ai/api/v1"
+
+
+def _endpoint_settings(provider: str) -> dict[str, JsonValue]:
+ return _valid_settings() | {
+ "llm.provider": {"value": provider},
+ "llm.model": {"value": "some-model"},
+ "search.tool": {"value": "searxng"},
+ "llm.openai_endpoint.url": {"value": _STALE_ENDPOINT},
+ }
+
+
+_ENDPOINT_CASES = [
+ ("qwen", None),
+ ("QWEN", None),
+ ("lmstudio", None),
+ ("openai_endpoint", _STALE_ENDPOINT),
+ ("OPENAI_ENDPOINT", _STALE_ENDPOINT),
+]
+
+
[email protected](("provider", "expected"), _ENDPOINT_CASES)
+async def test_send_forwards_custom_endpoint_only_for_openai_endpoint(
+ mocker: MockerFixture, provider: str, expected: str | None
+) -> None:
+ _service(mocker)
+ cap_db, _stale_row = _send_cap_db()
+ write_db = MagicMock()
+ mocker.patch.object(
+ chat, "get_user_db_session", side_effect=_db_factory(cap_db, write_db)
+ )
+ mocker.patch.object(
+ chat, "resolve_user_password", return_value=("pw", False)
+ )
+ mocker.patch.object(chat, "get_user_password", return_value="pw")
+ mocker.patch.object(
+ chat, "_load_settings", return_value=_endpoint_settings(provider)
+ )
+ mocker.patch.object(
+ chat, "reclaim_stale_user_active_research", return_value=False
+ )
+ mocker.patch.object(chat, "is_research_thread_alive", return_value=True)
+ mocker.patch.object(
+ chat, "SettingsManager"
+ ).return_value.get_setting.return_value = 3
+ mocker.patch.object(
+ chat, "ChatContextManager"
+ ).return_value.build_research_context.return_value = {
+ "is_multi_turn": False
+ }
+ start = mocker.patch.object(chat, "start_research_process")
+
+ response = await chat.send_message(
+ _request({"content": "question"}), "session-1", username="alice"
+ )
+
+ assert response.status_code == 200, response.body
+ start.assert_called_once()
+ assert start.call_args.kwargs["model_provider"] == provider
+ assert start.call_args.kwargs["custom_endpoint"] == expected
+
+
[email protected](("provider", "expected"), _ENDPOINT_CASES)
+async def test_retry_forwards_custom_endpoint_only_for_openai_endpoint(
+ mocker: MockerFixture, provider: str, expected: str | None
+) -> None:
+ _service(mocker)
+ cap_db = MagicMock()
+ cap_db.query.return_value.filter.return_value.all.return_value = []
+ write_db = MagicMock()
+ mocker.patch.object(
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(cap_db, write_db, MagicMock()),
+ )
+ mocker.patch.object(
+ chat, "resolve_user_password", return_value=("pw", False)
+ )
+ mocker.patch.object(chat, "get_user_password", return_value="pw")
+ mocker.patch.object(
+ chat, "reclaim_stale_user_active_research", return_value=False
+ )
+ mocker.patch.object(
+ chat, "_enforce_chat_session_research_slot", return_value=None
+ )
+ mocker.patch.object(
+ chat, "_load_settings", return_value=_endpoint_settings(provider)
+ )
+ mocker.patch.object(
+ chat, "ChatContextManager"
+ ).return_value.build_research_context.return_value = {
+ "is_multi_turn": False
+ }
+ start = mocker.patch.object(chat, "start_research_process")
+
+ response = await chat.retry_attempt(
+ MagicMock(spec=Request), "session-1", "research-1", username="alice"
+ )
+
+ assert response.status_code == 200, response.body
+ start.assert_called_once()
+ assert start.call_args.kwargs["model_provider"] == provider
+ assert start.call_args.kwargs["custom_endpoint"] == expected
diff --git a/tests/web/routers/test_followup_routes_coverage_port.py b/tests/web/routers/test_followup_routes_coverage_port.py
index c4542b27d4..8e13087d3e 100644
--- a/tests/web/routers/test_followup_routes_coverage_port.py
+++ b/tests/web/routers/test_followup_routes_coverage_port.py
@@ -468,9 +468,10 @@ class TestStartFollowupCustomEndpointSSRF:
"http://169.254.169.254/latest/meta-data/iam/security-credentials/"
)
- def _snapshot_with_endpoint(self, url):
+ def _snapshot_with_endpoint(self, url, provider="OPENAI_ENDPOINT"):
snapshot = _fake_settings_snapshot()
snapshot["llm.openai_endpoint.url"] = {"value": url}
+ snapshot["llm.provider"] = {"value": provider}
return snapshot
def test_metadata_endpoint_rejected_before_db_write(self, app):
@@ -592,6 +593,54 @@ class TestStartFollowupCustomEndpointSSRF:
== "http://localhost:11434/v1"
)
+ def test_endpoint_not_forwarded_for_other_providers(self, app):
+ """llm.openai_endpoint.url is only the client's base URL for the
+ openai_endpoint provider. For any other provider a stale value
+ (default: the OpenRouter URL) must not reach the worker, where it
+ would mislabel that provider's endpoint in error messages."""
+ mock_service = _service_mock(
+ {
+ "query": "q",
+ "max_iterations": 1,
+ "questions_per_iteration": 1,
+ "delegate_strategy": "source-based",
+ "research_context": {},
+ "parent_research_id": "parent-1",
+ }
+ )
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.count.return_value = 0
+ mock_db.query.return_value.filter.return_value.all.return_value = []
+
+ with (
+ patch(
+ SETTINGS_MANAGER,
+ return_value=_make_settings_mock(
+ self._snapshot_with_endpoint(
+ "https://openrouter.ai/api/v1", provider="QWEN"
+ )
+ ),
+ ),
+ _mock_db_session_ctx(mock_db),
+ patch(
+ f"{MODULE}.FollowUpResearchService", return_value=mock_service
+ ),
+ patch(START_RESEARCH) as mock_start,
+ patch(RUN_RESEARCH),
+ patch(RESEARCH_HISTORY),
+ patch(RESOLVE_PASSWORD, return_value=("secret-password", False)),
+ ):
+ resp = _authed_post(
+ app,
+ "/api/followup/start",
+ {"parent_research_id": "parent-1", "question": "details?"},
+ )
+
+ assert resp.status_code == 200, resp.text
+ mock_start.assert_called_once()
+ assert mock_start.call_args.kwargs["model_provider"] == "qwen"
+ assert mock_start.call_args.kwargs["custom_endpoint"] is None
+
class TestStartFollowupNoPassword:
def test_no_password_on_unencrypted_db_still_starts(self, app):
diff --git a/tests/web/routers/test_model_discovery_cancellation.py b/tests/web/routers/test_model_discovery_cancellation.py
index c0ee34cf4b..f2d44d29cd 100644
--- a/tests/web/routers/test_model_discovery_cancellation.py
+++ b/tests/web/routers/test_model_discovery_cancellation.py
@@ -14,6 +14,7 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from local_deep_research.database.models.providers import ProviderModel
+from local_deep_research.database.models.settings import Setting
from local_deep_research.database import thread_local_session
from local_deep_research.llm import providers
from local_deep_research.web.dependencies.auth import require_auth
@@ -28,6 +29,9 @@ from local_deep_research.web.routers import settings
def discovery_http(tmp_path, monkeypatch):
engine = create_engine(f"sqlite:///{tmp_path / 'models.db'}")
ProviderModel.__table__.create(engine)
+ # The cache write re-reads each provider's key/URL settings in its
+ # transaction and skips a provider whose inputs changed meanwhile.
+ Setting.__table__.create(engine)
sessions = sessionmaker(bind=engine)
with sessions() as session:
session.add(
@@ -137,8 +141,10 @@ async def test_cancellation_stops_later_providers_and_preserves_cache(
async with httpx.AsyncClient(
transport=transport, base_url="http://test"
) as client:
+ # A full refresh is a POST without a target; GET with
+ # ?force_refresh=true answers 405 before any discovery work.
request = asyncio.create_task(
- client.get("/settings/api/available-models?force_refresh=true")
+ client.post("/settings/api/available-models")
)
try:
assert await asyncio.to_thread(started.wait, 10)
@@ -186,9 +192,7 @@ async def test_uncancelled_discovery_fetches_and_persists_all_models(
async with httpx.AsyncClient(
transport=transport, base_url="http://test"
) as client:
- response = await client.get(
- "/settings/api/available-models?force_refresh=true"
- )
+ response = await client.post("/settings/api/available-models")
assert response.status_code == 200
assert set(response.json()["providers"]) == {
@@ -238,7 +242,7 @@ async def test_slow_discovery_leaves_the_default_executor_free(
transport=transport, base_url="http://test"
) as client:
request = asyncio.create_task(
- client.get("/settings/api/available-models?force_refresh=true")
+ client.post("/settings/api/available-models")
)
try:
for _ in range(1000):
diff --git a/tests/web/routers/test_model_refresh_concurrency.py b/tests/web/routers/test_model_refresh_concurrency.py
new file mode 100644
index 0000000000..eb3dfe75cd
--- /dev/null
+++ b/tests/web/routers/test_model_refresh_concurrency.py
@@ -0,0 +1,296 @@
+"""Model discovery must not persist a superseded credential/endpoint snapshot."""
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from datetime import UTC, datetime, timedelta
+from threading import Event
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.exc import OperationalError
+from sqlalchemy.orm import Session
+from sqlalchemy.pool import QueuePool
+from starlette.requests import Request
+
+from local_deep_research.database.models.providers import ProviderModel
+from local_deep_research.database.models.settings import Setting, SettingType
+from local_deep_research.database.sqlcipher_compat import get_sqlcipher_module
+from local_deep_research.database.sqlcipher_utils import (
+ create_sqlcipher_connection,
+)
+from local_deep_research.web.routers import settings as routes
+
+
[email protected](params=["sqlite", "sqlcipher"])
+def model_catalog(tmp_path, monkeypatch, request):
+ db_path = tmp_path / "models.sqlite"
+ if request.param == "sqlcipher":
+ try:
+ driver = get_sqlcipher_module()
+ except ImportError:
+ pytest.skip("SQLCipher not installed")
+ monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "1000")
+ engine = create_engine(
+ "sqlite://",
+ module=driver,
+ creator=lambda: create_sqlcipher_connection(
+ db_path,
+ password="catalog-test-password",
+ creation_mode=not db_path.exists(),
+ connect_kwargs={
+ "timeout": 0,
+ "isolation_level": "",
+ "check_same_thread": False,
+ },
+ ),
+ poolclass=QueuePool,
+ )
+ else:
+ engine = create_engine(
+ f"sqlite:///{db_path}", connect_args={"timeout": 0}
+ )
+ Setting.__table__.create(engine)
+ ProviderModel.__table__.create(engine)
+ key_setting = "llm.qwen.api_key"
+ url_setting = "llm.openai.api_base"
+ monkeypatch.delenv("LDR_LLM_QWEN_API_KEY", raising=False)
+ monkeypatch.delenv("LDR_LLM_OPENAI_API_BASE", raising=False)
+ original_inputs = ("older-key", "https://older.example/v1")
+ with Session(engine) as db:
+ for key, value, element in [
+ (key_setting, original_inputs[0], "password"),
+ (url_setting, original_inputs[1], "text"),
+ ]:
+ db.add(
+ Setting(
+ key=key,
+ value=value,
+ name=key,
+ type=SettingType.LLM,
+ ui_element=element,
+ )
+ )
+ for provider in ["QWEN", "OLLAMA"]:
+ db.add(
+ ProviderModel(
+ provider=provider,
+ model_key="cached-" + provider.lower(),
+ model_label="cached-" + provider.lower(),
+ last_updated=datetime.now(UTC),
+ )
+ )
+ db.commit()
+
+ started = Event()
+ release = Event()
+
+ class Provider:
+ api_key_setting = key_setting
+ url_setting = "llm.openai.api_base"
+
+ @staticmethod
+ def list_models_for_api(api_key, base_url):
+ if (api_key, base_url) == original_inputs:
+ started.set()
+ assert release.wait(10), "older discovery was not released"
+ model = "older-model"
+ else:
+ model = "replacement-model"
+ return [{"value": model, "label": model}]
+
+ class LocalProvider:
+ api_key_setting = None
+ url_setting = None
+
+ @staticmethod
+ def list_models_for_api(api_key, base_url):
+ return [{"value": "cached-ollama", "label": "cached-ollama"}]
+
+ @contextmanager
+ def user_session(username):
+ assert username == "catalog-user"
+ with Session(engine) as db:
+ yield db
+
+ def refresh(full=False):
+ request = Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/settings/api/available-models",
+ "query_string": b"" if full else b"refresh_provider=qwen",
+ "headers": [],
+ }
+ )
+ return asyncio.run(
+ routes.api_get_available_models(request, "catalog-user")
+ )
+
+ def cached_models():
+ with Session(engine) as db:
+ return {
+ row.provider: row.model_key
+ for row in db.query(ProviderModel).all()
+ }
+
+ monkeypatch.setattr(routes, "get_user_db_session", user_session)
+ monkeypatch.setattr(
+ routes,
+ "_resolve_model_discovery_policy",
+ lambda _: (SimpleNamespace(require_local_llm=False), {}),
+ )
+ monkeypatch.setattr(routes, "_provider_options_for_snapshot", lambda *a: [])
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ lambda: [],
+ )
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.discover_providers",
+ lambda: {
+ "QWEN": SimpleNamespace(
+ provider_name="QwenCloud", provider_class=Provider
+ ),
+ "OLLAMA": SimpleNamespace(
+ provider_name="Ollama", provider_class=LocalProvider
+ ),
+ },
+ )
+ yield SimpleNamespace(
+ engine=engine,
+ key_setting=key_setting,
+ url_setting=url_setting,
+ provider=Provider,
+ refresh=refresh,
+ cached_models=cached_models,
+ started=started,
+ release=release,
+ )
+ release.set()
+ engine.dispose()
+
+
[email protected]("full", [False, True], ids=["targeted", "full"])
[email protected]("changed", ["key_setting", "url_setting"])
[email protected]("edit", ["replace", "clear", "delete"])
+def test_older_discovery_cannot_replace_newer_cache(
+ model_catalog, full, changed, edit
+):
+ catalog = model_catalog
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ older = pool.submit(catalog.refresh, full)
+ try:
+ assert catalog.started.wait(10)
+ with Session(catalog.engine) as db:
+ setting = db.query(Setting).filter_by(
+ key=getattr(catalog, changed)
+ )
+ if edit == "delete":
+ setting.delete()
+ else:
+ setting.update(
+ {
+ Setting.value: "replacement"
+ if edit == "replace"
+ else ""
+ }
+ )
+ db.commit()
+ newer = catalog.refresh(full)
+ assert newer["providers"]["qwen_models"][0]["value"] == (
+ "replacement-model"
+ )
+ assert catalog.cached_models()["QWEN"] == "replacement-model"
+ finally:
+ catalog.release.set()
+ assert (
+ older.result(timeout=10)["providers"]["qwen_models"][0]["value"]
+ == "older-model"
+ )
+ assert catalog.cached_models() == {
+ "QWEN": "replacement-model",
+ "OLLAMA": "cached-ollama",
+ }
+
+
[email protected]("full", [False, True], ids=["targeted", "full"])
+def test_unchanged_settings_still_replace_cached_models(model_catalog, full):
+ model_catalog.release.set()
+ model_catalog.refresh(full)
+ assert model_catalog.cached_models()["QWEN"] == "older-model"
+
+
+def test_environment_override_is_compared_as_effective_value(
+ model_catalog, monkeypatch
+):
+ monkeypatch.setenv("LDR_LLM_QWEN_API_KEY", "environment-key")
+ model_catalog.refresh()
+ assert model_catalog.cached_models()["QWEN"] == "replacement-model"
+
+
+def test_setting_write_cannot_enter_between_cache_check_and_commit(
+ model_catalog, monkeypatch
+):
+ unchanged = routes._model_discovery_settings_unchanged
+ checked = []
+
+ def check_with_competing_writer(db, fetched):
+ matches = unchanged(db, fetched)
+ # A separate connection represents another request/worker trying to
+ # rotate the key in the last possible check-to-write window.
+ with Session(model_catalog.engine) as other:
+ with pytest.raises(OperationalError, match="locked"):
+ other.query(Setting).filter_by(
+ key=model_catalog.key_setting
+ ).update({Setting.value: "competing-key"})
+ other.commit()
+ other.rollback()
+ checked.append(matches)
+ return matches
+
+ monkeypatch.setattr(
+ routes,
+ "_model_discovery_settings_unchanged",
+ check_with_competing_writer,
+ )
+ model_catalog.release.set()
+ model_catalog.refresh()
+ assert checked == [True]
+ assert model_catalog.cached_models()["QWEN"] == "older-model"
+
+
+def test_targeted_rows_follow_a_full_refresh_committed_mid_discovery(
+ model_catalog,
+):
+ """The target's rows take the other providers' oldest timestamp as it
+ stands at write time, not at this request's cache read. A full refresh
+ that re-stamps the other rows while this discovery is in flight must
+ not leave the target's rows expiring up to 24h before them."""
+ catalog = model_catalog
+ stale = datetime.now(UTC) - timedelta(hours=20)
+ with Session(catalog.engine) as db:
+ db.query(ProviderModel).update({ProviderModel.last_updated: stale})
+ db.commit()
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ targeted = pool.submit(catalog.refresh)
+ try:
+ assert catalog.started.wait(10)
+ restamped = datetime.now(UTC)
+ with Session(catalog.engine) as db:
+ db.query(ProviderModel).filter_by(provider="OLLAMA").update(
+ {ProviderModel.last_updated: restamped}
+ )
+ db.commit()
+ finally:
+ catalog.release.set()
+ targeted.result(timeout=10)
+
+ with Session(catalog.engine) as db:
+ row = db.query(ProviderModel).filter_by(provider="QWEN").one()
+ assert row.model_key == "older-model"
+ row_time = row.last_updated
+ if row_time.tzinfo is None:
+ row_time = row_time.replace(tzinfo=UTC)
+ assert row_time >= restamped - timedelta(seconds=1)
diff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.py
index b9a20f8e08..4b95c8a2b7 100644
--- a/tests/web/routers/test_research_model_log_preview_bound.py
+++ b/tests/web/routers/test_research_model_log_preview_bound.py
@@ -929,6 +929,10 @@ class TestDeferredRequestValueLogSites:
model_provider=wide,
model=wide,
search_engine=wide,
+ # Keep the malformed-provider probe on the logging path;
+ # provider normalization for a missing endpoint rejects
+ # dict inputs before the later override diagnostic.
+ custom_endpoint=None,
)
assert (
diff --git a/tests/web/routers/test_settings_routes_deep_coverage2_port.py b/tests/web/routers/test_settings_routes_deep_coverage2_port.py
index 4eea6a6b71..401b9d7c6f 100644
--- a/tests/web/routers/test_settings_routes_deep_coverage2_port.py
+++ b/tests/web/routers/test_settings_routes_deep_coverage2_port.py
@@ -790,11 +790,9 @@ def _call_available_models():
api_get_available_models,
)
- return asyncio.run(
- api_get_available_models(
- _fake_request({"force_refresh": "true"}), username="testuser"
- )
- )
+ request = _fake_request()
+ request.method = "POST"
+ return asyncio.run(api_get_available_models(request, username="testuser"))
class TestApiGetAvailableModelsAnthropic:
diff --git a/tests/web/routers/test_settings_routes_gaps_coverage_port.py b/tests/web/routers/test_settings_routes_gaps_coverage_port.py
index d408a267fd..e13e9a2a83 100644
--- a/tests/web/routers/test_settings_routes_gaps_coverage_port.py
+++ b/tests/web/routers/test_settings_routes_gaps_coverage_port.py
@@ -689,7 +689,7 @@ class TestApiGetAvailableModels:
the single guarded Ollama fetch path had no behavior-sensitive coverage.
"""
- def _cache_vs_fresh(self, client, query):
+ def _cache_vs_fresh(self, client, query, *, post=None):
"""Drive the route with a populated model cache AND a live discovery
that returns a DIFFERENT model, so the response says which path ran."""
from local_deep_research.security.egress.policy import (
@@ -741,22 +741,30 @@ class TestApiGetAvailableModels:
),
patch(f"{S}._get_setting_from_session", return_value=""),
):
- resp = client.get(f"/settings/api/available-models{query}")
+ # A refresh is a state change: POST-only (CSRF).
+ if post is None:
+ post = (
+ "refresh_provider" in query or "force_refresh=true" in query
+ )
+ send = client.post if post else client.get
+ resp = send(f"/settings/api/available-models{query}")
assert resp.status_code == 200, resp.text[:300]
return resp.json()
- def test_cache_is_used_when_force_refresh_is_absent(self, client):
- """Control for the test below: without ``force_refresh`` the cached
- rows are what comes back, so 'fresh models' below means the cache was
+ @pytest.mark.parametrize("query", ["", "?force_refresh=false"])
+ def test_cache_is_used_when_force_refresh_is_absent(self, client, query):
+ """Control for the test below: a GET without ``force_refresh=true``
+ returns the cached rows, so 'fresh models' below means the cache was
genuinely bypassed rather than empty."""
- data = self._cache_vs_fresh(client, "")
+ data = self._cache_vs_fresh(client, query)
assert [m["value"] for m in data["providers"]["ollama_models"]] == [
"cached-only-model"
]
def test_force_refresh_bypasses_cache(self, client):
- """``force_refresh=true`` skips the cache and fetches live.
+ """A ``POST`` still carrying the legacy ``force_refresh=true`` (and
+ no target) skips the cache and fetches live.
The original asserted only ``200`` + ``"providers" in body``, which
stays green with the query-param parsing deleted. The cached-vs-fresh
@@ -770,6 +778,636 @@ class TestApiGetAvailableModels:
"fresh-model"
]
+ def test_refresh_provider_bypasses_cache_for_target_only(self, client):
+ """``?refresh_provider=<p>`` re-fetches just that provider's catalog
+ while other providers keep their cached rows.
+
+ This is the path the research page takes after a provider API key
+ is saved: the plain cache read would keep the newly keyed
+ provider's stale/empty list for up to 24h, and a full
+ ``force_refresh`` re-probes every provider serially.
+ """
+ data = self._cache_vs_fresh(client, "?refresh_provider=ollama")
+
+ assert "providers" in data
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "fresh-model"
+ ]
+
+ def test_post_without_target_is_a_full_refresh(self, client):
+ """A ``POST`` with no ``refresh_provider`` re-discovers every
+ provider, bypassing the cache like ``POST ?force_refresh=true``."""
+ data = self._cache_vs_fresh(client, "", post=True)
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "fresh-model"
+ ]
+
+ @pytest.mark.parametrize(
+ "query",
+ [
+ "?refresh_provider=ollama",
+ "?force_refresh=true",
+ "?force_refresh=TRUE",
+ "?force_refresh=true&refresh_provider=ollama",
+ ],
+ )
+ def test_get_with_a_refresh_query_is_refused_before_any_work(
+ self, client, query
+ ):
+ """A refresh calls providers with the stored keys and rewrites
+ cached rows (``force_refresh=true`` used to delete every cached
+ row), so on ``GET`` (no CSRF check) it answers 405 with
+ ``Allow: POST`` before the policy is resolved, the cache is read or
+ any provider is discovered."""
+ with (
+ patch(f"{S}.get_user_db_session") as session,
+ patch(f"{S}._resolve_model_discovery_policy") as policy,
+ patch(
+ "local_deep_research.llm.providers.discover_providers"
+ ) as discover,
+ ):
+ resp = client.get(f"/settings/api/available-models{query}")
+
+ assert resp.status_code == 405, resp.text[:300]
+ assert resp.headers["allow"] == "POST"
+ session.assert_not_called()
+ policy.assert_not_called()
+ discover.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "query",
+ [
+ "?refresh_provider=LMSTUDIO",
+ "?refresh_provider=LMSTUDIO&force_refresh=true",
+ ],
+ ids=["targeted", "legacy-force-flag-does-not-widen"],
+ )
+ def test_refresh_provider_fetches_only_the_target(self, client, query):
+ """A targeted refresh must not touch any other provider's
+ upstream: only the named provider's ``list_models_for_api`` runs,
+ and its rows merge with (not replace) the cached catalog. The
+ legacy ``force_refresh=true`` flag is ignored on a POST, so it
+ cannot widen a targeted refresh into a full one."""
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ cached = MagicMock()
+ cached.provider = "OLLAMA"
+ cached.model_key = "cached-ollama-model"
+ cached.model_label = "cached-ollama-model"
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = [
+ cached
+ ]
+
+ @contextmanager
+ def _session(*a, **kw):
+ yield session
+
+ ollama_info = self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh (Ollama)"}]
+ )
+ lmstudio_info = self._discovered(
+ "LM Studio",
+ [{"value": "fresh-lmstudio", "label": "Fresh (LM Studio)"}],
+ )
+ policy_context = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ local_hostnames=(),
+ username="testuser",
+ )
+
+ with (
+ patch(f"{S}.get_user_db_session", side_effect=_session),
+ patch(
+ f"{S}._resolve_model_discovery_policy",
+ return_value=(policy_context, {}),
+ ),
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value={
+ "OLLAMA": ollama_info,
+ "LMSTUDIO": lmstudio_info,
+ },
+ ),
+ patch(f"{S}._get_setting_from_session", return_value=""),
+ ):
+ resp = client.post(f"/settings/api/available-models{query}")
+
+ assert resp.status_code == 200, resp.text[:300]
+ data = resp.json()
+ lmstudio_info.provider_class.list_models_for_api.assert_called_once()
+ ollama_info.provider_class.list_models_for_api.assert_not_called()
+ assert [m["value"] for m in data["providers"]["lmstudio_models"]] == [
+ "fresh-lmstudio"
+ ]
+ # Cached Ollama rows are merged through untouched.
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-ollama-model"
+ ]
+
+ def test_refresh_provider_unknown_name_returns_cache(self, client):
+ """An unknown provider name degrades to the plain cache read —
+ no upstream fetch, cached rows intact."""
+ data = self._cache_vs_fresh(client, "?refresh_provider=no_such")
+
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-only-model"
+ ]
+
+ def test_refresh_provider_with_cold_cache_falls_back_to_full_discovery(
+ self,
+ client,
+ ):
+ """A targeted refresh against an empty model cache (fresh install)
+ must NOT return a one-provider catalog — the client would cache it
+ as the whole world and blank every other provider's dropdown. It
+ falls back to the same full discovery the plain cold-cache path
+ performs."""
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = []
+
+ @contextmanager
+ def _session(*a, **kw):
+ yield session
+
+ ollama_info = self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh (Ollama)"}]
+ )
+ lmstudio_info = self._discovered(
+ "LM Studio",
+ [{"value": "fresh-lmstudio", "label": "Fresh (LM Studio)"}],
+ )
+ policy_context = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ local_hostnames=(),
+ username="testuser",
+ )
+
+ with (
+ patch(f"{S}.get_user_db_session", side_effect=_session),
+ patch(
+ f"{S}._resolve_model_discovery_policy",
+ return_value=(policy_context, {}),
+ ),
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value={
+ "OLLAMA": ollama_info,
+ "LMSTUDIO": lmstudio_info,
+ },
+ ),
+ patch(f"{S}._get_setting_from_session", return_value=""),
+ ):
+ resp = client.post(
+ "/settings/api/available-models?refresh_provider=ollama"
+ )
+
+ assert resp.status_code == 200, resp.text[:300]
+ data = resp.json()
+ # Full discovery ran: BOTH providers' models are in the response.
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "fresh-ollama"
+ ]
+ assert [m["value"] for m in data["providers"]["lmstudio_models"]] == [
+ "fresh-lmstudio"
+ ]
+
+ def test_refresh_provider_failure_keeps_cached_rows(self, client):
+ """A transient upstream failure during a targeted refresh must not
+ blank the provider's catalog: the response restores the cached rows
+ and the DB rows are never deleted."""
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ cached = MagicMock()
+ cached.provider = "OLLAMA"
+ cached.model_key = "cached-ollama-model"
+ cached.model_label = "cached-ollama-model"
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = [
+ cached
+ ]
+
+ @contextmanager
+ def _session(*a, **kw):
+ yield session
+
+ ollama_info = self._discovered("Ollama", [])
+ ollama_info.provider_class.list_models_for_api.side_effect = (
+ ConnectionError("transient upstream failure")
+ )
+ policy_context = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ local_hostnames=(),
+ username="testuser",
+ )
+
+ with (
+ patch(f"{S}.get_user_db_session", side_effect=_session),
+ patch(
+ f"{S}._resolve_model_discovery_policy",
+ return_value=(policy_context, {}),
+ ),
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value={"OLLAMA": ollama_info},
+ ),
+ patch(f"{S}._get_setting_from_session", return_value=""),
+ ):
+ resp = client.post(
+ "/settings/api/available-models?refresh_provider=ollama"
+ )
+
+ assert resp.status_code == 200, resp.text[:300]
+ data = resp.json()
+ # Cached rows restored to the response...
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-ollama-model"
+ ]
+ # ...and the DB cache was never touched (no delete on any provider).
+ delete_calls = session.query.return_value.filter.return_value.delete
+ delete_calls.assert_not_called()
+
+ def test_refresh_provider_empty_result_keeps_cached_rows(self, client):
+ """``list_models_for_api`` converts upstream failures into an empty
+ list (its catch-all never raises), so a dead endpoint during a key
+ re-save arrives here as a *successful* fetch of zero models. That
+ must be treated as a failed probe: the cached rows are kept in the
+ response and the DB, not deleted."""
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ cached = MagicMock()
+ cached.provider = "OLLAMA"
+ cached.model_key = "cached-ollama-model"
+ cached.model_label = "cached-ollama-model"
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = [
+ cached
+ ]
+
+ @contextmanager
+ def _session(*a, **kw):
+ yield session
+
+ # No side_effect: the fetch "succeeds" with zero models, which is
+ # the real-world shape of a transient upstream failure.
+ ollama_info = self._discovered("Ollama", [])
+ policy_context = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ local_hostnames=(),
+ username="testuser",
+ )
+
+ with (
+ patch(f"{S}.get_user_db_session", side_effect=_session),
+ patch(
+ f"{S}._resolve_model_discovery_policy",
+ return_value=(policy_context, {}),
+ ),
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value={"OLLAMA": ollama_info},
+ ),
+ patch(f"{S}._get_setting_from_session", return_value=""),
+ ):
+ resp = client.post(
+ "/settings/api/available-models?refresh_provider=ollama"
+ )
+
+ assert resp.status_code == 200, resp.text[:300]
+ data = resp.json()
+ # Cached rows kept in the response...
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-ollama-model"
+ ]
+ # ...and the DB rows were never deleted.
+ session.query.return_value.filter.return_value.delete.assert_not_called()
+
+ def _targeted_refresh(
+ self,
+ client,
+ query,
+ cached_rows,
+ discovered,
+ *,
+ require_local_llm=False,
+ allowed_providers=None,
+ row_times=None,
+ ):
+ """Drive ``?refresh_provider=`` against a populated cache.
+
+ ``cached_rows`` is ``[(PROVIDER, model_key), ...]``;
+ ``row_times`` optionally maps a PROVIDER to its rows'
+ ``last_updated``. Returns
+ ``(json, session)``; the session mock records the DB writes.
+ ``allowed_providers`` (with ``require_local_llm``) stubs the
+ endpoint-policy verdict so no provider URL is ever resolved.
+ """
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ rows = []
+ for provider, key in cached_rows:
+ row = MagicMock()
+ row.provider = provider
+ row.model_key = key
+ row.model_label = key
+ if row_times and provider in row_times:
+ row.last_updated = row_times[provider]
+ rows.append(row)
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = rows
+
+ @contextmanager
+ def _session(*a, **kw):
+ yield session
+
+ policy_context = EgressContext(
+ scope=(
+ EgressScope.PRIVATE_ONLY
+ if require_local_llm
+ else EgressScope.PUBLIC_ONLY
+ ),
+ primary_engine="library",
+ require_local_llm=require_local_llm,
+ require_local_embeddings=False,
+ local_hostnames=(),
+ username="testuser",
+ )
+ allowed = {p.upper() for p in (allowed_providers or ())}
+
+ with (
+ patch(f"{S}.get_user_db_session", side_effect=_session),
+ patch(
+ f"{S}._resolve_model_discovery_policy",
+ return_value=(policy_context, {}),
+ ),
+ patch(
+ f"{S}._model_discovery_provider_allowed",
+ side_effect=lambda provider, *a, **kw: (
+ provider.upper() in allowed
+ ),
+ ),
+ patch(
+ "local_deep_research.llm.providers.get_discovered_provider_options",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.llm.providers.discover_providers",
+ return_value=discovered,
+ ),
+ patch(f"{S}._get_setting_from_session", return_value=""),
+ ):
+ # A targeted refresh is a state change: POST-only (CSRF).
+ send = client.post if "refresh_provider" in query else client.get
+ resp = send(f"/settings/api/available-models{query}")
+
+ assert resp.status_code == 200, resp.text[:300]
+ return resp.json(), session
+
+ @staticmethod
+ def _deleted_providers(session):
+ """Provider names whose cached rows the route deleted (the
+ ``ProviderModel.provider == X`` filters; the cache-read filter on
+ ``last_updated`` is ignored)."""
+ deleted = []
+ for call in session.query.return_value.filter.call_args_list:
+ expr = call.args[0] if call.args else None
+ left = getattr(expr, "left", None)
+ if getattr(left, "key", None) == "provider":
+ deleted.append(expr.right.value)
+ return deleted
+
+ @staticmethod
+ def _inserted_providers(session):
+ return sorted({c.args[0].provider for c in session.add.call_args_list})
+
+ def test_refresh_provider_success_rewrites_only_target_rows(self, client):
+ """A successful targeted refresh deletes and re-inserts ONLY the
+ target provider's cached rows. Every other provider keeps its DB
+ rows (and their 24h TTL) untouched — re-writing them would reset
+ their TTL with stale data and churn the whole cache on each key
+ save."""
+ discovered = {
+ "OLLAMA": self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh"}]
+ ),
+ "QWEN": self._discovered(
+ "QwenCloud", [{"value": "qwen3.8-max", "label": "Qwen Max"}]
+ ),
+ }
+ data, session = self._targeted_refresh(
+ client,
+ "?refresh_provider=qwen",
+ [("OLLAMA", "cached-ollama"), ("QWEN", "cached-qwen")],
+ discovered,
+ )
+
+ discovered[
+ "QWEN"
+ ].provider_class.list_models_for_api.assert_called_once()
+ discovered[
+ "OLLAMA"
+ ].provider_class.list_models_for_api.assert_not_called()
+ assert [m["value"] for m in data["providers"]["qwen_models"]] == [
+ "qwen3.8-max"
+ ]
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-ollama"
+ ]
+ # DB: only QWEN rows deleted and only QWEN rows inserted.
+ assert self._deleted_providers(session) == ["QWEN"]
+ assert self._inserted_providers(session) == ["QWEN"]
+ session.query.return_value.delete.assert_not_called()
+ session.commit.assert_called_once()
+
+ def test_refresh_provider_rows_expire_with_the_rest_of_the_cache(
+ self, client
+ ):
+ """The cache read returns ANY fresh rows as the whole catalog, so
+ the target's re-fetched rows must not outlive the other providers'
+ rows: they are stamped with the oldest other provider's
+ ``last_updated``, not ``now``. Otherwise, e.g. 20h after a full
+ discovery, a key save would keep only the target's models fresh
+ between hours 24 and 44 and hide every other provider's models."""
+ from datetime import UTC, datetime, timedelta
+
+ now = datetime.now(UTC)
+ ollama_time = now - timedelta(hours=20)
+ lmstudio_time = now - timedelta(hours=10)
+ discovered = {
+ "OLLAMA": self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh"}]
+ ),
+ "QWEN": self._discovered(
+ "QwenCloud", [{"value": "qwen3.8-max", "label": "Qwen Max"}]
+ ),
+ }
+ _data, session = self._targeted_refresh(
+ client,
+ "?refresh_provider=qwen",
+ [
+ ("OLLAMA", "cached-ollama"),
+ ("LMSTUDIO", "cached-lmstudio"),
+ # The target's own old rows never set the timestamp.
+ ("QWEN", "cached-qwen"),
+ ],
+ discovered,
+ row_times={
+ "OLLAMA": ollama_time,
+ "LMSTUDIO": lmstudio_time,
+ "QWEN": now - timedelta(hours=23),
+ },
+ )
+
+ added = [c.args[0] for c in session.add.call_args_list]
+ assert [row.provider for row in added] == ["QWEN"]
+ assert [row.last_updated for row in added] == [ollama_time]
+
+ def test_refresh_provider_rows_use_now_when_no_other_rows(self, client):
+ """With no other provider's cached rows there is nothing to stay
+ in step with: the target's rows get a current timestamp."""
+ from datetime import UTC, datetime, timedelta
+
+ before = datetime.now(UTC)
+ discovered = {
+ "QWEN": self._discovered(
+ "QwenCloud", [{"value": "qwen3.8-max", "label": "Qwen Max"}]
+ ),
+ }
+ _data, session = self._targeted_refresh(
+ client,
+ "?refresh_provider=qwen",
+ [("QWEN", "cached-qwen")],
+ discovered,
+ row_times={"QWEN": before - timedelta(hours=23)},
+ )
+
+ added = [c.args[0] for c in session.add.call_args_list]
+ assert [row.provider for row in added] == ["QWEN"]
+ assert added[0].last_updated >= before
+
+ def test_refresh_provider_under_require_local_llm_skips_blocked_target(
+ self, client
+ ):
+ """Local-only posture: a targeted refresh of a cloud provider the
+ policy blocks must not contact it, must not leak its cached rows
+ into the response, and must not touch the DB — the other (allowed)
+ providers' cached rows are returned as-is."""
+ discovered = {
+ "OLLAMA": self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh"}]
+ ),
+ "QWEN": self._discovered(
+ "QwenCloud", [{"value": "qwen3.8-max", "label": "Qwen Max"}]
+ ),
+ }
+ data, session = self._targeted_refresh(
+ client,
+ "?refresh_provider=qwen",
+ [("OLLAMA", "cached-ollama"), ("QWEN", "cached-qwen")],
+ discovered,
+ require_local_llm=True,
+ allowed_providers={"OLLAMA"},
+ )
+
+ discovered[
+ "QWEN"
+ ].provider_class.list_models_for_api.assert_not_called()
+ discovered[
+ "OLLAMA"
+ ].provider_class.list_models_for_api.assert_not_called()
+ assert "qwen_models" not in data["providers"]
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "cached-ollama"
+ ]
+ assert self._deleted_providers(session) == []
+ session.add.assert_not_called()
+ session.query.return_value.delete.assert_not_called()
+
+ def test_refresh_provider_under_require_local_llm_refreshes_allowed_target(
+ self, client
+ ):
+ """Local-only posture, allowed target: only that provider is
+ re-fetched and re-written; the blocked cloud provider is neither
+ contacted nor returned, and its DB rows are left alone."""
+ discovered = {
+ "OLLAMA": self._discovered(
+ "Ollama", [{"value": "fresh-ollama", "label": "Fresh"}]
+ ),
+ "QWEN": self._discovered(
+ "QwenCloud", [{"value": "qwen3.8-max", "label": "Qwen Max"}]
+ ),
+ }
+ data, session = self._targeted_refresh(
+ client,
+ "?refresh_provider=ollama",
+ [("OLLAMA", "cached-ollama"), ("QWEN", "cached-qwen")],
+ discovered,
+ require_local_llm=True,
+ allowed_providers={"OLLAMA"},
+ )
+
+ discovered[
+ "OLLAMA"
+ ].provider_class.list_models_for_api.assert_called_once()
+ discovered[
+ "QWEN"
+ ].provider_class.list_models_for_api.assert_not_called()
+ assert [m["value"] for m in data["providers"]["ollama_models"]] == [
+ "fresh-ollama"
+ ]
+ assert "qwen_models" not in data["providers"]
+ assert self._deleted_providers(session) == ["OLLAMA"]
+ assert self._inserted_providers(session) == ["OLLAMA"]
+
def test_force_refresh_uses_one_guarded_ollama_provider_path(self):
"""The router delegates Ollama listing, URL validation, and auth.
@@ -841,6 +1479,8 @@ class TestApiGetAvailableModels:
],
):
request = MagicMock()
+ # A refresh is POST-only: a GET carrying force_refresh=true is a 405.
+ request.method = "POST"
request.query_params.get.side_effect = lambda key, default=None: {
"force_refresh": "true"
}.get(key, default)
@@ -889,9 +1529,7 @@ class TestApiGetAvailableModels:
discovered,
extra=[patch(f"{S}._get_setting_from_session", return_value=None)],
):
- resp = client.get(
- "/settings/api/available-models?force_refresh=true"
- )
+ resp = client.post("/settings/api/available-models")
assert resp.status_code == 200
values = [opt["value"] for opt in resp.json()["provider_options"]]
@@ -948,9 +1586,7 @@ class TestApiGetAvailableModels:
patch(f"{S}._get_setting_from_session", return_value=""),
],
):
- resp = client.get(
- "/settings/api/available-models?force_refresh=true"
- )
+ resp = client.post("/settings/api/available-models")
assert resp.status_code == 200, resp.text[:400]
return resp.json()["providers"]
@@ -1116,9 +1752,7 @@ class TestApiGetAvailableModelsEgressPolicy:
),
):
# When models are refreshed.
- response = client.get(
- "/settings/api/available-models?force_refresh=true"
- )
+ response = client.post("/settings/api/available-models")
# Then the provider is never actually called and no models are
# returned, but the option is still surfaced in the dropdown marked as
diff --git a/tests/web/services/test_research_service_openai_rewrite_call_site.py b/tests/web/services/test_research_service_openai_rewrite_call_site.py
new file mode 100644
index 0000000000..a78a25a07a
--- /dev/null
+++ b/tests/web/services/test_research_service_openai_rewrite_call_site.py
@@ -0,0 +1,314 @@
+"""The #3878 friendly-error rewrite, driven through its real call site.
+
+``run_research_process``'s ``except Exception as search_error`` block
+rewrites OpenAI-compatible client failures into a message naming the
+provider, base URL and model -- but only for providers in
+``_OPENAI_COMPAT_RUNTIME_ERROR_PROVIDERS``, and with the base URL resolved
+by ``_resolve_error_rewrite_base_url``. The unit tests in
+``tests/error_handling/test_openai_compat_errors.py`` pin the set and the
+resolver in isolation; this module pins that the worker actually wires them
+together.
+
+The rewritten text is server-side detail: the outer handler replaces it
+with a scrubbed category message before anything reaches the client
+(CWE-209), so the observable output is the ``Research failed: ...`` log
+line. It is captured with a loguru sink.
+
+What breaks if this regresses: a QwenCloud (or DeepSeek, Requesty) outage
+is logged as a generic "Connection error" with no provider/endpoint, or --
+when chat/follow-up pass ``llm.openai_endpoint.url`` (default: the
+OpenRouter URL) as ``custom_endpoint`` -- it is logged against an endpoint
+the client never contacted.
+
+Network: ``get_llm`` and ``AdvancedSearchSystem`` are mocked, and the
+connection error is constructed locally, so nothing is contacted.
+"""
+
+from contextlib import ExitStack
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+from loguru import logger
+from openai import (
+ APIConnectionError,
+ APITimeoutError,
+ AuthenticationError,
+ BadRequestError,
+ NotFoundError,
+ PermissionDeniedError,
+)
+
+from local_deep_research.web.services import research_service
+from tests.web.services.helpers import (
+ MODULE,
+ QUEUE_PROC_MOD,
+ _base_run_patches,
+ _egress_and_search_patches,
+ _get_raw_run_research_process,
+)
+
+QWEN_URL = "https://maas.qwencloudapi.com/compatible-mode/v1"
+OPENROUTER_URL = "https://openrouter.ai/api/v1"
+
+
+def _connection_error():
+ return APIConnectionError(
+ message="Connection error.",
+ request=httpx.Request("POST", f"{QWEN_URL}/chat/completions"),
+ )
+
+
+def _status_error(cls, status):
+ request = httpx.Request("POST", f"{QWEN_URL}/chat/completions")
+ return cls(
+ message=f"upstream said {status}",
+ response=httpx.Response(status, request=request),
+ body=None,
+ )
+
+
+_OMIT = object()
+
+
+def _run_worker_logging(
+ *,
+ provider,
+ model,
+ custom_endpoint,
+ error=None,
+ all_messages=None,
+ get_llm=None,
+):
+ """Drive the real worker with ``analyze_topic`` raising an
+ OpenAI-compatible error (default: a connection error); return the
+ ``Research failed`` log lines and the metadata queued for the client.
+ ``all_messages``, when a list, receives every captured log line."""
+ system = MagicMock()
+ system.analyze_topic.side_effect = (
+ error if error is not None else _connection_error()
+ )
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_llm"] = get_llm or MagicMock(
+ return_value=MagicMock()
+ )
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(return_value=system)
+
+ snapshot = {
+ "llm.provider": provider,
+ "llm.model": model,
+ "search.tool": "searxng",
+ # The stale value chat/follow-up used to forward for every provider.
+ "llm.openai_endpoint.url": OPENROUTER_URL,
+ }
+ messages = [] if all_messages is None else all_messages
+ # The package disables its loguru logging on import (see
+ # ``local_deep_research/__init__.py``); re-enable it for the capture and
+ # restore the default afterwards, as the ``loguru_caplog`` fixture does.
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: messages.append(m.record["message"]), level="DEBUG"
+ )
+ try:
+ with ExitStack() as stack:
+ for cm in _egress_and_search_patches():
+ stack.enter_context(cm)
+ for target, mock_obj in patches.items():
+ stack.enter_context(patch(target, mock_obj))
+ _get_raw_run_research_process()(
+ 1,
+ "test query",
+ "quick",
+ username="user1",
+ settings_snapshot=snapshot,
+ search_engine="searxng",
+ model_provider=provider,
+ model=model,
+ **(
+ {}
+ if custom_endpoint is _OMIT
+ else {"custom_endpoint": custom_endpoint}
+ ),
+ )
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+ assert system.analyze_topic.called, (
+ "the worker never reached analyze_topic -- the search-error path "
+ "did not run, so nothing below is being tested"
+ )
+ failed = [m for m in messages if m.startswith("Research failed:")]
+ assert failed, "the outer handler never logged the failure"
+ queue = patches[f"{QUEUE_PROC_MOD}.queue_processor"]
+ assert queue.queue_error_update.called, "no error update was queued"
+ return failed, queue.queue_error_update.call_args.kwargs["metadata"]
+
+
+ "custom_endpoint",
+ [None, OPENROUTER_URL],
+ ids=["no-custom-endpoint", "stale-openai-endpoint-url"],
+)
+def test_qwen_connection_error_is_rewritten_with_its_real_endpoint(
+ custom_endpoint,
+):
+ """QwenCloud's failure is rewritten (it is in the provider set) and
+ names its own QwenCloud endpoint -- not ``<unknown>`` and not the
+ OpenRouter URL that ``llm.openai_endpoint.url`` defaults to."""
+ # Premise: the patch targets below resolve against the module that
+ # holds the worker.
+ assert research_service.__name__ == MODULE
+ failed, _metadata = _run_worker_logging(
+ provider="qwen", model="qwen3.8-max", custom_endpoint=custom_endpoint
+ )
+ text = "\n".join(failed)
+
+ assert "Error type: openai_connection_refused" in text, text
+ # The connection-refused wording names provider and endpoint (the model
+ # only appears for model-specific failures such as a 404).
+ assert "Cannot reach qwen at " + QWEN_URL in text, text
+ assert "<unknown>" not in text
+ assert "openrouter.ai" not in text
+
+
+def test_client_gets_provider_neutral_category_message_and_hint():
+ """The client never sees the rewritten detail (CWE-209); it gets the
+ category message and ``solution``. Those now reach cloud providers
+ (QwenCloud, DeepSeek, OpenRouter, ...) too, so they name the configured
+ endpoint and only mention local servers as an example."""
+ _failed, metadata = _run_worker_logging(
+ provider="qwen", model="qwen3.8-max", custom_endpoint=None
+ )
+
+ assert metadata["error"] == (
+ "Could not connect to the configured LLM endpoint."
+ )
+ solution = metadata["solution"]
+ assert "configured LLM endpoint is reachable" in solution
+ assert not solution.startswith("Start your LLM server")
+ # CWE-209: neither the endpoint nor the raw detail reaches the client.
+ assert QWEN_URL not in str(metadata)
+ assert "Details:" not in str(metadata)
+
+
+def test_legacy_uppercase_provider_still_gets_the_rewrite():
+ """A provider stored before normalisation (``"QWEN"``) must still be
+ matched against the lower-case provider set and rewritten."""
+ failed, _metadata = _run_worker_logging(
+ provider="QWEN", model="qwen3.8-max", custom_endpoint=None
+ )
+ text = "\n".join(failed)
+
+ assert "Error type: openai_connection_refused" in text, text
+ assert "Cannot reach qwen at " + QWEN_URL in text, text
+
+
+def test_research_parameters_log_redacts_the_custom_endpoint():
+ """The INFO "Research parameters" line logs the per-run endpoint; a
+ credential embedded in it (userinfo, ``?api_key=``) must not reach the
+ log."""
+ endpoint = "https://user:[email protected]/v1?api_key=sk-leak123&v=1"
+ messages = []
+ _run_worker_logging(
+ provider="openai_endpoint",
+ model="m",
+ custom_endpoint=endpoint,
+ all_messages=messages,
+ )
+
+ params = [m for m in messages if m.startswith("Research parameters:")]
+ assert params, "the worker never logged its parameters"
+ # The worker preserves main's stricter policy: retain the origin only,
+ # so arbitrary path/query values never reach this diagnostic.
+ assert "custom_endpoint=https://gw.example," in params[0], params[0]
+ assert "/v1" not in params[0], params[0]
+ assert "api_key=" not in params[0], params[0]
+ for message in messages:
+ assert "sk-leak123" not in message
+ assert "pw-leak" not in message
+
+
+def test_research_parameters_log_keeps_absent_endpoint_as_none():
+ messages = []
+ _run_worker_logging(
+ provider="qwen",
+ model="qwen3.8-max",
+ custom_endpoint=None,
+ all_messages=messages,
+ )
+ params = [m for m in messages if m.startswith("Research parameters:")]
+ assert "custom_endpoint=None," in params[0], params[0]
+
+
+ ("error", "expected_message"),
+ [
+ (
+ APITimeoutError(
+ request=httpx.Request("POST", f"{QWEN_URL}/chat/completions")
+ ),
+ "The configured LLM endpoint timed out.",
+ ),
+ (
+ _status_error(AuthenticationError, 401),
+ "Authentication with the configured LLM provider failed.",
+ ),
+ (
+ _status_error(PermissionDeniedError, 403),
+ "The configured LLM provider denied access to the model.",
+ ),
+ (
+ _status_error(NotFoundError, 404),
+ "The configured model was not found at the LLM endpoint.",
+ ),
+ (
+ _status_error(BadRequestError, 400),
+ "The LLM endpoint rejected the request.",
+ ),
+ ],
+ ids=[
+ "timeout",
+ "auth",
+ "permission_denied",
+ "model_not_found",
+ "bad_request",
+ ],
+)
+def test_other_categories_are_provider_neutral(error, expected_message):
+ """The other five categories, as a cloud provider's client sees them:
+ timeout, model-not-found and bad-request were reworded to name the
+ configured endpoint; auth and permission-denied already named the
+ configured provider and only their hints changed. None of them
+ mentions a local or LLM server."""
+ _failed, metadata = _run_worker_logging(
+ provider="qwen",
+ model="qwen3.8-max",
+ custom_endpoint=None,
+ error=error,
+ )
+
+ assert metadata["error"] == expected_message
+ client_text = f"{metadata['error']} {metadata['solution']}".lower()
+ assert "local server" not in client_text
+ assert "llm server" not in client_text
+ assert "loaded on this server" not in client_text
+ assert "account/server" not in client_text
+ assert QWEN_URL not in str(metadata)
+
+
+def test_settings_fallback_endpoint_matches_legacy_uppercase_provider():
+ """With no per-run ``custom_endpoint`` kwarg, the worker falls back to
+ ``llm.openai_endpoint.url`` for the openai_endpoint provider and hands
+ it to ``get_llm`` -- also when the provider is stored in legacy upper
+ case."""
+ get_llm = MagicMock(return_value=MagicMock())
+ _run_worker_logging(
+ provider="OPENAI_ENDPOINT",
+ model="m",
+ custom_endpoint=_OMIT,
+ get_llm=get_llm,
+ )
+ assert get_llm.called
+ assert get_llm.call_args.kwargs["openai_endpoint_url"] == OPENROUTER_URL
diff --git a/tests/web/test_news_run_once_model_dispatch.py b/tests/web/test_news_run_once_model_dispatch.py
index adead865b4..d7c54902f7 100644
--- a/tests/web/test_news_run_once_model_dispatch.py
+++ b/tests/web/test_news_run_once_model_dispatch.py
@@ -2,6 +2,7 @@
import json
from pathlib import Path
+import re
import shutil
import subprocess
from unittest.mock import Mock, patch
@@ -107,3 +108,26 @@ def test_news_run_once_model_reaches_provider_constructor(
constructor.assert_called_once()
assert constructor.call_args.kwargs["model"] == model
assert llm.base_llm is fake
+
+
+def test_news_run_once_provider_set_matches_the_provider_registry():
+ """Run Once splits a ``PROVIDER:model`` selection only when the prefix
+ is in news.js's ``knownProviders`` set; any other prefix stays inside
+ the model id and the run silently uses the default provider. That set
+ is hand-maintained, so pin it to the auto-discovered provider registry:
+ a provider added to the registry (or removed from it) must be added to
+ (or removed from) the set too."""
+ match = re.search(
+ r"const knownProviders = new Set\(\[(.*?)\]\);",
+ NEWS_JS.read_text(encoding="utf-8"),
+ re.DOTALL,
+ )
+ assert match is not None, "knownProviders set not found in news.js"
+ listed = re.findall(r"'([^']*)'", match.group(1))
+ assert len(listed) == len(set(listed)), f"duplicate keys: {listed}"
+ registry = set(discover_providers(force_refresh=True))
+ assert registry, "provider auto-discovery returned nothing"
+ assert set(listed) == registry, (
+ f"news.js knownProviders is missing {sorted(registry - set(listed))} "
+ f"and lists unregistered {sorted(set(listed) - registry)}"
+ )
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index b8c46486a8..34853e1533 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -192,6 +192,11 @@ EXPECTED_ADDED = [
("DELETE", "/settings/api/{}"),
("GET", "/settings/api/{}"),
("PUT", "/settings/api/{}"),
+ # A model refresh (``?refresh_provider=`` for one provider, else every
+ # provider) calls providers with the user's stored keys and rewrites
+ # their cached rows, so it moved from GET ``?force_refresh=true`` to a
+ # CSRF-protected POST. Ordinary GET reads remain available.
+ ("POST", "/settings/api/available-models"),
# FastAPI-side counterpart of the bulk re-index GET -> POST move
# recorded in EXPECTED_REMOVED above.
("POST", "/library/api/rag/index-all"),
@@ -1538,6 +1543,10 @@ def _where(views) -> str:
# sides spelled out — and an entry whose two sides stop diverging, or
# start diverging differently, fails too.
EXPECTED_METHOD_SET_DIVERGENCES = {
+ # GET remains a read, while POST performs a model refresh (targeted by
+ # ``?refresh_provider=``, else full). A GET carrying ``refresh_provider``
+ # or ``force_refresh=true`` returns 405.
+ "/settings/api/available-models": ({"GET"}, {"GET", "POST"}),
# The bulk re-index trigger; see the paired entries in
# EXPECTED_REMOVED / EXPECTED_ADDED for why the verb changed. Stated
# here as well because a verb move is exactly the "silent 405 for
@@ -1671,6 +1680,11 @@ EXPECTED_STATUS_CODES_LOST = {
# not. Not automatically a regression — most are new input validation — but
# each one can turn a request that used to succeed into a failure.
EXPECTED_STATUS_CODES_GAINED = {
+ # A GET carrying ``refresh_provider`` or ``force_refresh=true`` would
+ # call providers with the stored keys and rewrite cached models without
+ # a CSRF check (``force_refresh=true`` deleted every cached row). It now
+ # fails with 405 and directs clients to POST.
+ ("GET", "/settings/api/available-models"): [405],
# Offsets above 10,000 are rejected before reaching the database. Flask
# attempted the query (and could raise on values outside SQLite's integer
# range); ordinary offsets and non-integer fallback behavior are retained.