Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(network): centralize proxy settings and add MCP routing (NAN-315) (#6372)
chengyongru084b6bb394fd
diff --git a/.agent/security.md b/.agent/security.mdindex 51139cf9b..d1dda4073 100644--- a/.agent/security.md+++ b/.agent/security.md@@ -16,7 +16,7 @@ Shell execution (`ExecTool`, `agent/tools/shell.py`) also respects `restrict_to_All outbound HTTP requests from agent tools must pass through the shared URL guards in `security/network.py` (`validate_url_target` or `resolve_url_target`). By default they block loopback, RFC1918 private addresses, CGNAT ranges, link-local ranges, and cloud metadata endpoints (including `169.254.169.254`).-For direct requests, the only escape hatch is `configure_ssrf_whitelist(cidrs)`, which reads from `config.tools.ssrf_whitelist` at load time. An explicitly configured `providers.<name>.proxy` is a separate user-authorized trust boundary for provider requests and provider-returned image URL downloads. Those downloads still reject malformed URLs and locally identifiable private/internal targets on every redirect, but hostnames unavailable to local DNS are delegated to the trusted proxy. The user-selected proxy owns final DNS resolution and network egress policy.+For direct requests, the only escape hatch is `configure_ssrf_whitelist(cidrs)`, which reads from `config.tools.ssrf_whitelist` at load time. The shared `network.proxy` address enabled by `providers.<name>.useProxy` is a separate user-authorized trust boundary for provider requests and provider-returned image URL downloads. Those downloads still reject malformed URLs and locally identifiable private/internal targets on every redirect, but hostnames unavailable to local DNS are delegated to the trusted proxy. The user-selected proxy owns final DNS resolution and network egress policy.HTTP/SSE MCP transports are part of this boundary: validate configured MCP URLs before probing or constructing clients, and validate each outgoing HTTP request before redirects are followed. Local/private HTTP MCP endpoints are allowed only through the explicit SSRF whitelist. Stdio MCP servers are not part of the HTTP SSRF path.diff --git a/docs/channel-package-guide.md b/docs/channel-package-guide.mdindex 013d16231..9c0c9af03 100644--- a/docs/channel-package-guide.md+++ b/docs/channel-package-guide.md@@ -339,6 +339,34 @@ A normal return from `send()` means either the visible payload was accepted by t`send()` may run as soon as `is_running` becomes true. If a channel sets `_running` before its transport is ready, it must keep raising until delivery can be attempted safely. Small platform-specific retries are fine, but the final failure must still reach the manager.+### Optional shared proxy++Existing `__init__(config, bus)` constructors remain valid. `BaseChannel.uses_shared_proxy` defaults to `False`; only runtimes that explicitly set this class capability to `True` receive the instance-scoped top-level `NetworkConfig` as the keyword-only `network` argument. This capability is not a user setting.++To support the shared proxy, declare `use_proxy: bool = False` on your channel's config model and expose `"useProxy": ChannelFieldSpec(kind="bool", default=False)` in its setup fields. Opt in on the runtime class and forward `network` to the base constructor:++```python+from typing import Any++from nanobot.bus.queue import MessageBus+from nanobot.channels.base import BaseChannel+from nanobot.config.network import NetworkConfig+++class WebhookChannel(BaseChannel):+ uses_shared_proxy = True++ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):+ if isinstance(config, dict):+ config = WebhookConfig(**config)+ super().__init__(config, bus, network=network)+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)+```++Pass the resolved address to your platform clients. `useProxy: false` keeps the channel direct even when `network.proxy` is configured; `true` requires a shared proxy address and fails rather than silently connecting directly. Setup validators receive the same settings through `context.network`. Do not load global config or persist a proxy address in the channel config.+### Interactive LoginIf your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:diff --git a/docs/chat-apps.md b/docs/chat-apps.mdindex 3bead19af..71e8a1a30 100644--- a/docs/chat-apps.md+++ b/docs/chat-apps.md@@ -127,7 +127,7 @@ See the [native Linear agent guide](./guides/linear-agent.md) for the complete s1. Create a bot with `@BotFather` and copy its token.2. Run `nanobot webui`, then open **Channels → Telegram**.-3. Paste the token. If the gateway cannot reach Telegram directly, expand **Advanced** and add an HTTP or SOCKS proxy.+3. Paste the token. If the gateway cannot reach Telegram directly, set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.4. Save and enable Telegram, then send the bot a direct message.The configuration badge means nanobot found a saved token. The live connection check is separate, so a temporary Telegram or proxy outage does not make an existing configuration disappear. Saved tokens and proxy URLs remain masked.@@ -161,13 +161,14 @@ nanobot plugins enable telegram}```-If the gateway cannot reach Telegram directly, add a proxy to the same section:+If the gateway cannot reach Telegram directly, set the shared address and enable it for Telegram:```json{+ "network": { "proxy": "http://127.0.0.1:7890" },"channels": {"telegram": {- "proxy": "http://127.0.0.1:7890"+ "useProxy": true}}}diff --git a/docs/configuration.md b/docs/configuration.mdindex da3396140..96b8b9f76 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -69,6 +69,41 @@ If the WebUI does not expose the option you need, start from the task below. Mos| Run multiple isolated bots | separate `--home` directories, or `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Place `--home` before the subcommand; use the same instance selectors with `status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) || Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |+## Shared network proxy++Set one proxy address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** for each provider, Web access, channel, or remote MCP connection that needs it. The address is used by the gateway, so `127.0.0.1` refers to the machine running nanobot. Restart when Settings requests it. MCP connections can select the proxy before browser sign-in.++For proxies that require credentials, expand **Authentication (optional)** and enter the username and password, then choose **Save** to apply the address and credentials together. The same editor is available from **Configure proxy** without leaving the current form. Passwords are masked in the interface but remain part of the proxy URL in the local configuration; protect that file. If the address is a whole-URL `${ENV_VAR}` reference, include authentication in the referenced URL.++Only features with a **Use proxy** switch use this address. Turning a switch off preserves the feature's normal environment/system proxy behavior. An enabled switch without a configured address fails rather than silently connecting directly. Use a trusted proxy and keep credentials in its URL private.++<details>+<summary>Manual configuration</summary>++```json+{+ "network": { "proxy": "http://127.0.0.1:7890" },+ "providers": { "openai": { "useProxy": true } },+ "tools": {+ "web": { "useProxy": true },+ "mcpServers": {+ "figma-remote": {+ "type": "streamableHttp",+ "url": "https://mcp.figma.com/mcp",+ "auth": "oauth",+ "useProxy": true+ }+ }+ }+}+```++HTTP, HTTPS, SOCKS5, and SOCKS5H URLs are accepted; individual integrations retain their transport limits. `${ENV_VAR}` references work in `network.proxy`.++</details>++On upgrade, one legacy proxy address moves to `network.proxy` and previously configured features receive `useProxy: true`. The migrated configuration is written on the next normal save, including `nanobot onboard --refresh`. If the old configuration contains different proxy addresses, choose one and set `network.proxy` explicitly before upgrading; multiple per-feature addresses are no longer supported. For Discord configurations that store the entire proxy URL in an environment variable and credentials separately, combine them into one full URL environment variable and set `network.proxy` to that reference before upgrading. Credential references inside a URL remain references when saved. Back up the original configuration before saving if you may need to downgrade.+## Environment Variables for SecretsInstead of storing secrets directly in `config.json`, you can use `${VAR_NAME}` references that are resolved from environment variables at startup:@@ -277,7 +312,7 @@ A Base URL is the service address nanobot sends model requests to. Change it onl> - **Xiaomi MiMo thinking mode**: MiMo models (e.g. `mimo-v2.5-pro`) default to enabled thinking. In the preset's **Advanced options**, set reasoning effort to `none` to disable it, or `low` / `medium` / `high` to keep it on. Omitting the field preserves the provider's per-model default.> - **Xiaomi MiMo Token Plan**: If you're on MiMo's token plan, open the xiaomi_mimo connection in **Settings → Models** and set its base URL to `https://token-plan-sgp.xiaomimimo.com/v1`.> - **Custom providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. Declare accepted protocols with `providers.<name>.api`; custom connections can use Chat Completions, Responses, or Anthropic Messages. See [custom connection APIs](#custom-connection-apis).-> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends reject `proxy`.+> - **Use proxy**: `providers.<name>.useProxy` opts that provider into the [shared network proxy](#shared-network-proxy). It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends do not support this switch.</details>@@ -754,14 +789,13 @@ The default model is `xai-grok/grok-4.6` with a 500,000-token context window. ThThis is xAI subscription OAuth, not X Developer OAuth. nanobot follows the public OAuth client and proxy contract used by [Grok Build](https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/02-authentication.md). The browser flow uses a random loopback callback and PKCE. The resulting token is stored in the active instance's `auth/xai.json` (normally `~/.nanobot/auth/xai.json`), separately from Grok Build so rotating refresh tokens cannot invalidate one another.-To use a provider-specific proxy, merge this into `config.json` before login:+To use the shared proxy, configure its address and enable it for xAI before login:```json{+ "network": { "proxy": "http://127.0.0.1:7890" },"providers": {- "xaiGrok": {- "proxy": "http://127.0.0.1:7890"- }+ "xaiGrok": { "useProxy": true }}}```@@ -1744,7 +1778,7 @@ When ripgrep (`rg`) is installed, nanobot automatically uses it in place of the## Web Tools-Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for the web proxy and User-Agent, and **Settings → Advanced** for the SSRF whitelist. Follow any restart prompt.+Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for **Use proxy** and User-Agent, and **Settings → Advanced** for the shared proxy address and SSRF whitelist. Follow any restart prompt.nanobot includes web search and web fetch tools. They are enabled by default. The collapsed examples below show the equivalent `tools.web` configuration.@@ -1782,28 +1816,28 @@ nanobot uses a shared SSRF guard for built-in web fetches and HTTP/SSE MCP conneKeep whitelist entries as narrow as possible, such as a single host CIDR (`192.168.1.50/32`). The whitelist is global for the shared SSRF guard; it is not limited to one tool or one MCP server. This guard does not filter network traffic from shell commands or stdio MCP processes. The shell sandboxes also allow network access; use host or container egress controls when you need to prevent outbound connections.-HTTP/SSE MCP connections use the same process-wide proxy environment behavior as `web_fetch`: proxied targets use the configured proxy, and URLs excluded by `NO_PROXY` remain DNS-pinned direct connections.+Web access and HTTP/SSE MCP connections can opt into the [shared network proxy](#shared-network-proxy). With **Use proxy** off, their normal environment proxy settings and `NO_PROXY` still apply.-In WebUI, open **Settings → Capabilities → Web access → Configure → Advanced options** to set the web proxy. This setting applies to the agent's web search and page reading, not model providers, MCP, or your browser. `127.0.0.1` refers to the machine that runs nanobot, not the phone or computer that opens WebUI. Clear the field to use the default network settings, which can include proxy environment variables. After saving, restart nanobot when WebUI requests it. You can configure the proxy before enabling web access.+Set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** under **Settings → Capabilities → Web access → Configure → Advanced options**. This switch applies to web search and page reading; providers and MCP connections have their own switches. Your browser uses its own network settings. Follow any restart prompt. You can configure the proxy before enabling web access.> [!TIP]-> Use `proxy` in `tools.web` to route web requests through a proxy:+> Set `network.proxy` once and enable `tools.web.useProxy` to route web requests through it:> <details>> <summary>Manual configuration</summary>>> ```json-> { "tools": { "web": { "proxy": "http://127.0.0.1:7890" } } }+> { "network": { "proxy": "http://127.0.0.1:7890" }, "tools": { "web": { "useProxy": true } } }> ```>> </details>-> `web_fetch` applies DNS pinning for direct connections. When an explicit `tools.web.proxy` or a process-wide proxy environment variable applies to the target URL, nanobot still validates the requested URL locally, but DNS resolution for the outbound fetch happens at the proxy; configure only trusted proxies. URLs excluded by `NO_PROXY` keep the DNS-pinned direct path unless `tools.web.proxy` is configured.+> Web requests still enforce URL safety checks when using a proxy. Use only trusted proxies: the proxy controls final DNS resolution and outbound access. With **Use proxy** enabled, the shared address takes precedence over environment proxy settings, including `NO_PROXY`.### `tools.web`| Option | Type | Default | Description ||--------|------|---------|-------------|| `enable` | boolean | `true` | Enable or disable all built-in web tools (`web_search` + `web_fetch`) |-| `proxy` | string or null | `null` | Proxy for web requests, for example `http://127.0.0.1:7890`. `web_fetch` DNS pinning applies only to direct connections; proxied fetches rely on the configured proxy as the trusted network exit. |+| `useProxy` | boolean | `false` | Use the [shared network proxy](#shared-network-proxy) for web search and fetch. || `userAgent` | string or null | `null` | User-Agent header for all web requests. If null, a browser one will be used |### Web Search@@ -2098,7 +2132,7 @@ Queries are limited to 128 Unicode characters after trimming whitespace; longer### Web Fetch-In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options** in the same Web access card for network proxy settings.+In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options → Use proxy** to enable the address saved in **Settings → Advanced → Shared proxy**.> [!TIP]> If you are having issues with JS proof-of-work or Cloudflare captchas, set a random user agent and disable Jina Reader:diff --git a/docs/guides/telegram-ai-agent.md b/docs/guides/telegram-ai-agent.mdindex 15b706228..c5833fc1a 100644--- a/docs/guides/telegram-ai-agent.md+++ b/docs/guides/telegram-ai-agent.md@@ -28,12 +28,12 @@ Open **Channels → Telegram**:1. If Telegram support is not installed, turn on its switch and confirm the installation.2. Paste the token from BotFather.-3. If the gateway cannot reach Telegram directly, expand **Advanced** and enter an HTTP or SOCKS proxy such as `http://127.0.0.1:7890`.+3. If the gateway cannot reach Telegram directly, set an address such as `http://127.0.0.1:7890` in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.4. Save and enable Telegram. For a first private setup, leave the sender allowlist empty: new senders must pair before they can use the agent. Do not set it to `*`.The configuration badge appears as soon as a bot token is saved. A connection check is separate: if Telegram is temporarily unreachable, the saved configuration remains valid and the bot can continue working in environments where the gateway has network access.-Saved tokens and proxy URLs are masked. A proxy entered here is used both for the connection check and for normal Telegram traffic.+Saved tokens and proxy URLs are masked. **Use proxy** applies the shared address to both the connection check and normal Telegram traffic.## Manual setup@@ -50,17 +50,18 @@ Then merge this snippet into `~/.nanobot/config.json`:```json{+ "network": { "proxy": "http://127.0.0.1:7890" },"channels": {"telegram": {"enabled": true,"token": "YOUR_BOT_TOKEN",- "proxy": "http://127.0.0.1:7890"+ "useProxy": true}}}```-Omit `proxy` when the gateway can reach Telegram directly.+Leave `useProxy` off when the gateway can reach Telegram directly.Omitting `allowFrom` enables pairing-only mode. The first DM from a new user gets a pairing code instead of agent access.@@ -109,7 +110,7 @@ Send the message again after approval. Confirm that your private chat now receiv## Troubleshooting- If the channel is not listed, run `nanobot plugins enable telegram` again in the same Python environment.-- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or open **Advanced → Network proxy** and enter a proxy.+- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or configure **Settings → Advanced → Shared proxy** and turn on Telegram's **Use proxy** switch.- If Telegram rejects the token, copy the current token from BotFather or regenerate it.- If messages do not arrive, check the Telegram runtime status in **Channels** and the logs of the running gateway. Confirm it is enabled and can reach Telegram; do not start a second gateway to diagnose the first.- If a first DM returns a pairing code, that is expected. Approve the code before testing normal agent replies.diff --git a/docs/image-generation.md b/docs/image-generation.mdindex 2748cdfee..6cfe020ad 100644--- a/docs/image-generation.md+++ b/docs/image-generation.md@@ -85,7 +85,7 @@ Provider settings reuse normal provider config fields:| `providers.<name>.apiBase` | Optional custom base URL || `providers.<name>.extraHeaders` | Headers merged into provider requests || `providers.<name>.extraBody` | Extra JSON fields merged into provider request bodies |-| `providers.<name>.proxy` | Explicit trusted HTTP proxy for provider requests and returned image URL downloads |+| `providers.<name>.useProxy` | Use the shared `network.proxy` address for provider requests and returned image URL downloads |For providers that return image URLs, direct downloads use DNS pinning. When an explicit provider `proxy` is configured, nanobot rejects malformed URLs and locally identifiable private/internal targets on the initial URL and every redirect. Hostnames unavailable to local DNS are delegated to that trusted proxy, which owns final DNS resolution and network egress. Process-wide proxy environment variables are not used for these downloads.diff --git a/docs/mcp-presets.md b/docs/mcp-presets.mdindex a95b548f0..8856e6ddd 100644--- a/docs/mcp-presets.md+++ b/docs/mcp-presets.md@@ -2,6 +2,8 @@Open **Apps → MCP** to find a service, configure its connection, and select **Connect**. Presets save MCP server configuration; the gateway discovers and runs the tools. Each service still requires its own account access and permissions. The tables below list all built-in presets.+For a remote HTTP/SSE service that needs a proxy, first set the shared address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** in its connection dialog before selecting **Connect**. The gateway uses that route for MCP requests and authorization. The browser's sign-in page still uses your browser's own network settings. Local stdio servers keep their own networking configuration.+## Hosted servicesBrowser sign-in uses the service's MCP OAuth flow. API-key presets ask for the credential listed below and add it to the required HTTP header or URL parameter. Paste the token itself into the credential field.@@ -123,6 +125,8 @@ Datadog uses the MCP endpoint for your Datadog site and a Personal or Service AcFigma uses the desktop app's local MCP endpoint, and Supabase starts a local server in read-only mode. Their **(remote)** variants use browser sign-in. GitHub uses Docker; **GitHub (remote)** uses a personal access token. Changes to credentials retain the connection's tool selection, timeout, and other saved settings.+Figma (remote) also requires [Figma's approval of the MCP client](https://developers.figma.com/docs/figma-mcp-server/remote-server-installation/). A client rejected during registration cannot connect until Figma approves it, even when its network connection works.+## Local serversLocal servers run on the gateway computer. Install the runtime or application listed for each service. Stdio servers use a managed working directory under the nanobot data directory so their runtime files stay outside the source checkout. Figma connects over HTTP to the local desktop app.diff --git a/docs/providers.md b/docs/providers.mdindex 38bf75bc4..645342673 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -72,7 +72,7 @@ These fields answer different questions:| `model` | `modelPresets.<name>.model` | The model ID expected by that provider or gateway. || `apiKey` | `providers.<provider>.apiKey` | Credential for that provider. Use `${ENV_VAR}` for secrets. || `apiBase` | `providers.<provider>.apiBase` | HTTP base URL of the provider endpoint. |-| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |+| `use_proxy` | `providers.<provider>.useProxy` | Use the shared `network.proxy` address for this provider. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Anthropic direct, OpenAI direct, Groq, or Bedrock because nanobot knows their default endpoints. Set `apiBase` for `custom`, local OpenAI-compatible servers, provider proxies, regional endpoints, or subscription endpoints. Include the API version path when the endpoint requires it, for example `https://api.example.com/v1` or `http://localhost:11434/v1`.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex f22e8366d..de5bdee3b 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -148,12 +148,12 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m| Local model connection refused | Ollama, vLLM, LM Studio, or another local server is not running, or `apiBase` points to the wrong port. || Bedrock validation error | Check AWS region, credentials, model access, model ID, and whether the model supports Converse. || OAuth provider fails | Run the matching login command: `openai-codex`, `xai-grok`, or `github-copilot`, normally with `--set-main`. |-| Codex OAuth needs a proxy | Set `providers.openaiCodex.proxy` before running the login command. The proxy applies to login, token refresh, and Codex API requests. |+| Codex OAuth needs a proxy | Set the address in **Settings → Advanced → Shared proxy** and enable **Use proxy** for OpenAI Codex before login. In `config.json`, use `network.proxy` and `providers.openaiCodex.useProxy: true`. This applies to login, token refresh, and Codex API requests. || Codex login runs on a remote/headless machine | In the WebUI, open ChatGPT in your local browser; when the localhost callback page cannot load, copy the full `http://localhost:1455/auth/callback?...` URL from the address bar and paste it into the WebUI dialog. From the CLI, open the printed URL locally and paste the same callback URL back into the terminal. || Codex login runs in Docker | Start the container with `docker run -it` so the OAuth flow has an interactive terminal. || Codex says a model is not supported with a ChatGPT account | Use provider `openai_codex` with a Codex model such as `openai-codex/gpt-5.6-sol`. Do not use the direct-API `openai/...` prefix with Codex OAuth. || Config says `providers.openai_codex` conflicts with the built-in provider | Under `providers`, keep only the canonical `openaiCodex` settings key and remove a duplicate `openai_codex` key. A model preset's `provider` value remains `openai_codex`. |-| xAI OAuth needs a proxy | Set `providers.xaiGrok.proxy` before login. It applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. |+| xAI OAuth needs a proxy | Set `network.proxy` and `providers.xaiGrok.useProxy: true` before login, or use the shared address and provider switch in Settings. This applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. || xAI login runs on a remote/headless machine | In the WebUI, finish sign-in in your local browser; if the loopback redirect cannot reach the server, copy the final URL from the address bar into the WebUI dialog. From the CLI, run `nanobot provider login xai-grok` interactively, open the printed URL elsewhere, and paste the final callback URL or authorization code when prompted. || xAI returns 403 or subscription access denied | Confirm the signed-in account has an eligible X Premium / Grok subscription, then run `nanobot provider login xai-grok` again. This provider does not use an xAI API key or X Developer OAuth. || xAI returns 400 `invalid-argument` | Read the bounded `Response body` appended to the provider error. Hosted `x_search` is sent only when xAI's model catalog advertises `supportsBackendSearch`; the model ID `grok-4.5` itself is valid. |diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex 38a32e0fd..98c6a3be2 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -61,6 +61,7 @@ from nanobot.bus.outbound_events import (from nanobot.bus.queue import MessageBusfrom nanobot.command import CommandContext, CommandRouter, register_builtin_commandsfrom nanobot.command.router import command_text+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import AgentDefaults, ModelPresetConfigfrom nanobot.events import NO_EVENTS, AgentEvent, EventSinkfrom nanobot.llm_usage.context import source_from_request@@ -301,6 +302,7 @@ class AgentLoop:unified_session: bool = False,disabled_skills: list[str] | None = None,tools_config: ToolsConfig | None = None,+ network_config: NetworkConfig | None = None,provider_snapshot_loader: Callable[..., ProviderSnapshot] | None = None,provider_signature: tuple[object, ...] | None = None,model_presets: dict[str, ModelPresetConfig] | None = None,@@ -367,6 +369,7 @@ class AgentLoop:else defaults.tool_hint_max_length)self.tools_config = _tc+ self.network_config = network_config or NetworkConfig()self.web_config = _tc.webself.exec_config = _tc.execself.cron_service = cron_service@@ -406,6 +409,7 @@ class AgentLoop:workspace=workspace,bus=bus,tools_config=_tc,+ network_config=self.network_config,max_tool_result_chars=self.max_tool_result_chars,restrict_to_workspace=restrict_to_workspace,disabled_skills=disabled_skills,@@ -519,6 +523,7 @@ class AgentLoop:session_ttl_minutes=defaults.session_ttl_minutes,idle_compact_check_interval_seconds=defaults.idle_compact_check_interval_seconds,tools_config=config.tools,+ network_config=config.network,model_presets=preset_helpers.configured_model_presets(config),model_preset=defaults.model_preset,dream_model_preset=defaults.dream.model_override,@@ -656,6 +661,7 @@ class AgentLoop:self.register_runtime_context_provider(runtime_control.workspace_context)ctx = ToolContext(config=self.tools_config,+ network=self.network_config,workspace=str(self.workspace),bus=self.bus,subagent_manager=self.subagents,diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.pyindex 20d9d177f..713c74602 100644--- a/nanobot/agent/subagent.py+++ b/nanobot/agent/subagent.py@@ -38,6 +38,7 @@ from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hookfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import AgentDefaults, ToolsConfigfrom nanobot.events import AgentEvent, EventSinkfrom nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source@@ -220,6 +221,7 @@ class SubagentManager:max_concurrent_subagents: int | None = None,*,consolidator: Consolidator,+ network_config: NetworkConfig | None = None,session_manager: SessionManager | None = None,):if cast(object, consolidator) is None:@@ -252,6 +254,7 @@ class SubagentManager:self.workspace = workspaceself.bus = busself.tools_config = tools_config or ToolsConfig()+ self.network_config = network_config or NetworkConfig()self.max_tool_result_chars = max_tool_result_charsself.restrict_to_workspace = restrict_to_workspaceself.disabled_skills = set(disabled_skills or [])@@ -526,6 +529,7 @@ class SubagentManager:cfg = tools_config if tools_config is not None else self._subagent_tools_config()ctx = ToolContext(config=cfg,+ network=self.network_config,workspace=str(root.resolve()),exec_session_manager=exec_manager or self._exec_session_manager,file_state_store=FileStates(),diff --git a/nanobot/agent/tools/context.py b/nanobot/agent/tools/context.pyindex af8b72427..22e18e3dc 100644--- a/nanobot/agent/tools/context.py+++ b/nanobot/agent/tools/context.py@@ -7,6 +7,8 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable+from nanobot.config.network import NetworkConfig+if TYPE_CHECKING:from nanobot.agent.subagent import SubagentManagerfrom nanobot.agent.tools.exec_session import ExecSessionManager@@ -92,6 +94,7 @@ def current_request_session_key() -> str | None:class ToolContext:config: ToolsConfigworkspace: str+ network: NetworkConfig = field(default_factory=NetworkConfig)bus: MessageBus | None = Nonesubagent_manager: SubagentManager | None = Nonecron_service: CronService | None = Nonediff --git a/nanobot/agent/tools/image_generation.py b/nanobot/agent/tools/image_generation.pyindex 86f365bd3..b11a79c4d 100644--- a/nanobot/agent/tools/image_generation.py+++ b/nanobot/agent/tools/image_generation.py@@ -17,6 +17,7 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.providers.image_generation import (ImageGenerationError,@@ -81,6 +82,7 @@ class ImageGenerationTool(Tool):workspace=ctx.workspace,config=ctx.config.image_generation,provider_configs=image_gen_provider_configs(ctx.providers_config),+ network=ctx.network,)def __init__(@@ -90,9 +92,11 @@ class ImageGenerationTool(Tool):config: ImageGenerationToolConfig,provider_config: ProviderConfig | None = None,provider_configs: dict[str, ProviderConfig] | None = None,+ network: NetworkConfig | None = None,) -> None:self.workspace = Path(workspace).expanduser()self.config = config+ self.network = network or NetworkConfig()self.provider_configs = dict(provider_configs or {})if provider_config is not None and "openrouter" not in self.provider_configs:self.provider_configs["openrouter"] = provider_config@@ -126,7 +130,7 @@ class ImageGenerationTool(Tool):"api_base": provider.api_base if provider and isinstance(provider.api_base, str) else None,"extra_headers": headers or None,"extra_body": body or None,- "proxy": provider.proxy if provider and isinstance(provider.proxy, str) else None,+ "proxy": self.network.resolve_proxy(provider.use_proxy) if provider else None,}return cls(**kwargs)@@ -218,6 +222,7 @@ def register_image_generation_tool(ctx = ToolContext(config=config.tools,+ network=config.network,workspace=str(workspace),providers_config=config.providers,)diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.pyindex 84d8b4fe8..87d92259e 100644--- a/nanobot/agent/tools/mcp.py+++ b/nanobot/agent/tools/mcp.py@@ -8,6 +8,7 @@ import jsonimport osimport reimport shutil+import tracebackimport urllib.parsefrom collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mappingfrom contextlib import AsyncExitStack, suppress@@ -19,6 +20,7 @@ from loguru import loggerfrom nanobot.agent.tools.base import Tool, ToolResultfrom nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.agent.tools.registry import ToolRegistry+from nanobot.config.network import NetworkConfigfrom nanobot.security.network import (PinnedDNSAsyncTransport,env_proxy_applies_to_url,@@ -60,7 +62,7 @@ _HTTP_READ_TIMEOUT = 300.0# Replace anything outside [a-zA-Z0-9_-] with underscore and collapse runs._SANITIZE_RE = re.compile(r"_+")_ReconnectCallback = Callable[[str, str, Tool], Awaitable[Tool | None]]-MCPServerLoader = Callable[[], Mapping[str, "MCPServerConfig"]]+MCPServerLoader = Callable[[], tuple[Mapping[str, "MCPServerConfig"], NetworkConfig]]MCPRuntimeStatus = Literal["connecting", "connected", "failed"]@@ -216,8 +218,26 @@ def _is_transient_connection_failure(exc: BaseException) -> bool:return isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) or _is_transient(exc)-def _log_mcp_connection_failure(name: str, exc: BaseException, hint: str = "") -> None:- exception = exc if tool_log_content_allowed() else False+def _log_mcp_connection_failure(+ name: str, exc: BaseException, hint: str = "", *, proxy: str | None = None,+) -> None:+ exception: Exception | bool = False+ if tool_log_content_allowed():+ details = "".join(traceback.TracebackException.from_exception(+ exc, capture_locals=False,+ ).format())+ if proxy:+ for value in (proxy, urllib.parse.unquote(proxy)):+ details = details.replace(value, _redact_url(proxy))+ # Match userinfo only with its URL delimiter, never isolated short+ # credentials that could rewrite exception types or stack text.+ userinfo = urllib.parse.urlsplit(proxy).netloc.rpartition("@")[0]+ if userinfo:+ for value in (userinfo, urllib.parse.unquote(userinfo)):+ details = details.replace(f"{value}@", "[redacted]@")+ # Keep exception-aware sinks, but never give Loguru live frames or a raw+ # exception chain: diagnose=True would render credential-bearing locals.+ exception = Exception("\n" + details.rstrip())if _is_transient_connection_failure(exc):logger.warning("MCP server '{}': transient connection failure", name)logger.opt(exception=exception).debug(@@ -242,7 +262,7 @@ def _is_session_terminated(exc: BaseException) -> bool:)-async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:+async def _probe_http_url(url: str, timeout: float = 3.0, *, proxy: str | None = None) -> bool:"""Quick TCP probe to check if an HTTP MCP server is reachable.Avoids entering ``streamable_http_client`` / ``sse_client`` when the port is@@ -258,7 +278,7 @@ async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:ok, _, resolved_ips = resolve_url_target(url)if not ok:return False- if env_proxy_applies_to_url(url):+ if proxy or env_proxy_applies_to_url(url):return Truefor target_host in resolved_ips or (host,):try:@@ -294,7 +314,9 @@ def _redact_url(url: str) -> str:return "<redacted-url>"-def _pinned_transport_kwargs() -> dict[str, Any]:+def _pinned_transport_kwargs(proxy: str | None = None) -> dict[str, Any]:+ if proxy:+ return {"transport": httpx.AsyncHTTPTransport(proxy=proxy), "trust_env": False}kwargs: dict[str, Any] = {"transport": PinnedDNSAsyncTransport()}mounts = httpx_env_proxy_mounts()if mounts:@@ -1008,6 +1030,7 @@ async def connect_mcp_servers(registry: ToolRegistry,*,oauth_handlers: Mapping[str, MCPOAuthHandlers] | None = None,+ network: NetworkConfig | None = None,) -> dict[str, MCPConnection]:"""Connect to configured MCP servers and register their tools, resources, prompts.@@ -1020,6 +1043,10 @@ async def connect_mcp_servers(from mcp.client.stdio import stdio_clientfrom mcp.client.streamable_http import streamable_http_client+ # Stack-exit failures are logged outside open_single_server; retain the exact+ # selected value there too, including credentials resolved from environment refs.+ selected_proxies: dict[str, str | None] = {}+async def open_single_server(name: str, cfg: MCPServerConfig, server_stack: AsyncExitStack) -> bool:@@ -1047,6 +1074,10 @@ async def connect_mcp_servers()return False+ if cfg.use_proxy and transport_type == "stdio":+ raise ValueError("The shared proxy is available for HTTP and SSE MCP connections")+ proxy = (network or NetworkConfig()).resolve_proxy(cfg.use_proxy)+ selected_proxies[name] = proxyoauth_auth: httpx.Auth | None = Noneif cfg.auth == "oauth":if transport_type not in {"sse", "streamableHttp"}:@@ -1084,7 +1115,7 @@ async def connect_mcp_servers()read, write = await server_stack.enter_async_context(stdio_client(params))elif transport_type == "sse":- if not await _probe_http_url(cfg.url):+ if not await _probe_http_url(cfg.url, proxy=proxy):logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))return False@@ -1104,7 +1135,7 @@ async def connect_mcp_servers(follow_redirects=True,timeout=timeout,auth=auth,- **_pinned_transport_kwargs(),+ **_pinned_transport_kwargs(proxy),)sse_kwargs: dict[str, Any] = {@@ -1116,7 +1147,7 @@ async def connect_mcp_servers(sse_client(cfg.url, **sse_kwargs))elif transport_type == "streamableHttp":- if not await _probe_http_url(cfg.url):+ if not await _probe_http_url(cfg.url, proxy=proxy):logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))return False@@ -1131,7 +1162,7 @@ async def connect_mcp_servers(connect=10.0,read=max(_HTTP_READ_TIMEOUT, cfg.tool_timeout),),- **_pinned_transport_kwargs(),+ **_pinned_transport_kwargs(proxy),}if oauth_auth is not None:http_client_kwargs["auth"] = oauth_auth@@ -1300,7 +1331,7 @@ async def connect_mcp_servers(" Hint: this looks like stdio protocol pollution. Make sure the MCP server writes ""only JSON-RPC to stdout and sends logs/debug output to stderr instead.")- _log_mcp_connection_failure(name, e, hint)+ _log_mcp_connection_failure(name, e, hint, proxy=selected_proxies.get(name))return Falseasync def connect_single_server(@@ -1350,7 +1381,7 @@ async def connect_mcp_servers(try:result = await connect_single_server(name, cfg)except Exception as e:- _log_mcp_connection_failure(name, e)+ _log_mcp_connection_failure(name, e, proxy=selected_proxies.get(name))continueif result[1] is not None:server_stacks[result[0]] = result[1]@@ -1384,10 +1415,11 @@ def _configured_servers(config: Config) -> dict[str, MCPServerConfig]:)-def _load_current_servers() -> dict[str, MCPServerConfig]:+def _load_current_servers() -> tuple[dict[str, MCPServerConfig], NetworkConfig]:from nanobot.config.loader import load_config, resolve_config_env_vars- return _configured_servers(resolve_config_env_vars(load_config()))+ config = resolve_config_env_vars(load_config())+ return _configured_servers(config), config.networkclass MCPProvider:@@ -1399,8 +1431,10 @@ class MCPProvider:registry: ToolRegistry,*,server_loader: MCPServerLoader | None = None,+ network: NetworkConfig | None = None,) -> None:self._servers = dict(servers)+ self._network = (network or NetworkConfig()).model_copy(deep=True)self._registry = registryself._server_loader = server_loader or _load_current_serversself._connections: dict[str, MCPConnection] = {}@@ -1420,6 +1454,7 @@ class MCPProvider:_configured_servers(config),registry,server_loader=server_loader,+ network=config.network,)@property@@ -1491,7 +1526,7 @@ class MCPProvider:returnself._set_runtime_status(missing_servers, "connecting")try:- connected = await connect_mcp_servers(missing_servers, self._registry)+ connected = await connect_mcp_servers(missing_servers, self._registry, network=self._network)if self._closing:await _close_mcp_connections(connected)return@@ -1526,7 +1561,8 @@ class MCPProvider:if self._closing:return self._closing_result()try:- next_servers = dict(self._server_loader())+ loaded_servers, next_network = self._server_loader()+ next_servers = dict(loaded_servers)except Exception as exc:logger.warning("MCP hot reload could not read config: {}", exc)return {@@ -1553,6 +1589,7 @@ class MCPProvider:for name in current_names & next_namesif _server_signature(current_servers[name])!= _server_signature(next_servers[name])+ or (next_servers[name].use_proxy and self._network.proxy != next_network.proxy))tools_removed = 0@@ -1564,6 +1601,7 @@ class MCPProvider:self._runtime_statuses.pop(name, None)self._servers = next_servers+ self._network = next_network.model_copy(deep=True)retry_missing = sorted(namefor name in next_names@@ -1580,7 +1618,7 @@ class MCPProvider:if to_connect:self._set_runtime_status(to_connect, "connecting")try:- connected = await connect_mcp_servers(to_connect, self._registry)+ connected = await connect_mcp_servers(to_connect, self._registry, network=self._network)except BaseException:self._set_runtime_status(to_connect, "failed")raise@@ -1695,6 +1733,7 @@ class MCPProvider:connected = await connect_mcp_servers({server_name: cfg},self._registry,+ network=self._network,)if self._closing:await _close_mcp_connections(connected)diff --git a/nanobot/agent/tools/runtime_control.py b/nanobot/agent/tools/runtime_control.pyindex 958d9f533..cf44a8b5b 100644--- a/nanobot/agent/tools/runtime_control.py+++ b/nanobot/agent/tools/runtime_control.py@@ -282,8 +282,7 @@ def _snapshot_model_presets(def _snapshot_web_config(config: WebToolsConfig) -> dict[str, object]:return {"enable": config.enable,- # Proxy URLs may embed credentials. Presence is enough for diagnosis.- "proxy": "<configured>" if config.proxy else config.proxy,+ "use_proxy": config.use_proxy,"user_agent": config.user_agent,"search": {"provider": config.search.provider,diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.pyindex 1d81565a0..1643336fe 100644--- a/nanobot/agent/tools/web.py+++ b/nanobot/agent/tools/web.py@@ -416,7 +416,7 @@ class WebSearchTool(Tool):config_loader = _load_search_configreturn cls(config=ctx.config.web.search,- proxy=ctx.config.web.proxy,+ proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),user_agent=ctx.config.web.user_agent,config_loader=config_loader,)@@ -1296,7 +1296,7 @@ class WebFetchTool(Tool):def create(cls, ctx: ToolContext) -> Tool:return cls(config=ctx.config.web.fetch,- proxy=ctx.config.web.proxy,+ proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),user_agent=ctx.config.web.user_agent,)diff --git a/nanobot/agent/tools/web_config.py b/nanobot/agent/tools/web_config.pyindex 761e5cb88..73c258a5a 100644--- a/nanobot/agent/tools/web_config.py+++ b/nanobot/agent/tools/web_config.py@@ -22,7 +22,7 @@ class WebFetchConfig(Base):class WebToolsConfig(Base):"""Web tools configuration."""enable: bool = True- proxy: str | None = None+ use_proxy: bool = Falseuser_agent: str | None = Nonesearch: WebSearchConfig = Field(default_factory=WebSearchConfig)fetch: WebFetchConfig = Field(default_factory=WebFetchConfig)diff --git a/nanobot/channels/base.py b/nanobot/channels/base.pyindex ea4a6dde2..bd455965f 100644--- a/nanobot/channels/base.py+++ b/nanobot/channels/base.py@@ -10,6 +10,7 @@ from loguru import loggerfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.queue import MessageBus+from nanobot.config.network import NetworkConfigfrom nanobot.pairing import (PAIRING_CODE_META_KEY,format_pairing_reply,@@ -29,20 +30,26 @@ class BaseChannel(ABC):name: str = "base"display_name: str = "Base"+ # Opt-in construction capability, not a channel configuration field.+ uses_shared_proxy: bool = Falsesend_progress: bool = Truesend_tool_hints: bool = Trueshow_reasoning: bool = Trueshow_compaction_notices: bool = False- def __init__(self, config: Any, bus: MessageBus):+ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):"""Initialize the channel.Args:config: Channel-specific configuration.bus: The message bus for communication.+ network: Instance-scoped shared network settings."""self.config = config+ self.network = network if network is not None else NetworkConfig()self.logger = logger.bind(channel=self.name)self.bus = busself._running = Falsediff --git a/nanobot/channels/contracts.py b/nanobot/channels/contracts.pyindex 9bb8a6324..01514a881 100644--- a/nanobot/channels/contracts.py+++ b/nanobot/channels/contracts.py@@ -6,9 +6,12 @@ import jsonfrom collections.abc import Iterablefrom copy import deepcopyfrom dataclasses import dataclass+from dataclasses import field as dataclass_fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Literal, TypeGuard, cast+from nanobot.config.network import NetworkConfig+if TYPE_CHECKING:from nanobot.channels.plugin import ChannelPlugin@@ -21,6 +24,7 @@ class ChannelValidationContext:"""Host policy passed to package-owned setup validators."""allow_local_service_access: bool = False+ network: NetworkConfig = dataclass_field(default_factory=NetworkConfig)# Keep callback contracts precise for static consumers. The public adapters belowdiff --git a/nanobot/channels/discord/manifest.py b/nanobot/channels/discord/manifest.pyindex 80b769e58..b09c881eb 100644--- a/nanobot/channels/discord/manifest.py+++ b/nanobot/channels/discord/manifest.py@@ -8,9 +8,7 @@ from nanobot.channels.plugin import ChannelPluginSETUP_SPEC = ChannelSetupSpec(fields={"token": field("secret"),- "proxy": field(),- "proxyUsername": field(),- "proxyPassword": field("secret"),+ "useProxy": field("bool", default=False),"allowFrom": field("list", snapshot=False),"allowChannels": field("list"),"groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"),diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex c4ef223cc..5cc58afb9 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -19,6 +19,7 @@ from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.command.builtin import build_help_text+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.config_base import Basefrom nanobot.utils.helpers import safe_filename, split_message@@ -64,9 +65,7 @@ class DiscordConfig(Base):working_emoji_delay: float = 2.0streaming: bool = Truereply_to_message: bool = False- proxy: str | None = None- proxy_username: str | None = None- proxy_password: str | None = None+ use_proxy: bool = Falseif DISCORD_AVAILABLE:@@ -378,6 +377,7 @@ class DiscordChannel(BaseChannel):name = "discord"display_name = "Discord"+ uses_shared_proxy = True_STREAM_EDIT_INTERVAL = 0.8@classmethod@@ -443,11 +443,14 @@ class DiscordChannel(BaseChannel):partial = cast(Any, channel).get_partial_message(message_id)return partial.to_reference(fail_if_not_exists=fail_if_not_exists), mention_settings- def __init__(self, config: Any, bus: MessageBus):+ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):if isinstance(config, dict):config = DiscordConfig.model_validate(config)- super().__init__(config, bus)+ super().__init__(config, bus, network=network)self.config: DiscordConfig = config+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)self._client: DiscordBotClient | None = Noneself._typing_tasks: dict[str, asyncio.Task[None]] = {}self._bot_user_id: str | None = None@@ -478,30 +481,10 @@ class DiscordChannel(BaseChannel):intents = discord.Intents.none()intents.value = self.config.intents- proxy_auth = None- has_user = bool(self.config.proxy_username)- has_pass = bool(self.config.proxy_password)- if has_user and has_pass:- import aiohttp-- proxy_auth = aiohttp.BasicAuth(- login=cast(str, self.config.proxy_username),- password=cast(str, self.config.proxy_password),- )- elif has_user != has_pass:- self.logger.warning(- "proxy auth incomplete: both proxy_username and "- "proxy_password must be set; ignoring partial credentials",- )-- proxy = self.config.proxy- if proxy and "://" not in proxy:- proxy = f"http://{proxy}"self._client = DiscordBotClient(self,intents=intents,- proxy=proxy,- proxy_auth=proxy_auth,+ proxy=self._proxy,)except Exception:self.logger.exception("Failed to initialize client")diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.pyindex f11a243ca..47d1ff2cc 100644--- a/nanobot/channels/discord/tests/test_discord_channel.py+++ b/nanobot/channels/discord/tests/test_discord_channel.py@@ -22,6 +22,7 @@ from nanobot.channels.discord.runtime import (DiscordConfig,)from nanobot.command.builtin import build_help_text+from nanobot.config.network import NetworkConfig# Minimal Discord client test double used to control startup/readiness behavior.@@ -1566,25 +1567,20 @@ async def test_start_typing_uses_typing_context_when_trigger_typing_missing() ->assert channel._typing_tasks == {}-def test_config_accepts_proxy_fields() -> None:- config = DiscordConfig(- enabled=True,- token="token",- allow_from=["*"],- proxy="http://127.0.0.1:7890",- proxy_username="user",- proxy_password="pass",- )- assert config.proxy == "http://127.0.0.1:7890"- assert config.proxy_username == "user"- assert config.proxy_password == "pass"+def test_config_accepts_proxy_opt_in() -> None:+ config = DiscordConfig.model_validate({+ "enabled": True,+ "token": "token",+ "allowFrom": ["*"],+ "useProxy": True,+ })+ assert config.use_proxy is True+ assert config.model_dump(by_alias=True)["useProxy"] is True-def test_config_proxy_defaults_to_none() -> None:+def test_config_proxy_defaults_to_disabled() -> None:config = DiscordConfig(enabled=True, token="token", allow_from=["*"])- assert config.proxy is None- assert config.proxy_username is None- assert config.proxy_password is None+ assert config.use_proxy is False@pytest.mark.asyncio@@ -1595,9 +1591,10 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:enabled=True,token="token",allow_from=["*"],- proxy="http://127.0.0.1:7890",+ use_proxy=True,),MessageBus(),+ network=NetworkConfig(proxy="http://127.0.0.1:7890"),)monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)@@ -1610,19 +1607,15 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:@pytest.mark.asyncio-async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) -> None:+async def test_start_passes_shared_url_credentials_to_aiohttp(monkeypatch) -> None:aiohttp = pytest.importorskip("aiohttp")+_FakeDiscordClient.instances.clear()+ network = NetworkConfig(proxy="http://user:p%[email protected]:7890")channel = DiscordChannel(- DiscordConfig(- enabled=True,- token="token",- allow_from=["*"],- proxy="http://127.0.0.1:7890",- proxy_username="user",- proxy_password="pass",- ),+ DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=True),MessageBus(),+ network=network,)monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)@@ -1630,54 +1623,51 @@ async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) ->assert channel.is_running is Falseassert len(_FakeDiscordClient.instances) == 1- assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"- assert _FakeDiscordClient.instances[0].proxy_auth is not None- assert isinstance(_FakeDiscordClient.instances[0].proxy_auth, aiohttp.BasicAuth)- assert _FakeDiscordClient.instances[0].proxy_auth.login == "user"- assert _FakeDiscordClient.instances[0].proxy_auth.password == "pass"---async def test_start_no_proxy_auth_when_only_username(monkeypatch) -> None:+ client = _FakeDiscordClient.instances[0]+ assert client.proxy == network.proxy+ # aiohttp extracts URL credentials for the proxy connection, not the destination request.+ proxy_connection = AsyncMock(side_effect=RuntimeError("stop before opening proxy socket"))+ monkeypatch.setattr(aiohttp.TCPConnector, "_create_direct_connection", proxy_connection)+ async with aiohttp.ClientSession() as session:+ with pytest.raises(RuntimeError, match="stop before opening proxy socket"):+ await session.get(+ "https://discord.com/api/v10/users/@me",+ proxy=client.proxy, proxy_auth=client.proxy_auth,+ )++ proxy_connection.assert_awaited_once()+ request = proxy_connection.await_args.args[0]+ assert request.url.host == "127.0.0.1"+ assert request.url.port == 7890+ auth = aiohttp.BasicAuth.decode(request.headers["Proxy-Authorization"])+ assert auth.login == "user"+ assert auth.password == "p@ss"+++async def test_start_without_opt_in_ignores_shared_proxy_credentials(monkeypatch) -> None:_FakeDiscordClient.instances.clear()channel = DiscordChannel(- DiscordConfig(- enabled=True,- token="token",- allow_from=["*"],- proxy="http://127.0.0.1:7890",- proxy_username="user",- ),+ DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=False),MessageBus(),+ network=NetworkConfig(proxy="http://user:[email protected]:7890"),)monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)await channel.start()assert channel.is_running is False+ assert _FakeDiscordClient.instances[0].proxy is Noneassert _FakeDiscordClient.instances[0].proxy_auth is None-async def test_start_no_proxy_auth_when_only_password(monkeypatch) -> None:- _FakeDiscordClient.instances.clear()- channel = DiscordChannel(- DiscordConfig(- enabled=True,- token="token",- allow_from=["*"],- proxy="http://127.0.0.1:7890",- proxy_password="pass",- ),- MessageBus(),- )- monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)-- await channel.start()-- assert channel.is_running is False- assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"- assert _FakeDiscordClient.instances[0].proxy_auth is None+def test_proxy_opt_in_without_shared_address_fails_before_start() -> None:+ with pytest.raises(ValueError, match="Advanced"):+ DiscordChannel(+ DiscordConfig(enabled=True, token="token", use_proxy=True),+ MessageBus(),+ network=NetworkConfig(),+ )# ---------------------------------------------------------------------------diff --git a/nanobot/channels/discord/validation.py b/nanobot/channels/discord/validation.pyindex 6fb1025ee..637a3b049 100644--- a/nanobot/channels/discord/validation.py+++ b/nanobot/channels/discord/validation.py@@ -10,15 +10,20 @@ from nanobot.channels.validation import (http_get,payload,required_checks,+ resolve_proxy,status_from_checks,string_value,)-def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:+def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:checks, missing = required_checks("discord", values)+ try:+ proxy = resolve_proxy(values, context)+ except ValueError as exc:+ checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))+ return status_from_checks("discord", checks, missing)token = string_value(values.get("token"))- proxy = string_value(values.get("proxy"))if token:try:data = http_get(@@ -61,9 +66,9 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dictf"Discord rejected the token: HTTP {exc.response.status_code}",))- except Exception as exc:+ except Exception:checks.append(- check("bot_token", "Bot token", "warn", f"Could not reach Discord now: {exc}")+ check("bot_token", "Bot token", "warn", "Could not reach Discord now. Try again later."))return status_from_checks("discord", checks, missing)diff --git a/nanobot/channels/discord/webui/index.ts b/nanobot/channels/discord/webui/index.tsindex 3c5b129da..0fa87d0bd 100644--- a/nanobot/channels/discord/webui/index.ts+++ b/nanobot/channels/discord/webui/index.ts@@ -12,9 +12,7 @@ export default {docsUrl: chatAppGuideUrl("discord"),fields: [{ key: "channels.discord.token", section: "credentials" },- { key: "channels.discord.proxy", section: "connection" },- { key: "channels.discord.proxyUsername", section: "connection" },- { key: "channels.discord.proxyPassword", section: "connection" },+ { key: "channels.discord.useProxy", section: "connection", control: "switch" },{ key: "channels.discord.allowFrom", section: "access" },{ key: "channels.discord.allowChannels", section: "access" },{ key: "channels.discord.groupPolicy", section: "behavior" },diff --git a/nanobot/channels/discord/webui/locales/en.json b/nanobot/channels/discord/webui/locales/en.jsonindex 5abca7762..548378dbf 100644--- a/nanobot/channels/discord/webui/locales/en.json+++ b/nanobot/channels/discord/webui/locales/en.json@@ -23,14 +23,8 @@"label": "Allowed users","placeholder": "User IDs, comma separated"},- "proxy": {- "label": "Network proxy"- },- "proxyUsername": {- "label": "Proxy username"- },- "proxyPassword": {- "label": "Proxy password"+ "useProxy": {+ "label": "Use proxy"},"intents": {"label": "Gateway intents"diff --git a/nanobot/channels/discord/webui/locales/es.json b/nanobot/channels/discord/webui/locales/es.jsonindex 1d1569b05..cf1e23d59 100644--- a/nanobot/channels/discord/webui/locales/es.json+++ b/nanobot/channels/discord/webui/locales/es.json@@ -23,14 +23,8 @@"label": "Usuarios permitidos","placeholder": "ID de usuario separados por comas"},- "proxy": {- "label": "proxy de red"- },- "proxyUsername": {- "label": "Usuario del proxy"- },- "proxyPassword": {- "label": "Contraseña de proxy"+ "useProxy": {+ "label": "Usar proxy"},"intents": {"label": "Intentos de puerta de enlace"diff --git a/nanobot/channels/discord/webui/locales/fr.json b/nanobot/channels/discord/webui/locales/fr.jsonindex 85e487113..de7a9d315 100644--- a/nanobot/channels/discord/webui/locales/fr.json+++ b/nanobot/channels/discord/webui/locales/fr.json@@ -23,14 +23,8 @@"label": "Utilisateurs autorisés","placeholder": "ID utilisateur séparés par des virgules"},- "proxy": {- "label": "Mandataire réseau"- },- "proxyUsername": {- "label": "Utilisateur du proxy"- },- "proxyPassword": {- "label": "Mot de passe proxy"+ "useProxy": {+ "label": "Utiliser le proxy"},"intents": {"label": "Intentions de passerelle"diff --git a/nanobot/channels/discord/webui/locales/id.json b/nanobot/channels/discord/webui/locales/id.jsonindex ea5490ced..8caaacfb3 100644--- a/nanobot/channels/discord/webui/locales/id.json+++ b/nanobot/channels/discord/webui/locales/id.json@@ -23,14 +23,8 @@"label": "Pengguna diizinkan","placeholder": "ID pengguna, dipisahkan koma"},- "proxy": {- "label": "Proksi jaringan"- },- "proxyUsername": {- "label": "Nama pengguna proxy"- },- "proxyPassword": {- "label": "Kata sandi proksi"+ "useProxy": {+ "label": "Gunakan proxy"},"intents": {"label": "Maksud gerbang"diff --git a/nanobot/channels/discord/webui/locales/ja.json b/nanobot/channels/discord/webui/locales/ja.jsonindex a12f19f8b..68e27f87a 100644--- a/nanobot/channels/discord/webui/locales/ja.json+++ b/nanobot/channels/discord/webui/locales/ja.json@@ -23,14 +23,8 @@"label": "許可ユーザー","placeholder": "ユーザー ID(カンマ区切り)"},- "proxy": {- "label": "ネットワークプロキシ"- },- "proxyUsername": {- "label": "プロキシのユーザー名"- },- "proxyPassword": {- "label": "プロキシパスワード"+ "useProxy": {+ "label": "プロキシを使う"},"intents": {"label": "ゲートウェイの意図"diff --git a/nanobot/channels/discord/webui/locales/ko.json b/nanobot/channels/discord/webui/locales/ko.jsonindex 3706f7d81..548684c50 100644--- a/nanobot/channels/discord/webui/locales/ko.json+++ b/nanobot/channels/discord/webui/locales/ko.json@@ -23,14 +23,8 @@"label": "허용 사용자","placeholder": "사용자 ID, 쉼표로 구분"},- "proxy": {- "label": "네트워크 프록시"- },- "proxyUsername": {- "label": "프록시 사용자 이름"- },- "proxyPassword": {- "label": "프록시 비밀번호"+ "useProxy": {+ "label": "프록시 사용"},"intents": {"label": "게이트웨이 인텐트"diff --git a/nanobot/channels/discord/webui/locales/pt-BR.json b/nanobot/channels/discord/webui/locales/pt-BR.jsonindex 1e887f5ec..013afc12f 100644--- a/nanobot/channels/discord/webui/locales/pt-BR.json+++ b/nanobot/channels/discord/webui/locales/pt-BR.json@@ -23,14 +23,8 @@"label": "Usuários permitidos","placeholder": "IDs de usuário separados por vírgulas"},- "proxy": {- "label": "Proxy de rede"- },- "proxyUsername": {- "label": "Usuário do proxy"- },- "proxyPassword": {- "label": "Senha proxy"+ "useProxy": {+ "label": "Usar proxy"},"intents": {"label": "Intenções de gateway"diff --git a/nanobot/channels/discord/webui/locales/vi.json b/nanobot/channels/discord/webui/locales/vi.jsonindex 37d17d357..997d9a4ab 100644--- a/nanobot/channels/discord/webui/locales/vi.json+++ b/nanobot/channels/discord/webui/locales/vi.json@@ -23,14 +23,8 @@"label": "Người dùng được phép","placeholder": "ID người dùng, phân tách bằng dấu phẩy"},- "proxy": {- "label": "Proxy mạng"- },- "proxyUsername": {- "label": "Tên người dùng proxy"- },- "proxyPassword": {- "label": "Mật khẩu proxy"+ "useProxy": {+ "label": "Dùng proxy"},"intents": {"label": "Ý định của cổng"diff --git a/nanobot/channels/discord/webui/locales/zh-CN.json b/nanobot/channels/discord/webui/locales/zh-CN.jsonindex e367b8190..e393ec63a 100644--- a/nanobot/channels/discord/webui/locales/zh-CN.json+++ b/nanobot/channels/discord/webui/locales/zh-CN.json@@ -23,14 +23,8 @@"label": "允许用户","placeholder": "用户 ID,用逗号分隔"},- "proxy": {- "label": "网络代理"- },- "proxyUsername": {- "label": "代理账号"- },- "proxyPassword": {- "label": "代理密码"+ "useProxy": {+ "label": "使用代理"},"intents": {"label": "Gateway Intents"diff --git a/nanobot/channels/discord/webui/locales/zh-TW.json b/nanobot/channels/discord/webui/locales/zh-TW.jsonindex fa01cba16..e1da2f862 100644--- a/nanobot/channels/discord/webui/locales/zh-TW.json+++ b/nanobot/channels/discord/webui/locales/zh-TW.json@@ -23,14 +23,8 @@"label": "允許使用者","placeholder": "使用者 ID,以逗號分隔"},- "proxy": {- "label": "網路代理"- },- "proxyUsername": {- "label": "代理賬號"- },- "proxyPassword": {- "label": "代理密碼"+ "useProxy": {+ "label": "使用代理"},"intents": {"label": "Gateway Intents"diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pyindex 6700f69cb..bc07c1a3a 100644--- a/nanobot/channels/manager.py+++ b/nanobot/channels/manager.py@@ -202,6 +202,8 @@ class ChannelManager:runtime_name: str | None = None,) -> BaseChannel:kwargs: dict[str, Any] = {}+ if cls.uses_shared_proxy:+ kwargs["network"] = self.config.networkif cls.name == "websocket":from nanobot.channels.websocket.runtime import WebSocketConfigfrom nanobot.webui.gateway_services import build_gateway_servicesdiff --git a/nanobot/channels/matrix/manifest.py b/nanobot/channels/matrix/manifest.pyindex d6096b6f1..45546866e 100644--- a/nanobot/channels/matrix/manifest.py+++ b/nanobot/channels/matrix/manifest.py@@ -22,7 +22,7 @@ SETUP_SPEC = ChannelSetupSpec("groupAllowFrom": field("list"),"allowRoomMentions": field("bool", default=False),"streaming": field("bool", default=False),- "proxy": field(),+ "useProxy": field("bool", default=False),},required=(*required_fields("homeserver", "userId"),diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex 94997d9b1..b2b1fb8aa 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -63,6 +63,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_data_dir, get_media_dirfrom nanobot.config_base import Basefrom nanobot.events import ContextCompactionEvent@@ -303,7 +304,7 @@ class MatrixConfig(Base):group_allow_from: list[str] = Field(default_factory=list)allow_room_mentions: bool = Falsestreaming: bool = False- proxy: str | None = None+ use_proxy: bool = Falseclass MatrixChannel(BaseChannel):@@ -311,6 +312,7 @@ class MatrixChannel(BaseChannel):name = "matrix"display_name = "Matrix"+ uses_shared_proxy = True_STREAM_EDIT_INTERVAL = 2 # min seconds between edit_message_text callsmonotonic_time: Callable[[], float] = staticmethod(time.monotonic)@@ -323,12 +325,15 @@ class MatrixChannel(BaseChannel):config: Any,bus: MessageBus,*,+ network: NetworkConfig | None = None,restrict_to_workspace: bool = False,workspace: str | Path | None = None,):if isinstance(config, dict):config = MatrixConfig.model_validate(config)- super().__init__(config, bus)+ super().__init__(config, bus, network=network)+ self.config: MatrixConfig = config+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)self.client: AsyncClient | None = Noneself._sync_task: asyncio.Task[None] | None = Noneself._typing_tasks: dict[str, asyncio.Task[None]] = {}@@ -359,14 +364,11 @@ class MatrixChannel(BaseChannel):# Replace ':' with '_' to produce a Windows-safe filenamesafe_store_name = self.config.user_id.replace(":", "_") + f"_{self.config.device_id}.db"- proxy = self.config.proxy.strip() if self.config.proxy else ""- if proxy and "://" not in proxy:- proxy = f"http://{proxy}"self.client = AsyncClient(homeserver=self.config.homeserver,user=self.config.user_id,store_path=str(self.store_path),- proxy=proxy or None,+ proxy=self._proxy,config=AsyncClientConfig(store_sync_tokens=True,encryption_enabled=self.config.e2ee_enabled,diff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.pyindex 31ce7a5ee..1cc943c41 100644--- a/nanobot/channels/matrix/tests/test_matrix_channel.py+++ b/nanobot/channels/matrix/tests/test_matrix_channel.py@@ -25,6 +25,7 @@ from nanobot.channels.matrix.runtime import (MatrixConfig,_build_matrix_text_content,)+from nanobot.config.network import NetworkConfig_ROOM_SEND_UNSET = object()@@ -328,8 +329,9 @@ async def test_start_skips_load_store_when_device_id_missing()channel = MatrixChannel(- _make_config(device_id="", e2ee_enabled=True, proxy="127.0.0.1:7890"),+ _make_config(device_id="", e2ee_enabled=True, use_proxy=True),MessageBus(),+ network=NetworkConfig(proxy="127.0.0.1:7890"),)await channel.start()diff --git a/nanobot/channels/matrix/validation.py b/nanobot/channels/matrix/validation.pyindex cfe443661..ff68f6302 100644--- a/nanobot/channels/matrix/validation.py+++ b/nanobot/channels/matrix/validation.py@@ -3,11 +3,22 @@from typing import Anyfrom nanobot.channels.contracts import ChannelValidationContext-from nanobot.channels.validation import check, required_checks, status_from_checks, string_value+from nanobot.channels.validation import (+ check,+ required_checks,+ resolve_proxy,+ status_from_checks,+ string_value,+)-def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:+def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:checks, missing = required_checks("matrix", values)+ try:+ resolve_proxy(values, context)+ except ValueError as exc:+ checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))+ return status_from_checks("matrix", checks, missing)password = string_value(values.get("password"))access_token = string_value(values.get("accessToken"))device_id = string_value(values.get("deviceId"))diff --git a/nanobot/channels/matrix/webui/index.ts b/nanobot/channels/matrix/webui/index.tsindex 803bd6c7a..e7ef2d271 100644--- a/nanobot/channels/matrix/webui/index.ts+++ b/nanobot/channels/matrix/webui/index.ts@@ -12,6 +12,7 @@ export default {docsUrl: chatAppGuideUrl("matrix"),fields: [{ key: "channels.matrix.homeserver", section: "connection" },+ { key: "channels.matrix.useProxy", section: "connection", control: "switch" },{ key: "channels.matrix.userId", section: "account" },{ key: "channels.matrix.password", section: "credentials" },{ key: "channels.matrix.accessToken", section: "credentials" },diff --git a/nanobot/channels/matrix/webui/locales/en.json b/nanobot/channels/matrix/webui/locales/en.jsonindex 81dd1c96a..7f0c79dd1 100644--- a/nanobot/channels/matrix/webui/locales/en.json+++ b/nanobot/channels/matrix/webui/locales/en.json@@ -74,9 +74,8 @@"false": "Off"}},- "proxy": {- "label": "Network proxy",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Use proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/es.json b/nanobot/channels/matrix/webui/locales/es.jsonindex ddb517a5b..9551b70ef 100644--- a/nanobot/channels/matrix/webui/locales/es.json+++ b/nanobot/channels/matrix/webui/locales/es.json@@ -74,9 +74,8 @@"false": "Apagado"}},- "proxy": {- "label": "Proxy de red",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/fr.json b/nanobot/channels/matrix/webui/locales/fr.jsonindex 6d609c414..82c60ce48 100644--- a/nanobot/channels/matrix/webui/locales/fr.json+++ b/nanobot/channels/matrix/webui/locales/fr.json@@ -74,9 +74,8 @@"false": "Désactivé"}},- "proxy": {- "label": "Proxy réseau",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Utiliser le proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/id.json b/nanobot/channels/matrix/webui/locales/id.jsonindex 2e66c56e6..c409eb5da 100644--- a/nanobot/channels/matrix/webui/locales/id.json+++ b/nanobot/channels/matrix/webui/locales/id.json@@ -74,9 +74,8 @@"false": "Mati"}},- "proxy": {- "label": "Proxy jaringan",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Gunakan proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/ja.json b/nanobot/channels/matrix/webui/locales/ja.jsonindex e5fda500c..665b0056a 100644--- a/nanobot/channels/matrix/webui/locales/ja.json+++ b/nanobot/channels/matrix/webui/locales/ja.json@@ -74,9 +74,8 @@"false": "オフ"}},- "proxy": {- "label": "ネットワークプロキシ",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "プロキシを使う"}}}diff --git a/nanobot/channels/matrix/webui/locales/ko.json b/nanobot/channels/matrix/webui/locales/ko.jsonindex df9f0460f..c72483054 100644--- a/nanobot/channels/matrix/webui/locales/ko.json+++ b/nanobot/channels/matrix/webui/locales/ko.json@@ -74,9 +74,8 @@"false": "끄기"}},- "proxy": {- "label": "네트워크 프록시",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "프록시 사용"}}}diff --git a/nanobot/channels/matrix/webui/locales/pt-BR.json b/nanobot/channels/matrix/webui/locales/pt-BR.jsonindex 2aaf6d335..841304b13 100644--- a/nanobot/channels/matrix/webui/locales/pt-BR.json+++ b/nanobot/channels/matrix/webui/locales/pt-BR.json@@ -74,9 +74,8 @@"false": "Desligado"}},- "proxy": {- "label": "Proxy de rede",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/vi.json b/nanobot/channels/matrix/webui/locales/vi.jsonindex 7e46e5a1b..715f4a623 100644--- a/nanobot/channels/matrix/webui/locales/vi.json+++ b/nanobot/channels/matrix/webui/locales/vi.json@@ -74,9 +74,8 @@"false": "Tắt"}},- "proxy": {- "label": "Proxy mạng",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Dùng proxy"}}}diff --git a/nanobot/channels/matrix/webui/locales/zh-CN.json b/nanobot/channels/matrix/webui/locales/zh-CN.jsonindex aa971b2bb..13b601166 100644--- a/nanobot/channels/matrix/webui/locales/zh-CN.json+++ b/nanobot/channels/matrix/webui/locales/zh-CN.json@@ -74,9 +74,8 @@"false": "关闭"}},- "proxy": {- "label": "网络代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}}diff --git a/nanobot/channels/matrix/webui/locales/zh-TW.json b/nanobot/channels/matrix/webui/locales/zh-TW.jsonindex 39c50037e..9ebd4b7dc 100644--- a/nanobot/channels/matrix/webui/locales/zh-TW.json+++ b/nanobot/channels/matrix/webui/locales/zh-TW.json@@ -74,9 +74,8 @@"false": "關閉"}},- "proxy": {- "label": "網路代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}}diff --git a/nanobot/channels/slack/manifest.py b/nanobot/channels/slack/manifest.pyindex 1428ef030..6ee22ceea 100644--- a/nanobot/channels/slack/manifest.py+++ b/nanobot/channels/slack/manifest.py@@ -23,7 +23,7 @@ SETUP_SPEC = ChannelSetupSpec("dm.enabled": field("bool", default=True),"dm.policy": field("enum", choices={"open", "allowlist"}, default="open"),"dm.allowFrom": field("list"),- "proxy": field(),+ "useProxy": field("bool", default=False),},required=required_fields("appToken", "botToken"),official_url="https://api.slack.com/apps",diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.pyindex 13f393005..7e199a6e9 100644--- a/nanobot/channels/slack/runtime.py+++ b/nanobot/channels/slack/runtime.py@@ -19,6 +19,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.config_base import Basefrom nanobot.events import ContextCompactionEvent@@ -84,7 +85,7 @@ class SlackConfig(Base):# instead of every message). No effect for "mention"/"open" policies.group_require_mention: bool = Falsedm: SlackDMConfig = Field(default_factory=SlackDMConfig)- proxy: str | None = None+ use_proxy: bool = FalseSLACK_MAX_MESSAGE_LEN = 39_000 # Slack API allows ~40k; leave margin@@ -109,6 +110,7 @@ class SlackChannel(BaseChannel):name = "slack"display_name = "Slack"+ uses_shared_proxy = True_SLACK_ID_RE = re.compile(r"^[CDGUW][A-Z0-9]{2,}$")_SLACK_CHANNEL_REF_RE = re.compile(r"^<#([A-Z0-9]+)(?:\|[^>]+)?>$")_SLACK_USER_REF_RE = re.compile(r"^<@([A-Z0-9]+)(?:\|[^>]+)?>$")@@ -119,11 +121,14 @@ class SlackChannel(BaseChannel):_THREAD_CONTEXT_CACHE_LIMIT = 10_000- def __init__(self, config: Any, bus: MessageBus):+ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):if isinstance(config, dict):config = SlackConfig.model_validate(config)- super().__init__(config, bus)+ super().__init__(config, bus, network=network)self.config: SlackConfig = config+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)self._web_client: AsyncWebClient | None = Noneself._socket_client: SocketModeClient | None = Noneself._bot_user_id: str | None = None@@ -148,10 +153,7 @@ class SlackChannel(BaseChannel):self._running = True- proxy = self.config.proxy.strip() if self.config.proxy else ""- if proxy and "://" not in proxy:- proxy = f"http://{proxy}"- proxy = proxy or None+ proxy = self._proxyself._web_client = AsyncWebClient(token=self.config.bot_token, proxy=proxy)self._socket_client = SocketModeClient(app_token=self.config.app_token,@@ -592,14 +594,10 @@ class SlackChannel(BaseChannel):mounts=({"all://": httpx.AsyncHTTPTransport(- proxy=httpx.Proxy(- self.config.proxy- if "://" in self.config.proxy- else f"http://{self.config.proxy}"- )+ proxy=httpx.Proxy(self._proxy))}- if self.config.proxy+ if self._proxyelse httpx_env_proxy_mounts()),event_hooks={"request": [_validate_slack_download_request]},diff --git a/nanobot/channels/slack/tests/test_slack_channel.py b/nanobot/channels/slack/tests/test_slack_channel.pyindex dbfe8bd6c..4aa9a58e2 100644--- a/nanobot/channels/slack/tests/test_slack_channel.py+++ b/nanobot/channels/slack/tests/test_slack_channel.py@@ -17,6 +17,7 @@ except ImportError:from nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.slack.runtime import SLACK_MAX_MESSAGE_LEN, SlackChannel, SlackConfig+from nanobot.config.network import NetworkConfigclass _FakeAsyncWebClient:@@ -984,3 +985,74 @@ async def test_download_follows_safe_redirect(assert validated == [url, "https://cdn.example/file.bin"]assert requests[0].headers["Authorization"] == "Bearer xoxb-test"assert "Authorization" not in requests[1].headers++[email protected]("use_proxy", [True, False])+async def test_start_uses_shared_proxy_for_web_api_and_socket_mode(monkeypatch, use_proxy) -> None:+ network = NetworkConfig(proxy="http://127.0.0.1:7890")+ channel = SlackChannel(+ SlackConfig(bot_token="xoxb-test", app_token="xapp-test", use_proxy=use_proxy),+ MessageBus(),+ network=network,+ )+ captured = {}++ def web_client(**kwargs):+ captured["web"] = kwargs+ return SimpleNamespace(auth_test=AsyncMock(return_value={"user_id": "U42"}))++ async def connect():+ channel._running = False++ def socket_client(**kwargs):+ captured["socket"] = kwargs+ return SimpleNamespace(socket_mode_request_listeners=[], connect=connect)++ monkeypatch.setattr("nanobot.channels.slack.runtime.AsyncWebClient", web_client)+ monkeypatch.setattr("nanobot.channels.slack.runtime.SocketModeClient", socket_client)++ await channel.start()++ expected = network.proxy if use_proxy else None+ assert captured["web"] == {"token": "xoxb-test", "proxy": expected}+ assert captured["socket"]["proxy"] == expected+ assert captured["socket"]["web_client"] is channel._web_client+ assert channel._bot_user_id == "U42"+++async def test_download_uses_shared_proxy_and_keeps_redirect_validation(monkeypatch, tmp_path) -> None:+ proxies = []+ requests = []+ validated = []+ network = NetworkConfig(proxy="http://user:[email protected]:7890")++ def handler(request):+ requests.append(request)+ return httpx.Response(302, headers={"location": "http://169.254.169.254/secret"})++ def proxy_transport(*, proxy):+ proxies.append(proxy)+ return httpx.MockTransport(handler)++ monkeypatch.setattr("nanobot.channels.slack.runtime.httpx.AsyncHTTPTransport", proxy_transport)+ monkeypatch.setattr("nanobot.channels.slack.runtime.PinnedDNSAsyncTransport", lambda: httpx.MockTransport(handler))+ monkeypatch.setattr("nanobot.channels.slack.runtime.get_media_dir", lambda _name: tmp_path)+ _patch_download_validation(monkeypatch, validated)+ channel = SlackChannel(+ SlackConfig(bot_token="xoxb-test", use_proxy=True), MessageBus(), network=network,+ )+ url = "https://files.slack.com/file.bin"++ path, _marker = await channel._download_slack_file({+ "id": "F1", "name": "file.bin", "url_private_download": url,+ })++ assert path is None+ assert len(proxies) == 1+ assert proxies[0].url == httpx.URL("http://127.0.0.1:7890")+ assert proxies[0].raw_auth == (b"user", b"pass")+ assert len(requests) == 1+ assert validated == [url, "http://169.254.169.254/secret"]+ assert requests[0].headers["Authorization"] == "Bearer xoxb-test"diff --git a/nanobot/channels/slack/validation.py b/nanobot/channels/slack/validation.pyindex 4b5e8efc1..f45f14eb5 100644--- a/nanobot/channels/slack/validation.py+++ b/nanobot/channels/slack/validation.py@@ -10,16 +10,21 @@ from nanobot.channels.validation import (official_action,payload,required_checks,+ resolve_proxy,status_from_checks,string_value,)-def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:+def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:checks, missing = required_checks("slack", values)+ try:+ proxy = resolve_proxy(values, context)+ except ValueError as exc:+ checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))+ return status_from_checks("slack", checks, missing)app_token = string_value(values.get("appToken"))bot_token = string_value(values.get("botToken"))- proxy = string_value(values.get("proxy"))if app_token:checks.append(check(@@ -76,13 +81,13 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dictmessage_from_response(data, "Slack rejected the bot token."),))- except Exception as exc:+ except Exception:checks.append(check("auth_test","Workspace identity","warn",- f"Could not reach Slack now: {exc}",+ "Could not reach Slack now. Try again later.",))return status_from_checks("slack", checks, missing)diff --git a/nanobot/channels/slack/webui/index.ts b/nanobot/channels/slack/webui/index.tsindex 7b40a5581..c60a819bd 100644--- a/nanobot/channels/slack/webui/index.ts+++ b/nanobot/channels/slack/webui/index.ts@@ -56,6 +56,7 @@ export default {fields: [{ key: "channels.slack.appToken", section: "credentials" },{ key: "channels.slack.botToken", section: "credentials" },+ { key: "channels.slack.useProxy", section: "connection", control: "switch" },{ key: "channels.slack.groupPolicy", section: "behavior" },],},diff --git a/nanobot/channels/slack/webui/locales/en.json b/nanobot/channels/slack/webui/locales/en.jsonindex abca17633..426d5210c 100644--- a/nanobot/channels/slack/webui/locales/en.json+++ b/nanobot/channels/slack/webui/locales/en.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Allowed DM users"},- "proxy": {- "label": "Network proxy",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Use proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/es.json b/nanobot/channels/slack/webui/locales/es.jsonindex 16e1fd4ab..912ee2033 100644--- a/nanobot/channels/slack/webui/locales/es.json+++ b/nanobot/channels/slack/webui/locales/es.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Usuarios de DM permitidos"},- "proxy": {- "label": "Proxy de red",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/fr.json b/nanobot/channels/slack/webui/locales/fr.jsonindex a8772e7f2..f9fe9ad8f 100644--- a/nanobot/channels/slack/webui/locales/fr.json+++ b/nanobot/channels/slack/webui/locales/fr.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Utilisateurs de DM autorisés"},- "proxy": {- "label": "Proxy réseau",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Utiliser le proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/id.json b/nanobot/channels/slack/webui/locales/id.jsonindex bdb2d2a59..505a319fc 100644--- a/nanobot/channels/slack/webui/locales/id.json+++ b/nanobot/channels/slack/webui/locales/id.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Pengguna DM diizinkan"},- "proxy": {- "label": "Proxy jaringan",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Gunakan proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/ja.json b/nanobot/channels/slack/webui/locales/ja.jsonindex 39794b3fe..ae81f2011 100644--- a/nanobot/channels/slack/webui/locales/ja.json+++ b/nanobot/channels/slack/webui/locales/ja.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "許可する DM ユーザー"},- "proxy": {- "label": "ネットワークプロキシ",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "プロキシを使う"}}}diff --git a/nanobot/channels/slack/webui/locales/ko.json b/nanobot/channels/slack/webui/locales/ko.jsonindex 21373083b..2e2179832 100644--- a/nanobot/channels/slack/webui/locales/ko.json+++ b/nanobot/channels/slack/webui/locales/ko.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "허용 DM 사용자"},- "proxy": {- "label": "네트워크 프록시",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "프록시 사용"}}}diff --git a/nanobot/channels/slack/webui/locales/pt-BR.json b/nanobot/channels/slack/webui/locales/pt-BR.jsonindex 3550ec5b0..859efb470 100644--- a/nanobot/channels/slack/webui/locales/pt-BR.json+++ b/nanobot/channels/slack/webui/locales/pt-BR.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Usuários de DM permitidos"},- "proxy": {- "label": "Proxy de rede",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/vi.json b/nanobot/channels/slack/webui/locales/vi.jsonindex 1c35e1845..5c3d8934e 100644--- a/nanobot/channels/slack/webui/locales/vi.json+++ b/nanobot/channels/slack/webui/locales/vi.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "Người dùng DM được phép"},- "proxy": {- "label": "Proxy mạng",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Dùng proxy"}}}diff --git a/nanobot/channels/slack/webui/locales/zh-CN.json b/nanobot/channels/slack/webui/locales/zh-CN.jsonindex d1dcf8159..8acc0bbe6 100644--- a/nanobot/channels/slack/webui/locales/zh-CN.json+++ b/nanobot/channels/slack/webui/locales/zh-CN.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "私聊用户"},- "proxy": {- "label": "网络代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}}diff --git a/nanobot/channels/slack/webui/locales/zh-TW.json b/nanobot/channels/slack/webui/locales/zh-TW.jsonindex 4c1a5f952..69e8ef342 100644--- a/nanobot/channels/slack/webui/locales/zh-TW.json+++ b/nanobot/channels/slack/webui/locales/zh-TW.json@@ -84,9 +84,8 @@"dm_allowFrom": {"label": "私聊使用者"},- "proxy": {- "label": "網路代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}}diff --git a/nanobot/channels/telegram/manifest.py b/nanobot/channels/telegram/manifest.pyindex 93d806ee3..abff86593 100644--- a/nanobot/channels/telegram/manifest.py+++ b/nanobot/channels/telegram/manifest.py@@ -8,7 +8,7 @@ from nanobot.channels.telegram.validation import validateSETUP_SPEC = ChannelSetupSpec(fields={"token": field("secret"),- "proxy": field(),+ "useProxy": field("bool", default=False),"allowFrom": field("list"),"groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),"mode": field("enum", choices={"polling", "webhook"}, default="polling"),diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex b4d249551..0d7c894cb 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -35,6 +35,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.command.builtin import build_help_text+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.config_base import Basefrom nanobot.events import ContextCompactionEvent@@ -495,7 +496,7 @@ class TelegramConfig(Base):token: str = ""mode: Literal["polling", "webhook"] = "polling"allow_from: list[str] = Field(default_factory=list)- proxy: str | None = None+ use_proxy: bool = Falsereply_to_message: bool = Falsereact_emoji: str = "👀"group_policy: Literal["open", "mention"] = "mention"@@ -588,6 +589,7 @@ class TelegramChannel(BaseChannel):name = "telegram"display_name = "Telegram"+ uses_shared_proxy = True# Commands registered with Telegram's command menuBOT_COMMANDS: list[BotCommand] = [@@ -623,11 +625,14 @@ class TelegramChannel(BaseChannel):def default_config(cls) -> dict[str, Any]:return TelegramConfig().model_dump(by_alias=True)- def __init__(self, config: Any, bus: MessageBus):+ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):if isinstance(config, dict):config = TelegramConfig.model_validate(config)- super().__init__(config, bus)+ super().__init__(config, bus, network=network)self.config: TelegramConfig = config+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)self._app: TelegramApplication | None = Noneself._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop taskself._media_group_buffers: dict[str, dict[str, Any]] = {}@@ -735,9 +740,7 @@ class TelegramChannel(BaseChannel):async def _start_app(self) -> None:"""Build, initialize and start the Telegram application."""- proxy = self.config.proxy or None- if proxy and "://" not in proxy:- proxy = f"http://{proxy}"+ proxy = self._proxy# Separate pools so long-polling (getUpdates) never starves outbound sends.api_request = HTTPXRequest(diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.pyindex 4b703695d..cb96ac85f 100644--- a/nanobot/channels/telegram/tests/test_telegram_channel.py+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py@@ -28,6 +28,7 @@ from nanobot.channels.telegram.runtime import (_StreamBuf,_telegram_command_text,)+from nanobot.config.network import NetworkConfigfrom nanobot.events import ContextCompactionEvent@@ -349,10 +350,11 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:enabled=True,token="123:abc",allow_from=["*"],- proxy="http://127.0.0.1:7890",+ use_proxy=True,)bus = MessageBus()- channel = TelegramChannel(config, bus)+ network = NetworkConfig(proxy="http://127.0.0.1:7890")+ channel = TelegramChannel(config, bus, network=network)app = _FakeApp(lambda: setattr(channel, "_running", False))builder = _FakeBuilder(app)@@ -366,8 +368,8 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:assert len(_FakeHTTPXRequest.instances) == 2api_req, poll_req = _FakeHTTPXRequest.instances- assert api_req.kwargs["proxy"] == config.proxy- assert poll_req.kwargs["proxy"] == config.proxy+ assert api_req.kwargs["proxy"] == network.proxy+ assert poll_req.kwargs["proxy"] == network.proxyassert api_req.kwargs["connection_pool_size"] == 32assert poll_req.kwargs["connection_pool_size"] == 4assert builder.request_value is api_reqdiff --git a/nanobot/channels/telegram/tests/test_validation.py b/nanobot/channels/telegram/tests/test_validation.pyindex 81fe982ba..629301680 100644--- a/nanobot/channels/telegram/tests/test_validation.py+++ b/nanobot/channels/telegram/tests/test_validation.py@@ -10,11 +10,12 @@ from nanobot.config.loader import save_configfrom nanobot.config.schema import Config-def test_telegram_setup_exposes_proxy_as_an_optional_field() -> None:- proxy = SETUP_SPEC.fields["proxy"]+def test_telegram_setup_exposes_proxy_opt_in_as_an_optional_field() -> None:+ use_proxy = SETUP_SPEC.fields["useProxy"]- assert proxy.kind == "string"- assert "proxy" not in SETUP_SPEC.simple_required_fields+ assert use_proxy.kind == "bool"+ assert use_proxy.default is False+ assert "useProxy" not in SETUP_SPEC.simple_required_fieldsdef test_get_me_builds_http_client_with_explicit_proxy(@@ -169,7 +170,7 @@ def test_validate_telegram_marks_proxy_transport_failures_without_exposing_proxyconfig_path = tmp_path / "config.json"save_config(Config.model_validate(- {"channels": {"telegram": {"token": token, "proxy": proxy}}}+ {"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}),config_path,)@@ -197,7 +198,7 @@ def test_validate_telegram_uses_saved_proxy_without_exposing_it(config_path = tmp_path / "config.json"save_config(Config.model_validate(- {"channels": {"telegram": {"token": token, "proxy": proxy}}}+ {"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}),config_path,)@@ -230,7 +231,7 @@ def test_validate_telegram_resolves_saved_secret_env_refs_without_exposing_them(config_path = tmp_path / "config.json"save_config(Config.model_validate(- {"channels": {"telegram": {"token": token_ref, "proxy": proxy_ref}}}+ {"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token_ref, "useProxy": True}}}),config_path,)@@ -263,7 +264,7 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(config_path = tmp_path / "config.json"save_config(Config.model_validate(- {"channels": {"telegram": {"token": token, "proxy": proxy_ref}}}+ {"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token, "useProxy": True}}}),config_path,)@@ -279,17 +280,17 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(assert result["status"] == "invalid"assert result["can_enable"] is Falseassert proxy_ref not in str(result)- assert any(check["id"] == "proxy_env" for check in result["checks"])+ assert any(check["id"] == "network_proxy" for check in result["checks"])-def test_validate_telegram_uses_proxy_submitted_with_new_token(+def test_validate_telegram_uses_shared_proxy_when_opt_in_is_submitted_with_new_token(tmp_path,monkeypatch: pytest.MonkeyPatch,) -> None:token = "123456:abcdefghijklmnopqrstuvwxyz"proxy = "http://127.0.0.1:7890"config_path = tmp_path / "config.json"- save_config(Config(), config_path)+ save_config(Config.model_validate({"network": {"proxy": proxy}}), config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)captured: dict[str, str | None] = {}@@ -303,7 +304,7 @@ def test_validate_telegram_uses_proxy_submitted_with_new_token("telegram",{"channels.telegram.token": token,- "channels.telegram.proxy": proxy,+ "channels.telegram.useProxy": True,},)@@ -319,7 +320,10 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token() -> None:token = "123456:abcdefghijklmnopqrstuvwxyz"config_path = tmp_path / "config.json"- save_config(Config(), config_path)+ monkeypatch.setenv("NETWORK_PROXY_TEST", proxy)+ save_config(+ Config.model_validate({"network": {"proxy": "${NETWORK_PROXY_TEST}"}}), config_path,+ )monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)def fail_get_me(*_args) -> dict:@@ -331,11 +335,11 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token("telegram",{"channels.telegram.token": token,- "channels.telegram.proxy": proxy,+ "channels.telegram.useProxy": True,},)assert result["status"] == "invalid"assert result["can_enable"] is Falseassert proxy not in str(result)- assert any(check["id"] == "proxy_format" for check in result["checks"])+ assert any(check["id"] == "network_proxy" for check in result["checks"])diff --git a/nanobot/channels/telegram/validation.py b/nanobot/channels/telegram/validation.pyindex 67302566c..6c92ccf79 100644--- a/nanobot/channels/telegram/validation.py+++ b/nanobot/channels/telegram/validation.py@@ -2,7 +2,6 @@import refrom typing import Any, cast-from urllib.parse import urlparseimport httpx@@ -12,25 +11,13 @@ from nanobot.channels.validation import (message_from_response,payload,required_checks,+ resolve_proxy,status_from_checks,string_value,)from nanobot.config.loader import resolve_env_refs_TIMEOUT_SECONDS = 4.0-_SUPPORTED_PROXY_SCHEMES = {"http", "https", "socks5", "socks5h"}---def _proxy_url_is_valid(proxy: str) -> bool:- if "://" not in proxy:- proxy = f"http://{proxy}"- try:- parsed = urlparse(proxy)- hostname = parsed.hostname- parsed.port- except ValueError:- return False- return parsed.scheme.lower() in _SUPPORTED_PROXY_SCHEMES and bool(hostname)def _get_me(token: str, proxy: str | None) -> dict[str, Any]:@@ -46,12 +33,15 @@ def _get_me(token: str, proxy: str | None) -> dict[str, Any]:return cast(dict[str, Any], data) if isinstance(data, dict) else {}-def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:+def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:checks, missing = required_checks("telegram", values)+ try:+ proxy = resolve_proxy(values, context)+ except ValueError as exc:+ checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))+ return status_from_checks("telegram", checks, missing)raw_token = string_value(values.get("token"))- raw_proxy = string_value(values.get("proxy"))token = string_value(resolve_env_refs(raw_token))- proxy = string_value(resolve_env_refs(raw_proxy))if raw_token and not token:checks.append(check(@@ -61,26 +51,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict"Set every environment variable referenced by the bot token.",))- if raw_proxy and not proxy:- checks.append(- check(- "proxy_env",- "Proxy environment variable",- "fail",- "Set every environment variable referenced by the network proxy.",- )- )- if (raw_token and not token) or (raw_proxy and not proxy):- return status_from_checks("telegram", checks, missing)- if proxy and not _proxy_url_is_valid(proxy):- checks.append(- check(- "proxy_format",- "Network proxy",- "fail",- "Enter a valid HTTP or SOCKS proxy.",- )- )+ if raw_token and not token:return status_from_checks("telegram", checks, missing)if token:if not re.match(r"^\d+:[A-Za-z0-9_-]{20,}$", token):diff --git a/nanobot/channels/telegram/webui/index.ts b/nanobot/channels/telegram/webui/index.tsindex 3a8c3df31..0da0429c1 100644--- a/nanobot/channels/telegram/webui/index.ts+++ b/nanobot/channels/telegram/webui/index.ts@@ -12,7 +12,7 @@ export default {docsUrl: chatAppGuideUrl("telegram"),fields: [{ key: "channels.telegram.token", section: "credentials" },- { key: "channels.telegram.proxy", section: "connection" },+ { key: "channels.telegram.useProxy", section: "connection", control: "switch" },{ key: "channels.telegram.allowFrom", section: "access" },{ key: "channels.telegram.groupPolicy", section: "behavior" },],diff --git a/nanobot/channels/telegram/webui/locales/en.json b/nanobot/channels/telegram/webui/locales/en.jsonindex 94c5a1bfd..ccdbc22c8 100644--- a/nanobot/channels/telegram/webui/locales/en.json+++ b/nanobot/channels/telegram/webui/locales/en.json@@ -7,9 +7,8 @@"label": "Bot token","placeholder": "123456:ABC..."},- "proxy": {- "label": "Network proxy",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Use proxy"},"allowFrom": {"label": "Allowed users",diff --git a/nanobot/channels/telegram/webui/locales/es.json b/nanobot/channels/telegram/webui/locales/es.jsonindex 3cfe2696d..d9bf2b202 100644--- a/nanobot/channels/telegram/webui/locales/es.json+++ b/nanobot/channels/telegram/webui/locales/es.json@@ -7,9 +7,8 @@"label": "Token del bot","placeholder": "123456:ABC..."},- "proxy": {- "label": "Proxy de red",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"},"allowFrom": {"label": "Usuarios permitidos",diff --git a/nanobot/channels/telegram/webui/locales/fr.json b/nanobot/channels/telegram/webui/locales/fr.jsonindex e3b2dc444..9c5b57e82 100644--- a/nanobot/channels/telegram/webui/locales/fr.json+++ b/nanobot/channels/telegram/webui/locales/fr.json@@ -7,9 +7,8 @@"label": "Jeton du bot","placeholder": "123456:ABC..."},- "proxy": {- "label": "Proxy réseau",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Utiliser le proxy"},"allowFrom": {"label": "Utilisateurs autorisés",diff --git a/nanobot/channels/telegram/webui/locales/id.json b/nanobot/channels/telegram/webui/locales/id.jsonindex b5035786a..c13ce46e5 100644--- a/nanobot/channels/telegram/webui/locales/id.json+++ b/nanobot/channels/telegram/webui/locales/id.json@@ -7,9 +7,8 @@"label": "Token bot","placeholder": "123456:ABC..."},- "proxy": {- "label": "Proxy jaringan",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Gunakan proxy"},"allowFrom": {"label": "Pengguna diizinkan",diff --git a/nanobot/channels/telegram/webui/locales/ja.json b/nanobot/channels/telegram/webui/locales/ja.jsonindex 680aeea9a..93a737bfa 100644--- a/nanobot/channels/telegram/webui/locales/ja.json+++ b/nanobot/channels/telegram/webui/locales/ja.json@@ -7,9 +7,8 @@"label": "ボットトークン","placeholder": "123456:ABC..."},- "proxy": {- "label": "ネットワークプロキシ",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "プロキシを使う"},"allowFrom": {"label": "許可ユーザー",diff --git a/nanobot/channels/telegram/webui/locales/ko.json b/nanobot/channels/telegram/webui/locales/ko.jsonindex 58be87ad3..6f038bf9e 100644--- a/nanobot/channels/telegram/webui/locales/ko.json+++ b/nanobot/channels/telegram/webui/locales/ko.json@@ -7,9 +7,8 @@"label": "봇 토큰","placeholder": "123456:ABC..."},- "proxy": {- "label": "네트워크 프록시",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "프록시 사용"},"allowFrom": {"label": "허용 사용자",diff --git a/nanobot/channels/telegram/webui/locales/pt-BR.json b/nanobot/channels/telegram/webui/locales/pt-BR.jsonindex 507d8feed..6ba31a284 100644--- a/nanobot/channels/telegram/webui/locales/pt-BR.json+++ b/nanobot/channels/telegram/webui/locales/pt-BR.json@@ -7,9 +7,8 @@"label": "Token do bot","placeholder": "123456:ABC..."},- "proxy": {- "label": "Proxy de rede",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"},"allowFrom": {"label": "Usuários permitidos",diff --git a/nanobot/channels/telegram/webui/locales/vi.json b/nanobot/channels/telegram/webui/locales/vi.jsonindex 363cd5f2a..c89d1956a 100644--- a/nanobot/channels/telegram/webui/locales/vi.json+++ b/nanobot/channels/telegram/webui/locales/vi.json@@ -7,9 +7,8 @@"label": "Token bot","placeholder": "123456:ABC..."},- "proxy": {- "label": "Proxy mạng",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Dùng proxy"},"allowFrom": {"label": "Người dùng được phép",diff --git a/nanobot/channels/telegram/webui/locales/zh-CN.json b/nanobot/channels/telegram/webui/locales/zh-CN.jsonindex 82bb493cc..134073362 100644--- a/nanobot/channels/telegram/webui/locales/zh-CN.json+++ b/nanobot/channels/telegram/webui/locales/zh-CN.json@@ -7,9 +7,8 @@"label": "机器人令牌","placeholder": "123456:ABC..."},- "proxy": {- "label": "网络代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"},"allowFrom": {"label": "允许用户",diff --git a/nanobot/channels/telegram/webui/locales/zh-TW.json b/nanobot/channels/telegram/webui/locales/zh-TW.jsonindex bbd563978..77b6a2fd3 100644--- a/nanobot/channels/telegram/webui/locales/zh-TW.json+++ b/nanobot/channels/telegram/webui/locales/zh-TW.json@@ -7,9 +7,8 @@"label": "機器人權杖","placeholder": "123456:ABC..."},- "proxy": {- "label": "網路代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"},"allowFrom": {"label": "允許使用者",diff --git a/nanobot/channels/tests/__init__.py b/nanobot/channels/tests/__init__.pynew file mode 100644index 000000000..8920956f5--- /dev/null+++ b/nanobot/channels/tests/__init__.py@@ -0,0 +1 @@+"""Cross-channel Python tests."""diff --git a/nanobot/channels/tests/test_network_proxy.py b/nanobot/channels/tests/test_network_proxy.pynew file mode 100644index 000000000..83c526020--- /dev/null+++ b/nanobot/channels/tests/test_network_proxy.py@@ -0,0 +1,159 @@+"""Shared proxy ownership at channel construction and setup boundaries."""++from __future__ import annotations++import importlib+import sys+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from nanobot.bus.queue import MessageBus+from nanobot.channels.contracts import ChannelValidationContext+from nanobot.channels.manager import ChannelManager+from nanobot.channels.registry import load_channel_plugin+from nanobot.channels.whatsapp.runtime import WhatsAppChannel+from nanobot.config.network import NetworkConfig+from nanobot.config.schema import Config++_CHANNEL_VALUES = {+ "telegram": {"token": "123456:abcdefghijklmnopqrstuvwxyz"},+ "discord": {"token": "discord-token"},+ "slack": {"appToken": "xapp-test", "botToken": "xoxb-test"},+ "matrix": {+ "homeserver": "https://matrix.example",+ "userId": "@bot:matrix.example",+ "password": "matrix-password",+ },+ "whatsapp": {"enabled": True},+}++[email protected]("name", _CHANNEL_VALUES)+def test_setup_refuses_proxy_opt_in_without_shared_address(name, monkeypatch) -> None:+ def fail_client(*_args, **_kwargs):+ pytest.fail("missing shared proxy must not fall back to a direct connection")++ monkeypatch.setattr("httpx.Client", fail_client)+ validator = load_channel_plugin(name).setup.validator++ result = validator(+ {**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(),+ )++ assert result["status"] == "invalid"+ assert result["can_enable"] is False+ proxy_check = next(check for check in result["checks"] if check["id"] == "network_proxy")+ assert proxy_check["status"] == "fail"+ assert "Advanced" in proxy_check["message"]+++ ("name", "request_method", "response"),+ [+ ("telegram", "_get_me", {"ok": True, "result": {"id": 42}}),+ ("discord", "http_get", {"id": "42", "username": "bot"}),+ ("slack", "http_post", {"ok": True, "user_id": "U42"}),+ ],+)[email protected]("use_proxy", [True, False, "false"])+def test_identity_validation_respects_shared_proxy_opt_in(+ name, request_method, response, use_proxy, monkeypatch,+) -> None:+ module = importlib.import_module(f"nanobot.channels.{name}.validation")+ proxies = []++ def request(_target, proxy=None, **_kwargs):+ proxies.append(proxy)+ return response++ monkeypatch.setattr(module, request_method, request)+ network = NetworkConfig(proxy="http://user:[email protected]:7890")++ result = module.validate(+ {**_CHANNEL_VALUES[name], "useProxy": use_proxy},+ ChannelValidationContext(network=network),+ )++ assert result["status"] == "connected"+ assert proxies == [network.proxy if use_proxy is True else None]+ assert network.proxy not in str(result)++[email protected]("name", _CHANNEL_VALUES)+def test_runtime_refuses_proxy_opt_in_without_shared_address(name) -> None:+ pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)+ channel_cls = load_channel_plugin(name).load_channel_class()++ with pytest.raises(ValueError, match="Advanced"):+ channel_cls({"useProxy": True}, MessageBus(), network=NetworkConfig())++[email protected]("name", _CHANNEL_VALUES)[email protected]("use_proxy", [True, False])+def test_manager_constructs_proxy_capable_builtin_from_descriptor(+ name, use_proxy, monkeypatch, tmp_path,+) -> None:+ pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)+ plugin = load_channel_plugin(name)+ monkeypatch.setattr("nanobot.channels.registry.discover_plugins", lambda: {name: plugin})+ monkeypatch.setattr("nanobot.optional_features.extra_installed", lambda *_args: True)+ config = Config.model_validate({+ "network": {"proxy": "http://127.0.0.1:7890"},+ "channels": {+ name: {**_CHANNEL_VALUES[name], "enabled": True, "useProxy": use_proxy},+ },+ })++ manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")++ channel = manager.channels[name]+ assert isinstance(channel, plugin.load_channel_class())+ assert channel.uses_shared_proxy is True+ assert channel.network is config.network+ assert channel._proxy == (config.network.proxy if use_proxy else None)+++async def test_manager_keeps_shared_proxy_instance_scoped(monkeypatch) -> None:+ class ProxySettings:+ def __init__(self, *, proxy_address: str) -> None:+ self.proxy_address = proxy_address++ monkeypatch.setitem(sys.modules, "neonize._binder", SimpleNamespace(ProxySettings=ProxySettings))+ channels = []+ for address in ("http://127.0.0.1:7890", "http://127.0.0.1:7891"):+ manager = object.__new__(ChannelManager)+ manager.config = Config(network=NetworkConfig(proxy=address))+ manager.bus = MessageBus()+ channel = manager._build_channel("whatsapp", WhatsAppChannel, {"useProxy": True})+ assert channel.network is manager.config.network+ channels.append(channel)++ for channel, address in zip(channels, ("http://127.0.0.1:7890", "http://127.0.0.1:7891")):+ client = SimpleNamespace(connect=AsyncMock())+ await channel._connect_client(client)+ assert client.connect.await_args.args[0].proxy_address == address+ assert channel.config.model_dump(by_alias=True)["useProxy"] is True+ assert "proxy" not in channel.config.model_dump(by_alias=True)++[email protected](("name", "request_method"), [("discord", "http_get"), ("slack", "http_post")])+def test_identity_validation_does_not_expose_shared_proxy_in_errors(name, request_method, monkeypatch) -> None:+ module = importlib.import_module(f"nanobot.channels.{name}.validation")+ network = NetworkConfig(proxy="http://user:[email protected]:7890")++ def fail_request(*_args, **_kwargs):+ raise OSError(f"could not connect through {network.proxy}")++ monkeypatch.setattr(module, request_method, fail_request)+ result = module.validate(+ {**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(network=network),+ )++ assert result["status"] == "configured"+ assert result["can_enable"] is True+ assert any(check["status"] == "warn" for check in result["checks"])+ assert network.proxy not in str(result)+ assert "user:pass" not in str(result)diff --git a/nanobot/channels/validation.py b/nanobot/channels/validation.pyindex 4432ffdee..960acd1ec 100644--- a/nanobot/channels/validation.py+++ b/nanobot/channels/validation.py@@ -74,6 +74,7 @@ def validate_channel_config(if setup_spec is not None and setup_spec.validator is not None:context = ChannelValidationContext(allow_local_service_access=config.tools.webui_allow_local_service_access,+ network=config.network,)custom_payload = setup_spec.validator(values, context)if cast(object, custom_payload) is not None:@@ -321,6 +322,11 @@ def _enabled(values: dict[str, Any]) -> bool:return _truthy(values.get("enabled"))+def resolve_proxy(values: dict[str, Any], context: ChannelValidationContext) -> str | None:+ """Resolve a channel's opt-in against the host's shared network settings."""+ return context.network.resolve_proxy(_truthy(channel_field_value(values, "useProxy")))++def _label(field: str) -> str:words = re.sub(r"([a-z])([A-Z])", r"\1 \2", field).replace(".", " ").replace("_", " ")return words[:1].upper() + words[1:]@@ -424,6 +430,7 @@ __all__ = ["payload","probe_tcp","required_checks",+ "resolve_proxy","status_from_checks","string_value","truthy",diff --git a/nanobot/channels/whatsapp/connect.py b/nanobot/channels/whatsapp/connect.pyindex 0b3768339..047121042 100644--- a/nanobot/channels/whatsapp/connect.py+++ b/nanobot/channels/whatsapp/connect.py@@ -331,14 +331,15 @@ class WhatsAppConnectStore:from nanobot.bus.queue import MessageBusfrom nanobot.channels.whatsapp.runtime import WhatsAppChannel- section = getattr(load_config().channels, "whatsapp", None)+ root_config = load_config()+ section = getattr(root_config.channels, "whatsapp", None)if section is not None and hasattr(section, "model_dump"):config = section.model_dump(mode="json", by_alias=True)elif isinstance(section, dict):config = dict(cast(dict[str, Any], section))else:config = {}- channel = WhatsAppChannel(config, MessageBus())+ channel = WhatsAppChannel(config, MessageBus(), network=root_config.network)return channel, channel.connect_database_path()@staticmethoddiff --git a/nanobot/channels/whatsapp/manifest.py b/nanobot/channels/whatsapp/manifest.pyindex 7e7f9716a..3e6df63d1 100644--- a/nanobot/channels/whatsapp/manifest.py+++ b/nanobot/channels/whatsapp/manifest.py@@ -8,7 +8,7 @@ from nanobot.channels.whatsapp.validation import validateSETUP_SPEC = ChannelSetupSpec(fields={- "proxy": field(),+ "useProxy": field("bool", default=False),"allowFrom": field("list", snapshot=False),"groupPolicy": field("enum",diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.pyindex 71df1e5b5..4ea575600 100644--- a/nanobot/channels/whatsapp/runtime.py+++ b/nanobot/channels/whatsapp/runtime.py@@ -22,6 +22,7 @@ from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dir, get_runtime_subdirfrom nanobot.config_base import Basefrom nanobot.events import ContextCompactionEvent@@ -35,7 +36,7 @@ class WhatsAppConfig(Base):allow_from: list[str] = Field(default_factory=list)group_policy: Literal["open", "mention"] = "open"database_path: str = ""- proxy: str = ""+ use_proxy: bool = Falselid_mappings: dict[str, str] = Field(default_factory=dict)@@ -299,19 +300,24 @@ class WhatsAppChannel(BaseChannel):name = "whatsapp"display_name = "WhatsApp"+ uses_shared_proxy = True@classmethoddef default_config(cls) -> dict[str, Any]:return WhatsAppConfig().model_dump(by_alias=True)- def __init__(self, config: Any, bus: MessageBus):+ def __init__(+ self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,+ ):legacy_bridge_fields = (_legacy_bridge_config_fields(cast(dict[str, Any], config))if isinstance(config, dict) else [])if isinstance(config, dict):config = WhatsAppConfig.model_validate(config)- super().__init__(config, bus)+ super().__init__(config, bus, network=network)+ self.config: WhatsAppConfig = config+ self._proxy = self.network.resolve_proxy(self.config.use_proxy)if legacy_bridge_fields:self.logger.warning("Ignoring deprecated WhatsApp bridge config fields: {}. "@@ -348,11 +354,9 @@ class WhatsAppChannel(BaseChannel):return api.NewAClient(str(db_path))async def _connect_client(self, client: Any) -> Any:- proxy = self.config.proxy.strip()+ proxy = self._proxyif not proxy:return await client.connect()- if "://" not in proxy:- proxy = f"http://{proxy}"from neonize._binder import ProxySettingsreturn await client.connect(ProxySettings(proxy_address=proxy))@@ -513,8 +517,12 @@ class WhatsAppChannel(BaseChannel):async def _fetch_remote_media(self, url: str) -> bytes:timeout = httpx.Timeout(_REMOTE_MEDIA_TIMEOUT_SECONDS, connect=10.0)+ transport = (+ PinnedDNSAsyncTransport(inner=httpx.AsyncHTTPTransport(proxy=self._proxy))+ if self._proxy else PinnedDNSAsyncTransport()+ )async with httpx.AsyncClient(- transport=PinnedDNSAsyncTransport(),+ transport=transport,follow_redirects=True,max_redirects=_REMOTE_MEDIA_MAX_REDIRECTS,timeout=timeout,diff --git a/nanobot/channels/whatsapp/tests/test_connect.py b/nanobot/channels/whatsapp/tests/test_connect.pyindex 7fd889cf8..7a3559c79 100644--- a/nanobot/channels/whatsapp/tests/test_connect.py+++ b/nanobot/channels/whatsapp/tests/test_connect.py@@ -10,6 +10,7 @@ from typing import Anyimport pytestfrom nanobot.channels.whatsapp.connect import WhatsAppConnectStore+from nanobot.config.schema import Configclass _FakeClient:@@ -359,3 +360,18 @@ async def test_cancel_during_finalize_does_not_promote_login_database(assert target.read_bytes() == b"working-session"assert not Path(channel.config.database_path).exists()assert store.has_pending_work is False+++def test_connect_builds_channel_with_shared_network_settings(monkeypatch, tmp_path) -> None:+ database = tmp_path / "neonize.db"+ config = Config.model_validate({+ "network": {"proxy": "http://127.0.0.1:7890"},+ "channels": {"whatsapp": {"useProxy": True, "databasePath": str(database)}},+ })+ monkeypatch.setattr("nanobot.channels.whatsapp.connect.load_config", lambda: config)++ channel, target = WhatsAppConnectStore._build_channel()++ assert channel.network is config.network+ assert channel.config.use_proxy is True+ assert target == databasediff --git a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.pyindex b66530762..5ab946cca 100644--- a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py+++ b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py@@ -18,6 +18,7 @@ from nanobot.channels.whatsapp.runtime import (_legacy_bridge_config_fields,_NeonizeAPI,)+from nanobot.config.network import NetworkConfigclass _Proto:@@ -139,7 +140,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->"neonize._binder",SimpleNamespace(ProxySettings=ProxySettings),)- channel = _make_channel({"proxy": "127.0.0.1:23458"})+ channel = WhatsAppChannel(+ {"useProxy": True}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),+ )client = SimpleNamespace(connect=AsyncMock(return_value=None))await channel._connect_client(client)@@ -150,7 +153,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->@pytest.mark.asyncioasync def test_connect_client_without_proxy_uses_default_connection() -> None:- channel = _make_channel({"proxy": ""})+ channel = WhatsAppChannel(+ {"useProxy": False}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),+ )client = SimpleNamespace(connect=AsyncMock(return_value=None))await channel._connect_client(client)@@ -828,3 +833,32 @@ def test_reset_database_removes_sqlite_sidecars(tmp_path) -> None:assert not db.exists()assert not wal.exists()assert not shm.exists()+++async def test_remote_media_uses_shared_proxy_without_bypassing_url_guard(monkeypatch) -> None:+ network = NetworkConfig(proxy="http://user:[email protected]:7890")+ proxies = []+ requests = []++ def handler(request):+ requests.append(request)+ return httpx.Response(200, content=b"remote media")++ def proxy_transport(*, proxy):+ proxies.append(proxy)+ return httpx.MockTransport(handler)++ monkeypatch.setattr(whatsapp_module.httpx, "AsyncHTTPTransport", proxy_transport)+ channel = WhatsAppChannel({"useProxy": True}, MessageBus(), network=network)++ with pytest.raises(httpx.RequestError, match="private/internal"):+ await channel._fetch_remote_media("http://127.0.0.1/media.wav")++ assert proxies == [network.proxy]+ assert requests == []++ public_url = "https://93.184.216.34/media.wav"+ assert await channel._fetch_remote_media(public_url) == b"remote media"+ assert proxies == [network.proxy, network.proxy]+ assert [str(request.url) for request in requests] == [public_url]diff --git a/nanobot/channels/whatsapp/validation.py b/nanobot/channels/whatsapp/validation.pyindex 13c82c9e4..cd218d818 100644--- a/nanobot/channels/whatsapp/validation.py+++ b/nanobot/channels/whatsapp/validation.py@@ -3,11 +3,23 @@from typing import Anyfrom nanobot.channels.contracts import ChannelValidationContext-from nanobot.channels.validation import check, enabled, official_action, payload, string_value+from nanobot.channels.validation import (+ check,+ enabled,+ official_action,+ payload,+ resolve_proxy,+ string_value,+)-def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:+def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:checks: list[dict[str, Any]] = []+ try:+ resolve_proxy(values, context)+ except ValueError as exc:+ checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))+ return payload("whatsapp", "invalid", checks, can_enable=False)if enabled(values) or string_value(values.get("databasePath")):checks.append(check("local_state", "Local login state", "pass", "Saved local login state was detected.")diff --git a/nanobot/channels/whatsapp/webui/index.tsx b/nanobot/channels/whatsapp/webui/index.tsxindex d22761c13..d965f4255 100644--- a/nanobot/channels/whatsapp/webui/index.tsx+++ b/nanobot/channels/whatsapp/webui/index.tsx@@ -16,7 +16,7 @@ export default {mode: "connect",docsUrl: chatAppGuideUrl("whatsapp"),manualFields: [- { key: "channels.whatsapp.proxy", section: "connection" },+ { key: "channels.whatsapp.useProxy", section: "connection", control: "switch" },{ key: "channels.whatsapp.allowFrom", section: "access" },{ key: "channels.whatsapp.groupPolicy", section: "behavior" },],diff --git a/nanobot/channels/whatsapp/webui/locales/en.json b/nanobot/channels/whatsapp/webui/locales/en.jsonindex 93c96caa0..ce197e236 100644--- a/nanobot/channels/whatsapp/webui/locales/en.json+++ b/nanobot/channels/whatsapp/webui/locales/en.json@@ -16,9 +16,8 @@"allowlist": "Allowlist"}},- "proxy": {- "label": "Network proxy",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Use proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/es.json b/nanobot/channels/whatsapp/webui/locales/es.jsonindex 25e2b29a0..6f5bdeab3 100644--- a/nanobot/channels/whatsapp/webui/locales/es.json+++ b/nanobot/channels/whatsapp/webui/locales/es.json@@ -16,9 +16,8 @@"allowlist": "Lista de permitidos"}},- "proxy": {- "label": "Proxy de red",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/fr.json b/nanobot/channels/whatsapp/webui/locales/fr.jsonindex 4b79eeadd..1000648cd 100644--- a/nanobot/channels/whatsapp/webui/locales/fr.json+++ b/nanobot/channels/whatsapp/webui/locales/fr.json@@ -16,9 +16,8 @@"allowlist": "Liste d’autorisation"}},- "proxy": {- "label": "Proxy réseau",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Utiliser le proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/id.json b/nanobot/channels/whatsapp/webui/locales/id.jsonindex 8b4d31161..1c34896c0 100644--- a/nanobot/channels/whatsapp/webui/locales/id.json+++ b/nanobot/channels/whatsapp/webui/locales/id.json@@ -16,9 +16,8 @@"allowlist": "Daftar izin"}},- "proxy": {- "label": "Proxy jaringan",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Gunakan proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/ja.json b/nanobot/channels/whatsapp/webui/locales/ja.jsonindex 20063f763..25473c2e6 100644--- a/nanobot/channels/whatsapp/webui/locales/ja.json+++ b/nanobot/channels/whatsapp/webui/locales/ja.json@@ -16,9 +16,8 @@"allowlist": "許可リスト"}},- "proxy": {- "label": "ネットワークプロキシ",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "プロキシを使う"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/ko.json b/nanobot/channels/whatsapp/webui/locales/ko.jsonindex ee4a1a37d..c5abbd323 100644--- a/nanobot/channels/whatsapp/webui/locales/ko.json+++ b/nanobot/channels/whatsapp/webui/locales/ko.json@@ -16,9 +16,8 @@"allowlist": "허용 목록"}},- "proxy": {- "label": "네트워크 프록시",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "프록시 사용"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/pt-BR.json b/nanobot/channels/whatsapp/webui/locales/pt-BR.jsonindex 717433e36..795365958 100644--- a/nanobot/channels/whatsapp/webui/locales/pt-BR.json+++ b/nanobot/channels/whatsapp/webui/locales/pt-BR.json@@ -16,9 +16,8 @@"allowlist": "Lista de permissão"}},- "proxy": {- "label": "Proxy de rede",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Usar proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/vi.json b/nanobot/channels/whatsapp/webui/locales/vi.jsonindex 6a2083a39..48a75edcc 100644--- a/nanobot/channels/whatsapp/webui/locales/vi.json+++ b/nanobot/channels/whatsapp/webui/locales/vi.json@@ -16,9 +16,8 @@"allowlist": "Danh sách cho phép"}},- "proxy": {- "label": "Proxy mạng",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "Dùng proxy"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/zh-CN.json b/nanobot/channels/whatsapp/webui/locales/zh-CN.jsonindex 359bb1bdf..14340f9c7 100644--- a/nanobot/channels/whatsapp/webui/locales/zh-CN.json+++ b/nanobot/channels/whatsapp/webui/locales/zh-CN.json@@ -16,9 +16,8 @@"allowlist": "白名单"}},- "proxy": {- "label": "网络代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}},diff --git a/nanobot/channels/whatsapp/webui/locales/zh-TW.json b/nanobot/channels/whatsapp/webui/locales/zh-TW.jsonindex 97a3468b7..eee65621a 100644--- a/nanobot/channels/whatsapp/webui/locales/zh-TW.json+++ b/nanobot/channels/whatsapp/webui/locales/zh-TW.json@@ -16,9 +16,8 @@"allowlist": "允許清單"}},- "proxy": {- "label": "網路代理",- "placeholder": "http://127.0.0.1:7890"+ "useProxy": {+ "label": "使用代理"}}},diff --git a/nanobot/cli/onboard.py b/nanobot/cli/onboard.pyindex 07aa7fada..2ec6ab4fa 100644--- a/nanobot/cli/onboard.py+++ b/nanobot/cli/onboard.py@@ -30,7 +30,7 @@ from nanobot.cli.models import (get_model_catalog,get_model_context_limit,)-from nanobot.config.loader import get_config_path, load_config, resolve_config_env_vars+from nanobot.config.loader import get_config_path, load_configfrom nanobot.config.schema import Config, ModelPresetConfigfrom nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE@@ -1321,7 +1321,8 @@ def _run_channel_login(console.print(f"[{_UI_ACCENT}]Starting {display_name} login...[/]")try:- channel = channel_cls(model, bus=None)+ kwargs = {"network": config.network} if channel_cls.uses_shared_proxy else {}+ channel = channel_cls(model, bus=None, **kwargs)success = asyncio.run(channel.login(force=False))except KeyboardInterrupt:console.print("\n[dim]Login cancelled.[/dim]")@@ -1601,9 +1602,7 @@ def _quick_start_requires_api_key(provider_name: str, info: _QuickStartProviderIdef _quick_start_codex_proxy(config: Config) -> str | None:"""Resolve only the Codex proxy without validating unrelated provider secrets."""- proxy_config = Config()- proxy_config.providers.openai_codex.proxy = config.providers.openai_codex.proxy- return resolve_config_env_vars(proxy_config).providers.openai_codex.proxy or None+ return config.network.resolve_proxy(config.providers.openai_codex.use_proxy)def _quick_start_oauth_login(config: Config, provider_name: str) -> bool:diff --git a/nanobot/cli/provider.py b/nanobot/cli/provider.pyindex 2a4c4d201..13e70b9db 100644--- a/nanobot/cli/provider.py+++ b/nanobot/cli/provider.py@@ -224,7 +224,8 @@ def _login_openai_codex() -> None:get_token, login_oauth_interactive = _load_openai_oauth_client()proxy = Nonetry:- proxy = resolve_config_env_vars(load_config()).providers.openai_codex.proxy or None+ config = resolve_config_env_vars(load_config())+ proxy = config.network.resolve_proxy(config.providers.openai_codex.use_proxy)except ValueError as e:console.print(f"[red]{e}[/red]")raise typer.Exit(1) from e@@ -267,7 +268,8 @@ def _login_xai_grok() -> None:from nanobot.providers.xai_oauth import get_xai_oauth_token, login_xai_oauthtry:- proxy = resolve_config_env_vars(load_config()).providers.xai_grok.proxy or None+ config = resolve_config_env_vars(load_config())+ proxy = config.network.resolve_proxy(config.providers.xai_grok.use_proxy)except ValueError as exc:console.print(f"[red]{exc}[/red]")raise typer.Exit(1) from excdiff --git a/nanobot/config/loader.py b/nanobot/config/loader.pyindex 5d6c72bf5..8f1449af0 100644--- a/nanobot/config/loader.py+++ b/nanobot/config/loader.py@@ -11,6 +11,7 @@ from pydantic_settings import SettingsErrorfrom nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issuesfrom nanobot.config.home import get_home_path+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import Configfrom nanobot.utils.file_io import write_text_atomic@@ -156,8 +157,9 @@ def save_config(config: Config, config_path: Path | None = None) -> None:settings = provider.model_dump(mode="json",by_alias=True,- include={"proxy", "extra_body"},+ include={"use_proxy", "extra_body"},exclude_none=True,+ exclude_unset=True,)if settings:data.setdefault("providers", {})[alias] = settings@@ -234,6 +236,9 @@ def resolve_env_refs(value: object) -> object:def _resolve_in_place(obj: Any) -> Any:+ if isinstance(obj, NetworkConfig):+ proxy = obj.resolve_environment()+ return obj.model_copy(update={"proxy": proxy}) if proxy != obj.proxy else objif isinstance(obj, str):new = _ENV_REF_PATTERN.sub(_env_replace, obj)return new if new != obj else objdiff --git a/nanobot/config/network.py b/nanobot/config/network.pynew file mode 100644index 000000000..9b5dc5ba5--- /dev/null+++ b/nanobot/config/network.py@@ -0,0 +1,128 @@+"""Instance-scoped outbound proxy configuration."""++import os+import re+from typing import Any, cast+from urllib.parse import quote, urlsplit++from pydantic import Field, field_validator+from pydantic_core import PydanticCustomError++from nanobot.config_base import Base++_ENV_REF_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")+++class NetworkConfig(Base):+ proxy: str | None = Field(default=None, repr=False)++ @field_validator("proxy")+ @classmethod+ def normalize_proxy(cls, value: str | None) -> str | None:+ value = value.strip() if value else ""+ if not value:+ return None+ if "://" not in value and not _ENV_REF_PATTERN.fullmatch(value):+ value = f"http://{value}"+ if "${" in value:+ return value+ try:+ parsed = urlsplit(value)+ valid = (+ parsed.scheme in {"http", "https", "socks5", "socks5h"}+ and bool(parsed.hostname)+ and parsed.port != 0+ and not parsed.query+ and not parsed.fragment+ and parsed.path in {"", "/"}+ and not any(char.isspace() for char in value)+ )+ except ValueError:+ valid = False+ if not valid:+ raise ValueError("Enter an HTTP, HTTPS or SOCKS5 proxy URL")+ return value++ def resolve_environment(self) -> str | None:+ value = self.proxy or ""+ userinfo_start = value.find("://") + 3+ userinfo_end = value.rfind("@")++ def replace(match: re.Match[str]) -> str:+ resolved = os.environ[match[1]]+ if userinfo_start <= match.start() < userinfo_end:+ if match.start() == userinfo_start and match.end() == userinfo_end:+ # Whole userinfo supplies its own delimiter and URL escapes.+ username, separator, password = resolved.partition(":")+ return f"{quote(username, safe='%')}{separator}{quote(password, safe='%')}"+ return quote(resolved, safe="")+ return resolved++ try:+ return self.normalize_proxy(_ENV_REF_PATTERN.sub(replace, value))+ except KeyError:+ raise ValueError("The shared proxy environment variable is not set") from None++ def resolve_proxy(self, enabled: bool) -> str | None:+ if not enabled:+ return None+ proxy = self.resolve_environment()+ if not proxy:+ raise ValueError("Configure the shared proxy in Advanced before enabling it")+ return proxy+++def _config_object(value: object) -> dict[str, Any] | None:+ return cast(dict[str, Any], value) if isinstance(value, dict) else None+++def migrate_legacy_proxy_config(value: Any) -> Any:+ """Consolidate legacy addresses after settings sources have been merged."""+ if not isinstance(value, dict):+ return value+ data = cast(dict[str, Any], value)+ sections: list[dict[str, Any]] = []+ providers = _config_object(data.get("providers")) or {}+ sections.extend(section for value in providers.values() if (section := _config_object(value)) is not None)+ tools = _config_object(data.get("tools")) or {}+ if (web := _config_object(tools.get("web"))) is not None:+ sections.append(web)+ channels = _config_object(data.get("channels")) or {}+ sections.extend(section for name in ("telegram", "discord", "slack", "matrix", "whatsapp") if (section := _config_object(channels.get(name))) is not None)++ network = data.get("network")+ explicit_proxy = isinstance(network, NetworkConfig) or isinstance(network, dict) and "proxy" in network+ addresses: set[str] = set()+ migrated: list[dict[str, Any]] = []+ for section in sections:+ raw = section.get("proxy")+ if isinstance(raw, str) and raw.strip():+ if not explicit_proxy:+ proxy = NetworkConfig.normalize_proxy(raw)+ assert proxy is not None+ username = section.get("proxyUsername", section.get("proxy_username"))+ password = section.get("proxyPassword", section.get("proxy_password"))+ if isinstance(username, str) and username and isinstance(password, str) and password:+ if _ENV_REF_PATTERN.fullmatch(proxy):+ raise PydanticCustomError("proxy_credential_migration", "Combine the Discord proxy URL and credentials into one full URL environment variable, or set network.proxy before upgrading.")+ scheme, host = proxy.split("://", 1)+ host = host.rsplit("@", 1)[-1]+ credentials = f"{quote(username, safe='${}')}:{quote(password, safe='${}')}"+ proxy = f"{scheme}://{credentials}@{host}"+ addresses.add(proxy)+ migrated.append(section)++ if addresses:+ if len(addresses) > 1:+ raise PydanticCustomError("proxy_address_migration", "Multiple legacy proxy addresses are no longer supported. Set network.proxy to one address before upgrading.")+ if not isinstance(network, dict):+ network = {}+ data["network"] = network+ network["proxy"] = next(iter(addresses))+ for section in sections:+ for key in ("proxy", "proxyUsername", "proxy_username", "proxyPassword", "proxy_password"):+ section.pop(key, None)+ for section in migrated:+ if "useProxy" not in section and "use_proxy" not in section:+ section["useProxy"] = True+ return datadiff --git a/nanobot/config/schema.py b/nanobot/config/schema.pyindex 1a2eaf3dc..99c62e1ab 100644--- a/nanobot/config/schema.py+++ b/nanobot/config/schema.py@@ -21,6 +21,7 @@ from nanobot.agent.tools.web_config import ()from nanobot.agent.tools.web_config import WebToolsConfigfrom nanobot.config.home import get_default_workspace+from nanobot.config.network import NetworkConfig, migrate_legacy_proxy_configfrom nanobot.config.provider_api_migration import migrate_legacy_provider_apifrom nanobot.config.timezone import detect_system_timezonefrom nanobot.config_base import Base@@ -255,7 +256,7 @@ class ProviderConfig(Base):extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)extra_body: dict[str, Any] | None = None # Extra provider request fields; shape depends on provider/API surfaceextra_query: dict[str, str] | None = None # Extra query params (e.g. api-version for Azure-style gateways)- proxy: str | None = None # Explicit HTTP proxy; image downloads trust its DNS and egress+ use_proxy: bool = Falsethinking_style: str | None = None # Thinking/reasoning style for custom providers# Valid values mirror the keys of _THINKING_STYLE_MAP in@@ -421,6 +422,7 @@ class MCPServerConfig(Base):cwd: str = "" # Stdio: working directory for MCP server runtime artifactsurl: str = "" # HTTP/SSE: endpoint URLheaders: dict[str, str] = Field(default_factory=dict) # HTTP/SSE: custom headers+ use_proxy: bool = Falsetool_timeout: int = 30 # seconds before a tool call is cancelledenabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all capabilities (tools, resources, prompts); any restriction = only listed tools, no resources/prompts@@ -505,6 +507,7 @@ class Config(BaseSettings):channels: ChannelsConfig = Field(default_factory=ChannelsConfig)transcription: TranscriptionConfig = Field(default_factory=TranscriptionConfig)providers: ProvidersConfig = Field(default_factory=ProvidersConfig)+ network: NetworkConfig = Field(default_factory=NetworkConfig)api: ApiConfig = Field(default_factory=ApiConfig)gateway: GatewayConfig = Field(default_factory=GatewayConfig)tools: ToolsConfig = Field(default_factory=ToolsConfig)@@ -514,6 +517,11 @@ class Config(BaseSettings):serialization_alias="modelPresets",)+ @model_validator(mode="before")+ @classmethod+ def _migrate_proxy_config(cls, value: Any) -> Any:+ return migrate_legacy_proxy_config(value)+@classmethoddef settings_customise_sources(cls,diff --git a/nanobot/providers/factory.py b/nanobot/providers/factory.pyindex 7f1190b91..77d991d54 100644--- a/nanobot/providers/factory.py+++ b/nanobot/providers/factory.py@@ -69,13 +69,14 @@ def _make_provider_core(p = setup.provider_configspec = setup.specbackend = setup.backend+ proxy = config.network.resolve_proxy(p.use_proxy) if p else Noneif backend == "openai_codex":from nanobot.providers.openai_codex_provider import OpenAICodexProviderprovider = OpenAICodexProvider(default_model=model,- proxy=getattr(p, "proxy", None) if p else None,+ proxy=proxy,extra_body=p.extra_body if p else None,provider_name=provider_name,)@@ -84,7 +85,7 @@ def _make_provider_core(provider = XAIGrokProvider(default_model=model,- proxy=getattr(p, "proxy", None) if p else None,+ proxy=proxy,extra_body=p.extra_body if p else None,provider_name=provider_name,)@@ -120,7 +121,7 @@ def _make_provider_core(extra_headers=_provider_extra_headers(spec, p),extra_body=p.extra_body if p else None,extra_query=p.extra_query if p else None,- proxy=p.proxy if p else None,+ proxy=proxy,spec=custom_spec,provider_name=provider_name,)@@ -148,7 +149,7 @@ def _make_provider_core(extra_body=p.extra_body if p else None,model_api=setup.model_api,extra_query=p.extra_query if p else None,- proxy=p.proxy if p else None,+ proxy=proxy,provider_name=provider_name,)@@ -261,7 +262,7 @@ def _preset_provider_signature(preset.reasoning_effort,preset.context_window_tokens,preset.api.model_dump_json() if preset.api is not None else None,- getattr(provider_config, "proxy", None) if provider_config else None,+ config.network.resolve_proxy(provider_config.use_proxy) if provider_config else None,provider_config.thinking_style if provider_config else None,)diff --git a/nanobot/providers/routing.py b/nanobot/providers/routing.pyindex c9540a31b..c1802ab9e 100644--- a/nanobot/providers/routing.py+++ b/nanobot/providers/routing.py@@ -123,14 +123,17 @@ def resolve_provider_route(provider_config = apply_request_overrides(provider_config, preset)if (provider_config- and provider_config.proxy+ and provider_config.use_proxyand backend not in {"openai_compat", "openai_codex", "xai_grok", "anthropic"}):raise ValueError(- f"providers.{provider_name}.proxy is only supported for "+ f"providers.{provider_name}.use_proxy is only supported for ""OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI Grok.")+ if provider_config:+ config.network.resolve_proxy(provider_config.use_proxy)+if backend == "azure_openai":if not provider_config or not provider_config.api_base:raise ValueError("Azure OpenAI requires api_base in config.")@@ -177,7 +180,7 @@ def resolve_automatic_model_api(from nanobot.providers.github_copilot_provider import cached_github_copilot_model_apiapi = cached_github_copilot_model_api(- setup.model, provider_config.proxy if provider_config else None,+ setup.model, config.network.resolve_proxy(provider_config.use_proxy) if provider_config else None,)if api is not None:return setup.provider_name, api.preferred_apidiff --git a/nanobot/webui/mcp_oauth_api.py b/nanobot/webui/mcp_oauth_api.pyindex a4c54b759..a34821850 100644--- a/nanobot/webui/mcp_oauth_api.py+++ b/nanobot/webui/mcp_oauth_api.py@@ -15,6 +15,7 @@ from urllib.parse import SplitResult, parse_qs, urlsplit, urlunsplitfrom nanobot.agent.tools.mcp import MCPConnection, connect_mcp_serversfrom nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH, MCPOAuthHandlersfrom nanobot.agent.tools.registry import ToolRegistry+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import MCPServerConfigfrom nanobot.runtime_admission import RuntimeAdmissionfrom nanobot.security.network import validate_url_target@@ -44,6 +45,7 @@ class _McpOAuthFlow:flow_id: strname: strcfg: MCPServerConfig+ network: NetworkConfigredirect_uri: strmanual_callback: boolexpires_at: float@@ -139,6 +141,7 @@ class McpOAuthManager:redirect_uri: str,*,reload_mcp: McpReload,+ network: NetworkConfig | None = None,reset_credentials: bool = False,) -> dict[str, Any]:self._admission.check()@@ -156,7 +159,8 @@ class McpOAuthManager:flow = _McpOAuthFlow(flow_id=secrets.token_urlsafe(24),name=name,- cfg=cfg,+ cfg=cfg.model_copy(deep=True),+ network=(network or NetworkConfig()).model_copy(deep=True),redirect_uri=redirect_uri,manual_callback=manual_callback,expires_at=now + _FLOW_TTL_S,@@ -348,6 +352,7 @@ class McpOAuthManager:{flow.name: flow.cfg},ToolRegistry(),oauth_handlers={flow.name: handlers},+ network=flow.network,)if flow.name not in connections:await self._close_connections(connections)diff --git a/nanobot/webui/mcp_presets_api.py b/nanobot/webui/mcp_presets_api.pyindex 8d9254b84..dd5fd76a3 100644--- a/nanobot/webui/mcp_presets_api.py+++ b/nanobot/webui/mcp_presets_api.py@@ -27,6 +27,7 @@ from nanobot.agent.tools.mcp_oauth import (from nanobot.agent.tools.registry import ToolRegistryfrom nanobot.apps.protocol import app_manifest, compact_dictfrom nanobot.config.loader import load_config, resolve_config_env_vars, save_config+from nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_runtime_subdirfrom nanobot.config.schema import MCPServerConfigfrom nanobot.utils.helpers import ensure_dir@@ -290,6 +291,24 @@ def _resolve_field_value(return None+def _proxy_enabled(query: QueryParams, current: bool = False) -> bool:+ raw = _query_first(query, "use_proxy")+ if raw is None:+ return current+ if raw.lower() not in {"true", "false"}:+ raise McpPresetError("use_proxy must be true or false")+ return raw.lower() == "true"+++def _validate_proxy(cfg: MCPServerConfig, network: NetworkConfig) -> None:+ if cfg.use_proxy and (cfg.command or not cfg.url):+ raise McpPresetError("The shared proxy is available for HTTP and SSE MCP connections")+ try:+ network.resolve_proxy(cfg.use_proxy)+ except ValueError as exc:+ raise McpPresetError(str(exc)) from None++def _materialize_server(preset: McpPreset,query: QueryParams,@@ -299,6 +318,7 @@ def _materialize_server(raise McpPresetError(f"{preset.display_name} is not supported yet", status=409)cfg = _clone_server(existing or preset.server)+ cfg.use_proxy = _proxy_enabled(query, cfg.use_proxy)for field_spec in preset.fields:value = _resolve_field_value(field_spec, query, existing)if field_spec.required and not value:@@ -479,6 +499,7 @@ def _preset_payload(preset: McpPreset, configured_servers: dict[str, MCPServerCo"docs_url": preset.docs_url,"transport": preset.transport,"auth": (cfg.auth if cfg is not None else (preset.server.auth if preset.server else None)),+ "use_proxy": cfg.use_proxy if cfg is not None else False,"requires": preset.requires,"note": preset.note,"install_supported": preset.install_supported,@@ -518,6 +539,7 @@ def _custom_payload("docs_url": "","transport": transport,"auth": cfg.auth,+ "use_proxy": cfg.use_proxy,"requires": "","note": "","install_supported": True,@@ -587,6 +609,7 @@ def mcp_presets_payload(]payload: dict[str, Any] = {"presets": [*preset_rows, *custom_rows, *plugin_rows],+ "proxy_configured": bool(config.network.proxy),"installed_count": len(config.tools.mcp_servers)+ sum(int(row["enabled"]) for row in plugin_rows),}@@ -783,7 +806,7 @@ async def mcp_presets_test_action(inspection_cfg = cfg.model_copy(update={"enabled_tools": ["*"]})try:stacks = await asyncio.wait_for(- connect_mcp_servers({name: inspection_cfg}, registry),+ connect_mcp_servers({name: inspection_cfg}, registry, network=config.network),timeout=_test_timeout(cfg),)tool_prefix = f"mcp_{name}_"@@ -975,6 +998,7 @@ def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig]cwd=(_query_first(query, "cwd") or "").strip() if transport == "stdio" else "",url=url if transport in {"sse", "streamableHttp"} else "",headers=headers,+ use_proxy=_proxy_enabled(query),tool_timeout=tool_timeout,enabled_tools=_parse_enabled_tools(_query_first(query, "enabled_tools")),)@@ -1020,6 +1044,9 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]:if not all(isinstance(k, str) and isinstance(v, str) for k, v in headers.items()):raise McpPresetError(f"MCP server '{server_name}' headers must be a string object")typed_headers = cast(dict[str, str], headers)+ use_proxy = server.get("useProxy", server.get("use_proxy", False))+ if not isinstance(use_proxy, bool):+ raise McpPresetError(f"MCP server '{server_name}' useProxy must be a boolean")auth = _normalize_auth(server.get("auth"),transport=transport,@@ -1041,6 +1068,7 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]:cwd=cwd if transport == "stdio" else "",url=url if transport in {"sse", "streamableHttp"} else "",headers=typed_headers,+ use_proxy=use_proxy,tool_timeout=timeout_int,enabled_tools=cast(list[str], enabled_tools_value),)@@ -1083,6 +1111,7 @@ def custom_mcp_action(config = load_config(config_path) if config_path is not None else load_config()if action == "custom":name, cfg = _custom_server_from_query(query)+ _validate_proxy(cfg, config.network)delete_credentials = _oauth_credentials_replaced(config.tools.mcp_servers.get(name), cfg)config.tools.mcp_servers[name] = cfgsave_config(config, config_path)@@ -1097,6 +1126,8 @@ def custom_mcp_action(if action in {"import", "import-cursor"}:servers = _import_mcp_servers(_query_first(query, "config"))+ for cfg in servers.values():+ _validate_proxy(cfg, config.network)delete_credentials = [namefor name, cfg in servers.items()@@ -1138,7 +1169,7 @@ def ensure_mcp_oauth_server(query: QueryParams,*,config_path: Path | None = None,-) -> tuple[str, MCPServerConfig]:+) -> tuple[str, MCPServerConfig, NetworkConfig]:"""Materialize an OAuth preset on first click and return its saved config."""name = _validated_server_name((_query_first(query, "name") or "").strip())config = load_config(config_path) if config_path is not None else load_config()@@ -1153,11 +1184,14 @@ def ensure_mcp_oauth_server(if preset.server is None or preset.server.auth != "oauth":raise McpPresetError("MCP server does not support browser authorization", status=409)cfg = _materialize_server(preset, query, cfg)- config.tools.mcp_servers[name] = cfg- save_config(config, config_path)+ cfg = _clone_server(cfg)+ cfg.use_proxy = _proxy_enabled(query, cfg.use_proxy)+ _validate_proxy(cfg, config.network)if cfg.auth != "oauth" or cfg.type not in {"sse", "streamableHttp"} or not cfg.url:raise McpPresetError("MCP server is not configured for OAuth", status=409)- return name, cfg+ config.tools.mcp_servers[name] = cfg+ save_config(config, config_path)+ return name, cfg, config.networkdef mcp_presets_action(@@ -1174,10 +1208,27 @@ def mcp_presets_action(config = load_config(config_path) if config_path is not None else load_config()existing = config.tools.mcp_servers.get(name)+ if action == "proxy":+ if existing is None:+ if preset is None:+ raise McpPresetError("unknown MCP server", status=404)+ cfg = _materialize_server(preset, query, None)+ else:+ cfg = _clone_server(existing)+ cfg.use_proxy = _proxy_enabled(query, cfg.use_proxy)+ _validate_proxy(cfg, config.network)+ config.tools.mcp_servers[name] = cfg+ save_config(config, config_path)+ payload = mcp_presets_payload(config_path=config_path)+ payload["requires_restart"] = True+ return payload+if action == "enable":if preset is None:raise McpPresetError("unknown MCP preset", status=404)- config.tools.mcp_servers[preset.name] = _materialize_server(preset, query, existing)+ cfg = _materialize_server(preset, query, existing)+ _validate_proxy(cfg, config.network)+ config.tools.mcp_servers[preset.name] = cfgsave_config(config, config_path)payload = mcp_presets_payload(last_action=_action_message(action, preset),diff --git a/nanobot/webui/settings_capabilities.py b/nanobot/webui/settings_capabilities.pyindex 064af3a9a..82dab832d 100644--- a/nanobot/webui/settings_capabilities.py+++ b/nanobot/webui/settings_capabilities.py@@ -186,7 +186,7 @@ def capability_settings_payload(},"web": {"enable": config.tools.web.enable,- "proxy": config.tools.web.proxy,+ "use_proxy": config.tools.web.use_proxy,"user_agent": config.tools.web.user_agent,"search": {"max_results": search_config.max_results,diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.pyindex 1f1252ab8..68c30732a 100644--- a/nanobot/webui/settings_models.py+++ b/nanobot/webui/settings_models.py@@ -135,7 +135,6 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:string_fields = (("api_key", "apiKey"),("api_base", "apiBase"),- ("proxy", "proxy"),("thinking_style", "thinkingStyle"),("region", "region"),("profile", "profile"),@@ -146,6 +145,9 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:value = (query_first_alias(query, snake, camel) or "").strip()updates[snake] = value or None+ if query_has_alias(query, "use_proxy", "useProxy"):+ updates["use_proxy"] = parse_bool(query_first_alias(query, "use_proxy", "useProxy") or "", "use_proxy")+for snake, camel in (("extra_headers", "extraHeaders"),("extra_body", "extraBody"),@@ -348,9 +350,9 @@ def _provider_advanced_field_names(name: str, spec: Any) -> list[str]:if spec.backend in {"openai_compat", "anthropic", "bedrock", "openai_codex", "xai_grok"}:fields.append("extra_body")if spec.backend in {"openai_compat", "anthropic"}:- fields.extend(("extra_query", "proxy"))- if spec.name in _OAUTH_PROXY_PROVIDERS and "proxy" not in fields:- fields.append("proxy")+ fields.extend(("extra_query", "use_proxy"))+ if spec.name in _OAUTH_PROXY_PROVIDERS and "use_proxy" not in fields:+ fields.append("use_proxy")if spec.backend == "bedrock":fields.extend(("region", "profile"))if find_by_name(name) is None:@@ -398,7 +400,7 @@ def _provider_settings_row("thinking_style": provider_config.thinking_style,"region": getattr(provider_config, "region", None),"profile": getattr(provider_config, "profile", None),- "proxy": provider_config.proxy,+ "use_proxy": provider_config.use_proxy,}if oauth_status is not None:row["oauth_account"] = oauth_status["account"]@@ -695,7 +697,7 @@ def provider_models_payload("model_count": len(rows),}if catalog_kind == "hybrid":- proxy = _resolve_env_placeholders(provider_config.proxy)+ proxy = config.network.resolve_proxy(provider_config.use_proxy)catalog = get_oauth_model_catalog(spec.name, proxy=proxy, refresh=query_first(query, "refresh") == "1",)@@ -758,11 +760,13 @@ def provider_models_payload(models_url = f"{api_base.rstrip('/')}/v1/models"try:+ proxy = config.network.resolve_proxy(provider_config.use_proxy)response = http_get(models_url,headers=headers,timeout=10.0,follow_redirects=False,+ **({"proxy": proxy, "trust_env": False} if proxy else {}),)response.raise_for_status()rows = _extract_model_rows(response.json(), spec=spec)@@ -1602,10 +1606,15 @@ def create_provider_settings(config: Config, query: QueryParams) -> str:if len(display_name) > 80:raise WebUISettingsError("provider name must be 80 characters or fewer")updates = _provider_config_updates(query)+ if updates.get("use_proxy"):+ try:+ config.network.resolve_proxy(True)+ except ValueError as exc:+ raise WebUISettingsError(str(exc)) from Noneallowed = {"api_key","api_base",- "proxy",+ "use_proxy","extra_headers","extra_body","extra_query",@@ -1643,6 +1652,11 @@ def update_provider_settings(raise WebUISettingsError("unknown provider")spec, provider_key, provider_config = resolved_providerupdates = _provider_config_updates(query)+ if updates.get("use_proxy"):+ try:+ config.network.resolve_proxy(True)+ except ValueError as exc:+ raise WebUISettingsError(str(exc)) from Noneif not spec.is_oauth and spec.name != "openai":updates.pop("api_type", None)try:@@ -1652,10 +1666,10 @@ def update_provider_settings(if spec.is_oauth:if spec.name not in _OAUTH_PROXY_PROVIDERS:raise WebUISettingsError("unknown provider")- unsupported = set(updates) - {"proxy", "extra_body"}+ unsupported = set(updates) - {"use_proxy", "extra_body"}if unsupported:raise WebUISettingsError(- "OAuth provider only supports proxy and extra_body settings"+ "OAuth provider only supports use_proxy and extra_body settings")else:allowed = {@@ -1730,10 +1744,8 @@ def login_oauth_provider(raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from Nonetry:- proxy = resolve_config_env_vars(- config,- config_path=config_path,- ).providers.openai_codex.proxy or None+ resolved_config = resolve_config_env_vars(config, config_path=config_path)+ proxy = resolved_config.network.resolve_proxy(resolved_config.providers.openai_codex.use_proxy)except ValueError as exc:raise WebUISettingsError(str(exc), status=400) from excremote_browser_value = query_first(query, "remote_browser")@@ -1799,10 +1811,8 @@ def login_oauth_provider(from nanobot.providers.xai_oauth import create_xai_oauth_logintry:- proxy = resolve_config_env_vars(- config,- config_path=config_path,- ).providers.xai_grok.proxy or None+ resolved_config = resolve_config_env_vars(config, config_path=config_path)+ proxy = resolved_config.network.resolve_proxy(resolved_config.providers.xai_grok.use_proxy)except ValueError as exc:raise WebUISettingsError(str(exc), status=400) from exctry:diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.pyindex b2796704f..8c1fa870f 100644--- a/nanobot/webui/settings_routes.py+++ b/nanobot/webui/settings_routes.py@@ -97,6 +97,7 @@ _MCP_PRESET_ACTIONS_BY_PATH = {"/api/settings/mcp-presets/remove": "remove","/api/settings/mcp-presets/test": "test","/api/settings/mcp-presets/reconnect": "reconnect",+ "/api/settings/mcp-presets/proxy": "proxy","/api/settings/mcp-presets/custom": "custom","/api/settings/mcp-presets/import": "import","/api/settings/mcp-presets/import-cursor": "import-cursor",@@ -653,7 +654,7 @@ class WebUISettingsRouter:return self._error_response(500, "MCP OAuth callback is not configured")query = self._parse_mcp_settings_query(request)try:- name, cfg = await asyncio.to_thread(+ name, cfg, network = await asyncio.to_thread(self.settings.mutate,ensure_mcp_oauth_server,query,@@ -665,6 +666,7 @@ class WebUISettingsRouter:cfg,redirect_uri,reload_mcp=self._reload_mcp_runtime,+ network=network,reset_credentials=reset,)except Exception as exc:diff --git a/nanobot/webui/settings_runtime.py b/nanobot/webui/settings_runtime.pyindex 398eb695a..219c8e470 100644--- a/nanobot/webui/settings_runtime.py+++ b/nanobot/webui/settings_runtime.py@@ -52,7 +52,8 @@ RUNTIME_CONFIG_PATHS = ("tools.max_session_messages_per_minute","tools.webui_allow_remote_package_install","tools.web.enable",- "tools.web.proxy",+ "network.proxy",+ "tools.web.use_proxy","tools.web.user_agent","tools.image_generation.save_dir","api.host",@@ -167,12 +168,18 @@ def update_runtime_config(re.compile(pattern)except re.error:raise WebUISettingsError(f"{path}: invalid regular expression") from None+ if values.get("tools.web.use_proxy") is True:+ try:+ validated.network.resolve_proxy(True)+ except ValueError as exc:+ raise WebUISettingsError(str(exc)) from Nonebefore = runtime_config_payload(config)after = runtime_config_payload(validated)if before == after:return Falseconfig.agents = validated.agentsconfig.tools = validated.tools+ config.network = validated.networkconfig.gateway = validated.gatewayconfig.api = validated.apireturn Truediff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 7ebd11e62..3f7311ea3 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -238,6 +238,7 @@ _WEBUI_MUTATION_PATHS = {"settings.mcp.remove": "/api/settings/mcp-presets/remove","settings.mcp.test": "/api/settings/mcp-presets/test","settings.mcp.reconnect": "/api/settings/mcp-presets/reconnect",+ "settings.mcp.proxy": "/api/settings/mcp-presets/proxy","settings.mcp.custom": "/api/settings/mcp-presets/custom","settings.mcp.import": "/api/settings/mcp-presets/import","settings.mcp.import_cursor": "/api/settings/mcp-presets/import-cursor",diff --git a/tests/agent/test_mcp_connection.py b/tests/agent/test_mcp_connection.pyindex 724e1af0c..8fc5b586f 100644--- a/tests/agent/test_mcp_connection.py+++ b/tests/agent/test_mcp_connection.py@@ -20,7 +20,8 @@ from nanobot.agent.tools.base import Toolfrom nanobot.agent.tools.mcp import MCPProvider, MCPResourceWrapper, MCPToolWrapperfrom nanobot.agent.tools.registry import ToolRegistryfrom nanobot.config.loader import load_config, save_config-from nanobot.config.schema import MCPServerConfig+from nanobot.config.network import NetworkConfig+from nanobot.config.schema import Config, MCPServerConfigdef _mcp_notification(method: str, params: dict[str, Any] | None = None) -> SessionMessage:@@ -144,7 +145,7 @@ async def test_connect_mcp_retries_when_no_servers_connect(tmp_path, monkeypatchprovider, _registry = _make_provider()attempts = 0- async def _fake_connect(_servers, _registry):+ async def _fake_connect(_servers, _registry, *, network):nonlocal attemptsattempts += 1return {}@@ -203,7 +204,7 @@ async def test_mcp_provider_closes_connections_independently_from_agent_loop(closed_tasks.append(asyncio.current_task())assert asyncio.current_task() is self.owner- async def _fake_connect(servers, _registry):+ async def _fake_connect(servers, _registry, *, network):stacks = {name: _OwnerCheckedStack() for name in servers}return stacks@@ -333,7 +334,7 @@ async def test_reload_mcp_servers_adds_and_removes_tools_without_restart(async def _mark_closed(name: str) -> None:closed.append(name)- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):stacks = {}for name in servers:registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))@@ -382,7 +383,7 @@ async def test_reload_is_a_direct_provider_operation_without_an_agent_loop(async def _mark_closed(name: str) -> None:closed.append(name)- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):stacks = {}for name in servers:registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))@@ -394,7 +395,7 @@ async def test_reload_is_a_direct_provider_operation_without_an_agent_loop(monkeypatch.setattr("nanobot.agent.tools.mcp.connect_mcp_servers", _fake_connect)registry = ToolRegistry()- provider = MCPProvider({}, registry, server_loader=lambda: configured)+ provider = MCPProvider({}, registry, server_loader=lambda: (configured, NetworkConfig()))result = await provider.reload()@@ -422,7 +423,7 @@ async def test_reload_timeout_marks_attempted_server_failed_and_allows_retry(started = asyncio.Event()attempts = 0- async def _fake_connect(servers, _registry):+ async def _fake_connect(servers, _registry, *, network):nonlocal attemptsattempts += 1if attempts == 1:@@ -436,7 +437,7 @@ async def test_reload_timeout_marks_attempted_server_failed_and_allows_retry(provider = MCPProvider({"test": server},ToolRegistry(),- server_loader=lambda: {"test": server},+ server_loader=lambda: ({"test": server}, NetworkConfig()),)reload_task = asyncio.create_task(provider.reload())@@ -469,7 +470,7 @@ async def test_reload_mcp_servers_retries_configured_server_without_live_stack()save_config(config)- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):stacks = {}for name in servers:registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))@@ -516,7 +517,7 @@ async def test_reload_mcp_servers_skips_oauth_server_waiting_for_authorization(attempted: list[str] = []- async def _fake_connect(servers, _registry):+ async def _fake_connect(servers, _registry, *, network):attempted.extend(servers)stack = AsyncExitStack()await stack.__aenter__()@@ -568,7 +569,7 @@ async def test_mcp_tool_reconnects_after_session_terminated(content=[mcp_types.TextContent(type="text", text="recovered")])- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):nonlocal connect_countstacks = {}for name in servers:@@ -626,7 +627,7 @@ async def test_mcp_reconnect_handler_uses_sanitized_server_prefix(content=[mcp_types.TextContent(type="text", text="recovered")])- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):nonlocal connect_countstacks = {}for name in servers:@@ -685,7 +686,7 @@ async def test_concurrent_mcp_reconnect_reuses_fresh_session(])- async def _fake_connect(servers, registry):+ async def _fake_connect(servers, registry, *, network):nonlocal connect_countstacks = {}for name in servers:@@ -717,3 +718,101 @@ async def test_concurrent_mcp_reconnect_reuses_fresh_session(assert outputs == ["fresh:alpha", "fresh:beta"]assert connect_count == 2assert closed == ["remote"]+++async def test_shared_proxy_snapshot_survives_reconnect_and_reloads_only_opted_in_servers(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+):+ config = Config()+ config.agents.defaults.workspace = str(tmp_path / "workspace")+ config.network.proxy = "http://proxy-a.example:8080"+ config.tools.mcp_servers = {+ "proxied": MCPServerConfig(url="https://mcp.example.com/mcp", use_proxy=True),+ "independent": MCPServerConfig(url="https://other.example.com/mcp"),+ }+ next_network = NetworkConfig(proxy="http://proxy-b.example:8080")+ attempts: list[tuple[str, str | None, str | None]] = []+ closed: list[str] = []+ sessions: dict[str, Any] = {}++ class Session:+ expired = False++ async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:+ if self.expired:+ raise McpError(ErrorData(code=-32000, message="Session terminated"))+ return SimpleNamespace(content=[mcp_types.TextContent(type="text", text="ok")])++ async def mark_closed(name: str) -> None:+ closed.append(name)++ async def connect(servers, registry, *, network):+ connections = {}+ for name, cfg in servers.items():+ attempts.append((name, network.proxy, network.resolve_proxy(cfg.use_proxy)))+ sessions[name] = Session()+ registry.register(MCPToolWrapper(sessions[name], name, SimpleNamespace(+ name="echo", description="echo", inputSchema={"type": "object"},+ )))+ stack = AsyncExitStack()+ await stack.__aenter__()+ stack.push_async_callback(mark_closed, name)+ connections[name] = stack+ return connections++ monkeypatch.setattr(mcp_runtime, "connect_mcp_servers", connect)+ registry = ToolRegistry()+ provider = MCPProvider.from_config(+ config,+ registry,+ server_loader=lambda: (config.tools.mcp_servers, next_network),+ )+ try:+ await provider.connect()+ independent_tool = registry.get("mcp_independent_echo")+ assert attempts == [+ ("proxied", "http://proxy-a.example:8080", "http://proxy-a.example:8080"),+ ("independent", "http://proxy-a.example:8080", None),+ ]++ # Mutating the caller's config must not reroute a live provider's reconnect.+ config.network.proxy = "http://not-live.example:8080"+ sessions["proxied"].expired = True+ old_tool = registry.get("mcp_proxied_echo")+ assert isinstance(old_tool, MCPToolWrapper)+ assert await old_tool.execute() == "ok"+ assert attempts[-1] == (+ "proxied", "http://proxy-a.example:8080", "http://proxy-a.example:8080"+ )++ result = await provider.reload()+ assert result["ok"] is True+ assert result["changed"] == ["proxied"]+ assert result["connected"] == ["independent", "proxied"]+ assert result["tools_removed"] == 1+ assert attempts[-1] == (+ "proxied", "http://proxy-b.example:8080", "http://proxy-b.example:8080"+ )+ assert closed == ["proxied", "proxied"]+ assert registry.get("mcp_independent_echo") is independent_tool++ # Reload also captures a copy, rather than retaining the loader's mutable model.+ next_network.proxy = "http://proxy-c.example:8080"+ sessions["proxied"].expired = True+ current_tool = registry.get("mcp_proxied_echo")+ assert isinstance(current_tool, MCPToolWrapper)+ assert await current_tool.execute() == "ok"+ assert attempts[-1] == (+ "proxied", "http://proxy-b.example:8080", "http://proxy-b.example:8080"+ )+ result = await provider.reload()+ assert result["changed"] == ["proxied"]+ assert attempts[-1] == (+ "proxied", "http://proxy-c.example:8080", "http://proxy-c.example:8080"+ )+ assert registry.get("mcp_independent_echo") is independent_tool+ assert closed == ["proxied"] * 4+ finally:+ await provider.aclose()diff --git a/tests/agent/test_onboard_logic.py b/tests/agent/test_onboard_logic.pyindex cd7d71052..7dceb801b 100644--- a/tests/agent/test_onboard_logic.py+++ b/tests/agent/test_onboard_logic.py@@ -1090,7 +1090,8 @@ class TestMainMenuInteraction:config = Config()config.providers.openai.api_key = "${UNRELATED_MISSING_KEY}"- config.providers.openai_codex.proxy = "${CODEX_PROXY}"+ config.network.proxy = "${CODEX_PROXY}"+ config.providers.openai_codex.use_proxy = Truetoken = SimpleNamespace(access="existing-token", account_id="account-123")token_proxies: list[str | None] = []login_calls: list[object] = []@@ -1113,7 +1114,8 @@ class TestMainMenuInteraction:assert token_proxies == ["http://127.0.0.1:8080"]assert login_calls == []assert config.providers.openai.api_key == "${UNRELATED_MISSING_KEY}"- assert config.providers.openai_codex.proxy == "${CODEX_PROXY}"+ assert config.network.proxy == "${CODEX_PROXY}"+ assert config.providers.openai_codex.use_proxy is Truedef test_quick_start_openai_codex_reports_incomplete_installation(self, monkeypatch):import oauth_cli_kit@@ -1139,7 +1141,8 @@ class TestMainMenuInteraction:import oauth_cli_kitconfig = Config()- config.providers.openai_codex.proxy = "http://127.0.0.1:8080"+ config.network.proxy = "http://127.0.0.1:8080"+ config.providers.openai_codex.use_proxy = Trueprompts: list[str] = []printed: list[tuple[tuple[object, ...], dict[str, object]]] = []diff --git a/tests/agent/tools/test_runtime_control.py b/tests/agent/tools/test_runtime_control.pyindex 3b82a9fbd..e7187ca26 100644--- a/tests/agent/tools/test_runtime_control.py+++ b/tests/agent/tools/test_runtime_control.py@@ -93,7 +93,8 @@ def test_agent_loop_assembles_my_tool_with_runtime_control(tmp_path: Path) -> Nodef test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path) -> None:loop = _make_loop(tmp_path)loop.web_config.search.api_key = "search-secret"- loop.web_config.proxy = "http://proxy-user:[email protected]"+ loop.network_config.proxy = "http://proxy-user:[email protected]"+ loop.web_config.use_proxy = Trueloop.unlisted_secret = "loop-secret"snapshot = _my_tool(loop)._runtime_control.snapshot()@@ -132,7 +133,7 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Pathassert "search-secret" not in renderedassert "proxy-secret" not in renderedassert "loop-secret" not in rendered- assert snapshot.web_config["proxy"] == "<configured>"+ assert snapshot.web_config["use_proxy"] is Truedef test_runtime_snapshot_is_detached_from_mutable_config(tmp_path: Path) -> None:diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.pyindex 269241aae..741a1fab1 100644--- a/tests/channels/test_channel_plugins.py+++ b/tests/channels/test_channel_plugins.py@@ -912,11 +912,13 @@ def test_discover_enabled_warns_for_enabled_package_import_errors():# Manager _init_channels with dict config# ----------------------------------------------------------------------------def test_manager_loads_plugin_from_dict_config(monkeypatch):- """ChannelManager should instantiate a channel package from a raw dict config."""[email protected]("proxy", ["", "http://127.0.0.1:7890"])+def test_manager_loads_plugin_from_dict_config(monkeypatch, proxy):+ """Existing two-argument plugins work with or without a shared proxy configured."""from nanobot.channels.manager import ChannelManagerfake_config = Config.model_validate({+ "network": {"proxy": proxy},"channels": {"fakeplugin": {"enabled": True, "allowFrom": ["*"]},}diff --git a/tests/channels/test_channel_setup.py b/tests/channels/test_channel_setup.pyindex 5bc097eb1..1da3fea37 100644--- a/tests/channels/test_channel_setup.py+++ b/tests/channels/test_channel_setup.py@@ -130,7 +130,7 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:assert whatsapp is not Noneassert mattermost.route_field_types["serverUrl"] == "string"assert mattermost.route_field_types["token"] == "secret"- assert whatsapp.route_field_types["proxy"] == "string"+ assert whatsapp.route_field_types["useProxy"] == "bool"assert whatsapp.route_field_types["allowFrom"] == "list"assert whatsapp.route_field_types["groupPolicy"] == ("enum",diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex 69b057290..658aec544 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -911,7 +911,7 @@ def test_provider_login_openai_codex_passes_configured_proxy(monkeypatch):proxy = "http://127.0.0.1:23458"monkeypatch.setattr("nanobot.config.loader.load_config",- lambda: Config.model_validate({"providers": {"openaiCodex": {"proxy": proxy}}}),+ lambda: Config.model_validate({"network": {"proxy": proxy}, "providers": {"openaiCodex": {"useProxy": True}}}),)import oauth_cli_kit@@ -954,7 +954,7 @@ def test_provider_login_openai_codex_uses_explicit_config_proxy(tmp_path, monkeypath = config_path or active_path.get("path")if path is None:return Config.model_validate(- {"providers": {"openaiCodex": {"proxy": "http://default-proxy:8080"}}}+ {"network": {"proxy": "http://default-proxy:8080"}, "providers": {"openaiCodex": {"useProxy": True}}})return real_load_config(path)@@ -987,7 +987,7 @@ def test_provider_login_openai_codex_resolves_proxy_env_ref(monkeypatch):monkeypatch.setattr("nanobot.config.loader.load_config",lambda: Config.model_validate(- {"providers": {"openaiCodex": {"proxy": "${CODEX_PROXY_FOR_TEST}"}}}+ {"network": {"proxy": "${CODEX_PROXY_FOR_TEST}"}, "providers": {"openaiCodex": {"useProxy": True}}}),)@@ -1011,7 +1011,7 @@ def test_provider_login_xai_grok_runs_browser_flow_with_configured_proxy(monkeypproxy = "http://127.0.0.1:23458"monkeypatch.setattr("nanobot.config.loader.load_config",- lambda: Config.model_validate({"providers": {"xaiGrok": {"proxy": proxy}}}),+ lambda: Config.model_validate({"network": {"proxy": proxy}, "providers": {"xaiGrok": {"useProxy": True}}}),)monkeypatch.setattr("nanobot.providers.xai_oauth.get_xai_oauth_token",@@ -1326,7 +1326,8 @@ def test_openai_codex_proxy_config_affects_provider_and_signature():"model": "openai-codex/gpt-5.5",}},- "providers": {"openaiCodex": {"proxy": proxy}},+ "network": {"proxy": proxy},+ "providers": {"openaiCodex": {"useProxy": True}},})@@ -1355,13 +1356,13 @@ def test_provider_proxy_rejects_unsupported_backend():"azureOpenai": {"apiKey": "sk-test","apiBase": "https://azure.example/openai/v1",- "proxy": "http://127.0.0.1:23458",+ "useProxy": True,}},})- with pytest.raises(ValueError, match=r"providers\.azure_openai\.proxy"):+ with pytest.raises(ValueError, match=r"providers\.azure_openai\.use_proxy"):make_provider(config)diff --git a/tests/config/test_env_interpolation.py b/tests/config/test_env_interpolation.pyindex 21ce71490..ae9e3727f 100644--- a/tests/config/test_env_interpolation.py+++ b/tests/config/test_env_interpolation.py@@ -159,10 +159,11 @@ class TestResolveConfig:proxy = "http://127.0.0.1:23458"config = Config.model_validate({+ "network": {"proxy": proxy},"providers": {"openaiCodex": {"apiKey": "codex-secret",- "proxy": proxy,+ "useProxy": True,"extraBody": {"service_tier": "priority"},},"groq": {"apiKey": "groq-secret"},@@ -175,12 +176,13 @@ class TestResolveConfig:saved = json.loads(config_path.read_text(encoding="utf-8"))assert saved["providers"]["openaiCodex"] == {"extraBody": {"service_tier": "priority"},- "proxy": proxy,+ "useProxy": True,}assert saved["providers"]["groq"]["apiKey"] == "groq-secret"reloaded = load_config(config_path)- assert reloaded.providers.openai_codex.proxy == proxy+ assert reloaded.network.proxy == proxy+ assert reloaded.providers.openai_codex.use_proxy is Trueassert reloaded.providers.openai_codex.extra_body == {"service_tier": "priority"}assert reloaded.providers.openai_codex.api_key is None@@ -189,10 +191,11 @@ class TestResolveConfig:proxy = "http://127.0.0.1:23458"config = Config.model_validate({+ "network": {"proxy": proxy},"providers": {"xaiGrok": {"apiKey": "must-not-be-saved",- "proxy": proxy,+ "useProxy": True,"extraBody": {"parallel_tool_calls": False},}}@@ -204,12 +207,13 @@ class TestResolveConfig:saved = json.loads(config_path.read_text(encoding="utf-8"))assert saved["providers"]["xaiGrok"] == {"extraBody": {"parallel_tool_calls": False},- "proxy": proxy,+ "useProxy": True,}assert "must-not-be-saved" not in config_path.read_text(encoding="utf-8")reloaded = load_config(config_path)- assert reloaded.providers.xai_grok.proxy == proxy+ assert reloaded.network.proxy == proxy+ assert reloaded.providers.xai_grok.use_proxy is Trueassert reloaded.providers.xai_grok.extra_body == {"parallel_tool_calls": False}assert reloaded.providers.xai_grok.api_key is None@@ -217,6 +221,7 @@ class TestResolveConfig:config_path = tmp_path / "config.json"config = Config.model_validate({+ "network": {"proxy": "http://127.0.0.1:7890"},"providers": {"openaiCodex": {"apiKey": "codex-secret",@@ -224,7 +229,7 @@ class TestResolveConfig:},"xaiGrok": {"apiKey": "xai-secret",- "proxy": "http://127.0.0.1:7890",+ "useProxy": True,"extraBody": {"parallel_tool_calls": False},},}@@ -239,7 +244,7 @@ class TestResolveConfig:}assert saved["providers"]["xaiGrok"] == {"extraBody": {"parallel_tool_calls": False},- "proxy": "http://127.0.0.1:7890",+ "useProxy": True,}assert "codex-secret" not in config_path.read_text(encoding="utf-8")assert "xai-secret" not in config_path.read_text(encoding="utf-8")diff --git a/tests/config/test_network_proxy.py b/tests/config/test_network_proxy.pynew file mode 100644index 000000000..c3d1fcc1b--- /dev/null+++ b/tests/config/test_network_proxy.py@@ -0,0 +1,267 @@+"""One shared address, explicit feature opt-in, and legacy config migration."""++import json++import httpx+import pytest++from nanobot.config.loader import ConfigLoadError, load_config, resolve_config_env_vars, save_config+from nanobot.config.network import NetworkConfig+from nanobot.config.schema import Config++[email protected]("address", ["http://127.0.0.1:7890", "socks5://user:pass@localhost:1080", "${SHARED_PROXY}"])+def test_legacy_proxy_migrates_once_across_features(tmp_path, address):+ path = tmp_path / "config.json"+ original = {+ "providers": {"openai": {"proxy": address}, "openaiCodex": {"proxy": address}},+ "tools": {"web": {"proxy": address}},+ "channels": {"telegram": {"proxy": address}, "slack": {"proxy": ""}},+ }+ path.write_text(json.dumps(original), encoding="utf-8")+ config = load_config(path)+ assert json.loads(path.read_text(encoding="utf-8")) == original+ assert config.network.proxy == address+ assert config.providers.openai.use_proxy is True+ assert config.providers.openai_codex.use_proxy is True+ assert config.tools.web.use_proxy is True+ assert config.channels.telegram["useProxy"] is True+ assert "useProxy" not in config.channels.slack+ config.providers.openai.use_proxy = False+ save_config(config, path)+ saved = json.loads(path.read_text(encoding="utf-8"))+ assert saved["network"]["proxy"] == address+ assert "proxy" not in saved["providers"]["openai"]+ assert "proxy" not in saved["tools"]["web"]+ assert "proxy" not in saved["channels"]["telegram"]+ assert load_config(path).providers.openai.use_proxy is False+++def test_multiple_legacy_addresses_require_one_explicit_global_address(tmp_path):+ path = tmp_path / "config.json"+ original = {"tools": {"web": {"proxy": "http://secret:password@localhost:7890"}}, "channels": {"discord": {"proxy": "http://localhost:7891"}}}+ path.write_text(json.dumps(original), encoding="utf-8")+ with pytest.raises(ConfigLoadError, match="Multiple legacy proxy addresses") as caught:+ load_config(path)+ assert "secret" not in str(caught.value)+ assert json.loads(path.read_text(encoding="utf-8")) == original+ original["network"] = {"proxy": "http://localhost:7892"}+ path.write_text(json.dumps(original), encoding="utf-8")+ config = load_config(path)+ assert config.network.proxy == "http://localhost:7892"+ assert config.tools.web.use_proxy is True+ assert config.channels.discord["useProxy"] is True+++def test_discord_proxy_credentials_move_into_the_shared_url(tmp_path):+ path = tmp_path / "config.json"+ path.write_text(json.dumps({"channels": {"discord": {"proxy": "localhost:7890", "proxyUsername": "user@host", "proxyPassword": "pass:word"}}}), encoding="utf-8")+ config = load_config(path)+ assert config.network.proxy == "http://user%40host:pass%3Aword@localhost:7890"+ assert config.channels.discord == {"useProxy": True}+++def test_proxy_opt_in_does_not_fall_back_when_unconfigured():+ network = NetworkConfig()+ assert network.resolve_proxy(False) is None+ with pytest.raises(ValueError, match="Advanced"):+ network.resolve_proxy(True)+++def test_shared_proxy_environment_reference_stays_unresolved_on_disk(tmp_path, monkeypatch):+ monkeypatch.setenv("SHARED_PROXY", "http://localhost:7890")+ config = Config(network=NetworkConfig(proxy="${SHARED_PROXY}"))+ config.tools.web.use_proxy = True+ resolved = resolve_config_env_vars(config)+ assert resolved.network.resolve_proxy(True) == "http://localhost:7890"+ assert config.network.proxy == "${SHARED_PROXY}"+ path = tmp_path / "config.json"+ save_config(config, path)+ assert load_config(path).network.proxy == "${SHARED_PROXY}"++[email protected]("address", ["file:///tmp/proxy", "http://host:99999", "http://host/path", "http://user:secret@["])+def test_invalid_shared_proxy_has_a_safe_error(address):+ with pytest.raises(ValueError, match="proxy URL") as caught:+ NetworkConfig.normalize_proxy(address)+ assert address not in str(caught.value)++[email protected]("file_present", [False, True])+def test_environment_legacy_proxy_migrates_after_source_merge(tmp_path, monkeypatch, file_present):+ proxy = "http://localhost:7890"+ monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": proxy}}))+ monkeypatch.setenv("NANOBOT_TOOLS", json.dumps({"web": {"proxy": proxy}}))+ monkeypatch.setenv("NANOBOT_CHANNELS", json.dumps({"telegram": {"proxy": proxy}}))+ path = tmp_path / "config.json"+ if file_present:+ path.write_text(json.dumps({"providers": {"openai": {"apiKey": "test-key"}}}), encoding="utf-8")+ config = load_config(path)+ assert config.network.proxy == proxy+ assert config.providers.openai.use_proxy is True+ assert config.tools.web.use_proxy is True+ assert config.channels.telegram == {"useProxy": True}+ save_config(config, path)+ saved = json.loads(path.read_text(encoding="utf-8"))+ assert saved["network"]["proxy"] == proxy+ assert "proxy" not in saved["providers"]["openai"]+ config.providers.openai.use_proxy = False+ save_config(config, path)+ assert load_config(path).providers.openai.use_proxy is False+++def test_file_proxy_and_opt_out_take_precedence_over_environment(tmp_path, monkeypatch):+ monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": "http://environment:7890"}}))+ path = tmp_path / "config.json"+ path.write_text(json.dumps({"providers": {"openai": {"proxy": "http://file:7891", "useProxy": False}}}), encoding="utf-8")+ config = load_config(path)+ assert config.network.proxy == "http://file:7891"+ assert config.providers.openai.use_proxy is False++[email protected]("password", ["a/b", "a#b?c", "a@b:c%"])+def test_discord_credential_references_are_escaped_without_persisting_secrets(tmp_path, monkeypatch, password):+ from urllib.parse import unquote, urlsplit++ monkeypatch.setenv("PROXY_USER", "alice@example")+ monkeypatch.setenv("PROXY_PASSWORD", password)+ path = tmp_path / "config.json"+ path.write_text(json.dumps({"channels": {"discord": {"proxy": "http://localhost:7890", "proxyUsername": "${PROXY_USER}", "proxyPassword": "${PROXY_PASSWORD}"}}}), encoding="utf-8")+ config = load_config(path)+ for network in (config.network, resolve_config_env_vars(config).network):+ proxy = network.resolve_proxy(True)+ parsed = urlsplit(proxy)+ assert parsed.hostname == "localhost"+ assert parsed.port == 7890+ assert unquote(parsed.username) == "alice@example"+ assert unquote(parsed.password) == password+ save_config(config, path)+ saved = json.loads(path.read_text(encoding="utf-8"))+ assert saved["network"]["proxy"] == "http://${PROXY_USER}:${PROXY_PASSWORD}@localhost:7890"+ assert "alice@example" not in path.read_text(encoding="utf-8")+ assert load_config(path).network.resolve_proxy(True) == config.network.resolve_proxy(True)+++def test_whole_discord_url_reference_with_separate_credentials_requires_consolidation(tmp_path, monkeypatch):+ monkeypatch.setenv("DISCORD_PROXY", "http://localhost:7890")+ original = {"channels": {"discord": {"proxy": "${DISCORD_PROXY}", "proxyUsername": "alice", "proxyPassword": "secret-password"}}}+ path = tmp_path / "config.json"+ path.write_text(json.dumps(original), encoding="utf-8")+ with pytest.raises(ConfigLoadError, match="one full URL environment variable") as caught:+ load_config(path)+ assert "secret-password" not in str(caught.value)+ assert json.loads(path.read_text(encoding="utf-8")) == original+ original["network"] = {"proxy": "${SHARED_PROXY}"}+ path.write_text(json.dumps(original), encoding="utf-8")+ config = load_config(path)+ assert config.network.proxy == "${SHARED_PROXY}"+ assert config.channels.discord == {"useProxy": True}++[email protected]("alias, attribute", [("openaiCodex", "openai_codex"), ("xaiGrok", "xai_grok")])[email protected]("saved_opt_out", [True, False], ids=["refresh", "changed-setting"])+def test_oauth_proxy_opt_out_survives_save_with_legacy_environment(tmp_path, monkeypatch, alias, attribute, saved_opt_out):+ proxy = "http://proxy.example:8080"+ monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({alias: {"proxy": proxy, "apiKey": "oauth-secret"}}))+ original = {"network": {"proxy": proxy}, "providers": {alias: {"useProxy": False} if saved_opt_out else {}}}+ path = tmp_path / "config.json"+ path.write_text(json.dumps(original), encoding="utf-8")++ config = load_config(path)+ provider = getattr(config.providers, attribute)+ assert provider.use_proxy is (not saved_opt_out)+ assert json.loads(path.read_text(encoding="utf-8")) == original+ if not saved_opt_out:+ provider.use_proxy = False+ save_config(config, path)++ saved = json.loads(path.read_text(encoding="utf-8"))+ assert saved["providers"][alias] == {"useProxy": False}+ assert "oauth-secret" not in path.read_text(encoding="utf-8")+ assert getattr(load_config(path).providers, attribute).use_proxy is False++[email protected]("legacy", [False, True], ids=["shared", "legacy"])+ "userinfo, environment, expected_auth",+ [+ ("${PROXY_AUTH}", {"PROXY_AUTH": "alice:pw"}, (b"alice", b"pw")),+ ("${PROXY_AUTH}", {"PROXY_AUTH": "alice%40mail:p%2Fa%23b%3Fc%40d%3Ae%2525f"}, (b"alice@mail", b"p/a#b?c@d:e%25f")),+ ("${PROXY_AUTH}", {"PROXY_AUTH": "alice:p/a#b?c@d:e%f"}, (b"alice", b"p/a#b?c@d:e%f")),+ (+ "${PROXY_USER}:${PROXY_PASSWORD}",+ {"PROXY_USER": "alice/a#b?c@d:e%25f", "PROXY_PASSWORD": "p/a#b?c@d:e%25f"},+ (b"alice/a#b?c@d:e%25f", b"p/a#b?c@d:e%25f"),+ ),+ ],+ ids=["combined-auth", "combined-encoded-auth", "combined-special-password", "credential-components"],+)+def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypatch, legacy, userinfo, environment, expected_auth):+ for name, value in environment.items():+ monkeypatch.setenv(name, value)+ template = f"http://{userinfo}@proxy.example:8080"+ original = {"providers": {"openai": {"proxy": template}}} if legacy else {+ "network": {"proxy": template}, "providers": {"openai": {"useProxy": True}},+ }+ path = tmp_path / "config.json"+ path.write_text(json.dumps(original), encoding="utf-8")++ config = load_config(path)+ assert config.network.proxy == template+ assert config.providers.openai.use_proxy is True+ for current in (config, resolve_config_env_vars(config)):+ assert httpx.Proxy(current.network.resolve_proxy(current.providers.openai.use_proxy)).raw_auth == expected_auth+ assert json.loads(path.read_text(encoding="utf-8")) == original+ save_config(config, path)++ saved_text = path.read_text(encoding="utf-8")+ assert json.loads(saved_text)["network"]["proxy"] == template+ for value in environment.values():+ assert value not in saved_text+ reloaded = load_config(path)+ assert reloaded.network.proxy == template+ assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == expected_auth++[email protected]("address", ["${PROXY_SCHEME}://proxy.example:8080", "${PROXY_SCHEME}://${PROXY_HOST}:8080", "http://${PROXY_HOST}:8080"])[email protected]("credential_refs", [False, True], ids=["literal-auth", "referenced-auth"])+def test_discord_partial_url_reference_migrates_without_resolving_on_disk(tmp_path, monkeypatch, address, credential_refs):+ from urllib.parse import quote++ username = "alice/a#b?c@d:e%25f"+ password = "p/a#b?c@d:e%25f"+ monkeypatch.setenv("PROXY_SCHEME", "http")+ monkeypatch.setenv("PROXY_HOST", "proxy.example")+ monkeypatch.setenv("PROXY_USER", username)+ monkeypatch.setenv("PROXY_PASSWORD", password)+ user_template = "${PROXY_USER}" if credential_refs else quote(username, safe="")+ password_template = "${PROXY_PASSWORD}" if credential_refs else quote(password, safe="")+ scheme, host = address.split("://", 1)+ expected_template = f"{scheme}://{user_template}:{password_template}@{host}"+ original = {"channels": {"discord": {+ "proxy": address,+ "proxyUsername": "${PROXY_USER}" if credential_refs else username,+ "proxyPassword": "${PROXY_PASSWORD}" if credential_refs else password,+ }}}+ path = tmp_path / "config.json"+ path.write_text(json.dumps(original), encoding="utf-8")++ config = load_config(path)+ assert config.network.proxy == expected_template+ assert config.channels.discord == {"useProxy": True}+ assert json.loads(path.read_text(encoding="utf-8")) == original+ for network in (config.network, resolve_config_env_vars(config).network):+ proxy = httpx.Proxy(network.resolve_proxy(True))+ assert proxy.url.host == "proxy.example"+ assert proxy.url.port == 8080+ assert proxy.raw_auth == (username.encode(), password.encode())+ save_config(config, path)++ saved_text = path.read_text(encoding="utf-8")+ assert json.loads(saved_text)["network"]["proxy"] == expected_template+ if credential_refs:+ assert username not in saved_text+ assert password not in saved_text+ reloaded = load_config(path)+ assert reloaded.network.proxy == expected_template+ assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == (username.encode(), password.encode())diff --git a/tests/providers/test_model_api_presets.py b/tests/providers/test_model_api_presets.pyindex 722732e29..e9ad2ee5f 100644--- a/tests/providers/test_model_api_presets.py+++ b/tests/providers/test_model_api_presets.py@@ -602,7 +602,8 @@ async def test_custom_messages_uses_its_proxy_and_does_not_inherit_native_credenconfig = _config()connection = config.get_provider(preset=config.model_presets["messages"])connection.api_key = None- connection.proxy = "http://proxy.test:8080"+ config.network.proxy = "http://proxy.test:8080"+ connection.use_proxy = Truemonkeypatch.setenv("ANTHROPIC_API_KEY", "native-key")monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "native-token")requests = []@@ -612,7 +613,7 @@ async def test_custom_messages_uses_its_proxy_and_does_not_inherit_native_credenreturn _answer(request)def transport(**kwargs):- assert kwargs.pop("proxy") == connection.proxy+ assert kwargs.pop("proxy") == config.network.proxyassert kwargs["trust_env"] is Falsereturn DefaultAsyncHttpxClient(transport=httpx.MockTransport(handler), **kwargs)diff --git a/tests/providers/test_xai_grok_provider.py b/tests/providers/test_xai_grok_provider.pyindex 7abf46d12..e286b356b 100644--- a/tests/providers/test_xai_grok_provider.py+++ b/tests/providers/test_xai_grok_provider.py@@ -417,9 +417,10 @@ async def test_factory_builds_xai_provider_and_applies_explicit_body_overrides(m"provider": "xai_grok",}},+ "network": {"proxy": "http://127.0.0.1:7890"},"providers": {"xaiGrok": {- "proxy": "http://127.0.0.1:7890",+ "useProxy": True,"extraBody": {"parallel_tool_calls": False,"max_turns": 2,diff --git a/tests/tools/test_image_generation_tool.py b/tests/tools/test_image_generation_tool.pyindex b48f03bcb..5e0d06b40 100644--- a/tests/tools/test_image_generation_tool.py+++ b/tests/tools/test_image_generation_tool.py@@ -9,6 +9,7 @@ import pytestfrom nanobot.agent.tools.image_generation import ImageGenerationTool, ImageGenerationToolConfigfrom nanobot.config.loader import set_config_path+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import Config, ProviderConfigfrom nanobot.providers.image_generation import GeneratedImageResponse, image_gen_provider_configs@@ -188,7 +189,8 @@ def test_image_generation_tool_passes_provider_proxy_to_client(provider="openai_codex",model="openai-codex/gpt-image-2",),- provider_configs={"openai_codex": ProviderConfig(proxy=proxy)},+ provider_configs={"openai_codex": ProviderConfig(use_proxy=True)},+ network=NetworkConfig(proxy=proxy),)client = tool._provider_client()diff --git a/tests/tools/test_mcp_probe.py b/tests/tools/test_mcp_probe.pyindex d97bd48c1..12b936618 100644--- a/tests/tools/test_mcp_probe.py+++ b/tests/tools/test_mcp_probe.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport socket-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom urllib.request import getproxies_environmentimport httpx@@ -79,7 +79,8 @@ async def test_probe_returns_false_when_validated_target_refuses_connection(@pytest.mark.asyncio-async def test_probe_rejects_public_name_resolving_to_loopback():[email protected]("proxy", [None, "http://shared-proxy.example:8080"])+async def test_probe_rejects_public_name_resolving_to_loopback(proxy):def _resolver(hostname, port, family=0, type_=0):return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))]@@ -87,7 +88,7 @@ async def test_probe_rejects_public_name_resolving_to_loopback():patch("nanobot.security.network.socket.getaddrinfo", _resolver),patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection,):- assert await _probe_http_url("http://example.com:8765/mcp") is False+ assert await _probe_http_url("http://example.com:8765/mcp", proxy=proxy) is Falseopen_connection.assert_not_called()@@ -145,22 +146,13 @@ async def test_probe_tries_next_validated_ip_when_first_is_unreachable(monkeypat# ---------------------------------------------------------------------------def _make_http_cfg(url: str, transport: str = "streamableHttp"):- cfg = MagicMock()- cfg.type = transport- cfg.url = url- cfg.command = None- cfg.args = []- cfg.env = {}- cfg.headers = None- cfg.tool_timeout = 30- cfg.enabled_tools = ["*"]- return cfg+ return MCPServerConfig(type=transport, url=url)@pytest.mark.asyncioasync def test_connect_skips_unreachable_streamable_http():"""Unreachable streamableHttp server should be skipped with a warning, no crash."""- async def _unreachable(_url: str) -> bool:+ async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:return Falseregistry = ToolRegistry()@@ -174,7 +166,7 @@ async def test_connect_skips_unreachable_streamable_http():@pytest.mark.asyncioasync def test_connect_skips_unreachable_sse():"""Unreachable SSE server should be skipped with a warning, no crash."""- async def _unreachable(_url: str) -> bool:+ async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:return Falseregistry = ToolRegistry()@@ -190,7 +182,7 @@ async def test_connect_isolates_streamable_http_status_failure(monkeypatch: pytest.MonkeyPatch,) -> None:"""A reachable endpoint returning HTTP 530 must not poison the event loop."""- async def _reachable(_url: str) -> bool:+ async def _reachable(_url: str, *, proxy: str | None = None) -> bool:return Truedef _return_http_530(request: httpx.Request) -> httpx.Response:@@ -249,16 +241,22 @@ async def test_probe_not_called_for_stdio():return await original_probe(url, **kw)with patch("nanobot.agent.tools.mcp._probe_http_url", _spy_probe):- cfg = MagicMock()- cfg.type = "stdio"- cfg.url = None- cfg.command = "nonexistent-command-xyz"- cfg.args = []- cfg.env = None- cfg.headers = None- cfg.tool_timeout = 30- cfg.enabled_tools = ["*"]+ cfg = MCPServerConfig(type="stdio", command="nonexistent-command-xyz")registry = ToolRegistry()await connect_mcp_servers({"s": cfg}, registry)assert not called, "probe should not be called for stdio transport"+++async def test_explicit_proxy_skips_direct_probe_even_when_no_proxy_env_matches(monkeypatch):+ monkeypatch.setenv("NO_PROXY", "mcp.example.com")+ monkeypatch.setattr(+ "nanobot.agent.tools.mcp.resolve_url_target",+ lambda _url: (True, "", ("93.184.216.34",)),+ )+ with patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection:+ assert await _probe_http_url(+ "https://mcp.example.com/mcp", proxy="http://shared-proxy.example:8080"+ ) is True+ open_connection.assert_not_called()diff --git a/tests/tools/test_mcp_proxy.py b/tests/tools/test_mcp_proxy.pynew file mode 100644index 000000000..4c597e015--- /dev/null+++ b/tests/tools/test_mcp_proxy.py@@ -0,0 +1,275 @@+"""Shared MCP routing exercised through a real loopback HTTP recording proxy."""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from urllib.parse import parse_qs, urlsplit+from urllib.request import getproxies_environment++import aiohttp+import pytest+import pytest_asyncio+from aiohttp import web++from nanobot.agent.tools.mcp import MCPProvider, MCPToolWrapper, connect_mcp_servers+from nanobot.agent.tools.mcp_oauth import MCPOAuthStorage+from nanobot.agent.tools.registry import ToolRegistry+from nanobot.config.network import NetworkConfig+from nanobot.config.schema import MCPServerConfig+from nanobot.runtime_admission import RuntimeAdmission+from nanobot.security import network as security_network+from nanobot.webui.mcp_oauth_api import McpOAuthManager++_PROXY_ENV_VARS = (+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",+ "http_proxy", "https_proxy", "all_proxy", "no_proxy",+)+++@dataclass+class _RecordingMCPProxy:+ origin: str = ""+ proxy: str = ""+ proxy_requests: list[tuple[str, str]] = field(default_factory=list)+ origin_requests: list[tuple[str, str, str | None]] = field(default_factory=list)+ rpc_methods: list[str] = field(default_factory=list)+ token_grants: list[str] = field(default_factory=list)+ proxy_fails: bool = False+ terminate_next_call: bool = False+ initialized: int = 0++ async def serve_origin(self, request: web.Request) -> web.Response:+ self.origin_requests.append((request.method, request.path, request.headers.get("X-Test-Proxy")))+ if request.path == "/.well-known/oauth-protected-resource":+ return web.json_response({+ "resource": f"{self.origin}/mcp",+ "authorization_servers": [self.origin],+ })+ if request.path == "/.well-known/oauth-authorization-server":+ return web.json_response({+ "issuer": self.origin,+ # Browser navigation is not performed by this fixture or the gateway.+ "authorization_endpoint": "https://8.8.8.8/authorize",+ "token_endpoint": f"{self.origin}/token",+ "registration_endpoint": f"{self.origin}/register",+ "response_types_supported": ["code"],+ "code_challenge_methods_supported": ["S256"],+ })+ if request.path == "/register":+ registration = await request.json()+ return web.json_response({+ "client_id": "local-test-client",+ "redirect_uris": registration["redirect_uris"],+ "token_endpoint_auth_method": "none",+ }, status=201)+ if request.path == "/token":+ token_request = parse_qs(await request.text())+ grant = token_request["grant_type"][0]+ self.token_grants.append(grant)+ if grant == "authorization_code":+ assert token_request["code"] == ["local-test-code"]+ assert len(token_request["code_verifier"][0]) >= 43+ else:+ assert grant == "refresh_token"+ assert token_request["refresh_token"] == ["local-refresh-token"]+ return web.json_response({+ "access_token": "local-access-token", "refresh_token": "local-refresh-token",+ "token_type": "Bearer", "expires_in": 3600,+ })+ if request.path != "/mcp":+ return web.Response(status=404)+ if request.headers.get("Authorization") != "Bearer local-access-token":+ return web.Response(status=401, headers={+ "WWW-Authenticate": (+ f'Bearer resource_metadata="{self.origin}/.well-known/oauth-protected-resource"'+ ),+ })+ if request.method == "DELETE":+ return web.Response(status=200)+ if request.method != "POST":+ return web.Response(status=405)+ payload = await request.json()+ method = payload["method"]+ self.rpc_methods.append(method)+ if "id" not in payload:+ return web.Response(status=202)+ headers = {}+ if method == "initialize":+ self.initialized += 1+ headers["Mcp-Session-Id"] = f"test-session-{self.initialized}"+ result = {+ "protocolVersion": payload["params"]["protocolVersion"],+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "local-proxy-test", "version": "1"},+ }+ elif method == "tools/list":+ result = {"tools": [{+ "name": "echo", "description": "Echo over the selected route",+ "inputSchema": {"type": "object", "properties": {}},+ }]}+ elif method == "tools/call":+ if self.terminate_next_call:+ self.terminate_next_call = False+ return web.json_response({+ "jsonrpc": "2.0", "id": payload["id"],+ "error": {"code": -32000, "message": "Session terminated"},+ })+ result = {"content": [{"type": "text", "text": "through-shared-proxy"}]}+ else:+ raise AssertionError(f"Unexpected MCP method: {method}")+ return web.json_response({"jsonrpc": "2.0", "id": payload["id"], "result": result}, headers=headers)+++@pytest_asyncio.fixture+async def recording_mcp_proxy(tmp_path, monkeypatch: pytest.MonkeyPatch):+ for name in _PROXY_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(security_network, "getproxies", getproxies_environment)+ monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)+ previous_whitelist = [str(cidr) for cidr in security_network._allowed_networks]+ security_network.configure_ssrf_whitelist(["127.0.0.1/32"])+ fixture = _RecordingMCPProxy()+ runners: list[web.AppRunner] = []++ async def serve(handler) -> str:+ app = web.Application()+ app.router.add_route("*", "/{tail:.*}", handler)+ runner = web.AppRunner(app)+ runners.append(runner)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ port = site._server.sockets[0].getsockname()[1]+ return f"http://127.0.0.1:{port}"++ try:+ fixture.origin = await serve(fixture.serve_origin)+ async with aiohttp.ClientSession(trust_env=False) as forwarding_client:+ async def forward(request: web.Request) -> web.Response:+ target = request.raw_path+ fixture.proxy_requests.append((request.method, target))+ assert target.startswith(f"{fixture.origin}/"), "test proxy must never forward externally"+ if fixture.proxy_fails:+ return web.Response(status=502, text="controlled proxy failure")+ headers = {+ key: value for key, value in request.headers.items()+ if key.lower() not in {"host", "content-length", "connection", "proxy-connection"}+ }+ headers["X-Test-Proxy"] = "shared"+ async with forwarding_client.request(+ request.method, target, headers=headers, data=await request.read(),+ allow_redirects=False,+ ) as response:+ body = await response.read()+ response_headers = {+ key: value for key, value in response.headers.items()+ if key.lower() not in {"content-length", "transfer-encoding", "connection"}+ }+ return web.Response(body=body, status=response.status, headers=response_headers)++ fixture.proxy = await serve(forward)+ yield fixture+ finally:+ for runner in reversed(runners):+ await runner.cleanup()+ security_network.configure_ssrf_whitelist(previous_whitelist)+++async def test_oauth_discovery_tokens_reconnect_and_tool_calls_share_real_proxy(+ recording_mcp_proxy,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ fixture = recording_mcp_proxy+ # Even an ambient proxy or NO_PROXY=* cannot override an explicitly selected route.+ monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:9")+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")+ monkeypatch.setenv("NO_PROXY", "*")+ cfg = MCPServerConfig(+ type="streamableHttp", auth="oauth", url=f"{fixture.origin}/mcp",+ use_proxy=True, enabled_tools=["echo"],+ )+ network = NetworkConfig(proxy=fixture.proxy)+ registry = ToolRegistry()+ provider = MCPProvider({"local": cfg}, registry, network=network)+ manager = McpOAuthManager(RuntimeAdmission())++ async def reload_mcp():+ await provider.connect()+ return {"ok": provider.connected_server_names == {"local"}, "connected": ["local"]}++ started = await asyncio.wait_for(manager.start(+ "local", cfg, "http://127.0.0.1:8765/auth/mcp/callback",+ reload_mcp=reload_mcp, network=network,+ ), timeout=10)+ try:+ assert started["status"] == "authorization_required"+ state = parse_qs(urlsplit(started["authorization_url"]).query)["state"][0]+ manager.submit_callback(state=state, code="local-test-code", error=None)+ async with asyncio.timeout(10):+ while (await manager.status(started["flow_id"]))["status"] == "connecting":+ await asyncio.sleep(0.01)+ assert (await manager.status(started["flow_id"]))["status"] == "connected"+ tool = registry.get("mcp_local_echo")+ assert isinstance(tool, MCPToolWrapper)+ assert await tool.execute() == "through-shared-proxy"+ fixture.terminate_next_call = True+ assert await tool.execute() == "through-shared-proxy"+ assert registry.get("mcp_local_echo") is not tool+ assert fixture.initialized == 3 # Browser flow, activation, terminated-session recovery.+ assert fixture.rpc_methods.count("tools/call") == 3+ storage = MCPOAuthStorage("local", cfg.url)+ snapshot = await storage.get_snapshot()+ assert snapshot.tokens is not None+ assert snapshot.tokens.access_token == "local-access-token"+ # A later runtime loads an expired saved token and must refresh over the same route.+ await storage.set_tokens(snapshot.tokens.model_copy(update={"expires_in": -1}))+ await provider.aclose()+ registry = ToolRegistry()+ provider = MCPProvider({"local": cfg}, registry, network=network)+ await provider.connect()+ refreshed_tool = registry.get("mcp_local_echo")+ assert isinstance(refreshed_tool, MCPToolWrapper)+ assert await refreshed_tool.execute() == "through-shared-proxy"+ assert fixture.token_grants == ["authorization_code", "refresh_token"]+ assert ("POST", f"{fixture.origin}/register") in fixture.proxy_requests+ assert ("POST", f"{fixture.origin}/token") in fixture.proxy_requests+ assert ("GET", f"{fixture.origin}/.well-known/oauth-protected-resource") in fixture.proxy_requests+ assert ("GET", f"{fixture.origin}/.well-known/oauth-authorization-server") in fixture.proxy_requests+ assert fixture.origin_requests+ assert all(route == "shared" for _, _, route in fixture.origin_requests)+ finally:+ await manager.cancel(started["flow_id"])+ await provider.aclose()++[email protected]("transport", ["sse", "streamableHttp"])+async def test_failing_shared_proxy_never_retries_reachable_origin_directly(recording_mcp_proxy, transport) -> None:+ fixture = recording_mcp_proxy+ fixture.proxy_fails = True+ registry = ToolRegistry()+ connections = await asyncio.wait_for(connect_mcp_servers(+ {"local": MCPServerConfig(type=transport, url=f"{fixture.origin}/mcp", use_proxy=True)},+ registry, network=NetworkConfig(proxy=fixture.proxy),+ ), timeout=5)+ assert connections == {}+ assert registry.tool_names == []+ assert fixture.proxy_requests+ assert fixture.origin_requests == []++[email protected]("transport", ["sse", "streamableHttp"])+async def test_missing_shared_address_does_not_open_http_connection(recording_mcp_proxy, transport) -> None:+ fixture = recording_mcp_proxy+ registry = ToolRegistry()+ connections = await connect_mcp_servers(+ {"local": MCPServerConfig(type=transport, url=f"{fixture.origin}/mcp", use_proxy=True)},+ registry, network=NetworkConfig(),+ )+ assert connections == {}+ assert registry.tool_names == []+ assert fixture.proxy_requests == []+ assert fixture.origin_requests == []diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 1dc974d7b..b61ec6582 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -7,12 +7,14 @@ from contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import ModuleType, SimpleNamespacefrom unittest.mock import AsyncMock+from urllib.parse import unquotefrom urllib.request import getproxies_environmentimport httpximport pytestimport nanobot.agent.tools.mcp as mcp_mod+from nanobot.agent.tools.context import RequestContext, request_contextfrom nanobot.agent.tools.mcp import (MCPPromptWrapper,MCPProvider,@@ -24,6 +26,7 @@ from nanobot.agent.tools.mcp import (connect_mcp_servers,)from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import MCPServerConfig_PROXY_ENV_VARS = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy")@@ -163,7 +166,9 @@ def _make_wrapper(session: object, *, timeout: float = 0.1) -> MCPToolWrapper:async def test_mcp_provider_connect_propagates_external_cancellation(monkeypatch) -> None:started = asyncio.Event()- async def connect_mcp_servers(_servers: dict, _registry: ToolRegistry) -> dict:+ async def connect_mcp_servers(+ _servers: dict, _registry: ToolRegistry, *, network+ ) -> dict:started.set()await asyncio.sleep(60)return {}@@ -211,7 +216,7 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details()yield object(), object(), object()- async def reachable(_url: str) -> bool:+ async def reachable(_url: str, *, proxy: str | None = None) -> bool:return Trueoauth_mod = ModuleType("nanobot.agent.tools.mcp_oauth")@@ -1117,6 +1122,160 @@ def test_unexpected_connection_failure_keeps_error_trace() -> None:assert not any(record["level"].name == "WARNING" for record in records)[email protected]("transport", ["sse", "streamableHttp"])[email protected]("log_content", [True, False])+async def test_proxy_constructor_failure_diagnostics_never_render_live_locals(+ monkeypatch: pytest.MonkeyPatch, transport: str, log_content: bool,+) -> None:+ proxy = "http://diagnostic-user:diagnostic-secret@\u2603.example:8080"+ network = NetworkConfig(proxy=proxy)+ with pytest.raises(httpx.InvalidURL):+ httpx.AsyncHTTPTransport(proxy=network.proxy)++ @asynccontextmanager+ async def sse_client(_url, *, httpx_client_factory):+ async with httpx_client_factory():+ yield object(), object()++ monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", sse_client)+ monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))+ monkeypatch.setattr(mcp_mod, "_probe_http_url", AsyncMock(return_value=True))+ messages: list[str] = []+ sink = mcp_mod.logger.add(+ lambda message: messages.append(str(message)), level="DEBUG",+ format="{level} {message}", diagnose=True, backtrace=True,+ )+ registry = ToolRegistry()+ try:+ with request_context(RequestContext(channel="test", chat_id="proxy", log_content=log_content)):+ connections = await connect_mcp_servers(+ {"remote": MCPServerConfig(+ type=transport, url="https://mcp.example.invalid/mcp", use_proxy=True,+ )}, registry, network=network,+ )+ finally:+ mcp_mod.logger.remove(sink)++ assert connections == {}+ assert registry.tool_names == []+ output = "\n".join(messages)+ assert "diagnostic-secret" not in output+ assert "diagnostic-user" not in output+ assert "failed to connect" in output+ if log_content:+ assert "InvalidURL" in output+ assert "Invalid IDNA hostname" in output+ assert "Traceback (most recent call last)" in output+ assert "in _pinned_transport_kwargs" in output+ else:+ assert "InvalidURL" not in output+ assert "Traceback" not in output++[email protected]("failure_stage", ["open", "cleanup"])[email protected]("userinfo", ["diagnostic-user:diagnostic%3Asecret", "e:p", "e"])+async def test_connection_failure_redacts_resolved_proxy_in_exception_chain_and_group(+ fake_mcp_runtime, monkeypatch: pytest.MonkeyPatch, failure_stage: str, userinfo: str,+) -> None:+ proxy = f"http://{userinfo}@proxy.example.invalid:8080"+ authority = proxy.removeprefix("http://")+ monkeypatch.setenv("MCP_DIAGNOSTIC_PROXY", proxy)+ network = NetworkConfig(proxy="${MCP_DIAGNOSTIC_PROXY}")+ session = _make_fake_session(["demo"])+ session.initialize = AsyncMock(side_effect=RuntimeError("initialize failed"))+ fake_mcp_runtime["session"] = session++ @asynccontextmanager+ async def failing_sse(_url, *, httpx_client_factory):+ if failure_stage == "cleanup":+ yield object(), object()+ try:+ raise ValueError(f"proxy handshake rejected {proxy}")+ except ValueError as cause:+ raise ExceptionGroup("MCP transport setup failed", [+ httpx.ProxyError(+ f"authentication rejected {authority} / {unquote(authority)} / {unquote(proxy)}"+ ),+ ]) from cause+ yield # pragma: no cover++ monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", failing_sse)+ monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))+ monkeypatch.setattr(mcp_mod, "_probe_http_url", AsyncMock(return_value=True))+ messages: list[str] = []+ sink = mcp_mod.logger.add(+ lambda message: messages.append(str(message)), level="DEBUG",+ format="{level} {message}", diagnose=True, backtrace=True,+ )+ try:+ assert await connect_mcp_servers(+ {"remote": MCPServerConfig(type="sse", url="https://mcp.example.invalid/sse", use_proxy=True)},+ ToolRegistry(), network=network,+ ) == {}+ finally:+ mcp_mod.logger.remove(sink)++ output = "\n".join(messages)+ for credential_context in (proxy, unquote(proxy), f"{userinfo}@", f"{unquote(userinfo)}@"):+ assert credential_context not in output+ assert "Traceback (most recent call last)" in output+ assert "httpx.ProxyError: authentication rejected" in output+ assert "ValueError: proxy handshake rejected" in output+ assert "ExceptionGroup: MCP transport setup failed" in output+ assert "http://proxy.example.invalid:8080" in output+ assert "[redacted]@proxy.example.invalid:8080" in output+ assert "direct cause" in output+ assert "in failing_sse" in output+ if failure_stage == "cleanup":+ assert "initialize failed" in output++[email protected]("transient", [False, True])+def test_connection_failure_retains_useful_trace_without_local_values(transient: bool) -> None:+ messages: list[str] = []+ records: list[dict] = []++ def capture(message):+ messages.append(str(message))+ records.append(message.record)++ sink = mcp_mod.logger.add(+ capture, level="DEBUG", format="{level} {message}", diagnose=True, backtrace=True,+ )++ def fail_transport():+ local_credential = "unrelated-local-credential"+ error = httpx.ConnectError if transient else RuntimeError+ raise error(f"handshake failed (credential length {len(local_credential)})")++ try:+ try:+ fail_transport()+ except Exception as exc:+ mcp_mod._log_mcp_connection_failure("remote", exc, " check server configuration")+ finally:+ mcp_mod.logger.remove(sink)++ output = "\n".join(messages)+ assert "unrelated-local-credential" not in output+ assert "handshake failed (credential length 26)" in output+ assert "in fail_transport" in output+ assert "Traceback (most recent call last)" in output+ detail = next(record for record in records if record["exception"] is not None)+ assert detail["exception"].traceback is None+ assert detail["exception"].value.__traceback__ is None+ assert detail["exception"].value.__context__ is None+ assert detail["level"].name == ("DEBUG" if transient else "ERROR")+ if transient:+ assert "ConnectError" in output+ assert "transient connection failure" in output+ else:+ assert "RuntimeError" in output+ assert "check server configuration" in output++@pytest.mark.asyncio@pytest.mark.parametrize("config",@@ -1127,7 +1286,9 @@ def test_unexpected_connection_failure_keeps_error_trace() -> None:MCPServerConfig(type="streamableHttp", url="http://169.254.169.254/mcp"),],)[email protected]("use_proxy", [False, True])async def test_connect_mcp_servers_rejects_unsafe_http_urls_before_probe(+ use_proxy: bool,config: MCPServerConfig,monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1145,7 +1306,11 @@ async def test_connect_mcp_servers_rejects_unsafe_http_urls_before_probe(monkeypatch.setattr("nanobot.agent.tools.mcp.logger.warning", _warning)registry = ToolRegistry()- stacks = await connect_mcp_servers({"local": config}, registry)+ stacks = await connect_mcp_servers(+ {"local": config.model_copy(update={"use_proxy": use_proxy})},+ registry,+ network=NetworkConfig(proxy="http://shared-proxy.example:8080"),+ )assert stacks == {}assert registry.tool_names == []@@ -1180,7 +1345,7 @@ async def test_connect_mcp_servers_env_proxy_adds_proxy_mounts_and_keeps_pinned_fake_mcp_runtime["session"] = _make_fake_session(["demo"])client_kwargs: list[dict[str, object]] = []- async def _reachable(_url: str) -> bool:+ async def _reachable(_url: str, *, proxy: str | None = None) -> bool:return Truedef _validate(_url: str) -> tuple[bool, str]:@@ -1273,7 +1438,9 @@ def test_mcp_http_clients_no_proxy_env_keeps_pinned_direct_route(monkeypatch):),],)[email protected]("use_proxy", [False, True])async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(+ use_proxy: bool,config: MCPServerConfig,expected_transport: str,monkeypatch: pytest.MonkeyPatch,@@ -1288,7 +1455,7 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(return False, "loopback blocked"return True, ""- async def _reachable(_url: str) -> bool:+ async def _reachable(_url: str, *, proxy: str | None = None) -> bool:return Truedef _handler(request: httpx.Request) -> httpx.Response:@@ -1329,6 +1496,11 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets("PinnedDNSAsyncTransport",lambda **_kwargs: httpx.MockTransport(_handler),)+ monkeypatch.setattr(+ mcp_mod.httpx,+ "AsyncHTTPTransport",+ lambda **_kwargs: httpx.MockTransport(_handler),+ )monkeypatch.setattr(mcp_mod.httpx, "AsyncClient", _async_client_with_mock_transport)monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", _fake_sse_client)monkeypatch.setattr(@@ -1338,7 +1510,11 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets()registry = ToolRegistry()- stacks = await connect_mcp_servers({"remote": config}, registry)+ stacks = await connect_mcp_servers(+ {"remote": config.model_copy(update={"use_proxy": use_proxy})},+ registry,+ network=NetworkConfig(proxy="http://shared-proxy.example:8080"),+ )assert stacks == {}assert registry.tool_names == []@@ -1503,7 +1679,7 @@ async def test_connect_mcp_servers_streamable_http_uses_finite_timeout(fake_mcp_runtime["session"] = _make_fake_session(["demo"])captured: dict[str, object] = {}- async def _reachable(_url: str) -> bool:+ async def _reachable(_url: str, *, proxy: str | None = None) -> bool:return Truedef _validate(_url: str) -> tuple[bool, str]:@@ -1558,7 +1734,7 @@ async def test_connect_mcp_servers_attaches_oauth_to_remote_http_client(oauth_handlers = object()captured: dict[str, object] = {}- async def _reachable(_url: str) -> bool:+ async def _reachable(_url: str, *, proxy: str | None = None) -> bool:return Truedef _validate(_url: str) -> tuple[bool, str]:@@ -1642,7 +1818,7 @@ async def test_connect_mcp_servers_skips_background_oauth_without_credentials(probe_called = False- async def _probe(_url: str) -> bool:+ async def _probe(_url: str, *, proxy: str | None = None) -> bool:nonlocal probe_calledprobe_called = Truereturn True@@ -2342,3 +2518,88 @@ async def test_optional_mcp_filters_reach_server_unchanged(params, error):else:assert result == "ok"session.call_tool.assert_awaited_once_with("list_issues", arguments=params)++[email protected]("transport", ["sse", "streamableHttp"])[email protected]("use_proxy", [False, True], ids=["environment-route", "shared-route"])+async def test_mcp_http_requests_use_selected_transport_without_route_fallback(+ fake_mcp_runtime,+ monkeypatch: pytest.MonkeyPatch,+ transport: str,+ use_proxy: bool,+) -> None:+ fake_mcp_runtime["session"] = _make_fake_session(["demo"])+ routes: list[str] = []+ constructed_proxies: list[str] = []+ shared_proxy = "http://shared.example:8080"++ def recording_transport(route: str) -> httpx.MockTransport:+ def respond(request: httpx.Request) -> httpx.Response:+ routes.append(route)+ return httpx.Response(200, json={"ok": True}, request=request)+ return httpx.MockTransport(respond)++ def proxy_transport(*, proxy: str) -> httpx.MockTransport:+ constructed_proxies.append(proxy)+ return recording_transport("shared")++ async def probe(_url, *, proxy):+ assert proxy == (shared_proxy if use_proxy else None)+ return True++ @asynccontextmanager+ async def sse_client(url, *, httpx_client_factory):+ async with httpx_client_factory() as client:+ response = await client.get(url)+ assert response.json() == {"ok": True}+ yield object(), object()++ @asynccontextmanager+ async def streamable_client(url, *, http_client):+ response = await http_client.get(url)+ assert response.json() == {"ok": True}+ yield object(), object(), object()++ monkeypatch.setenv("HTTPS_PROXY", "http://environment.example:8888")+ monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))+ monkeypatch.setattr(mcp_mod, "_probe_http_url", probe)+ monkeypatch.setattr(mcp_mod, "PinnedDNSAsyncTransport", lambda: recording_transport("direct"))+ monkeypatch.setattr(+ mcp_mod, "httpx_env_proxy_mounts", lambda: {"all://": recording_transport("environment")},+ )+ monkeypatch.setattr(mcp_mod.httpx, "AsyncHTTPTransport", proxy_transport)+ monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", sse_client)+ monkeypatch.setattr(sys.modules["mcp.client.streamable_http"], "streamable_http_client", streamable_client)++ registry = ToolRegistry()+ connections = await connect_mcp_servers(+ {"remote": MCPServerConfig(+ type=transport, url="https://93.184.216.34/mcp", use_proxy=use_proxy,+ )},+ registry,+ network=NetworkConfig(proxy=shared_proxy),+ )+ try:+ assert set(connections) == {"remote"}+ assert registry.has("mcp_remote_demo")+ assert routes == (["shared"] if use_proxy else ["environment"])+ assert constructed_proxies == ([shared_proxy] if use_proxy else [])+ finally:+ for connection in connections.values():+ await connection.aclose()+++async def test_stdio_cannot_opt_into_shared_proxy(monkeypatch) -> None:+ stdio_client = AsyncMock()+ monkeypatch.setattr(sys.modules["mcp.client.stdio"], "stdio_client", stdio_client)+ registry = ToolRegistry()+ connections = await connect_mcp_servers(+ {"local": MCPServerConfig(command="must-not-launch", use_proxy=True)},+ registry,+ network=NetworkConfig(proxy="http://shared.example:8080"),+ )+ assert connections == {}+ assert registry.tool_names == []+ stdio_client.assert_not_called()diff --git a/tests/tools/test_tool_loader.py b/tests/tools/test_tool_loader.pyindex 1c62486b3..3b6f576a5 100644--- a/tests/tools/test_tool_loader.py+++ b/tests/tools/test_tool_loader.py@@ -337,7 +337,7 @@ def test_web_search_tool_create():mock_config = MagicMock()mock_config.web.enable = Truemock_config.web.search = MagicMock()- mock_config.web.proxy = None+ mock_config.web.use_proxy = Falsemock_config.web.user_agent = Nonectx = ToolContext(config=mock_config, workspace="/tmp")tool = WebSearchTool.create(ctx)@@ -349,7 +349,7 @@ def test_web_fetch_tool_create():mock_config = MagicMock()mock_config.web.enable = Truemock_config.web.fetch = MagicMock()- mock_config.web.proxy = None+ mock_config.web.use_proxy = Falsemock_config.web.user_agent = Nonectx = ToolContext(config=mock_config, workspace="/tmp")tool = WebFetchTool.create(ctx)@@ -442,7 +442,7 @@ def test_loader_registers_builtin_tools():mock_config.web.enable = Truemock_config.web.search = MagicMock()mock_config.web.fetch = MagicMock()- mock_config.web.proxy = None+ mock_config.web.use_proxy = Falsemock_config.web.user_agent = Nonemock_config.image_generation.enabled = Falsemock_config.my.enable = Truediff --git a/tests/webui/fixtures/runtime-config-keys.json b/tests/webui/fixtures/runtime-config-keys.jsonindex 498eb4b6e..47e909e2a 100644--- a/tests/webui/fixtures/runtime-config-keys.json+++ b/tests/webui/fixtures/runtime-config-keys.json@@ -34,7 +34,8 @@"tools.max_session_messages_per_minute","tools.webui_allow_remote_package_install","tools.web.enable",- "tools.web.proxy",+ "network.proxy",+ "tools.web.use_proxy","tools.web.user_agent","tools.image_generation.save_dir","api.host",diff --git a/tests/webui/test_mcp_oauth_api.py b/tests/webui/test_mcp_oauth_api.pyindex 1aeeba857..2cb0c108a 100644--- a/tests/webui/test_mcp_oauth_api.py+++ b/tests/webui/test_mcp_oauth_api.py@@ -4,6 +4,7 @@ import asyncioimport pytest+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import MCPServerConfigfrom nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError, RuntimeMaintenanceErrorfrom nanobot.webui.mcp_oauth_api import (@@ -50,14 +51,19 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_connection = _Connection()received: dict[str, object] = {}reload_calls = 0+ cfg = _config()+ cfg.use_proxy = True+ network_config = NetworkConfig(proxy="http://proxy-a.example:8080")monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target",lambda _url: (True, ""),)- async def connect(servers, _registry, *, oauth_handlers):+ async def connect(servers, _registry, *, oauth_handlers, network):assert set(servers) == {"xmind"}+ received["cfg"] = servers["xmind"]+ received["network"] = networkhandlers = oauth_handlers["xmind"]await handlers.redirect_handler("https://accounts.example.com/authorize?client_id=test&state=state-123"@@ -86,13 +92,20 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_started = await manager.start("xmind",- _config(),+ cfg,"https://agent.example.com/auth/mcp/callback",reload_mcp=reload_mcp,+ network=network_config,)assert started["status"] == "authorization_required"assert started["authorization_url"].startswith("https://accounts.example.com/authorize?")+ cfg.use_proxy = False+ network_config.proxy = "http://proxy-b.example:8080"+ assert received["cfg"] is not cfg+ assert received["cfg"].use_proxy is True+ assert received["network"] is not network_config+ assert received["network"].proxy == "http://proxy-a.example:8080"manager.submit_callback(state="state-123", code="oauth-code", error=None)with pytest.raises(McpOAuthError, match="expired"):manager.submit_callback(state="state-123", code="replayed-code", error=None)@@ -135,7 +148,7 @@ async def test_browser_flow_activates_tools_before_probe_cleanup_completes(lambda _url: (True, ""),)- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):handlers = oauth_handlers["linear"]await handlers.redirect_handler("https://accounts.example.com/authorize?client_id=test&state=blocked-close"@@ -202,7 +215,7 @@ async def test_browser_flow_remains_busy_through_cancelled_or_expired_cleanup(if expire:monkeypatch.setattr("nanobot.webui.mcp_oauth_api._FLOW_TTL_S", 0)- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):handlers = oauth_handlers["linear"]await handlers.redirect_handler("https://accounts.example.com/auth?state=pending")try:@@ -256,7 +269,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(lambda _url: (True, ""),)- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):handlers = oauth_handlers["linear"]received["redirect_uri"] = handlers.redirect_uriawait handlers.redirect_handler(@@ -329,7 +342,7 @@ async def test_browser_flow_surfaces_provider_denial_without_callback_descriptiolambda _url: (True, ""),)- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):handlers = oauth_handlers["notion"]await handlers.redirect_handler("https://accounts.example.com/auth?state=deny-state")await handlers.callback_handler()@@ -375,7 +388,7 @@ async def test_browser_flow_blocks_unsafe_authorization_url(lambda _url: (url_is_safe, "private address"),)- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):await oauth_handlers["linear"].redirect_handler(authorization_url)return {}diff --git a/tests/webui/test_mcp_presets_api.py b/tests/webui/test_mcp_presets_api.pyindex 2593f1cea..07784fb35 100644--- a/tests/webui/test_mcp_presets_api.py+++ b/tests/webui/test_mcp_presets_api.py@@ -359,11 +359,12 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(monkeypatch: pytest.MonkeyPatch,) -> None:_use_config(tmp_path, monkeypatch)- name, cfg = ensure_mcp_oauth_server(+ name, cfg, network = ensure_mcp_oauth_server({"name": ["metabase"], "mcp_url": ["https://analytics.example.com/api/metabase-mcp"]})assert name == "metabase"assert cfg.auth == "oauth"+ assert network == load_config().networkassert cfg.url == "https://analytics.example.com/api/metabase-mcp"row = next(item for item in mcp_presets_payload()["presets"] if item["name"] == name)assert row["installed"] is True@@ -372,7 +373,7 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(config = load_config()config.tools.mcp_servers[name].enabled_tools = ["search"]save_config(config)- _, updated = ensure_mcp_oauth_server(+ _, updated, _network = ensure_mcp_oauth_server({"name": [name], "mcp_url": ["https://other.example.com/api/metabase-mcp"]})assert updated.url == "https://other.example.com/api/metabase-mcp"@@ -615,7 +616,7 @@ def test_test_mcp_preset_connects_and_reports_tools(async def aclose(self) -> None:return None- async def fake_connect(servers, registry):+ async def fake_connect(servers, registry, *, network):assert list(servers) == ["playwright"]class FakeTool:@@ -652,7 +653,7 @@ def test_test_mcp_preset_inspects_tools_outside_the_enabled_allowlist(async def aclose(self) -> None:return None- async def fake_connect(servers, registry):+ async def fake_connect(servers, registry, *, network):assert servers["playwright"].enabled_tools == ["*"]class FakeTool:@@ -689,7 +690,7 @@ def test_test_mcp_preset_scrubs_connection_errors(},)- async def fake_connect(_servers, _registry):+ async def fake_connect(_servers, _registry, *, network):raise RuntimeError("failed https://mcp.browserbase.com/mcp?browserbaseApiKey=bb_live_secret")monkeypatch.setattr("nanobot.agent.tools.mcp.connect_mcp_servers", fake_connect)@@ -930,3 +931,146 @@ def test_normalize_mcp_mentions_uses_explicit_gateway_config()assert payload == [{"name": "gateway-docs", "display_name": "Gateway docs"}]++[email protected]("installed", [False, True], ids=["first-authorization", "existing-preset"])+def test_oauth_setup_persists_proxy_choice_without_credential_fields(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+ installed: bool,+) -> None:+ _use_config(tmp_path, monkeypatch)+ config = load_config()+ config.network.proxy = "http://shared.example:8080"+ save_config(config)+ if installed:+ mcp_presets_action("enable", {"name": ["xmind"]})++ name, cfg, network = ensure_mcp_oauth_server({+ "name": ["xmind"], "use_proxy": ["true"],+ })++ assert name == "xmind"+ assert cfg.use_proxy is True+ assert cfg.auth == "oauth"+ assert network.proxy == "http://shared.example:8080"+ assert load_config().tools.mcp_servers[name].use_proxy is True+ payload = mcp_presets_payload()+ row = next(item for item in payload["presets"] if item["name"] == name)+ assert row["use_proxy"] is True+ assert row["status"] == "authorization_required"+ assert payload["proxy_configured"] is True+ assert "shared.example" not in json.dumps(payload)++ _, updated, _ = ensure_mcp_oauth_server({"name": [name], "use_proxy": ["false"]})+ assert updated.use_proxy is False+ assert load_config().tools.mcp_servers[name].use_proxy is False++[email protected]("name", ["xmind", "custom-docs"])+def test_proxy_action_preserves_existing_server_and_materializes_presets(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+ name: str,+) -> None:+ _use_config(tmp_path, monkeypatch)+ config = load_config()+ config.network.proxy = "http://shared.example:8080"+ save_config(config)+ if name == "custom-docs":+ custom_mcp_action("custom", {+ "name": [name], "url": ["https://docs.example.com/mcp"],+ "headers": ['{"Authorization": "Bearer preserved-secret"}'],+ "enabled_tools": ['["search"]'], "tool_timeout": ["90"],+ })++ payload = mcp_presets_action("proxy", {"name": [name], "use_proxy": ["true"]})+ before = load_config().tools.mcp_servers[name]+ assert before.use_proxy is True+ assert payload["requires_restart"] is True+ assert next(row for row in payload["presets"] if row["name"] == name)["use_proxy"] is True++ mcp_presets_action("proxy", {"name": [name], "use_proxy": ["false"]})+ after = load_config().tools.mcp_servers[name]+ assert after.use_proxy is False+ assert after.model_dump(exclude={"use_proxy"}) == before.model_dump(exclude={"use_proxy"})+ if name == "custom-docs":+ assert after.headers == {"Authorization": "Bearer preserved-secret"}+ assert after.enabled_tools == ["search"]+ assert after.tool_timeout == 90++[email protected]("transport", ["sse", "streamableHttp"])+def test_custom_server_saves_explicit_proxy_flag(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+ transport: str,+) -> None:+ _use_config(tmp_path, monkeypatch)+ config = load_config()+ config.network.proxy = "http://shared.example:8080"+ save_config(config)+ payload = custom_mcp_action("custom", {+ "name": ["company-docs"], "transport": [transport],+ "url": ["https://docs.example.com/mcp"], "use_proxy": ["true"],+ })+ assert load_config().tools.mcp_servers["company-docs"].use_proxy is True+ assert next(row for row in payload["presets"] if row["name"] == "company-docs")["use_proxy"] is True++[email protected]("use_proxy", [False, True])+def test_import_preserves_boolean_proxy_flag(tmp_path, monkeypatch, use_proxy: bool) -> None:+ _use_config(tmp_path, monkeypatch)+ config = load_config()+ config.network.proxy = "http://shared.example:8080"+ save_config(config)+ custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {+ "company-docs": {"url": "https://docs.example.com/mcp", "useProxy": use_proxy},+ }})]})+ assert load_config().tools.mcp_servers["company-docs"].use_proxy is use_proxy++[email protected]("invalid", ["true", "false", 1, None])+def test_import_rejects_nonboolean_proxy_flag_without_saving(tmp_path, monkeypatch, invalid) -> None:+ _use_config(tmp_path, monkeypatch)+ with pytest.raises(McpPresetError, match="useProxy must be a boolean"):+ custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {+ "valid-first": {"url": "https://docs.example.com/mcp"},+ "bad-flag": {"url": "https://docs.example.com/mcp", "useProxy": invalid},+ }})]})+ assert load_config().tools.mcp_servers == {}++[email protected]("action", ["enable", "proxy", "oauth", "custom", "import"])+def test_explicit_proxy_requires_shared_address_before_saving(tmp_path, monkeypatch, action) -> None:+ _use_config(tmp_path, monkeypatch)+ with pytest.raises(McpPresetError, match="Configure the shared proxy"):+ if action == "oauth":+ ensure_mcp_oauth_server({"name": ["xmind"], "use_proxy": ["true"]})+ elif action == "custom":+ custom_mcp_action("custom", {+ "name": ["company-docs"], "url": ["https://docs.example.com/mcp"],+ "use_proxy": ["true"],+ })+ elif action == "import":+ custom_mcp_action("import", {"config": [json.dumps({+ "company-docs": {"url": "https://docs.example.com/mcp", "useProxy": True},+ })]})+ else:+ mcp_presets_action(action, {"name": ["xmind"], "use_proxy": ["true"]})+ assert load_config().tools.mcp_servers == {}+ assert mcp_presets_payload()["proxy_configured"] is False+++def test_enable_preset_preserves_proxy_choice_on_later_enable(tmp_path, monkeypatch) -> None:+ _use_config(tmp_path, monkeypatch)+ config = load_config()+ config.network.proxy = "http://shared.example:8080"+ save_config(config)++ mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["true"]})+ assert load_config().tools.mcp_servers["xmind"].use_proxy is True+ mcp_presets_action("enable", {"name": ["xmind"]})+ assert load_config().tools.mcp_servers["xmind"].use_proxy is True+ mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["false"]})+ assert load_config().tools.mcp_servers["xmind"].use_proxy is Falsediff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.pyindex abb039bf6..69181fbb1 100644--- a/tests/webui/test_settings_api.py+++ b/tests/webui/test_settings_api.py@@ -906,7 +906,8 @@ def test_create_provider_settings_persists_custom_advanced_options(monkeypatch: pytest.MonkeyPatch,) -> None:config_path = tmp_path / "config.json"- save_config(Config(), config_path)+ config = Config.model_validate({"network": {"proxy": "http://127.0.0.1:7890"}})+ save_config(config, config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)payload = create_provider_settings(@@ -914,7 +915,7 @@ def test_create_provider_settings_persists_custom_advanced_options("name": ["Company Gateway"],"apiBase": ["https://gateway.example/v1"],"apiKey": ["sk-company"],- "proxy": ["http://127.0.0.1:7890"],+ "use_proxy": ["true"],"extraHeaders": [json.dumps({"X-Tenant": "engineering"})],"extraBody": [json.dumps({"service_tier": "priority"})],"extraQuery": [json.dumps({"api-version": "2026-01-01"})],@@ -930,7 +931,7 @@ def test_create_provider_settings_persists_custom_advanced_options("extra_headers","extra_body","extra_query",- "proxy",+ "use_proxy","thinking_style",]assert row["extra_headers"] == {"X-Tenant": "engineering"}@@ -941,7 +942,8 @@ def test_create_provider_settings_persists_custom_advanced_options(assert saved.display_name == "Company Gateway"assert saved.api_key == "sk-company"assert saved.api_base == "https://gateway.example/v1"- assert saved.proxy == "http://127.0.0.1:7890"+ assert saved.use_proxy is True+ assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"assert saved.extra_headers == {"X-Tenant": "engineering"}assert saved.extra_body == {"service_tier": "priority"}assert saved.extra_query == {"api-version": "2026-01-01"}@@ -1023,6 +1025,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(config_path = tmp_path / "config.json"config = Config()config.providers.openai.api_key = "sk-openai"+ config.network.proxy = "http://127.0.0.1:7890"save_config(config, config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)@@ -1030,7 +1033,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options({"provider": ["openai"],"apiType": ["responses"],- "proxy": ["http://127.0.0.1:7890"],+ "use_proxy": ["true"],"extraHeaders": [json.dumps({"X-Trace": "enabled"})],"extraBody": [json.dumps({"service_tier": "priority"})],"extraQuery": [json.dumps({"trace": "true"})],@@ -1047,7 +1050,8 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(saved = load_config(config_path)assert saved.providers.openai.api.to_capabilities().preferred_api == "responses"- assert saved.providers.openai.proxy == "http://127.0.0.1:7890"+ assert saved.providers.openai.use_proxy is True+ assert saved.network.proxy == "http://127.0.0.1:7890"assert saved.providers.openai.extra_headers == {"X-Trace": "enabled"}assert saved.providers.openai.extra_body == {"service_tier": "priority"}assert saved.providers.openai.extra_query == {"trace": "true"}@@ -1071,7 +1075,7 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy() -> None:config_path = tmp_path / "config.json"config = Config()- getattr(config.providers, config_attr).proxy = "http://127.0.0.1:7000"+ config.network.proxy = "http://127.0.0.1:7890"save_config(config, config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)monkeypatch.setattr(@@ -1087,24 +1091,24 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy(payload = update_provider_settings({"provider": [provider_name],- "proxy": [" http://127.0.0.1:7890 "],+ "use_proxy": ["true"],"extraBody": [json.dumps({"tools": []})],})providers = {row["name"]: row for row in payload["providers"]}- assert providers[provider_name]["proxy"] == "http://127.0.0.1:7890"- assert getattr(load_config(config_path).providers, config_attr).proxy == (- "http://127.0.0.1:7890"- )+ assert providers[provider_name]["use_proxy"] is True+ assert getattr(load_config(config_path).providers, config_attr).use_proxy is True+ assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"assert providers[provider_name]["extra_body"] == {"tools": []}assert getattr(load_config(config_path).providers, config_attr).extra_body == {"tools": []}- cleared = update_provider_settings({"provider": [provider_name], "proxy": [" "]})+ cleared = update_provider_settings({"provider": [provider_name], "use_proxy": ["false"]})providers = {row["name"]: row for row in cleared["providers"]}- assert providers[provider_name]["proxy"] is None- assert getattr(load_config(config_path).providers, config_attr).proxy is None+ assert providers[provider_name]["use_proxy"] is False+ assert getattr(load_config(config_path).providers, config_attr).use_proxy is False+ assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"def test_update_provider_settings_keeps_oauth_credentials_read_only(@@ -1115,7 +1119,7 @@ def test_update_provider_settings_keeps_oauth_credentials_read_only(save_config(Config(), config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)- with pytest.raises(WebUISettingsError, match="only supports proxy and extra_body settings"):+ with pytest.raises(WebUISettingsError, match="only supports use_proxy and extra_body settings"):update_provider_settings({"provider": ["openai_codex"], "apiKey": ["not-allowed"]})@@ -1930,7 +1934,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(proxy = "http://127.0.0.1:23458"config_path = tmp_path / "config.json"save_config(- Config.model_validate({"providers": {"openaiCodex": {"proxy": "${CODEX_PROXY_TEST}"}}}),+ Config.model_validate({"network": {"proxy": "${CODEX_PROXY_TEST}"}, "providers": {"openaiCodex": {"useProxy": True}}}),config_path,)monkeypatch.setenv("CODEX_PROXY_TEST", proxy)@@ -2112,7 +2116,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy() -> None:proxy = "http://127.0.0.1:23458"config_path = tmp_path / "config.json"- save_config(Config.model_validate({"providers": {"xaiGrok": {"proxy": proxy}}}), config_path)+ save_config(Config.model_validate({"network": {"proxy": proxy}, "providers": {"xaiGrok": {"useProxy": True}}}), config_path)monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)captured: dict[str, object] = {}diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.pyindex 792a3981d..8d3259e11 100644--- a/tests/webui/test_settings_routes.py+++ b/tests/webui/test_settings_routes.py@@ -14,6 +14,7 @@ from websockets.datastructures import Headersfrom nanobot.bus.queue import MessageBusfrom nanobot.config.loader import get_config_path+from nanobot.config.network import NetworkConfigfrom nanobot.config.schema import MCPServerConfigfrom nanobot.runtime_admission import RuntimeBusyErrorfrom nanobot.webui.http_utils import http_json_response@@ -413,12 +414,12 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admissconfig = MCPServerConfig(type="streamableHttp", auth="oauth", url="https://mcp.example/mcp")monkeypatch.setattr("nanobot.webui.settings_routes.ensure_mcp_oauth_server",- lambda _query, *, config_path=None: ("linear", config),+ lambda _query, *, config_path=None: ("linear", config, NetworkConfig()),)monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()- async def connect(_servers, _registry, *, oauth_handlers):+ async def connect(_servers, _registry, *, oauth_handlers, network):handlers = oauth_handlers["linear"]await handlers.redirect_handler("https://accounts.example/authorize?state=settings")try:@@ -457,9 +458,10 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeauth="oauth",url="https://app.xmind.com/api/mcp",)+ network = SimpleNamespace(proxy="http://shared.example:8080")monkeypatch.setattr("nanobot.webui.settings_routes.ensure_mcp_oauth_server",- lambda _query, *, config_path=None: ("xmind", config),+ lambda _query, *, config_path=None: ("xmind", config, network),)router = _router()start = AsyncMock(return_value={@@ -484,6 +486,7 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeconfig,"https://gateway.example/auth/mcp/callback",reload_mcp=ANY,+ network=network,reset_credentials=False,)@@ -1040,3 +1043,103 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, enabled):reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path)assert json.loads(reverted.body)["requires_restart"] is Falseassert json.loads(reverted.body)["restart_required_sections"] == []+++async def test_first_mcp_oauth_request_saves_proxy_flag_before_starting_flow(tmp_path) -> None:+ from nanobot.config.loader import load_config++ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps({+ "network": {"proxy": "http://shared.example:8080"},+ "agents": {"defaults": {"workspace": str(tmp_path / "workspace")}},+ }), encoding="utf-8")+ router = _router(config_path=config_path)+ captured = {}++ async def start(name, cfg, redirect_uri, *, reload_mcp, network, reset_credentials):+ saved = load_config(config_path)+ assert name == "xmind"+ assert cfg.auth == "oauth"+ assert cfg.use_proxy is True+ assert saved.tools.mcp_servers[name].use_proxy is True+ assert network == saved.network+ captured["network"] = network.proxy+ return {"status": "authorization_required", "name": name, "flow_id": "first-flow"}++ router._mcp_oauth = SimpleNamespace(start=start)+ request = _mutation_request(+ "/api/settings/mcp-oauth/start",+ {"name": "xmind", "use_proxy": True},+ )+ response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start")++ assert response is not None+ assert response.status_code == 200+ assert json.loads(response.body)["flow_id"] == "first-flow"+ assert captured == {"network": "http://shared.example:8080"}++[email protected]("use_proxy", [True, False])+async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_proxy: bool,+) -> None:+ from mcp.shared.auth import OAuthToken+ from websockets.http11 import Request++ from nanobot.agent.tools.mcp_oauth import MCPOAuthStorage+ from nanobot.bus.queue import MessageBus+ from nanobot.channels.websocket.runtime import WebSocketConfig+ from nanobot.config.loader import load_config, save_config+ from nanobot.config.schema import Config+ from nanobot.webui.gateway_services import build_gateway_services++ monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)+ config_path = tmp_path / "config.json"+ config = Config.model_validate({+ "network": {"proxy": "http://proxy.example:8080"},+ "tools": {"mcpServers": {"team-docs": {+ "type": "streamableHttp", "auth": "oauth",+ "url": "https://mcp.example.com/mcp", "useProxy": not use_proxy,+ "headers": {"X-Organization": "team"}, "enabledTools": ["read"],+ }}},+ })+ save_config(config, config_path)+ original = config.tools.mcp_servers["team-docs"].model_copy(deep=True)+ storage = MCPOAuthStorage("team-docs", original.url)+ await storage.set_tokens(OAuthToken(access_token="synthetic-access", token_type="Bearer"))++ async def reload_mcp() -> dict[str, object]:+ assert load_config(config_path).tools.mcp_servers["team-docs"].use_proxy is use_proxy+ return {"ok": True, "connected": ["team-docs"], "requires_restart": False}++ reload = AsyncMock(side_effect=reload_mcp)+ gateway = build_gateway_services(+ config=WebSocketConfig(), bus=MessageBus(), session_manager=None,+ static_dist_path=None, workspace_path=tmp_path, config_path=config_path,+ default_restrict_to_workspace=True, runtime_model_name=None,+ runtime_surface="browser", runtime_capabilities_overrides=None, mcp_reload=reload,+ )+ connection = SimpleNamespace(+ remote_address=("127.0.0.1", 12345),+ request=Request("/", Headers({"Host": "127.0.0.1:8765"})),+ )+ path = "/api/settings/mcp-presets/proxy"+ try:+ http_response = await gateway.http.dispatch(connection, Request(path, Headers()))+ assert http_response.status_code == 405+ response = await gateway.http.dispatch_webui_mutation(+ connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()},+ )+ assert response.status_code == 200+ payload = json.loads(response.body)+ assert payload["hot_reload"]["ok"] is True+ assert payload["requires_restart"] is False+ row = next(row for row in payload["presets"] if row["name"] == "team-docs")+ assert row["use_proxy"] is use_proxy+ assert load_config(config_path).tools.mcp_servers["team-docs"] == original.model_copy(update={"use_proxy": use_proxy})+ assert storage.has_credentials() is True+ reload.assert_awaited_once()+ finally:+ await gateway.http.settings_routes.close()diff --git a/tests/webui/test_settings_runtime.py b/tests/webui/test_settings_runtime.pyindex 2dee494a2..0528e8cfc 100644--- a/tests/webui/test_settings_runtime.py+++ b/tests/webui/test_settings_runtime.py@@ -16,20 +16,32 @@ from nanobot.webui.settings_runtime import (from nanobot.webui.settings_services import WebUISettingsServices-def test_web_proxy_roundtrip_while_disabled_preserves_model_proxy(tmp_path):+def test_shared_proxy_roundtrip_preserves_independent_feature_switches(tmp_path):path = tmp_path / "config.json"config = Config()config.tools.web.enable = False- config.providers.openai.proxy = "http://model-proxy.example:8080"+ config.providers.openai.use_proxy = Truesave_config(config, path)- for proxy in ("http://web-proxy.example:7890", None):- payload = update_runtime_config_settings({"tools.web.proxy": proxy}, local_browser=True, config_path=path)- assert payload["runtime_config"]["tools.web.proxy"] == proxy+ for proxy in ("http://shared-proxy.example:7890", "http://shared-proxy.example:7891"):+ payload = update_runtime_config_settings({"network.proxy": proxy}, local_browser=True, config_path=path)+ assert payload["runtime_config"]["network.proxy"] == proxyassert payload["requires_restart"]saved = load_config(path)- assert saved.tools.web.proxy == proxy+ assert saved.network.proxy == proxyassert saved.tools.web.enable is False- assert saved.providers.openai.proxy == "http://model-proxy.example:8080"+ assert saved.tools.web.use_proxy is False+ assert saved.providers.openai.use_proxy is True+ update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)+ assert load_config(path).tools.web.use_proxy is True+++def test_enabling_web_proxy_without_an_address_preserves_config(tmp_path):+ path = tmp_path / "config.json"+ save_config(Config(), path)+ before = path.read_bytes()+ with pytest.raises(WebUISettingsError, match="Advanced"):+ update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)+ assert path.read_bytes() == beforedef test_runtime_patch_persists_and_preserves_other_domains(tmp_path):@@ -158,7 +170,7 @@ def test_timezone_auto_and_nullable_fields():}}})assert update_runtime_config(config, {"agents.defaults.timezone_mode": "auto",- "tools.web.proxy": None,+ "network.proxy": None,}, local_browser=True)assert config.agents.defaults.timezone_mode == "auto"assert config.agents.defaults.dream.cron == "0 2 * * *"diff --git a/webui/browser/skeleton-additions.spec.ts b/webui/browser/skeleton-additions.spec.tsindex a20629122..a8de47833 100644--- a/webui/browser/skeleton-additions.spec.ts+++ b/webui/browser/skeleton-additions.spec.ts@@ -74,14 +74,18 @@ for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {await settle(page);const selector = section === "overview" ? "section button.group" : section === "models" ? '[data-testid^="model-call-order-row"], .settings-footer' : section === "about" ? ".settings-list-row" : ".settings-row";const notificationDetails = section === "notifications" ? ", .settings-list-inset > .border-t, section > p" : "";- const loaded = await boxes(target.locator(selector + notificationDetails));+ const proxyForm = section === "advanced" ? ", [data-shared-proxy-editor]" : "";+ const loaded = await boxes(target.locator(selector + notificationDetails + proxyForm));+ const proxyAddress = section === "advanced" ? await boxes(target.locator('[data-shared-proxy-editor] input')) : null;const loadedControls = section === "notifications" ? await boxes(target.getByRole("switch")) : null;const readingControl = section === "appearance" ? await boxes(target.getByRole("radiogroup")) : null;await page.goto(fixture("settings", "loading", extra));await settle(page);const skeletonSelector = section === "overview" ? "[data-overview-skeleton-row]" : section === "models" ? "[data-model-preset-skeleton], .settings-footer" : section === "about" ? ".settings-list-row" : "[data-settings-skeleton-row]";- const skeleton = await boxes(target.locator(skeletonSelector + notificationDetails));+ const proxySkeleton = section === "advanced" ? ", [data-shared-proxy-skeleton]" : "";+ const skeleton = await boxes(target.locator(skeletonSelector + notificationDetails + proxySkeleton));sameBoxes(skeleton, loaded, section);+ if (proxyAddress) sameBoxes(await boxes(target.locator("[data-proxy-address-skeleton]")), proxyAddress, "shared proxy address");if (readingControl) sameBoxes(await boxes(target.locator("[data-skeleton-reading-size]")), readingControl);if (loadedControls) {const skeletonControls = await boxes(target.locator("[data-skeleton-switch]"));diff --git a/webui/src/channel-plugins/catalog.ts b/webui/src/channel-plugins/catalog.tsindex 4b44e7e39..d9050047c 100644--- a/webui/src/channel-plugins/catalog.ts+++ b/webui/src/channel-plugins/catalog.ts@@ -44,6 +44,7 @@ type ChannelCatalogSetupPresentation = {export type ChannelFieldPresentation = {key: string;section?: string;+ control?: "switch";};export type ChannelFieldSection =@@ -87,6 +88,7 @@ export type ChannelConfigField = {kind?: "string" | "secret" | "int" | "bool" | "list" | "enum" | string;section?: string;defaultValue?: string;+ control?: "switch";options?: ChannelConfigOption[];};diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsxindex 58390b816..0ac1cbad6 100644--- a/webui/src/components/settings/SettingsPage.tsx+++ b/webui/src/components/settings/SettingsPage.tsx@@ -6,6 +6,7 @@ import type { SettingsExitGuard } from "@/components/settings/contracts";import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";import type { EditCompletion } from "@/components/settings/shared/useEditCompletion";+import { SharedProxySetupDialog } from "@/components/settings/shared/SharedProxySetupDialog";import { SettingsSectionSkeleton } from "@/components/settings/shared/SettingsSectionSkeleton";import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";@@ -94,6 +95,7 @@ export function SettingsPage({const [mcpSetupName, setMcpSetupName] = useState<string | null>(null);const presetDeletedCallback = useRef<(() => void) | null>(null);const [providerPanel, setProviderPanel] = useState<ProviderSettingsEntry | null>(null);+ const [proxySetupOpen, setProxySetupOpen] = useState(false);const providerSetupOrigin = useRef<{trigger: HTMLButtonElement | null;onAdded?: (provider: string) => void;@@ -129,6 +131,9 @@ export function SettingsPage({transcriptionDirty,} = controller;const { providerOAuthFlow } = modelState;+ const configureProxy = settings?.runtime_config && !String(settings.runtime_config["network.proxy"] ?? "").trim()+ ? () => setProxySetupOpen(true)+ : undefined;const restartInProgress = isRestarting || hostEngineApplying;const latestExitState = useRef({ requiresRestart: settings?.requires_restart, restartInProgress });@@ -327,6 +332,7 @@ export function SettingsPage({}}/>{providerPanel ? <ProvidersSettings+ onConfigureProxy={configureProxy}entry={providerPanel}onClose={() => setProviderPanel(null)}onProviderAdded={providerSetupOrigin.current?.onAdded@@ -518,6 +524,7 @@ export function SettingsPage({return (<div className="settings-stack"><AppsCatalogSettings+ onConfigureProxy={configureProxy}setupName={mcpSetupName}onSetupOpened={() => setMcpSetupName(null)}cliApps={systemState.cliApps}@@ -793,6 +800,11 @@ export function SettingsPage({</div></div></div>+ {proxySetupOpen ? <SharedProxySetupDialog+ busy={controller.runtimeConfigState.saving !== null}+ onClose={() => setProxySetupOpen(false)}+ onSave={controller.runtimeConfigState.saveProxy}+ /> : null}</DialogLayoutContext.Provider>);}diff --git a/webui/src/components/settings/channels/ChannelIdentity.tsx b/webui/src/components/settings/channels/ChannelIdentity.tsxindex f085e1442..cfa042569 100644--- a/webui/src/components/settings/channels/ChannelIdentity.tsx+++ b/webui/src/components/settings/channels/ChannelIdentity.tsx@@ -47,6 +47,7 @@ export function channelSetup(): ChannelConfigField => ({...localizeField(field.key),section: field.section,+ control: field.control,});const presentation: ChannelSetupPresentation = {...definition,diff --git a/webui/src/components/settings/channels/CredentialForm.tsx b/webui/src/components/settings/channels/CredentialForm.tsxindex d771705e8..53ab2f20a 100644--- a/webui/src/components/settings/channels/CredentialForm.tsx+++ b/webui/src/components/settings/channels/CredentialForm.tsx@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";import type { ChannelConfigField } from "@/channel-plugins/catalog";+import { ToggleButton } from "@/components/ui/toggle-button";import { cn } from "@/lib/utils";function channelFieldValue(field: ChannelConfigField, values: Record<string, string>): string {@@ -129,6 +130,25 @@ export function CredentialForm({{error}</span>) : null;+ if (field.control === "switch" && field.kind === "bool") {+ return (+ <div key={field.key} className="flex items-center justify-between gap-4 py-2">+ <label htmlFor={inputId} className="min-w-0">{header}</label>+ <div className="flex shrink-0 items-center gap-2">+ {errorMessage}+ <ToggleButton+ id={inputId}+ checked={selectedOption === "true"}+ disabled={disabled}+ aria-invalid={Boolean(error)}+ aria-describedby={describedBy}+ label={field.label}+ onChange={(checked) => onChange(field.key, String(checked))}+ />+ </div>+ </div>+ );+ }if (field.options?.length) {return (<fieldsetdiff --git a/webui/src/components/settings/models/ProviderSettings.tsx b/webui/src/components/settings/models/ProviderSettings.tsxindex e37abdd89..67ca2e99d 100644--- a/webui/src/components/settings/models/ProviderSettings.tsx+++ b/webui/src/components/settings/models/ProviderSettings.tsx@@ -25,6 +25,7 @@ import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";import { Button } from "@/components/ui/button";import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { ProxySettingsControl } from "@/components/settings/shared/ProxySettingsControl";import {Dialog,DialogContent,@@ -107,7 +108,7 @@ const CUSTOM_PROVIDER_ADVANCED_FIELDS: ProviderAdvancedField[] = ["extra_headers","extra_body","extra_query",- "proxy",+ "use_proxy","thinking_style",];@@ -381,11 +382,13 @@ function ProviderRequestOptions({}function ProviderAdvancedOptions({+ onConfigureProxy,fields,form,onChange,children,}: {+ onConfigureProxy?: () => void;fields: ProviderAdvancedField[];form: ProviderForm;onChange: (value: Partial<ProviderForm>) => void;@@ -466,22 +469,13 @@ function ProviderAdvancedOptions({</DropdownMenu></label>) : null}- {enabled.has("proxy") ? (- <label className="block space-y-1.5 md:col-span-2">- <span className="block px-3 text-[12px] font-medium text-muted-foreground">- {tx("settings.providers.proxy", "Network proxy")}- </span>- <Input- value={form.proxy}- onChange={(event) => onChange({ proxy: event.target.value })}- placeholder="http://127.0.0.1:7890"- autoCapitalize="none"- autoComplete="off"- autoCorrect="off"- spellCheck={false}- className="h-9 rounded-full font-mono text-[12px]"- />- </label>+ {enabled.has("use_proxy") ? (+ <ProxySettingsControl+ className="px-3 py-2 md:col-span-2"+ checked={form.useProxy}+ onChange={(useProxy) => onChange({ useProxy })}+ onConfigure={onConfigureProxy}+ />) : null}{enabled.has("region") ? (<label className="block space-y-1.5">@@ -535,6 +529,7 @@ type ProviderSettingsView =| { kind: "provider"; name: string; adding: boolean };export function ProvidersSettings({+ onConfigureProxy,entry,onClose,onCloseAutoFocus,@@ -560,6 +555,7 @@ export function ProvidersSettings({onProviderOAuthLogout,}: {entry: ProviderSettingsEntry;+ onConfigureProxy?: () => void;onClose: () => void;onCloseAutoFocus: (event: Event) => void;onProviderAdded?: (provider: string) => void;@@ -671,7 +667,7 @@ export function ProvidersSettings({const apiBase = form.apiBase.trim();const advancedFields = provider.advanced_fields ?? [];const oauthSettingsDirty = isOauthProvider && (- form.proxy.trim() !== (provider.proxy ?? "").trim()+ form.useProxy !== (provider.use_proxy ?? false)|| form.extraBody.trim() !== providerJsonValue(provider.extra_body).trim());const oauthSettingsSaving = saving && providerOperation?.action === "save";@@ -680,7 +676,7 @@ export function ProvidersSettings({const hasOptionalProviderSetting = Boolean(apiKey|| apiBase- || form.proxy.trim()+ || form.useProxy|| form.extraHeaders.trim()|| form.extraBody.trim()|| form.extraQuery.trim()@@ -787,6 +783,7 @@ export function ProvidersSettings({/>{supportsOauthAdvancedSettings ? (<ProviderAdvancedOptions+ onConfigureProxy={onConfigureProxy}fields={advancedFields}form={form}onChange={(value) => onChangeProviderForm(provider.name, value)}@@ -902,6 +899,7 @@ export function ProvidersSettings({onChange={(value) => onChangeProviderForm(provider.name, value)}/><ProviderAdvancedOptions+ onConfigureProxy={onConfigureProxy}fields={advancedFields}form={form}onChange={(value) => onChangeProviderForm(provider.name, value)}@@ -1039,6 +1037,7 @@ export function ProvidersSettings({</div></label><ProviderAdvancedOptions+ onConfigureProxy={onConfigureProxy}fields={CUSTOM_PROVIDER_ADVANCED_FIELDS}form={customProviderDraft}onChange={(value) =>diff --git a/webui/src/components/settings/models/providerForm.ts b/webui/src/components/settings/models/providerForm.tsindex 7402e1082..d8489734c 100644--- a/webui/src/components/settings/models/providerForm.ts+++ b/webui/src/components/settings/models/providerForm.ts@@ -8,7 +8,7 @@ export type ProviderForm = {apiKey: string;apiBase: string;api: ModelAPIConfig | null;- proxy: string;+ useProxy: boolean;extraHeaders: string;extraBody: string;extraQuery: string;@@ -43,7 +43,7 @@ export function providerFormFromRow(apiKey: "",apiBase: provider.api_base ?? provider.default_api_base ?? "",api: provider.api ?? null,- proxy: provider.proxy ?? "",+ useProxy: provider.use_proxy ?? false,extraHeaders: providerJsonValue(provider.extra_headers),extraBody: providerJsonValue(provider.extra_body),extraQuery: providerJsonValue(provider.extra_query),@@ -60,7 +60,7 @@ export function emptyCustomProviderDraft(): CustomProviderDraft {apiKey: "",apiBase: "",api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },- proxy: "",+ useProxy: false,extraHeaders: "",extraBody: "",extraQuery: "",diff --git a/webui/src/components/settings/models/useModelSettingsActions.ts b/webui/src/components/settings/models/useModelSettingsActions.tsindex 537020bd8..91359e466 100644--- a/webui/src/components/settings/models/useModelSettingsActions.ts+++ b/webui/src/components/settings/models/useModelSettingsActions.ts@@ -456,7 +456,7 @@ export function useModelSettingsActions({if (provider.provider_api_configurable) update.api = providerForm.api;}for (const field of provider.advanced_fields ?? []) {- if (field === "proxy") update.proxy = providerForm.proxy.trim();+ if (field === "use_proxy") update.use_proxy = providerForm.useProxy;if (field === "extra_headers") {update.extraHeaders = providerForm.extraHeaders.trim();}@@ -500,7 +500,7 @@ export function useModelSettingsActions({apiKey: draft.apiKey.trim() || undefined,apiBase: draft.apiBase.trim(),...(settings?.provider_api_configuration_supported ? { api: draft.api } : {}),- proxy: draft.proxy.trim(),+ use_proxy: draft.useProxy,extraHeaders: draft.extraHeaders.trim(),extraBody: draft.extraBody.trim(),extraQuery: draft.extraQuery.trim(),diff --git a/webui/src/components/settings/shared/ProxySettingsControl.tsx b/webui/src/components/settings/shared/ProxySettingsControl.tsxnew file mode 100644index 000000000..092dc748c--- /dev/null+++ b/webui/src/components/settings/shared/ProxySettingsControl.tsx@@ -0,0 +1,31 @@+import { useTranslation } from "react-i18next";++import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { Button } from "@/components/ui/button";+import { ToggleButton } from "@/components/ui/toggle-button";+import { cn } from "@/lib/utils";++export function ProxySettingsControl({ checked, disabled, onChange, onConfigure, className }: {+ checked: boolean;+ disabled?: boolean;+ onChange: (checked: boolean) => void;+ onConfigure?: () => void;+ className?: string;+}) {+ const { t } = useTranslation();+ return (+ <div data-proxy-control className={cn("flex items-center justify-between gap-4", className)}>+ <SettingsHint description={t("settings.network.useProxyHelp")}>+ <span className="block text-[13px] font-medium leading-5 text-foreground">{t("settings.network.useProxy")}</span>+ </SettingsHint>+ {onConfigure ? (+ <Button type="button" variant="outline" size="sm" onClick={onConfigure}+ className="h-7 shrink-0 rounded-full px-3 text-[13px] font-medium leading-5">+ {t("settings.network.configureProxy")}+ </Button>+ ) : (+ <ToggleButton checked={checked} disabled={disabled} onChange={onChange} label={t("settings.network.useProxy")} />+ )}+ </div>+ );+}diff --git a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsxindex 5ba1ef04d..d5023f206 100644--- a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx+++ b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx@@ -39,9 +39,23 @@ function Group({ controls }: { controls: Control[] }) {return <section><Title /><SettingsGroup>{controls.map((control, index) => <Row key={index} control={control} />)}</SettingsGroup></section>;}+function ProxyGroup() {+ return <section><Title /><SettingsGroup>+ <div className="px-4 py-4 sm:px-5">+ <div data-shared-proxy-skeleton className="w-full space-y-3">+ <div data-proxy-address-skeleton className={cn(block, "h-10 w-full rounded-control")} />+ <div className="flex h-7 items-center justify-between gap-3 py-1">+ <div className={cn(block, "h-3 w-40")} /><div className={cn(block, "h-3.5 w-3.5 shrink-0")} />+ </div>+ </div>+ </div>+ </SettingsGroup></section>;+}+function RuntimeGroups({ page }: { page: RuntimeConfigPage }) {return <>{RUNTIME_CONFIG_GROUPS.filter((group) => group.page === page).map((group) => group.id === "chat"? <Group key={group.id} controls={["switch", "segments"]} />+ : group.id === "proxy" ? <ProxyGroup key={group.id} />: <Group key={group.id} controls={RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group.id && (!field.when || field.when.value === true)).flatMap<Control>((field) =>field.kind === "idle-compaction" ? ["switch", "idle-timeout"] : [field.kind === "boolean" || field.kind === "toggle" ? "switch" : field.kind === "list" ? "edit" : field.kind === "duration" ? "duration" : "input",diff --git a/webui/src/components/settings/shared/SharedProxyEditor.tsx b/webui/src/components/settings/shared/SharedProxyEditor.tsxnew file mode 100644index 000000000..3fa6b56dc--- /dev/null+++ b/webui/src/components/settings/shared/SharedProxyEditor.tsx@@ -0,0 +1,56 @@+import { useState, type ComponentProps, type Ref } from "react";+import { ChevronDown } from "lucide-react";+import { useTranslation } from "react-i18next";++import { Input } from "@/components/ui/input";+import { changeProxyAddress, changeProxyAuthentication, isProxyUrlReference, splitProxyUrl } from "@/lib/proxy-url";+import { cn } from "@/lib/utils";++type AddressProps = Pick<ComponentProps<typeof Input>, "id" | "aria-describedby" | "aria-invalid">;++export function SharedProxyEditor({ value, onChange, disabled, inputRef, addressProps, stackCredentials = false }: {+ value: string;+ onChange: (value: string) => void;+ disabled?: boolean;+ inputRef?: Ref<HTMLInputElement>;+ addressProps?: AddressProps;+ stackCredentials?: boolean;+}) {+ const { t } = useTranslation();+ const parts = splitProxyUrl(value);+ const [expanded, setExpanded] = useState<boolean | null>(null);+ const open = expanded ?? parts.userinfo !== null;+ const reference = isProxyUrlReference(parts.address);+ const credentialsDisabled = disabled || !parts.address.trim() || reference;+ return (+ <div data-shared-proxy-editor className="w-full space-y-3">+ <Input {...addressProps} ref={inputRef} aria-label={t("settings.runtimeConfig.fields.network_proxy.label")}+ type="text" value={parts.address} disabled={disabled} autoComplete="off" spellCheck={false}+ placeholder="http://127.0.0.1:7890" className="h-10 rounded-control text-[13px]"+ onChange={(event) => onChange(changeProxyAddress(value, event.target.value))} />+ <button type="button" aria-expanded={open} onClick={() => setExpanded(!open)}+ className="flex w-full items-center justify-between gap-3 rounded-sm py-1 text-[13px] font-medium leading-5 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {t("settings.network.authentication")}+ <ChevronDown aria-hidden className={cn("h-3.5 w-3.5 shrink-0 transition-transform motion-reduce:transition-none", open && "rotate-180")} />+ </button>+ {open ? reference ? (+ <p className="px-1 text-[12px] leading-5 text-muted-foreground">{t("settings.network.proxyReferenceAuth")}</p>+ ) : (+ <div className={cn("grid gap-4", !stackCredentials && "sm:grid-cols-2")}>+ <label className="block space-y-1">+ <span className="px-1 text-[13px] leading-5 text-muted-foreground">{t("settings.network.username")}</span>+ <Input type="text" value={parts.username} disabled={credentialsDisabled} autoComplete="off" spellCheck={false}+ className="h-10 rounded-control text-[13px]"+ onChange={(event) => { setExpanded(true); onChange(changeProxyAuthentication(value, event.target.value, parts.password)); }} />+ </label>+ <label className="block space-y-1">+ <span className="px-1 text-[13px] leading-5 text-muted-foreground">{t("settings.network.password")}</span>+ <Input type="password" value={parts.password} disabled={credentialsDisabled} autoComplete="new-password"+ className="h-10 rounded-control text-[13px]"+ onChange={(event) => { setExpanded(true); onChange(changeProxyAuthentication(value, parts.username, event.target.value)); }} />+ </label>+ </div>+ ) : null}+ </div>+ );+}diff --git a/webui/src/components/settings/shared/SharedProxySetupDialog.tsx b/webui/src/components/settings/shared/SharedProxySetupDialog.tsxnew file mode 100644index 000000000..592e90fb3--- /dev/null+++ b/webui/src/components/settings/shared/SharedProxySetupDialog.tsx@@ -0,0 +1,68 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";++import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { SharedProxyEditor } from "@/components/settings/shared/SharedProxyEditor";++export function SharedProxySetupDialog({ onClose, onSave, busy }: {+ busy: boolean;+ onClose: () => void;+ onSave: (address: string) => Promise<void>;+}) {+ const { t } = useTranslation();+ const [address, setAddress] = useState("");+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState("");+ const input = useRef<HTMLInputElement>(null);+ const origin = useRef(document.activeElement?.closest("[data-proxy-control]") ?? null);+ const title = t("settings.runtimeConfig.fields.network_proxy.label");+ useEffect(() => { if (error && !saving) input.current?.focus(); }, [error, saving]);+ const save = async () => {+ if (saving || busy || !address.trim()) return;+ setSaving(true);+ setError("");+ try {+ await onSave(address);+ onClose();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setSaving(false);+ }+ };+ return (+ <Dialog open onOpenChange={(open) => { if (!open && !saving) onClose(); }}>+ <DialogContent className="max-w-sm" showCloseButton={!saving}+ onOpenAutoFocus={(event) => { event.preventDefault(); input.current?.focus(); }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ const row = origin.current;+ const target = row?.querySelector<HTMLElement>('[role="switch"]') ?? row?.querySelector<HTMLElement>("button:last-child");+ target?.focus();+ }}+ onEscapeKeyDown={(event) => { if (saving) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (saving) event.preventDefault(); }}>+ <form className="space-y-4" onSubmit={(event) => { event.preventDefault(); void save(); }}>+ <DialogHeader>+ <DialogTitle className="pr-6 text-base">+ <SettingsHint description={t("settings.runtimeConfig.fields.network_proxy.help")}>{title}</SettingsHint>+ </DialogTitle>+ <DialogDescription>{t("settings.network.sharedProxyScope")}</DialogDescription>+ </DialogHeader>+ <div className="space-y-2">+ <SharedProxyEditor value={address} inputRef={input} disabled={saving} stackCredentials+ addressProps={{ "aria-invalid": Boolean(error), "aria-describedby": error ? "shared-proxy-setup-error" : undefined }}+ onChange={(next) => { setAddress(next); setError(""); }} />+ {error ? <p id="shared-proxy-setup-error" role="alert" className="break-words text-[13px] text-destructive">{error}</p> : null}+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" disabled={saving} onClick={onClose}>{t("settings.actions.cancel")}</Button>+ <Button type="submit" disabled={saving || busy || !address.trim()}>{saving ? t("settings.actions.saving") : t("settings.actions.save")}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/webui/src/components/settings/system/AppsSettings.tsx b/webui/src/components/settings/system/AppsSettings.tsxindex fbdfd9b5f..01ca41227 100644--- a/webui/src/components/settings/system/AppsSettings.tsx+++ b/webui/src/components/settings/system/AppsSettings.tsx@@ -32,6 +32,7 @@ import {import { useTranslation } from "react-i18next";import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";+import { ProxySettingsControl } from "@/components/settings/shared/ProxySettingsControl";import {DismissibleStatusMessage,@@ -84,6 +85,7 @@ export interface CustomMcpForm {env: string;headers: string;toolTimeout: string;+ useProxy: boolean;}export const DEFAULT_CUSTOM_MCP_FORM: CustomMcpForm = {@@ -96,11 +98,13 @@ export const DEFAULT_CUSTOM_MCP_FORM: CustomMcpForm = {env: "",headers: "",toolTimeout: "30",+ useProxy: false,};export function AppsCatalogSettings({setupName,onSetupOpened,+ onConfigureProxy,cliApps,mcpPresets,cliAppsLoading,@@ -146,6 +150,7 @@ export function AppsCatalogSettings({}: {setupName?: string | null;onSetupOpened?: () => void;+ onConfigureProxy?: () => void;cliApps: CliAppsPayload | null;mcpPresets: McpPresetsPayload | null;cliAppsLoading: boolean;@@ -172,7 +177,7 @@ export function AppsCatalogSettings({onQueryChange: (value: string) => void;onFilterChange: (value: AppsKindFilter) => void;onCliAction: (action: "install" | "update" | "uninstall" | "test", name: string) => void;- onMcpAction: (action: "enable" | "disable" | "remove" | "test" | "reconnect", name: string, values?: Record<string, string>) => void;+ onMcpAction: (action: "enable" | "disable" | "remove" | "test" | "reconnect" | "proxy", name: string, values?: Record<string, string>) => void;onMcpOAuthConnect: (name: string, reset?: boolean, values?: Record<string, string>) => void;onMcpOAuthCancel: () => void;onMcpOAuthOpen: () => void;@@ -325,6 +330,7 @@ export function AppsCatalogSettings({preset={item.preset}openConnection={setupName === item.preset.name}onConnectionOpened={onSetupOpened}+ onConfigureProxy={onConfigureProxy}values={mcpFieldValues[item.preset.name] ?? {}}actionKey={mcpActionKey}oauthFlow={mcpOAuthFlow?.name === item.preset.name ? mcpOAuthFlow : null}@@ -387,6 +393,7 @@ export function AppsCatalogSettings({{filter === "mcp" ? (<McpCustomServerPanel+ onConfigureProxy={onConfigureProxy}form={customMcpForm}configImport={mcpConfigImport}actionKey={mcpActionKey}@@ -494,6 +501,7 @@ function CliAppsCatalogRow({function McpAppsCatalogRow({openConnection = false,onConnectionOpened,+ onConfigureProxy,preset,values,actionKey,@@ -515,6 +523,7 @@ function McpAppsCatalogRow({}: {openConnection?: boolean;onConnectionOpened?: () => void;+ onConfigureProxy?: () => void;preset: McpPresetInfo;values: Record<string, string>;actionKey: string | null;@@ -526,7 +535,7 @@ function McpAppsCatalogRow({showBrandLogos: boolean;showTypeBadge: boolean;onFieldChange: (presetName: string, fieldName: string, value: string) => void;- onAction: (action: "enable" | "disable" | "remove" | "test" | "reconnect", name: string, values?: Record<string, string>) => void;+ onAction: (action: "enable" | "disable" | "remove" | "test" | "reconnect" | "proxy", name: string, values?: Record<string, string>) => void;onOAuthConnect: (name: string, reset?: boolean, values?: Record<string, string>) => void;onOAuthCancel: () => void;onOAuthOpen: () => void;@@ -552,7 +561,8 @@ function McpAppsCatalogRow({const toolsBusy = actionKey === `tools:${preset.name}`;const oauthBusy = actionKey === `oauth:${preset.name}`;const anotherOAuthBusy = Boolean(actionKey?.startsWith("oauth:")) && !oauthBusy;- const busy = enableBusy || disableBusy || removeBusy || testBusy || reconnectBusy || toolsBusy || oauthBusy;+ const proxyBusy = actionKey === `proxy:${preset.name}`;+ const busy = enableBusy || disableBusy || removeBusy || testBusy || reconnectBusy || toolsBusy || oauthBusy || proxyBusy;const agentPlugin = preset.source === "agent-plugin";const toggleable = preset.enabled !== undefined;const isOAuth = preset.auth === "oauth";@@ -583,7 +593,7 @@ function McpAppsCatalogRow({const callbackErrorId = `${callbackInputId}-error`;const enableOrOpenSetup = () => {- if (needsSetupInput || (preset.installed && !preset.configured && hasFields)) {+ if (preset.transport !== "stdio" || needsSetupInput || (preset.installed && !preset.configured && hasFields)) {setManagementTab("connection");setManagementOpen(true);return;@@ -709,7 +719,7 @@ function McpAppsCatalogRow({defaultValue: "Manage {{name}}",})}visibleLabel={tx("settings.mcp.manage", "Manage")}- busy={testBusy || toolsBusy || removeBusy || reconnectBusy}+ busy={testBusy || toolsBusy || removeBusy || reconnectBusy || proxyBusy}disabled={busy}tone={runtimeConnected ? "installed" : "default"}onClick={() => openManagement("overview")}@@ -741,7 +751,7 @@ function McpAppsCatalogRow({visibleLabel={hasFields ? tx("settings.mcp.configure", "Connect") : tx("settings.mcp.enable", "Enable")}busy={enableBusy}onClick={() => {- if (hasFields) openManagement("connection");+ if (hasFields || preset.transport !== "stdio") openManagement("connection");else onAction("enable", preset.name, values);}}/>@@ -873,6 +883,7 @@ function McpAppsCatalogRow({{managementOpen ? (<McpManagementDialog+ onConfigureProxy={onConfigureProxy}preset={preset}values={values}actionKey={actionKey}@@ -994,6 +1005,7 @@ function appsSearchText(item: AppsCatalogItem): string {}function McpCustomServerPanel({+ onConfigureProxy,form,configImport,actionKey,@@ -1002,6 +1014,7 @@ function McpCustomServerPanel({onSave,onImportConfig,}: {+ onConfigureProxy?: () => void;form: CustomMcpForm;configImport: string;actionKey: string | null;@@ -1160,6 +1173,16 @@ function McpCustomServerPanel({</div>) : null}+ {remote ? (+ <ProxySettingsControl+ className="mt-3 rounded-control bg-background/55 px-3 py-3"+ checked={form.useProxy}+ disabled={customBusy}+ onChange={(useProxy) => update("useProxy", useProxy)}+ onConfigure={onConfigureProxy}+ />+ ) : null}+{remote && form.auth === "headers" ? (<div className="mt-3 min-w-0"><labeldiff --git a/webui/src/components/settings/system/McpManagementDialog.tsx b/webui/src/components/settings/system/McpManagementDialog.tsxindex d29d01cf4..bff78af8d 100644--- a/webui/src/components/settings/system/McpManagementDialog.tsx+++ b/webui/src/components/settings/system/McpManagementDialog.tsx@@ -6,6 +6,7 @@ import { Check, ExternalLink, Loader2, RotateCcw, Search, Server, Trash2, X } frimport { useTranslation } from "react-i18next";import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";+import { ProxySettingsControl } from "@/components/settings/shared/ProxySettingsControl";import { Button } from "@/components/ui/button";import {Dialog,@@ -20,7 +21,7 @@ import { cn } from "@/lib/utils";export type McpManagementTab = "overview" | "tools" | "connection";-type McpAction = "enable" | "disable" | "remove" | "test" | "reconnect";+type McpAction = "enable" | "disable" | "remove" | "test" | "reconnect" | "proxy";interface McpManagementDialogProps {preset: McpPresetInfo;@@ -36,6 +37,7 @@ interface McpManagementDialogProps {onAction: (action: McpAction, name: string, values?: Record<string, string>) => void;onOAuthConnect: (name: string, reset?: boolean, values?: Record<string, string>) => void;onToolsChange: (name: string, enabledTools: string[]) => void;+ onConfigureProxy?: () => void;}export function McpManagementDialog({@@ -52,6 +54,7 @@ export function McpManagementDialog({onAction,onOAuthConnect,onToolsChange,+ onConfigureProxy,}: McpManagementDialogProps) {const { t } = useTranslation();const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });@@ -68,9 +71,14 @@ export function McpManagementDialog({const enableBusy = actionKey === `enable:${preset.name}`;const toolsBusy = actionKey === `tools:${preset.name}`;const oauthBusy = actionKey === `oauth:${preset.name}`;- const busy = testBusy || reconnectBusy || removeBusy || enableBusy || toolsBusy || oauthBusy;+ const proxyBusy = actionKey === `proxy:${preset.name}`;+ const busy = testBusy || reconnectBusy || removeBusy || enableBusy || toolsBusy || oauthBusy || proxyBusy;const configuredInstalled = preset.installed && preset.configured;const isOAuth = preset.auth === "oauth";+ const remote = preset.transport !== "stdio";+ const useProxy = values.use_proxy ?? String(preset.use_proxy ?? false);+ const proxyDirty = remote && useProxy !== String(preset.use_proxy ?? false);+ const connectionValues = remote ? { ...values, use_proxy: useProxy } : values;const inspectionRequestedRef = useRef(false);const allowAllTools = draftEnabledTools.includes("*");const selectedTools = new Set(allowAllTools ? toolNames : draftEnabledTools);@@ -115,10 +123,14 @@ export function McpManagementDialog({const connect = () => {onOpenChange(false);if (isOAuth) {- onOAuthConnect(preset.name, configuredInstalled, values);+ onOAuthConnect(preset.name, configuredInstalled, connectionValues);return;}- onAction(configuredInstalled ? "reconnect" : "enable", preset.name, values);+ if (configuredInstalled && proxyDirty) {+ onAction("proxy", preset.name, { use_proxy: useProxy });+ return;+ }+ onAction(configuredInstalled ? "reconnect" : "enable", preset.name, configuredInstalled ? values : connectionValues);};const inspectTools = () => {@@ -219,8 +231,9 @@ export function McpManagementDialog({/>) : (<ConnectionPanel+ onConfigureProxy={onConfigureProxy}preset={preset}- values={values}+ values={connectionValues}busy={busy}connectBusy={reconnectBusy || enableBusy || oauthBusy}removeBusy={removeBusy}@@ -235,6 +248,23 @@ export function McpManagementDialog({)}</div>+ {tab === "connection" && preset.installed && proxyDirty ? (+ <div className="flex shrink-0 items-center justify-end border-t border-border/45 bg-background/95 px-5 py-3 sm:px-6">+ <Button+ type="button"+ disabled={busy}+ onClick={() => {+ onOpenChange(false);+ onAction("proxy", preset.name, { use_proxy: useProxy });+ }}+ className="h-9 rounded-full px-4 text-[13px] font-semibold"+ >+ {proxyBusy ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ {tx("settings.mcp.applyChanges", "Apply changes")}+ </Button>+ </div>+ ) : null}+{tab === "tools" && toolsDirty ? (<div className="flex shrink-0 items-center justify-end border-t border-border/45 bg-background/95 px-5 py-3 sm:px-6"><Button@@ -503,6 +533,7 @@ function ToolsPanel({}function ConnectionPanel({+ onConfigureProxy,preset,values,busy,@@ -519,6 +550,7 @@ function ConnectionPanel({connectBusy: boolean;removeBusy: boolean;requiredFieldsComplete: boolean;+ onConfigureProxy?: () => void;onFieldChange: (presetName: string, fieldName: string, value: string) => void;onConnect: () => void;onRemove: () => void;@@ -599,6 +631,16 @@ function ConnectionPanel({</div>) : null}+ {preset.transport !== "stdio" ? (+ <ProxySettingsControl+ className="rounded-control bg-muted/40 px-4 py-3.5"+ checked={values.use_proxy === "true"}+ disabled={busy}+ onChange={(checked) => onFieldChange(preset.name, "use_proxy", String(checked))}+ onConfigure={onConfigureProxy}+ />+ ) : null}+{hasFields ? (<section><h3 className="text-[13px] font-semibold text-foreground">diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsxindex 718298ef5..8a0b82610 100644--- a/webui/src/components/settings/system/RuntimeConfigSettings.tsx+++ b/webui/src/components/settings/system/RuntimeConfigSettings.tsx@@ -6,6 +6,8 @@ import { SettingsGroup, SettingsRow, SettingsSectionTitle, RestartRequiredNoticeimport { ProviderPicker } from "@/components/settings/shared/ModelControls";import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";+import { SharedProxyEditor } from "@/components/settings/shared/SharedProxyEditor";+import { SettingsHint } from "@/components/settings/shared/SettingsHint";import { ShellRuntimeControl } from "@/components/settings/system/ShellRuntimeControl";import { IdleCompactionControl } from "@/components/settings/system/IdleCompactionControl";import { Input } from "@/components/ui/input";@@ -145,7 +147,18 @@ export function useRuntimeConfigSettings(change(field, next);void save(field.group, { [field.path]: next });};- return { value, visible, dirty, discard, change, commit, reject, save, saveList, saving, errors, invalidField, saved };+ const saveProxy = async (next: string) => {+ setSaving("proxy");+ try {+ const payload = await updateRuntimeConfigSettings(client, { "network.proxy": next.trim() || null });+ applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });+ discard("proxy");+ setSaved((prev) => ({ ...prev, proxy: true }));+ } finally {+ setSaving(null);+ }+ };+ return { value, visible, dirty, discard, change, commit, reject, save, saveList, saveProxy, saving, errors, invalidField, saved };}export type RuntimeConfigController = ReturnType<typeof useRuntimeConfigSettings>;@@ -184,7 +197,9 @@ export function RuntimeConfigSettings({const inlineError = fields.some((field) => field.kind === "duration" && state.invalidField === field.path);const section = (<section key={group.id} aria-label={title}>- <SettingsSectionTitle>{title}</SettingsSectionTitle>+ <SettingsSectionTitle>{group.id === "proxy"+ ? <SettingsHint description={tr("fields.network_proxy.help")}>{title}</SettingsHint>+ : title}</SettingsSectionTitle><form noValidate onSubmit={(event) => { event.preventDefault(); void state.save(group.id); }}onBlur={(event) => {if (event.relatedTarget && event.currentTarget.contains(event.relatedTarget)) return;@@ -221,6 +236,14 @@ export function RuntimeConfigSettings({: [...field.options ?? []];// Keep a configured preset visible if it is no longer available.if (field.kind === "preset" && current && !options.includes(String(current))) options.push(String(current));+ if (field.path === "network.proxy") return (+ <div key={field.path} className="px-4 py-4 sm:px-5">+ <span id={`${id}-help`} className="sr-only">{help}</span>+ <SharedProxyEditor value={String(current)} addressProps={common}+ disabled={disabled || state.saving !== null || isRestarting}+ onChange={(next) => state.change(field, next)} />+ </div>+ );return (<SettingsRow key={field.path} title={text} description={help}><span id={`${id}-help`} className="sr-only">{help}</span>diff --git a/webui/src/components/settings/system/createSystemSettingsActions.ts b/webui/src/components/settings/system/createSystemSettingsActions.tsindex 9c3350351..e733e923d 100644--- a/webui/src/components/settings/system/createSystemSettingsActions.ts+++ b/webui/src/components/settings/system/createSystemSettingsActions.ts@@ -306,6 +306,20 @@ export function createSystemSettingsActions({setAutomations(payload);};+ const retireMcpProxyDrafts = (names: string[]) => {+ setMcpFieldValues((prev) => {+ const next = { ...prev };+ for (const name of names) {+ const key = name.trim().toLowerCase();+ if (prev[key]?.use_proxy === undefined) continue;+ const fields = { ...prev[key] };+ delete fields.use_proxy;+ next[key] = fields;+ }+ return next;+ });+ };+const closeMcpOAuthPopup = () => {const popup = mcpOAuthPopupRef.current;mcpOAuthPopupRef.current = null;@@ -390,6 +404,7 @@ export function createSystemSettingsActions({try {const payload = await fetchMcpPresets(getToken());setMcpPresets(payload);+ retireMcpProxyDrafts([flow.name]);notifyMcpPresetsChanged(payload);setMcpMessage(null);setMcpError(null);@@ -560,7 +575,7 @@ export function createSystemSettingsActions({};const handleMcpPresetAction = async (- action: "enable" | "disable" | "remove" | "test" | "reconnect",+ action: "enable" | "disable" | "remove" | "test" | "reconnect" | "proxy",name: string,values: Record<string, string> = {},) => {@@ -578,6 +593,12 @@ export function createSystemSettingsActions({if (payload.requires_restart) {setPendingRestartSections((prev) => ({ ...prev, runtime: true }));}+ if (+ (action === "proxy" || action === "remove")+ && payload.last_action?.ok !== false+ ) {+ retireMcpProxyDrafts([name]);+ }await maybeRestartHostEngine(payload);if (action === "enable") {setMcpFieldValues((prev) => ({ ...prev, [name]: {} }));@@ -615,6 +636,7 @@ export function createSystemSettingsActions({? customMcpForm.headers: "",tool_timeout: customMcpForm.toolTimeout,+ ...(customMcpForm.transport !== "stdio" ? { use_proxy: String(customMcpForm.useProxy) } : {}),});setMcpPresets(payload);applyMcpActionFeedback(@@ -622,6 +644,9 @@ export function createSystemSettingsActions({false,expectsOAuthAuthorization ? name : undefined,);+ if (payload.last_action?.ok !== false) {+ retireMcpProxyDrafts([name]);+ }notifyMcpPresetsChanged(payload);if (payload.requires_restart) {setPendingRestartSections((prev) => ({ ...prev, runtime: true }));@@ -643,6 +668,11 @@ export function createSystemSettingsActions({const payload = await importMcpConfig(client, mcpConfigImport);setMcpPresets(payload);applyMcpActionFeedback(payload);+ if (payload.last_action?.ok !== false) {+ // The accepted import has been validated by the server; its response has no name list.+ const config: { mcpServers?: object } = JSON.parse(mcpConfigImport);+ retireMcpProxyDrafts(Object.keys(config.mcpServers ?? config));+ }notifyMcpPresetsChanged(payload);if (payload.requires_restart) {setPendingRestartSections((prev) => ({ ...prev, runtime: true }));diff --git a/webui/src/components/settings/system/runtime-config-fields.ts b/webui/src/components/settings/system/runtime-config-fields.tsindex 6f95ed8d9..8cb6c3dee 100644--- a/webui/src/components/settings/system/runtime-config-fields.ts+++ b/webui/src/components/settings/system/runtime-config-fields.ts@@ -21,6 +21,7 @@ export const RUNTIME_CONFIG_GROUPS: { id: string; page: RuntimeConfigPage; enabl{ id: "web", page: "browser" },{ id: "shell", page: "advanced", enabledBy: "tools.exec.enable" },{ id: "network", page: "network" },+ { id: "proxy", page: "advanced" },{ id: "safety", page: "advanced" },{ id: "cli", page: "advanced", enabledBy: "tools.cli_apps.enable" },{ id: "gateway", page: "advanced" },@@ -54,7 +55,8 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [{ group: "shell", path: "tools.exec.allowed_env_keys", kind: "list" },{ group: "shell", path: "tools.exec.allow_patterns", kind: "list" },{ group: "shell", path: "tools.exec.deny_patterns", kind: "list" },- { group: "network", path: "tools.web.proxy", kind: "nullable" },+ { group: "proxy", path: "network.proxy", kind: "nullable", manual: true },+ { group: "network", path: "tools.web.use_proxy", kind: "boolean" },{ group: "network", path: "tools.web.user_agent", kind: "nullable" },{ group: "safety", path: "tools.restrict_to_workspace", kind: "boolean" },{ group: "safety", path: "tools.webui_allow_remote_package_install", kind: "boolean" },diff --git a/webui/src/dev/gallery/channel-fixtures.ts b/webui/src/dev/gallery/channel-fixtures.tsindex 0237d1d65..8f942ef21 100644--- a/webui/src/dev/gallery/channel-fixtures.ts+++ b/webui/src/dev/gallery/channel-fixtures.ts@@ -3,22 +3,22 @@ import type { NanobotFeatureInfo } from "@/lib/types";export const channelFeatures: Record<string, NanobotFeatureInfo> = {"dingtalk": {"name": "dingtalk","display_name": "DingTalk","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.dingtalk.clientId","field": "clientId","kind": "string","choices": [],"required": true},{"key": "channels.dingtalk.clientSecret","field": "clientSecret","kind": "secret","choices": [],"required": true},{"key": "channels.dingtalk.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.dingtalk.allowRemoteMediaRedirects","field": "allowRemoteMediaRedirects","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.dingtalk.remoteMediaRedirectAllowedHosts","field": "remoteMediaRedirectAllowedHosts","kind": "list","choices": [],"required": false},{"key": "channels.dingtalk.groupUserIsolation","field": "groupUserIsolation","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.dingtalk.disablePrivateChat","field": "disablePrivateChat","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.dingtalk.clientId"]]},{"alternatives": [["channels.dingtalk.clientSecret"]]}],"official_url": "https://open.dingtalk.com/"}},- "discord": {"name": "discord","display_name": "Discord","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.discord.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.discord.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.discord.proxyUsername","field": "proxyUsername","kind": "string","choices": [],"required": false},{"key": "channels.discord.proxyPassword","field": "proxyPassword","kind": "secret","choices": [],"required": false},{"key": "channels.discord.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.discord.allowChannels","field": "allowChannels","kind": "list","choices": [],"required": false},{"key": "channels.discord.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.discord.intents","field": "intents","kind": "int","choices": [],"required": false,"default_value": "37377"},{"key": "channels.discord.readReceiptEmoji","field": "readReceiptEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.discord.workingEmoji","field": "workingEmoji","kind": "string","choices": [],"required": false,"default_value": "🔧"},{"key": "channels.discord.workingEmojiDelay","field": "workingEmojiDelay","kind": "float","choices": [],"required": false,"default_value": "2.0"},{"key": "channels.discord.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.discord.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.discord.token"]]}],"official_url": "https://discord.com/developers/applications","verifies_connection": true}},+ "discord": {"name": "discord","display_name": "Discord","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.discord.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.discord.useProxy","field": "use_proxy","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.discord.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.discord.allowChannels","field": "allowChannels","kind": "list","choices": [],"required": false},{"key": "channels.discord.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.discord.intents","field": "intents","kind": "int","choices": [],"required": false,"default_value": "37377"},{"key": "channels.discord.readReceiptEmoji","field": "readReceiptEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.discord.workingEmoji","field": "workingEmoji","kind": "string","choices": [],"required": false,"default_value": "🔧"},{"key": "channels.discord.workingEmojiDelay","field": "workingEmojiDelay","kind": "float","choices": [],"required": false,"default_value": "2.0"},{"key": "channels.discord.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.discord.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.discord.token"]]}],"official_url": "https://discord.com/developers/applications","verifies_connection": true}},"email": {"name": "email","display_name": "Email","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.email.consentGranted","field": "consentGranted","kind": "bool","choices": [],"required": true,"default_value": "false"},{"key": "channels.email.imapHost","field": "imapHost","kind": "string","choices": [],"required": true},{"key": "channels.email.imapPort","field": "imapPort","kind": "int","choices": [],"required": false,"default_value": "993"},{"key": "channels.email.imapUsername","field": "imapUsername","kind": "string","choices": [],"required": true},{"key": "channels.email.imapPassword","field": "imapPassword","kind": "secret","choices": [],"required": true},{"key": "channels.email.smtpHost","field": "smtpHost","kind": "string","choices": [],"required": true},{"key": "channels.email.smtpPort","field": "smtpPort","kind": "int","choices": [],"required": false,"default_value": "587"},{"key": "channels.email.smtpUsername","field": "smtpUsername","kind": "string","choices": [],"required": true},{"key": "channels.email.smtpPassword","field": "smtpPassword","kind": "secret","choices": [],"required": true},{"key": "channels.email.fromAddress","field": "fromAddress","kind": "string","choices": [],"required": false},{"key": "channels.email.pollIntervalSeconds","field": "pollIntervalSeconds","kind": "int","choices": [],"required": false,"default_value": "30"},{"key": "channels.email.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.email.verifyDkim","field": "verifyDkim","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.verifySpf","field": "verifySpf","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.imapMailbox","field": "imapMailbox","kind": "string","choices": [],"required": false,"default_value": "INBOX"},{"key": "channels.email.imapUseSsl","field": "imapUseSsl","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.smtpUseTls","field": "smtpUseTls","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.smtpUseSsl","field": "smtpUseSsl","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.email.autoReplyEnabled","field": "autoReplyEnabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.markSeen","field": "markSeen","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.postAction","field": "postAction","kind": "enum","choices": ["delete","move"],"required": false},{"key": "channels.email.postActionMoveMailbox","field": "postActionMoveMailbox","kind": "string","choices": [],"required": false},{"key": "channels.email.postActionExpunge","field": "postActionExpunge","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.email.postActionIgnoreSkipped","field": "postActionIgnoreSkipped","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.maxBodyChars","field": "maxBodyChars","kind": "int","choices": [],"required": false,"default_value": "12000"},{"key": "channels.email.subjectPrefix","field": "subjectPrefix","kind": "string","choices": [],"required": false,"default_value": "Re: "},{"key": "channels.email.allowedAttachmentTypes","field": "allowedAttachmentTypes","kind": "list","choices": [],"required": false},{"key": "channels.email.maxAttachmentSize","field": "maxAttachmentSize","kind": "int","choices": [],"required": false,"default_value": "2000000"},{"key": "channels.email.maxAttachmentsPerEmail","field": "maxAttachmentsPerEmail","kind": "int","choices": [],"required": false,"default_value": "5"},{"key": "channels.email.trustedAuthservIds","field": "trustedAuthservIds","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.email.consentGranted"]]},{"alternatives": [["channels.email.imapHost"]]},{"alternatives": [["channels.email.imapUsername"]]},{"alternatives": [["channels.email.imapPassword"]]},{"alternatives": [["channels.email.smtpHost"]]},{"alternatives": [["channels.email.smtpUsername"]]},{"alternatives": [["channels.email.smtpPassword"]]}],"official_url": "https://support.google.com/accounts/answer/185833","verifies_connection": true}},"feishu": {"name": "feishu","display_name": "Feishu","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.feishu.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.feishu.appSecret","field": "appSecret","kind": "secret","choices": [],"required": true},{"key": "channels.feishu.domain","field": "domain","kind": "enum","choices": ["feishu","lark"],"required": false,"default_value": "feishu"},{"key": "channels.feishu.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.feishu.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.feishu.topicIsolation","field": "topicIsolation","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.feishu.name","field": "name","kind": "string","choices": [],"required": false,"default_value": "nanobot"},{"key": "channels.feishu.encryptKey","field": "encryptKey","kind": "secret","choices": [],"required": false},{"key": "channels.feishu.verificationToken","field": "verificationToken","kind": "secret","choices": [],"required": false},{"key": "channels.feishu.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "THUMBSUP"},{"key": "channels.feishu.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false},{"key": "channels.feishu.toolHintPrefix","field": "toolHintPrefix","kind": "string","choices": [],"required": false,"default_value": "🔧"},{"key": "channels.feishu.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.feishu.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.feishu.appId"]]},{"alternatives": [["channels.feishu.appSecret"]]}],"official_url": "https://open.feishu.cn/app"}},"linear": {"name": "linear","display_name": "Linear","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.linear.clientId","field": "clientId","kind": "string","choices": [],"required": true},{"key": "channels.linear.clientSecret","field": "clientSecret","kind": "secret","choices": [],"required": true},{"key": "channels.linear.webhookSigningSecret","field": "webhookSigningSecret","kind": "secret","choices": [],"required": true},{"key": "channels.linear.publicBaseUrl","field": "publicBaseUrl","kind": "string","choices": [],"required": true},{"key": "channels.linear.host","field": "host","kind": "string","choices": [],"required": false,"default_value": "0.0.0.0"},{"key": "channels.linear.port","field": "port","kind": "int","choices": [],"required": false,"default_value": "3979"},{"key": "channels.linear.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/linear/webhook"},{"key": "channels.linear.oauthCallbackPath","field": "oauthCallbackPath","kind": "string","choices": [],"required": false,"default_value": "/linear/oauth/callback"},{"key": "channels.linear.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.linear.showReasoning","field": "showReasoning","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.linear.clientId"]]},{"alternatives": [["channels.linear.clientSecret"]]},{"alternatives": [["channels.linear.webhookSigningSecret"]]},{"alternatives": [["channels.linear.publicBaseUrl"]]}],"official_url": "https://linear.app/settings/api/applications/new"}},- "matrix": {"name": "matrix","display_name": "Matrix","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.matrix.homeserver","field": "homeserver","kind": "string","choices": [],"required": true,"default_value": "https://matrix.org"},{"key": "channels.matrix.userId","field": "userId","kind": "string","choices": [],"required": true},{"key": "channels.matrix.password","field": "password","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.accessToken","field": "accessToken","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.deviceId","field": "deviceId","kind": "string","choices": [],"required": false},{"key": "channels.matrix.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "open"},{"key": "channels.matrix.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.e2eeEnabled","field": "e2eeEnabled","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.sasVerification","field": "sasVerification","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.syncStopGraceSeconds","field": "syncStopGraceSeconds","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.maxMediaBytes","field": "maxMediaBytes","kind": "int","choices": [],"required": false,"default_value": "20971520"},{"key": "channels.matrix.maxConcurrentMediaDownloads","field": "maxConcurrentMediaDownloads","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.allowRoomMentions","field": "allowRoomMentions","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.proxy","field": "proxy","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.matrix.homeserver"]]},{"alternatives": [["channels.matrix.userId"]]},{"alternatives": [["channels.matrix.password"],["channels.matrix.accessToken","channels.matrix.deviceId"]]}],"official_url": "https://matrix.org/ecosystem/clients/"}},+ "matrix": {"name": "matrix","display_name": "Matrix","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.matrix.homeserver","field": "homeserver","kind": "string","choices": [],"required": true,"default_value": "https://matrix.org"},{"key": "channels.matrix.userId","field": "userId","kind": "string","choices": [],"required": true},{"key": "channels.matrix.password","field": "password","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.accessToken","field": "accessToken","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.deviceId","field": "deviceId","kind": "string","choices": [],"required": false},{"key": "channels.matrix.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "open"},{"key": "channels.matrix.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.e2eeEnabled","field": "e2eeEnabled","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.sasVerification","field": "sasVerification","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.syncStopGraceSeconds","field": "syncStopGraceSeconds","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.maxMediaBytes","field": "maxMediaBytes","kind": "int","choices": [],"required": false,"default_value": "20971520"},{"key": "channels.matrix.maxConcurrentMediaDownloads","field": "maxConcurrentMediaDownloads","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.allowRoomMentions","field": "allowRoomMentions","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.useProxy","field": "use_proxy","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.matrix.homeserver"]]},{"alternatives": [["channels.matrix.userId"]]},{"alternatives": [["channels.matrix.password"],["channels.matrix.accessToken","channels.matrix.deviceId"]]}],"official_url": "https://matrix.org/ecosystem/clients/"}},"mattermost": {"name": "mattermost","display_name": "Mattermost","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.mattermost.serverUrl","field": "serverUrl","kind": "string","choices": [],"required": true},{"key": "channels.mattermost.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.mattermost.teamId","field": "teamId","kind": "string","choices": [],"required": false},{"key": "channels.mattermost.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.mattermost.groupPolicyInThread","field": "groupPolicyInThread","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.mattermost.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mattermost.allowFromMatchMode","field": "allowFromMatchMode","kind": "enum","choices": ["email","id","username"],"required": false,"default_value": "id"},{"key": "channels.mattermost.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mattermost.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.includeThreadContext","field": "includeThreadContext","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.threadContextLimit","field": "threadContextLimit","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.mattermost.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "eyes"},{"key": "channels.mattermost.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false,"default_value": "white_check_mark"},{"key": "channels.mattermost.sendProgress","field": "sendProgress","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.sendToolHints","field": "sendToolHints","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "open"},{"key": "channels.mattermost.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.mattermost.serverUrl"]]},{"alternatives": [["channels.mattermost.token"]]}],"official_url": "https://developers.mattermost.com/integrate/reference/bot-accounts/"}},"mochat": {"name": "mochat","display_name": "MoChat","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.mochat.baseUrl","field": "baseUrl","kind": "string","choices": [],"required": false,"default_value": "https://mochat.io"},{"key": "channels.mochat.clawToken","field": "clawToken","kind": "secret","choices": [],"required": true},{"key": "channels.mochat.agentUserId","field": "agentUserId","kind": "string","choices": [],"required": false},{"key": "channels.mochat.sessions","field": "sessions","kind": "list","choices": [],"required": false},{"key": "channels.mochat.panels","field": "panels","kind": "list","choices": [],"required": false},{"key": "channels.mochat.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mochat.socketUrl","field": "socketUrl","kind": "string","choices": [],"required": false},{"key": "channels.mochat.socketPath","field": "socketPath","kind": "string","choices": [],"required": false,"default_value": "/socket.io"},{"key": "channels.mochat.socketDisableMsgpack","field": "socketDisableMsgpack","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.mochat.socketReconnectDelayMs","field": "socketReconnectDelayMs","kind": "int","choices": [],"required": false,"default_value": "1000"},{"key": "channels.mochat.socketMaxReconnectDelayMs","field": "socketMaxReconnectDelayMs","kind": "int","choices": [],"required": false,"default_value": "10000"},{"key": "channels.mochat.socketConnectTimeoutMs","field": "socketConnectTimeoutMs","kind": "int","choices": [],"required": false,"default_value": "10000"},{"key": "channels.mochat.refreshIntervalMs","field": "refreshIntervalMs","kind": "int","choices": [],"required": false,"default_value": "30000"},{"key": "channels.mochat.watchTimeoutMs","field": "watchTimeoutMs","kind": "int","choices": [],"required": false,"default_value": "25000"},{"key": "channels.mochat.watchLimit","field": "watchLimit","kind": "int","choices": [],"required": false,"default_value": "100"},{"key": "channels.mochat.retryDelayMs","field": "retryDelayMs","kind": "int","choices": [],"required": false,"default_value": "500"},{"key": "channels.mochat.maxRetryAttempts","field": "maxRetryAttempts","kind": "int","choices": [],"required": false,"default_value": "0"},{"key": "channels.mochat.mention.requireInGroups","field": "mention.requireInGroups","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.mochat.groups","field": "groups","kind": "json","choices": [],"required": false,"default_value": "{}"},{"key": "channels.mochat.replyDelayMode","field": "replyDelayMode","kind": "string","choices": [],"required": false,"default_value": "non-mention"},{"key": "channels.mochat.replyDelayMs","field": "replyDelayMs","kind": "int","choices": [],"required": false,"default_value": "120000"}],"requirements": [{"alternatives": [["channels.mochat.clawToken"]]}],"official_url": "https://mochat.io/"}},"msteams": {"name": "msteams","display_name": "Microsoft Teams","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.msteams.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.msteams.appPassword","field": "appPassword","kind": "secret","choices": [],"required": true},{"key": "channels.msteams.tenantId","field": "tenantId","kind": "string","choices": [],"required": false},{"key": "channels.msteams.path","field": "path","kind": "string","choices": [],"required": false,"default_value": "/api/messages"},{"key": "channels.msteams.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.msteams.host","field": "host","kind": "string","choices": [],"required": false,"default_value": "0.0.0.0"},{"key": "channels.msteams.port","field": "port","kind": "int","choices": [],"required": false,"default_value": "3978"},{"key": "channels.msteams.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.mentionOnlyResponse","field": "mentionOnlyResponse","kind": "string","choices": [],"required": false,"default_value": "Hi — what can I help with?"},{"key": "channels.msteams.validateInboundAuth","field": "validateInboundAuth","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.refTtlDays","field": "refTtlDays","kind": "int","choices": [],"required": false,"default_value": "30"},{"key": "channels.msteams.pruneWebChatRefs","field": "pruneWebChatRefs","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.pruneNonPersonalRefs","field": "pruneNonPersonalRefs","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.refTouchIntervalS","field": "refTouchIntervalS","kind": "int","choices": [],"required": false,"default_value": "300"},{"key": "channels.msteams.trustedServiceUrlHosts","field": "trustedServiceUrlHosts","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.msteams.appId"]]},{"alternatives": [["channels.msteams.appPassword"]]}],"official_url": "https://dev.teams.microsoft.com/apps"}},"napcat": {"name": "napcat","display_name": "NapCat","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.napcat.wsUrl","field": "wsUrl","kind": "string","choices": [],"required": true,"default_value": "ws://127.0.0.1:3001"},{"key": "channels.napcat.accessToken","field": "accessToken","kind": "secret","choices": [],"required": false},{"key": "channels.napcat.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.napcat.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.napcat.groupPolicyOverrides","field": "groupPolicyOverrides","kind": "json","choices": [],"required": false,"default_value": "{}"},{"key": "channels.napcat.welcomeNewMembers","field": "welcomeNewMembers","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.napcat.maxImageBytes","field": "maxImageBytes","kind": "int","choices": [],"required": false,"default_value": "20971520"}],"requirements": [{"alternatives": [["channels.napcat.wsUrl"]]}],"official_url": "https://napneko.github.io/"}},"qq": {"name": "qq","display_name": "QQ","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.qq.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.qq.secret","field": "secret","kind": "secret","choices": [],"required": true},{"key": "channels.qq.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.qq.msgFormat","field": "msgFormat","kind": "enum","choices": ["markdown","plain"],"required": false,"default_value": "plain"},{"key": "channels.qq.ackMessage","field": "ackMessage","kind": "string","choices": [],"required": false,"default_value": "⏳ Processing..."},{"key": "channels.qq.showCompactionNotices","field": "showCompactionNotices","kind": "bool","choices": [],"required": false,"inheritable": true},{"key": "channels.qq.mediaDir","field": "mediaDir","kind": "string","choices": [],"required": false},{"key": "channels.qq.downloadChunkSize","field": "downloadChunkSize","kind": "int","choices": [],"required": false,"default_value": "262144"},{"key": "channels.qq.downloadMaxBytes","field": "downloadMaxBytes","kind": "int","choices": [],"required": false,"default_value": "209715200"}],"requirements": [{"alternatives": [["channels.qq.appId"]]},{"alternatives": [["channels.qq.secret"]]}],"official_url": "https://q.qq.com/"}},"signal": {"name": "signal","display_name": "Signal","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.signal.phoneNumber","field": "phoneNumber","kind": "string","choices": [],"required": true},{"key": "channels.signal.daemonHost","field": "daemonHost","kind": "string","choices": [],"required": false,"default_value": "localhost"},{"key": "channels.signal.daemonPort","field": "daemonPort","kind": "int","choices": [],"required": false,"default_value": "8080"},{"key": "channels.signal.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.signal.group.allowFrom","field": "group.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.signal.groupMessageBufferSize","field": "groupMessageBufferSize","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.signal.attachmentsDir","field": "attachmentsDir","kind": "string","choices": [],"required": false},{"key": "channels.signal.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.signal.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "allowlist"},{"key": "channels.signal.group.enabled","field": "group.enabled","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.signal.group.policy","field": "group.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "allowlist"},{"key": "channels.signal.group.requireMention","field": "group.requireMention","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.signal.phoneNumber"]]}],"official_url": "https://github.com/bbernhard/signal-cli-rest-api"}},- "slack": {"name": "slack","display_name": "Slack","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.slack.appToken","field": "appToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.botToken","field": "botToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.slack.mode","field": "mode","kind": "enum","choices": ["socket"],"required": false,"default_value": "socket"},{"key": "channels.slack.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/slack/events"},{"key": "channels.slack.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "eyes"},{"key": "channels.slack.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false,"default_value": "white_check_mark"},{"key": "channels.slack.includeThreadContext","field": "includeThreadContext","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.threadContextLimit","field": "threadContextLimit","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.slack.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupRequireMention","field": "groupRequireMention","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.slack.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "open"},{"key": "channels.slack.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.proxy","field": "proxy","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.slack.appToken"]]},{"alternatives": [["channels.slack.botToken"]]}],"official_url": "https://api.slack.com/apps","verifies_connection": true}},- "telegram": {"name": "telegram","display_name": "Telegram","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.telegram.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.telegram.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.telegram.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.telegram.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.telegram.mode","field": "mode","kind": "enum","choices": ["polling","webhook"],"required": false,"default_value": "polling"},{"key": "channels.telegram.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.telegram.connectionPoolSize","field": "connectionPoolSize","kind": "int","choices": [],"required": false,"default_value": "32"},{"key": "channels.telegram.poolTimeout","field": "poolTimeout","kind": "float","choices": [],"required": false,"default_value": "5.0"},{"key": "channels.telegram.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.telegram.inlineKeyboards","field": "inlineKeyboards","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.richMessages","field": "richMessages","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.streamEditInterval","field": "streamEditInterval","kind": "float","choices": [],"required": false,"default_value": "0.6"},{"key": "channels.telegram.webhookUrl","field": "webhookUrl","kind": "string","choices": [],"required": false},{"key": "channels.telegram.webhookListenHost","field": "webhookListenHost","kind": "string","choices": [],"required": false,"default_value": "127.0.0.1"},{"key": "channels.telegram.webhookListenPort","field": "webhookListenPort","kind": "int","choices": [],"required": false,"default_value": "8081"},{"key": "channels.telegram.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/telegram"},{"key": "channels.telegram.webhookSecretToken","field": "webhookSecretToken","kind": "secret","choices": [],"required": false},{"key": "channels.telegram.webhookMaxConnections","field": "webhookMaxConnections","kind": "int","choices": [],"required": false,"default_value": "4"}],"requirements": [{"alternatives": [["channels.telegram.token"]]}],"official_url": "https://t.me/BotFather","verifies_connection": true}},+ "slack": {"name": "slack","display_name": "Slack","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.slack.appToken","field": "appToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.botToken","field": "botToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.slack.mode","field": "mode","kind": "enum","choices": ["socket"],"required": false,"default_value": "socket"},{"key": "channels.slack.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/slack/events"},{"key": "channels.slack.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "eyes"},{"key": "channels.slack.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false,"default_value": "white_check_mark"},{"key": "channels.slack.includeThreadContext","field": "includeThreadContext","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.threadContextLimit","field": "threadContextLimit","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.slack.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupRequireMention","field": "groupRequireMention","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.slack.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "open"},{"key": "channels.slack.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.useProxy","field": "use_proxy","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.slack.appToken"]]},{"alternatives": [["channels.slack.botToken"]]}],"official_url": "https://api.slack.com/apps","verifies_connection": true}},+ "telegram": {"name": "telegram","display_name": "Telegram","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.telegram.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.telegram.useProxy","field": "use_proxy","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.telegram.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.telegram.mode","field": "mode","kind": "enum","choices": ["polling","webhook"],"required": false,"default_value": "polling"},{"key": "channels.telegram.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.telegram.connectionPoolSize","field": "connectionPoolSize","kind": "int","choices": [],"required": false,"default_value": "32"},{"key": "channels.telegram.poolTimeout","field": "poolTimeout","kind": "float","choices": [],"required": false,"default_value": "5.0"},{"key": "channels.telegram.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.telegram.inlineKeyboards","field": "inlineKeyboards","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.richMessages","field": "richMessages","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.streamEditInterval","field": "streamEditInterval","kind": "float","choices": [],"required": false,"default_value": "0.6"},{"key": "channels.telegram.webhookUrl","field": "webhookUrl","kind": "string","choices": [],"required": false},{"key": "channels.telegram.webhookListenHost","field": "webhookListenHost","kind": "string","choices": [],"required": false,"default_value": "127.0.0.1"},{"key": "channels.telegram.webhookListenPort","field": "webhookListenPort","kind": "int","choices": [],"required": false,"default_value": "8081"},{"key": "channels.telegram.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/telegram"},{"key": "channels.telegram.webhookSecretToken","field": "webhookSecretToken","kind": "secret","choices": [],"required": false},{"key": "channels.telegram.webhookMaxConnections","field": "webhookMaxConnections","kind": "int","choices": [],"required": false,"default_value": "4"}],"requirements": [{"alternatives": [["channels.telegram.token"]]}],"official_url": "https://t.me/BotFather","verifies_connection": true}},"websocket": {"name": "websocket","display_name": "WebSocket","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [],"requirements": [],"official_url": "http://127.0.0.1:8765"}},"wecom": {"name": "wecom","display_name": "WeCom","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.wecom.botId","field": "botId","kind": "string","choices": [],"required": true},{"key": "channels.wecom.secret","field": "secret","kind": "secret","choices": [],"required": true},{"key": "channels.wecom.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.wecom.welcomeMessage","field": "welcomeMessage","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.wecom.botId"]]},{"alternatives": [["channels.wecom.secret"]]}],"official_url": "https://developer.work.weixin.qq.com/"}},"weixin": {"name": "weixin","display_name": "WeChat","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.weixin.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.weixin.baseUrl","field": "baseUrl","kind": "string","choices": [],"required": false,"default_value": "https://ilinkai.weixin.qq.com"},{"key": "channels.weixin.cdnBaseUrl","field": "cdnBaseUrl","kind": "string","choices": [],"required": false,"default_value": "https://novac2c.cdn.weixin.qq.com/c2c"},{"key": "channels.weixin.routeTag","field": "routeTag","kind": "string","choices": [],"required": false},{"key": "channels.weixin.stateDir","field": "stateDir","kind": "string","choices": [],"required": false},{"key": "channels.weixin.pollTimeout","field": "pollTimeout","kind": "int","choices": [],"required": false,"default_value": "35"},{"key": "channels.weixin.sendProgress","field": "sendProgress","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.sendToolHints","field": "sendToolHints","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.replyProgressMessages","field": "replyProgressMessages","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.replyProgressMaxMessages","field": "replyProgressMaxMessages","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.weixin.contextMessageBudget","field": "contextMessageBudget","kind": "int","choices": [],"required": false,"default_value": "8"},{"key": "channels.weixin.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.weixin.blockStreaming","field": "blockStreaming","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.blockStreamingMinChars","field": "blockStreamingMinChars","kind": "int","choices": [],"required": false,"default_value": "1200"},{"key": "channels.weixin.blockStreamingMaxMessages","field": "blockStreamingMaxMessages","kind": "int","choices": [],"required": false,"default_value": "3"}],"requirements": [{"alternatives": [["channels.weixin.token"]]}],"official_url": "https://weixin.qq.com/"}},- "whatsapp": {"name": "whatsapp","display_name": "WhatsApp","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.whatsapp.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.whatsapp.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.whatsapp.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "open"}],"requirements": [],"official_url": "https://faq.whatsapp.com/"}},+ "whatsapp": {"name": "whatsapp","display_name": "WhatsApp","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.whatsapp.useProxy","field": "use_proxy","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.whatsapp.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.whatsapp.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "open"}],"requirements": [],"official_url": "https://faq.whatsapp.com/"}},"whatsapp_agent": {"name": "whatsapp_agent","display_name": "WhatsApp Agent Platform","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.whatsapp_agent.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.whatsapp_agent.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.whatsapp_agent.stateDir","field": "stateDir","kind": "string","choices": [],"required": false},{"key": "channels.whatsapp_agent.pollTimeout","field": "pollTimeout","kind": "int","choices": [],"required": false,"default_value": "25"},{"key": "channels.whatsapp_agent.markRead","field": "markRead","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.whatsapp_agent.typingIndicator","field": "typingIndicator","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.whatsapp_agent.downloadMedia","field": "downloadMedia","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.whatsapp_agent.deleteMediaAfterDownload","field": "deleteMediaAfterDownload","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.whatsapp_agent.maxMediaMb","field": "maxMediaMb","kind": "int","choices": [],"required": false,"default_value": "16"},{"key": "channels.whatsapp_agent.retryAmbiguousSends","field": "retryAmbiguousSends","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.whatsapp_agent.sendProgress","field": "sendProgress","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.whatsapp_agent.sendToolHints","field": "sendToolHints","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.whatsapp_agent.token"]]}],"official_url": "https://faq.whatsapp.com/1050934623978152","verifies_connection": true}},};diff --git a/webui/src/dev/gallery/providers.tsx b/webui/src/dev/gallery/providers.tsxindex 4eafb41f9..ffef1843b 100644--- a/webui/src/dev/gallery/providers.tsx+++ b/webui/src/dev/gallery/providers.tsx@@ -14,8 +14,8 @@ type ProviderRow = SettingsPayload["providers"][number];const previewProviders: ProviderRow[] = [{ name: "custom", label: "Custom", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.example.com/v1" },{ name: "anthropic", label: "Anthropic", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.anthropic.com", request_apis: ["anthropic_messages"] },- { name: "openai_codex", label: "OpenAI Codex", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["proxy", "extra_body"] },- { name: "xai_grok", label: "xAI Grok", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["proxy", "extra_body"] },+ { name: "openai_codex", label: "OpenAI Codex", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["use_proxy", "extra_body"] },+ { name: "xai_grok", label: "xAI Grok", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["use_proxy", "extra_body"] },{ name: "deepseek", label: "DeepSeek", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.deepseek.com" },{ name: "zhipu", label: "Zhipu AI", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://open.bigmodel.cn/api/paas/v4" },{ name: "minimax", label: "MiniMax", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.minimax.io/v1" },@@ -44,7 +44,7 @@ function providerValues(form: ProviderForm) {api_base: form.apiBase.trim() || null,api: form.api,api_key_hint: form.apiKey.trim() ? "••••••••" : undefined,- proxy: form.proxy.trim() || null,+ use_proxy: form.useProxy,extra_headers: extraHeaders,extra_query: extraQuery,extra_body: extraBody,@@ -101,7 +101,7 @@ function ProvidersPreview() {const name = `custom_preview_${nextCustomId.current++}`;const row: ProviderRow = { ...values, name, label: form.name.trim(), is_custom: true,configured: true, auth_type: "api_key", api_key_required: false, provider_api_configurable: true,- advanced_fields: ["extra_headers", "extra_body", "extra_query", "proxy", "thinking_style"] };+ advanced_fields: ["extra_headers", "extra_body", "extra_query", "use_proxy", "thinking_style"] };const next: SettingsPayload = { ...payload, providers: [...payload.providers, row], created_provider: name };setPayload(next);setDrafts((current) => ({ ...current, [name]: providerFormFromRow(row) }));diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex e2ccad147..d93c77e39 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -491,6 +491,16 @@"description": "Your changes are saved. Restart to apply them.","later": "Restart later"},+ "network": {+ "useProxy": "Use proxy",+ "useProxyHelp": "Uses the shared proxy in Advanced.",+ "configureProxy": "Configure proxy",+ "sharedProxyScope": "Shared by all features with proxy enabled.",+ "authentication": "Authentication (optional)",+ "username": "Username",+ "password": "Password",+ "proxyReferenceAuth": "Set authentication in the referenced proxy URL."+ },"runtimeConfig": {"apiSaved": "Saved. Restart the API service to apply changes.","commandRuntime": {@@ -609,9 +619,13 @@"label": "Blocked commands","help": "Block commands that match these rules.\n\nOne regular expression per line, checked alongside built-in deny rules. Commands that fully match allow rules skip these checks."},- "tools_web_proxy": {- "label": "Web proxy",- "help": "Used for the agent's web search and page reading. Leave blank to use the default network settings, including proxy environment variables.\n\n127.0.0.1 refers to the machine that runs nanobot. This setting does not change model, MCP, or browser connections."+ "network_proxy": {+ "label": "Shared proxy",+ "help": "Address used by features with Use proxy enabled. 127.0.0.1 is the machine running nanobot."+ },+ "tools_web_use_proxy": {+ "label": "Use proxy",+ "help": "Use the shared proxy for web search and page reading."},"tools_web_user_agent": {"label": "User agent",@@ -699,9 +713,13 @@"title": "Shell and sandbox","help": "Set command timeouts, environment, and access rules."},+ "proxy": {+ "title": "Shared proxy",+ "help": "Set one address for features that use a proxy."+ },"network": {"title": "Web connections",- "help": "Set the proxy and User-Agent.\n\nSet the proxy and User-Agent header for web requests."+ "help": "Set the proxy preference and User-Agent for web requests."},"safety": {"title": "Global permissions",@@ -1379,7 +1397,6 @@"defaultAPIDescription": "Presets set to Auto use this API. A preset can choose another API from the supported list.","declareAPIs": "Set supported APIs","openaiDefaultAPIDescription": "Sets the default API for presets using Auto. Auto here follows known model rules. Individual presets can override this choice.",- "proxy": "Network proxy","thinkingStyle": "Reasoning format","region": "Region","profile": "AWS profile",@@ -1788,9 +1805,6 @@"signInBeforeSaving": "Sign in before saving this provider in the preset.","signedIn": "Signed in","notSignedIn": "Not signed in",- "proxyLabel": "Network proxy",- "proxySaveBeforeSignIn": "Save proxy changes before signing in.",- "saveProxy": "Save proxy","localCodeHelp": "Complete sign-in in your browser. If nanobot does not connect automatically, paste the authorization code below.","remoteCodeHelp": "Select Sign in to open xAI on your computer. After signing in, paste the authorization code shown by xAI below.","localCallbackHelp": "Complete sign-in in your browser. If nanobot does not connect automatically, copy the full localhost callback URL from the address bar and paste it below.",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex e1ec9d10e..40f7b29b7 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -491,6 +491,16 @@"description": "Los cambios están guardados. Reinicia para aplicarlos.","later": "Reiniciar más tarde"},+ "network": {+ "useProxy": "Usar proxy",+ "useProxyHelp": "Usa el proxy compartido de los ajustes avanzados.",+ "configureProxy": "Configurar proxy",+ "sharedProxyScope": "Se comparte entre las funciones con el proxy activado.",+ "authentication": "Autenticación (opcional)",+ "username": "Usuario",+ "password": "Contraseña",+ "proxyReferenceAuth": "Configura la autenticación en la URL del proxy referenciada."+ },"runtimeConfig": {"apiSaved": "Guardado. Reinicia el servicio API para aplicar los cambios.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "Variables de entorno", "help": "Variables adicionales para los comandos, un nombre por línea.\n\nVariables adicionales que se pasan a los comandos, una por línea. Las variables básicas necesarias siguen disponibles."},"tools_exec_allow_patterns": {"label": "Comandos permitidos", "help": "Ejecuta solo comandos que coincidan por completo con las reglas permitidas.\n\nUna expresión regular por línea. Si añades reglas, cada segmento del comando debe coincidir por completo con alguna de ellas. Los comandos permitidos omiten las reglas de bloqueo integradas y personalizadas, pero mantienen las restricciones de red y del espacio de trabajo."},"tools_exec_deny_patterns": {"label": "Comandos bloqueados", "help": "Bloquea los comandos que coincidan con estas reglas.\n\nExpresiones regulares de bloqueo adicionales, una por línea. Las reglas de permiso explícitas tienen prioridad sobre las reglas de bloqueo integradas y personalizadas."},- "tools_web_proxy": {"label": "Proxy web", "help": "Se usa para las búsquedas web y la lectura de páginas del agente. Déjalo vacío para usar la red predeterminada, incluidas las variables de entorno del proxy.\n\n127.0.0.1 es el equipo que ejecuta nanobot. Este ajuste no cambia las conexiones de modelos, MCP ni del navegador."},+ "network_proxy": {"label": "Proxy compartido", "help": "Dirección usada por las funciones con el proxy activado. 127.0.0.1 es el equipo que ejecuta nanobot."},+ "tools_web_use_proxy": {"label": "Usar proxy", "help": "Usa el proxy compartido para buscar en la web y leer páginas."},"tools_web_user_agent": {"label": "Cabecera User-Agent", "help": "User-Agent para solicitudes web; en blanco usa el predeterminado.\n\nCabecera User-Agent personalizada. Déjalo vacío para usar el valor predeterminado."},"tools_restrict_to_workspace": {"label": "Restricción del espacio", "help": "Límites globales del espacio; los permisos de chats WebUI se ajustan aparte.\n\nPolítica global de herramientas. Los permisos de cada conversación WebUI se configuran por separado."},"tools_ssrf_whitelist": {"label": "IP permitidas", "help": "IP o rangos CIDR permitidos, uno por línea.\n\nDirecciones IP o rangos CIDR exentos de la protección de solicitudes salientes, uno por línea."},@@ -552,7 +563,8 @@"sessions": {"title": "Conversaciones", "help": "Configura chats compartidos entre plataformas."},"tools": {"title": "Herramientas integradas", "help": "Elige las herramientas que puede usar el agente."},"shell": {"title": "Shell y entorno aislado", "help": "Configura los tiempos límite, el entorno y las reglas de acceso."},- "network": {"title": "Conexiones web", "help": "Configura el proxy y User-Agent.\n\nProxy e identificación de las solicitudes web."},+ "proxy": {"title": "Proxy compartido", "help": "Define una dirección para las funciones que usan proxy."},+ "network": {"title": "Conexiones web", "help": "Configura el uso de proxy y el User-Agent de las solicitudes web."},"safety": {"title": "Permisos globales", "help": "Configura límites del espacio, excepciones de red e instalaciones remotas.\n\nRestricciones del espacio de trabajo, redes privadas e instalaciones remotas."},"cli": {"title": "Límites CLI", "help": "Configura tiempos límite de instalación y ejecución y la duración de caché.\n\nTiempos de instalación, ejecución y caché del catálogo."},"gateway": {"title": "Puerta de enlace", "help": "Configura el despliegue y el reinicio."},@@ -949,7 +961,6 @@"defaultAPIDescription": "Los preajustes configurados en Auto usan esta API. Cada preajuste puede elegir otra API de la lista de API compatibles.","declareAPIs": "Configurar API compatibles","openaiDefaultAPIDescription": "Define la API predeterminada para los preajustes que usan Auto. Aquí, Auto sigue las reglas conocidas del modelo. Cada preajuste puede cambiar esta elección.",- "proxy": "Proxy de red","thinkingStyle": "Formato de razonamiento","region": "Región","profile": "Perfil de AWS",@@ -1589,9 +1600,6 @@"signInBeforeSaving": "Inicia sesión en este proveedor antes de guardar el preajuste.","signedIn": "Sesión iniciada","notSignedIn": "Sin sesión",- "proxyLabel": "Proxy de red",- "proxySaveBeforeSignIn": "Guarda los cambios del proxy antes de iniciar sesión.",- "saveProxy": "Guardar proxy","localCodeHelp": "Completa el inicio de sesión en el navegador. nanobot suele finalizar automáticamente; si no lo hace, pega el código de autorización abajo.","remoteCodeHelp": "Selecciona Iniciar sesión para abrir xAI en tu computadora. Después de iniciar sesión, pega abajo el código de autorización que muestra xAI.","localCallbackHelp": "Completa el inicio de sesión en el navegador. nanobot suele finalizar automáticamente; si no lo hace, copia de la barra de direcciones la URL completa de devolución de localhost y pégala abajo.",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 8c908605e..353c62937 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -491,6 +491,16 @@"description": "Vos modifications sont enregistrées. Redémarrez pour les appliquer.","later": "Redémarrer plus tard"},+ "network": {+ "useProxy": "Utiliser le proxy",+ "useProxyHelp": "Utilise le proxy partagé des réglages avancés.",+ "configureProxy": "Configurer le proxy",+ "sharedProxyScope": "Partagé par toutes les fonctions utilisant le proxy.",+ "authentication": "Authentification (facultative)",+ "username": "Nom d’utilisateur",+ "password": "Mot de passe",+ "proxyReferenceAuth": "Configurez l’authentification dans l’URL du proxy référencée."+ },"runtimeConfig": {"apiSaved": "Enregistré. Redémarrez le service API pour appliquer les modifications.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "Variables d’environnement", "help": "Variables supplémentaires transmises aux commandes, un nom par ligne.\n\nVariables supplémentaires à transmettre aux commandes, une par ligne. Les variables nécessaires au fonctionnement restent disponibles."},"tools_exec_allow_patterns": {"label": "Commandes autorisées", "help": "Exécutez seulement les commandes correspondant entièrement aux règles d’autorisation.\n\nUne expression régulière par ligne. Si cette liste est renseignée, chaque segment de commande doit correspondre entièrement à une règle. Les commandes autorisées échappent aux règles de blocage intégrées et personnalisées, mais restent soumises aux restrictions réseau et d’espace de travail."},"tools_exec_deny_patterns": {"label": "Commandes bloquées", "help": "Bloquez les commandes correspondant à ces règles.\n\nExpressions régulières de blocage supplémentaires, une par ligne. Les règles d’autorisation explicites ont priorité sur ces règles et sur les protections intégrées."},- "tools_web_proxy": {"label": "Proxy web", "help": "Utilisé pour la recherche web et la lecture de pages par l’agent. Laissez vide pour utiliser le réseau par défaut, y compris les variables d’environnement du proxy.\n\n127.0.0.1 désigne la machine qui exécute nanobot. Ce réglage ne change pas les connexions des modèles, de MCP ou du navigateur."},+ "network_proxy": {"label": "Proxy partagé", "help": "Adresse utilisée par les fonctions dont le proxy est activé. 127.0.0.1 désigne la machine qui exécute nanobot."},+ "tools_web_use_proxy": {"label": "Utiliser le proxy", "help": "Utiliser le proxy partagé pour la recherche web et la lecture de pages."},"tools_web_user_agent": {"label": "En-tête User-Agent", "help": "User-Agent des requêtes web ; laissez vide pour la valeur par défaut.\n\nEn-tête User-Agent personnalisé. Laissez vide pour utiliser la valeur par défaut."},"tools_restrict_to_workspace": {"label": "Restriction de l’espace", "help": "Limites globales de l’espace ; les permissions WebUI sont réglées séparément.\n\nRègle globale des outils. Les autorisations de chaque conversation WebUI sont distinctes."},"tools_ssrf_whitelist": {"label": "IP autorisées", "help": "IP ou plages CIDR autorisées, une par ligne.\n\nAdresses IP ou plages CIDR exemptées de la protection des requêtes sortantes, une par ligne."},@@ -552,7 +563,8 @@"sessions": {"title": "Conversations", "help": "Configurez les discussions partagées entre plateformes."},"tools": {"title": "Outils intégrés", "help": "Choisissez les outils accessibles à l’agent."},"shell": {"title": "Shell et bac à sable", "help": "Réglez les délais, l’environnement et les règles d’accès des commandes."},- "network": {"title": "Connexions web", "help": "Réglez le proxy et le User-Agent.\n\nProxy et identification des requêtes web."},+ "proxy": {"title": "Proxy partagé", "help": "Définissez une adresse pour les fonctions utilisant un proxy."},+ "network": {"title": "Connexions web", "help": "Réglez l’utilisation du proxy et le User-Agent des requêtes web."},"safety": {"title": "Permissions globales", "help": "Réglez les limites de l’espace, les exceptions réseau et les installations distantes.\n\nRestrictions de l’espace de travail, réseaux privés et installations à distance."},"cli": {"title": "Limites CLI", "help": "Réglez les délais d’installation et d’exécution, et la durée du cache.\n\nDélais d’installation, d’exécution et de cache du catalogue."},"gateway": {"title": "Passerelle", "help": "Réglez le déploiement et le redémarrage."},@@ -949,7 +961,6 @@"defaultAPIDescription": "Les préréglages définis sur Auto utilisent cette API. Chaque préréglage peut choisir une autre API de la liste des API prises en charge.","declareAPIs": "Définir les API prises en charge","openaiDefaultAPIDescription": "Définit l’API par défaut des préréglages utilisant Auto. Ici, Auto suit les règles connues du modèle. Chaque préréglage peut modifier ce choix.",- "proxy": "Proxy réseau","thinkingStyle": "Format du raisonnement","region": "Région","profile": "Profil AWS",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "Connectez-vous à ce fournisseur avant d’enregistrer le préréglage.","signedIn": "Connecté","notSignedIn": "Non connecté",- "proxyLabel": "Proxy réseau",- "proxySaveBeforeSignIn": "Enregistrez les modifications du proxy avant de vous connecter.",- "saveProxy": "Enregistrer le proxy","localCodeHelp": "Terminez la connexion dans votre navigateur. nanobot termine généralement automatiquement ; sinon, collez le code d’autorisation ci-dessous.","remoteCodeHelp": "Sélectionnez Se connecter pour ouvrir xAI sur votre ordinateur. Après la connexion, collez ci-dessous le code d’autorisation affiché par xAI.","localCallbackHelp": "Terminez la connexion dans votre navigateur. nanobot termine généralement automatiquement ; sinon, copiez l’URL complète de rappel localhost depuis la barre d’adresse et collez-la ci-dessous.",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 57aec7b24..a82e7ffed 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -491,6 +491,16 @@"description": "Perubahan sudah disimpan. Mulai ulang untuk menerapkannya.","later": "Mulai ulang nanti"},+ "network": {+ "useProxy": "Gunakan proxy",+ "useProxyHelp": "Menggunakan proxy bersama di pengaturan Lanjutan.",+ "configureProxy": "Atur proxy",+ "sharedProxyScope": "Dipakai bersama oleh semua fitur yang mengaktifkan proxy.",+ "authentication": "Autentikasi (opsional)",+ "username": "Nama pengguna",+ "password": "Kata sandi",+ "proxyReferenceAuth": "Atur autentikasi di URL proxy yang dirujuk."+ },"runtimeConfig": {"apiSaved": "Tersimpan. Mulai ulang layanan API untuk menerapkan perubahan.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "Variabel lingkungan", "help": "Variabel tambahan untuk perintah, satu nama per baris.\n\nVariabel tambahan yang diteruskan ke perintah, satu per baris. Variabel dasar yang diperlukan tetap tersedia."},"tools_exec_allow_patterns": {"label": "Perintah diizinkan", "help": "Hanya jalankan perintah yang cocok sepenuhnya dengan aturan izin.\n\nSatu ekspresi reguler per baris. Jika diisi, setiap bagian perintah harus cocok sepenuhnya dengan salah satu aturan. Perintah yang diizinkan melewati aturan pemblokiran bawaan dan tambahan, tetapi tetap mengikuti batasan jaringan dan ruang kerja."},"tools_exec_deny_patterns": {"label": "Perintah diblokir", "help": "Blokir perintah yang cocok dengan aturan ini.\n\nAturan pemblokiran tambahan berupa ekspresi reguler, satu per baris. Aturan izin eksplisit mengesampingkan aturan pemblokiran bawaan dan tambahan."},- "tools_web_proxy": {"label": "Proxy web", "help": "Digunakan untuk pencarian web dan pembacaan halaman oleh agen. Kosongkan untuk memakai pengaturan jaringan default, termasuk variabel lingkungan proxy.\n\n127.0.0.1 adalah mesin yang menjalankan nanobot. Pengaturan ini tidak mengubah koneksi model, MCP, atau browser."},+ "network_proxy": {"label": "Proxy bersama", "help": "Alamat untuk fitur yang mengaktifkan proxy. 127.0.0.1 adalah perangkat yang menjalankan nanobot."},+ "tools_web_use_proxy": {"label": "Gunakan proxy", "help": "Gunakan proxy bersama untuk pencarian web dan pembacaan halaman."},"tools_web_user_agent": {"label": "Header User-Agent", "help": "User-Agent untuk permintaan web; kosongkan untuk nilai default.\n\nHeader User-Agent kustom. Kosongkan untuk memakai nilai default."},"tools_restrict_to_workspace": {"label": "Batas ruang kerja", "help": "Batas ruang kerja global; izin chat WebUI diatur terpisah.\n\nKebijakan alat global. Izin setiap percakapan WebUI diatur secara terpisah."},"tools_ssrf_whitelist": {"label": "IP diizinkan", "help": "IP atau rentang CIDR diizinkan, satu per baris.\n\nIP atau rentang CIDR yang dikecualikan dari perlindungan permintaan keluar, satu per baris."},@@ -552,7 +563,8 @@"sessions": {"title": "Percakapan", "help": "Atur chat bersama di berbagai platform."},"tools": {"title": "Alat bawaan", "help": "Pilih alat yang boleh digunakan agen."},"shell": {"title": "Shell dan sandbox", "help": "Atur batas waktu perintah, lingkungan, dan aturan akses."},- "network": {"title": "Koneksi web", "help": "Atur proxy dan User-Agent.\n\nProxy dan identitas permintaan web."},+ "proxy": {"title": "Proxy bersama", "help": "Tetapkan satu alamat untuk fitur yang menggunakan proxy."},+ "network": {"title": "Koneksi web", "help": "Atur penggunaan proxy dan User-Agent untuk permintaan web."},"safety": {"title": "Izin global", "help": "Atur batas ruang kerja, pengecualian jaringan, dan pemasangan jarak jauh.\n\nPembatasan ruang kerja, jaringan privat, dan instalasi jarak jauh."},"cli": {"title": "Batas CLI", "help": "Atur batas waktu pemasangan dan eksekusi, serta durasi cache daftar.\n\nBatas waktu instalasi, eksekusi, dan cache katalog."},"gateway": {"title": "Gateway", "help": "Atur opsi penerapan dan mulai ulang."},@@ -949,7 +961,6 @@"defaultAPIDescription": "Preset yang diatur ke Otomatis memakai API ini. Setiap preset dapat memilih API lain dari daftar yang didukung.","declareAPIs": "Atur API yang didukung","openaiDefaultAPIDescription": "Menetapkan API default untuk preset yang memakai Otomatis. Otomatis di sini mengikuti aturan model yang sudah diketahui. Setiap preset dapat mengubah pilihan ini.",- "proxy": "Proksi jaringan","thinkingStyle": "Format penalaran","region": "Wilayah","profile": "Profil AWS",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "Masuk ke penyedia ini sebelum menyimpan prasetel.","signedIn": "Sudah masuk","notSignedIn": "Belum masuk",- "proxyLabel": "Proksi jaringan",- "proxySaveBeforeSignIn": "Simpan perubahan proksi sebelum login.",- "saveProxy": "Simpan proksi","localCodeHelp": "Selesaikan proses masuk di browser. nanobot biasanya menyelesaikannya secara otomatis; jika tidak, tempel kode otorisasi di bawah.","remoteCodeHelp": "Pilih Masuk untuk membuka xAI di komputer Anda. Setelah masuk, tempel kode otorisasi yang ditampilkan xAI di bawah.","localCallbackHelp": "Selesaikan proses masuk di browser. nanobot biasanya menyelesaikannya secara otomatis; jika tidak, salin URL callback localhost lengkap dari bilah alamat dan tempel di bawah.",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex ce081603c..fca23c88e 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -491,6 +491,16 @@"description": "変更は保存されています。反映するには再起動してください。","later": "後で再起動"},+ "network": {+ "useProxy": "プロキシを使う",+ "useProxyHelp": "詳細設定の共有プロキシを使います。",+ "configureProxy": "プロキシを設定",+ "sharedProxyScope": "プロキシを有効にしたすべての機能で共有します。",+ "authentication": "認証(任意)",+ "username": "ユーザー名",+ "password": "パスワード",+ "proxyReferenceAuth": "参照先のプロキシ URL に認証情報を設定してください。"+ },"runtimeConfig": {"apiSaved": "保存しました。API サービスを再起動すると反映されます。","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "環境変数", "help": "コマンドに追加で渡す変数名を1行に1つ指定します。\n\nコマンドに渡す環境変数を追加します。1 行に 1 つ指定してください。動作に必要な基本の環境変数は引き続き渡されます。"},"tools_exec_allow_patterns": {"label": "許可コマンド", "help": "許可ルールに完全一致するコマンドのみ実行します。\n\n1 行に 1 つ正規表現を指定します。設定すると、コマンドの各部分がいずれかのルールに完全一致する場合のみ実行できます。許可されたコマンドには組み込み・追加の禁止ルールを適用しませんが、ネットワークとワークスペースの制限は適用されます。"},"tools_exec_deny_patterns": {"label": "禁止コマンド", "help": "これらのルールに一致するコマンドを禁止します。\n\n追加の禁止ルールを正規表現で 1 行に 1 つ指定します。明示的な許可ルールは、組み込み・追加の禁止ルールより優先されます。"},- "tools_web_proxy": {"label": "ウェブプロキシ", "help": "エージェントのウェブ検索とページ読み取りに使用します。空欄では、プロキシ環境変数を含む既定のネットワーク設定を使用します。\n\n127.0.0.1 は nanobot を実行するマシンです。モデル、MCP、ブラウザーの接続には影響しません。"},+ "network_proxy": {"label": "共有プロキシ", "help": "プロキシを有効にした機能で共有するアドレスです。127.0.0.1 は nanobot を実行する端末を指します。"},+ "tools_web_use_proxy": {"label": "プロキシを使う", "help": "ウェブ検索とページの読み取りに共有プロキシを使います。"},"tools_web_user_agent": {"label": "User-Agent ヘッダー", "help": "ウェブ要求の User-Agent です。空欄では既定値を使います。\n\nカスタムの User-Agent ヘッダー。空欄の場合は既定値を使用します。"},"tools_restrict_to_workspace": {"label": "ワークスペース制限", "help": "ワークスペースの全体制限です。WebUI のチャット権限は別に設定します。\n\nツール全体のアクセス方針です。WebUI の会話ごとの権限は別途設定します。"},"tools_ssrf_whitelist": {"label": "許可 IP", "help": "許可する IP または CIDR を1行に1つ指定します。\n\n送信リクエストの保護から除外する IP/CIDR 範囲。1 行に 1 つ指定します。"},@@ -552,7 +563,8 @@"sessions": {"title": "会話", "help": "複数プラットフォーム間のチャット共有を設定します。"},"tools": {"title": "組み込みツール", "help": "エージェントが使えるツールを選びます。"},"shell": {"title": "シェルとサンドボックス", "help": "コマンドの制限時間、環境、アクセスルールを設定します。"},- "network": {"title": "ウェブ接続", "help": "プロキシと User-Agent を設定します。\n\nプロキシとリクエストの識別情報。"},+ "proxy": {"title": "共有プロキシ", "help": "プロキシを使う機能の共有アドレスを設定します。"},+ "network": {"title": "ウェブ接続", "help": "ウェブリクエストのプロキシ使用と User-Agent を設定します。"},"safety": {"title": "全体の権限", "help": "ワークスペース制限、ネットワーク例外、リモートインストールを設定します。\n\nワークスペース制限、プライベートネットワーク、リモートインストール。"},"cli": {"title": "CLI 制限", "help": "インストール・実行の制限時間と一覧のキャッシュ期間を設定します。\n\nインストール、実行、カタログキャッシュの時間制限。"},"gateway": {"title": "ゲートウェイ", "help": "配置と再起動の方法を設定します。"},@@ -949,7 +961,6 @@"defaultAPIDescription": "自動に設定したプリセットはこの API を使用します。各プリセットでは対応 API の一覧から別の API を選択できます。","declareAPIs": "対応する API を設定","openaiDefaultAPIDescription": "自動を使うプリセットのデフォルト API を設定します。ここで自動を選ぶと既知のモデルルールに従います。各プリセットでこの設定を変更できます。",- "proxy": "ネットワークプロキシ","thinkingStyle": "推論の形式","region": "リージョン","profile": "AWS プロファイル",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "プリセットを保存する前に、このプロバイダーへサインインしてください。","signedIn": "サインイン済み","notSignedIn": "未サインイン",- "proxyLabel": "ネットワークプロキシ",- "proxySaveBeforeSignIn": "サインイン前にプロキシの変更を保存してください。",- "saveProxy": "プロキシを保存","localCodeHelp": "ブラウザーでサインインを完了してください。通常は nanobot が自動で完了します。完了しない場合は、認証コードを下に貼り付けてください。","remoteCodeHelp": "「サインイン」を選択して自分のコンピューターで xAI を開いてください。サインイン後、xAI に表示された認証コードを下に貼り付けてください。","localCallbackHelp": "ブラウザーでサインインを完了してください。通常は nanobot が自動で完了します。完了しない場合は、アドレスバーから localhost の完全なコールバック URL をコピーして下に貼り付けてください。",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 92786701c..5744278fa 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -491,6 +491,16 @@"description": "변경 사항이 저장되었습니다. 적용하려면 다시 시작하세요.","later": "나중에 다시 시작"},+ "network": {+ "useProxy": "프록시 사용",+ "useProxyHelp": "고급 설정의 공유 프록시를 사용합니다.",+ "configureProxy": "프록시 설정",+ "sharedProxyScope": "프록시를 켠 모든 기능에서 함께 사용합니다.",+ "authentication": "인증 (선택 사항)",+ "username": "사용자 이름",+ "password": "비밀번호",+ "proxyReferenceAuth": "참조된 프록시 URL에서 인증 정보를 설정하세요."+ },"runtimeConfig": {"apiSaved": "저장했습니다. API 서비스를 다시 시작하면 적용됩니다.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "환경 변수", "help": "명령에 추가로 전달할 변수 이름을 한 줄에 하나씩 입력하세요.\n\n명령에 전달할 환경 변수를 추가합니다. 한 줄에 하나씩 입력하세요. 실행에 필요한 기본 환경 변수는 계속 전달됩니다."},"tools_exec_allow_patterns": {"label": "허용 명령", "help": "허용 규칙과 완전히 일치하는 명령만 실행합니다.\n\n정규식을 한 줄에 하나씩 입력하세요. 규칙을 추가하면 명령의 각 부분이 규칙 중 하나와 완전히 일치해야 실행됩니다. 허용된 명령에는 기본 및 추가 차단 규칙이 적용되지 않지만, 네트워크와 작업 공간 제한은 유지됩니다."},"tools_exec_deny_patterns": {"label": "차단 명령", "help": "이 규칙과 일치하는 명령을 차단합니다.\n\n추가 차단 정규식을 한 줄에 하나씩 입력하세요. 명시적 허용 규칙이 기본 및 추가 차단 규칙보다 우선합니다."},- "tools_web_proxy": {"label": "웹 프록시", "help": "에이전트의 웹 검색과 페이지 읽기에 사용합니다. 비워 두면 프록시 환경 변수를 포함한 기본 네트워크 설정을 사용합니다.\n\n127.0.0.1은 nanobot이 실행되는 기기입니다. 모델, MCP 또는 브라우저 연결에는 영향을 주지 않습니다."},+ "network_proxy": {"label": "공유 프록시", "help": "프록시 사용이 켜진 기능에서 공유하는 주소입니다. 127.0.0.1은 nanobot을 실행하는 기기를 뜻합니다."},+ "tools_web_use_proxy": {"label": "프록시 사용", "help": "웹 검색과 페이지 읽기에 공유 프록시를 사용합니다."},"tools_web_user_agent": {"label": "User-Agent 헤더", "help": "웹 요청의 User-Agent입니다. 비워 두면 기본값을 사용합니다.\n\n사용자 지정 User-Agent 헤더입니다. 비워 두면 기본값을 사용합니다."},"tools_restrict_to_workspace": {"label": "작업 공간 제한", "help": "전체 작업 공간 제한입니다. WebUI 채팅 권한은 별도로 설정합니다.\n\n전체 도구 접근 정책입니다. WebUI의 대화별 권한은 별도로 설정합니다."},"tools_ssrf_whitelist": {"label": "허용 IP", "help": "허용할 IP 또는 CIDR 범위를 한 줄에 하나씩 입력하세요.\n\n외부 요청 보호에서 제외할 IP/CIDR 범위를 한 줄에 하나씩 입력하세요."},@@ -552,7 +563,8 @@"sessions": {"title": "대화", "help": "플랫폼 간 채팅 공유를 설정하세요."},"tools": {"title": "기본 도구", "help": "에이전트가 사용할 도구를 선택하세요."},"shell": {"title": "셸 및 샌드박스", "help": "명령 제한 시간, 환경 및 접근 규칙을 설정하세요."},- "network": {"title": "웹 연결", "help": "프록시와 User-Agent를 설정하세요.\n\n웹 프록시 및 요청 식별 정보입니다."},+ "proxy": {"title": "공유 프록시", "help": "프록시를 사용하는 기능의 공통 주소를 설정합니다."},+ "network": {"title": "웹 연결", "help": "웹 요청의 프록시 사용 여부와 User-Agent를 설정합니다."},"safety": {"title": "전체 권한", "help": "작업 공간 제한, 네트워크 예외 및 원격 설치를 설정하세요.\n\n작업 공간 제한, 사설 네트워크 및 원격 설치입니다."},"cli": {"title": "CLI 제한", "help": "설치와 실행 제한 시간, 목록 캐시 시간을 설정하세요.\n\n설치, 실행 및 카탈로그 캐시의 시간 제한입니다."},"gateway": {"title": "게이트웨이", "help": "배포와 재시작 옵션을 설정하세요."},@@ -949,7 +961,6 @@"defaultAPIDescription": "자동으로 설정한 프리셋은 이 API를 사용합니다. 개별 프리셋에서는 지원 목록의 다른 API를 선택할 수 있습니다.","declareAPIs": "지원 API 설정","openaiDefaultAPIDescription": "자동을 사용하는 프리셋의 기본 API를 설정합니다. 여기서 자동을 선택하면 알려진 모델 규칙을 따릅니다. 개별 프리셋에서 이 설정을 바꿀 수 있습니다.",- "proxy": "네트워크 프록시","thinkingStyle": "추론 형식","region": "리전","profile": "AWS 프로필",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "프리셋을 저장하기 전에 이 제공업체에 로그인하세요.","signedIn": "로그인됨","notSignedIn": "로그인 안 됨",- "proxyLabel": "네트워크 프록시",- "proxySaveBeforeSignIn": "로그인하기 전에 프록시 변경 사항을 저장하세요.",- "saveProxy": "프록시 저장","localCodeHelp": "브라우저에서 로그인을 완료하세요. 일반적으로 nanobot이 자동으로 완료합니다. 완료되지 않으면 인증 코드를 아래에 붙여 넣으세요.","remoteCodeHelp": "로그인을 선택하여 사용자 컴퓨터에서 xAI를 여세요. 로그인 후 xAI에 표시된 인증 코드를 아래에 붙여 넣으세요.","localCallbackHelp": "브라우저에서 로그인을 완료하세요. 일반적으로 nanobot이 자동으로 완료합니다. 완료되지 않으면 주소 표시줄에서 전체 localhost 콜백 URL을 복사해 아래에 붙여 넣으세요.",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex b989863a0..8c8cb0cf7 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -491,6 +491,16 @@"description": "As alterações foram salvas. Reinicie para aplicá-las.","later": "Reiniciar mais tarde"},+ "network": {+ "useProxy": "Usar proxy",+ "useProxyHelp": "Usa o proxy compartilhado dos ajustes avançados.",+ "configureProxy": "Configurar proxy",+ "sharedProxyScope": "Compartilhado por todos os recursos com proxy ativado.",+ "authentication": "Autenticação (opcional)",+ "username": "Usuário",+ "password": "Senha",+ "proxyReferenceAuth": "Configure a autenticação na URL do proxy referenciada."+ },"runtimeConfig": {"apiSaved": "Salvo. Reinicie o serviço de API para aplicar as alterações.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "Variáveis de ambiente", "help": "Variáveis extras para os comandos, um nome por linha.\n\nVariáveis adicionais passadas aos comandos, uma por linha. As variáveis básicas necessárias continuam disponíveis."},"tools_exec_allow_patterns": {"label": "Comandos permitidos", "help": "Execute apenas comandos que correspondam totalmente às regras de permissão.\n\nUma expressão regular por linha. Se houver regras, cada trecho do comando deve corresponder por completo a uma delas. Os comandos permitidos ignoram as regras de bloqueio integradas e personalizadas, mas continuam sujeitos às restrições de rede e do espaço de trabalho."},"tools_exec_deny_patterns": {"label": "Comandos bloqueados", "help": "Bloqueie comandos que correspondam a estas regras.\n\nExpressões regulares de bloqueio adicionais, uma por linha. As regras de permissão explícitas têm prioridade sobre as regras de bloqueio integradas e personalizadas."},- "tools_web_proxy": {"label": "Proxy web", "help": "Usado para a pesquisa web e a leitura de páginas pelo agente. Deixe em branco para usar a rede padrão, incluindo as variáveis de ambiente de proxy.\n\n127.0.0.1 é a máquina que executa nanobot. Esta configuração não altera as conexões de modelos, MCP ou do navegador."},+ "network_proxy": {"label": "Proxy compartilhado", "help": "Endereço usado pelos recursos com o proxy ativado. 127.0.0.1 é a máquina que executa nanobot."},+ "tools_web_use_proxy": {"label": "Usar proxy", "help": "Usa o proxy compartilhado para pesquisar na web e ler páginas."},"tools_web_user_agent": {"label": "Cabeçalho User-Agent", "help": "User-Agent das solicitações web; deixe vazio para usar o padrão.\n\nCabeçalho User-Agent personalizado. Deixe vazio para usar o valor padrão."},"tools_restrict_to_workspace": {"label": "Restrição do espaço", "help": "Limites globais do espaço; permissões de conversas WebUI são separadas.\n\nPolítica global das ferramentas. As permissões de cada conversa WebUI são configuradas separadamente."},"tools_ssrf_whitelist": {"label": "IPs permitidos", "help": "IPs ou faixas CIDR permitidos, um por linha.\n\nEndereços IP ou faixas CIDR isentos da proteção de solicitações de saída, um por linha."},@@ -552,7 +563,8 @@"sessions": {"title": "Conversas", "help": "Configure conversas compartilhadas entre plataformas."},"tools": {"title": "Ferramentas integradas", "help": "Escolha as ferramentas que o agente pode usar."},"shell": {"title": "Shell e sandbox", "help": "Configure tempos limite, ambiente e regras de acesso dos comandos."},- "network": {"title": "Conexões web", "help": "Configure o proxy e o User-Agent.\n\nProxy e identificação das solicitações web."},+ "proxy": {"title": "Proxy compartilhado", "help": "Defina um endereço para os recursos que usam proxy."},+ "network": {"title": "Conexões web", "help": "Configure o uso de proxy e o User-Agent das solicitações web."},"safety": {"title": "Permissões globais", "help": "Configure limites do espaço, exceções de rede e instalações remotas.\n\nRestrições do espaço de trabalho, redes privadas e instalações remotas."},"cli": {"title": "Limites CLI", "help": "Configure tempos limite de instalação e execução e duração do cache.\n\nTempos de instalação, execução e cache do catálogo."},"gateway": {"title": "Gateway", "help": "Configure implantação e reinício."},@@ -1193,7 +1205,6 @@"defaultAPIDescription": "As predefinições configuradas como Auto usam esta API. Cada predefinição pode escolher outra API da lista de APIs compatíveis.","declareAPIs": "Definir APIs compatíveis","openaiDefaultAPIDescription": "Define a API padrão das predefinições que usam Auto. Aqui, Auto segue as regras conhecidas do modelo. Cada predefinição pode alterar essa escolha.",- "proxy": "Proxy de rede","thinkingStyle": "Formato de raciocínio","region": "Região","profile": "Perfil da AWS",@@ -1602,9 +1613,6 @@"signInBeforeSaving": "Entre neste provedor antes de salvar a predefinição.","signedIn": "Conectado","notSignedIn": "Desconectado",- "proxyLabel": "Proxy de rede",- "proxySaveBeforeSignIn": "Salve as alterações do proxy antes de entrar.",- "saveProxy": "Salvar proxy","localCodeHelp": "Conclua o login no navegador. O nanobot geralmente termina automaticamente; caso contrário, cole o código de autorização abaixo.","remoteCodeHelp": "Selecione Entrar para abrir a xAI no seu computador. Após o login, cole abaixo o código de autorização exibido pela xAI.","localCallbackHelp": "Conclua o login no navegador. O nanobot geralmente termina automaticamente; caso contrário, copie da barra de endereço a URL completa de callback do localhost e cole abaixo.",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 500c149de..0e985c022 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -491,6 +491,16 @@"description": "Thay đổi đã được lưu. Khởi động lại để áp dụng.","later": "Khởi động lại sau"},+ "network": {+ "useProxy": "Dùng proxy",+ "useProxyHelp": "Dùng proxy chung trong phần Nâng cao.",+ "configureProxy": "Cấu hình proxy",+ "sharedProxyScope": "Dùng chung cho mọi tính năng đã bật proxy.",+ "authentication": "Xác thực (tùy chọn)",+ "username": "Tên người dùng",+ "password": "Mật khẩu",+ "proxyReferenceAuth": "Thiết lập xác thực trong URL proxy được tham chiếu."+ },"runtimeConfig": {"apiSaved": "Đã lưu. Khởi động lại dịch vụ API để áp dụng thay đổi.","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "Biến môi trường", "help": "Thêm biến truyền cho lệnh, mỗi dòng một tên.\n\nCác biến môi trường bổ sung được truyền cho lệnh, mỗi dòng một tên. Các biến cơ bản cần cho hoạt động vẫn được truyền."},"tools_exec_allow_patterns": {"label": "Lệnh được phép", "help": "Chỉ chạy lệnh khớp hoàn toàn với quy tắc cho phép.\n\nMỗi dòng một biểu thức chính quy. Khi có quy tắc, từng phần của lệnh phải khớp hoàn toàn với ít nhất một quy tắc. Lệnh được phép sẽ bỏ qua quy tắc chặn tích hợp và bổ sung, nhưng vẫn chịu giới hạn mạng và không gian làm việc."},"tools_exec_deny_patterns": {"label": "Lệnh bị chặn", "help": "Chặn lệnh khớp với các quy tắc này.\n\nQuy tắc chặn bổ sung dưới dạng biểu thức chính quy, mỗi dòng một quy tắc. Quy tắc cho phép được ưu tiên hơn cả quy tắc chặn tích hợp và bổ sung."},- "tools_web_proxy": {"label": "Proxy web", "help": "Dùng cho tìm kiếm web và đọc trang của tác nhân. Để trống để dùng mạng mặc định, bao gồm các biến môi trường proxy.\n\n127.0.0.1 là máy chạy nanobot. Cài đặt này không thay đổi kết nối mô hình, MCP hoặc trình duyệt."},+ "network_proxy": {"label": "Proxy chung", "help": "Địa chỉ dùng cho các tính năng đã bật proxy. 127.0.0.1 là máy chạy nanobot."},+ "tools_web_use_proxy": {"label": "Dùng proxy", "help": "Dùng proxy chung để tìm kiếm web và đọc trang."},"tools_web_user_agent": {"label": "Header User-Agent", "help": "User-Agent cho yêu cầu web; để trống để dùng mặc định.\n\nHeader User-Agent tùy chỉnh cho yêu cầu web. Để trống để dùng giá trị mặc định."},"tools_restrict_to_workspace": {"label": "Giới hạn vùng làm việc", "help": "Giới hạn vùng làm việc chung; quyền trò chuyện WebUI được đặt riêng.\n\nChính sách công cụ toàn cục. Quyền của từng cuộc trò chuyện WebUI được đặt riêng."},"tools_ssrf_whitelist": {"label": "IP được phép", "help": "IP hoặc dải CIDR được phép, mỗi dòng một mục.\n\nIP hoặc dải CIDR được miễn bảo vệ yêu cầu ra ngoài, mỗi dòng một mục."},@@ -552,7 +563,8 @@"sessions": {"title": "Cuộc trò chuyện", "help": "Đặt chia sẻ trò chuyện giữa các nền tảng."},"tools": {"title": "Công cụ tích hợp", "help": "Chọn công cụ agent được phép dùng."},"shell": {"title": "Shell và sandbox", "help": "Đặt thời hạn lệnh, môi trường và quy tắc truy cập."},- "network": {"title": "Kết nối web", "help": "Đặt proxy và User-Agent.\n\nProxy và thông tin nhận dạng yêu cầu web."},+ "proxy": {"title": "Proxy chung", "help": "Đặt một địa chỉ cho các tính năng dùng proxy."},+ "network": {"title": "Kết nối web", "help": "Đặt tùy chọn proxy và User-Agent cho yêu cầu web."},"safety": {"title": "Quyền chung", "help": "Đặt giới hạn vùng làm việc, ngoại lệ mạng và cài đặt từ xa.\n\nGiới hạn không gian làm việc, mạng riêng và cài đặt từ xa."},"cli": {"title": "Giới hạn CLI", "help": "Đặt thời hạn cài đặt, chạy và thời gian cache danh sách.\n\nGiới hạn thời gian cài đặt, thực thi và lưu đệm danh mục."},"gateway": {"title": "Gateway", "help": "Đặt cách triển khai và khởi động lại."},@@ -949,7 +961,6 @@"defaultAPIDescription": "Cấu hình sẵn đặt ở Tự động sẽ dùng API này. Mỗi cấu hình sẵn có thể chọn API khác trong danh sách được hỗ trợ.","declareAPIs": "Đặt API được hỗ trợ","openaiDefaultAPIDescription": "Đặt API mặc định cho cấu hình sẵn dùng Tự động. Chọn Tự động tại đây sẽ áp dụng quy tắc đã biết của mô hình. Mỗi cấu hình sẵn có thể thay đổi lựa chọn này.",- "proxy": "Proxy mạng","thinkingStyle": "Định dạng suy luận","region": "Khu vực","profile": "Hồ sơ AWS",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "Hãy đăng nhập nhà cung cấp này trước khi lưu cấu hình đặt trước.","signedIn": "Đã đăng nhập","notSignedIn": "Chưa đăng nhập",- "proxyLabel": "Proxy mạng",- "proxySaveBeforeSignIn": "Hãy lưu thay đổi proxy trước khi đăng nhập.",- "saveProxy": "Lưu proxy","localCodeHelp": "Hoàn tất đăng nhập trong trình duyệt. nanobot thường tự động hoàn tất; nếu không, hãy dán mã ủy quyền bên dưới.","remoteCodeHelp": "Chọn Đăng nhập để mở xAI trên máy tính của bạn. Sau khi đăng nhập, hãy dán mã ủy quyền do xAI hiển thị bên dưới.","localCallbackHelp": "Hoàn tất đăng nhập trong trình duyệt. nanobot thường tự động hoàn tất; nếu không, hãy sao chép URL callback localhost đầy đủ từ thanh địa chỉ và dán vào bên dưới.",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 9d4cb5397..c1f47e320 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -491,6 +491,16 @@"description": "更改已保存,重启后生效。","later": "稍后重启"},+ "network": {+ "useProxy": "使用代理",+ "useProxyHelp": "使用高级设置中的共享代理。",+ "configureProxy": "配置代理",+ "sharedProxyScope": "供所有启用代理的功能共用。",+ "authentication": "认证(可选)",+ "username": "用户名",+ "password": "密码",+ "proxyReferenceAuth": "请在引用的代理 URL 中设置认证信息。"+ },"runtimeConfig": {"apiSaved": "已保存,重启 API 服务后生效。","commandRuntime": {@@ -609,9 +619,13 @@"label": "禁止命令","help": "阻止匹配规则的命令\n\n每行一个正则表达式,与内置拒绝规则一同检查。完整匹配允许规则的命令会跳过这些检查。"},- "tools_web_proxy": {- "label": "网页代理",- "help": "用于智能体搜索和读取网页。留空使用默认网络设置,包括环境变量中的代理。\n\n127.0.0.1 指运行 nanobot 的机器,不是打开网页的手机。本设置不影响模型、MCP 或浏览器的连接。"+ "network_proxy": {+ "label": "共享代理",+ "help": "启用“使用代理”的功能共用此地址。127.0.0.1 指运行 nanobot 的设备。"+ },+ "tools_web_use_proxy": {+ "label": "使用代理",+ "help": "网页搜索和读取使用共享代理。"},"tools_web_user_agent": {"label": "User-Agent",@@ -699,9 +713,13 @@"title": "Shell 与沙箱","help": "设置命令超时、环境和访问规则"},+ "proxy": {+ "title": "共享代理",+ "help": "为使用代理的功能设置共享地址。"+ },"network": {"title": "网页连接",- "help": "设置代理和 User-Agent\n\n设置网页访问代理和 User-Agent 标识。"+ "help": "设置网页请求的代理开关和 User-Agent。"},"safety": {"title": "全局权限",@@ -1379,7 +1397,6 @@"defaultAPIDescription": "预设选择「自动」时使用此协议。单个预设可改用支持列表中的其他协议。","declareAPIs": "设置支持的协议","openaiDefaultAPIDescription": "设为「自动」的预设使用此默认协议。此处选择「自动」会遵循已知模型规则;单个预设可以覆盖此默认值。",- "proxy": "网络代理","thinkingStyle": "推理格式","region": "区域","profile": "AWS 配置名称",@@ -1788,9 +1805,6 @@"signInBeforeSaving": "请先登录此提供商,再保存模型预设。","signedIn": "已登录","notSignedIn": "未登录",- "proxyLabel": "网络代理",- "proxySaveBeforeSignIn": "请先保存代理更改再登录。",- "saveProxy": "保存代理","localCodeHelp": "请在浏览器中完成登录。若 nanobot 未自动完成连接,请将授权码粘贴到下方。","remoteCodeHelp": "点击“登录”在你的电脑上打开 xAI。完成登录后,请将 xAI 显示的授权码粘贴到下方。","localCallbackHelp": "请在浏览器中完成登录。若 nanobot 未自动完成连接,请复制地址栏中完整的 localhost 回调地址,粘贴到下方。",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 5e148a5ae..efb41ee1e 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -491,6 +491,16 @@"description": "變更已儲存,重新啟動後生效。","later": "稍後重新啟動"},+ "network": {+ "useProxy": "使用代理",+ "useProxyHelp": "使用進階設定中的共用代理。",+ "configureProxy": "設定代理",+ "sharedProxyScope": "供所有啟用代理的功能共用。",+ "authentication": "認證(選填)",+ "username": "使用者名稱",+ "password": "密碼",+ "proxyReferenceAuth": "請在參照的代理 URL 中設定認證資訊。"+ },"runtimeConfig": {"apiSaved": "已儲存,重新啟動 API 服務後生效。","commandRuntime": {@@ -528,7 +538,8 @@"tools_exec_allowed_env_keys": {"label": "環境變數", "help": "額外傳給命令的變數名,每行一個\n\n除必需變數外,還要從主機傳遞給命令的環境變數名稱,每行一個。"},"tools_exec_allow_patterns": {"label": "允許命令", "help": "只允許完整匹配規則的命令\n\n每行一個正規表示式。填寫後,只允許每段命令都完整匹配規則的命令執行,且優先於內建和自定義拒絕規則;工作區和網路限制仍生效。"},"tools_exec_deny_patterns": {"label": "禁止命令", "help": "阻止匹配規則的命令\n\n每行一個正規表示式,與內建拒絕規則一同檢查。完整匹配允許規則的命令會跳過這些檢查。"},- "tools_web_proxy": {"label": "網頁代理", "help": "用於智慧體搜尋和讀取網頁。留空使用預設網路設定,包括環境變數中的代理。\n\n127.0.0.1 指執行 nanobot 的機器,不是開啟網頁的手機。本設定不影響模型、MCP 或瀏覽器的連線。"},+ "network_proxy": {"label": "共用代理", "help": "啟用「使用代理」的功能共用此位址。127.0.0.1 指執行 nanobot 的裝置。"},+ "tools_web_use_proxy": {"label": "使用代理", "help": "網頁搜尋與讀取使用共用代理。"},"tools_web_user_agent": {"label": "User-Agent", "help": "網頁請求標識,留空使用預設值\n\n網頁請求使用的 User-Agent 標識,留空使用預設值。"},"tools_restrict_to_workspace": {"label": "目錄限制", "help": "全域性目錄限制,WebUI 許可權另設\n\n設定全域性工作區訪問限制;WebUI 中每個對話的許可權單獨設定。"},"tools_ssrf_whitelist": {"label": "允許 IP", "help": "允許訪問的 IP 或 CIDR,每行一項\n\n允許網頁等出站請求訪問這些受限地址。每行填寫一個 IP 地址或 CIDR 網段。"},@@ -552,7 +563,8 @@"sessions": {"title": "對話", "help": "設定跨平臺對話共享"},"tools": {"title": "內建工具", "help": "選擇智慧體可以使用的工具"},"shell": {"title": "Shell 與沙箱", "help": "設定命令超時、環境和訪問規則"},- "network": {"title": "網頁連線", "help": "設定代理和 User-Agent\n\n設定網頁訪問代理和 User-Agent 標識。"},+ "proxy": {"title": "共用代理", "help": "為使用代理的功能設定共用位址。"},+ "network": {"title": "網頁連線", "help": "設定網頁請求的代理開關與 User-Agent。"},"safety": {"title": "全域性許可權", "help": "設定目錄限制、網路例外和遠端安裝\n\n設定工作區訪問限制、網路訪問例外和遠端安裝許可權。"},"cli": {"title": "CLI 限制", "help": "設定安裝、執行超時和列表快取\n\n設定安裝和執行超時,以及應用列表的快取時長。"},"gateway": {"title": "閘道器", "help": "設定部署和重啟方式"},@@ -949,7 +961,6 @@"defaultAPIDescription": "預設選擇「自動」時使用此協定。個別預設可改用支援清單中的其他協定。","declareAPIs": "設定支援的協定","openaiDefaultAPIDescription": "設為「自動」的預設使用此預設協定。此處選擇「自動」會遵循已知模型規則;個別預設可以覆寫此預設值。",- "proxy": "網路代理","thinkingStyle": "推理格式","region": "區域","profile": "AWS 設定檔名稱",@@ -1588,9 +1599,6 @@"signInBeforeSaving": "請先登入此供應商,再儲存模型預設。","signedIn": "已登入","notSignedIn": "未登入",- "proxyLabel": "網路代理",- "proxySaveBeforeSignIn": "請先儲存代理變更再登入。",- "saveProxy": "儲存代理","localCodeHelp": "請在瀏覽器中完成登入。nanobot 通常會自動完成;若未自動完成,請將授權碼貼到下方。","remoteCodeHelp": "請點選 [登入],在電腦上開啟 xAI。完成登入後,請將 xAI 顯示的授權碼貼到下方。","localCallbackHelp": "請在瀏覽器中完成登入。nanobot 通常會自動完成;若未自動完成,請複製網址列中的完整 localhost 回呼 URL 並貼到下方。",diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.tsindex 2a397ba4b..79c6dd296 100644--- a/webui/src/lib/api.ts+++ b/webui/src/lib/api.ts@@ -1211,7 +1211,7 @@ export async function fetchProviderModels(export async function runMcpPresetAction(transport: WebUIMutationTransport,- action: "enable" | "disable" | "remove" | "test" | "reconnect",+ action: "enable" | "disable" | "remove" | "test" | "reconnect" | "proxy",name: string,values: Record<string, string> = {},): Promise<McpPresetsPayload> {diff --git a/webui/src/lib/proxy-url.ts b/webui/src/lib/proxy-url.tsnew file mode 100644index 000000000..99c6dabcc--- /dev/null+++ b/webui/src/lib/proxy-url.ts@@ -0,0 +1,63 @@+const environmentReference = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/;++function decodeCredential(value: string): string {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}++function encodeCredential(value: string): string {+ return value.split(/(\$\{[A-Za-z_][A-Za-z0-9_]*\})/).map((part) =>+ environmentReference.test(part) ? part : encodeURIComponent(part),+ ).join("");+}++export function splitProxyUrl(value: string) {+ const schemeEnd = value.indexOf("://");+ const start = schemeEnd < 0 ? 0 : schemeEnd + 3;+ const authorityEnd = value.slice(start).search(/[/?#]/);+ const end = authorityEnd < 0 ? value.length : start + authorityEnd;+ const at = value.lastIndexOf("@", end - 1);+ const userinfo = at >= start ? value.slice(start, at) : null;+ const colon = userinfo?.indexOf(":") ?? -1;+ const rawUsername = userinfo === null ? "" : colon < 0 ? userinfo : userinfo.slice(0, colon);+ const rawPassword = userinfo === null || colon < 0 ? "" : userinfo.slice(colon + 1);+ return {+ address: userinfo === null ? value : value.slice(0, start) + value.slice(at + 1),+ username: decodeCredential(rawUsername),+ password: decodeCredential(rawPassword),+ rawUsername,+ rawPassword,+ userinfo,+ hasColon: colon >= 0,+ };+}++function insertUserinfo(address: string, userinfo: string | null): string {+ if (userinfo === null) return address;+ const schemeEnd = address.indexOf("://");+ const start = schemeEnd < 0 ? 0 : schemeEnd + 3;+ return address.slice(0, start) + userinfo + "@" + address.slice(start);+}++export function changeProxyAddress(value: string, address: string): string {+ if (!address.trim() || isProxyUrlReference(address)) return address;+ const pasted = splitProxyUrl(address);+ if (pasted.userinfo !== null) return address;+ return insertUserinfo(address, splitProxyUrl(value).userinfo);+}++export function changeProxyAuthentication(value: string, username: string, password: string): string {+ const current = splitProxyUrl(value);+ if (!username && !password) return current.address;+ const user = username === current.username ? current.rawUsername : encodeCredential(username);+ const pass = password === current.password ? current.rawPassword : encodeCredential(password);+ const separator = current.hasColon || password ? ":" : "";+ return insertUserinfo(current.address, user + separator + pass);+}++export function isProxyUrlReference(address: string): boolean {+ return /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(address.trim());+}diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 43752e9e7..cd58f1b79 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -748,12 +748,12 @@ export interface SettingsPayload {oauth_account?: string | null;oauth_expires_at?: number | null;oauth_login_supported?: boolean;- proxy?: string | null;+ use_proxy?: boolean;advanced_fields?: Array<| "extra_headers"| "extra_body"| "extra_query"- | "proxy"+ | "use_proxy"| "thinking_style"| "region"| "profile"@@ -779,7 +779,7 @@ export interface SettingsPayload {};web: {enable: boolean;- proxy?: string | null;+ use_proxy?: boolean;user_agent?: string | null;search: {max_results: number;@@ -1242,6 +1242,7 @@ export interface McpPresetInfo {docs_url: string;transport: "stdio" | "streamableHttp" | "sse" | "oauth" | string;auth?: "oauth" | null;+ use_proxy?: boolean;requires: string;note: string;install_supported: boolean;@@ -1290,6 +1291,7 @@ export interface McpOAuthFlowPayload {export interface McpPresetsPayload {presets: McpPresetInfo[];+ proxy_configured?: boolean;installed_count: number;requires_restart?: boolean;hot_reload?: {@@ -1376,7 +1378,7 @@ export interface ProviderSettingsUpdate {apiKey?: string;apiBase?: string;api?: ModelAPIConfig | null;- proxy?: string;+ use_proxy?: boolean;extraHeaders?: string;extraBody?: string;extraQuery?: string;@@ -1390,7 +1392,7 @@ export interface ProviderCreationUpdate {apiKey?: string;apiBase: string;api?: ModelAPIConfig | null;- proxy?: string;+ use_proxy?: boolean;extraHeaders?: string;extraBody?: string;extraQuery?: string;diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.tsindex 26d86fafa..bcf346bbc 100644--- a/webui/src/tests/api.test.ts+++ b/webui/src/tests/api.test.ts@@ -841,7 +841,7 @@ describe("webui API helpers", () => {it("serializes OAuth provider advanced settings", async () => {await updateProviderSettings(mutationTransport, {provider: "xai_grok",- proxy: "http://127.0.0.1:7890",+ use_proxy: true,extraBody: '{"tools":[]}',});@@ -849,7 +849,7 @@ describe("webui API helpers", () => {"settings.provider.update",{provider: "xai_grok",- proxy: "http://127.0.0.1:7890",+ use_proxy: true,extraBody: '{"tools":[]}',},20_000,@@ -864,7 +864,7 @@ describe("webui API helpers", () => {extraHeaders: '{"X-Tenant":"engineering"}',extraBody: '{"service_tier":"priority"}',extraQuery: '{"api-version":"2026-01-01"}',- proxy: "http://127.0.0.1:7890",+ use_proxy: true,thinkingStyle: "enable_thinking",};await createProviderSettings(mutationTransport, update);@@ -1182,6 +1182,18 @@ describe("webui API helpers", () => {);});+ it.each(["true", "false"])("preserves explicit MCP proxy flag %s across setup and edits", async (use_proxy) => {+ await runMcpPresetAction(mutationTransport, "enable", "notion", { use_proxy });+ expect(requestMutation).toHaveBeenLastCalledWith("settings.mcp.enable", { name: "notion", use_proxy }, 20_000);+ await startMcpOAuth(mutationTransport, "notion", false, { use_proxy });+ expect(requestMutation).toHaveBeenLastCalledWith("settings.mcp.oauth_start", { name: "notion", use_proxy }, 30_000);+ await runMcpPresetAction(mutationTransport, "proxy", "notion", { use_proxy });+ expect(requestMutation).toHaveBeenLastCalledWith("settings.mcp.proxy", { name: "notion", use_proxy }, 20_000);+ const custom = { name: "docs", transport: "sse", url: "https://example.com/sse", use_proxy };+ await saveCustomMcpServer(mutationTransport, custom);+ expect(requestMutation).toHaveBeenLastCalledWith("settings.mcp.custom", custom, 20_000);+ });+it("serializes custom MCP, mcp.json import, and tool allowlist actions", async () => {const custom = {name: "docs",diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsxindex de6159f77..ada93de4a 100644--- a/webui/src/tests/app-layout.test.tsx+++ b/webui/src/tests/app-layout.test.tsx@@ -122,7 +122,7 @@ function baseSettingsPayload() {},web: {enable: true,- proxy: null,+ use_proxy: false,user_agent: null,search: { max_results: 5, timeout: 30 },fetch: { use_jina_reader: true },@@ -3482,7 +3482,7 @@ describe("App layout", () => {},web: {enable: true,- proxy: null,+ use_proxy: false,user_agent: null,search: { max_results: 5, timeout: 30 },fetch: { use_jina_reader: true },diff --git a/webui/src/tests/channel-credential-form.test.tsx b/webui/src/tests/channel-credential-form.test.tsxindex b6b54132d..211668380 100644--- a/webui/src/tests/channel-credential-form.test.tsx+++ b/webui/src/tests/channel-credential-form.test.tsx@@ -54,6 +54,32 @@ describe("CredentialForm", () => {expect(onChange).toHaveBeenCalledWith(key, "");});+ it.each(["telegram", "discord", "matrix", "slack", "whatsapp"])("renders %s proxy configuration as a switch and submits both boolean states", (channel) => {+ const key = `channels.${channel}.useProxy`;+ const setup = channelSetup({+ name: channel, display_name: channel, type: "channel", enabled: true,+ webui: channel === "whatsapp" ? "webui/index.tsx" : "webui/index.ts",+ installed: true, ready: true, status: "enabled",+ install_supported: true, requires_restart: false,+ setup: { fields: [{ key, field: "use_proxy", kind: "bool", choices: [], required: false, default_value: "false" }] },+ });+ const proxyFields = [...setup.fields ?? [], ...setup.manualFields ?? []];+ expect(proxyFields[0].section).toBe("connection");+ const onChange = vi.fn();+ const { rerender } = render(<CredentialForm fields={proxyFields} values={{ [key]: "true" }}+ visibleSecrets={{}} onChange={onChange} onToggleSecret={vi.fn()} />);+ const useProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(useProxy).toBeChecked();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ fireEvent.click(useProxy);+ expect(onChange).toHaveBeenCalledWith(key, "false");+ expect(channelValuesForSubmit(proxyFields, { [key]: "false" }, new Set([key]))).toEqual({ [key]: "false" });+ rerender(<CredentialForm fields={proxyFields} values={{ [key]: "false" }}+ visibleSecrets={{}} onChange={onChange} onToggleSecret={vi.fn()} />);+ fireEvent.click(screen.getByRole("switch", { name: "Use proxy" }));+ expect(onChange).toHaveBeenLastCalledWith(key, "true");+ });+it("uses native radio semantics for option fields", () => {const onChange = vi.fn();render(diff --git a/webui/src/tests/mcp-management-dialog.test.tsx b/webui/src/tests/mcp-management-dialog.test.tsxindex 18a38d241..1a17d6056 100644--- a/webui/src/tests/mcp-management-dialog.test.tsx+++ b/webui/src/tests/mcp-management-dialog.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";import { useState } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -6,8 +6,18 @@ import {McpManagementDialog,type McpManagementTab,} from "@/components/settings/system/McpManagementDialog";+import { createSystemSettingsActions } from "@/components/settings/system/createSystemSettingsActions";+import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";import i18n from "@/i18n";-import type { McpPresetInfo } from "@/lib/types";+import { NanobotClient } from "@/lib/nanobot-client";+import type { McpPresetInfo, McpPresetsPayload } from "@/lib/types";+import {+ installSettingsViewTestHooks,+ jsonResponse,+ renderSettingsView,+ requestMutationMock,+ settingsPayload,+} from "@/tests/settings-test-utils";const connectedPreset: McpPresetInfo = {name: "docs",@@ -83,6 +93,51 @@ describe("McpManagementDialog", () => {expect(onAction).toHaveBeenCalledWith("reconnect", "docs", {});});+ it.each(["streamableHttp", "sse"])("edits an existing %s proxy flag without restarting OAuth", (transport) => {+ const onAction = vi.fn();+ const { updateDialog } = renderDialog({+ initialTab: "connection", onAction,+ preset: { ...connectedPreset, transport, use_proxy: true },+ });+ const useProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(useProxy).toBeChecked();+ expect(screen.queryByRole("textbox", { name: /proxy/i })).not.toBeInTheDocument();+ fireEvent.click(useProxy);+ expect(onAction).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ expect(onAction).toHaveBeenCalledWith("proxy", "docs", { use_proxy: "false" });+ updateDialog({ ...connectedPreset, transport, use_proxy: false });+ expect(useProxy).not.toBeChecked();+ expect(screen.queryByRole("button", { name: "Save changes" })).not.toBeInTheDocument();+ });++ it("shows proxy guidance on demand without changing the connection draft", async () => {+ const onAction = vi.fn();+ renderDialog({ initialTab: "connection", onAction });+ expect(screen.queryByText("Uses the shared proxy in Advanced.")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Use proxy" }));+ expect(await screen.findByRole("tooltip")).toHaveTextContent("Uses the shared proxy in Advanced.");+ expect(onAction).not.toHaveBeenCalled();+ expect(screen.getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ expect(screen.queryByRole("button", { name: "Save changes" })).not.toBeInTheDocument();+ });++ it("preserves the configured proxy flag when reconnecting OAuth", () => {+ const onOAuthConnect = vi.fn();+ renderDialog({+ initialTab: "connection", onOAuthConnect,+ preset: { ...connectedPreset, auth: "oauth", use_proxy: true },+ });+ expect(screen.getByRole("switch", { name: "Use proxy" })).toBeChecked();+ fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));+ expect(onOAuthConnect).toHaveBeenCalledWith("docs", true, { use_proxy: "true" });+ });++ it("does not offer a proxy switch for stdio servers", () => {+ renderDialog({ initialTab: "connection", preset: { ...connectedPreset, transport: "stdio" } });+ expect(screen.queryByRole("switch", { name: "Use proxy" })).not.toBeInTheDocument();+ });+it("loads tools on entry and replaces passive inspection copy with recovery", async () => {const onAction = vi.fn();renderDialog({@@ -154,21 +209,24 @@ function renderDialog({initialTab,onAction = vi.fn(),onToolsChange = vi.fn(),+ onOAuthConnect = vi.fn(),preset = connectedPreset,actionKey = null,}: {initialTab: McpManagementTab;onAction?: ReturnType<typeof vi.fn>;onToolsChange?: ReturnType<typeof vi.fn>;+ onOAuthConnect?: ReturnType<typeof vi.fn>;preset?: McpPresetInfo;actionKey?: string | null;}) {function Harness({ preset, actionKey }: { preset: McpPresetInfo; actionKey: string | null }) {const [tab, setTab] = useState(initialTab);+ const [values, setValues] = useState<Record<string, string>>({});return (<McpManagementDialogpreset={preset}- values={{}}+ values={values}actionKey={actionKey}statusLabel="Connected"statusTone="success"@@ -176,9 +234,9 @@ function renderDialog({icon={<span aria-hidden>DM</span>}onTabChange={setTab}onOpenChange={vi.fn()}- onFieldChange={vi.fn()}+ onFieldChange={(_name, field, value) => setValues((prev) => ({ ...prev, [field]: value }))}onAction={onAction}- onOAuthConnect={vi.fn()}+ onOAuthConnect={onOAuthConnect}onToolsChange={onToolsChange}/>);@@ -191,3 +249,241 @@ function renderDialog({},};}++describe("MCP connection draft lifecycle", () => {+ installSettingsViewTestHooks();++ const metabasePreset: McpPresetInfo = {+ ...connectedPreset,+ name: "metabase",+ display_name: "Metabase",+ auth: "oauth",+ source: "preset",+ required_fields: [{+ name: "mcp_url", label: "MCP server URL", secret: false, required: true, configured: true,+ }],+ };++ it("reopens and reconnects without proxy after OAuth with proxy and a same-endpoint import", async () => {+ const endpoint = "https://app.xmind.com/api/mcp";+ let preset: McpPresetInfo = {+ ...connectedPreset,+ name: "xmind",+ display_name: "Xmind",+ auth: "oauth",+ source: "preset",+ installed: false,+ configured: false,+ available: false,+ status: "not_installed",+ runtime_status: undefined,+ connection_summary: "",+ use_proxy: false,+ };+ const importedConfig = JSON.stringify({+ mcpServers: { Xmind: { url: endpoint, auth: "oauth", useProxy: false } },+ });+ vi.stubGlobal("open", vi.fn(() => null));+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settingsPayload());+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") {+ return jsonResponse({ presets: [preset], installed_count: Number(preset.installed) });+ }+ if (url === "/api/settings/mcp-oauth/status?flow_id=flow-proxy") {+ preset = {+ ...preset,+ installed: true,+ configured: true,+ available: true,+ status: "configured",+ runtime_status: "connected",+ connection_summary: endpoint,+ use_proxy: true,+ };+ return jsonResponse({+ flow_id: "flow-proxy", name: "xmind", status: "connected", expires_in: 299,+ });+ }+ return { ok: false, status: 404, text: async () => "Not found" } as Response;+ }));+ requestMutationMock.mockImplementation(async (action: string) => {+ if (action === "settings.mcp.oauth_start") {+ return {+ flow_id: "flow-proxy", name: "xmind", status: "authorization_required", expires_in: 300,+ authorization_url: "https://accounts.xmind.test/authorize?state=proxy",+ };+ }+ if (action === "settings.mcp.import") {+ preset = { ...preset, use_proxy: false };+ return {+ presets: [preset], installed_count: 1,+ last_action: { ok: true, message: "Imported 1 MCP server(s)." },+ };+ }+ if (action === "settings.mcp.oauth_cancel") {+ return { flow_id: "flow-proxy", name: "xmind", status: "cancelled", expires_in: 299 };+ }+ throw new Error(`Unexpected mutation: ${action}`);+ });++ renderSettingsView({ initialSection: "apps" });+ fireEvent.click(await screen.findByRole("button", { name: "MCP" }));+ fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ fireEvent.click(screen.getByRole("switch", { name: "Use proxy" }));+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.mcp.oauth_start", { name: "xmind", use_proxy: "true" }, 30_000,+ ));+ await screen.findByRole("button", { name: "Manage Xmind" });++ fireEvent.click(screen.getByRole("button", { name: "Import" }));+ fireEvent.click(screen.getByRole("button", { name: "Import mcp.json" }));+ const editor = screen.getByRole("dialog", { name: "Import mcp.json" });+ fireEvent.change(within(editor).getByRole("textbox", { name: "Import mcp.json" }), {+ target: { value: importedConfig },+ });+ await act(async () => fireEvent.click(within(editor).getByRole("button", { name: "Save" })));+ await act(async () => fireEvent.click(screen.getAllByRole("button", { name: "Import" })[1]));+ expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.mcp.import", { config: importedConfig }, 20_000,+ );++ fireEvent.click(screen.getByRole("button", { name: "Manage Xmind" }));+ fireEvent.click(screen.getByRole("tab", { name: "Connection" }));+ expect(screen.getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ expect(screen.getByText(endpoint)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(+ "settings.mcp.oauth_start", { name: "xmind", reset: true, use_proxy: "false" }, 30_000,+ ));+ const cancel = await screen.findByRole("button", { name: "Cancel" });+ await act(async () => fireEvent.click(cancel));+ });++ it("retires the consumed OAuth proxy draft only after success, preserving a failed attempt", async () => {+ const { result } = renderMcpActions();+ const drafts = { docs: { use_proxy: "true" }, metabase: { mcp_url: "https://analytics.example.com/mcp", use_proxy: "true" } };+ await act(async () => result.current.state.setMcpFieldValues(drafts));+ vi.stubGlobal("open", vi.fn(() => null));+ requestMutationMock.mockResolvedValueOnce({+ flow_id: "flow-failed", name: "docs", status: "failed", error: "Proxy connection failed", expires_in: 300,+ });++ await act(async () => result.current.actions.handleMcpOAuthConnect("docs", false, drafts.docs));+ expect(result.current.state.mcpError).toBe("Proxy connection failed");+ expect(result.current.state.mcpFieldValues).toEqual(drafts);++ requestMutationMock.mockResolvedValueOnce({+ flow_id: "flow-connected", name: "docs", status: "connected", expires_in: 300,+ });+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({+ presets: [{ ...connectedPreset, auth: "oauth", use_proxy: true }], installed_count: 1,+ })));+ await act(async () => result.current.actions.handleMcpOAuthConnect("docs", false, drafts.docs));+ expect(result.current.state.mcpPresets?.presets[0].use_proxy).toBe(true);+ expect(result.current.state.mcpFieldValues).toEqual({ docs: {}, metabase: drafts.metabase });+ });++ it.each([true, false])("reconciles only accepted import names (mcpServers wrapper: %s)", async (wrapped) => {+ const { result } = renderMcpActions();+ const drafts = {+ metabase: { use_proxy: "true", mcp_url: "https://analytics.example.com/mcp" },+ docs: { use_proxy: "true" },+ };+ const servers = { Metabase: { url: metabasePreset.connection_summary, auth: "oauth", useProxy: false } };+ const config = JSON.stringify(wrapped ? { mcpServers: servers } : servers);+ await act(async () => {+ result.current.state.setMcpFieldValues(drafts);+ result.current.state.setMcpConfigImport(config);+ });+ requestMutationMock.mockRejectedValueOnce(new Error("Import could not be saved"));+ await act(async () => result.current.actions.handleImportMcpConfig());+ expect(result.current.state.mcpFieldValues).toEqual(drafts);+ expect(result.current.state.mcpConfigImport).toBe(config);++ requestMutationMock.mockResolvedValueOnce({+ presets: [{ ...metabasePreset, use_proxy: false }, connectedPreset],+ installed_count: 2,+ last_action: { ok: true, message: "Imported 1 MCP server(s)." },+ });+ await act(async () => result.current.actions.handleImportMcpConfig());+ expect(result.current.state.mcpFieldValues).toEqual({+ metabase: { mcp_url: drafts.metabase.mcp_url }, docs: drafts.docs,+ });+ expect(result.current.state.mcpConfigImport).toBe("");+ });++ it("reconciles a saved custom replacement even while its OAuth authorization is pending", async () => {+ const { result } = renderMcpActions();+ await act(async () => {+ result.current.state.setMcpFieldValues({+ metabase: { use_proxy: "true", mcp_url: "https://analytics.example.com/mcp" }, docs: { use_proxy: "true" },+ });+ result.current.state.setCustomMcpForm((prev) => ({+ ...prev, name: "Metabase", transport: "streamableHttp", auth: "oauth",+ url: metabasePreset.connection_summary, useProxy: false,+ }));+ });+ requestMutationMock.mockResolvedValueOnce({+ presets: [{ ...metabasePreset, configured: false, use_proxy: false, status: "authorization_required" }],+ installed_count: 1,+ last_action: { ok: true, message: "Saved MCP server metabase." },+ hot_reload: { ok: false, message: "Authorization required", failed: ["metabase"] },+ });+ await act(async () => result.current.actions.handleSaveCustomMcp());+ expect(result.current.state.mcpError).toBeNull();+ expect(result.current.state.mcpFieldValues).toEqual({+ metabase: { mcp_url: "https://analytics.example.com/mcp" }, docs: { use_proxy: "true" },+ });+ });++ it("retains failed proxy drafts, then retires applied or removed flags without discarding other edits", async () => {+ const { result } = renderMcpActions();+ const drafts = {+ metabase: { use_proxy: "true", mcp_url: "https://analytics.example.com/mcp" }, docs: { use_proxy: "true" },+ };+ await act(async () => result.current.state.setMcpFieldValues(drafts));+ const payload: McpPresetsPayload = { presets: [{ ...metabasePreset, use_proxy: true }], installed_count: 1 };+ requestMutationMock.mockRejectedValueOnce(new Error("Proxy could not be saved"));+ await act(async () => result.current.actions.handleMcpPresetAction("proxy", "metabase", { use_proxy: "true" }));+ expect(result.current.state.mcpFieldValues).toEqual(drafts);++ requestMutationMock.mockResolvedValueOnce(payload);+ await act(async () => result.current.actions.handleMcpPresetAction("proxy", "metabase", { use_proxy: "true" }));+ expect(result.current.state.mcpFieldValues).toEqual({+ metabase: { mcp_url: drafts.metabase.mcp_url }, docs: drafts.docs,+ });++ await act(async () => result.current.state.setMcpFieldValues(drafts));+ requestMutationMock.mockResolvedValueOnce({+ presets: [], installed_count: 0, last_action: { ok: true, removed: true, message: "Removed MCP server metabase." },+ });+ await act(async () => result.current.actions.handleMcpPresetAction("remove", "metabase"));+ expect(result.current.state.mcpFieldValues).toEqual({+ metabase: { mcp_url: drafts.metabase.mcp_url }, docs: drafts.docs,+ });+ });+});++function renderMcpActions() {+ const client = new NanobotClient({ url: "ws://example.test" });+ client.requestMutation = requestMutationMock;+ return renderHook(() => {+ const state = useSystemSettingsState();+ const actions = createSystemSettingsActions({+ state,+ featureCatalog: [],+ client,+ token: "tok",+ getToken: () => "tok",+ t: i18n.t,+ applyPayload: vi.fn(),+ maybeRestartHostEngine: vi.fn(),+ setPendingRestartSections: vi.fn(),+ refreshAutomations: vi.fn(),+ });+ return { state, actions };+ });+}diff --git a/webui/src/tests/proxy-url.test.ts b/webui/src/tests/proxy-url.test.tsnew file mode 100644index 000000000..e32ddc627--- /dev/null+++ b/webui/src/tests/proxy-url.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import { changeProxyAddress, changeProxyAuthentication, splitProxyUrl } from "@/lib/proxy-url";++describe("Proxy URL credentials", () => {+ it("separates encoded credentials without changing the address or decoded content", () => {+ const raw = "socks5://user%40org:p%3Aa%2F%25%2B%E5%AF%86@[::1]:1080/";+ const parts = splitProxyUrl(raw);+ expect(parts.address).toBe("socks5://[::1]:1080/");+ expect(parts.username).toBe("user@org");+ expect(parts.password).toBe("p:a/%+密");+ expect(changeProxyAuthentication(raw, parts.username, parts.password)).toBe(raw);+ });++ it("preserves unchanged credential escapes while changing host", () => {+ expect(changeProxyAddress("http://u%73er:p%61ss@old:8080", "https://new:8443"))+ .toBe("https://u%73er:p%61ss@new:8443");+ });++ it("encodes typed separators, whitespace, percent, plus and Unicode once", () => {+ const raw = changeProxyAuthentication("http://proxy:8080", "u:@ /%+名", "p:@ /%+密");+ expect(raw).toBe("http://u%3A%40%20%2F%25%2B%E5%90%8D:p%3A%40%20%2F%25%2B%E5%AF%86@proxy:8080");+ expect(splitProxyUrl(raw).password).toBe("p:@ /%+密");+ });++ it("updates only the edited credential and supports username-only authentication", () => {+ const raw = changeProxyAuthentication("http://user@proxy:8080", "user", "");+ expect(raw).toBe("http://user@proxy:8080");+ expect(changeProxyAuthentication(raw, "user", "password")).toBe("http://user:password@proxy:8080");+ expect(changeProxyAuthentication("http://u:p%61ss@proxy", "new", "pass")).toBe("http://new:p%61ss@proxy");+ });++ it("preserves raw environment references rather than encoding or resolving them", () => {+ expect(changeProxyAuthentication("${SCHEME}://${USER}:${PASSWORD}@proxy:8080", "${USER}", "new:@"))+ .toBe("${SCHEME}://${USER}:new%3A%40@proxy:8080");+ expect(changeProxyAddress("http://${PROXY_AUTH}@old:8080", "http://new:8080"))+ .toBe("http://${PROXY_AUTH}@new:8080");+ expect(splitProxyUrl("${FULL_PROXY}").address).toBe("${FULL_PROXY}");+ expect(changeProxyAddress("http://u:p@old", "${FULL_PROXY}")).toBe("${FULL_PROXY}");+ });++ it("uses pasted URL authentication and removes it only on explicit clearing", () => {+ expect(changeProxyAddress("http://old:pw@proxy", "http://new:secret@next"))+ .toBe("http://new:secret@next");+ expect(changeProxyAuthentication("http://u:p@proxy", "", "")).toBe("http://proxy");+ expect(changeProxyAddress("http://u:p@proxy", "")).toBe("");+ });++ it("does not throw or rewrite an existing malformed percent escape on an address edit", () => {+ expect(splitProxyUrl("http://u:p%invalid@old").password).toBe("p%invalid");+ expect(changeProxyAddress("http://u:p%invalid@old", "http://new")).toBe("http://u:p%invalid@new");+ });+});diff --git a/webui/src/tests/settings-apps-oauth.test.tsx b/webui/src/tests/settings-apps-oauth.test.tsxindex 7525739fc..2c9eb9caa 100644--- a/webui/src/tests/settings-apps-oauth.test.tsx+++ b/webui/src/tests/settings-apps-oauth.test.tsx@@ -18,6 +18,7 @@ const xmindMcpPreset = {docs_url: "https://xmind.com/user-guide/xmind-mcp",transport: "streamableHttp",auth: "oauth" as const,+ use_proxy: false,requires: "Xmind account",note: "Connects securely in your browser with Xmind OAuth.",install_supported: true,@@ -33,9 +34,46 @@ const xmindMcpPreset = {source: "preset",};+async function connectXmind() {+ fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ const dialog = await screen.findByRole("dialog", { name: "Xmind" });+ fireEvent.click(within(dialog).getByRole("button", { name: "Connect" }));+}+describe("SettingsView Apps catalog", () => {installSettingsViewTestHooks();+ it.each([null, "", " ", "http://127.0.0.1:8080"])("offers inline proxy setup for missing shared proxy %j", async (proxy) => {+ const settings = { ...settingsPayload(), runtime_config: { "network.proxy": proxy } };+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settings);+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [xmindMcpPreset], installed_count: 0 });+ return { ok: false, status: 404, text: async () => "Not found" } as Response;+ }));+ renderSettingsView({ initialSection: "apps" });+ fireEvent.click(await screen.findByRole("button", { name: "MCP" }));+ fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ const dialog = await screen.findByRole("dialog", { name: "Xmind" });+ const configure = within(dialog).queryByRole("button", { name: "Configure proxy" });+ if (proxy?.trim()) {+ expect(configure).not.toBeInTheDocument();+ expect(within(dialog).getByRole("switch", { name: "Use proxy" })).toBeInTheDocument();+ } else {+ expect(configure).toBeInTheDocument();+ expect(within(dialog).queryByRole("switch", { name: "Use proxy" })).not.toBeInTheDocument();+ fireEvent.click(configure!);+ const setup = await screen.findByRole("dialog", { name: "Shared proxy" });+ expect(dialog).toBeInTheDocument();+ const input = within(setup).getByRole("textbox", { name: "Shared proxy" });+ await waitFor(() => expect(input).toHaveFocus());+ fireEvent.click(within(setup).getByRole("button", { name: "Cancel" }));+ expect(await screen.findByRole("dialog", { name: "Xmind" })).toBe(dialog);+ }+ expect(requestMutationMock).not.toHaveBeenCalled();+ });+it("collects an instance MCP URL before starting browser authorization", async () => {const metabasePreset = {...xmindMcpPreset,@@ -85,14 +123,14 @@ describe("SettingsView Apps catalog", () => {await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.mcp.oauth_start",- { name: "metabase", mcp_url: "https://analytics.example.com/api/metabase-mcp" },+ { name: "metabase", mcp_url: "https://analytics.example.com/api/metabase-mcp", use_proxy: "false" },expect.any(Number),));});- it("connects an OAuth MCP from the Apps catalog without manual callback input", async () => {+ it("sets the proxy flag before the first OAuth request, even with no credential fields", async () => {let connected = false;const fetchMock = vi.fn(async (input: RequestInfo | URL) => {const url = String(input);@@ -110,6 +148,7 @@ describe("SettingsView Apps catalog", () => {available: true,status: "configured",connection_summary: "https://app.xmind.com/api/mcp",+ use_proxy: true,}: xmindMcpPreset],installed_count: connected ? 1 : 0,@@ -164,6 +203,17 @@ describe("SettingsView Apps catalog", () => {const connectButton = await screen.findByRole("button", { name: "Connect Xmind" });expect(connectButton).toHaveTextContent("Connect");fireEvent.click(connectButton);+ const dialog = await screen.findByRole("dialog", { name: "Xmind" });+ expect(open).not.toHaveBeenCalled();+ expect(requestMutationMock).not.toHaveBeenCalled();+ const useProxy = within(dialog).getByRole("switch", { name: "Use proxy" });+ expect(useProxy).not.toBeChecked();+ expect(within(dialog).queryByRole("textbox", { name: /proxy/i })).not.toBeInTheDocument();+ fireEvent.click(useProxy);+ fireEvent.click(within(dialog).getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.mcp.oauth_start", { name: "xmind", use_proxy: "true" }, 30_000,+ ));expect(open).toHaveBeenCalledWith("about:blank",@@ -185,6 +235,9 @@ describe("SettingsView Apps catalog", () => {expect(await screen.findByRole("button", { name: "Manage Xmind" }, { timeout: 2500 })).toHaveTextContent("Manage");expect(popup.close).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "Manage Xmind" }));+ fireEvent.click(screen.getByRole("tab", { name: "Connection" }));+ expect(screen.getByRole("switch", { name: "Use proxy" })).toBeChecked();expect(replace).toHaveBeenCalledTimes(1);expect(fetchMock).toHaveBeenCalledWith("/api/settings/mcp-oauth/status?flow_id=flow-123",@@ -250,7 +303,7 @@ describe("SettingsView Apps catalog", () => {await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.mcp.oauth_start",- { name: "xmind", reset: true },+ { name: "xmind", reset: true, use_proxy: "false" },30_000,));await act(() => i18n.changeLanguage("en"));@@ -405,6 +458,7 @@ describe("SettingsView Apps catalog", () => {display_name: "team-mcp",source: "custom",installed: true,+ use_proxy: true,status: "authorization_required",connection_summary: "https://mcp.example.com/mcp",};@@ -464,6 +518,7 @@ describe("SettingsView Apps catalog", () => {screen.getByText("Save the server, then select Connect to sign in."),).toBeInTheDocument();+ fireEvent.click(screen.getByRole("switch", { name: "Use proxy" }));fireEvent.click(screen.getByRole("button", { name: "Save MCP server" }));await waitFor(() => {@@ -477,12 +532,15 @@ describe("SettingsView Apps catalog", () => {transport: "streamableHttp",url: "https://mcp.example.com/mcp",auth: "oauth",+ use_proxy: "true",});expect(values).not.toHaveProperty("headers");expect(saveCall?.[2]).toBe(20_000);});- expect(await screen.findByRole("button", { name: "Connect team-mcp" }))- .toBeInTheDocument();+ fireEvent.click(await screen.findByRole("button", { name: "Connect team-mcp" }));+ const connection = await screen.findByRole("dialog", { name: "team-mcp" });+ expect(within(connection).getByRole("switch", { name: "Use proxy" })).toBeChecked();+ expect(requestMutationMock).not.toHaveBeenCalledWith("settings.mcp.oauth_start", expect.anything(), expect.anything());});it("offers a pasted callback flow when the remote WebUI uses HTTP", async () => {@@ -561,7 +619,7 @@ describe("SettingsView Apps catalog", () => {renderSettingsView({ initialSection: "apps" });fireEvent.click(await screen.findByRole("button", { name: "MCP" }));- fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ await connectXmind();const callbackInput = await screen.findByRole("textbox", { name: "Callback URL" });expect(screen.getByText(/localhost page will not load/i)).toBeInTheDocument();@@ -628,7 +686,7 @@ describe("SettingsView Apps catalog", () => {renderSettingsView({ initialSection: "apps" });fireEvent.click(await screen.findByRole("button", { name: "MCP" }));- fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ await connectXmind();const cancelButton = await screen.findByRole("button", { name: "Cancel" });expect(screen.getByRole("button", { name: "Connecting Xmind" })).toBeInTheDocument();@@ -734,7 +792,7 @@ describe("SettingsView Apps catalog", () => {renderSettingsView({ initialSection: "apps" });fireEvent.click(await screen.findByRole("button", { name: "MCP" }));- fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ await connectXmind();const continueButton = await screen.findByRole("button", { name: "Continue sign-in" });expect(screen.getByRole("status")).toHaveTextContent("Open the sign-in page to continue.");@@ -804,7 +862,7 @@ describe("SettingsView Apps catalog", () => {renderSettingsView({ initialSection: "apps" });fireEvent.click(await screen.findByRole("button", { name: "MCP" }));- fireEvent.click(await screen.findByRole("button", { name: "Connect Xmind" }));+ await connectXmind();await waitFor(() => expect(statusCalls).toBe(1), { timeout: 2000 });expect(screen.getByRole("status")).toHaveTextContent(diff --git a/webui/src/tests/settings-capabilities.test.tsx b/webui/src/tests/settings-capabilities.test.tsxindex c9ad363c9..ceb71cac7 100644--- a/webui/src/tests/settings-capabilities.test.tsx+++ b/webui/src/tests/settings-capabilities.test.tsx@@ -317,9 +317,10 @@ describe("Settings capabilities", () => {);});- it("edits the existing web proxy in web access even while disabled, without a duplicate advanced editor", async () => {+ it("saves the web proxy switch separately from the shared address in Advanced", async () => {let payload = { ...settingsPayload(), runtime_config: {- "tools.web.enable": false, "tools.web.proxy": "http://old-proxy.example:8080", "tools.web.user_agent": null,+ "tools.web.enable": false, "tools.web.use_proxy": false,+ "network.proxy": "http://old-proxy.example:8080", "tools.web.user_agent": null,} } as SettingsPayload;requestMutationMock.mockImplementation(async (_method, update) => {payload = { ...payload, runtime_config: { ...payload.runtime_config, ...update.values },@@ -329,21 +330,41 @@ describe("Settings capabilities", () => {renderSettingsView({ initialSection: "capabilities", initialSettings: payload });fireEvent.click(within(screen.getByRole("region", { name: "Web access" })).getByRole("button", { name: "Configure" }));fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));- const proxy = screen.getByRole("textbox", { name: "Web proxy" });- expect(proxy).toHaveValue("http://old-proxy.example:8080");- fireEvent.change(proxy, { target: { value: "http://new-proxy.example:7890" } });+ const useProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(useProxy).not.toBeChecked();+ expect(screen.queryByRole("textbox", { name: /proxy/i })).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Shared proxy")).not.toBeInTheDocument();+ fireEvent.click(useProxy);await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(- "settings.runtime_config.update", { values: { "tools.web.proxy": "http://new-proxy.example:7890" } }, 20_000,+ "settings.runtime_config.update", { values: { "tools.web.use_proxy": true } }, 20_000,));- expect(await screen.findByText("Saved. Restart to apply changes.")).toBeVisible();- fireEvent.change(proxy, { target: { value: "" } });+ await waitFor(() => expect(useProxy).toBeEnabled());+ expect(useProxy).toBeChecked();+ fireEvent.click(useProxy);await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(- "settings.runtime_config.update", { values: { "tools.web.proxy": null } }, 20_000,+ "settings.runtime_config.update", { values: { "tools.web.use_proxy": false } }, 20_000,));fireEvent.click(within(screen.getByRole("dialog", { name: "Web access" })).getByRole("button", { name: "Close" }));expect(screen.getByRole("switch", { name: "Web access" })).not.toBeChecked();fireEvent.click(screen.getByRole("button", { name: "Advanced" }));- expect(screen.queryByRole("textbox", { name: "Web proxy" })).not.toBeInTheDocument();+ const proxy = screen.getByRole("textbox", { name: "Shared proxy" });+ expect(proxy).toHaveAttribute("type", "text");+ expect(proxy).toHaveValue("http://old-proxy.example:8080");+ expect(screen.queryByRole("switch", { name: "Use proxy" })).not.toBeInTheDocument();+ const address = "http://user:[email protected]:7890";+ fireEvent.change(proxy, { target: { value: address } });+ expect(proxy).toHaveValue("http://new-proxy.example:7890");+ expect(screen.getByLabelText("Password")).toHaveAttribute("type", "password");+ fireEvent.click(within(screen.getByRole("region", { name: "Shared proxy" })).getByRole("button", { name: "Save" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(+ "settings.runtime_config.update", { values: { "network.proxy": address } }, 20_000,+ ));+ fireEvent.click(screen.getByRole("button", { name: "System" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ expect(screen.getByLabelText("Shared proxy", { selector: "input" })).toHaveValue("http://new-proxy.example:7890");+ expect(screen.getByLabelText("Username")).toHaveValue("user");+ expect(screen.getByLabelText("Password")).toHaveValue("secret");+ expect(document.body).not.toHaveTextContent(address);});it("saves optional-key web search providers without an API key", async () => {diff --git a/webui/src/tests/settings-providers.test.tsx b/webui/src/tests/settings-providers.test.tsxindex 1ff60ca1e..b5363d8d2 100644--- a/webui/src/tests/settings-providers.test.tsx+++ b/webui/src/tests/settings-providers.test.tsx@@ -1,7 +1,7 @@import { fireEvent, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { expect, it, vi } from "vitest";-import type { SettingsPayload } from "@/lib/types";+import type { ProviderCreationUpdate, SettingsPayload } from "@/lib/types";import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";@@ -711,7 +711,7 @@ describe("Settings providers", () => {}});- it("saves scoped proxies for xAI and OpenAI Codex OAuth providers", async () => {+ it("saves proxy switches for xAI and OpenAI Codex OAuth providers before sign-in", async () => {const base = settingsPayload();const providers: SettingsPayload["providers"] = [{@@ -727,8 +727,8 @@ describe("Settings providers", () => {oauth_account: null,oauth_expires_at: null,oauth_login_supported: true,- proxy: "http://127.0.0.1:7000",- advanced_fields: ["extra_body", "proxy"],+ use_proxy: true,+ advanced_fields: ["extra_body", "use_proxy"],extra_body: null,},{@@ -744,8 +744,8 @@ describe("Settings providers", () => {oauth_account: null,oauth_expires_at: null,oauth_login_supported: true,- proxy: null,- advanced_fields: ["extra_body", "proxy"],+ use_proxy: false,+ advanced_fields: ["extra_body", "use_proxy"],extra_body: null,},];@@ -764,7 +764,7 @@ describe("Settings providers", () => {vi.stubGlobal("fetch", fetchMock);requestMutationMock.mockImplementation(async (_action: string,- values: { provider?: string; proxy?: string; extraBody?: string },+ values: { provider?: string; use_proxy?: boolean; extraBody?: string },) => {payload = {...payload,@@ -772,7 +772,7 @@ describe("Settings providers", () => {provider.name === values.provider? {...provider,- proxy: values.proxy || null,+ use_proxy: values.use_proxy,extra_body: values.extraBody ? JSON.parse(values.extraBody) : null,}: provider,@@ -785,9 +785,10 @@ describe("Settings providers", () => {await chooseProviderToConfigure("xAI Grok");fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));- const xaiProxy = screen.getByLabelText("Network proxy");- expect(xaiProxy).toHaveValue("http://127.0.0.1:7000");- fireEvent.change(xaiProxy, { target: { value: "http://127.0.0.1:7890" } });+ const xaiProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(xaiProxy).toBeChecked();+ expect(screen.queryByPlaceholderText("http://127.0.0.1:7890")).not.toBeInTheDocument();+ fireEvent.click(xaiProxy);expect(screen.getByRole("button", { name: "Sign in" })).toBeDisabled();expect(screen.getByRole("button", { name: "Sign in" })).toHaveAttribute("title",@@ -801,7 +802,7 @@ describe("Settings providers", () => {{provider: "xai_grok",extraBody: "",- proxy: "http://127.0.0.1:7890",+ use_proxy: false,},20_000,),@@ -812,9 +813,9 @@ describe("Settings providers", () => {fireEvent.click(screen.getByRole("button", { name: "Back to providers" }));await chooseProviderToConfigure("OpenAI Codex");fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));- const codexProxy = screen.getByLabelText("Network proxy");- expect(codexProxy).toHaveValue("");- fireEvent.change(codexProxy, { target: { value: "http://proxy.example:8080" } });+ const codexProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(codexProxy).not.toBeChecked();+ fireEvent.click(codexProxy);fireEvent.click(screen.getByRole("button", { name: "Save provider" }));await waitFor(() =>@@ -823,13 +824,41 @@ describe("Settings providers", () => {{provider: "openai_codex",extraBody: "",- proxy: "http://proxy.example:8080",+ use_proxy: true,},20_000,),);});+ it("persists a disabled proxy switch on an API-key provider without changing credentials", async () => {+ const base = settingsPayload();+ let payload: SettingsPayload = { ...base, providers: [{+ name: "openrouter", label: "OpenRouter", configured: true,+ api_key_hint: "sk-••••test", api_base: "https://openrouter.ai/api/v1",+ use_proxy: true, advanced_fields: ["use_proxy"],+ }] };+ requestMutationMock.mockImplementation(async (_action, values) => {+ payload = { ...payload, providers: payload.providers.map((provider) => ({ ...provider, use_proxy: values.use_proxy })) };+ return payload;+ });+ renderProviderManager({ initialSection: "models", initialSettings: payload });+ fireEvent.click(screen.getByRole("button", { name: "OpenRouter" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));+ const useProxy = screen.getByRole("switch", { name: "Use proxy" });+ expect(useProxy).toBeChecked();+ fireEvent.click(useProxy);+ fireEvent.click(screen.getByRole("button", { name: "Save provider" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.provider.update",+ { provider: "openrouter", apiBase: "https://openrouter.ai/api/v1", apiKey: undefined, use_proxy: false },+ 20_000,+ ));+ fireEvent.click(await screen.findByRole("button", { name: "OpenRouter" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));+ expect(screen.getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ });+it("maps provider request switches to raw extraBody fields", async () => {const base = settingsPayload();const providers: SettingsPayload["providers"] = [@@ -841,7 +870,7 @@ describe("Settings providers", () => {api_key_required: false,oauth_account: "[email protected]",oauth_login_supported: true,- advanced_fields: ["extra_body", "proxy"],+ advanced_fields: ["extra_body", "use_proxy"],extra_body: null,},{@@ -852,7 +881,7 @@ describe("Settings providers", () => {api_key_required: false,oauth_account: "[email protected]",oauth_login_supported: true,- advanced_fields: ["extra_body", "proxy"],+ advanced_fields: ["extra_body", "use_proxy"],extra_body: null,},{@@ -1056,7 +1085,7 @@ describe("Settings providers", () => {vi.stubGlobal("fetch", fetchMock);requestMutationMock.mockImplementationOnce(async (_action: string,- values: Record<string, string>,+ values: ProviderCreationUpdate,) => {payload = {...payload,@@ -1076,13 +1105,13 @@ describe("Settings providers", () => {"extra_headers","extra_body","extra_query",- "proxy",+ "use_proxy","thinking_style",],- extra_headers: JSON.parse(values.extraHeaders),- extra_body: JSON.parse(values.extraBody),- extra_query: JSON.parse(values.extraQuery),- proxy: values.proxy,+ extra_headers: JSON.parse(values.extraHeaders ?? "{}"),+ extra_body: JSON.parse(values.extraBody ?? "{}"),+ extra_query: JSON.parse(values.extraQuery ?? "{}"),+ use_proxy: values.use_proxy,thinking_style: values.thinkingStyle,},],@@ -1123,9 +1152,7 @@ describe("Settings providers", () => {fireEvent.click(within(editor).getByRole("button", { name: "Save" }));await waitFor(() => expect(screen.queryByRole("dialog", { name: title })).not.toBeInTheDocument());}- fireEvent.change(screen.getByLabelText("Network proxy"), {- target: { value: "http://127.0.0.1:7890" },- });+ fireEvent.click(screen.getByRole("switch", { name: "Use proxy" }));fireEvent.pointerDown(screen.getByRole("button", { name: "Reasoning format" }));fireEvent.click(await screen.findByRole("menuitem", { name: "enable_thinking" }));fireEvent.click(screen.getByRole("button", { name: "Add provider" }));@@ -1139,7 +1166,7 @@ describe("Settings providers", () => {name: "Company Gateway",apiKey: "sk-company",apiBase: "https://gateway.example/v1",- proxy: "http://127.0.0.1:7890",+ use_proxy: true,extraHeaders: '{"X-Tenant":"engineering"}',extraBody: '{"service_tier":"priority"}',extraQuery: '{"api-version":"2026-01-01"}',diff --git a/webui/src/tests/settings-runtime-config.test.tsx b/webui/src/tests/settings-runtime-config.test.tsxindex 333b9828b..acb771192 100644--- a/webui/src/tests/settings-runtime-config.test.tsx+++ b/webui/src/tests/settings-runtime-config.test.tsx@@ -26,7 +26,8 @@ function runtimeSettings() {"tools.exec.sandbox_ro_binds": [],"tools.exec.sandbox_rw_binds": [],"agents.defaults.max_tool_iterations": 200,- "tools.web.proxy": "http://localhost:8080",+ "network.proxy": "http://localhost:8080",+ "tools.web.use_proxy": false,};return { ...payload, advanced: { ...payload.advanced, exec_max_runtime_limit: 86400 }, runtime_config: runtimeConfig };}@@ -301,22 +302,47 @@ describe("Runtime configuration settings", () => {});it("preserves drafts when navigating away and supports explicit clearing", async () => {- renderSettingsView({ initialSection: "capabilities", initialSettings: runtimeSettings() });- const openWebSettings = () => {- fireEvent.click(within(screen.getByRole("region", { name: "Web access" })).getByRole("button", { name: "Configure" }));- fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));- };- openWebSettings();- const proxy = screen.getByRole("textbox", { name: "Web proxy" });+ let payload = runtimeSettings();+ requestMutationMock.mockImplementation(async (_method, update) => {+ payload = { ...payload, runtime_config: { ...payload.runtime_config, ...update.values } };+ return payload;+ });+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });+ const proxy = screen.getByRole("textbox", { name: "Shared proxy" });+ expect(proxy).toHaveAttribute("type", "text");+ expect(proxy).toHaveValue("http://localhost:8080");fireEvent.change(proxy, { target: { value: "" } });- fireEvent.click(within(screen.getByRole("dialog", { name: "Web access" })).getByRole("button", { name: "Close" }));fireEvent.click(screen.getByRole("button", { name: "System" }));- fireEvent.click(screen.getByRole("button", { name: "Capabilities" }));- openWebSettings();- expect(screen.getByRole("textbox", { name: "Web proxy" })).toHaveValue("");+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ expect(screen.getByLabelText("Shared proxy", { selector: "input" })).toHaveValue("");+ fireEvent.click(within(screen.getByRole("region", { name: "Shared proxy" })).getByRole("button", { name: "Save" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.runtime_config.update", { values: { "network.proxy": null } }, 20_000,+ ));+ fireEvent.click(screen.getByRole("button", { name: "System" }));+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ expect(screen.getByLabelText("Shared proxy", { selector: "input" })).toHaveValue("");+ });++ it("saves proxy address and authentication together without exposing the password in the address", async () => {+ const payload = runtimeSettings();+ payload.runtime_config!["network.proxy"] = "http://old:p%40ss@proxy:8080";+ requestMutationMock.mockImplementation(async (_method, update) => ({+ ...payload, runtime_config: { ...payload.runtime_config, ...update.values }, requires_restart: true,+ }));+ renderSettingsView({ initialSection: "advanced", initialSettings: payload });+ const group = within(screen.getByRole("region", { name: "Shared proxy" }));+ expect(group.getByRole("textbox", { name: "Shared proxy" })).toHaveValue("http://proxy:8080");+ expect(group.getByLabelText("Password")).toHaveAttribute("type", "password");+ expect(group.getByLabelText("Password")).toHaveValue("p@ss");+ fireEvent.change(group.getByLabelText("Username"), { target: { value: "new@user" } });+ fireEvent.change(group.getByLabelText("Password"), { target: { value: "p:@ %密" } });+ expect(requestMutationMock).not.toHaveBeenCalled();+ fireEvent.click(group.getByRole("button", { name: "Save" }));await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(- "settings.runtime_config.update", { values: { "tools.web.proxy": null } }, 20_000,+ "settings.runtime_config.update", { values: { "network.proxy": "http://new%40user:p%3A%40%20%25%E5%AF%86@proxy:8080" } }, 20_000,));+ expect(group.getByRole("textbox", { name: "Shared proxy" })).toHaveValue("http://proxy:8080");});it("keeps an existing timezone alias selectable and accepts only listed search results", () => {diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsxindex aafe0d046..9400c042d 100644--- a/webui/src/tests/settings-test-utils.tsx+++ b/webui/src/tests/settings-test-utils.tsx@@ -59,7 +59,7 @@ export function settingsPayload(): SettingsPayload {},web: {enable: true,- proxy: null,+ use_proxy: false,user_agent: null,search: { max_results: 5, timeout: 30 },fetch: { use_jina_reader: true },diff --git a/webui/src/tests/shared-proxy-editor.test.tsx b/webui/src/tests/shared-proxy-editor.test.tsxnew file mode 100644index 000000000..7cd84d785--- /dev/null+++ b/webui/src/tests/shared-proxy-editor.test.tsx@@ -0,0 +1,53 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import { beforeEach, describe, expect, it } from "vitest";++import { SharedProxyEditor } from "@/components/settings/shared/SharedProxyEditor";+import i18n from "@/i18n";++function editor(initial: string) {+ let current = initial;+ function Harness() {+ const [value, setValue] = useState(initial);+ return <SharedProxyEditor value={value} onChange={(next) => { current = next; setValue(next); }} />;+ }+ render(<Harness />);+ return () => current;+}++describe("Shared proxy editor", () => {+ beforeEach(async () => { await i18n.changeLanguage("en"); });++ it("shows an existing URL password only in a masked password field", () => {+ const value = editor("http://user:p%40ss@proxy:8080");+ expect(screen.getByRole("textbox", { name: "Shared proxy" })).toHaveValue("http://proxy:8080");+ expect(screen.getByRole("textbox", { name: "Username" })).toHaveValue("user");+ expect(screen.getByLabelText("Password")).toHaveAttribute("type", "password");+ expect(screen.getByLabelText("Password")).toHaveValue("p@ss");+ fireEvent.change(screen.getByRole("textbox", { name: "Shared proxy" }), { target: { value: "http://new:8080" } });+ expect(value()).toBe("http://user:p%40ss@new:8080");+ fireEvent.click(screen.getByRole("button", { name: "Authentication (optional)" }));+ expect(value()).toBe("http://user:p%40ss@new:8080");+ expect(screen.queryByLabelText("Password")).not.toBeInTheDocument();+ });++ it("keeps pasted authentication out of the plain address and encodes credential edits", () => {+ const value = editor("");+ const address = screen.getByRole("textbox", { name: "Shared proxy" });+ fireEvent.change(address, { target: { value: "http://user:secret@proxy:8080" } });+ expect(address).toHaveValue("http://proxy:8080");+ expect(screen.getByLabelText("Password")).toHaveAttribute("type", "password");+ fireEvent.change(screen.getByLabelText("Username"), { target: { value: "new@user" } });+ fireEvent.change(screen.getByLabelText("Password"), { target: { value: "p:@ %密" } });+ expect(value()).toBe("http://new%40user:p%3A%40%20%25%E5%AF%86@proxy:8080");+ expect(address).toHaveValue("http://proxy:8080");+ });++ it("preserves whole-URL environment references and explains where authentication is set", () => {+ const value = editor("${FULL_PROXY}");+ fireEvent.click(screen.getByRole("button", { name: "Authentication (optional)" }));+ expect(screen.getByText("Set authentication in the referenced proxy URL.")).toBeVisible();+ expect(screen.queryByLabelText("Password")).not.toBeInTheDocument();+ expect(value()).toBe("${FULL_PROXY}");+ });+});diff --git a/webui/src/tests/shared-proxy-setup.test.tsx b/webui/src/tests/shared-proxy-setup.test.tsxnew file mode 100644index 000000000..c8a822f16--- /dev/null+++ b/webui/src/tests/shared-proxy-setup.test.tsx@@ -0,0 +1,142 @@+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import type { McpPresetInfo } from "@/lib/types";+import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";++const preset: McpPresetInfo = {+ name: "docs", display_name: "Docs MCP", category: "productivity", description: "Docs",+ docs_url: "https://example.com", transport: "streamableHttp", auth: null, requires: "", note: "",+ install_supported: true, installed: true, configured: true, available: true, status: "configured",+ runtime_status: "connected", required_fields: [], connection_summary: "https://example.com/mcp",+ tool_count: 2, tool_names: ["search_docs", "write_note"], enabled_tools: ["*"], source: "custom",+};++function installProxySettings() {+ const settings = { ...settingsPayload(), runtime_config: { "network.proxy": null } };+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url === "/api/settings") return jsonResponse(settings);+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [preset], installed_count: 1 });+ return jsonResponse({});+ }));+ return { settings, saved: { ...settings, runtime_config: { "network.proxy": "http://127.0.0.1:7890" }, requires_restart: true } };+}++async function openMcpSetup() {+ fireEvent.click(await screen.findByRole("button", { name: "MCP" }));+ fireEvent.click(await screen.findByRole("button", { name: "Manage Docs MCP" }));+ const parent = await screen.findByRole("dialog", { name: "Docs MCP" });+ fireEvent.click(within(parent).getByRole("tab", { name: "Connection" }));+ fireEvent.click(within(parent).getByRole("button", { name: "Configure proxy" }));+ return { parent, setup: await screen.findByRole("dialog", { name: "Shared proxy" }) };+}++describe("Inline shared proxy setup", () => {+ installSettingsViewTestHooks();++ it("keeps custom Provider fields across cancel and successful setup without enabling proxy", async () => {+ const user = userEvent.setup();+ const { settings, saved } = installProxySettings();+ renderSettingsView({ initialSection: "models", initialSettings: settings });+ await user.click(await screen.findByRole("button", { name: "Manage providers" }));+ await user.click(screen.getByRole("button", { name: "Add provider" }));+ await user.click(await screen.findByRole("button", { name: "Custom" }));+ const parent = screen.getByRole("dialog", { name: "Custom" });+ const name = within(parent).getByPlaceholderText("My model provider");+ const url = within(parent).getByPlaceholderText("https://api.example.com/v1");+ const key = within(parent).getByPlaceholderText("Enter API key");+ await user.type(name, "Keep this draft");+ await user.type(url, "https://gateway.example/v1");+ await user.type(key, "draft-key");+ await user.click(within(parent).getByRole("button", { name: "Advanced options" }));+ await user.click(within(parent).getByRole("button", { name: "Configure proxy" }));+ let setup = await screen.findByRole("dialog", { name: "Shared proxy" });+ await user.type(within(setup).getByRole("textbox"), "http://127.0.0.1:7890");+ await user.click(within(setup).getByRole("button", { name: "Cancel" }));+ expect(name).toHaveValue("Keep this draft");+ expect(url).toHaveValue("https://gateway.example/v1");+ expect(key).toHaveValue("draft-key");+ expect(requestMutationMock).not.toHaveBeenCalled();+ await user.click(within(parent).getByRole("button", { name: "Configure proxy" }));+ setup = await screen.findByRole("dialog", { name: "Shared proxy" });+ expect(within(setup).getByRole("textbox")).toHaveValue("");+ await user.type(within(setup).getByRole("textbox"), "http://127.0.0.1:7890");+ requestMutationMock.mockResolvedValueOnce(saved);+ await user.click(within(setup).getByRole("button", { name: "Save" }));+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Shared proxy" })).not.toBeInTheDocument());+ expect(await screen.findByRole("dialog", { name: "Custom" })).toBe(parent);+ expect(name).toHaveValue("Keep this draft");+ expect(url).toHaveValue("https://gateway.example/v1");+ expect(key).toHaveValue("draft-key");+ expect(within(parent).getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "network.proxy": "http://127.0.0.1:7890" } }, 20_000);+ });++ it("saves optional credentials from inline setup without enabling the consumer", async () => {+ const { settings, saved } = installProxySettings();+ renderSettingsView({ initialSection: "apps", initialSettings: settings });+ const { parent, setup } = await openMcpSetup();+ fireEvent.change(within(setup).getByRole("textbox", { name: "Shared proxy" }), { target: { value: "socks5://proxy:1080" } });+ fireEvent.click(within(setup).getByRole("button", { name: "Authentication (optional)" }));+ fireEvent.change(within(setup).getByLabelText("Username"), { target: { value: "user@org" } });+ fireEvent.change(within(setup).getByLabelText("Password"), { target: { value: "p:a@ss" } });+ expect(within(setup).getByLabelText("Password")).toHaveAttribute("type", "password");+ const encoded = "socks5://user%40org:p%3Aa%40ss@proxy:1080";+ requestMutationMock.mockResolvedValueOnce({ ...saved, runtime_config: { "network.proxy": encoded } });+ fireEvent.click(within(setup).getByRole("button", { name: "Save" }));+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Shared proxy" })).not.toBeInTheDocument());+ expect(requestMutationMock).toHaveBeenCalledWith("settings.runtime_config.update", { values: { "network.proxy": encoded } }, 20_000);+ expect(within(parent).getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ });++ it("retains MCP tool selections when setup is cancelled", async () => {+ const { settings } = installProxySettings();+ renderSettingsView({ initialSection: "apps", initialSettings: settings });+ fireEvent.click(await screen.findByRole("button", { name: "MCP" }));+ fireEvent.click(await screen.findByRole("button", { name: "Manage Docs MCP" }));+ const parent = await screen.findByRole("dialog", { name: "Docs MCP" });+ fireEvent.click(within(parent).getByRole("tab", { name: "Tools" }));+ fireEvent.click(within(parent).getByRole("checkbox", { name: "write_note" }));+ expect(within(parent).getByRole("checkbox", { name: "write_note" })).not.toBeChecked();+ fireEvent.click(within(parent).getByRole("tab", { name: "Connection" }));+ fireEvent.click(within(parent).getByRole("button", { name: "Configure proxy" }));+ const setup = await screen.findByRole("dialog", { name: "Shared proxy" });+ fireEvent.click(within(setup).getByRole("button", { name: "Cancel" }));+ fireEvent.click(within(parent).getByRole("tab", { name: "Tools" }));+ expect(within(parent).getByRole("checkbox", { name: "write_note" })).not.toBeChecked();+ expect(within(parent).getByRole("button", { name: "Save changes" })).toBeEnabled();+ expect(requestMutationMock).not.toHaveBeenCalled();+ });++ it("keeps failed input and inline errors, blocks dismissal while saving and retries", async () => {+ const { settings, saved } = installProxySettings();+ renderSettingsView({ initialSection: "apps", initialSettings: settings });+ const { parent, setup } = await openMcpSetup();+ const input = within(setup).getByRole("textbox");+ const save = within(setup).getByRole("button", { name: "Save" });+ expect(save).toBeDisabled();+ fireEvent.change(input, { target: { value: "bad-address" } });+ requestMutationMock.mockRejectedValueOnce(new Error("Unsupported proxy scheme"));+ fireEvent.click(save);+ expect(await within(setup).findByRole("alert")).toHaveTextContent("Unsupported proxy scheme");+ expect(input).toHaveValue("bad-address");+ await waitFor(() => expect(input).toHaveFocus());+ fireEvent.change(input, { target: { value: "http://127.0.0.1:7890" } });+ let resolveSave!: (value: typeof saved) => void;+ requestMutationMock.mockImplementationOnce(() => new Promise((resolve) => { resolveSave = resolve; }));+ fireEvent.click(save);+ expect(within(setup).getByRole("button", { name: "Cancel" })).toBeDisabled();+ expect(input).toBeDisabled();+ fireEvent.keyDown(setup, { key: "Escape" });+ expect(setup).toBeInTheDocument();+ await act(async () => { resolveSave(saved); });+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Shared proxy" })).not.toBeInTheDocument());+ expect(screen.getByRole("dialog", { name: "Docs MCP" })).toBe(parent);+ expect(within(parent).getByRole("switch", { name: "Use proxy" })).not.toBeChecked();+ expect(requestMutationMock).toHaveBeenLastCalledWith("settings.runtime_config.update", { values: { "network.proxy": "http://127.0.0.1:7890" } }, 20_000);+ });+});diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsxindex bf071f69a..afa382bd0 100644--- a/webui/src/tests/thread-shell.test.tsx+++ b/webui/src/tests/thread-shell.test.tsx@@ -522,7 +522,7 @@ function modelSettings(model: string, provider: string): SettingsPayload {},web: {enable: true,- proxy: null,+ use_proxy: false,user_agent: null,search: { max_results: 5, timeout: 30 },fetch: { use_jina_reader: true },