Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: align Windows exec runtime and search readiness

zhou2030109-glitchb342b63b7a7a
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 2096e7713..25c652085 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -1660,10 +1660,14 @@ class AgenticChatPipeline:
if self.language == "zh":
how_to_write = (
(
- "通过 exec 使用 PowerShell here-string 将脚本写入文件再运行,例如:\n"
+ "当前 shell 是 Windows PowerShell。列目录使用 Get-ChildItem,限制输出使用 "
+ "Select-Object -First;连续命令使用分号。`python` 与 `python -m pip` 均指向 "
+ "DeepTutor 自己的运行环境。通过 exec 使用 PowerShell here-string 将脚本写入文件再运行,例如:\n"
" @'\n...Python 脚本内容...\n'@ | Set-Content -Encoding utf8 gen.py\n"
" python gen.py\n"
- "不要使用 bash heredoc(<<'PY')或 POSIX 重定向语法——当前为 Windows 环境。"
+ "本地路径经 Test-Path 或 Get-Item 验证存在后,直接读取,不要要求用户重复上传。"
+ "命令失败时先根据 STDERR 与退出码修正命令或依赖;只有工具明确返回拒绝访问时,"
+ "才能判断为权限问题。不要把命令语法或依赖错误说成沙箱无权访问。"
)
if is_windows
else (
@@ -1681,12 +1685,17 @@ class AgenticChatPipeline:
)
how_to_write = (
(
- "write the script to a file through exec with a PowerShell "
+ "the current shell is Windows PowerShell. Use Get-ChildItem to list files, "
+ "Select-Object -First to limit output, and semicolons between commands. "
+ "Both `python` and `python -m pip` resolve to DeepTutor's runtime. "
+ "Write the script to a file through exec with a PowerShell "
"here-string, then run it, for example:\n"
" @'\n...Python script contents...\n'@ | Set-Content -Encoding utf8 gen.py\n"
" python gen.py\n"
- "Do not use Bash heredoc (<<'PY') or POSIX redirection syntax; "
- "this is a Windows environment. "
+ "After Test-Path or Get-Item confirms a local path, read it directly instead "
+ "of asking the user to upload it again. Correct the command or dependency from "
+ "STDERR and the exit code first. Do not describe a syntax or dependency failure "
+ "as denied sandbox access unless the tool explicitly reports access denied. "
)
if is_windows
else (
diff --git a/deeptutor/api/routers/tools.py b/deeptutor/api/routers/tools.py
index 87041bd46..979e62366 100644
--- a/deeptutor/api/routers/tools.py
+++ b/deeptutor/api/routers/tools.py
@@ -19,6 +19,7 @@ from pydantic import BaseModel
from deeptutor.api.routers.settings import get_enabled_optional_tools
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolPromptHints
from deeptutor.i18n.metadata_i18n import tool_description_i18n
+from deeptutor.services.config import resolve_search_runtime_config
from deeptutor.tools.builtin import (
BUILTIN_TOOL_TYPES,
COMING_SOON_TOOL_TYPES,
@@ -84,6 +85,11 @@ class BuiltinToolPayload(BaseModel):
# capability on top of the shared built-in surface; the settings UI groups
# them under their owner, below the built-in section.
capability: str | None = None
+ # Runtime readiness is separate from the saved on/off preference. A tool
+ # may be enabled in the composer while its backing service still needs
+ # configuration (notably web_search with provider="none").
+ available: bool = True
+ unavailable_reason: str | None = None
class ToolsListResponse(BaseModel):
@@ -149,6 +155,7 @@ def _build_tool_payload(
enabled = name in enabled_optional
else:
enabled = True
+ available, unavailable_reason = _runtime_availability(name, coming_soon=coming_soon)
return BuiltinToolPayload(
name=name,
description=descriptions.get("en") or description,
@@ -163,9 +170,30 @@ def _build_tool_payload(
enabled=enabled,
coming_soon=coming_soon,
capability=capability,
+ available=available,
+ unavailable_reason=unavailable_reason,
)
+def _runtime_availability(name: str, *, coming_soon: bool = False) -> tuple[bool, str | None]:
+ if coming_soon:
+ return False, "coming_soon"
+ if name != "web_search":
+ return True, None
+ try:
+ config = resolve_search_runtime_config()
+ except Exception:
+ logger.exception("Failed to resolve web_search runtime availability")
+ return False, "search_configuration_error"
+ if config.provider == "none":
+ return False, "search_provider_not_configured"
+ if config.unsupported_provider or config.deprecated_provider:
+ return False, "search_provider_unsupported"
+ if config.missing_credentials:
+ return False, "search_credentials_missing"
+ return True, None
+
+
@router.get("", response_model=ToolsListResponse)
async def list_builtin_tools() -> ToolsListResponse:
"""Return all built-in tools the chat agent can invoke, plus any
diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.py
index 7c81e2ca9..892cb6e51 100644
--- a/deeptutor/services/sandbox/backends.py
+++ b/deeptutor/services/sandbox/backends.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import asyncio
from contextlib import suppress
+import locale
import os
from pathlib import Path
import shutil
@@ -251,6 +252,47 @@ class RestrictedSubprocessBackend(SandboxBackend):
_SAFE_ENV_KEYS = ("PATH", "PATHEXT", "HOME", "LANG", "LC_ALL", "TMPDIR", "SYSTEMROOT")
+ def __init__(
+ self,
+ *,
+ venv_path: str | Path | None = None,
+ inherit_virtualenv: bool = True,
+ ) -> None:
+ """Keep model-authored ``python`` and ``pip`` on one interpreter.
+
+ Desktop installs run DeepTutor from a virtual environment but can
+ inherit a host ``PATH`` whose first Python belongs to MSYS, Conda, or a
+ system install. Prepending the environment that launched DeepTutor
+ prevents a bare ``pip install`` followed by ``python -c`` from silently
+ targeting two different environments.
+ """
+ if venv_path is not None:
+ candidate = Path(venv_path).resolve()
+ elif inherit_virtualenv and sys.prefix != sys.base_prefix:
+ candidate = Path(sys.prefix).resolve()
+ else:
+ candidate = None
+ self._venv_path = candidate if candidate is not None and candidate.is_dir() else None
+
+ def _build_env(self, request_env: dict[str, str]) -> dict[str, str]:
+ env = {key: os.environ[key] for key in self._SAFE_ENV_KEYS if key in os.environ}
+ env.update(request_env)
+ if self._venv_path is None:
+ return env
+
+ venv = str(self._venv_path)
+ venv_bin = str(self._venv_path / ("Scripts" if sys.platform == "win32" else "bin"))
+ base_path = env.get("PATH") or ""
+ normalized_venv_bin = os.path.normcase(os.path.normpath(venv_bin))
+ path_entries = [
+ entry
+ for entry in base_path.split(os.pathsep)
+ if entry and os.path.normcase(os.path.normpath(entry)) != normalized_venv_bin
+ ]
+ env["PATH"] = os.pathsep.join([venv_bin, *path_entries])
+ env["VIRTUAL_ENV"] = venv
+ return env
+
@staticmethod
def _powershell_executable() -> str:
"""Return the PowerShell executable available on PATH.
@@ -278,8 +320,7 @@ class RestrictedSubprocessBackend(SandboxBackend):
)
async def exec(self, request: ExecRequest) -> ExecResult:
- env = {k: os.environ[k] for k in self._SAFE_ENV_KEYS if k in os.environ}
- env.update(request.env)
+ env = self._build_env(request.env)
cwd = request.workdir or None
try:
if request.argv:
@@ -344,12 +385,29 @@ async def _communicate(process: asyncio.subprocess.Process, timeout_s: int) -> E
await asyncio.wait_for(process.wait(), timeout=5.0)
return ExecResult(timed_out=True, exit_code=124)
return ExecResult(
- stdout=stdout.decode("utf-8", errors="replace") if stdout else "",
- stderr=stderr.decode("utf-8", errors="replace") if stderr else "",
+ stdout=_decode_process_output(stdout),
+ stderr=_decode_process_output(stderr),
exit_code=process.returncode if process.returncode is not None else 0,
)
+def _decode_process_output(data: bytes | None) -> str:
+ """Decode native-process output without turning Windows errors into mojibake."""
+ if not data:
+ return ""
+ try:
+ return data.decode("utf-8")
+ except UnicodeDecodeError:
+ pass
+ if sys.platform == "win32":
+ for encoding in (locale.getpreferredencoding(False), "mbcs"):
+ try:
+ return data.decode(encoding)
+ except (LookupError, UnicodeDecodeError):
+ continue
+ return data.decode("utf-8", errors="replace")
+
+
__all__ = [
"BwrapBackend",
"RestrictedSubprocessBackend",
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py
index 4b6b012cf..735a9699c 100644
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@ -85,14 +85,21 @@ def _assert_provider_supported(provider_name: str) -> None:
)
-def _disabled_result(query: str, provider: str) -> dict[str, Any]:
+def _disabled_result(
+ query: str,
+ provider: str,
+ *,
+ error_code: str,
+ answer: str,
+) -> dict[str, Any]:
return {
"timestamp": datetime.now().isoformat(),
"query": query,
- "answer": "Web search is disabled.",
+ "answer": answer,
"citations": [],
"search_results": [],
"provider": provider,
+ "error_code": error_code,
}
@@ -126,13 +133,27 @@ def web_search(
config = _get_web_search_config()
if not config.get("enabled", True):
_logger.warning("Web search is disabled in config")
- return _disabled_result(query, "disabled")
+ return _disabled_result(
+ query,
+ "disabled",
+ error_code="web_search_disabled",
+ answer="Web search is disabled by system configuration.",
+ )
resolved = resolve_search_runtime_config()
provider_name = (provider or resolved.provider).strip().lower()
_assert_provider_supported(provider_name)
if provider_name == "none":
- return _disabled_result(query, "none")
+ return _disabled_result(
+ query,
+ "none",
+ error_code="search_provider_not_configured",
+ answer=(
+ "Web search is enabled but no search provider is configured. "
+ "Open Settings > Search and choose a provider; DuckDuckGo works "
+ "without an API key."
+ ),
+ )
api_key, base_url = _credentials_for(provider_name, resolved)
base_url = provider_kwargs.get("base_url") or base_url
diff --git a/deeptutor/tools/prompting/hints/en/exec.yaml b/deeptutor/tools/prompting/hints/en/exec.yaml
index 63252a611..8dd0e1a16 100644
--- a/deeptutor/tools/prompting/hints/en/exec.yaml
+++ b/deeptutor/tools/prompting/hints/en/exec.yaml
@@ -1,6 +1,6 @@
short_description: "Run a shell command inside an isolated sandbox; returns stdout/stderr + exit code."
when_to_use: "For data processing, running a skill's bundled scripts, or invoking CLI tools the task needs. Not for destructive or system-management commands."
input_format: "`command` — the shell command. Optional `timeout` — seconds (default 30, max 300). Runs in this turn's workspace directory."
-guideline: "Prefer non-interactive flags (e.g. `-y`). Keep output small; pipe through `head`/`grep` when a command is chatty. Read a skill's SKILL.md before running its scripts. If the user asks you to create/export a file, run the command, save the file in the workspace, then include any Generated artifacts URL from the tool result in your final answer."
-note: "Destructive patterns (rm -rf, mkfs, shutdown, …) are blocked. The sandbox confines filesystem and network access; commands that need the open internet may fail."
+guideline: "Prefer non-interactive flags (e.g. `-y`). Follow the host shell named in the workspace note and use that shell's native output-limiting syntax. Read a skill's SKILL.md before running its scripts. Invoke package management as `python -m pip` so it targets the same interpreter. If the user asks you to create/export a file, run the command, save the file in the workspace, then include any Generated artifacts URL from the tool result in your final answer."
+note: "Destructive patterns (rm -rf, mkfs, shutdown, …) are blocked. On failure, inspect STDERR, the exit code, and the actual shell. Do not describe syntax or dependency failures as sandbox denial; report a filesystem or network restriction only when the tool explicitly returns that error."
phase: "expansion"
diff --git a/deeptutor/tools/prompting/hints/zh/exec.yaml b/deeptutor/tools/prompting/hints/zh/exec.yaml
index b3aaac6fd..c96bc94e2 100644
--- a/deeptutor/tools/prompting/hints/zh/exec.yaml
+++ b/deeptutor/tools/prompting/hints/zh/exec.yaml
@@ -1,6 +1,6 @@
short_description: "在隔离沙箱中执行 shell 命令,返回 stdout/stderr 与退出码。"
when_to_use: "用于数据处理、运行技能自带脚本、调用任务所需的 CLI 工具。不要用于破坏性或系统管理类命令。"
input_format: "`command` — shell 命令。可选 `timeout` — 秒(默认 30,上限 300)。命令运行在本回合的工作目录中。"
-guideline: "优先使用非交互参数(如 `-y`)。控制输出体量,命令过于啰嗦时用 `head`/`grep` 过滤。运行技能脚本前先读其 SKILL.md。若用户要求创建/导出文件,执行命令并把文件保存到工作目录,然后在最终回答中给出工具结果里的 Generated artifacts 下载链接。"
-note: "破坏性命令(rm -rf、mkfs、shutdown 等)会被拦截。沙箱限制文件与网络访问,需要公网的命令可能失败。"
+guideline: "优先使用非交互参数(如 `-y`)。根据工作区说明中标明的宿主 shell 使用对应语法,并用该 shell 自带的方式限制输出。运行技能脚本前先读其 SKILL.md。调用 Python 包管理器时使用 `python -m pip`,不要把 `pip` 与另一个 `python` 混用。若用户要求创建/导出文件,执行命令并把文件保存到工作目录,然后在最终回答中给出工具结果里的 Generated artifacts 下载链接。"
+note: "破坏性命令(rm -rf、mkfs、shutdown 等)会被拦截。命令失败时检查 STDERR、退出码和实际 shell;不要把命令语法或依赖错误说成沙箱无权访问。只有工具明确返回拒绝访问或网络错误时,才能据此说明对应限制。"
phase: "expansion"
diff --git a/tests/agents/chat/test_workspace_system_note.py b/tests/agents/chat/test_workspace_system_note.py
index a357c994f..f7bdba035 100644
--- a/tests/agents/chat/test_workspace_system_note.py
+++ b/tests/agents/chat/test_workspace_system_note.py
@@ -47,10 +47,18 @@ def note(monkeypatch: pytest.MonkeyPatch):
def test_windows_note_teaches_powershell_not_heredoc(note, language: str) -> None:
windows = note(language=language, platform="win32")
assert "Set-Content" in windows
- assert "python gen.py" in windows
+ assert "python -m pip" in windows
+ assert "Get-ChildItem" in windows
+ assert "Select-Object" in windows
# A Bash heredoc as the *instruction* is what breaks on Windows; the note
# may name it only to tell the model not to use it.
assert "python - <<'PY'" not in windows
+ for incompatible in ("ls -la", "| head", "| tail", "cd /d"):
+ assert incompatible not in windows
+ if language == "zh":
+ assert "不要把命令语法或依赖错误说成沙箱无权访问" in windows
+ else:
+ assert "Do not describe a syntax or dependency failure as denied sandbox access" in windows
@pytest.mark.parametrize("language", ["en", "zh"])
diff --git a/tests/api/test_tools_router.py b/tests/api/test_tools_router.py
index 18772246e..27101fb93 100644
--- a/tests/api/test_tools_router.py
+++ b/tests/api/test_tools_router.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from types import SimpleNamespace
+
import pytest
from deeptutor.api.routers import settings as settings_router
@@ -107,3 +109,29 @@ async def test_list_builtin_tools_reflects_user_toggle(
assert by_name["code_execution"].enabled is True
assert by_name["rag"].enabled is True
assert by_name["web_fetch"].enabled is True
+
+
+async def test_web_search_reports_enabled_but_not_configured(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ settings_file = tmp_path / "interface.json"
+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)
+ monkeypatch.setattr(
+ tools_router,
+ "resolve_search_runtime_config",
+ lambda: SimpleNamespace(
+ provider="none",
+ requested_provider="none",
+ unsupported_provider=False,
+ deprecated_provider=False,
+ missing_credentials=False,
+ ),
+ )
+
+ response = await tools_router.list_builtin_tools()
+ web_search = next(tool for tool in response.tools if tool.name == "web_search")
+
+ assert web_search.enabled is True # saved composer preference
+ assert web_search.available is False # runtime can actually execute it
+ assert web_search.unavailable_reason == "search_provider_not_configured"
diff --git a/tests/services/sandbox/test_sandbox.py b/tests/services/sandbox/test_sandbox.py
index 30e9d425b..31dd456e2 100644
--- a/tests/services/sandbox/test_sandbox.py
+++ b/tests/services/sandbox/test_sandbox.py
@@ -3,10 +3,15 @@
from __future__ import annotations
import asyncio
+import os
import pytest
-from deeptutor.services.sandbox.backends import BwrapBackend, RestrictedSubprocessBackend
+from deeptutor.services.sandbox.backends import (
+ BwrapBackend,
+ RestrictedSubprocessBackend,
+ _decode_process_output,
+)
from deeptutor.services.sandbox.config import SandboxSettings, build_backend
from deeptutor.services.sandbox.quota import QuotaExceeded, UserExecQuota
from deeptutor.services.sandbox.service import SandboxService
@@ -172,6 +177,55 @@ async def test_restricted_subprocess_runs() -> None:
assert result.exit_code == 0
+def test_restricted_subprocess_prefers_configured_virtualenv(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Bare ``python``/``pip`` must resolve inside DeepTutor's own env.
+
+ A Windows desktop install can inherit MSYS Python before the interpreter
+ that launched DeepTutor. That split makes ``pip install`` and the next
+ ``python -c`` target different environments.
+ """
+ venv = tmp_path / "deeptutor-venv"
+ bin_dir = venv / ("Scripts" if os.name == "nt" else "bin")
+ bin_dir.mkdir(parents=True)
+ monkeypatch.setenv("PATH", os.pathsep.join(["foreign-python", "system-tools"]))
+
+ backend = RestrictedSubprocessBackend(venv_path=venv)
+ env = backend._build_env({})
+
+ assert env["VIRTUAL_ENV"] == str(venv.resolve())
+ assert env["PATH"].split(os.pathsep)[0] == str(bin_dir.resolve())
+ assert env["PATH"].split(os.pathsep).count(str(bin_dir.resolve())) == 1
+
+
+def test_restricted_subprocess_request_path_keeps_virtualenv_first(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ venv = tmp_path / "deeptutor-venv"
+ bin_dir = venv / ("Scripts" if os.name == "nt" else "bin")
+ bin_dir.mkdir(parents=True)
+ monkeypatch.setenv("PATH", "host-tools")
+
+ backend = RestrictedSubprocessBackend(venv_path=venv)
+ env = backend._build_env({"PATH": os.pathsep.join(["turn-tools", str(bin_dir)])})
+
+ assert env["PATH"].split(os.pathsep) == [str(bin_dir.resolve()), "turn-tools"]
+
+
+def test_windows_process_output_falls_back_to_the_console_encoding(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ message = "不是内部或外部命令"
+ monkeypatch.setattr("deeptutor.services.sandbox.backends.sys.platform", "win32")
+ monkeypatch.setattr(
+ "deeptutor.services.sandbox.backends.locale.getpreferredencoding",
+ lambda _do_setlocale=False: "gbk",
+ )
+
+ assert _decode_process_output(message.encode("gbk")) == message
+
+
@pytest.mark.asyncio
async def test_restricted_subprocess_timeout() -> None:
backend = RestrictedSubprocessBackend()
diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.py
index a034cbb80..b6153f80a 100644
--- a/tests/services/search/test_web_search_runtime.py
+++ b/tests/services/search/test_web_search_runtime.py
@@ -63,6 +63,24 @@ def test_web_search_rejects_deprecated_provider(monkeypatch) -> None:
web_search("hello")
+def test_web_search_none_provider_returns_actionable_configuration_error(monkeypatch) -> None:
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="none",
+ requested_provider="none",
+ max_results=5,
+ ),
+ )
+
+ result = web_search("hello")
+
+ assert result["provider"] == "none"
+ assert result["error_code"] == "search_provider_not_configured"
+ assert "Settings" in result["answer"]
+ assert "DuckDuckGo" in result["answer"]
+
+
def test_web_search_perplexity_missing_key_hard_fails(monkeypatch) -> None:
_patch_runtime(
monkeypatch,
diff --git a/tests/tools/test_exec_prompt_hints.py b/tests/tools/test_exec_prompt_hints.py
new file mode 100644
index 000000000..88c01378f
--- /dev/null
+++ b/tests/tools/test_exec_prompt_hints.py
@@ -0,0 +1,21 @@
+"""The exec prompt must not teach one operating system's shell on another."""
+
+from __future__ import annotations
+
+from deeptutor.tools.exec_tool import ExecTool
+
+
+def test_exec_prompt_does_not_recommend_posix_filters_as_portable_commands() -> None:
+ for language in ("en", "zh"):
+ hints = ExecTool().get_prompt_hints(language=language)
+ rendered = "\n".join((hints.input_format, hints.guideline, hints.note))
+ for fragment in ("head", "grep", "tail"):
+ assert fragment not in rendered
+
+
+def test_exec_prompt_requires_real_access_error_before_claiming_denial() -> None:
+ zh = ExecTool().get_prompt_hints(language="zh")
+ en = ExecTool().get_prompt_hints(language="en")
+
+ assert "不要把命令语法或依赖错误说成沙箱无权访问" in zh.note
+ assert "Do not describe syntax or dependency failures as sandbox denial" in en.note
diff --git a/web/app/(utility)/settings/tools/page.tsx b/web/app/(utility)/settings/tools/page.tsx
index 3e7299797..18e938249 100644
--- a/web/app/(utility)/settings/tools/page.tsx
+++ b/web/app/(utility)/settings/tools/page.tsx
@@ -2,12 +2,17 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDown, Loader2, Lock, Wrench } from "lucide-react";
+import Link from "next/link";
import { useTranslation } from "react-i18next";
import { useSettings } from "@/components/settings/SettingsContext";
import { SettingsPageHeader } from "@/components/settings/shared";
import { apiFetch, apiUrl } from "@/lib/api";
import { invalidateEnabledOptionalToolsCache } from "@/lib/tools-settings";
+import {
+ toolAvailabilityCopy,
+ toolEffectiveEnabled,
+} from "@/lib/tool-availability";
type ToolParameter = {
name: string;
@@ -44,6 +49,9 @@ type BuiltinTool = {
// for a plain system built-in. Owned tools render in their own section
// below the built-in tools.
capability?: string | null;
+ // Runtime readiness is independent of the saved composer preference.
+ available?: boolean;
+ unavailable_reason?: string | null;
};
type ToolsResponse = {
@@ -258,9 +266,18 @@ export default function ToolsSettingsPage() {
const hints = tool.hints[language];
const isPending = pending.has(tool.name);
const isComingSoon = !!tool.coming_soon;
- const isEnabled =
- !isComingSoon &&
- (tool.toggleable ? enabled.has(tool.name) : true);
+ const isAvailable = tool.available !== false;
+ const availability = !isAvailable
+ ? toolAvailabilityCopy(
+ tool.unavailable_reason,
+ language === "zh" ? "zh" : "en",
+ )
+ : null;
+ const isEnabled = toolEffectiveEnabled(
+ tool.toggleable ? enabled.has(tool.name) : true,
+ isAvailable,
+ isComingSoon,
+ );
return (
<div
key={tool.name}
@@ -273,7 +290,7 @@ export default function ToolsSettingsPage() {
<div className="flex w-full items-start gap-3 px-5 py-4">
<Wrench
className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${
- isComingSoon
+ isComingSoon || !isAvailable
? "text-[var(--muted-foreground)]/40"
: "text-[var(--muted-foreground)]"
}`}
@@ -307,6 +324,11 @@ export default function ToolsSettingsPage() {
: "Coming soon"}
</span>
)}
+ {availability && !isComingSoon && (
+ <span className="inline-flex items-center rounded-full border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300">
+ {availability.badge}
+ </span>
+ )}
</div>
<p
className={`mt-1 text-[12.5px] leading-relaxed ${
@@ -317,6 +339,19 @@ export default function ToolsSettingsPage() {
>
{hints.short_description || tool.description}
</p>
+ {availability && !isComingSoon && (
+ <p className="mt-1 text-[11.5px] leading-relaxed text-amber-700 dark:text-amber-300">
+ {availability.detail}{" "}
+ {availability.href && (
+ <Link
+ href={availability.href}
+ className="font-medium underline underline-offset-2"
+ >
+ {language === "zh" ? "打开设置" : "Open settings"}
+ </Link>
+ )}
+ </p>
+ )}
</div>
<ChevronDown
className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${
@@ -336,6 +371,15 @@ export default function ToolsSettingsPage() {
language === "zh" ? "敬请期待" : "Coming soon"
}
/>
+ ) : !isAvailable ? (
+ <ToolToggle
+ checked={false}
+ disabled
+ onChange={() => {
+ /* runtime unavailable */
+ }}
+ label={availability?.badge ?? t("Not configured")}
+ />
) : tool.toggleable ? (
<ToolToggle
checked={isEnabled}
diff --git a/web/lib/tool-availability.ts b/web/lib/tool-availability.ts
new file mode 100644
index 000000000..2a5aa2882
--- /dev/null
+++ b/web/lib/tool-availability.ts
@@ -0,0 +1,51 @@
+export type ToolAvailabilityLanguage = "en" | "zh";
+
+export type ToolAvailabilityCopy = {
+ badge: string;
+ detail: string;
+ href?: string;
+};
+
+export function toolEffectiveEnabled(
+ savedEnabled: boolean,
+ available: boolean,
+ comingSoon: boolean,
+): boolean {
+ return savedEnabled && available && !comingSoon;
+}
+
+export function toolAvailabilityCopy(
+ reason: string | null | undefined,
+ language: ToolAvailabilityLanguage,
+): ToolAvailabilityCopy {
+ if (reason === "search_provider_not_configured") {
+ return language === "zh"
+ ? {
+ badge: "未配置",
+ detail: "请先在搜索设置中选择提供商。DuckDuckGo 无需 API 密钥。",
+ href: "/settings/search",
+ }
+ : {
+ badge: "Not configured",
+ detail:
+ "Choose a provider in Search settings first. DuckDuckGo needs no API key.",
+ href: "/settings/search",
+ };
+ }
+ if (reason === "search_credentials_missing") {
+ return language === "zh"
+ ? {
+ badge: "缺少凭证",
+ detail: "当前搜索提供商缺少所需凭证,请检查搜索设置。",
+ href: "/settings/search",
+ }
+ : {
+ badge: "Credentials missing",
+ detail: "The selected search provider needs credentials. Check Search settings.",
+ href: "/settings/search",
+ };
+ }
+ return language === "zh"
+ ? { badge: "暂不可用", detail: "该工具的运行服务当前不可用。" }
+ : { badge: "Unavailable", detail: "This tool's runtime service is unavailable." };
+}
diff --git a/web/tests/tool-availability.test.ts b/web/tests/tool-availability.test.ts
new file mode 100644
index 000000000..2d5f9f06e
--- /dev/null
+++ b/web/tests/tool-availability.test.ts
@@ -0,0 +1,34 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ toolAvailabilityCopy,
+ toolEffectiveEnabled,
+} from "../lib/tool-availability";
+
+test("configured runtime and saved preference are both required", () => {
+ assert.equal(toolEffectiveEnabled(true, true, false), true);
+ assert.equal(toolEffectiveEnabled(true, false, false), false);
+ assert.equal(toolEffectiveEnabled(false, true, false), false);
+ assert.equal(toolEffectiveEnabled(true, true, true), false);
+});
+
+test("search provider readiness has actionable bilingual copy", () => {
+ assert.deepEqual(
+ toolAvailabilityCopy("search_provider_not_configured", "zh"),
+ {
+ badge: "未配置",
+ detail: "请先在搜索设置中选择提供商。DuckDuckGo 无需 API 密钥。",
+ href: "/settings/search",
+ },
+ );
+ assert.deepEqual(
+ toolAvailabilityCopy("search_provider_not_configured", "en"),
+ {
+ badge: "Not configured",
+ detail:
+ "Choose a provider in Search settings first. DuckDuckGo needs no API key.",
+ href: "/settings/search",
+ },
+ );
+});